blob: c93a2ca0bee8d17c53378caa718cecaf38d9dc13 [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")
Nick Coghlan1f7ce622012-01-13 21:43:40 +100054 self.check_suite("def f(): yield from 1")
55 self.check_suite("def f(): x = yield from 1")
56 self.check_suite("def f(): f((yield from 1))")
57 self.check_suite("def f(): yield 1; return 1")
Tim Peters496563a2002-04-01 00:28:59 +000058 self.check_suite("def f():\n"
Fred Drakecf580c72001-07-17 03:01:29 +000059 " for x in range(30):\n"
60 " yield x\n")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000061 self.check_suite("def f():\n"
62 " if (yield):\n"
63 " yield x\n")
Fred Drakecf580c72001-07-17 03:01:29 +000064
Mark Dickinson407b3bd2012-04-29 22:18:31 +010065 def test_nonlocal_statement(self):
66 self.check_suite("def f():\n"
67 " x = 0\n"
68 " def g():\n"
69 " nonlocal x\n")
70 self.check_suite("def f():\n"
71 " x = y = 0\n"
72 " def g():\n"
73 " nonlocal x, y\n")
74
Fred Drake58422e52001-06-04 03:56:24 +000075 def test_expressions(self):
76 self.check_expr("foo(1)")
77 self.check_expr("[1, 2, 3]")
78 self.check_expr("[x**3 for x in range(20)]")
79 self.check_expr("[x**3 for x in range(20) if x % 3]")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000080 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
81 self.check_expr("list(x**3 for x in range(20))")
82 self.check_expr("list(x**3 for x in range(20) if x % 3)")
83 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Fred Drake58422e52001-06-04 03:56:24 +000084 self.check_expr("foo(*args)")
85 self.check_expr("foo(*args, **kw)")
86 self.check_expr("foo(**kw)")
87 self.check_expr("foo(key=value)")
88 self.check_expr("foo(key=value, *args)")
89 self.check_expr("foo(key=value, *args, **kw)")
90 self.check_expr("foo(key=value, **kw)")
91 self.check_expr("foo(a, b, c, *args)")
92 self.check_expr("foo(a, b, c, *args, **kw)")
93 self.check_expr("foo(a, b, c, **kw)")
Benjamin Peterson3938a902008-08-20 02:33:00 +000094 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +000095 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +000096 self.check_expr("foo - bar")
97 self.check_expr("foo * bar")
98 self.check_expr("foo / bar")
99 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +0000100 self.check_expr("lambda: 0")
101 self.check_expr("lambda x: 0")
102 self.check_expr("lambda *y: 0")
103 self.check_expr("lambda *y, **z: 0")
104 self.check_expr("lambda **z: 0")
105 self.check_expr("lambda x, y: 0")
106 self.check_expr("lambda foo=bar: 0")
107 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
108 self.check_expr("lambda foo=bar, **z: 0")
109 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
110 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
111 self.check_expr("lambda x, *y, **z: 0")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000112 self.check_expr("(x for x in range(10))")
113 self.check_expr("foo(x for x in range(10))")
Mark Dickinsonda029fb2012-05-07 17:24:04 +0100114 self.check_expr("...")
115 self.check_expr("a[...]")
Fred Drake79ca79d2000-08-21 22:30:53 +0000116
Fred Drake58422e52001-06-04 03:56:24 +0000117 def test_simple_expression(self):
118 # expr_stmt
119 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000120
Fred Drake58422e52001-06-04 03:56:24 +0000121 def test_simple_assignments(self):
122 self.check_suite("a = b")
123 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000124
Fred Drake58422e52001-06-04 03:56:24 +0000125 def test_simple_augmented_assignments(self):
126 self.check_suite("a += b")
127 self.check_suite("a -= b")
128 self.check_suite("a *= b")
129 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000130 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000131 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")
137 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000138
Fred Drake58422e52001-06-04 03:56:24 +0000139 def test_function_defs(self):
140 self.check_suite("def f(): pass")
141 self.check_suite("def f(*args): pass")
142 self.check_suite("def f(*args, **kw): pass")
143 self.check_suite("def f(**kw): pass")
144 self.check_suite("def f(foo=bar): pass")
145 self.check_suite("def f(foo=bar, *args): pass")
146 self.check_suite("def f(foo=bar, *args, **kw): pass")
147 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000148
Fred Drake58422e52001-06-04 03:56:24 +0000149 self.check_suite("def f(a, b): pass")
150 self.check_suite("def f(a, b, *args): pass")
151 self.check_suite("def f(a, b, *args, **kw): pass")
152 self.check_suite("def f(a, b, **kw): pass")
153 self.check_suite("def f(a, b, foo=bar): pass")
154 self.check_suite("def f(a, b, foo=bar, *args): pass")
155 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
156 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000157
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000158 self.check_suite("@staticmethod\n"
159 "def f(): pass")
160 self.check_suite("@staticmethod\n"
161 "@funcattrs(x, y)\n"
162 "def f(): pass")
163 self.check_suite("@funcattrs()\n"
164 "def f(): pass")
165
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100166 # keyword-only arguments
167 self.check_suite("def f(*, a): pass")
168 self.check_suite("def f(*, a = 5): pass")
169 self.check_suite("def f(*, a = 5, b): pass")
170 self.check_suite("def f(*, a, b = 5): pass")
171 self.check_suite("def f(*, a, b = 5, **kwds): pass")
172 self.check_suite("def f(*args, a): pass")
173 self.check_suite("def f(*args, a = 5): pass")
174 self.check_suite("def f(*args, a = 5, b): pass")
175 self.check_suite("def f(*args, a, b = 5): pass")
176 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
177
178 # function annotations
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(*args: list): pass")
182 self.check_suite("def f(**kwds: dict): pass")
183 self.check_suite("def f(*, a: int): pass")
184 self.check_suite("def f(*, a: int = 5): pass")
185 self.check_suite("def f() -> int: pass")
186
Brett Cannonf4189912005-04-09 02:30:16 +0000187 def test_class_defs(self):
188 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000189 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000190 self.check_suite("@class_decorator\n"
191 "class foo():pass")
192 self.check_suite("@class_decorator(arg)\n"
193 "class foo():pass")
194 self.check_suite("@decorator1\n"
195 "@decorator2\n"
196 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000197
Fred Drake58422e52001-06-04 03:56:24 +0000198 def test_import_from_statement(self):
199 self.check_suite("from sys.path import *")
200 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000201 self.check_suite("from sys.path import (dirname)")
202 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000203 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000204 self.check_suite("from sys.path import (dirname as my_dirname)")
205 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000206 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000207 self.check_suite("from sys.path import (dirname, basename)")
208 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000209 self.check_suite(
210 "from sys.path import dirname as my_dirname, basename")
211 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000212 "from sys.path import (dirname as my_dirname, basename)")
213 self.check_suite(
214 "from sys.path import (dirname as my_dirname, basename,)")
215 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000216 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000217 self.check_suite(
218 "from sys.path import (dirname, basename as my_basename)")
219 self.check_suite(
220 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000221 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000222
Fred Drake58422e52001-06-04 03:56:24 +0000223 def test_basic_import_statement(self):
224 self.check_suite("import sys")
225 self.check_suite("import sys as system")
226 self.check_suite("import sys, math")
227 self.check_suite("import sys as system, math")
228 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000229
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000230 def test_relative_imports(self):
231 self.check_suite("from . import name")
232 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000233 # check all the way up to '....', since '...' is tokenized
234 # differently from '.' (it's an ellipsis token).
235 self.check_suite("from ... import name")
236 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000237 self.check_suite("from .pkg import name")
238 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000239 self.check_suite("from ...pkg import name")
240 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000241
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000242 def test_pep263(self):
243 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
244 "pass\n")
245
246 def test_assert(self):
247 self.check_suite("assert alo < ahi and blo < bhi\n")
248
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000249 def test_with(self):
250 self.check_suite("with open('x'): pass\n")
251 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000252 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000253
Georg Brandleee31162008-12-07 15:15:22 +0000254 def test_try_stmt(self):
255 self.check_suite("try: pass\nexcept: pass\n")
256 self.check_suite("try: pass\nfinally: pass\n")
257 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
258 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
259 "finally: pass\n")
260 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
261 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
262 "finally: pass\n")
263
Thomas Wouters89f507f2006-12-13 04:49:30 +0000264 def test_position(self):
265 # An absolutely minimal test of position information. Better
266 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000267 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000268 st1 = parser.suite(code)
269 st2 = st1.totuple(line_info=1, col_info=1)
270
271 def walk(tree):
272 node_type = tree[0]
273 next = tree[1]
274 if isinstance(next, tuple):
275 for elt in tree[1:]:
276 for x in walk(elt):
277 yield x
278 else:
279 yield tree
280
281 terminals = list(walk(st2))
282 self.assertEqual([
283 (1, 'def', 1, 0),
284 (1, 'f', 1, 4),
285 (7, '(', 1, 5),
286 (1, 'x', 1, 6),
287 (8, ')', 1, 7),
288 (11, ':', 1, 8),
289 (4, '', 1, 9),
290 (5, '', 2, -1),
291 (1, 'return', 2, 4),
292 (1, 'x', 2, 11),
293 (14, '+', 2, 13),
294 (2, '1', 2, 15),
295 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000296 (6, '', 2, -1),
297 (4, '', 2, -1),
298 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000299 terminals)
300
Benjamin Peterson4905e802009-09-27 02:43:28 +0000301 def test_extended_unpacking(self):
302 self.check_suite("*a = y")
303 self.check_suite("x, *b, = m")
304 self.check_suite("[*a, *b] = y")
305 self.check_suite("for [*x, b] in x: pass")
306
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100307 def test_raise_statement(self):
308 self.check_suite("raise\n")
309 self.check_suite("raise e\n")
310 self.check_suite("try:\n"
311 " suite\n"
312 "except Exception as e:\n"
313 " raise ValueError from e\n")
314
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100315 def test_set_displays(self):
316 self.check_expr('{2}')
317 self.check_expr('{2,}')
318 self.check_expr('{2, 3}')
319 self.check_expr('{2, 3,}')
320
321 def test_dict_displays(self):
322 self.check_expr('{}')
323 self.check_expr('{a:b}')
324 self.check_expr('{a:b,}')
325 self.check_expr('{a:b, c:d}')
326 self.check_expr('{a:b, c:d,}')
327
328 def test_set_comprehensions(self):
329 self.check_expr('{x for x in seq}')
330 self.check_expr('{f(x) for x in seq}')
331 self.check_expr('{f(x) for x in seq if condition(x)}')
332
333 def test_dict_comprehensions(self):
334 self.check_expr('{x:x for x in seq}')
335 self.check_expr('{x**2:x[3] for x in seq if condition(x)}')
336 self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}')
337
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338
Fred Drake79ca79d2000-08-21 22:30:53 +0000339#
340# Second, we take *invalid* trees and make sure we get ParserError
341# rejections for them.
342#
343
Fred Drake58422e52001-06-04 03:56:24 +0000344class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000345
Fred Drake58422e52001-06-04 03:56:24 +0000346 def check_bad_tree(self, tree, label):
347 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000348 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000349 except parser.ParserError:
350 pass
351 else:
352 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000353
Fred Drake58422e52001-06-04 03:56:24 +0000354 def test_junk(self):
355 # not even remotely valid:
356 self.check_bad_tree((1, 2, 3), "<junk>")
357
Fred Drakecf580c72001-07-17 03:01:29 +0000358 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000359 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000360 tree = \
361 (257,
362 (264,
363 (285,
364 (259,
365 (1, 'def'),
366 (1, 'f'),
367 (260, (7, '('), (8, ')')),
368 (11, ':'),
369 (291,
370 (4, ''),
371 (5, ''),
372 (264,
373 (265,
374 (266,
375 (272,
376 (275,
377 (1, 'return'),
378 (313,
379 (292,
380 (293,
381 (294,
382 (295,
383 (297,
384 (298,
385 (299,
386 (300,
387 (301,
388 (302, (303, (304, (305, (2, '1')))))))))))))))))),
389 (264,
390 (265,
391 (266,
392 (272,
393 (276,
394 (1, 'yield'),
395 (313,
396 (292,
397 (293,
398 (294,
399 (295,
400 (297,
401 (298,
402 (299,
403 (300,
404 (301,
405 (302,
406 (303, (304, (305, (2, '1')))))))))))))))))),
407 (4, ''))),
408 (6, ''))))),
409 (4, ''),
410 (0, ''))))
411 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
412
413 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000414 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000415 tree = \
416 (257,
417 (264,
418 (265,
419 (266,
420 (278,
421 (1, 'from'),
422 (281, (1, '__future__')),
423 (1, 'import'),
424 (279, (1, 'generators')))),
425 (4, ''))),
426 (264,
427 (285,
428 (259,
429 (1, 'def'),
430 (1, 'f'),
431 (260, (7, '('), (8, ')')),
432 (11, ':'),
433 (291,
434 (4, ''),
435 (5, ''),
436 (264,
437 (265,
438 (266,
439 (272,
440 (275,
441 (1, 'return'),
442 (313,
443 (292,
444 (293,
445 (294,
446 (295,
447 (297,
448 (298,
449 (299,
450 (300,
451 (301,
452 (302, (303, (304, (305, (2, '1')))))))))))))))))),
453 (264,
454 (265,
455 (266,
456 (272,
457 (276,
458 (1, 'yield'),
459 (313,
460 (292,
461 (293,
462 (294,
463 (295,
464 (297,
465 (298,
466 (299,
467 (300,
468 (301,
469 (302,
470 (303, (304, (305, (2, '1')))))))))))))))))),
471 (4, ''))),
472 (6, ''))))),
473 (4, ''),
474 (0, ''))))
475 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
476
Fred Drake58422e52001-06-04 03:56:24 +0000477 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000478 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000479 tree = \
480 (258,
481 (311,
482 (290,
483 (291,
484 (292,
485 (293,
486 (295,
487 (296,
488 (297,
489 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
490 (12, ','),
491 (12, ','),
492 (290,
493 (291,
494 (292,
495 (293,
496 (295,
497 (296,
498 (297,
499 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
500 (4, ''),
501 (0, ''))
502 self.check_bad_tree(tree, "a,,c")
503
504 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000505 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000506 tree = \
507 (257,
508 (264,
509 (265,
510 (266,
511 (267,
512 (312,
513 (291,
514 (292,
515 (293,
516 (294,
517 (296,
518 (297,
519 (298,
520 (299,
521 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
522 (268, (37, '$=')),
523 (312,
524 (291,
525 (292,
526 (293,
527 (294,
528 (296,
529 (297,
530 (298,
531 (299,
532 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
533 (4, ''))),
534 (0, ''))
535 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000536
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000537 def test_malformed_global(self):
538 #doesn't have global keyword in ast
539 tree = (257,
540 (264,
541 (265,
542 (266,
543 (282, (1, 'foo'))), (4, ''))),
544 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000545 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000546 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000547
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000548 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000549 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000550 tree = \
551 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000552 (268,
553 (269,
554 (270,
555 (282,
556 (284, (1, 'from'), (1, 'import'),
557 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000558 (4, ''))),
559 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000560 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000561
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000562
563class CompileTestCase(unittest.TestCase):
564
565 # These tests are very minimal. :-(
566
567 def test_compile_expr(self):
568 st = parser.expr('2 + 3')
569 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000570 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000571
572 def test_compile_suite(self):
573 st = parser.suite('x = 2; y = x + 3')
574 code = parser.compilest(st)
575 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000576 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000577 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000578
579 def test_compile_error(self):
580 st = parser.suite('1 = 3 + 4')
581 self.assertRaises(SyntaxError, parser.compilest, st)
582
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000583 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000584 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000585 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000586 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000587 self.assertRaises(SyntaxError, parser.compilest, st)
588
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000589 def test_issue_9011(self):
590 # Issue 9011: compilation of an unary minus expression changed
591 # the meaning of the ST, so that a second compilation produced
592 # incorrect results.
593 st = parser.expr('-3')
594 code1 = parser.compilest(st)
595 self.assertEqual(eval(code1), -3)
596 code2 = parser.compilest(st)
597 self.assertEqual(eval(code2), -3)
598
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000599class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000600 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000601 see http://bugs.python.org/issue1881 for a discussion
602 """
603 def _nested_expression(self, level):
604 return "["*level+"]"*level
605
606 def test_deeply_nested_list(self):
607 # XXX used to be 99 levels in 2.x
608 e = self._nested_expression(93)
609 st = parser.expr(e)
610 st.compile()
611
612 def test_trigger_memory_error(self):
613 e = self._nested_expression(100)
Christian Heimesb186d002008-03-18 15:15:01 +0000614 print("Expecting 's_push: parser stack overflow' in next line",
615 file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +0000616 sys.stderr.flush()
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000617 self.assertRaises(MemoryError, parser.expr, e)
618
Mark Dickinson211c6252009-02-01 10:28:51 +0000619class STObjectTestCase(unittest.TestCase):
620 """Test operations on ST objects themselves"""
621
622 def test_comparisons(self):
623 # ST objects should support order and equality comparisons
624 st1 = parser.expr('2 + 3')
625 st2 = parser.suite('x = 2; y = x + 3')
626 st3 = parser.expr('list(x**3 for x in range(20))')
627 st1_copy = parser.expr('2 + 3')
628 st2_copy = parser.suite('x = 2; y = x + 3')
629 st3_copy = parser.expr('list(x**3 for x in range(20))')
630
631 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000632 self.assertEqual(st1 == st1, True)
633 self.assertEqual(st2 == st2, True)
634 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000635 # slow path equality
636 self.assertEqual(st1, st1_copy)
637 self.assertEqual(st2, st2_copy)
638 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000639 self.assertEqual(st1 == st2, False)
640 self.assertEqual(st1 == st3, False)
641 self.assertEqual(st2 == st3, False)
642 self.assertEqual(st1 != st1, False)
643 self.assertEqual(st2 != st2, False)
644 self.assertEqual(st3 != st3, False)
645 self.assertEqual(st1 != st1_copy, False)
646 self.assertEqual(st2 != st2_copy, False)
647 self.assertEqual(st3 != st3_copy, False)
648 self.assertEqual(st2 != st1, True)
649 self.assertEqual(st1 != st3, True)
650 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000651 # we don't particularly care what the ordering is; just that
652 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000653 self.assertEqual(st1 < st2, not (st2 <= st1))
654 self.assertEqual(st1 < st3, not (st3 <= st1))
655 self.assertEqual(st2 < st3, not (st3 <= st2))
656 self.assertEqual(st1 < st2, st2 > st1)
657 self.assertEqual(st1 < st3, st3 > st1)
658 self.assertEqual(st2 < st3, st3 > st2)
659 self.assertEqual(st1 <= st2, st2 >= st1)
660 self.assertEqual(st3 <= st1, st1 >= st3)
661 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000662 # transitivity
663 bottom = min(st1, st2, st3)
664 top = max(st1, st2, st3)
665 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000666 self.assertTrue(bottom < mid)
667 self.assertTrue(bottom < top)
668 self.assertTrue(mid < top)
669 self.assertTrue(bottom <= mid)
670 self.assertTrue(bottom <= top)
671 self.assertTrue(mid <= top)
672 self.assertTrue(bottom <= bottom)
673 self.assertTrue(mid <= mid)
674 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000675 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000676 self.assertEqual(st1 == 1588.602459, False)
677 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000678 self.assertRaises(TypeError, operator.ge, st3, None)
679 self.assertRaises(TypeError, operator.le, False, st1)
680 self.assertRaises(TypeError, operator.lt, st1, 1815)
681 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
682
Jesus Ceae9c53182012-08-03 14:28:37 +0200683 check_sizeof = support.check_sizeof
684
685 @support.cpython_only
686 def test_sizeof(self):
687 def XXXROUNDUP(n):
688 if n <= 1:
689 return n
690 if n <= 128:
691 return (n + 3) & ~3
692 return 1 << (n - 1).bit_length()
693
694 basesize = support.calcobjsize('Pii')
695 nodesize = struct.calcsize('hP3iP0h')
696 def sizeofchildren(node):
697 if node is None:
698 return 0
699 res = 0
700 hasstr = len(node) > 1 and isinstance(node[-1], str)
701 if hasstr:
702 res += len(node[-1]) + 1
703 children = node[1:-1] if hasstr else node[1:]
704 if children:
705 res += XXXROUNDUP(len(children)) * nodesize
Jesus Ceae9c53182012-08-03 14:28:37 +0200706 for child in children:
707 res += sizeofchildren(child)
708 return res
709
710 def check_st_sizeof(st):
711 self.check_sizeof(st, basesize + nodesize +
712 sizeofchildren(st.totuple()))
713
714 check_st_sizeof(parser.expr('2 + 3'))
715 check_st_sizeof(parser.expr('2 + 3 + 4'))
716 check_st_sizeof(parser.suite('x = 2 + 3'))
717 check_st_sizeof(parser.suite(''))
718 check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
719 check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
720
Mark Dickinson211c6252009-02-01 10:28:51 +0000721
722 # XXX tests for pickling and unpickling of ST objects should go here
723
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500724class OtherParserCase(unittest.TestCase):
725
726 def test_two_args_to_expr(self):
727 # See bug #12264
728 with self.assertRaises(TypeError):
729 parser.expr("a", "b")
730
Fred Drake2e2be372001-09-20 21:33:42 +0000731def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000732 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000733 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000734 IllegalSyntaxTestCase,
735 CompileTestCase,
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000736 ParserStackLimitTestCase,
Mark Dickinson211c6252009-02-01 10:28:51 +0000737 STObjectTestCase,
Benjamin Petersonf719957d2011-06-04 22:06:42 -0500738 OtherParserCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000739 )
Fred Drake2e2be372001-09-20 21:33:42 +0000740
741
742if __name__ == "__main__":
743 test_main()