blob: cae09dfd32f5ad6f0edd194029bc06c81797ef1c [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))")
Mark Dickinsonda029fb2012-05-07 17:24:04 +0100109 self.check_expr("...")
110 self.check_expr("a[...]")
Fred Drake79ca79d2000-08-21 22:30:53 +0000111
Fred Drake58422e52001-06-04 03:56:24 +0000112 def test_simple_expression(self):
113 # expr_stmt
114 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000115
Fred Drake58422e52001-06-04 03:56:24 +0000116 def test_simple_assignments(self):
117 self.check_suite("a = b")
118 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000119
Fred Drake58422e52001-06-04 03:56:24 +0000120 def test_simple_augmented_assignments(self):
121 self.check_suite("a += b")
122 self.check_suite("a -= b")
123 self.check_suite("a *= b")
124 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000125 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000126 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")
131 self.check_suite("a >>= b")
132 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000133
Fred Drake58422e52001-06-04 03:56:24 +0000134 def test_function_defs(self):
135 self.check_suite("def f(): pass")
136 self.check_suite("def f(*args): pass")
137 self.check_suite("def f(*args, **kw): pass")
138 self.check_suite("def f(**kw): pass")
139 self.check_suite("def f(foo=bar): pass")
140 self.check_suite("def f(foo=bar, *args): pass")
141 self.check_suite("def f(foo=bar, *args, **kw): pass")
142 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000143
Fred Drake58422e52001-06-04 03:56:24 +0000144 self.check_suite("def f(a, b): pass")
145 self.check_suite("def f(a, b, *args): pass")
146 self.check_suite("def f(a, b, *args, **kw): pass")
147 self.check_suite("def f(a, b, **kw): pass")
148 self.check_suite("def f(a, b, foo=bar): pass")
149 self.check_suite("def f(a, b, foo=bar, *args): pass")
150 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
151 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000152
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000153 self.check_suite("@staticmethod\n"
154 "def f(): pass")
155 self.check_suite("@staticmethod\n"
156 "@funcattrs(x, y)\n"
157 "def f(): pass")
158 self.check_suite("@funcattrs()\n"
159 "def f(): pass")
160
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100161 # keyword-only arguments
162 self.check_suite("def f(*, a): pass")
163 self.check_suite("def f(*, a = 5): pass")
164 self.check_suite("def f(*, a = 5, b): pass")
165 self.check_suite("def f(*, a, b = 5): pass")
166 self.check_suite("def f(*, a, b = 5, **kwds): pass")
167 self.check_suite("def f(*args, a): pass")
168 self.check_suite("def f(*args, a = 5): pass")
169 self.check_suite("def f(*args, a = 5, b): pass")
170 self.check_suite("def f(*args, a, b = 5): pass")
171 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
172
173 # function annotations
174 self.check_suite("def f(a: int): pass")
175 self.check_suite("def f(a: int = 5): pass")
176 self.check_suite("def f(*args: list): pass")
177 self.check_suite("def f(**kwds: dict): pass")
178 self.check_suite("def f(*, a: int): pass")
179 self.check_suite("def f(*, a: int = 5): pass")
180 self.check_suite("def f() -> int: pass")
181
Brett Cannonf4189912005-04-09 02:30:16 +0000182 def test_class_defs(self):
183 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000184 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000185 self.check_suite("@class_decorator\n"
186 "class foo():pass")
187 self.check_suite("@class_decorator(arg)\n"
188 "class foo():pass")
189 self.check_suite("@decorator1\n"
190 "@decorator2\n"
191 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000192
Fred Drake58422e52001-06-04 03:56:24 +0000193 def test_import_from_statement(self):
194 self.check_suite("from sys.path import *")
195 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000196 self.check_suite("from sys.path import (dirname)")
197 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000198 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000199 self.check_suite("from sys.path import (dirname as my_dirname)")
200 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000201 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000202 self.check_suite("from sys.path import (dirname, basename)")
203 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000204 self.check_suite(
205 "from sys.path import dirname as my_dirname, basename")
206 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000207 "from sys.path import (dirname as my_dirname, basename)")
208 self.check_suite(
209 "from sys.path import (dirname as my_dirname, basename,)")
210 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000211 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000212 self.check_suite(
213 "from sys.path import (dirname, basename as my_basename)")
214 self.check_suite(
215 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000216 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000217
Fred Drake58422e52001-06-04 03:56:24 +0000218 def test_basic_import_statement(self):
219 self.check_suite("import sys")
220 self.check_suite("import sys as system")
221 self.check_suite("import sys, math")
222 self.check_suite("import sys as system, math")
223 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000224
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000225 def test_relative_imports(self):
226 self.check_suite("from . import name")
227 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000228 # check all the way up to '....', since '...' is tokenized
229 # differently from '.' (it's an ellipsis token).
230 self.check_suite("from ... import name")
231 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000232 self.check_suite("from .pkg import name")
233 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000234 self.check_suite("from ...pkg import name")
235 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000236
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000237 def test_pep263(self):
238 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
239 "pass\n")
240
241 def test_assert(self):
242 self.check_suite("assert alo < ahi and blo < bhi\n")
243
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000244 def test_with(self):
245 self.check_suite("with open('x'): pass\n")
246 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000247 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000248
Georg Brandleee31162008-12-07 15:15:22 +0000249 def test_try_stmt(self):
250 self.check_suite("try: pass\nexcept: pass\n")
251 self.check_suite("try: pass\nfinally: pass\n")
252 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
253 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
254 "finally: pass\n")
255 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
256 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
257 "finally: pass\n")
258
Thomas Wouters89f507f2006-12-13 04:49:30 +0000259 def test_position(self):
260 # An absolutely minimal test of position information. Better
261 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000262 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000263 st1 = parser.suite(code)
264 st2 = st1.totuple(line_info=1, col_info=1)
265
266 def walk(tree):
267 node_type = tree[0]
268 next = tree[1]
269 if isinstance(next, tuple):
270 for elt in tree[1:]:
271 for x in walk(elt):
272 yield x
273 else:
274 yield tree
275
276 terminals = list(walk(st2))
277 self.assertEqual([
278 (1, 'def', 1, 0),
279 (1, 'f', 1, 4),
280 (7, '(', 1, 5),
281 (1, 'x', 1, 6),
282 (8, ')', 1, 7),
283 (11, ':', 1, 8),
284 (4, '', 1, 9),
285 (5, '', 2, -1),
286 (1, 'return', 2, 4),
287 (1, 'x', 2, 11),
288 (14, '+', 2, 13),
289 (2, '1', 2, 15),
290 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000291 (6, '', 2, -1),
292 (4, '', 2, -1),
293 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000294 terminals)
295
Benjamin Peterson4905e802009-09-27 02:43:28 +0000296 def test_extended_unpacking(self):
297 self.check_suite("*a = y")
298 self.check_suite("x, *b, = m")
299 self.check_suite("[*a, *b] = y")
300 self.check_suite("for [*x, b] in x: pass")
301
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100302 def test_raise_statement(self):
303 self.check_suite("raise\n")
304 self.check_suite("raise e\n")
305 self.check_suite("try:\n"
306 " suite\n"
307 "except Exception as e:\n"
308 " raise ValueError from e\n")
309
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100310 def test_set_displays(self):
311 self.check_expr('{2}')
312 self.check_expr('{2,}')
313 self.check_expr('{2, 3}')
314 self.check_expr('{2, 3,}')
315
316 def test_dict_displays(self):
317 self.check_expr('{}')
318 self.check_expr('{a:b}')
319 self.check_expr('{a:b,}')
320 self.check_expr('{a:b, c:d}')
321 self.check_expr('{a:b, c:d,}')
322
323 def test_set_comprehensions(self):
324 self.check_expr('{x for x in seq}')
325 self.check_expr('{f(x) for x in seq}')
326 self.check_expr('{f(x) for x in seq if condition(x)}')
327
328 def test_dict_comprehensions(self):
329 self.check_expr('{x:x for x in seq}')
330 self.check_expr('{x**2:x[3] for x in seq if condition(x)}')
331 self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}')
332
Thomas Wouters89f507f2006-12-13 04:49:30 +0000333
Fred Drake79ca79d2000-08-21 22:30:53 +0000334#
335# Second, we take *invalid* trees and make sure we get ParserError
336# rejections for them.
337#
338
Fred Drake58422e52001-06-04 03:56:24 +0000339class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000340
Fred Drake58422e52001-06-04 03:56:24 +0000341 def check_bad_tree(self, tree, label):
342 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000343 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000344 except parser.ParserError:
345 pass
346 else:
347 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000348
Fred Drake58422e52001-06-04 03:56:24 +0000349 def test_junk(self):
350 # not even remotely valid:
351 self.check_bad_tree((1, 2, 3), "<junk>")
352
Fred Drakecf580c72001-07-17 03:01:29 +0000353 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000354 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000355 tree = \
356 (257,
357 (264,
358 (285,
359 (259,
360 (1, 'def'),
361 (1, 'f'),
362 (260, (7, '('), (8, ')')),
363 (11, ':'),
364 (291,
365 (4, ''),
366 (5, ''),
367 (264,
368 (265,
369 (266,
370 (272,
371 (275,
372 (1, 'return'),
373 (313,
374 (292,
375 (293,
376 (294,
377 (295,
378 (297,
379 (298,
380 (299,
381 (300,
382 (301,
383 (302, (303, (304, (305, (2, '1')))))))))))))))))),
384 (264,
385 (265,
386 (266,
387 (272,
388 (276,
389 (1, 'yield'),
390 (313,
391 (292,
392 (293,
393 (294,
394 (295,
395 (297,
396 (298,
397 (299,
398 (300,
399 (301,
400 (302,
401 (303, (304, (305, (2, '1')))))))))))))))))),
402 (4, ''))),
403 (6, ''))))),
404 (4, ''),
405 (0, ''))))
406 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
407
408 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000409 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000410 tree = \
411 (257,
412 (264,
413 (265,
414 (266,
415 (278,
416 (1, 'from'),
417 (281, (1, '__future__')),
418 (1, 'import'),
419 (279, (1, 'generators')))),
420 (4, ''))),
421 (264,
422 (285,
423 (259,
424 (1, 'def'),
425 (1, 'f'),
426 (260, (7, '('), (8, ')')),
427 (11, ':'),
428 (291,
429 (4, ''),
430 (5, ''),
431 (264,
432 (265,
433 (266,
434 (272,
435 (275,
436 (1, 'return'),
437 (313,
438 (292,
439 (293,
440 (294,
441 (295,
442 (297,
443 (298,
444 (299,
445 (300,
446 (301,
447 (302, (303, (304, (305, (2, '1')))))))))))))))))),
448 (264,
449 (265,
450 (266,
451 (272,
452 (276,
453 (1, 'yield'),
454 (313,
455 (292,
456 (293,
457 (294,
458 (295,
459 (297,
460 (298,
461 (299,
462 (300,
463 (301,
464 (302,
465 (303, (304, (305, (2, '1')))))))))))))))))),
466 (4, ''))),
467 (6, ''))))),
468 (4, ''),
469 (0, ''))))
470 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
471
Fred Drake58422e52001-06-04 03:56:24 +0000472 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000473 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000474 tree = \
475 (258,
476 (311,
477 (290,
478 (291,
479 (292,
480 (293,
481 (295,
482 (296,
483 (297,
484 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
485 (12, ','),
486 (12, ','),
487 (290,
488 (291,
489 (292,
490 (293,
491 (295,
492 (296,
493 (297,
494 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
495 (4, ''),
496 (0, ''))
497 self.check_bad_tree(tree, "a,,c")
498
499 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000500 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000501 tree = \
502 (257,
503 (264,
504 (265,
505 (266,
506 (267,
507 (312,
508 (291,
509 (292,
510 (293,
511 (294,
512 (296,
513 (297,
514 (298,
515 (299,
516 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
517 (268, (37, '$=')),
518 (312,
519 (291,
520 (292,
521 (293,
522 (294,
523 (296,
524 (297,
525 (298,
526 (299,
527 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
528 (4, ''))),
529 (0, ''))
530 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000531
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000532 def test_malformed_global(self):
533 #doesn't have global keyword in ast
534 tree = (257,
535 (264,
536 (265,
537 (266,
538 (282, (1, 'foo'))), (4, ''))),
539 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000540 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000541 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000542
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000543 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000544 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000545 tree = \
546 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000547 (268,
548 (269,
549 (270,
550 (282,
551 (284, (1, 'from'), (1, 'import'),
552 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000553 (4, ''))),
554 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000555 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000556
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000557
558class CompileTestCase(unittest.TestCase):
559
560 # These tests are very minimal. :-(
561
562 def test_compile_expr(self):
563 st = parser.expr('2 + 3')
564 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000565 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000566
567 def test_compile_suite(self):
568 st = parser.suite('x = 2; y = x + 3')
569 code = parser.compilest(st)
570 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000571 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000572 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000573
574 def test_compile_error(self):
575 st = parser.suite('1 = 3 + 4')
576 self.assertRaises(SyntaxError, parser.compilest, st)
577
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000578 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000579 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000580 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000581 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000582 self.assertRaises(SyntaxError, parser.compilest, st)
583
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000584 def test_issue_9011(self):
585 # Issue 9011: compilation of an unary minus expression changed
586 # the meaning of the ST, so that a second compilation produced
587 # incorrect results.
588 st = parser.expr('-3')
589 code1 = parser.compilest(st)
590 self.assertEqual(eval(code1), -3)
591 code2 = parser.compilest(st)
592 self.assertEqual(eval(code2), -3)
593
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000594class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000595 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000596 see http://bugs.python.org/issue1881 for a discussion
597 """
598 def _nested_expression(self, level):
599 return "["*level+"]"*level
600
601 def test_deeply_nested_list(self):
602 # XXX used to be 99 levels in 2.x
603 e = self._nested_expression(93)
604 st = parser.expr(e)
605 st.compile()
606
607 def test_trigger_memory_error(self):
608 e = self._nested_expression(100)
Christian Heimesb186d002008-03-18 15:15:01 +0000609 print("Expecting 's_push: parser stack overflow' in next line",
610 file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +0000611 sys.stderr.flush()
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000612 self.assertRaises(MemoryError, parser.expr, e)
613
Mark Dickinson211c6252009-02-01 10:28:51 +0000614class STObjectTestCase(unittest.TestCase):
615 """Test operations on ST objects themselves"""
616
617 def test_comparisons(self):
618 # ST objects should support order and equality comparisons
619 st1 = parser.expr('2 + 3')
620 st2 = parser.suite('x = 2; y = x + 3')
621 st3 = parser.expr('list(x**3 for x in range(20))')
622 st1_copy = parser.expr('2 + 3')
623 st2_copy = parser.suite('x = 2; y = x + 3')
624 st3_copy = parser.expr('list(x**3 for x in range(20))')
625
626 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000627 self.assertEqual(st1 == st1, True)
628 self.assertEqual(st2 == st2, True)
629 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000630 # slow path equality
631 self.assertEqual(st1, st1_copy)
632 self.assertEqual(st2, st2_copy)
633 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000634 self.assertEqual(st1 == st2, False)
635 self.assertEqual(st1 == st3, False)
636 self.assertEqual(st2 == st3, False)
637 self.assertEqual(st1 != st1, False)
638 self.assertEqual(st2 != st2, False)
639 self.assertEqual(st3 != st3, False)
640 self.assertEqual(st1 != st1_copy, False)
641 self.assertEqual(st2 != st2_copy, False)
642 self.assertEqual(st3 != st3_copy, False)
643 self.assertEqual(st2 != st1, True)
644 self.assertEqual(st1 != st3, True)
645 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000646 # we don't particularly care what the ordering is; just that
647 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000648 self.assertEqual(st1 < st2, not (st2 <= st1))
649 self.assertEqual(st1 < st3, not (st3 <= st1))
650 self.assertEqual(st2 < st3, not (st3 <= st2))
651 self.assertEqual(st1 < st2, st2 > st1)
652 self.assertEqual(st1 < st3, st3 > st1)
653 self.assertEqual(st2 < st3, st3 > st2)
654 self.assertEqual(st1 <= st2, st2 >= st1)
655 self.assertEqual(st3 <= st1, st1 >= st3)
656 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000657 # transitivity
658 bottom = min(st1, st2, st3)
659 top = max(st1, st2, st3)
660 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000661 self.assertTrue(bottom < mid)
662 self.assertTrue(bottom < top)
663 self.assertTrue(mid < top)
664 self.assertTrue(bottom <= mid)
665 self.assertTrue(bottom <= top)
666 self.assertTrue(mid <= top)
667 self.assertTrue(bottom <= bottom)
668 self.assertTrue(mid <= mid)
669 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000670 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000671 self.assertEqual(st1 == 1588.602459, False)
672 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000673 self.assertRaises(TypeError, operator.ge, st3, None)
674 self.assertRaises(TypeError, operator.le, False, st1)
675 self.assertRaises(TypeError, operator.lt, st1, 1815)
676 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
677
678
679 # XXX tests for pickling and unpickling of ST objects should go here
680
681
Fred Drake2e2be372001-09-20 21:33:42 +0000682def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000683 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000684 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000685 IllegalSyntaxTestCase,
686 CompileTestCase,
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000687 ParserStackLimitTestCase,
Mark Dickinson211c6252009-02-01 10:28:51 +0000688 STObjectTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000689 )
Fred Drake2e2be372001-09-20 21:33:42 +0000690
691
692if __name__ == "__main__":
693 test_main()