/Lib/test/test_grammar.py

http://unladen-swallow.googlecode.com/ · Python · 963 lines · 737 code · 109 blank · 117 comment · 277 complexity · bd412719f3cc6e75cb2bc3e0edc1b5fa MD5 · raw file

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