PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2/test/test_parser.py

https://bitbucket.org/kcr/pypy
Python | 596 lines | 554 code | 29 blank | 13 comment | 7 complexity | 6cf76ea62b411135f65d508b8c60cdf2 MD5 | raw file
Possible License(s): Apache-2.0
  1. import parser
  2. import unittest
  3. import sys
  4. from test import test_support
  5. #
  6. # First, we test that we can generate trees from valid source fragments,
  7. # and that these valid trees are indeed allowed by the tree-loading side
  8. # of the parser module.
  9. #
  10. class RoundtripLegalSyntaxTestCase(unittest.TestCase):
  11. def roundtrip(self, f, s):
  12. st1 = f(s)
  13. t = st1.totuple()
  14. try:
  15. st2 = parser.sequence2st(t)
  16. except parser.ParserError, why:
  17. self.fail("could not roundtrip %r: %s" % (s, why))
  18. self.assertEqual(t, st2.totuple(),
  19. "could not re-generate syntax tree")
  20. def check_expr(self, s):
  21. self.roundtrip(parser.expr, s)
  22. def test_flags_passed(self):
  23. # The unicode literals flags has to be passed from the paser to AST
  24. # generation.
  25. suite = parser.suite("from __future__ import unicode_literals; x = ''")
  26. code = suite.compile()
  27. scope = {}
  28. exec code in scope
  29. self.assertIsInstance(scope["x"], unicode)
  30. def check_suite(self, s):
  31. self.roundtrip(parser.suite, s)
  32. def test_yield_statement(self):
  33. self.check_suite("def f(): yield 1")
  34. self.check_suite("def f(): yield")
  35. self.check_suite("def f(): x += yield")
  36. self.check_suite("def f(): x = yield 1")
  37. self.check_suite("def f(): x = y = yield 1")
  38. self.check_suite("def f(): x = yield")
  39. self.check_suite("def f(): x = y = yield")
  40. self.check_suite("def f(): 1 + (yield)*2")
  41. self.check_suite("def f(): (yield 1)*2")
  42. self.check_suite("def f(): return; yield 1")
  43. self.check_suite("def f(): yield 1; return")
  44. self.check_suite("def f():\n"
  45. " for x in range(30):\n"
  46. " yield x\n")
  47. self.check_suite("def f():\n"
  48. " if (yield):\n"
  49. " yield x\n")
  50. def test_expressions(self):
  51. self.check_expr("foo(1)")
  52. self.check_expr("{1:1}")
  53. self.check_expr("{1:1, 2:2, 3:3}")
  54. self.check_expr("{1:1, 2:2, 3:3,}")
  55. self.check_expr("{1}")
  56. self.check_expr("{1, 2, 3}")
  57. self.check_expr("{1, 2, 3,}")
  58. self.check_expr("[]")
  59. self.check_expr("[1]")
  60. self.check_expr("[1, 2, 3]")
  61. self.check_expr("[1, 2, 3,]")
  62. self.check_expr("()")
  63. self.check_expr("(1,)")
  64. self.check_expr("(1, 2, 3)")
  65. self.check_expr("(1, 2, 3,)")
  66. self.check_expr("[x**3 for x in range(20)]")
  67. self.check_expr("[x**3 for x in range(20) if x % 3]")
  68. self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
  69. self.check_expr("[x+y for x in range(30) for y in range(20) if x % 2 if y % 3]")
  70. #self.check_expr("[x for x in lambda: True, lambda: False if x()]")
  71. self.check_expr("list(x**3 for x in range(20))")
  72. self.check_expr("list(x**3 for x in range(20) if x % 3)")
  73. self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
  74. self.check_expr("list(x+y for x in range(30) for y in range(20) if x % 2 if y % 3)")
  75. self.check_expr("{x**3 for x in range(30)}")
  76. self.check_expr("{x**3 for x in range(30) if x % 3}")
  77. self.check_expr("{x**3 for x in range(30) if x % 2 if x % 3}")
  78. self.check_expr("{x+y for x in range(30) for y in range(20) if x % 2 if y % 3}")
  79. self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30))}")
  80. self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30)) if x % 3}")
  81. self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30)) if x % 3 if y % 3}")
  82. self.check_expr("{x:y for x in range(30) for y in range(20) if x % 2 if y % 3}")
  83. self.check_expr("foo(*args)")
  84. self.check_expr("foo(*args, **kw)")
  85. self.check_expr("foo(**kw)")
  86. self.check_expr("foo(key=value)")
  87. self.check_expr("foo(key=value, *args)")
  88. self.check_expr("foo(key=value, *args, **kw)")
  89. self.check_expr("foo(key=value, **kw)")
  90. self.check_expr("foo(a, b, c, *args)")
  91. self.check_expr("foo(a, b, c, *args, **kw)")
  92. self.check_expr("foo(a, b, c, **kw)")
  93. self.check_expr("foo(a, *args, keyword=23)")
  94. self.check_expr("foo + bar")
  95. self.check_expr("foo - bar")
  96. self.check_expr("foo * bar")
  97. self.check_expr("foo / bar")
  98. self.check_expr("foo // bar")
  99. self.check_expr("lambda: 0")
  100. self.check_expr("lambda x: 0")
  101. self.check_expr("lambda *y: 0")
  102. self.check_expr("lambda *y, **z: 0")
  103. self.check_expr("lambda **z: 0")
  104. self.check_expr("lambda x, y: 0")
  105. self.check_expr("lambda foo=bar: 0")
  106. self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
  107. self.check_expr("lambda foo=bar, **z: 0")
  108. self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
  109. self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
  110. self.check_expr("lambda x, *y, **z: 0")
  111. self.check_expr("lambda x: 5 if x else 2")
  112. self.check_expr("(x for x in range(10))")
  113. self.check_expr("foo(x for x in range(10))")
  114. def test_print(self):
  115. self.check_suite("print")
  116. self.check_suite("print 1")
  117. self.check_suite("print 1,")
  118. self.check_suite("print >>fp")
  119. self.check_suite("print >>fp, 1")
  120. self.check_suite("print >>fp, 1,")
  121. def test_simple_expression(self):
  122. # expr_stmt
  123. self.check_suite("a")
  124. def test_simple_assignments(self):
  125. self.check_suite("a = b")
  126. self.check_suite("a = b = c = d = e")
  127. def test_simple_augmented_assignments(self):
  128. self.check_suite("a += b")
  129. self.check_suite("a -= b")
  130. self.check_suite("a *= b")
  131. self.check_suite("a /= b")
  132. self.check_suite("a //= b")
  133. self.check_suite("a %= b")
  134. self.check_suite("a &= b")
  135. self.check_suite("a |= b")
  136. self.check_suite("a ^= b")
  137. self.check_suite("a <<= b")
  138. self.check_suite("a >>= b")
  139. self.check_suite("a **= b")
  140. def test_function_defs(self):
  141. self.check_suite("def f(): pass")
  142. self.check_suite("def f(*args): pass")
  143. self.check_suite("def f(*args, **kw): pass")
  144. self.check_suite("def f(**kw): pass")
  145. self.check_suite("def f(foo=bar): pass")
  146. self.check_suite("def f(foo=bar, *args): pass")
  147. self.check_suite("def f(foo=bar, *args, **kw): pass")
  148. self.check_suite("def f(foo=bar, **kw): pass")
  149. self.check_suite("def f(a, b): pass")
  150. self.check_suite("def f(a, b, *args): pass")
  151. self.check_suite("def f(a, b, *args, **kw): pass")
  152. self.check_suite("def f(a, b, **kw): pass")
  153. self.check_suite("def f(a, b, foo=bar): pass")
  154. self.check_suite("def f(a, b, foo=bar, *args): pass")
  155. self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
  156. self.check_suite("def f(a, b, foo=bar, **kw): pass")
  157. self.check_suite("@staticmethod\n"
  158. "def f(): pass")
  159. self.check_suite("@staticmethod\n"
  160. "@funcattrs(x, y)\n"
  161. "def f(): pass")
  162. self.check_suite("@funcattrs()\n"
  163. "def f(): pass")
  164. def test_class_defs(self):
  165. self.check_suite("class foo():pass")
  166. self.check_suite("@class_decorator\n"
  167. "class foo():pass")
  168. self.check_suite("@class_decorator(arg)\n"
  169. "class foo():pass")
  170. self.check_suite("@decorator1\n"
  171. "@decorator2\n"
  172. "class foo():pass")
  173. def test_import_from_statement(self):
  174. self.check_suite("from sys.path import *")
  175. self.check_suite("from sys.path import dirname")
  176. self.check_suite("from sys.path import (dirname)")
  177. self.check_suite("from sys.path import (dirname,)")
  178. self.check_suite("from sys.path import dirname as my_dirname")
  179. self.check_suite("from sys.path import (dirname as my_dirname)")
  180. self.check_suite("from sys.path import (dirname as my_dirname,)")
  181. self.check_suite("from sys.path import dirname, basename")
  182. self.check_suite("from sys.path import (dirname, basename)")
  183. self.check_suite("from sys.path import (dirname, basename,)")
  184. self.check_suite(
  185. "from sys.path import dirname as my_dirname, basename")
  186. self.check_suite(
  187. "from sys.path import (dirname as my_dirname, basename)")
  188. self.check_suite(
  189. "from sys.path import (dirname as my_dirname, basename,)")
  190. self.check_suite(
  191. "from sys.path import dirname, basename as my_basename")
  192. self.check_suite(
  193. "from sys.path import (dirname, basename as my_basename)")
  194. self.check_suite(
  195. "from sys.path import (dirname, basename as my_basename,)")
  196. self.check_suite("from .bogus import x")
  197. def test_basic_import_statement(self):
  198. self.check_suite("import sys")
  199. self.check_suite("import sys as system")
  200. self.check_suite("import sys, math")
  201. self.check_suite("import sys as system, math")
  202. self.check_suite("import sys, math as my_math")
  203. def test_relative_imports(self):
  204. self.check_suite("from . import name")
  205. self.check_suite("from .. import name")
  206. self.check_suite("from .pkg import name")
  207. self.check_suite("from ..pkg import name")
  208. def test_pep263(self):
  209. self.check_suite("# -*- coding: iso-8859-1 -*-\n"
  210. "pass\n")
  211. def test_assert(self):
  212. self.check_suite("assert alo < ahi and blo < bhi\n")
  213. def test_with(self):
  214. self.check_suite("with open('x'): pass\n")
  215. self.check_suite("with open('x') as f: pass\n")
  216. self.check_suite("with open('x') as f, open('y') as g: pass\n")
  217. def test_try_stmt(self):
  218. self.check_suite("try: pass\nexcept: pass\n")
  219. self.check_suite("try: pass\nfinally: pass\n")
  220. self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
  221. self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
  222. "finally: pass\n")
  223. self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
  224. self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
  225. "finally: pass\n")
  226. def test_except_clause(self):
  227. self.check_suite("try: pass\nexcept: pass\n")
  228. self.check_suite("try: pass\nexcept A: pass\n")
  229. self.check_suite("try: pass\nexcept A, e: pass\n")
  230. self.check_suite("try: pass\nexcept A as e: pass\n")
  231. def test_position(self):
  232. # An absolutely minimal test of position information. Better
  233. # tests would be a big project.
  234. code = "def f(x):\n return x + 1"
  235. st1 = parser.suite(code)
  236. st2 = st1.totuple(line_info=1, col_info=1)
  237. def walk(tree):
  238. node_type = tree[0]
  239. next = tree[1]
  240. if isinstance(next, tuple):
  241. for elt in tree[1:]:
  242. for x in walk(elt):
  243. yield x
  244. else:
  245. yield tree
  246. terminals = list(walk(st2))
  247. self.assertEqual([
  248. (1, 'def', 1, 0),
  249. (1, 'f', 1, 4),
  250. (7, '(', 1, 5),
  251. (1, 'x', 1, 6),
  252. (8, ')', 1, 7),
  253. (11, ':', 1, 8),
  254. (4, '', 1, 9),
  255. (5, '', 2, -1),
  256. (1, 'return', 2, 4),
  257. (1, 'x', 2, 11),
  258. (14, '+', 2, 13),
  259. (2, '1', 2, 15),
  260. (4, '', 2, 16),
  261. (6, '', 2, -1),
  262. (4, '', 2, -1),
  263. (0, '', 2, -1)],
  264. terminals)
  265. #
  266. # Second, we take *invalid* trees and make sure we get ParserError
  267. # rejections for them.
  268. #
  269. class IllegalSyntaxTestCase(unittest.TestCase):
  270. def check_bad_tree(self, tree, label):
  271. try:
  272. parser.sequence2st(tree)
  273. except parser.ParserError:
  274. pass
  275. else:
  276. self.fail("did not detect invalid tree for %r" % label)
  277. def test_junk(self):
  278. # not even remotely valid:
  279. self.check_bad_tree((1, 2, 3), "<junk>")
  280. def test_illegal_yield_1(self):
  281. # Illegal yield statement: def f(): return 1; yield 1
  282. tree = \
  283. (257,
  284. (264,
  285. (285,
  286. (259,
  287. (1, 'def'),
  288. (1, 'f'),
  289. (260, (7, '('), (8, ')')),
  290. (11, ':'),
  291. (291,
  292. (4, ''),
  293. (5, ''),
  294. (264,
  295. (265,
  296. (266,
  297. (272,
  298. (275,
  299. (1, 'return'),
  300. (313,
  301. (292,
  302. (293,
  303. (294,
  304. (295,
  305. (297,
  306. (298,
  307. (299,
  308. (300,
  309. (301,
  310. (302, (303, (304, (305, (2, '1')))))))))))))))))),
  311. (264,
  312. (265,
  313. (266,
  314. (272,
  315. (276,
  316. (1, 'yield'),
  317. (313,
  318. (292,
  319. (293,
  320. (294,
  321. (295,
  322. (297,
  323. (298,
  324. (299,
  325. (300,
  326. (301,
  327. (302,
  328. (303, (304, (305, (2, '1')))))))))))))))))),
  329. (4, ''))),
  330. (6, ''))))),
  331. (4, ''),
  332. (0, ''))))
  333. self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
  334. def test_illegal_yield_2(self):
  335. # Illegal return in generator: def f(): return 1; yield 1
  336. tree = \
  337. (257,
  338. (264,
  339. (265,
  340. (266,
  341. (278,
  342. (1, 'from'),
  343. (281, (1, '__future__')),
  344. (1, 'import'),
  345. (279, (1, 'generators')))),
  346. (4, ''))),
  347. (264,
  348. (285,
  349. (259,
  350. (1, 'def'),
  351. (1, 'f'),
  352. (260, (7, '('), (8, ')')),
  353. (11, ':'),
  354. (291,
  355. (4, ''),
  356. (5, ''),
  357. (264,
  358. (265,
  359. (266,
  360. (272,
  361. (275,
  362. (1, 'return'),
  363. (313,
  364. (292,
  365. (293,
  366. (294,
  367. (295,
  368. (297,
  369. (298,
  370. (299,
  371. (300,
  372. (301,
  373. (302, (303, (304, (305, (2, '1')))))))))))))))))),
  374. (264,
  375. (265,
  376. (266,
  377. (272,
  378. (276,
  379. (1, 'yield'),
  380. (313,
  381. (292,
  382. (293,
  383. (294,
  384. (295,
  385. (297,
  386. (298,
  387. (299,
  388. (300,
  389. (301,
  390. (302,
  391. (303, (304, (305, (2, '1')))))))))))))))))),
  392. (4, ''))),
  393. (6, ''))))),
  394. (4, ''),
  395. (0, ''))))
  396. self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
  397. def test_print_chevron_comma(self):
  398. # Illegal input: print >>fp,
  399. tree = \
  400. (257,
  401. (264,
  402. (265,
  403. (266,
  404. (268,
  405. (1, 'print'),
  406. (35, '>>'),
  407. (290,
  408. (291,
  409. (292,
  410. (293,
  411. (295,
  412. (296,
  413. (297,
  414. (298, (299, (300, (301, (302, (303, (1, 'fp')))))))))))))),
  415. (12, ','))),
  416. (4, ''))),
  417. (0, ''))
  418. self.check_bad_tree(tree, "print >>fp,")
  419. def test_a_comma_comma_c(self):
  420. # Illegal input: a,,c
  421. tree = \
  422. (258,
  423. (311,
  424. (290,
  425. (291,
  426. (292,
  427. (293,
  428. (295,
  429. (296,
  430. (297,
  431. (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
  432. (12, ','),
  433. (12, ','),
  434. (290,
  435. (291,
  436. (292,
  437. (293,
  438. (295,
  439. (296,
  440. (297,
  441. (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
  442. (4, ''),
  443. (0, ''))
  444. self.check_bad_tree(tree, "a,,c")
  445. def test_illegal_operator(self):
  446. # Illegal input: a $= b
  447. tree = \
  448. (257,
  449. (264,
  450. (265,
  451. (266,
  452. (267,
  453. (312,
  454. (291,
  455. (292,
  456. (293,
  457. (294,
  458. (296,
  459. (297,
  460. (298,
  461. (299,
  462. (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
  463. (268, (37, '$=')),
  464. (312,
  465. (291,
  466. (292,
  467. (293,
  468. (294,
  469. (296,
  470. (297,
  471. (298,
  472. (299,
  473. (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
  474. (4, ''))),
  475. (0, ''))
  476. self.check_bad_tree(tree, "a $= b")
  477. def test_malformed_global(self):
  478. #doesn't have global keyword in ast
  479. tree = (257,
  480. (264,
  481. (265,
  482. (266,
  483. (282, (1, 'foo'))), (4, ''))),
  484. (4, ''),
  485. (0, ''))
  486. self.check_bad_tree(tree, "malformed global ast")
  487. def test_missing_import_source(self):
  488. # from import a
  489. tree = \
  490. (257,
  491. (267,
  492. (268,
  493. (269,
  494. (281,
  495. (283, (1, 'from'), (1, 'import'),
  496. (286, (284, (1, 'fred')))))),
  497. (4, ''))),
  498. (4, ''), (0, ''))
  499. self.check_bad_tree(tree, "from import a")
  500. class CompileTestCase(unittest.TestCase):
  501. # These tests are very minimal. :-(
  502. def test_compile_expr(self):
  503. st = parser.expr('2 + 3')
  504. code = parser.compilest(st)
  505. self.assertEqual(eval(code), 5)
  506. def test_compile_suite(self):
  507. st = parser.suite('x = 2; y = x + 3')
  508. code = parser.compilest(st)
  509. globs = {}
  510. exec code in globs
  511. self.assertEqual(globs['y'], 5)
  512. def test_compile_error(self):
  513. st = parser.suite('1 = 3 + 4')
  514. self.assertRaises(SyntaxError, parser.compilest, st)
  515. def test_compile_badunicode(self):
  516. st = parser.suite('a = u"\U12345678"')
  517. self.assertRaises(SyntaxError, parser.compilest, st)
  518. st = parser.suite('a = u"\u1"')
  519. self.assertRaises(SyntaxError, parser.compilest, st)
  520. class ParserStackLimitTestCase(unittest.TestCase):
  521. """try to push the parser to/over it's limits.
  522. see http://bugs.python.org/issue1881 for a discussion
  523. """
  524. def _nested_expression(self, level):
  525. return "["*level+"]"*level
  526. def test_deeply_nested_list(self):
  527. e = self._nested_expression(99)
  528. st = parser.expr(e)
  529. st.compile()
  530. def test_trigger_memory_error(self):
  531. e = self._nested_expression(100)
  532. print >>sys.stderr, "Expecting 's_push: parser stack overflow' in next line"
  533. self.assertRaises(MemoryError, parser.expr, e)
  534. def test_main():
  535. test_support.run_unittest(
  536. RoundtripLegalSyntaxTestCase,
  537. IllegalSyntaxTestCase,
  538. CompileTestCase,
  539. ParserStackLimitTestCase,
  540. )
  541. if __name__ == "__main__":
  542. test_main()