test_grammar.py 32 KB

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