py3_test_grammar.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947
  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.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(type(000), type(0))
  25. self.assertEquals(0xff, 255)
  26. self.assertEquals(0o377, 255)
  27. self.assertEquals(2147483647, 0o17777777777)
  28. self.assertEquals(0b1001, 9)
  29. # "0x" is not a valid literal
  30. self.assertRaises(SyntaxError, eval, "0x")
  31. from sys import maxsize
  32. if maxsize == 2147483647:
  33. self.assertEquals(-2147483647-1, -0o20000000000)
  34. # XXX -2147483648
  35. self.assert_(0o37777777777 > 0)
  36. self.assert_(0xffffffff > 0)
  37. self.assert_(0b1111111111111111111111111111111 > 0)
  38. for s in ('2147483648', '0o40000000000', '0x100000000',
  39. '0b10000000000000000000000000000000'):
  40. try:
  41. x = eval(s)
  42. except OverflowError:
  43. self.fail("OverflowError on huge integer literal %r" % s)
  44. elif maxsize == 9223372036854775807:
  45. self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000)
  46. self.assert_(0o1777777777777777777777 > 0)
  47. self.assert_(0xffffffffffffffff > 0)
  48. self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
  49. for s in '9223372036854775808', '0o2000000000000000000000', \
  50. '0x10000000000000000', \
  51. '0b100000000000000000000000000000000000000000000000000000000000000':
  52. try:
  53. x = eval(s)
  54. except OverflowError:
  55. self.fail("OverflowError on huge integer literal %r" % s)
  56. else:
  57. self.fail('Weird maxsize value %r' % maxsize)
  58. def testLongIntegers(self):
  59. x = 0
  60. x = 0xffffffffffffffff
  61. x = 0Xffffffffffffffff
  62. x = 0o77777777777777777
  63. x = 0O77777777777777777
  64. x = 123456789012345678901234567890
  65. x = 0b100000000000000000000000000000000000000000000000000000000000000000000
  66. x = 0B111111111111111111111111111111111111111111111111111111111111111111111
  67. def testUnderscoresInNumbers(self):
  68. # Integers
  69. x = 1_0
  70. x = 123_456_7_89
  71. x = 0xabc_123_4_5
  72. x = 0X_abc_123
  73. x = 0B11_01
  74. x = 0b_11_01
  75. x = 0o45_67
  76. x = 0O_45_67
  77. # Floats
  78. x = 3_1.4
  79. x = 03_1.4
  80. x = 3_1.
  81. x = .3_1
  82. x = 3.1_4
  83. x = 0_3.1_4
  84. x = 3e1_4
  85. x = 3_1e+4_1
  86. x = 3_1E-4_1
  87. def testFloats(self):
  88. x = 3.14
  89. x = 314.
  90. x = 0.314
  91. # XXX x = 000.314
  92. x = .314
  93. x = 3e14
  94. x = 3E14
  95. x = 3e-14
  96. x = 3e+14
  97. x = 3.e14
  98. x = .3e14
  99. x = 3.1e4
  100. def testStringLiterals(self):
  101. x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
  102. x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
  103. x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
  104. x = "doesn't \"shrink\" does it"
  105. y = 'doesn\'t "shrink" does it'
  106. self.assert_(len(x) == 24 and x == y)
  107. x = "does \"shrink\" doesn't it"
  108. y = 'does "shrink" doesn\'t it'
  109. self.assert_(len(x) == 24 and x == y)
  110. x = """
  111. The "quick"
  112. brown fox
  113. jumps over
  114. the 'lazy' dog.
  115. """
  116. y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
  117. self.assertEquals(x, y)
  118. y = '''
  119. The "quick"
  120. brown fox
  121. jumps over
  122. the 'lazy' dog.
  123. '''
  124. self.assertEquals(x, y)
  125. y = "\n\
  126. The \"quick\"\n\
  127. brown fox\n\
  128. jumps over\n\
  129. the 'lazy' dog.\n\
  130. "
  131. self.assertEquals(x, y)
  132. y = '\n\
  133. The \"quick\"\n\
  134. brown fox\n\
  135. jumps over\n\
  136. the \'lazy\' dog.\n\
  137. '
  138. self.assertEquals(x, y)
  139. x = rf"hello \{True}"; y = f"hello \\{True}"
  140. self.assertEquals(x, y)
  141. def testEllipsis(self):
  142. x = ...
  143. self.assert_(x is Ellipsis)
  144. self.assertRaises(SyntaxError, eval, ".. .")
  145. class GrammarTests(unittest.TestCase):
  146. # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
  147. # XXX can't test in a script -- this rule is only used when interactive
  148. # file_input: (NEWLINE | stmt)* ENDMARKER
  149. # Being tested as this very moment this very module
  150. # expr_input: testlist NEWLINE
  151. # XXX Hard to test -- used only in calls to input()
  152. def testEvalInput(self):
  153. # testlist ENDMARKER
  154. x = eval('1, 0 or 1')
  155. def testFuncdef(self):
  156. ### [decorators] 'def' NAME parameters ['->' test] ':' suite
  157. ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
  158. ### decorators: decorator+
  159. ### parameters: '(' [typedargslist] ')'
  160. ### typedargslist: ((tfpdef ['=' test] ',')*
  161. ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
  162. ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
  163. ### tfpdef: NAME [':' test]
  164. ### varargslist: ((vfpdef ['=' test] ',')*
  165. ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
  166. ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
  167. ### vfpdef: NAME
  168. def f1(): pass
  169. f1()
  170. f1(*())
  171. f1(*(), **{})
  172. def f2(one_argument): pass
  173. def f3(two, arguments): pass
  174. self.assertEquals(f2.__code__.co_varnames, ('one_argument',))
  175. self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments'))
  176. def a1(one_arg,): pass
  177. def a2(two, args,): pass
  178. def v0(*rest): pass
  179. def v1(a, *rest): pass
  180. def v2(a, b, *rest): pass
  181. f1()
  182. f2(1)
  183. f2(1,)
  184. f3(1, 2)
  185. f3(1, 2,)
  186. v0()
  187. v0(1)
  188. v0(1,)
  189. v0(1,2)
  190. v0(1,2,3,4,5,6,7,8,9,0)
  191. v1(1)
  192. v1(1,)
  193. v1(1,2)
  194. v1(1,2,3)
  195. v1(1,2,3,4,5,6,7,8,9,0)
  196. v2(1,2)
  197. v2(1,2,3)
  198. v2(1,2,3,4)
  199. v2(1,2,3,4,5,6,7,8,9,0)
  200. def d01(a=1): pass
  201. d01()
  202. d01(1)
  203. d01(*(1,))
  204. d01(**{'a':2})
  205. def d11(a, b=1): pass
  206. d11(1)
  207. d11(1, 2)
  208. d11(1, **{'b':2})
  209. def d21(a, b, c=1): pass
  210. d21(1, 2)
  211. d21(1, 2, 3)
  212. d21(*(1, 2, 3))
  213. d21(1, *(2, 3))
  214. d21(1, 2, *(3,))
  215. d21(1, 2, **{'c':3})
  216. def d02(a=1, b=2): pass
  217. d02()
  218. d02(1)
  219. d02(1, 2)
  220. d02(*(1, 2))
  221. d02(1, *(2,))
  222. d02(1, **{'b':2})
  223. d02(**{'a': 1, 'b': 2})
  224. def d12(a, b=1, c=2): pass
  225. d12(1)
  226. d12(1, 2)
  227. d12(1, 2, 3)
  228. def d22(a, b, c=1, d=2): pass
  229. d22(1, 2)
  230. d22(1, 2, 3)
  231. d22(1, 2, 3, 4)
  232. def d01v(a=1, *rest): pass
  233. d01v()
  234. d01v(1)
  235. d01v(1, 2)
  236. d01v(*(1, 2, 3, 4))
  237. d01v(*(1,))
  238. d01v(**{'a':2})
  239. def d11v(a, b=1, *rest): pass
  240. d11v(1)
  241. d11v(1, 2)
  242. d11v(1, 2, 3)
  243. def d21v(a, b, c=1, *rest): pass
  244. d21v(1, 2)
  245. d21v(1, 2, 3)
  246. d21v(1, 2, 3, 4)
  247. d21v(*(1, 2, 3, 4))
  248. d21v(1, 2, **{'c': 3})
  249. def d02v(a=1, b=2, *rest): pass
  250. d02v()
  251. d02v(1)
  252. d02v(1, 2)
  253. d02v(1, 2, 3)
  254. d02v(1, *(2, 3, 4))
  255. d02v(**{'a': 1, 'b': 2})
  256. def d12v(a, b=1, c=2, *rest): pass
  257. d12v(1)
  258. d12v(1, 2)
  259. d12v(1, 2, 3)
  260. d12v(1, 2, 3, 4)
  261. d12v(*(1, 2, 3, 4))
  262. d12v(1, 2, *(3, 4, 5))
  263. d12v(1, *(2,), **{'c': 3})
  264. def d22v(a, b, c=1, d=2, *rest): pass
  265. d22v(1, 2)
  266. d22v(1, 2, 3)
  267. d22v(1, 2, 3, 4)
  268. d22v(1, 2, 3, 4, 5)
  269. d22v(*(1, 2, 3, 4))
  270. d22v(1, 2, *(3, 4, 5))
  271. d22v(1, *(2, 3), **{'d': 4})
  272. # keyword argument type tests
  273. try:
  274. str('x', **{b'foo':1 })
  275. except TypeError:
  276. pass
  277. else:
  278. self.fail('Bytes should not work as keyword argument names')
  279. # keyword only argument tests
  280. def pos0key1(*, key): return key
  281. pos0key1(key=100)
  282. def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
  283. pos2key2(1, 2, k1=100)
  284. pos2key2(1, 2, k1=100, k2=200)
  285. pos2key2(1, 2, k2=100, k1=200)
  286. def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
  287. pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
  288. pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
  289. # keyword arguments after *arglist
  290. def f(*args, **kwargs):
  291. return args, kwargs
  292. self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
  293. {'x':2, 'y':5}))
  294. self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
  295. self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
  296. # argument annotation tests
  297. def f(x) -> list: pass
  298. self.assertEquals(f.__annotations__, {'return': list})
  299. def f(x:int): pass
  300. self.assertEquals(f.__annotations__, {'x': int})
  301. def f(*x:str): pass
  302. self.assertEquals(f.__annotations__, {'x': str})
  303. def f(**x:float): pass
  304. self.assertEquals(f.__annotations__, {'x': float})
  305. def f(x, y:1+2): pass
  306. self.assertEquals(f.__annotations__, {'y': 3})
  307. def f(a, b:1, c:2, d): pass
  308. self.assertEquals(f.__annotations__, {'b': 1, 'c': 2})
  309. def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
  310. self.assertEquals(f.__annotations__,
  311. {'b': 1, 'c': 2, 'e': 3, 'g': 6})
  312. def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
  313. **k:11) -> 12: pass
  314. self.assertEquals(f.__annotations__,
  315. {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
  316. 'k': 11, 'return': 12})
  317. # Check for SF Bug #1697248 - mixing decorators and a return annotation
  318. def null(x): return x
  319. @null
  320. def f(x) -> list: pass
  321. self.assertEquals(f.__annotations__, {'return': list})
  322. # test closures with a variety of oparg's
  323. closure = 1
  324. def f(): return closure
  325. def f(x=1): return closure
  326. def f(*, k=1): return closure
  327. def f() -> int: return closure
  328. # Check ast errors in *args and *kwargs
  329. check_syntax_error(self, "f(*g(1=2))")
  330. check_syntax_error(self, "f(**g(1=2))")
  331. def testLambdef(self):
  332. ### lambdef: 'lambda' [varargslist] ':' test
  333. l1 = lambda : 0
  334. self.assertEquals(l1(), 0)
  335. l2 = lambda : a[d] # XXX just testing the expression
  336. l3 = lambda : [2 < x for x in [-1, 3, 0]]
  337. self.assertEquals(l3(), [0, 1, 0])
  338. l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
  339. self.assertEquals(l4(), 1)
  340. l5 = lambda x, y, z=2: x + y + z
  341. self.assertEquals(l5(1, 2), 5)
  342. self.assertEquals(l5(1, 2, 3), 6)
  343. check_syntax_error(self, "lambda x: x = 2")
  344. check_syntax_error(self, "lambda (None,): None")
  345. l6 = lambda x, y, *, k=20: x+y+k
  346. self.assertEquals(l6(1,2), 1+2+20)
  347. self.assertEquals(l6(1,2,k=10), 1+2+10)
  348. ### stmt: simple_stmt | compound_stmt
  349. # Tested below
  350. def testSimpleStmt(self):
  351. ### simple_stmt: small_stmt (';' small_stmt)* [';']
  352. x = 1; pass; del x
  353. def foo():
  354. # verify statements that end with semi-colons
  355. x = 1; pass; del x;
  356. foo()
  357. ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
  358. # Tested below
  359. def testExprStmt(self):
  360. # (exprlist '=')* exprlist
  361. 1
  362. 1, 2, 3
  363. x = 1
  364. x = 1, 2, 3
  365. x = y = z = 1, 2, 3
  366. x, y, z = 1, 2, 3
  367. abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
  368. check_syntax_error(self, "x + 1 = 1")
  369. check_syntax_error(self, "a + 1 = b + 2")
  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 testNonlocal(self):
  465. # 'nonlocal' NAME (',' NAME)*
  466. x = 0
  467. y = 0
  468. def f():
  469. nonlocal x
  470. nonlocal x, y
  471. def testAssert(self):
  472. # assert_stmt: 'assert' test [',' test]
  473. assert 1
  474. assert 1, 1
  475. assert lambda x:x
  476. assert 1, lambda x:x+1
  477. try:
  478. assert 0, "msg"
  479. except AssertionError as e:
  480. self.assertEquals(e.args[0], "msg")
  481. else:
  482. if __debug__:
  483. self.fail("AssertionError not raised by assert 0")
  484. ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
  485. # Tested below
  486. def testIf(self):
  487. # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
  488. if 1: pass
  489. if 1: pass
  490. else: pass
  491. if 0: pass
  492. elif 0: pass
  493. if 0: pass
  494. elif 0: pass
  495. elif 0: pass
  496. elif 0: pass
  497. else: pass
  498. def testWhile(self):
  499. # 'while' test ':' suite ['else' ':' suite]
  500. while 0: pass
  501. while 0: pass
  502. else: pass
  503. # Issue1920: "while 0" is optimized away,
  504. # ensure that the "else" clause is still present.
  505. x = 0
  506. while 0:
  507. x = 1
  508. else:
  509. x = 2
  510. self.assertEquals(x, 2)
  511. def testFor(self):
  512. # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
  513. for i in 1, 2, 3: pass
  514. for i, j, k in (): pass
  515. else: pass
  516. class Squares:
  517. def __init__(self, max):
  518. self.max = max
  519. self.sofar = []
  520. def __len__(self): return len(self.sofar)
  521. def __getitem__(self, i):
  522. if not 0 <= i < self.max: raise IndexError
  523. n = len(self.sofar)
  524. while n <= i:
  525. self.sofar.append(n*n)
  526. n = n+1
  527. return self.sofar[i]
  528. n = 0
  529. for x in Squares(10): n = n+x
  530. if n != 285:
  531. self.fail('for over growing sequence')
  532. result = []
  533. for x, in [(1,), (2,), (3,)]:
  534. result.append(x)
  535. self.assertEqual(result, [1, 2, 3])
  536. def testTry(self):
  537. ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  538. ### | 'try' ':' suite 'finally' ':' suite
  539. ### except_clause: 'except' [expr ['as' expr]]
  540. try:
  541. 1/0
  542. except ZeroDivisionError:
  543. pass
  544. else:
  545. pass
  546. try: 1/0
  547. except EOFError: pass
  548. except TypeError as msg: pass
  549. except RuntimeError as msg: pass
  550. except: pass
  551. else: pass
  552. try: 1/0
  553. except (EOFError, TypeError, ZeroDivisionError): pass
  554. try: 1/0
  555. except (EOFError, TypeError, ZeroDivisionError) as msg: pass
  556. try: pass
  557. finally: pass
  558. def testSuite(self):
  559. # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
  560. if 1: pass
  561. if 1:
  562. pass
  563. if 1:
  564. #
  565. #
  566. #
  567. pass
  568. pass
  569. #
  570. pass
  571. #
  572. def testTest(self):
  573. ### and_test ('or' and_test)*
  574. ### and_test: not_test ('and' not_test)*
  575. ### not_test: 'not' not_test | comparison
  576. if not 1: pass
  577. if 1 and 1: pass
  578. if 1 or 1: pass
  579. if not not not 1: pass
  580. if not 1 and 1 and 1: pass
  581. if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
  582. def testComparison(self):
  583. ### comparison: expr (comp_op expr)*
  584. ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
  585. if 1: pass
  586. x = (1 == 1)
  587. if 1 == 1: pass
  588. if 1 != 1: pass
  589. if 1 < 1: pass
  590. if 1 > 1: pass
  591. if 1 <= 1: pass
  592. if 1 >= 1: pass
  593. if 1 is 1: pass
  594. if 1 is not 1: pass
  595. if 1 in (): pass
  596. if 1 not in (): pass
  597. if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
  598. def testBinaryMaskOps(self):
  599. x = 1 & 1
  600. x = 1 ^ 1
  601. x = 1 | 1
  602. def testShiftOps(self):
  603. x = 1 << 1
  604. x = 1 >> 1
  605. x = 1 << 1 >> 1
  606. def testAdditiveOps(self):
  607. x = 1
  608. x = 1 + 1
  609. x = 1 - 1 - 1
  610. x = 1 - 1 + 1 - 1 + 1
  611. def testMultiplicativeOps(self):
  612. x = 1 * 1
  613. x = 1 / 1
  614. x = 1 % 1
  615. x = 1 / 1 * 1 % 1
  616. def testUnaryOps(self):
  617. x = +1
  618. x = -1
  619. x = ~1
  620. x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
  621. x = -1*1/1 + 1*1 - ---1*1
  622. def testSelectors(self):
  623. ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
  624. ### subscript: expr | [expr] ':' [expr]
  625. import sys, time
  626. c = sys.path[0]
  627. x = time.time()
  628. x = sys.modules['time'].time()
  629. a = '01234'
  630. c = a[0]
  631. c = a[-1]
  632. s = a[0:5]
  633. s = a[:5]
  634. s = a[0:]
  635. s = a[:]
  636. s = a[-5:]
  637. s = a[:-1]
  638. s = a[-4:-3]
  639. # A rough test of SF bug 1333982. http://python.org/sf/1333982
  640. # The testing here is fairly incomplete.
  641. # Test cases should include: commas with 1 and 2 colons
  642. d = {}
  643. d[1] = 1
  644. d[1,] = 2
  645. d[1,2] = 3
  646. d[1,2,3] = 4
  647. L = list(d)
  648. L.sort(key=lambda x: x if isinstance(x, tuple) else ())
  649. self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
  650. def testAtoms(self):
  651. ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
  652. ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
  653. x = (1)
  654. x = (1 or 2 or 3)
  655. x = (1 or 2 or 3, 2, 3)
  656. x = []
  657. x = [1]
  658. x = [1 or 2 or 3]
  659. x = [1 or 2 or 3, 2, 3]
  660. x = []
  661. x = {}
  662. x = {'one': 1}
  663. x = {'one': 1,}
  664. x = {'one' or 'two': 1 or 2}
  665. x = {'one': 1, 'two': 2}
  666. x = {'one': 1, 'two': 2,}
  667. x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
  668. x = {'one'}
  669. x = {'one', 1,}
  670. x = {'one', 'two', 'three'}
  671. x = {2, 3, 4,}
  672. x = x
  673. x = 'x'
  674. x = 123
  675. ### exprlist: expr (',' expr)* [',']
  676. ### testlist: test (',' test)* [',']
  677. # These have been exercised enough above
  678. def testClassdef(self):
  679. # 'class' NAME ['(' [testlist] ')'] ':' suite
  680. class B: pass
  681. class B2(): pass
  682. class C1(B): pass
  683. class C2(B): pass
  684. class D(C1, C2, B): pass
  685. class C:
  686. def meth1(self): pass
  687. def meth2(self, arg): pass
  688. def meth3(self, a1, a2): pass
  689. # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
  690. # decorators: decorator+
  691. # decorated: decorators (classdef | funcdef)
  692. def class_decorator(x): return x
  693. @class_decorator
  694. class G: pass
  695. def testDictcomps(self):
  696. # dictorsetmaker: ( (test ':' test (comp_for |
  697. # (',' test ':' test)* [','])) |
  698. # (test (comp_for | (',' test)* [','])) )
  699. nums = [1, 2, 3]
  700. self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
  701. def testListcomps(self):
  702. # list comprehension tests
  703. nums = [1, 2, 3, 4, 5]
  704. strs = ["Apple", "Banana", "Coconut"]
  705. spcs = [" Apple", " Banana ", "Coco nut "]
  706. self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
  707. self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
  708. self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
  709. self.assertEqual([(i, s) for i in nums for s in strs],
  710. [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
  711. (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
  712. (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
  713. (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
  714. (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
  715. self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
  716. [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
  717. (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
  718. (5, 'Banana'), (5, 'Coconut')])
  719. self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
  720. [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
  721. def test_in_func(l):
  722. return [0 < x < 3 for x in l if x > 2]
  723. self.assertEqual(test_in_func(nums), [False, False, False])
  724. def test_nested_front():
  725. self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
  726. [[1, 2], [3, 4], [5, 6]])
  727. test_nested_front()
  728. check_syntax_error(self, "[i, s for i in nums for s in strs]")
  729. check_syntax_error(self, "[x if y]")
  730. suppliers = [
  731. (1, "Boeing"),
  732. (2, "Ford"),
  733. (3, "Macdonalds")
  734. ]
  735. parts = [
  736. (10, "Airliner"),
  737. (20, "Engine"),
  738. (30, "Cheeseburger")
  739. ]
  740. suppart = [
  741. (1, 10), (1, 20), (2, 20), (3, 30)
  742. ]
  743. x = [
  744. (sname, pname)
  745. for (sno, sname) in suppliers
  746. for (pno, pname) in parts
  747. for (sp_sno, sp_pno) in suppart
  748. if sno == sp_sno and pno == sp_pno
  749. ]
  750. self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
  751. ('Macdonalds', 'Cheeseburger')])
  752. def testGenexps(self):
  753. # generator expression tests
  754. g = ([x for x in range(10)] for x in range(1))
  755. self.assertEqual(next(g), [x for x in range(10)])
  756. try:
  757. next(g)
  758. self.fail('should produce StopIteration exception')
  759. except StopIteration:
  760. pass
  761. a = 1
  762. try:
  763. g = (a for d in a)
  764. next(g)
  765. self.fail('should produce TypeError')
  766. except TypeError:
  767. pass
  768. self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
  769. self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
  770. a = [x for x in range(10)]
  771. b = (x for x in (y for y in a))
  772. self.assertEqual(sum(b), sum([x for x in range(10)]))
  773. self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
  774. self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
  775. self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
  776. self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
  777. self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
  778. 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)]))
  779. self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
  780. check_syntax_error(self, "foo(x for x in range(10), 100)")
  781. check_syntax_error(self, "foo(100, x for x in range(10))")
  782. def testComprehensionSpecials(self):
  783. # test for outmost iterable precomputation
  784. x = 10; g = (i for i in range(x)); x = 5
  785. self.assertEqual(len(list(g)), 10)
  786. # This should hold, since we're only precomputing outmost iterable.
  787. x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
  788. x = 5; t = True;
  789. self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
  790. # Grammar allows multiple adjacent 'if's in listcomps and genexps,
  791. # even though it's silly. Make sure it works (ifelse broke this.)
  792. self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
  793. self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
  794. # verify unpacking single element tuples in listcomp/genexp.
  795. self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
  796. self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
  797. def test_with_statement(self):
  798. class manager(object):
  799. def __enter__(self):
  800. return (1, 2)
  801. def __exit__(self, *args):
  802. pass
  803. with manager():
  804. pass
  805. with manager() as x:
  806. pass
  807. with manager() as (x, y):
  808. pass
  809. with manager(), manager():
  810. pass
  811. with manager() as x, manager() as y:
  812. pass
  813. with manager() as x, manager():
  814. pass
  815. def testIfElseExpr(self):
  816. # Test ifelse expressions in various cases
  817. def _checkeval(msg, ret):
  818. "helper to check that evaluation of expressions is done correctly"
  819. print(x)
  820. return ret
  821. # the next line is not allowed anymore
  822. #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
  823. self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
  824. 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])
  825. self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
  826. self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
  827. self.assertEqual((5 and 6 if 0 else 1), 1)
  828. self.assertEqual(((5 and 6) if 0 else 1), 1)
  829. self.assertEqual((5 and (6 if 1 else 1)), 6)
  830. self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
  831. self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
  832. self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
  833. self.assertEqual((not 5 if 1 else 1), False)
  834. self.assertEqual((not 5 if 0 else 1), 1)
  835. self.assertEqual((6 + 1 if 1 else 2), 7)
  836. self.assertEqual((6 - 1 if 1 else 2), 5)
  837. self.assertEqual((6 * 2 if 1 else 4), 12)
  838. self.assertEqual((6 / 2 if 1 else 3), 3)
  839. self.assertEqual((6 < 4 if 0 else 2), 2)
  840. def test_main():
  841. run_unittest(TokenTests, GrammarTests)
  842. if __name__ == '__main__':
  843. test_main()