blob: e199728bc08524749374abd2cf82a97857045e2f [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))")
Mark Dickinsonda029fb2012-05-07 17:24:04 +0100113 self.check_expr("...")
114 self.check_expr("a[...]")
Fred Drake79ca79d2000-08-21 22:30:53 +0000115
Fred Drake58422e52001-06-04 03:56:24 +0000116 def test_simple_expression(self):
117 # expr_stmt
118 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000119
Fred Drake58422e52001-06-04 03:56:24 +0000120 def test_simple_assignments(self):
121 self.check_suite("a = b")
122 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000123
Fred Drake58422e52001-06-04 03:56:24 +0000124 def test_simple_augmented_assignments(self):
125 self.check_suite("a += b")
126 self.check_suite("a -= b")
127 self.check_suite("a *= b")
128 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000129 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000130 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")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000137
Fred Drake58422e52001-06-04 03:56:24 +0000138 def test_function_defs(self):
139 self.check_suite("def f(): pass")
140 self.check_suite("def f(*args): pass")
141 self.check_suite("def f(*args, **kw): pass")
142 self.check_suite("def f(**kw): pass")
143 self.check_suite("def f(foo=bar): pass")
144 self.check_suite("def f(foo=bar, *args): pass")
145 self.check_suite("def f(foo=bar, *args, **kw): pass")
146 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000147
Fred Drake58422e52001-06-04 03:56:24 +0000148 self.check_suite("def f(a, b): pass")
149 self.check_suite("def f(a, b, *args): pass")
150 self.check_suite("def f(a, b, *args, **kw): pass")
151 self.check_suite("def f(a, b, **kw): pass")
152 self.check_suite("def f(a, b, foo=bar): pass")
153 self.check_suite("def f(a, b, foo=bar, *args): pass")
154 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
155 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000156
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000157 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
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100165 # keyword-only arguments
166 self.check_suite("def f(*, a): pass")
167 self.check_suite("def f(*, a = 5): pass")
168 self.check_suite("def f(*, a = 5, b): pass")
169 self.check_suite("def f(*, a, b = 5): pass")
170 self.check_suite("def f(*, a, b = 5, **kwds): pass")
171 self.check_suite("def f(*args, a): pass")
172 self.check_suite("def f(*args, a = 5): pass")
173 self.check_suite("def f(*args, a = 5, b): pass")
174 self.check_suite("def f(*args, a, b = 5): pass")
175 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
176
177 # function annotations
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(*args: list): pass")
181 self.check_suite("def f(**kwds: dict): pass")
182 self.check_suite("def f(*, a: int): pass")
183 self.check_suite("def f(*, a: int = 5): pass")
184 self.check_suite("def f() -> int: pass")
185
Brett Cannonf4189912005-04-09 02:30:16 +0000186 def test_class_defs(self):
187 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000188 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000189 self.check_suite("@class_decorator\n"
190 "class foo():pass")
191 self.check_suite("@class_decorator(arg)\n"
192 "class foo():pass")
193 self.check_suite("@decorator1\n"
194 "@decorator2\n"
195 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000196
Fred Drake58422e52001-06-04 03:56:24 +0000197 def test_import_from_statement(self):
198 self.check_suite("from sys.path import *")
199 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000200 self.check_suite("from sys.path import (dirname)")
201 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000202 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000203 self.check_suite("from sys.path import (dirname as my_dirname)")
204 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000205 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000206 self.check_suite("from sys.path import (dirname, basename)")
207 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000208 self.check_suite(
209 "from sys.path import dirname as my_dirname, basename")
210 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000211 "from sys.path import (dirname as my_dirname, basename)")
212 self.check_suite(
213 "from sys.path import (dirname as my_dirname, basename,)")
214 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000215 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000216 self.check_suite(
217 "from sys.path import (dirname, basename as my_basename)")
218 self.check_suite(
219 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000220 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000221
Fred Drake58422e52001-06-04 03:56:24 +0000222 def test_basic_import_statement(self):
223 self.check_suite("import sys")
224 self.check_suite("import sys as system")
225 self.check_suite("import sys, math")
226 self.check_suite("import sys as system, math")
227 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000228
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000229 def test_relative_imports(self):
230 self.check_suite("from . import name")
231 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000232 # check all the way up to '....', since '...' is tokenized
233 # differently from '.' (it's an ellipsis token).
234 self.check_suite("from ... import name")
235 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000236 self.check_suite("from .pkg import name")
237 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000238 self.check_suite("from ...pkg import name")
239 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000240
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000241 def test_pep263(self):
242 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
243 "pass\n")
244
245 def test_assert(self):
246 self.check_suite("assert alo < ahi and blo < bhi\n")
247
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000248 def test_with(self):
249 self.check_suite("with open('x'): pass\n")
250 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000251 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000252
Georg Brandleee31162008-12-07 15:15:22 +0000253 def test_try_stmt(self):
254 self.check_suite("try: pass\nexcept: pass\n")
255 self.check_suite("try: pass\nfinally: pass\n")
256 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
257 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
258 "finally: pass\n")
259 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
260 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
261 "finally: pass\n")
262
Thomas Wouters89f507f2006-12-13 04:49:30 +0000263 def test_position(self):
264 # An absolutely minimal test of position information. Better
265 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000266 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000267 st1 = parser.suite(code)
268 st2 = st1.totuple(line_info=1, col_info=1)
269
270 def walk(tree):
271 node_type = tree[0]
272 next = tree[1]
273 if isinstance(next, tuple):
274 for elt in tree[1:]:
275 for x in walk(elt):
276 yield x
277 else:
278 yield tree
279
280 terminals = list(walk(st2))
281 self.assertEqual([
282 (1, 'def', 1, 0),
283 (1, 'f', 1, 4),
284 (7, '(', 1, 5),
285 (1, 'x', 1, 6),
286 (8, ')', 1, 7),
287 (11, ':', 1, 8),
288 (4, '', 1, 9),
289 (5, '', 2, -1),
290 (1, 'return', 2, 4),
291 (1, 'x', 2, 11),
292 (14, '+', 2, 13),
293 (2, '1', 2, 15),
294 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000295 (6, '', 2, -1),
296 (4, '', 2, -1),
297 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000298 terminals)
299
Benjamin Peterson4905e802009-09-27 02:43:28 +0000300 def test_extended_unpacking(self):
301 self.check_suite("*a = y")
302 self.check_suite("x, *b, = m")
303 self.check_suite("[*a, *b] = y")
304 self.check_suite("for [*x, b] in x: pass")
305
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100306 def test_raise_statement(self):
307 self.check_suite("raise\n")
308 self.check_suite("raise e\n")
309 self.check_suite("try:\n"
310 " suite\n"
311 "except Exception as e:\n"
312 " raise ValueError from e\n")
313
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100314 def test_set_displays(self):
315 self.check_expr('{2}')
316 self.check_expr('{2,}')
317 self.check_expr('{2, 3}')
318 self.check_expr('{2, 3,}')
319
320 def test_dict_displays(self):
321 self.check_expr('{}')
322 self.check_expr('{a:b}')
323 self.check_expr('{a:b,}')
324 self.check_expr('{a:b, c:d}')
325 self.check_expr('{a:b, c:d,}')
326
327 def test_set_comprehensions(self):
328 self.check_expr('{x for x in seq}')
329 self.check_expr('{f(x) for x in seq}')
330 self.check_expr('{f(x) for x in seq if condition(x)}')
331
332 def test_dict_comprehensions(self):
333 self.check_expr('{x:x for x in seq}')
334 self.check_expr('{x**2:x[3] for x in seq if condition(x)}')
335 self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}')
336
Thomas Wouters89f507f2006-12-13 04:49:30 +0000337
Fred Drake79ca79d2000-08-21 22:30:53 +0000338#
339# Second, we take *invalid* trees and make sure we get ParserError
340# rejections for them.
341#
342
Fred Drake58422e52001-06-04 03:56:24 +0000343class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000344
Fred Drake58422e52001-06-04 03:56:24 +0000345 def check_bad_tree(self, tree, label):
346 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000347 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000348 except parser.ParserError:
349 pass
350 else:
351 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000352
Fred Drake58422e52001-06-04 03:56:24 +0000353 def test_junk(self):
354 # not even remotely valid:
355 self.check_bad_tree((1, 2, 3), "<junk>")
356
Fred Drakecf580c72001-07-17 03:01:29 +0000357 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000358 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000359 tree = \
360 (257,
361 (264,
362 (285,
363 (259,
364 (1, 'def'),
365 (1, 'f'),
366 (260, (7, '('), (8, ')')),
367 (11, ':'),
368 (291,
369 (4, ''),
370 (5, ''),
371 (264,
372 (265,
373 (266,
374 (272,
375 (275,
376 (1, 'return'),
377 (313,
378 (292,
379 (293,
380 (294,
381 (295,
382 (297,
383 (298,
384 (299,
385 (300,
386 (301,
387 (302, (303, (304, (305, (2, '1')))))))))))))))))),
388 (264,
389 (265,
390 (266,
391 (272,
392 (276,
393 (1, 'yield'),
394 (313,
395 (292,
396 (293,
397 (294,
398 (295,
399 (297,
400 (298,
401 (299,
402 (300,
403 (301,
404 (302,
405 (303, (304, (305, (2, '1')))))))))))))))))),
406 (4, ''))),
407 (6, ''))))),
408 (4, ''),
409 (0, ''))))
410 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
411
412 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000413 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000414 tree = \
415 (257,
416 (264,
417 (265,
418 (266,
419 (278,
420 (1, 'from'),
421 (281, (1, '__future__')),
422 (1, 'import'),
423 (279, (1, 'generators')))),
424 (4, ''))),
425 (264,
426 (285,
427 (259,
428 (1, 'def'),
429 (1, 'f'),
430 (260, (7, '('), (8, ')')),
431 (11, ':'),
432 (291,
433 (4, ''),
434 (5, ''),
435 (264,
436 (265,
437 (266,
438 (272,
439 (275,
440 (1, 'return'),
441 (313,
442 (292,
443 (293,
444 (294,
445 (295,
446 (297,
447 (298,
448 (299,
449 (300,
450 (301,
451 (302, (303, (304, (305, (2, '1')))))))))))))))))),
452 (264,
453 (265,
454 (266,
455 (272,
456 (276,
457 (1, 'yield'),
458 (313,
459 (292,
460 (293,
461 (294,
462 (295,
463 (297,
464 (298,
465 (299,
466 (300,
467 (301,
468 (302,
469 (303, (304, (305, (2, '1')))))))))))))))))),
470 (4, ''))),
471 (6, ''))))),
472 (4, ''),
473 (0, ''))))
474 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
475
Fred Drake58422e52001-06-04 03:56:24 +0000476 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000477 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000478 tree = \
479 (258,
480 (311,
481 (290,
482 (291,
483 (292,
484 (293,
485 (295,
486 (296,
487 (297,
488 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
489 (12, ','),
490 (12, ','),
491 (290,
492 (291,
493 (292,
494 (293,
495 (295,
496 (296,
497 (297,
498 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
499 (4, ''),
500 (0, ''))
501 self.check_bad_tree(tree, "a,,c")
502
503 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000504 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000505 tree = \
506 (257,
507 (264,
508 (265,
509 (266,
510 (267,
511 (312,
512 (291,
513 (292,
514 (293,
515 (294,
516 (296,
517 (297,
518 (298,
519 (299,
520 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
521 (268, (37, '$=')),
522 (312,
523 (291,
524 (292,
525 (293,
526 (294,
527 (296,
528 (297,
529 (298,
530 (299,
531 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
532 (4, ''))),
533 (0, ''))
534 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000535
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000536 def test_malformed_global(self):
537 #doesn't have global keyword in ast
538 tree = (257,
539 (264,
540 (265,
541 (266,
542 (282, (1, 'foo'))), (4, ''))),
543 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000544 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000545 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000546
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000547 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000548 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000549 tree = \
550 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000551 (268,
552 (269,
553 (270,
554 (282,
555 (284, (1, 'from'), (1, 'import'),
556 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000557 (4, ''))),
558 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000559 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000560
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000561
562class CompileTestCase(unittest.TestCase):
563
564 # These tests are very minimal. :-(
565
566 def test_compile_expr(self):
567 st = parser.expr('2 + 3')
568 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000569 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000570
571 def test_compile_suite(self):
572 st = parser.suite('x = 2; y = x + 3')
573 code = parser.compilest(st)
574 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000575 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000576 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000577
578 def test_compile_error(self):
579 st = parser.suite('1 = 3 + 4')
580 self.assertRaises(SyntaxError, parser.compilest, st)
581
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000582 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000583 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000584 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000585 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000586 self.assertRaises(SyntaxError, parser.compilest, st)
587
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000588 def test_issue_9011(self):
589 # Issue 9011: compilation of an unary minus expression changed
590 # the meaning of the ST, so that a second compilation produced
591 # incorrect results.
592 st = parser.expr('-3')
593 code1 = parser.compilest(st)
594 self.assertEqual(eval(code1), -3)
595 code2 = parser.compilest(st)
596 self.assertEqual(eval(code2), -3)
597
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000598class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000599 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000600 see http://bugs.python.org/issue1881 for a discussion
601 """
602 def _nested_expression(self, level):
603 return "["*level+"]"*level
604
605 def test_deeply_nested_list(self):
606 # XXX used to be 99 levels in 2.x
607 e = self._nested_expression(93)
608 st = parser.expr(e)
609 st.compile()
610
611 def test_trigger_memory_error(self):
612 e = self._nested_expression(100)
Christian Heimesb186d002008-03-18 15:15:01 +0000613 print("Expecting 's_push: parser stack overflow' in next line",
614 file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +0000615 sys.stderr.flush()
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000616 self.assertRaises(MemoryError, parser.expr, e)
617
Mark Dickinson211c6252009-02-01 10:28:51 +0000618class STObjectTestCase(unittest.TestCase):
619 """Test operations on ST objects themselves"""
620
621 def test_comparisons(self):
622 # ST objects should support order and equality comparisons
623 st1 = parser.expr('2 + 3')
624 st2 = parser.suite('x = 2; y = x + 3')
625 st3 = parser.expr('list(x**3 for x in range(20))')
626 st1_copy = parser.expr('2 + 3')
627 st2_copy = parser.suite('x = 2; y = x + 3')
628 st3_copy = parser.expr('list(x**3 for x in range(20))')
629
630 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000631 self.assertEqual(st1 == st1, True)
632 self.assertEqual(st2 == st2, True)
633 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000634 # slow path equality
635 self.assertEqual(st1, st1_copy)
636 self.assertEqual(st2, st2_copy)
637 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000638 self.assertEqual(st1 == st2, False)
639 self.assertEqual(st1 == st3, False)
640 self.assertEqual(st2 == st3, False)
641 self.assertEqual(st1 != st1, False)
642 self.assertEqual(st2 != st2, False)
643 self.assertEqual(st3 != st3, False)
644 self.assertEqual(st1 != st1_copy, False)
645 self.assertEqual(st2 != st2_copy, False)
646 self.assertEqual(st3 != st3_copy, False)
647 self.assertEqual(st2 != st1, True)
648 self.assertEqual(st1 != st3, True)
649 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000650 # we don't particularly care what the ordering is; just that
651 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000652 self.assertEqual(st1 < st2, not (st2 <= st1))
653 self.assertEqual(st1 < st3, not (st3 <= st1))
654 self.assertEqual(st2 < st3, not (st3 <= st2))
655 self.assertEqual(st1 < st2, st2 > st1)
656 self.assertEqual(st1 < st3, st3 > st1)
657 self.assertEqual(st2 < st3, st3 > st2)
658 self.assertEqual(st1 <= st2, st2 >= st1)
659 self.assertEqual(st3 <= st1, st1 >= st3)
660 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000661 # transitivity
662 bottom = min(st1, st2, st3)
663 top = max(st1, st2, st3)
664 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000665 self.assertTrue(bottom < mid)
666 self.assertTrue(bottom < top)
667 self.assertTrue(mid < top)
668 self.assertTrue(bottom <= mid)
669 self.assertTrue(bottom <= top)
670 self.assertTrue(mid <= top)
671 self.assertTrue(bottom <= bottom)
672 self.assertTrue(mid <= mid)
673 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000674 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000675 self.assertEqual(st1 == 1588.602459, False)
676 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000677 self.assertRaises(TypeError, operator.ge, st3, None)
678 self.assertRaises(TypeError, operator.le, False, st1)
679 self.assertRaises(TypeError, operator.lt, st1, 1815)
680 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
681
682
683 # XXX tests for pickling and unpickling of ST objects should go here
684
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500685class OtherParserCase(unittest.TestCase):
686
687 def test_two_args_to_expr(self):
688 # See bug #12264
689 with self.assertRaises(TypeError):
690 parser.expr("a", "b")
691
Fred Drake2e2be372001-09-20 21:33:42 +0000692def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000693 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000694 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000695 IllegalSyntaxTestCase,
696 CompileTestCase,
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000697 ParserStackLimitTestCase,
Mark Dickinson211c6252009-02-01 10:28:51 +0000698 STObjectTestCase,
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500699 OtherParserCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000700 )
Fred Drake2e2be372001-09-20 21:33:42 +0000701
702
703if __name__ == "__main__":
704 test_main()