test_grammar.py 30 KB

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