/Lib/lib2to3/tests/data/py2_test_grammar.py

http://unladen-swallow.googlecode.com/ · Python · 956 lines · 729 code · 109 blank · 118 comment · 275 complexity · e942fb49c8000cb9a6b412726618c3a1 MD5 · raw file

  1. # Python 2's Lib/test/test_grammar.py (r66189)
  2. # Python test set -- part 1, grammar.
  3. # This just tests whether the parser accepts them all.
  4. # NOTE: When you run this test as a script from the command line, you
  5. # get warnings about certain hex/oct constants. Since those are
  6. # issued by the parser, you can't suppress them by adding a
  7. # filterwarnings() call to this module. Therefore, to shut up the
  8. # regression test, the filterwarnings() call has been added to
  9. # regrtest.py.
  10. from test.test_support import run_unittest, check_syntax_error
  11. import unittest
  12. import sys
  13. # testing import *
  14. from sys import *
  15. class TokenTests(unittest.TestCase):
  16. def testBackslash(self):
  17. # Backslash means line continuation:
  18. x = 1 \
  19. + 1
  20. self.assertEquals(x, 2, 'backslash for line continuation')
  21. # Backslash does not means continuation in comments :\
  22. x = 0
  23. self.assertEquals(x, 0, 'backslash ending comment')
  24. def testPlainIntegers(self):
  25. self.assertEquals(0xff, 255)
  26. self.assertEquals(0377, 255)
  27. self.assertEquals(2147483647, 017777777777)
  28. # "0x" is not a valid literal
  29. self.assertRaises(SyntaxError, eval, "0x")
  30. from sys import maxint
  31. if maxint == 2147483647:
  32. self.assertEquals(-2147483647-1, -020000000000)
  33. # XXX -2147483648
  34. self.assert_(037777777777 > 0)
  35. self.assert_(0xffffffff > 0)
  36. for s in '2147483648', '040000000000', '0x100000000':
  37. try:
  38. x = eval(s)
  39. except OverflowError:
  40. self.fail("OverflowError on huge integer literal %r" % s)
  41. elif maxint == 9223372036854775807:
  42. self.assertEquals(-9223372036854775807-1, -01000000000000000000000)
  43. self.assert_(01777777777777777777777 > 0)
  44. self.assert_(0xffffffffffffffff > 0)
  45. for s in '9223372036854775808', '02000000000000000000000', \
  46. '0x10000000000000000':
  47. try:
  48. x = eval(s)
  49. except OverflowError:
  50. self.fail("OverflowError on huge integer literal %r" % s)
  51. else:
  52. self.fail('Weird maxint value %r' % maxint)
  53. def testLongIntegers(self):
  54. x = 0L
  55. x = 0l
  56. x = 0xffffffffffffffffL
  57. x = 0xffffffffffffffffl
  58. x = 077777777777777777L
  59. x = 077777777777777777l
  60. x = 123456789012345678901234567890L
  61. x = 123456789012345678901234567890l
  62. def testFloats(self):
  63. x = 3.14
  64. x = 314.
  65. x = 0.314
  66. # XXX x = 000.314
  67. x = .314
  68. x = 3e14
  69. x = 3E14
  70. x = 3e-14
  71. x = 3e+14
  72. x = 3.e14
  73. x = .3e14
  74. x = 3.1e4
  75. def testStringLiterals(self):
  76. x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
  77. x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
  78. x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
  79. x = "doesn't \"shrink\" does it"
  80. y = 'doesn\'t "shrink" does it'
  81. self.assert_(len(x) == 24 and x == y)
  82. x = "does \"shrink\" doesn't it"
  83. y = 'does "shrink" doesn\'t it'
  84. self.assert_(len(x) == 24 and x == y)
  85. x = """
  86. The "quick"
  87. brown fox
  88. jumps over
  89. the 'lazy' dog.
  90. """
  91. y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
  92. self.assertEquals(x, y)
  93. y = '''
  94. The "quick"
  95. brown fox
  96. jumps over
  97. the 'lazy' dog.
  98. '''
  99. self.assertEquals(x, y)
  100. y = "\n\
  101. The \"quick\"\n\
  102. brown fox\n\
  103. jumps over\n\
  104. the 'lazy' dog.\n\
  105. "
  106. self.assertEquals(x, y)
  107. y = '\n\
  108. The \"quick\"\n\
  109. brown fox\n\
  110. jumps over\n\
  111. the \'lazy\' dog.\n\
  112. '
  113. self.assertEquals(x, y)
  114. class GrammarTests(unittest.TestCase):
  115. # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
  116. # XXX can't test in a script -- this rule is only used when interactive
  117. # file_input: (NEWLINE | stmt)* ENDMARKER
  118. # Being tested as this very moment this very module
  119. # expr_input: testlist NEWLINE
  120. # XXX Hard to test -- used only in calls to input()
  121. def testEvalInput(self):
  122. # testlist ENDMARKER
  123. x = eval('1, 0 or 1')
  124. def testFuncdef(self):
  125. ### 'def' NAME parameters ':' suite
  126. ### parameters: '(' [varargslist] ')'
  127. ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
  128. ### | ('**'|'*' '*') NAME)
  129. ### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
  130. ### fpdef: NAME | '(' fplist ')'
  131. ### fplist: fpdef (',' fpdef)* [',']
  132. ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
  133. ### argument: [test '='] test # Really [keyword '='] test
  134. def f1(): pass
  135. f1()
  136. f1(*())
  137. f1(*(), **{})
  138. def f2(one_argument): pass
  139. def f3(two, arguments): pass
  140. def f4(two, (compound, (argument, list))): pass
  141. def f5((compound, first), two): pass
  142. self.assertEquals(f2.func_code.co_varnames, ('one_argument',))
  143. self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments'))
  144. if sys.platform.startswith('java'):
  145. self.assertEquals(f4.func_code.co_varnames,
  146. ('two', '(compound, (argument, list))', 'compound', 'argument',
  147. 'list',))
  148. self.assertEquals(f5.func_code.co_varnames,
  149. ('(compound, first)', 'two', 'compound', 'first'))
  150. else:
  151. self.assertEquals(f4.func_code.co_varnames,
  152. ('two', '.1', 'compound', 'argument', 'list'))
  153. self.assertEquals(f5.func_code.co_varnames,
  154. ('.0', 'two', 'compound', 'first'))
  155. def a1(one_arg,): pass
  156. def a2(two, args,): pass
  157. def v0(*rest): pass
  158. def v1(a, *rest): pass
  159. def v2(a, b, *rest): pass
  160. def v3(a, (b, c), *rest): return a, b, c, rest
  161. f1()
  162. f2(1)
  163. f2(1,)
  164. f3(1, 2)
  165. f3(1, 2,)
  166. f4(1, (2, (3, 4)))
  167. v0()
  168. v0(1)
  169. v0(1,)
  170. v0(1,2)
  171. v0(1,2,3,4,5,6,7,8,9,0)
  172. v1(1)
  173. v1(1,)
  174. v1(1,2)
  175. v1(1,2,3)
  176. v1(1,2,3,4,5,6,7,8,9,0)
  177. v2(1,2)
  178. v2(1,2,3)
  179. v2(1,2,3,4)
  180. v2(1,2,3,4,5,6,7,8,9,0)
  181. v3(1,(2,3))
  182. v3(1,(2,3),4)
  183. v3(1,(2,3),4,5,6,7,8,9,0)
  184. # ceval unpacks the formal arguments into the first argcount names;
  185. # thus, the names nested inside tuples must appear after these names.
  186. if sys.platform.startswith('java'):
  187. self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
  188. else:
  189. self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
  190. self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
  191. def d01(a=1): pass
  192. d01()
  193. d01(1)
  194. d01(*(1,))
  195. d01(**{'a':2})
  196. def d11(a, b=1): pass
  197. d11(1)
  198. d11(1, 2)
  199. d11(1, **{'b':2})
  200. def d21(a, b, c=1): pass
  201. d21(1, 2)
  202. d21(1, 2, 3)
  203. d21(*(1, 2, 3))
  204. d21(1, *(2, 3))
  205. d21(1, 2, *(3,))
  206. d21(1, 2, **{'c':3})
  207. def d02(a=1, b=2): pass
  208. d02()
  209. d02(1)
  210. d02(1, 2)
  211. d02(*(1, 2))
  212. d02(1, *(2,))
  213. d02(1, **{'b':2})
  214. d02(**{'a': 1, 'b': 2})
  215. def d12(a, b=1, c=2): pass
  216. d12(1)
  217. d12(1, 2)
  218. d12(1, 2, 3)
  219. def d22(a, b, c=1, d=2): pass
  220. d22(1, 2)
  221. d22(1, 2, 3)
  222. d22(1, 2, 3, 4)
  223. def d01v(a=1, *rest): pass
  224. d01v()
  225. d01v(1)
  226. d01v(1, 2)
  227. d01v(*(1, 2, 3, 4))
  228. d01v(*(1,))
  229. d01v(**{'a':2})
  230. def d11v(a, b=1, *rest): pass
  231. d11v(1)
  232. d11v(1, 2)
  233. d11v(1, 2, 3)
  234. def d21v(a, b, c=1, *rest): pass
  235. d21v(1, 2)
  236. d21v(1, 2, 3)
  237. d21v(1, 2, 3, 4)
  238. d21v(*(1, 2, 3, 4))
  239. d21v(1, 2, **{'c': 3})
  240. def d02v(a=1, b=2, *rest): pass
  241. d02v()
  242. d02v(1)
  243. d02v(1, 2)
  244. d02v(1, 2, 3)
  245. d02v(1, *(2, 3, 4))
  246. d02v(**{'a': 1, 'b': 2})
  247. def d12v(a, b=1, c=2, *rest): pass
  248. d12v(1)
  249. d12v(1, 2)
  250. d12v(1, 2, 3)
  251. d12v(1, 2, 3, 4)
  252. d12v(*(1, 2, 3, 4))
  253. d12v(1, 2, *(3, 4, 5))
  254. d12v(1, *(2,), **{'c': 3})
  255. def d22v(a, b, c=1, d=2, *rest): pass
  256. d22v(1, 2)
  257. d22v(1, 2, 3)
  258. d22v(1, 2, 3, 4)
  259. d22v(1, 2, 3, 4, 5)
  260. d22v(*(1, 2, 3, 4))
  261. d22v(1, 2, *(3, 4, 5))
  262. d22v(1, *(2, 3), **{'d': 4})
  263. def d31v((x)): pass
  264. d31v(1)
  265. def d32v((x,)): pass
  266. d32v((1,))
  267. # keyword arguments after *arglist
  268. def f(*args, **kwargs):
  269. return args, kwargs
  270. self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
  271. {'x':2, 'y':5}))
  272. self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
  273. self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
  274. # Check ast errors in *args and *kwargs
  275. check_syntax_error(self, "f(*g(1=2))")
  276. check_syntax_error(self, "f(**g(1=2))")
  277. def testLambdef(self):
  278. ### lambdef: 'lambda' [varargslist] ':' test
  279. l1 = lambda : 0
  280. self.assertEquals(l1(), 0)
  281. l2 = lambda : a[d] # XXX just testing the expression
  282. l3 = lambda : [2 < x for x in [-1, 3, 0L]]
  283. self.assertEquals(l3(), [0, 1, 0])
  284. l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
  285. self.assertEquals(l4(), 1)
  286. l5 = lambda x, y, z=2: x + y + z
  287. self.assertEquals(l5(1, 2), 5)
  288. self.assertEquals(l5(1, 2, 3), 6)
  289. check_syntax_error(self, "lambda x: x = 2")
  290. check_syntax_error(self, "lambda (None,): None")
  291. ### stmt: simple_stmt | compound_stmt
  292. # Tested below
  293. def testSimpleStmt(self):
  294. ### simple_stmt: small_stmt (';' small_stmt)* [';']
  295. x = 1; pass; del x
  296. def foo():
  297. # verify statments that end with semi-colons
  298. x = 1; pass; del x;
  299. foo()
  300. ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
  301. # Tested below
  302. def testExprStmt(self):
  303. # (exprlist '=')* exprlist
  304. 1
  305. 1, 2, 3
  306. x = 1
  307. x = 1, 2, 3
  308. x = y = z = 1, 2, 3
  309. x, y, z = 1, 2, 3
  310. abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
  311. check_syntax_error(self, "x + 1 = 1")
  312. check_syntax_error(self, "a + 1 = b + 2")
  313. def testPrintStmt(self):
  314. # 'print' (test ',')* [test]
  315. import StringIO
  316. # Can't test printing to real stdout without comparing output
  317. # which is not available in unittest.
  318. save_stdout = sys.stdout
  319. sys.stdout = StringIO.StringIO()
  320. print 1, 2, 3
  321. print 1, 2, 3,
  322. print
  323. print 0 or 1, 0 or 1,
  324. print 0 or 1
  325. # 'print' '>>' test ','
  326. print >> sys.stdout, 1, 2, 3
  327. print >> sys.stdout, 1, 2, 3,
  328. print >> sys.stdout
  329. print >> sys.stdout, 0 or 1, 0 or 1,
  330. print >> sys.stdout, 0 or 1
  331. # test printing to an instance
  332. class Gulp:
  333. def write(self, msg): pass
  334. gulp = Gulp()
  335. print >> gulp, 1, 2, 3
  336. print >> gulp, 1, 2, 3,
  337. print >> gulp
  338. print >> gulp, 0 or 1, 0 or 1,
  339. print >> gulp, 0 or 1
  340. # test print >> None
  341. def driver():
  342. oldstdout = sys.stdout
  343. sys.stdout = Gulp()
  344. try:
  345. tellme(Gulp())
  346. tellme()
  347. finally:
  348. sys.stdout = oldstdout
  349. # we should see this once
  350. def tellme(file=sys.stdout):
  351. print >> file, 'hello world'
  352. driver()
  353. # we should not see this at all
  354. def tellme(file=None):
  355. print >> file, 'goodbye universe'
  356. driver()
  357. self.assertEqual(sys.stdout.getvalue(), '''\
  358. 1 2 3
  359. 1 2 3
  360. 1 1 1
  361. 1 2 3
  362. 1 2 3
  363. 1 1 1
  364. hello world
  365. ''')
  366. sys.stdout = save_stdout
  367. # syntax errors
  368. check_syntax_error(self, 'print ,')
  369. check_syntax_error(self, 'print >> x,')
  370. def testDelStmt(self):
  371. # 'del' exprlist
  372. abc = [1,2,3]
  373. x, y, z = abc
  374. xyz = x, y, z
  375. del abc
  376. del x, y, (z, xyz)
  377. def testPassStmt(self):
  378. # 'pass'
  379. pass
  380. # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
  381. # Tested below
  382. def testBreakStmt(self):
  383. # 'break'
  384. while 1: break
  385. def testContinueStmt(self):
  386. # 'continue'
  387. i = 1
  388. while i: i = 0; continue
  389. msg = ""
  390. while not msg:
  391. msg = "ok"
  392. try:
  393. continue
  394. msg = "continue failed to continue inside try"
  395. except:
  396. msg = "continue inside try called except block"
  397. if msg != "ok":
  398. self.fail(msg)
  399. msg = ""
  400. while not msg:
  401. msg = "finally block not called"
  402. try:
  403. continue
  404. finally:
  405. msg = "ok"
  406. if msg != "ok":
  407. self.fail(msg)
  408. def test_break_continue_loop(self):
  409. # This test warrants an explanation. It is a test specifically for SF bugs
  410. # #463359 and #462937. The bug is that a 'break' statement executed or
  411. # exception raised inside a try/except inside a loop, *after* a continue
  412. # statement has been executed in that loop, will cause the wrong number of
  413. # arguments to be popped off the stack and the instruction pointer reset to
  414. # a very small number (usually 0.) Because of this, the following test
  415. # *must* written as a function, and the tracking vars *must* be function
  416. # arguments with default values. Otherwise, the test will loop and loop.
  417. def test_inner(extra_burning_oil = 1, count=0):
  418. big_hippo = 2
  419. while big_hippo:
  420. count += 1
  421. try:
  422. if extra_burning_oil and big_hippo == 1:
  423. extra_burning_oil -= 1
  424. break
  425. big_hippo -= 1
  426. continue
  427. except:
  428. raise
  429. if count > 2 or big_hippo <> 1:
  430. self.fail("continue then break in try/except in loop broken!")
  431. test_inner()
  432. def testReturn(self):
  433. # 'return' [testlist]
  434. def g1(): return
  435. def g2(): return 1
  436. g1()
  437. x = g2()
  438. check_syntax_error(self, "class foo:return 1")
  439. def testYield(self):
  440. check_syntax_error(self, "class foo:yield 1")
  441. def testRaise(self):
  442. # 'raise' test [',' test]
  443. try: raise RuntimeError, 'just testing'
  444. except RuntimeError: pass
  445. try: raise KeyboardInterrupt
  446. except KeyboardInterrupt: pass
  447. def testImport(self):
  448. # 'import' dotted_as_names
  449. import sys
  450. import time, sys
  451. # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
  452. from time import time
  453. from time import (time)
  454. # not testable inside a function, but already done at top of the module
  455. # from sys import *
  456. from sys import path, argv
  457. from sys import (path, argv)
  458. from sys import (path, argv,)
  459. def testGlobal(self):
  460. # 'global' NAME (',' NAME)*
  461. global a
  462. global a, b
  463. global one, two, three, four, five, six, seven, eight, nine, ten
  464. def testExec(self):
  465. # 'exec' expr ['in' expr [',' expr]]
  466. z = None
  467. del z
  468. exec 'z=1+1\n'
  469. if z != 2: self.fail('exec \'z=1+1\'\\n')
  470. del z
  471. exec 'z=1+1'
  472. if z != 2: self.fail('exec \'z=1+1\'')
  473. z = None
  474. del z
  475. import types
  476. if hasattr(types, "UnicodeType"):
  477. exec r"""if 1:
  478. exec u'z=1+1\n'
  479. if z != 2: self.fail('exec u\'z=1+1\'\\n')
  480. del z
  481. exec u'z=1+1'
  482. if z != 2: self.fail('exec u\'z=1+1\'')"""
  483. g = {}
  484. exec 'z = 1' in g
  485. if g.has_key('__builtins__'): del g['__builtins__']
  486. if g != {'z': 1}: self.fail('exec \'z = 1\' in g')
  487. g = {}
  488. l = {}
  489. import warnings
  490. warnings.filterwarnings("ignore", "global statement", module="<string>")
  491. exec 'global a; a = 1; b = 2' in g, l
  492. if g.has_key('__builtins__'): del g['__builtins__']
  493. if l.has_key('__builtins__'): del l['__builtins__']
  494. if (g, l) != ({'a':1}, {'b':2}):
  495. self.fail('exec ... in g (%s), l (%s)' %(g,l))
  496. def testAssert(self):
  497. # assert_stmt: 'assert' test [',' test]
  498. assert 1
  499. assert 1, 1
  500. assert lambda x:x
  501. assert 1, lambda x:x+1
  502. try:
  503. assert 0, "msg"
  504. except AssertionError, e:
  505. self.assertEquals(e.args[0], "msg")
  506. else:
  507. if __debug__:
  508. self.fail("AssertionError not raised by assert 0")
  509. ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
  510. # Tested below
  511. def testIf(self):
  512. # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
  513. if 1: pass
  514. if 1: pass
  515. else: pass
  516. if 0: pass
  517. elif 0: pass
  518. if 0: pass
  519. elif 0: pass
  520. elif 0: pass
  521. elif 0: pass
  522. else: pass
  523. def testWhile(self):
  524. # 'while' test ':' suite ['else' ':' suite]
  525. while 0: pass
  526. while 0: pass
  527. else: pass
  528. # Issue1920: "while 0" is optimized away,
  529. # ensure that the "else" clause is still present.
  530. x = 0
  531. while 0:
  532. x = 1
  533. else:
  534. x = 2
  535. self.assertEquals(x, 2)
  536. def testFor(self):
  537. # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
  538. for i in 1, 2, 3: pass
  539. for i, j, k in (): pass
  540. else: pass
  541. class Squares:
  542. def __init__(self, max):
  543. self.max = max
  544. self.sofar = []
  545. def __len__(self): return len(self.sofar)
  546. def __getitem__(self, i):
  547. if not 0 <= i < self.max: raise IndexError
  548. n = len(self.sofar)
  549. while n <= i:
  550. self.sofar.append(n*n)
  551. n = n+1
  552. return self.sofar[i]
  553. n = 0
  554. for x in Squares(10): n = n+x
  555. if n != 285:
  556. self.fail('for over growing sequence')
  557. result = []
  558. for x, in [(1,), (2,), (3,)]:
  559. result.append(x)
  560. self.assertEqual(result, [1, 2, 3])
  561. def testTry(self):
  562. ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  563. ### | 'try' ':' suite 'finally' ':' suite
  564. ### except_clause: 'except' [expr [('as' | ',') expr]]
  565. try:
  566. 1/0
  567. except ZeroDivisionError:
  568. pass
  569. else:
  570. pass
  571. try: 1/0
  572. except EOFError: pass
  573. except TypeError as msg: pass
  574. except RuntimeError, msg: pass
  575. except: pass
  576. else: pass
  577. try: 1/0
  578. except (EOFError, TypeError, ZeroDivisionError): pass
  579. try: 1/0
  580. except (EOFError, TypeError, ZeroDivisionError), msg: pass
  581. try: pass
  582. finally: pass
  583. def testSuite(self):
  584. # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
  585. if 1: pass
  586. if 1:
  587. pass
  588. if 1:
  589. #
  590. #
  591. #
  592. pass
  593. pass
  594. #
  595. pass
  596. #
  597. def testTest(self):
  598. ### and_test ('or' and_test)*
  599. ### and_test: not_test ('and' not_test)*
  600. ### not_test: 'not' not_test | comparison
  601. if not 1: pass
  602. if 1 and 1: pass
  603. if 1 or 1: pass
  604. if not not not 1: pass
  605. if not 1 and 1 and 1: pass
  606. if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
  607. def testComparison(self):
  608. ### comparison: expr (comp_op expr)*
  609. ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
  610. if 1: pass
  611. x = (1 == 1)
  612. if 1 == 1: pass
  613. if 1 != 1: pass
  614. if 1 <> 1: pass
  615. if 1 < 1: pass
  616. if 1 > 1: pass
  617. if 1 <= 1: pass
  618. if 1 >= 1: pass
  619. if 1 is 1: pass
  620. if 1 is not 1: pass
  621. if 1 in (): pass
  622. if 1 not in (): pass
  623. if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
  624. def testBinaryMaskOps(self):
  625. x = 1 & 1
  626. x = 1 ^ 1
  627. x = 1 | 1
  628. def testShiftOps(self):
  629. x = 1 << 1
  630. x = 1 >> 1
  631. x = 1 << 1 >> 1
  632. def testAdditiveOps(self):
  633. x = 1
  634. x = 1 + 1
  635. x = 1 - 1 - 1
  636. x = 1 - 1 + 1 - 1 + 1
  637. def testMultiplicativeOps(self):
  638. x = 1 * 1
  639. x = 1 / 1
  640. x = 1 % 1
  641. x = 1 / 1 * 1 % 1
  642. def testUnaryOps(self):
  643. x = +1
  644. x = -1
  645. x = ~1
  646. x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
  647. x = -1*1/1 + 1*1 - ---1*1
  648. def testSelectors(self):
  649. ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
  650. ### subscript: expr | [expr] ':' [expr]
  651. import sys, time
  652. c = sys.path[0]
  653. x = time.time()
  654. x = sys.modules['time'].time()
  655. a = '01234'
  656. c = a[0]
  657. c = a[-1]
  658. s = a[0:5]
  659. s = a[:5]
  660. s = a[0:]
  661. s = a[:]
  662. s = a[-5:]
  663. s = a[:-1]
  664. s = a[-4:-3]
  665. # A rough test of SF bug 1333982. http://python.org/sf/1333982
  666. # The testing here is fairly incomplete.
  667. # Test cases should include: commas with 1 and 2 colons
  668. d = {}
  669. d[1] = 1
  670. d[1,] = 2
  671. d[1,2] = 3
  672. d[1,2,3] = 4
  673. L = list(d)
  674. L.sort()
  675. self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
  676. def testAtoms(self):
  677. ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
  678. ### dictmaker: test ':' test (',' test ':' test)* [',']
  679. x = (1)
  680. x = (1 or 2 or 3)
  681. x = (1 or 2 or 3, 2, 3)
  682. x = []
  683. x = [1]
  684. x = [1 or 2 or 3]
  685. x = [1 or 2 or 3, 2, 3]
  686. x = []
  687. x = {}
  688. x = {'one': 1}
  689. x = {'one': 1,}
  690. x = {'one' or 'two': 1 or 2}
  691. x = {'one': 1, 'two': 2}
  692. x = {'one': 1, 'two': 2,}
  693. x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
  694. x = `x`
  695. x = `1 or 2 or 3`
  696. self.assertEqual(`1,2`, '(1, 2)')
  697. x = x
  698. x = 'x'
  699. x = 123
  700. ### exprlist: expr (',' expr)* [',']
  701. ### testlist: test (',' test)* [',']
  702. # These have been exercised enough above
  703. def testClassdef(self):
  704. # 'class' NAME ['(' [testlist] ')'] ':' suite
  705. class B: pass
  706. class B2(): pass
  707. class C1(B): pass
  708. class C2(B): pass
  709. class D(C1, C2, B): pass
  710. class C:
  711. def meth1(self): pass
  712. def meth2(self, arg): pass
  713. def meth3(self, a1, a2): pass
  714. # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
  715. # decorators: decorator+
  716. # decorated: decorators (classdef | funcdef)
  717. def class_decorator(x):
  718. x.decorated = True
  719. return x
  720. @class_decorator
  721. class G:
  722. pass
  723. self.assertEqual(G.decorated, True)
  724. def testListcomps(self):
  725. # list comprehension tests
  726. nums = [1, 2, 3, 4, 5]
  727. strs = ["Apple", "Banana", "Coconut"]
  728. spcs = [" Apple", " Banana ", "Coco nut "]
  729. self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
  730. self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
  731. self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
  732. self.assertEqual([(i, s) for i in nums for s in strs],
  733. [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
  734. (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
  735. (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
  736. (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
  737. (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
  738. self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
  739. [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
  740. (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
  741. (5, 'Banana'), (5, 'Coconut')])
  742. self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
  743. [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
  744. def test_in_func(l):
  745. return [None < x < 3 for x in l if x > 2]
  746. self.assertEqual(test_in_func(nums), [False, False, False])
  747. def test_nested_front():
  748. self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
  749. [[1, 2], [3, 4], [5, 6]])
  750. test_nested_front()
  751. check_syntax_error(self, "[i, s for i in nums for s in strs]")
  752. check_syntax_error(self, "[x if y]")
  753. suppliers = [
  754. (1, "Boeing"),
  755. (2, "Ford"),
  756. (3, "Macdonalds")
  757. ]
  758. parts = [
  759. (10, "Airliner"),
  760. (20, "Engine"),
  761. (30, "Cheeseburger")
  762. ]
  763. suppart = [
  764. (1, 10), (1, 20), (2, 20), (3, 30)
  765. ]
  766. x = [
  767. (sname, pname)
  768. for (sno, sname) in suppliers
  769. for (pno, pname) in parts
  770. for (sp_sno, sp_pno) in suppart
  771. if sno == sp_sno and pno == sp_pno
  772. ]
  773. self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
  774. ('Macdonalds', 'Cheeseburger')])
  775. def testGenexps(self):
  776. # generator expression tests
  777. g = ([x for x in range(10)] for x in range(1))
  778. self.assertEqual(g.next(), [x for x in range(10)])
  779. try:
  780. g.next()
  781. self.fail('should produce StopIteration exception')
  782. except StopIteration:
  783. pass
  784. a = 1
  785. try:
  786. g = (a for d in a)
  787. g.next()
  788. self.fail('should produce TypeError')
  789. except TypeError:
  790. pass
  791. self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
  792. self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
  793. a = [x for x in range(10)]
  794. b = (x for x in (y for y in a))
  795. self.assertEqual(sum(b), sum([x for x in range(10)]))
  796. self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
  797. self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
  798. self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
  799. self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
  800. self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
  801. self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)]))
  802. self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
  803. check_syntax_error(self, "foo(x for x in range(10), 100)")
  804. check_syntax_error(self, "foo(100, x for x in range(10))")
  805. def testComprehensionSpecials(self):
  806. # test for outmost iterable precomputation
  807. x = 10; g = (i for i in range(x)); x = 5
  808. self.assertEqual(len(list(g)), 10)
  809. # This should hold, since we're only precomputing outmost iterable.
  810. x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
  811. x = 5; t = True;
  812. self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
  813. # Grammar allows multiple adjacent 'if's in listcomps and genexps,
  814. # even though it's silly. Make sure it works (ifelse broke this.)
  815. self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
  816. self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
  817. # verify unpacking single element tuples in listcomp/genexp.
  818. self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
  819. self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
  820. def testIfElseExpr(self):
  821. # Test ifelse expressions in various cases
  822. def _checkeval(msg, ret):
  823. "helper to check that evaluation of expressions is done correctly"
  824. print x
  825. return ret
  826. self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
  827. self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
  828. self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True])
  829. self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
  830. self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
  831. self.assertEqual((5 and 6 if 0 else 1), 1)
  832. self.assertEqual(((5 and 6) if 0 else 1), 1)
  833. self.assertEqual((5 and (6 if 1 else 1)), 6)
  834. self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
  835. self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
  836. self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
  837. self.assertEqual((not 5 if 1 else 1), False)
  838. self.assertEqual((not 5 if 0 else 1), 1)
  839. self.assertEqual((6 + 1 if 1 else 2), 7)
  840. self.assertEqual((6 - 1 if 1 else 2), 5)
  841. self.assertEqual((6 * 2 if 1 else 4), 12)
  842. self.assertEqual((6 / 2 if 1 else 3), 3)
  843. self.assertEqual((6 < 4 if 0 else 2), 2)
  844. def test_main():
  845. run_unittest(TokenTests, GrammarTests)
  846. if __name__ == '__main__':
  847. test_main()