python2-grammar.py 30 KB

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