blob: 46e7b9ec335b2b1174dd8387851e1aa050c65c89 [file] [log] [blame]
Fred Drake79ca79d2000-08-21 22:30:53 +00001import parser
Fred Drake58422e52001-06-04 03:56:24 +00002import unittest
Christian Heimesb186d002008-03-18 15:15:01 +00003import sys
Mark Dickinson211c6252009-02-01 10:28:51 +00004import operator
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import support
Fred Drake79ca79d2000-08-21 22:30:53 +00006
7#
8# First, we test that we can generate trees from valid source fragments,
9# and that these valid trees are indeed allowed by the tree-loading side
10# of the parser module.
11#
12
Fred Drake58422e52001-06-04 03:56:24 +000013class RoundtripLegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +000014
Fred Drake58422e52001-06-04 03:56:24 +000015 def roundtrip(self, f, s):
16 st1 = f(s)
17 t = st1.totuple()
18 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +000019 st2 = parser.sequence2st(t)
Guido van Rossumb940e112007-01-10 16:19:56 +000020 except parser.ParserError as why:
Anthony Baxterc2a5a632004-08-02 06:10:11 +000021 self.fail("could not roundtrip %r: %s" % (s, why))
Fred Drake79ca79d2000-08-21 22:30:53 +000022
Ezio Melottib3aedd42010-11-20 19:04:17 +000023 self.assertEqual(t, st2.totuple(),
24 "could not re-generate syntax tree")
Fred Drake28f739a2000-08-25 22:42:40 +000025
Fred Drake58422e52001-06-04 03:56:24 +000026 def check_expr(self, s):
27 self.roundtrip(parser.expr, s)
Fred Drake28f739a2000-08-25 22:42:40 +000028
Benjamin Petersonf216c942008-10-31 02:28:05 +000029 def test_flags_passed(self):
30 # The unicode literals flags has to be passed from the paser to AST
31 # generation.
32 suite = parser.suite("from __future__ import unicode_literals; x = ''")
33 code = suite.compile()
34 scope = {}
35 exec(code, {}, scope)
Ezio Melottie9615932010-01-24 19:26:24 +000036 self.assertIsInstance(scope["x"], str)
Benjamin Petersonf216c942008-10-31 02:28:05 +000037
Fred Drake58422e52001-06-04 03:56:24 +000038 def check_suite(self, s):
39 self.roundtrip(parser.suite, s)
Fred Drake28f739a2000-08-25 22:42:40 +000040
Fred Drakecf580c72001-07-17 03:01:29 +000041 def test_yield_statement(self):
Tim Peters496563a2002-04-01 00:28:59 +000042 self.check_suite("def f(): yield 1")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000043 self.check_suite("def f(): yield")
44 self.check_suite("def f(): x += yield")
45 self.check_suite("def f(): x = yield 1")
46 self.check_suite("def f(): x = y = yield 1")
47 self.check_suite("def f(): x = yield")
48 self.check_suite("def f(): x = y = yield")
49 self.check_suite("def f(): 1 + (yield)*2")
50 self.check_suite("def f(): (yield 1)*2")
Tim Peters496563a2002-04-01 00:28:59 +000051 self.check_suite("def f(): return; yield 1")
52 self.check_suite("def f(): yield 1; return")
Nick Coghlan1f7ce622012-01-13 21:43:40 +100053 self.check_suite("def f(): yield from 1")
54 self.check_suite("def f(): x = yield from 1")
55 self.check_suite("def f(): f((yield from 1))")
56 self.check_suite("def f(): yield 1; return 1")
Tim Peters496563a2002-04-01 00:28:59 +000057 self.check_suite("def f():\n"
Fred Drakecf580c72001-07-17 03:01:29 +000058 " for x in range(30):\n"
59 " yield x\n")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000060 self.check_suite("def f():\n"
61 " if (yield):\n"
62 " yield x\n")
Fred Drakecf580c72001-07-17 03:01:29 +000063
Mark Dickinson407b3bd2012-04-29 22:18:31 +010064 def test_nonlocal_statement(self):
65 self.check_suite("def f():\n"
66 " x = 0\n"
67 " def g():\n"
68 " nonlocal x\n")
69 self.check_suite("def f():\n"
70 " x = y = 0\n"
71 " def g():\n"
72 " nonlocal x, y\n")
73
Fred Drake58422e52001-06-04 03:56:24 +000074 def test_expressions(self):
75 self.check_expr("foo(1)")
76 self.check_expr("[1, 2, 3]")
77 self.check_expr("[x**3 for x in range(20)]")
78 self.check_expr("[x**3 for x in range(20) if x % 3]")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000079 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
80 self.check_expr("list(x**3 for x in range(20))")
81 self.check_expr("list(x**3 for x in range(20) if x % 3)")
82 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Fred Drake58422e52001-06-04 03:56:24 +000083 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)")
Benjamin Peterson3938a902008-08-20 02:33:00 +000093 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +000094 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +000095 self.check_expr("foo - bar")
96 self.check_expr("foo * bar")
97 self.check_expr("foo / bar")
98 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +000099 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")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000111 self.check_expr("(x for x in range(10))")
112 self.check_expr("foo(x for x in range(10))")
Fred Drake79ca79d2000-08-21 22:30:53 +0000113
Fred Drake58422e52001-06-04 03:56:24 +0000114 def test_simple_expression(self):
115 # expr_stmt
116 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000117
Fred Drake58422e52001-06-04 03:56:24 +0000118 def test_simple_assignments(self):
119 self.check_suite("a = b")
120 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000121
Fred Drake58422e52001-06-04 03:56:24 +0000122 def test_simple_augmented_assignments(self):
123 self.check_suite("a += b")
124 self.check_suite("a -= b")
125 self.check_suite("a *= b")
126 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000127 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000128 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")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000135
Fred Drake58422e52001-06-04 03:56:24 +0000136 def test_function_defs(self):
137 self.check_suite("def f(): pass")
138 self.check_suite("def f(*args): pass")
139 self.check_suite("def f(*args, **kw): pass")
140 self.check_suite("def f(**kw): pass")
141 self.check_suite("def f(foo=bar): pass")
142 self.check_suite("def f(foo=bar, *args): pass")
143 self.check_suite("def f(foo=bar, *args, **kw): pass")
144 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000145
Fred Drake58422e52001-06-04 03:56:24 +0000146 self.check_suite("def f(a, b): pass")
147 self.check_suite("def f(a, b, *args): pass")
148 self.check_suite("def f(a, b, *args, **kw): pass")
149 self.check_suite("def f(a, b, **kw): pass")
150 self.check_suite("def f(a, b, foo=bar): pass")
151 self.check_suite("def f(a, b, foo=bar, *args): pass")
152 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
153 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000154
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000155 self.check_suite("@staticmethod\n"
156 "def f(): pass")
157 self.check_suite("@staticmethod\n"
158 "@funcattrs(x, y)\n"
159 "def f(): pass")
160 self.check_suite("@funcattrs()\n"
161 "def f(): pass")
162
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100163 # keyword-only arguments
164 self.check_suite("def f(*, a): pass")
165 self.check_suite("def f(*, a = 5): pass")
166 self.check_suite("def f(*, a = 5, b): pass")
167 self.check_suite("def f(*, a, b = 5): pass")
168 self.check_suite("def f(*, a, b = 5, **kwds): pass")
169 self.check_suite("def f(*args, a): pass")
170 self.check_suite("def f(*args, a = 5): pass")
171 self.check_suite("def f(*args, a = 5, b): pass")
172 self.check_suite("def f(*args, a, b = 5): pass")
173 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
174
175 # function annotations
176 self.check_suite("def f(a: int): pass")
177 self.check_suite("def f(a: int = 5): pass")
178 self.check_suite("def f(*args: list): pass")
179 self.check_suite("def f(**kwds: dict): pass")
180 self.check_suite("def f(*, a: int): pass")
181 self.check_suite("def f(*, a: int = 5): pass")
182 self.check_suite("def f() -> int: pass")
183
Brett Cannonf4189912005-04-09 02:30:16 +0000184 def test_class_defs(self):
185 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000186 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000187 self.check_suite("@class_decorator\n"
188 "class foo():pass")
189 self.check_suite("@class_decorator(arg)\n"
190 "class foo():pass")
191 self.check_suite("@decorator1\n"
192 "@decorator2\n"
193 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000194
Fred Drake58422e52001-06-04 03:56:24 +0000195 def test_import_from_statement(self):
196 self.check_suite("from sys.path import *")
197 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000198 self.check_suite("from sys.path import (dirname)")
199 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000200 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000201 self.check_suite("from sys.path import (dirname as my_dirname)")
202 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000203 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000204 self.check_suite("from sys.path import (dirname, basename)")
205 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000206 self.check_suite(
207 "from sys.path import dirname as my_dirname, basename")
208 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000209 "from sys.path import (dirname as my_dirname, basename)")
210 self.check_suite(
211 "from sys.path import (dirname as my_dirname, basename,)")
212 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000213 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000214 self.check_suite(
215 "from sys.path import (dirname, basename as my_basename)")
216 self.check_suite(
217 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000218 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000219
Fred Drake58422e52001-06-04 03:56:24 +0000220 def test_basic_import_statement(self):
221 self.check_suite("import sys")
222 self.check_suite("import sys as system")
223 self.check_suite("import sys, math")
224 self.check_suite("import sys as system, math")
225 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000226
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000227 def test_relative_imports(self):
228 self.check_suite("from . import name")
229 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000230 # check all the way up to '....', since '...' is tokenized
231 # differently from '.' (it's an ellipsis token).
232 self.check_suite("from ... import name")
233 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000234 self.check_suite("from .pkg import name")
235 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000236 self.check_suite("from ...pkg import name")
237 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000238
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000239 def test_pep263(self):
240 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
241 "pass\n")
242
243 def test_assert(self):
244 self.check_suite("assert alo < ahi and blo < bhi\n")
245
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000246 def test_with(self):
247 self.check_suite("with open('x'): pass\n")
248 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000249 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000250
Georg Brandleee31162008-12-07 15:15:22 +0000251 def test_try_stmt(self):
252 self.check_suite("try: pass\nexcept: pass\n")
253 self.check_suite("try: pass\nfinally: pass\n")
254 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
255 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
256 "finally: pass\n")
257 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
258 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
259 "finally: pass\n")
260
Thomas Wouters89f507f2006-12-13 04:49:30 +0000261 def test_position(self):
262 # An absolutely minimal test of position information. Better
263 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000264 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000265 st1 = parser.suite(code)
266 st2 = st1.totuple(line_info=1, col_info=1)
267
268 def walk(tree):
269 node_type = tree[0]
270 next = tree[1]
271 if isinstance(next, tuple):
272 for elt in tree[1:]:
273 for x in walk(elt):
274 yield x
275 else:
276 yield tree
277
278 terminals = list(walk(st2))
279 self.assertEqual([
280 (1, 'def', 1, 0),
281 (1, 'f', 1, 4),
282 (7, '(', 1, 5),
283 (1, 'x', 1, 6),
284 (8, ')', 1, 7),
285 (11, ':', 1, 8),
286 (4, '', 1, 9),
287 (5, '', 2, -1),
288 (1, 'return', 2, 4),
289 (1, 'x', 2, 11),
290 (14, '+', 2, 13),
291 (2, '1', 2, 15),
292 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000293 (6, '', 2, -1),
294 (4, '', 2, -1),
295 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000296 terminals)
297
Benjamin Peterson4905e802009-09-27 02:43:28 +0000298 def test_extended_unpacking(self):
299 self.check_suite("*a = y")
300 self.check_suite("x, *b, = m")
301 self.check_suite("[*a, *b] = y")
302 self.check_suite("for [*x, b] in x: pass")
303
Thomas Wouters89f507f2006-12-13 04:49:30 +0000304
Fred Drake79ca79d2000-08-21 22:30:53 +0000305#
306# Second, we take *invalid* trees and make sure we get ParserError
307# rejections for them.
308#
309
Fred Drake58422e52001-06-04 03:56:24 +0000310class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000311
Fred Drake58422e52001-06-04 03:56:24 +0000312 def check_bad_tree(self, tree, label):
313 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000314 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000315 except parser.ParserError:
316 pass
317 else:
318 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000319
Fred Drake58422e52001-06-04 03:56:24 +0000320 def test_junk(self):
321 # not even remotely valid:
322 self.check_bad_tree((1, 2, 3), "<junk>")
323
Fred Drakecf580c72001-07-17 03:01:29 +0000324 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000325 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000326 tree = \
327 (257,
328 (264,
329 (285,
330 (259,
331 (1, 'def'),
332 (1, 'f'),
333 (260, (7, '('), (8, ')')),
334 (11, ':'),
335 (291,
336 (4, ''),
337 (5, ''),
338 (264,
339 (265,
340 (266,
341 (272,
342 (275,
343 (1, 'return'),
344 (313,
345 (292,
346 (293,
347 (294,
348 (295,
349 (297,
350 (298,
351 (299,
352 (300,
353 (301,
354 (302, (303, (304, (305, (2, '1')))))))))))))))))),
355 (264,
356 (265,
357 (266,
358 (272,
359 (276,
360 (1, 'yield'),
361 (313,
362 (292,
363 (293,
364 (294,
365 (295,
366 (297,
367 (298,
368 (299,
369 (300,
370 (301,
371 (302,
372 (303, (304, (305, (2, '1')))))))))))))))))),
373 (4, ''))),
374 (6, ''))))),
375 (4, ''),
376 (0, ''))))
377 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
378
379 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000380 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000381 tree = \
382 (257,
383 (264,
384 (265,
385 (266,
386 (278,
387 (1, 'from'),
388 (281, (1, '__future__')),
389 (1, 'import'),
390 (279, (1, 'generators')))),
391 (4, ''))),
392 (264,
393 (285,
394 (259,
395 (1, 'def'),
396 (1, 'f'),
397 (260, (7, '('), (8, ')')),
398 (11, ':'),
399 (291,
400 (4, ''),
401 (5, ''),
402 (264,
403 (265,
404 (266,
405 (272,
406 (275,
407 (1, 'return'),
408 (313,
409 (292,
410 (293,
411 (294,
412 (295,
413 (297,
414 (298,
415 (299,
416 (300,
417 (301,
418 (302, (303, (304, (305, (2, '1')))))))))))))))))),
419 (264,
420 (265,
421 (266,
422 (272,
423 (276,
424 (1, 'yield'),
425 (313,
426 (292,
427 (293,
428 (294,
429 (295,
430 (297,
431 (298,
432 (299,
433 (300,
434 (301,
435 (302,
436 (303, (304, (305, (2, '1')))))))))))))))))),
437 (4, ''))),
438 (6, ''))))),
439 (4, ''),
440 (0, ''))))
441 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
442
Fred Drake58422e52001-06-04 03:56:24 +0000443 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000444 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000445 tree = \
446 (258,
447 (311,
448 (290,
449 (291,
450 (292,
451 (293,
452 (295,
453 (296,
454 (297,
455 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
456 (12, ','),
457 (12, ','),
458 (290,
459 (291,
460 (292,
461 (293,
462 (295,
463 (296,
464 (297,
465 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
466 (4, ''),
467 (0, ''))
468 self.check_bad_tree(tree, "a,,c")
469
470 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000471 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000472 tree = \
473 (257,
474 (264,
475 (265,
476 (266,
477 (267,
478 (312,
479 (291,
480 (292,
481 (293,
482 (294,
483 (296,
484 (297,
485 (298,
486 (299,
487 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
488 (268, (37, '$=')),
489 (312,
490 (291,
491 (292,
492 (293,
493 (294,
494 (296,
495 (297,
496 (298,
497 (299,
498 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
499 (4, ''))),
500 (0, ''))
501 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000502
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000503 def test_malformed_global(self):
504 #doesn't have global keyword in ast
505 tree = (257,
506 (264,
507 (265,
508 (266,
509 (282, (1, 'foo'))), (4, ''))),
510 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000511 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000512 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000513
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000514 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000515 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000516 tree = \
517 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000518 (268,
519 (269,
520 (270,
521 (282,
522 (284, (1, 'from'), (1, 'import'),
523 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000524 (4, ''))),
525 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000526 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000527
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000528
529class CompileTestCase(unittest.TestCase):
530
531 # These tests are very minimal. :-(
532
533 def test_compile_expr(self):
534 st = parser.expr('2 + 3')
535 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000536 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000537
538 def test_compile_suite(self):
539 st = parser.suite('x = 2; y = x + 3')
540 code = parser.compilest(st)
541 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000542 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000543 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544
545 def test_compile_error(self):
546 st = parser.suite('1 = 3 + 4')
547 self.assertRaises(SyntaxError, parser.compilest, st)
548
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000549 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000550 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000551 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000552 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000553 self.assertRaises(SyntaxError, parser.compilest, st)
554
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000555 def test_issue_9011(self):
556 # Issue 9011: compilation of an unary minus expression changed
557 # the meaning of the ST, so that a second compilation produced
558 # incorrect results.
559 st = parser.expr('-3')
560 code1 = parser.compilest(st)
561 self.assertEqual(eval(code1), -3)
562 code2 = parser.compilest(st)
563 self.assertEqual(eval(code2), -3)
564
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000565class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000566 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000567 see http://bugs.python.org/issue1881 for a discussion
568 """
569 def _nested_expression(self, level):
570 return "["*level+"]"*level
571
572 def test_deeply_nested_list(self):
573 # XXX used to be 99 levels in 2.x
574 e = self._nested_expression(93)
575 st = parser.expr(e)
576 st.compile()
577
578 def test_trigger_memory_error(self):
579 e = self._nested_expression(100)
Christian Heimesb186d002008-03-18 15:15:01 +0000580 print("Expecting 's_push: parser stack overflow' in next line",
581 file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +0000582 sys.stderr.flush()
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000583 self.assertRaises(MemoryError, parser.expr, e)
584
Mark Dickinson211c6252009-02-01 10:28:51 +0000585class STObjectTestCase(unittest.TestCase):
586 """Test operations on ST objects themselves"""
587
588 def test_comparisons(self):
589 # ST objects should support order and equality comparisons
590 st1 = parser.expr('2 + 3')
591 st2 = parser.suite('x = 2; y = x + 3')
592 st3 = parser.expr('list(x**3 for x in range(20))')
593 st1_copy = parser.expr('2 + 3')
594 st2_copy = parser.suite('x = 2; y = x + 3')
595 st3_copy = parser.expr('list(x**3 for x in range(20))')
596
597 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000598 self.assertEqual(st1 == st1, True)
599 self.assertEqual(st2 == st2, True)
600 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000601 # slow path equality
602 self.assertEqual(st1, st1_copy)
603 self.assertEqual(st2, st2_copy)
604 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000605 self.assertEqual(st1 == st2, False)
606 self.assertEqual(st1 == st3, False)
607 self.assertEqual(st2 == st3, False)
608 self.assertEqual(st1 != st1, False)
609 self.assertEqual(st2 != st2, False)
610 self.assertEqual(st3 != st3, False)
611 self.assertEqual(st1 != st1_copy, False)
612 self.assertEqual(st2 != st2_copy, False)
613 self.assertEqual(st3 != st3_copy, False)
614 self.assertEqual(st2 != st1, True)
615 self.assertEqual(st1 != st3, True)
616 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000617 # we don't particularly care what the ordering is; just that
618 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000619 self.assertEqual(st1 < st2, not (st2 <= st1))
620 self.assertEqual(st1 < st3, not (st3 <= st1))
621 self.assertEqual(st2 < st3, not (st3 <= st2))
622 self.assertEqual(st1 < st2, st2 > st1)
623 self.assertEqual(st1 < st3, st3 > st1)
624 self.assertEqual(st2 < st3, st3 > st2)
625 self.assertEqual(st1 <= st2, st2 >= st1)
626 self.assertEqual(st3 <= st1, st1 >= st3)
627 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000628 # transitivity
629 bottom = min(st1, st2, st3)
630 top = max(st1, st2, st3)
631 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000632 self.assertTrue(bottom < mid)
633 self.assertTrue(bottom < top)
634 self.assertTrue(mid < top)
635 self.assertTrue(bottom <= mid)
636 self.assertTrue(bottom <= top)
637 self.assertTrue(mid <= top)
638 self.assertTrue(bottom <= bottom)
639 self.assertTrue(mid <= mid)
640 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000641 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000642 self.assertEqual(st1 == 1588.602459, False)
643 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000644 self.assertRaises(TypeError, operator.ge, st3, None)
645 self.assertRaises(TypeError, operator.le, False, st1)
646 self.assertRaises(TypeError, operator.lt, st1, 1815)
647 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
648
649
650 # XXX tests for pickling and unpickling of ST objects should go here
651
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500652class OtherParserCase(unittest.TestCase):
653
654 def test_two_args_to_expr(self):
655 # See bug #12264
656 with self.assertRaises(TypeError):
657 parser.expr("a", "b")
658
Fred Drake2e2be372001-09-20 21:33:42 +0000659def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000660 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000661 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000662 IllegalSyntaxTestCase,
663 CompileTestCase,
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000664 ParserStackLimitTestCase,
Mark Dickinson211c6252009-02-01 10:28:51 +0000665 STObjectTestCase,
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500666 OtherParserCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000667 )
Fred Drake2e2be372001-09-20 21:33:42 +0000668
669
670if __name__ == "__main__":
671 test_main()