blob: b39d37badd31526b642bc34d6a15ff032fa2a837 [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
Ezio Melotti39191842013-03-09 22:17:33 +02007from test.script_helper import assert_python_failure
Fred Drake79ca79d2000-08-21 22:30:53 +00008
9#
10# First, we test that we can generate trees from valid source fragments,
11# and that these valid trees are indeed allowed by the tree-loading side
12# of the parser module.
13#
14
Fred Drake58422e52001-06-04 03:56:24 +000015class RoundtripLegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +000016
Fred Drake58422e52001-06-04 03:56:24 +000017 def roundtrip(self, f, s):
18 st1 = f(s)
19 t = st1.totuple()
20 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +000021 st2 = parser.sequence2st(t)
Guido van Rossumb940e112007-01-10 16:19:56 +000022 except parser.ParserError as why:
Anthony Baxterc2a5a632004-08-02 06:10:11 +000023 self.fail("could not roundtrip %r: %s" % (s, why))
Fred Drake79ca79d2000-08-21 22:30:53 +000024
Ezio Melottib3aedd42010-11-20 19:04:17 +000025 self.assertEqual(t, st2.totuple(),
26 "could not re-generate syntax tree")
Fred Drake28f739a2000-08-25 22:42:40 +000027
Fred Drake58422e52001-06-04 03:56:24 +000028 def check_expr(self, s):
29 self.roundtrip(parser.expr, s)
Fred Drake28f739a2000-08-25 22:42:40 +000030
Benjamin Petersonf216c942008-10-31 02:28:05 +000031 def test_flags_passed(self):
32 # The unicode literals flags has to be passed from the paser to AST
33 # generation.
34 suite = parser.suite("from __future__ import unicode_literals; x = ''")
35 code = suite.compile()
36 scope = {}
37 exec(code, {}, scope)
Ezio Melottie9615932010-01-24 19:26:24 +000038 self.assertIsInstance(scope["x"], str)
Benjamin Petersonf216c942008-10-31 02:28:05 +000039
Fred Drake58422e52001-06-04 03:56:24 +000040 def check_suite(self, s):
41 self.roundtrip(parser.suite, s)
Fred Drake28f739a2000-08-25 22:42:40 +000042
Fred Drakecf580c72001-07-17 03:01:29 +000043 def test_yield_statement(self):
Tim Peters496563a2002-04-01 00:28:59 +000044 self.check_suite("def f(): yield 1")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000045 self.check_suite("def f(): yield")
46 self.check_suite("def f(): x += yield")
47 self.check_suite("def f(): x = yield 1")
48 self.check_suite("def f(): x = y = yield 1")
49 self.check_suite("def f(): x = yield")
50 self.check_suite("def f(): x = y = yield")
51 self.check_suite("def f(): 1 + (yield)*2")
52 self.check_suite("def f(): (yield 1)*2")
Tim Peters496563a2002-04-01 00:28:59 +000053 self.check_suite("def f(): return; yield 1")
54 self.check_suite("def f(): yield 1; return")
55 self.check_suite("def f():\n"
Fred Drakecf580c72001-07-17 03:01:29 +000056 " for x in range(30):\n"
57 " yield x\n")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000058 self.check_suite("def f():\n"
59 " if (yield):\n"
60 " yield x\n")
Fred Drakecf580c72001-07-17 03:01:29 +000061
Mark Dickinson407b3bd2012-04-29 22:18:31 +010062 def test_nonlocal_statement(self):
63 self.check_suite("def f():\n"
64 " x = 0\n"
65 " def g():\n"
66 " nonlocal x\n")
67 self.check_suite("def f():\n"
68 " x = y = 0\n"
69 " def g():\n"
70 " nonlocal x, y\n")
71
Fred Drake58422e52001-06-04 03:56:24 +000072 def test_expressions(self):
73 self.check_expr("foo(1)")
74 self.check_expr("[1, 2, 3]")
75 self.check_expr("[x**3 for x in range(20)]")
76 self.check_expr("[x**3 for x in range(20) if x % 3]")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000077 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
78 self.check_expr("list(x**3 for x in range(20))")
79 self.check_expr("list(x**3 for x in range(20) if x % 3)")
80 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Fred Drake58422e52001-06-04 03:56:24 +000081 self.check_expr("foo(*args)")
82 self.check_expr("foo(*args, **kw)")
83 self.check_expr("foo(**kw)")
84 self.check_expr("foo(key=value)")
85 self.check_expr("foo(key=value, *args)")
86 self.check_expr("foo(key=value, *args, **kw)")
87 self.check_expr("foo(key=value, **kw)")
88 self.check_expr("foo(a, b, c, *args)")
89 self.check_expr("foo(a, b, c, *args, **kw)")
90 self.check_expr("foo(a, b, c, **kw)")
Benjamin Peterson3938a902008-08-20 02:33:00 +000091 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +000092 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +000093 self.check_expr("foo - bar")
94 self.check_expr("foo * bar")
95 self.check_expr("foo / bar")
96 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +000097 self.check_expr("lambda: 0")
98 self.check_expr("lambda x: 0")
99 self.check_expr("lambda *y: 0")
100 self.check_expr("lambda *y, **z: 0")
101 self.check_expr("lambda **z: 0")
102 self.check_expr("lambda x, y: 0")
103 self.check_expr("lambda foo=bar: 0")
104 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
105 self.check_expr("lambda foo=bar, **z: 0")
106 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
107 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
108 self.check_expr("lambda x, *y, **z: 0")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000109 self.check_expr("(x for x in range(10))")
110 self.check_expr("foo(x for x in range(10))")
Mark Dickinsonda029fb2012-05-07 17:24:04 +0100111 self.check_expr("...")
112 self.check_expr("a[...]")
Fred Drake79ca79d2000-08-21 22:30:53 +0000113
Fred Drake58422e52001-06-04 03:56:24 +0000114 def test_simple_expression(self):
115 # expr_stmt
116 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000117
Fred Drake58422e52001-06-04 03:56:24 +0000118 def test_simple_assignments(self):
119 self.check_suite("a = b")
120 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000121
Fred Drake58422e52001-06-04 03:56:24 +0000122 def test_simple_augmented_assignments(self):
123 self.check_suite("a += b")
124 self.check_suite("a -= b")
125 self.check_suite("a *= b")
126 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000127 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000128 self.check_suite("a %= b")
129 self.check_suite("a &= b")
130 self.check_suite("a |= b")
131 self.check_suite("a ^= b")
132 self.check_suite("a <<= b")
133 self.check_suite("a >>= b")
134 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000135
Fred Drake58422e52001-06-04 03:56:24 +0000136 def test_function_defs(self):
137 self.check_suite("def f(): pass")
138 self.check_suite("def f(*args): pass")
139 self.check_suite("def f(*args, **kw): pass")
140 self.check_suite("def f(**kw): pass")
141 self.check_suite("def f(foo=bar): pass")
142 self.check_suite("def f(foo=bar, *args): pass")
143 self.check_suite("def f(foo=bar, *args, **kw): pass")
144 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000145
Fred Drake58422e52001-06-04 03:56:24 +0000146 self.check_suite("def f(a, b): pass")
147 self.check_suite("def f(a, b, *args): pass")
148 self.check_suite("def f(a, b, *args, **kw): pass")
149 self.check_suite("def f(a, b, **kw): pass")
150 self.check_suite("def f(a, b, foo=bar): pass")
151 self.check_suite("def f(a, b, foo=bar, *args): pass")
152 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
153 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000154
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000155 self.check_suite("@staticmethod\n"
156 "def f(): pass")
157 self.check_suite("@staticmethod\n"
158 "@funcattrs(x, y)\n"
159 "def f(): pass")
160 self.check_suite("@funcattrs()\n"
161 "def f(): pass")
162
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100163 # keyword-only arguments
164 self.check_suite("def f(*, a): pass")
165 self.check_suite("def f(*, a = 5): pass")
166 self.check_suite("def f(*, a = 5, b): pass")
167 self.check_suite("def f(*, a, b = 5): pass")
168 self.check_suite("def f(*, a, b = 5, **kwds): pass")
169 self.check_suite("def f(*args, a): pass")
170 self.check_suite("def f(*args, a = 5): pass")
171 self.check_suite("def f(*args, a = 5, b): pass")
172 self.check_suite("def f(*args, a, b = 5): pass")
173 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
174
175 # function annotations
176 self.check_suite("def f(a: int): pass")
177 self.check_suite("def f(a: int = 5): pass")
178 self.check_suite("def f(*args: list): pass")
179 self.check_suite("def f(**kwds: dict): pass")
180 self.check_suite("def f(*, a: int): pass")
181 self.check_suite("def f(*, a: int = 5): pass")
182 self.check_suite("def f() -> int: pass")
183
Brett Cannonf4189912005-04-09 02:30:16 +0000184 def test_class_defs(self):
185 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000186 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000187 self.check_suite("@class_decorator\n"
188 "class foo():pass")
189 self.check_suite("@class_decorator(arg)\n"
190 "class foo():pass")
191 self.check_suite("@decorator1\n"
192 "@decorator2\n"
193 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000194
Fred Drake58422e52001-06-04 03:56:24 +0000195 def test_import_from_statement(self):
196 self.check_suite("from sys.path import *")
197 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000198 self.check_suite("from sys.path import (dirname)")
199 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000200 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000201 self.check_suite("from sys.path import (dirname as my_dirname)")
202 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000203 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000204 self.check_suite("from sys.path import (dirname, basename)")
205 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000206 self.check_suite(
207 "from sys.path import dirname as my_dirname, basename")
208 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000209 "from sys.path import (dirname as my_dirname, basename)")
210 self.check_suite(
211 "from sys.path import (dirname as my_dirname, basename,)")
212 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000213 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000214 self.check_suite(
215 "from sys.path import (dirname, basename as my_basename)")
216 self.check_suite(
217 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000218 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000219
Fred Drake58422e52001-06-04 03:56:24 +0000220 def test_basic_import_statement(self):
221 self.check_suite("import sys")
222 self.check_suite("import sys as system")
223 self.check_suite("import sys, math")
224 self.check_suite("import sys as system, math")
225 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000226
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000227 def test_relative_imports(self):
228 self.check_suite("from . import name")
229 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000230 # check all the way up to '....', since '...' is tokenized
231 # differently from '.' (it's an ellipsis token).
232 self.check_suite("from ... import name")
233 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000234 self.check_suite("from .pkg import name")
235 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000236 self.check_suite("from ...pkg import name")
237 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000238
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000239 def test_pep263(self):
240 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
241 "pass\n")
242
243 def test_assert(self):
244 self.check_suite("assert alo < ahi and blo < bhi\n")
245
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000246 def test_with(self):
247 self.check_suite("with open('x'): pass\n")
248 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000249 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000250
Georg Brandleee31162008-12-07 15:15:22 +0000251 def test_try_stmt(self):
252 self.check_suite("try: pass\nexcept: pass\n")
253 self.check_suite("try: pass\nfinally: pass\n")
254 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
255 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
256 "finally: pass\n")
257 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
258 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
259 "finally: pass\n")
260
Thomas Wouters89f507f2006-12-13 04:49:30 +0000261 def test_position(self):
262 # An absolutely minimal test of position information. Better
263 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000264 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000265 st1 = parser.suite(code)
266 st2 = st1.totuple(line_info=1, col_info=1)
267
268 def walk(tree):
269 node_type = tree[0]
270 next = tree[1]
271 if isinstance(next, tuple):
272 for elt in tree[1:]:
273 for x in walk(elt):
274 yield x
275 else:
276 yield tree
277
278 terminals = list(walk(st2))
279 self.assertEqual([
280 (1, 'def', 1, 0),
281 (1, 'f', 1, 4),
282 (7, '(', 1, 5),
283 (1, 'x', 1, 6),
284 (8, ')', 1, 7),
285 (11, ':', 1, 8),
286 (4, '', 1, 9),
287 (5, '', 2, -1),
288 (1, 'return', 2, 4),
289 (1, 'x', 2, 11),
290 (14, '+', 2, 13),
291 (2, '1', 2, 15),
292 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000293 (6, '', 2, -1),
294 (4, '', 2, -1),
295 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000296 terminals)
297
Benjamin Peterson4905e802009-09-27 02:43:28 +0000298 def test_extended_unpacking(self):
299 self.check_suite("*a = y")
300 self.check_suite("x, *b, = m")
301 self.check_suite("[*a, *b] = y")
302 self.check_suite("for [*x, b] in x: pass")
303
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100304 def test_raise_statement(self):
305 self.check_suite("raise\n")
306 self.check_suite("raise e\n")
307 self.check_suite("try:\n"
308 " suite\n"
309 "except Exception as e:\n"
310 " raise ValueError from e\n")
311
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100312 def test_set_displays(self):
313 self.check_expr('{2}')
314 self.check_expr('{2,}')
315 self.check_expr('{2, 3}')
316 self.check_expr('{2, 3,}')
317
318 def test_dict_displays(self):
319 self.check_expr('{}')
320 self.check_expr('{a:b}')
321 self.check_expr('{a:b,}')
322 self.check_expr('{a:b, c:d}')
323 self.check_expr('{a:b, c:d,}')
324
325 def test_set_comprehensions(self):
326 self.check_expr('{x for x in seq}')
327 self.check_expr('{f(x) for x in seq}')
328 self.check_expr('{f(x) for x in seq if condition(x)}')
329
330 def test_dict_comprehensions(self):
331 self.check_expr('{x:x for x in seq}')
332 self.check_expr('{x**2:x[3] for x in seq if condition(x)}')
333 self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}')
334
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335
Fred Drake79ca79d2000-08-21 22:30:53 +0000336#
337# Second, we take *invalid* trees and make sure we get ParserError
338# rejections for them.
339#
340
Fred Drake58422e52001-06-04 03:56:24 +0000341class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000342
Fred Drake58422e52001-06-04 03:56:24 +0000343 def check_bad_tree(self, tree, label):
344 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000345 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000346 except parser.ParserError:
347 pass
348 else:
349 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000350
Fred Drake58422e52001-06-04 03:56:24 +0000351 def test_junk(self):
352 # not even remotely valid:
353 self.check_bad_tree((1, 2, 3), "<junk>")
354
Fred Drakecf580c72001-07-17 03:01:29 +0000355 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000356 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000357 tree = \
358 (257,
359 (264,
360 (285,
361 (259,
362 (1, 'def'),
363 (1, 'f'),
364 (260, (7, '('), (8, ')')),
365 (11, ':'),
366 (291,
367 (4, ''),
368 (5, ''),
369 (264,
370 (265,
371 (266,
372 (272,
373 (275,
374 (1, 'return'),
375 (313,
376 (292,
377 (293,
378 (294,
379 (295,
380 (297,
381 (298,
382 (299,
383 (300,
384 (301,
385 (302, (303, (304, (305, (2, '1')))))))))))))))))),
386 (264,
387 (265,
388 (266,
389 (272,
390 (276,
391 (1, 'yield'),
392 (313,
393 (292,
394 (293,
395 (294,
396 (295,
397 (297,
398 (298,
399 (299,
400 (300,
401 (301,
402 (302,
403 (303, (304, (305, (2, '1')))))))))))))))))),
404 (4, ''))),
405 (6, ''))))),
406 (4, ''),
407 (0, ''))))
408 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
409
410 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000411 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000412 tree = \
413 (257,
414 (264,
415 (265,
416 (266,
417 (278,
418 (1, 'from'),
419 (281, (1, '__future__')),
420 (1, 'import'),
421 (279, (1, 'generators')))),
422 (4, ''))),
423 (264,
424 (285,
425 (259,
426 (1, 'def'),
427 (1, 'f'),
428 (260, (7, '('), (8, ')')),
429 (11, ':'),
430 (291,
431 (4, ''),
432 (5, ''),
433 (264,
434 (265,
435 (266,
436 (272,
437 (275,
438 (1, 'return'),
439 (313,
440 (292,
441 (293,
442 (294,
443 (295,
444 (297,
445 (298,
446 (299,
447 (300,
448 (301,
449 (302, (303, (304, (305, (2, '1')))))))))))))))))),
450 (264,
451 (265,
452 (266,
453 (272,
454 (276,
455 (1, 'yield'),
456 (313,
457 (292,
458 (293,
459 (294,
460 (295,
461 (297,
462 (298,
463 (299,
464 (300,
465 (301,
466 (302,
467 (303, (304, (305, (2, '1')))))))))))))))))),
468 (4, ''))),
469 (6, ''))))),
470 (4, ''),
471 (0, ''))))
472 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
473
Fred Drake58422e52001-06-04 03:56:24 +0000474 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000475 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000476 tree = \
477 (258,
478 (311,
479 (290,
480 (291,
481 (292,
482 (293,
483 (295,
484 (296,
485 (297,
486 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
487 (12, ','),
488 (12, ','),
489 (290,
490 (291,
491 (292,
492 (293,
493 (295,
494 (296,
495 (297,
496 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
497 (4, ''),
498 (0, ''))
499 self.check_bad_tree(tree, "a,,c")
500
501 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000502 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000503 tree = \
504 (257,
505 (264,
506 (265,
507 (266,
508 (267,
509 (312,
510 (291,
511 (292,
512 (293,
513 (294,
514 (296,
515 (297,
516 (298,
517 (299,
518 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
519 (268, (37, '$=')),
520 (312,
521 (291,
522 (292,
523 (293,
524 (294,
525 (296,
526 (297,
527 (298,
528 (299,
529 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
530 (4, ''))),
531 (0, ''))
532 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000533
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000534 def test_malformed_global(self):
535 #doesn't have global keyword in ast
536 tree = (257,
537 (264,
538 (265,
539 (266,
540 (282, (1, 'foo'))), (4, ''))),
541 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000542 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000543 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000544
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000545 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000546 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000547 tree = \
548 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000549 (268,
550 (269,
551 (270,
552 (282,
553 (284, (1, 'from'), (1, 'import'),
554 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000555 (4, ''))),
556 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000557 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000558
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559
560class CompileTestCase(unittest.TestCase):
561
562 # These tests are very minimal. :-(
563
564 def test_compile_expr(self):
565 st = parser.expr('2 + 3')
566 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000567 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000568
569 def test_compile_suite(self):
570 st = parser.suite('x = 2; y = x + 3')
571 code = parser.compilest(st)
572 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000573 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000574 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000575
576 def test_compile_error(self):
577 st = parser.suite('1 = 3 + 4')
578 self.assertRaises(SyntaxError, parser.compilest, st)
579
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000580 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000581 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000582 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000583 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000584 self.assertRaises(SyntaxError, parser.compilest, st)
585
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000586 def test_issue_9011(self):
587 # Issue 9011: compilation of an unary minus expression changed
588 # the meaning of the ST, so that a second compilation produced
589 # incorrect results.
590 st = parser.expr('-3')
591 code1 = parser.compilest(st)
592 self.assertEqual(eval(code1), -3)
593 code2 = parser.compilest(st)
594 self.assertEqual(eval(code2), -3)
595
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000596class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000597 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000598 see http://bugs.python.org/issue1881 for a discussion
599 """
600 def _nested_expression(self, level):
601 return "["*level+"]"*level
602
603 def test_deeply_nested_list(self):
604 # XXX used to be 99 levels in 2.x
605 e = self._nested_expression(93)
606 st = parser.expr(e)
607 st.compile()
608
609 def test_trigger_memory_error(self):
610 e = self._nested_expression(100)
Ezio Melotti39191842013-03-09 22:17:33 +0200611 rc, out, err = assert_python_failure('-c', e)
612 # parsing the expression will result in an error message
613 # followed by a MemoryError (see #11963)
Ezio Melottie7c32992013-03-10 03:25:45 +0200614 self.assertIn(b's_push: parser stack overflow', err)
615 self.assertIn(b'MemoryError', err)
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000616
Mark Dickinson211c6252009-02-01 10:28:51 +0000617class STObjectTestCase(unittest.TestCase):
618 """Test operations on ST objects themselves"""
619
620 def test_comparisons(self):
621 # ST objects should support order and equality comparisons
622 st1 = parser.expr('2 + 3')
623 st2 = parser.suite('x = 2; y = x + 3')
624 st3 = parser.expr('list(x**3 for x in range(20))')
625 st1_copy = parser.expr('2 + 3')
626 st2_copy = parser.suite('x = 2; y = x + 3')
627 st3_copy = parser.expr('list(x**3 for x in range(20))')
628
629 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000630 self.assertEqual(st1 == st1, True)
631 self.assertEqual(st2 == st2, True)
632 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000633 # slow path equality
634 self.assertEqual(st1, st1_copy)
635 self.assertEqual(st2, st2_copy)
636 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000637 self.assertEqual(st1 == st2, False)
638 self.assertEqual(st1 == st3, False)
639 self.assertEqual(st2 == st3, False)
640 self.assertEqual(st1 != st1, False)
641 self.assertEqual(st2 != st2, False)
642 self.assertEqual(st3 != st3, False)
643 self.assertEqual(st1 != st1_copy, False)
644 self.assertEqual(st2 != st2_copy, False)
645 self.assertEqual(st3 != st3_copy, False)
646 self.assertEqual(st2 != st1, True)
647 self.assertEqual(st1 != st3, True)
648 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000649 # we don't particularly care what the ordering is; just that
650 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000651 self.assertEqual(st1 < st2, not (st2 <= st1))
652 self.assertEqual(st1 < st3, not (st3 <= st1))
653 self.assertEqual(st2 < st3, not (st3 <= st2))
654 self.assertEqual(st1 < st2, st2 > st1)
655 self.assertEqual(st1 < st3, st3 > st1)
656 self.assertEqual(st2 < st3, st3 > st2)
657 self.assertEqual(st1 <= st2, st2 >= st1)
658 self.assertEqual(st3 <= st1, st1 >= st3)
659 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000660 # transitivity
661 bottom = min(st1, st2, st3)
662 top = max(st1, st2, st3)
663 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000664 self.assertTrue(bottom < mid)
665 self.assertTrue(bottom < top)
666 self.assertTrue(mid < top)
667 self.assertTrue(bottom <= mid)
668 self.assertTrue(bottom <= top)
669 self.assertTrue(mid <= top)
670 self.assertTrue(bottom <= bottom)
671 self.assertTrue(mid <= mid)
672 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000673 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000674 self.assertEqual(st1 == 1588.602459, False)
675 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000676 self.assertRaises(TypeError, operator.ge, st3, None)
677 self.assertRaises(TypeError, operator.le, False, st1)
678 self.assertRaises(TypeError, operator.lt, st1, 1815)
679 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
680
Jesus Ceae9c53182012-08-03 14:28:37 +0200681 check_sizeof = support.check_sizeof
682
683 @support.cpython_only
684 def test_sizeof(self):
685 def XXXROUNDUP(n):
686 if n <= 1:
687 return n
688 if n <= 128:
689 return (n + 3) & ~3
690 return 1 << (n - 1).bit_length()
691
692 basesize = support.calcobjsize('Pii')
693 nodesize = struct.calcsize('hP3iP0h')
694 def sizeofchildren(node):
695 if node is None:
696 return 0
697 res = 0
698 hasstr = len(node) > 1 and isinstance(node[-1], str)
699 if hasstr:
700 res += len(node[-1]) + 1
701 children = node[1:-1] if hasstr else node[1:]
702 if children:
703 res += XXXROUNDUP(len(children)) * nodesize
Jesus Ceae9c53182012-08-03 14:28:37 +0200704 for child in children:
705 res += sizeofchildren(child)
706 return res
707
708 def check_st_sizeof(st):
709 self.check_sizeof(st, basesize + nodesize +
710 sizeofchildren(st.totuple()))
711
712 check_st_sizeof(parser.expr('2 + 3'))
713 check_st_sizeof(parser.expr('2 + 3 + 4'))
714 check_st_sizeof(parser.suite('x = 2 + 3'))
715 check_st_sizeof(parser.suite(''))
716 check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
717 check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
718
Mark Dickinson211c6252009-02-01 10:28:51 +0000719
720 # XXX tests for pickling and unpickling of ST objects should go here
721
722
Fred Drake2e2be372001-09-20 21:33:42 +0000723def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000724 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000725 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000726 IllegalSyntaxTestCase,
727 CompileTestCase,
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000728 ParserStackLimitTestCase,
Mark Dickinson211c6252009-02-01 10:28:51 +0000729 STObjectTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000730 )
Fred Drake2e2be372001-09-20 21:33:42 +0000731
732
733if __name__ == "__main__":
734 test_main()