blob: 70eb9c0cc2b0e59811a1b93f7676070be1523613 [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
Jesus Ceae9c53182012-08-03 14:28:37 +02005import struct
Benjamin Petersonee8712c2008-05-20 21:35:26 +00006from test import support
Fred Drake79ca79d2000-08-21 22:30:53 +00007
8#
9# First, we test that we can generate trees from valid source fragments,
10# and that these valid trees are indeed allowed by the tree-loading side
11# of the parser module.
12#
13
Fred Drake58422e52001-06-04 03:56:24 +000014class RoundtripLegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +000015
Fred Drake58422e52001-06-04 03:56:24 +000016 def roundtrip(self, f, s):
17 st1 = f(s)
18 t = st1.totuple()
19 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +000020 st2 = parser.sequence2st(t)
Guido van Rossumb940e112007-01-10 16:19:56 +000021 except parser.ParserError as why:
Anthony Baxterc2a5a632004-08-02 06:10:11 +000022 self.fail("could not roundtrip %r: %s" % (s, why))
Fred Drake79ca79d2000-08-21 22:30:53 +000023
Ezio Melottib3aedd42010-11-20 19:04:17 +000024 self.assertEqual(t, st2.totuple(),
25 "could not re-generate syntax tree")
Fred Drake28f739a2000-08-25 22:42:40 +000026
Fred Drake58422e52001-06-04 03:56:24 +000027 def check_expr(self, s):
28 self.roundtrip(parser.expr, s)
Fred Drake28f739a2000-08-25 22:42:40 +000029
Benjamin Petersonf216c942008-10-31 02:28:05 +000030 def test_flags_passed(self):
31 # The unicode literals flags has to be passed from the paser to AST
32 # generation.
33 suite = parser.suite("from __future__ import unicode_literals; x = ''")
34 code = suite.compile()
35 scope = {}
36 exec(code, {}, scope)
Ezio Melottie9615932010-01-24 19:26:24 +000037 self.assertIsInstance(scope["x"], str)
Benjamin Petersonf216c942008-10-31 02:28:05 +000038
Fred Drake58422e52001-06-04 03:56:24 +000039 def check_suite(self, s):
40 self.roundtrip(parser.suite, s)
Fred Drake28f739a2000-08-25 22:42:40 +000041
Fred Drakecf580c72001-07-17 03:01:29 +000042 def test_yield_statement(self):
Tim Peters496563a2002-04-01 00:28:59 +000043 self.check_suite("def f(): yield 1")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000044 self.check_suite("def f(): yield")
45 self.check_suite("def f(): x += yield")
46 self.check_suite("def f(): x = yield 1")
47 self.check_suite("def f(): x = y = yield 1")
48 self.check_suite("def f(): x = yield")
49 self.check_suite("def f(): x = y = yield")
50 self.check_suite("def f(): 1 + (yield)*2")
51 self.check_suite("def f(): (yield 1)*2")
Tim Peters496563a2002-04-01 00:28:59 +000052 self.check_suite("def f(): return; yield 1")
53 self.check_suite("def f(): yield 1; return")
54 self.check_suite("def f():\n"
Fred Drakecf580c72001-07-17 03:01:29 +000055 " for x in range(30):\n"
56 " yield x\n")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000057 self.check_suite("def f():\n"
58 " if (yield):\n"
59 " yield x\n")
Fred Drakecf580c72001-07-17 03:01:29 +000060
Mark Dickinson407b3bd2012-04-29 22:18:31 +010061 def test_nonlocal_statement(self):
62 self.check_suite("def f():\n"
63 " x = 0\n"
64 " def g():\n"
65 " nonlocal x\n")
66 self.check_suite("def f():\n"
67 " x = y = 0\n"
68 " def g():\n"
69 " nonlocal x, y\n")
70
Fred Drake58422e52001-06-04 03:56:24 +000071 def test_expressions(self):
72 self.check_expr("foo(1)")
73 self.check_expr("[1, 2, 3]")
74 self.check_expr("[x**3 for x in range(20)]")
75 self.check_expr("[x**3 for x in range(20) if x % 3]")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000076 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
77 self.check_expr("list(x**3 for x in range(20))")
78 self.check_expr("list(x**3 for x in range(20) if x % 3)")
79 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Fred Drake58422e52001-06-04 03:56:24 +000080 self.check_expr("foo(*args)")
81 self.check_expr("foo(*args, **kw)")
82 self.check_expr("foo(**kw)")
83 self.check_expr("foo(key=value)")
84 self.check_expr("foo(key=value, *args)")
85 self.check_expr("foo(key=value, *args, **kw)")
86 self.check_expr("foo(key=value, **kw)")
87 self.check_expr("foo(a, b, c, *args)")
88 self.check_expr("foo(a, b, c, *args, **kw)")
89 self.check_expr("foo(a, b, c, **kw)")
Benjamin Peterson3938a902008-08-20 02:33:00 +000090 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +000091 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +000092 self.check_expr("foo - bar")
93 self.check_expr("foo * bar")
94 self.check_expr("foo / bar")
95 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +000096 self.check_expr("lambda: 0")
97 self.check_expr("lambda x: 0")
98 self.check_expr("lambda *y: 0")
99 self.check_expr("lambda *y, **z: 0")
100 self.check_expr("lambda **z: 0")
101 self.check_expr("lambda x, y: 0")
102 self.check_expr("lambda foo=bar: 0")
103 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
104 self.check_expr("lambda foo=bar, **z: 0")
105 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
106 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
107 self.check_expr("lambda x, *y, **z: 0")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000108 self.check_expr("(x for x in range(10))")
109 self.check_expr("foo(x for x in range(10))")
Mark Dickinsonda029fb2012-05-07 17:24:04 +0100110 self.check_expr("...")
111 self.check_expr("a[...]")
Fred Drake79ca79d2000-08-21 22:30:53 +0000112
Fred Drake58422e52001-06-04 03:56:24 +0000113 def test_simple_expression(self):
114 # expr_stmt
115 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000116
Fred Drake58422e52001-06-04 03:56:24 +0000117 def test_simple_assignments(self):
118 self.check_suite("a = b")
119 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000120
Fred Drake58422e52001-06-04 03:56:24 +0000121 def test_simple_augmented_assignments(self):
122 self.check_suite("a += b")
123 self.check_suite("a -= b")
124 self.check_suite("a *= b")
125 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000126 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000127 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")
133 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000134
Fred Drake58422e52001-06-04 03:56:24 +0000135 def test_function_defs(self):
136 self.check_suite("def f(): pass")
137 self.check_suite("def f(*args): pass")
138 self.check_suite("def f(*args, **kw): pass")
139 self.check_suite("def f(**kw): pass")
140 self.check_suite("def f(foo=bar): pass")
141 self.check_suite("def f(foo=bar, *args): pass")
142 self.check_suite("def f(foo=bar, *args, **kw): pass")
143 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000144
Fred Drake58422e52001-06-04 03:56:24 +0000145 self.check_suite("def f(a, b): pass")
146 self.check_suite("def f(a, b, *args): pass")
147 self.check_suite("def f(a, b, *args, **kw): pass")
148 self.check_suite("def f(a, b, **kw): pass")
149 self.check_suite("def f(a, b, foo=bar): pass")
150 self.check_suite("def f(a, b, foo=bar, *args): pass")
151 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
152 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000153
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000154 self.check_suite("@staticmethod\n"
155 "def f(): pass")
156 self.check_suite("@staticmethod\n"
157 "@funcattrs(x, y)\n"
158 "def f(): pass")
159 self.check_suite("@funcattrs()\n"
160 "def f(): pass")
161
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100162 # keyword-only arguments
163 self.check_suite("def f(*, a): pass")
164 self.check_suite("def f(*, a = 5): pass")
165 self.check_suite("def f(*, a = 5, b): pass")
166 self.check_suite("def f(*, a, b = 5): pass")
167 self.check_suite("def f(*, a, b = 5, **kwds): pass")
168 self.check_suite("def f(*args, a): pass")
169 self.check_suite("def f(*args, a = 5): pass")
170 self.check_suite("def f(*args, a = 5, b): pass")
171 self.check_suite("def f(*args, a, b = 5): pass")
172 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
173
174 # function annotations
175 self.check_suite("def f(a: int): pass")
176 self.check_suite("def f(a: int = 5): pass")
177 self.check_suite("def f(*args: list): pass")
178 self.check_suite("def f(**kwds: dict): pass")
179 self.check_suite("def f(*, a: int): pass")
180 self.check_suite("def f(*, a: int = 5): pass")
181 self.check_suite("def f() -> int: pass")
182
Brett Cannonf4189912005-04-09 02:30:16 +0000183 def test_class_defs(self):
184 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000185 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000186 self.check_suite("@class_decorator\n"
187 "class foo():pass")
188 self.check_suite("@class_decorator(arg)\n"
189 "class foo():pass")
190 self.check_suite("@decorator1\n"
191 "@decorator2\n"
192 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000193
Fred Drake58422e52001-06-04 03:56:24 +0000194 def test_import_from_statement(self):
195 self.check_suite("from sys.path import *")
196 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000197 self.check_suite("from sys.path import (dirname)")
198 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000199 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000200 self.check_suite("from sys.path import (dirname as my_dirname)")
201 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000202 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000203 self.check_suite("from sys.path import (dirname, basename)")
204 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000205 self.check_suite(
206 "from sys.path import dirname as my_dirname, basename")
207 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000208 "from sys.path import (dirname as my_dirname, basename)")
209 self.check_suite(
210 "from sys.path import (dirname as my_dirname, basename,)")
211 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000212 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000213 self.check_suite(
214 "from sys.path import (dirname, basename as my_basename)")
215 self.check_suite(
216 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000217 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000218
Fred Drake58422e52001-06-04 03:56:24 +0000219 def test_basic_import_statement(self):
220 self.check_suite("import sys")
221 self.check_suite("import sys as system")
222 self.check_suite("import sys, math")
223 self.check_suite("import sys as system, math")
224 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000225
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000226 def test_relative_imports(self):
227 self.check_suite("from . import name")
228 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000229 # check all the way up to '....', since '...' is tokenized
230 # differently from '.' (it's an ellipsis token).
231 self.check_suite("from ... import name")
232 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000233 self.check_suite("from .pkg import name")
234 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000235 self.check_suite("from ...pkg import name")
236 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000237
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000238 def test_pep263(self):
239 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
240 "pass\n")
241
242 def test_assert(self):
243 self.check_suite("assert alo < ahi and blo < bhi\n")
244
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000245 def test_with(self):
246 self.check_suite("with open('x'): pass\n")
247 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000248 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000249
Georg Brandleee31162008-12-07 15:15:22 +0000250 def test_try_stmt(self):
251 self.check_suite("try: pass\nexcept: pass\n")
252 self.check_suite("try: pass\nfinally: pass\n")
253 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
254 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
255 "finally: pass\n")
256 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
257 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
258 "finally: pass\n")
259
Thomas Wouters89f507f2006-12-13 04:49:30 +0000260 def test_position(self):
261 # An absolutely minimal test of position information. Better
262 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000263 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000264 st1 = parser.suite(code)
265 st2 = st1.totuple(line_info=1, col_info=1)
266
267 def walk(tree):
268 node_type = tree[0]
269 next = tree[1]
270 if isinstance(next, tuple):
271 for elt in tree[1:]:
272 for x in walk(elt):
273 yield x
274 else:
275 yield tree
276
277 terminals = list(walk(st2))
278 self.assertEqual([
279 (1, 'def', 1, 0),
280 (1, 'f', 1, 4),
281 (7, '(', 1, 5),
282 (1, 'x', 1, 6),
283 (8, ')', 1, 7),
284 (11, ':', 1, 8),
285 (4, '', 1, 9),
286 (5, '', 2, -1),
287 (1, 'return', 2, 4),
288 (1, 'x', 2, 11),
289 (14, '+', 2, 13),
290 (2, '1', 2, 15),
291 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000292 (6, '', 2, -1),
293 (4, '', 2, -1),
294 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000295 terminals)
296
Benjamin Peterson4905e802009-09-27 02:43:28 +0000297 def test_extended_unpacking(self):
298 self.check_suite("*a = y")
299 self.check_suite("x, *b, = m")
300 self.check_suite("[*a, *b] = y")
301 self.check_suite("for [*x, b] in x: pass")
302
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100303 def test_raise_statement(self):
304 self.check_suite("raise\n")
305 self.check_suite("raise e\n")
306 self.check_suite("try:\n"
307 " suite\n"
308 "except Exception as e:\n"
309 " raise ValueError from e\n")
310
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100311 def test_set_displays(self):
312 self.check_expr('{2}')
313 self.check_expr('{2,}')
314 self.check_expr('{2, 3}')
315 self.check_expr('{2, 3,}')
316
317 def test_dict_displays(self):
318 self.check_expr('{}')
319 self.check_expr('{a:b}')
320 self.check_expr('{a:b,}')
321 self.check_expr('{a:b, c:d}')
322 self.check_expr('{a:b, c:d,}')
323
324 def test_set_comprehensions(self):
325 self.check_expr('{x for x in seq}')
326 self.check_expr('{f(x) for x in seq}')
327 self.check_expr('{f(x) for x in seq if condition(x)}')
328
329 def test_dict_comprehensions(self):
330 self.check_expr('{x:x for x in seq}')
331 self.check_expr('{x**2:x[3] for x in seq if condition(x)}')
332 self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}')
333
Thomas Wouters89f507f2006-12-13 04:49:30 +0000334
Fred Drake79ca79d2000-08-21 22:30:53 +0000335#
336# Second, we take *invalid* trees and make sure we get ParserError
337# rejections for them.
338#
339
Fred Drake58422e52001-06-04 03:56:24 +0000340class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000341
Fred Drake58422e52001-06-04 03:56:24 +0000342 def check_bad_tree(self, tree, label):
343 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000344 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000345 except parser.ParserError:
346 pass
347 else:
348 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000349
Fred Drake58422e52001-06-04 03:56:24 +0000350 def test_junk(self):
351 # not even remotely valid:
352 self.check_bad_tree((1, 2, 3), "<junk>")
353
Fred Drakecf580c72001-07-17 03:01:29 +0000354 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000355 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000356 tree = \
357 (257,
358 (264,
359 (285,
360 (259,
361 (1, 'def'),
362 (1, 'f'),
363 (260, (7, '('), (8, ')')),
364 (11, ':'),
365 (291,
366 (4, ''),
367 (5, ''),
368 (264,
369 (265,
370 (266,
371 (272,
372 (275,
373 (1, 'return'),
374 (313,
375 (292,
376 (293,
377 (294,
378 (295,
379 (297,
380 (298,
381 (299,
382 (300,
383 (301,
384 (302, (303, (304, (305, (2, '1')))))))))))))))))),
385 (264,
386 (265,
387 (266,
388 (272,
389 (276,
390 (1, 'yield'),
391 (313,
392 (292,
393 (293,
394 (294,
395 (295,
396 (297,
397 (298,
398 (299,
399 (300,
400 (301,
401 (302,
402 (303, (304, (305, (2, '1')))))))))))))))))),
403 (4, ''))),
404 (6, ''))))),
405 (4, ''),
406 (0, ''))))
407 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
408
409 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000410 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000411 tree = \
412 (257,
413 (264,
414 (265,
415 (266,
416 (278,
417 (1, 'from'),
418 (281, (1, '__future__')),
419 (1, 'import'),
420 (279, (1, 'generators')))),
421 (4, ''))),
422 (264,
423 (285,
424 (259,
425 (1, 'def'),
426 (1, 'f'),
427 (260, (7, '('), (8, ')')),
428 (11, ':'),
429 (291,
430 (4, ''),
431 (5, ''),
432 (264,
433 (265,
434 (266,
435 (272,
436 (275,
437 (1, 'return'),
438 (313,
439 (292,
440 (293,
441 (294,
442 (295,
443 (297,
444 (298,
445 (299,
446 (300,
447 (301,
448 (302, (303, (304, (305, (2, '1')))))))))))))))))),
449 (264,
450 (265,
451 (266,
452 (272,
453 (276,
454 (1, 'yield'),
455 (313,
456 (292,
457 (293,
458 (294,
459 (295,
460 (297,
461 (298,
462 (299,
463 (300,
464 (301,
465 (302,
466 (303, (304, (305, (2, '1')))))))))))))))))),
467 (4, ''))),
468 (6, ''))))),
469 (4, ''),
470 (0, ''))))
471 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
472
Fred Drake58422e52001-06-04 03:56:24 +0000473 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000474 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000475 tree = \
476 (258,
477 (311,
478 (290,
479 (291,
480 (292,
481 (293,
482 (295,
483 (296,
484 (297,
485 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
486 (12, ','),
487 (12, ','),
488 (290,
489 (291,
490 (292,
491 (293,
492 (295,
493 (296,
494 (297,
495 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
496 (4, ''),
497 (0, ''))
498 self.check_bad_tree(tree, "a,,c")
499
500 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000501 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000502 tree = \
503 (257,
504 (264,
505 (265,
506 (266,
507 (267,
508 (312,
509 (291,
510 (292,
511 (293,
512 (294,
513 (296,
514 (297,
515 (298,
516 (299,
517 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
518 (268, (37, '$=')),
519 (312,
520 (291,
521 (292,
522 (293,
523 (294,
524 (296,
525 (297,
526 (298,
527 (299,
528 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
529 (4, ''))),
530 (0, ''))
531 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000532
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000533 def test_malformed_global(self):
534 #doesn't have global keyword in ast
535 tree = (257,
536 (264,
537 (265,
538 (266,
539 (282, (1, 'foo'))), (4, ''))),
540 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000541 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000542 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000543
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000544 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000545 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000546 tree = \
547 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000548 (268,
549 (269,
550 (270,
551 (282,
552 (284, (1, 'from'), (1, 'import'),
553 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000554 (4, ''))),
555 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000556 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000557
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000558
559class CompileTestCase(unittest.TestCase):
560
561 # These tests are very minimal. :-(
562
563 def test_compile_expr(self):
564 st = parser.expr('2 + 3')
565 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000566 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000567
568 def test_compile_suite(self):
569 st = parser.suite('x = 2; y = x + 3')
570 code = parser.compilest(st)
571 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000572 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000573 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000574
575 def test_compile_error(self):
576 st = parser.suite('1 = 3 + 4')
577 self.assertRaises(SyntaxError, parser.compilest, st)
578
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000579 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000580 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000581 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000582 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000583 self.assertRaises(SyntaxError, parser.compilest, st)
584
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000585 def test_issue_9011(self):
586 # Issue 9011: compilation of an unary minus expression changed
587 # the meaning of the ST, so that a second compilation produced
588 # incorrect results.
589 st = parser.expr('-3')
590 code1 = parser.compilest(st)
591 self.assertEqual(eval(code1), -3)
592 code2 = parser.compilest(st)
593 self.assertEqual(eval(code2), -3)
594
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000595class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000596 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000597 see http://bugs.python.org/issue1881 for a discussion
598 """
599 def _nested_expression(self, level):
600 return "["*level+"]"*level
601
602 def test_deeply_nested_list(self):
603 # XXX used to be 99 levels in 2.x
604 e = self._nested_expression(93)
605 st = parser.expr(e)
606 st.compile()
607
608 def test_trigger_memory_error(self):
609 e = self._nested_expression(100)
Christian Heimesb186d002008-03-18 15:15:01 +0000610 print("Expecting 's_push: parser stack overflow' in next line",
611 file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +0000612 sys.stderr.flush()
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000613 self.assertRaises(MemoryError, parser.expr, e)
614
Mark Dickinson211c6252009-02-01 10:28:51 +0000615class STObjectTestCase(unittest.TestCase):
616 """Test operations on ST objects themselves"""
617
618 def test_comparisons(self):
619 # ST objects should support order and equality comparisons
620 st1 = parser.expr('2 + 3')
621 st2 = parser.suite('x = 2; y = x + 3')
622 st3 = parser.expr('list(x**3 for x in range(20))')
623 st1_copy = parser.expr('2 + 3')
624 st2_copy = parser.suite('x = 2; y = x + 3')
625 st3_copy = parser.expr('list(x**3 for x in range(20))')
626
627 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000628 self.assertEqual(st1 == st1, True)
629 self.assertEqual(st2 == st2, True)
630 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000631 # slow path equality
632 self.assertEqual(st1, st1_copy)
633 self.assertEqual(st2, st2_copy)
634 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000635 self.assertEqual(st1 == st2, False)
636 self.assertEqual(st1 == st3, False)
637 self.assertEqual(st2 == st3, False)
638 self.assertEqual(st1 != st1, False)
639 self.assertEqual(st2 != st2, False)
640 self.assertEqual(st3 != st3, False)
641 self.assertEqual(st1 != st1_copy, False)
642 self.assertEqual(st2 != st2_copy, False)
643 self.assertEqual(st3 != st3_copy, False)
644 self.assertEqual(st2 != st1, True)
645 self.assertEqual(st1 != st3, True)
646 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000647 # we don't particularly care what the ordering is; just that
648 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000649 self.assertEqual(st1 < st2, not (st2 <= st1))
650 self.assertEqual(st1 < st3, not (st3 <= st1))
651 self.assertEqual(st2 < st3, not (st3 <= st2))
652 self.assertEqual(st1 < st2, st2 > st1)
653 self.assertEqual(st1 < st3, st3 > st1)
654 self.assertEqual(st2 < st3, st3 > st2)
655 self.assertEqual(st1 <= st2, st2 >= st1)
656 self.assertEqual(st3 <= st1, st1 >= st3)
657 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000658 # transitivity
659 bottom = min(st1, st2, st3)
660 top = max(st1, st2, st3)
661 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000662 self.assertTrue(bottom < mid)
663 self.assertTrue(bottom < top)
664 self.assertTrue(mid < top)
665 self.assertTrue(bottom <= mid)
666 self.assertTrue(bottom <= top)
667 self.assertTrue(mid <= top)
668 self.assertTrue(bottom <= bottom)
669 self.assertTrue(mid <= mid)
670 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000671 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000672 self.assertEqual(st1 == 1588.602459, False)
673 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000674 self.assertRaises(TypeError, operator.ge, st3, None)
675 self.assertRaises(TypeError, operator.le, False, st1)
676 self.assertRaises(TypeError, operator.lt, st1, 1815)
677 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
678
Jesus Ceae9c53182012-08-03 14:28:37 +0200679 check_sizeof = support.check_sizeof
680
681 @support.cpython_only
682 def test_sizeof(self):
683 def XXXROUNDUP(n):
684 if n <= 1:
685 return n
686 if n <= 128:
687 return (n + 3) & ~3
688 return 1 << (n - 1).bit_length()
689
690 basesize = support.calcobjsize('Pii')
691 nodesize = struct.calcsize('hP3iP0h')
692 def sizeofchildren(node):
693 if node is None:
694 return 0
695 res = 0
696 hasstr = len(node) > 1 and isinstance(node[-1], str)
697 if hasstr:
698 res += len(node[-1]) + 1
699 children = node[1:-1] if hasstr else node[1:]
700 if children:
701 res += XXXROUNDUP(len(children)) * nodesize
Jesus Ceae9c53182012-08-03 14:28:37 +0200702 for child in children:
703 res += sizeofchildren(child)
704 return res
705
706 def check_st_sizeof(st):
707 self.check_sizeof(st, basesize + nodesize +
708 sizeofchildren(st.totuple()))
709
710 check_st_sizeof(parser.expr('2 + 3'))
711 check_st_sizeof(parser.expr('2 + 3 + 4'))
712 check_st_sizeof(parser.suite('x = 2 + 3'))
713 check_st_sizeof(parser.suite(''))
714 check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
715 check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
716
Mark Dickinson211c6252009-02-01 10:28:51 +0000717
718 # XXX tests for pickling and unpickling of ST objects should go here
719
720
Fred Drake2e2be372001-09-20 21:33:42 +0000721def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000722 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000723 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000724 IllegalSyntaxTestCase,
725 CompileTestCase,
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000726 ParserStackLimitTestCase,
Mark Dickinson211c6252009-02-01 10:28:51 +0000727 STObjectTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000728 )
Fred Drake2e2be372001-09-20 21:33:42 +0000729
730
731if __name__ == "__main__":
732 test_main()