python2-grammar-crlf.py 30 KB

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