blob: edd1a0947570f60fe8855423c3ba7f2d55a5e660 [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")
53 self.check_suite("def f():\n"
Fred Drakecf580c72001-07-17 03:01:29 +000054 " for x in range(30):\n"
55 " yield x\n")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000056 self.check_suite("def f():\n"
57 " if (yield):\n"
58 " yield x\n")
Fred Drakecf580c72001-07-17 03:01:29 +000059
Mark Dickinson407b3bd2012-04-29 22:18:31 +010060 def test_nonlocal_statement(self):
61 self.check_suite("def f():\n"
62 " x = 0\n"
63 " def g():\n"
64 " nonlocal x\n")
65 self.check_suite("def f():\n"
66 " x = y = 0\n"
67 " def g():\n"
68 " nonlocal x, y\n")
69
Fred Drake58422e52001-06-04 03:56:24 +000070 def test_expressions(self):
71 self.check_expr("foo(1)")
72 self.check_expr("[1, 2, 3]")
73 self.check_expr("[x**3 for x in range(20)]")
74 self.check_expr("[x**3 for x in range(20) if x % 3]")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000075 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
76 self.check_expr("list(x**3 for x in range(20))")
77 self.check_expr("list(x**3 for x in range(20) if x % 3)")
78 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Fred Drake58422e52001-06-04 03:56:24 +000079 self.check_expr("foo(*args)")
80 self.check_expr("foo(*args, **kw)")
81 self.check_expr("foo(**kw)")
82 self.check_expr("foo(key=value)")
83 self.check_expr("foo(key=value, *args)")
84 self.check_expr("foo(key=value, *args, **kw)")
85 self.check_expr("foo(key=value, **kw)")
86 self.check_expr("foo(a, b, c, *args)")
87 self.check_expr("foo(a, b, c, *args, **kw)")
88 self.check_expr("foo(a, b, c, **kw)")
Benjamin Peterson3938a902008-08-20 02:33:00 +000089 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +000090 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +000091 self.check_expr("foo - bar")
92 self.check_expr("foo * bar")
93 self.check_expr("foo / bar")
94 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +000095 self.check_expr("lambda: 0")
96 self.check_expr("lambda x: 0")
97 self.check_expr("lambda *y: 0")
98 self.check_expr("lambda *y, **z: 0")
99 self.check_expr("lambda **z: 0")
100 self.check_expr("lambda x, y: 0")
101 self.check_expr("lambda foo=bar: 0")
102 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
103 self.check_expr("lambda foo=bar, **z: 0")
104 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
105 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
106 self.check_expr("lambda x, *y, **z: 0")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000107 self.check_expr("(x for x in range(10))")
108 self.check_expr("foo(x for x in range(10))")
Fred Drake79ca79d2000-08-21 22:30:53 +0000109
Fred Drake58422e52001-06-04 03:56:24 +0000110 def test_simple_expression(self):
111 # expr_stmt
112 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000113
Fred Drake58422e52001-06-04 03:56:24 +0000114 def test_simple_assignments(self):
115 self.check_suite("a = b")
116 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000117
Fred Drake58422e52001-06-04 03:56:24 +0000118 def test_simple_augmented_assignments(self):
119 self.check_suite("a += b")
120 self.check_suite("a -= b")
121 self.check_suite("a *= b")
122 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000123 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000124 self.check_suite("a %= b")
125 self.check_suite("a &= b")
126 self.check_suite("a |= b")
127 self.check_suite("a ^= b")
128 self.check_suite("a <<= b")
129 self.check_suite("a >>= b")
130 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000131
Fred Drake58422e52001-06-04 03:56:24 +0000132 def test_function_defs(self):
133 self.check_suite("def f(): pass")
134 self.check_suite("def f(*args): pass")
135 self.check_suite("def f(*args, **kw): pass")
136 self.check_suite("def f(**kw): pass")
137 self.check_suite("def f(foo=bar): pass")
138 self.check_suite("def f(foo=bar, *args): pass")
139 self.check_suite("def f(foo=bar, *args, **kw): pass")
140 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000141
Fred Drake58422e52001-06-04 03:56:24 +0000142 self.check_suite("def f(a, b): pass")
143 self.check_suite("def f(a, b, *args): pass")
144 self.check_suite("def f(a, b, *args, **kw): pass")
145 self.check_suite("def f(a, b, **kw): pass")
146 self.check_suite("def f(a, b, foo=bar): pass")
147 self.check_suite("def f(a, b, foo=bar, *args): pass")
148 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
149 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000150
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000151 self.check_suite("@staticmethod\n"
152 "def f(): pass")
153 self.check_suite("@staticmethod\n"
154 "@funcattrs(x, y)\n"
155 "def f(): pass")
156 self.check_suite("@funcattrs()\n"
157 "def f(): pass")
158
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100159 # keyword-only arguments
160 self.check_suite("def f(*, a): pass")
161 self.check_suite("def f(*, a = 5): pass")
162 self.check_suite("def f(*, a = 5, b): pass")
163 self.check_suite("def f(*, a, b = 5): pass")
164 self.check_suite("def f(*, a, b = 5, **kwds): pass")
165 self.check_suite("def f(*args, a): pass")
166 self.check_suite("def f(*args, a = 5): pass")
167 self.check_suite("def f(*args, a = 5, b): pass")
168 self.check_suite("def f(*args, a, b = 5): pass")
169 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
170
171 # function annotations
172 self.check_suite("def f(a: int): pass")
173 self.check_suite("def f(a: int = 5): pass")
174 self.check_suite("def f(*args: list): pass")
175 self.check_suite("def f(**kwds: dict): pass")
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() -> int: pass")
179
Brett Cannonf4189912005-04-09 02:30:16 +0000180 def test_class_defs(self):
181 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000182 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000183 self.check_suite("@class_decorator\n"
184 "class foo():pass")
185 self.check_suite("@class_decorator(arg)\n"
186 "class foo():pass")
187 self.check_suite("@decorator1\n"
188 "@decorator2\n"
189 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000190
Fred Drake58422e52001-06-04 03:56:24 +0000191 def test_import_from_statement(self):
192 self.check_suite("from sys.path import *")
193 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000194 self.check_suite("from sys.path import (dirname)")
195 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000196 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000197 self.check_suite("from sys.path import (dirname as my_dirname)")
198 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000199 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000200 self.check_suite("from sys.path import (dirname, basename)")
201 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000202 self.check_suite(
203 "from sys.path import dirname as my_dirname, basename")
204 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000205 "from sys.path import (dirname as my_dirname, basename)")
206 self.check_suite(
207 "from sys.path import (dirname as my_dirname, basename,)")
208 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000209 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000210 self.check_suite(
211 "from sys.path import (dirname, basename as my_basename)")
212 self.check_suite(
213 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000214 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000215
Fred Drake58422e52001-06-04 03:56:24 +0000216 def test_basic_import_statement(self):
217 self.check_suite("import sys")
218 self.check_suite("import sys as system")
219 self.check_suite("import sys, math")
220 self.check_suite("import sys as system, math")
221 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000222
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000223 def test_relative_imports(self):
224 self.check_suite("from . import name")
225 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000226 # check all the way up to '....', since '...' is tokenized
227 # differently from '.' (it's an ellipsis token).
228 self.check_suite("from ... import name")
229 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000230 self.check_suite("from .pkg import name")
231 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000232 self.check_suite("from ...pkg import name")
233 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000234
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000235 def test_pep263(self):
236 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
237 "pass\n")
238
239 def test_assert(self):
240 self.check_suite("assert alo < ahi and blo < bhi\n")
241
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000242 def test_with(self):
243 self.check_suite("with open('x'): pass\n")
244 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000245 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000246
Georg Brandleee31162008-12-07 15:15:22 +0000247 def test_try_stmt(self):
248 self.check_suite("try: pass\nexcept: pass\n")
249 self.check_suite("try: pass\nfinally: pass\n")
250 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
251 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
252 "finally: pass\n")
253 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
254 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
255 "finally: pass\n")
256
Thomas Wouters89f507f2006-12-13 04:49:30 +0000257 def test_position(self):
258 # An absolutely minimal test of position information. Better
259 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000260 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000261 st1 = parser.suite(code)
262 st2 = st1.totuple(line_info=1, col_info=1)
263
264 def walk(tree):
265 node_type = tree[0]
266 next = tree[1]
267 if isinstance(next, tuple):
268 for elt in tree[1:]:
269 for x in walk(elt):
270 yield x
271 else:
272 yield tree
273
274 terminals = list(walk(st2))
275 self.assertEqual([
276 (1, 'def', 1, 0),
277 (1, 'f', 1, 4),
278 (7, '(', 1, 5),
279 (1, 'x', 1, 6),
280 (8, ')', 1, 7),
281 (11, ':', 1, 8),
282 (4, '', 1, 9),
283 (5, '', 2, -1),
284 (1, 'return', 2, 4),
285 (1, 'x', 2, 11),
286 (14, '+', 2, 13),
287 (2, '1', 2, 15),
288 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000289 (6, '', 2, -1),
290 (4, '', 2, -1),
291 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000292 terminals)
293
Benjamin Peterson4905e802009-09-27 02:43:28 +0000294 def test_extended_unpacking(self):
295 self.check_suite("*a = y")
296 self.check_suite("x, *b, = m")
297 self.check_suite("[*a, *b] = y")
298 self.check_suite("for [*x, b] in x: pass")
299
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100300 def test_raise_statement(self):
301 self.check_suite("raise\n")
302 self.check_suite("raise e\n")
303 self.check_suite("try:\n"
304 " suite\n"
305 "except Exception as e:\n"
306 " raise ValueError from e\n")
307
Thomas Wouters89f507f2006-12-13 04:49:30 +0000308
Fred Drake79ca79d2000-08-21 22:30:53 +0000309#
310# Second, we take *invalid* trees and make sure we get ParserError
311# rejections for them.
312#
313
Fred Drake58422e52001-06-04 03:56:24 +0000314class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000315
Fred Drake58422e52001-06-04 03:56:24 +0000316 def check_bad_tree(self, tree, label):
317 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000318 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000319 except parser.ParserError:
320 pass
321 else:
322 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000323
Fred Drake58422e52001-06-04 03:56:24 +0000324 def test_junk(self):
325 # not even remotely valid:
326 self.check_bad_tree((1, 2, 3), "<junk>")
327
Fred Drakecf580c72001-07-17 03:01:29 +0000328 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000329 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000330 tree = \
331 (257,
332 (264,
333 (285,
334 (259,
335 (1, 'def'),
336 (1, 'f'),
337 (260, (7, '('), (8, ')')),
338 (11, ':'),
339 (291,
340 (4, ''),
341 (5, ''),
342 (264,
343 (265,
344 (266,
345 (272,
346 (275,
347 (1, 'return'),
348 (313,
349 (292,
350 (293,
351 (294,
352 (295,
353 (297,
354 (298,
355 (299,
356 (300,
357 (301,
358 (302, (303, (304, (305, (2, '1')))))))))))))))))),
359 (264,
360 (265,
361 (266,
362 (272,
363 (276,
364 (1, 'yield'),
365 (313,
366 (292,
367 (293,
368 (294,
369 (295,
370 (297,
371 (298,
372 (299,
373 (300,
374 (301,
375 (302,
376 (303, (304, (305, (2, '1')))))))))))))))))),
377 (4, ''))),
378 (6, ''))))),
379 (4, ''),
380 (0, ''))))
381 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
382
383 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000384 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000385 tree = \
386 (257,
387 (264,
388 (265,
389 (266,
390 (278,
391 (1, 'from'),
392 (281, (1, '__future__')),
393 (1, 'import'),
394 (279, (1, 'generators')))),
395 (4, ''))),
396 (264,
397 (285,
398 (259,
399 (1, 'def'),
400 (1, 'f'),
401 (260, (7, '('), (8, ')')),
402 (11, ':'),
403 (291,
404 (4, ''),
405 (5, ''),
406 (264,
407 (265,
408 (266,
409 (272,
410 (275,
411 (1, 'return'),
412 (313,
413 (292,
414 (293,
415 (294,
416 (295,
417 (297,
418 (298,
419 (299,
420 (300,
421 (301,
422 (302, (303, (304, (305, (2, '1')))))))))))))))))),
423 (264,
424 (265,
425 (266,
426 (272,
427 (276,
428 (1, 'yield'),
429 (313,
430 (292,
431 (293,
432 (294,
433 (295,
434 (297,
435 (298,
436 (299,
437 (300,
438 (301,
439 (302,
440 (303, (304, (305, (2, '1')))))))))))))))))),
441 (4, ''))),
442 (6, ''))))),
443 (4, ''),
444 (0, ''))))
445 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
446
Fred Drake58422e52001-06-04 03:56:24 +0000447 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000448 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000449 tree = \
450 (258,
451 (311,
452 (290,
453 (291,
454 (292,
455 (293,
456 (295,
457 (296,
458 (297,
459 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
460 (12, ','),
461 (12, ','),
462 (290,
463 (291,
464 (292,
465 (293,
466 (295,
467 (296,
468 (297,
469 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
470 (4, ''),
471 (0, ''))
472 self.check_bad_tree(tree, "a,,c")
473
474 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000475 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000476 tree = \
477 (257,
478 (264,
479 (265,
480 (266,
481 (267,
482 (312,
483 (291,
484 (292,
485 (293,
486 (294,
487 (296,
488 (297,
489 (298,
490 (299,
491 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
492 (268, (37, '$=')),
493 (312,
494 (291,
495 (292,
496 (293,
497 (294,
498 (296,
499 (297,
500 (298,
501 (299,
502 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
503 (4, ''))),
504 (0, ''))
505 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000506
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000507 def test_malformed_global(self):
508 #doesn't have global keyword in ast
509 tree = (257,
510 (264,
511 (265,
512 (266,
513 (282, (1, 'foo'))), (4, ''))),
514 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000515 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000516 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000517
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000518 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000519 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000520 tree = \
521 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000522 (268,
523 (269,
524 (270,
525 (282,
526 (284, (1, 'from'), (1, 'import'),
527 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000528 (4, ''))),
529 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000530 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000531
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000532
533class CompileTestCase(unittest.TestCase):
534
535 # These tests are very minimal. :-(
536
537 def test_compile_expr(self):
538 st = parser.expr('2 + 3')
539 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000540 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000541
542 def test_compile_suite(self):
543 st = parser.suite('x = 2; y = x + 3')
544 code = parser.compilest(st)
545 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000546 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000547 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000548
549 def test_compile_error(self):
550 st = parser.suite('1 = 3 + 4')
551 self.assertRaises(SyntaxError, parser.compilest, st)
552
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000553 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000554 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000555 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000556 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000557 self.assertRaises(SyntaxError, parser.compilest, st)
558
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000559 def test_issue_9011(self):
560 # Issue 9011: compilation of an unary minus expression changed
561 # the meaning of the ST, so that a second compilation produced
562 # incorrect results.
563 st = parser.expr('-3')
564 code1 = parser.compilest(st)
565 self.assertEqual(eval(code1), -3)
566 code2 = parser.compilest(st)
567 self.assertEqual(eval(code2), -3)
568
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000569class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000570 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000571 see http://bugs.python.org/issue1881 for a discussion
572 """
573 def _nested_expression(self, level):
574 return "["*level+"]"*level
575
576 def test_deeply_nested_list(self):
577 # XXX used to be 99 levels in 2.x
578 e = self._nested_expression(93)
579 st = parser.expr(e)
580 st.compile()
581
582 def test_trigger_memory_error(self):
583 e = self._nested_expression(100)
Christian Heimesb186d002008-03-18 15:15:01 +0000584 print("Expecting 's_push: parser stack overflow' in next line",
585 file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +0000586 sys.stderr.flush()
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000587 self.assertRaises(MemoryError, parser.expr, e)
588
Mark Dickinson211c6252009-02-01 10:28:51 +0000589class STObjectTestCase(unittest.TestCase):
590 """Test operations on ST objects themselves"""
591
592 def test_comparisons(self):
593 # ST objects should support order and equality comparisons
594 st1 = parser.expr('2 + 3')
595 st2 = parser.suite('x = 2; y = x + 3')
596 st3 = parser.expr('list(x**3 for x in range(20))')
597 st1_copy = parser.expr('2 + 3')
598 st2_copy = parser.suite('x = 2; y = x + 3')
599 st3_copy = parser.expr('list(x**3 for x in range(20))')
600
601 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000602 self.assertEqual(st1 == st1, True)
603 self.assertEqual(st2 == st2, True)
604 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000605 # slow path equality
606 self.assertEqual(st1, st1_copy)
607 self.assertEqual(st2, st2_copy)
608 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000609 self.assertEqual(st1 == st2, False)
610 self.assertEqual(st1 == st3, False)
611 self.assertEqual(st2 == st3, False)
612 self.assertEqual(st1 != st1, False)
613 self.assertEqual(st2 != st2, False)
614 self.assertEqual(st3 != st3, False)
615 self.assertEqual(st1 != st1_copy, False)
616 self.assertEqual(st2 != st2_copy, False)
617 self.assertEqual(st3 != st3_copy, False)
618 self.assertEqual(st2 != st1, True)
619 self.assertEqual(st1 != st3, True)
620 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000621 # we don't particularly care what the ordering is; just that
622 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000623 self.assertEqual(st1 < st2, not (st2 <= st1))
624 self.assertEqual(st1 < st3, not (st3 <= st1))
625 self.assertEqual(st2 < st3, not (st3 <= st2))
626 self.assertEqual(st1 < st2, st2 > st1)
627 self.assertEqual(st1 < st3, st3 > st1)
628 self.assertEqual(st2 < st3, st3 > st2)
629 self.assertEqual(st1 <= st2, st2 >= st1)
630 self.assertEqual(st3 <= st1, st1 >= st3)
631 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000632 # transitivity
633 bottom = min(st1, st2, st3)
634 top = max(st1, st2, st3)
635 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000636 self.assertTrue(bottom < mid)
637 self.assertTrue(bottom < top)
638 self.assertTrue(mid < top)
639 self.assertTrue(bottom <= mid)
640 self.assertTrue(bottom <= top)
641 self.assertTrue(mid <= top)
642 self.assertTrue(bottom <= bottom)
643 self.assertTrue(mid <= mid)
644 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000645 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000646 self.assertEqual(st1 == 1588.602459, False)
647 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000648 self.assertRaises(TypeError, operator.ge, st3, None)
649 self.assertRaises(TypeError, operator.le, False, st1)
650 self.assertRaises(TypeError, operator.lt, st1, 1815)
651 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
652
653
654 # XXX tests for pickling and unpickling of ST objects should go here
655
656
Fred Drake2e2be372001-09-20 21:33:42 +0000657def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000658 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000659 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000660 IllegalSyntaxTestCase,
661 CompileTestCase,
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000662 ParserStackLimitTestCase,
Mark Dickinson211c6252009-02-01 10:28:51 +0000663 STObjectTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000664 )
Fred Drake2e2be372001-09-20 21:33:42 +0000665
666
667if __name__ == "__main__":
668 test_main()