blob: 65a762c8717e7efd9162dc2788ba28d8d32eb45a [file] [log] [blame]
Fred Drake79ca79d2000-08-21 22:30:53 +00001import parser
Fred Drake58422e52001-06-04 03:56:24 +00002import unittest
Martin v. Löwis66e26632008-03-18 13:16:05 +00003import sys
Jesus Cea3e3192d2012-08-03 14:25:53 +02004import struct
5from test import test_support as support
Ezio Melottida9eeae2013-03-09 22:17:33 +02006from test.script_helper import assert_python_failure
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)
Anthony Baxterc2a5a632004-08-02 06:10:11 +000021 except parser.ParserError, why:
22 self.fail("could not roundtrip %r: %s" % (s, why))
Fred Drake79ca79d2000-08-21 22:30:53 +000023
Ezio Melotti2623a372010-11-21 13:34:58 +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 Petersondcee09d2008-10-31 02:16: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 in scope
Ezio Melottib0f5adc2010-01-24 16:58:36 +000037 self.assertIsInstance(scope["x"], unicode)
Benjamin Petersondcee09d2008-10-31 02:16: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
Fred Drake58422e52001-06-04 03:56:24 +000061 def test_expressions(self):
62 self.check_expr("foo(1)")
Alexandre Vassalottiee936a22010-01-09 23:35:54 +000063 self.check_expr("{1:1}")
64 self.check_expr("{1:1, 2:2, 3:3}")
65 self.check_expr("{1:1, 2:2, 3:3,}")
66 self.check_expr("{1}")
67 self.check_expr("{1, 2, 3}")
68 self.check_expr("{1, 2, 3,}")
69 self.check_expr("[]")
70 self.check_expr("[1]")
Fred Drake58422e52001-06-04 03:56:24 +000071 self.check_expr("[1, 2, 3]")
Alexandre Vassalottiee936a22010-01-09 23:35:54 +000072 self.check_expr("[1, 2, 3,]")
73 self.check_expr("()")
74 self.check_expr("(1,)")
75 self.check_expr("(1, 2, 3)")
76 self.check_expr("(1, 2, 3,)")
Fred Drake58422e52001-06-04 03:56:24 +000077 self.check_expr("[x**3 for x in range(20)]")
78 self.check_expr("[x**3 for x in range(20) if x % 3]")
Neal Norwitzd3a91622006-04-12 05:27:46 +000079 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
Alexandre Vassalottib6465472010-01-11 22:36:12 +000080 self.check_expr("[x+y for x in range(30) for y in range(20) if x % 2 if y % 3]")
81 #self.check_expr("[x for x in lambda: True, lambda: False if x()]")
Neal Norwitzd3a91622006-04-12 05:27:46 +000082 self.check_expr("list(x**3 for x in range(20))")
83 self.check_expr("list(x**3 for x in range(20) if x % 3)")
84 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Alexandre Vassalottib6465472010-01-11 22:36:12 +000085 self.check_expr("list(x+y for x in range(30) for y in range(20) if x % 2 if y % 3)")
86 self.check_expr("{x**3 for x in range(30)}")
87 self.check_expr("{x**3 for x in range(30) if x % 3}")
88 self.check_expr("{x**3 for x in range(30) if x % 2 if x % 3}")
89 self.check_expr("{x+y for x in range(30) for y in range(20) if x % 2 if y % 3}")
90 self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30))}")
91 self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30)) if x % 3}")
92 self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30)) if x % 3 if y % 3}")
93 self.check_expr("{x:y for x in range(30) for y in range(20) if x % 2 if y % 3}")
Fred Drake58422e52001-06-04 03:56:24 +000094 self.check_expr("foo(*args)")
95 self.check_expr("foo(*args, **kw)")
96 self.check_expr("foo(**kw)")
97 self.check_expr("foo(key=value)")
98 self.check_expr("foo(key=value, *args)")
99 self.check_expr("foo(key=value, *args, **kw)")
100 self.check_expr("foo(key=value, **kw)")
101 self.check_expr("foo(a, b, c, *args)")
102 self.check_expr("foo(a, b, c, *args, **kw)")
103 self.check_expr("foo(a, b, c, **kw)")
Benjamin Petersonbd6a05f2008-08-19 22:06:11 +0000104 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +0000105 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000106 self.check_expr("foo - bar")
107 self.check_expr("foo * bar")
108 self.check_expr("foo / bar")
109 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +0000110 self.check_expr("lambda: 0")
111 self.check_expr("lambda x: 0")
112 self.check_expr("lambda *y: 0")
113 self.check_expr("lambda *y, **z: 0")
114 self.check_expr("lambda **z: 0")
115 self.check_expr("lambda x, y: 0")
116 self.check_expr("lambda foo=bar: 0")
117 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
118 self.check_expr("lambda foo=bar, **z: 0")
119 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
120 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
121 self.check_expr("lambda x, *y, **z: 0")
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000122 self.check_expr("lambda x: 5 if x else 2")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000123 self.check_expr("(x for x in range(10))")
124 self.check_expr("foo(x for x in range(10))")
Fred Drake79ca79d2000-08-21 22:30:53 +0000125
Fred Drake58422e52001-06-04 03:56:24 +0000126 def test_print(self):
127 self.check_suite("print")
128 self.check_suite("print 1")
129 self.check_suite("print 1,")
130 self.check_suite("print >>fp")
131 self.check_suite("print >>fp, 1")
132 self.check_suite("print >>fp, 1,")
Fred Drake79ca79d2000-08-21 22:30:53 +0000133
Fred Drake58422e52001-06-04 03:56:24 +0000134 def test_simple_expression(self):
135 # expr_stmt
136 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000137
Fred Drake58422e52001-06-04 03:56:24 +0000138 def test_simple_assignments(self):
139 self.check_suite("a = b")
140 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000141
Fred Drake58422e52001-06-04 03:56:24 +0000142 def test_simple_augmented_assignments(self):
143 self.check_suite("a += b")
144 self.check_suite("a -= b")
145 self.check_suite("a *= b")
146 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000147 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000148 self.check_suite("a %= b")
149 self.check_suite("a &= b")
150 self.check_suite("a |= b")
151 self.check_suite("a ^= b")
152 self.check_suite("a <<= b")
153 self.check_suite("a >>= b")
154 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000155
Fred Drake58422e52001-06-04 03:56:24 +0000156 def test_function_defs(self):
157 self.check_suite("def f(): pass")
158 self.check_suite("def f(*args): pass")
159 self.check_suite("def f(*args, **kw): pass")
160 self.check_suite("def f(**kw): pass")
161 self.check_suite("def f(foo=bar): pass")
162 self.check_suite("def f(foo=bar, *args): pass")
163 self.check_suite("def f(foo=bar, *args, **kw): pass")
164 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000165
Fred Drake58422e52001-06-04 03:56:24 +0000166 self.check_suite("def f(a, b): pass")
167 self.check_suite("def f(a, b, *args): pass")
168 self.check_suite("def f(a, b, *args, **kw): pass")
169 self.check_suite("def f(a, b, **kw): pass")
170 self.check_suite("def f(a, b, foo=bar): pass")
171 self.check_suite("def f(a, b, foo=bar, *args): pass")
172 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
173 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000174
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000175 self.check_suite("@staticmethod\n"
176 "def f(): pass")
177 self.check_suite("@staticmethod\n"
178 "@funcattrs(x, y)\n"
179 "def f(): pass")
180 self.check_suite("@funcattrs()\n"
181 "def f(): pass")
182
Brett Cannonf4189912005-04-09 02:30:16 +0000183 def test_class_defs(self):
184 self.check_suite("class foo():pass")
Mark Dickinsona7ee59b2010-07-04 16:23:54 +0000185 self.check_suite("@class_decorator\n"
186 "class foo():pass")
187 self.check_suite("@class_decorator(arg)\n"
188 "class foo():pass")
189 self.check_suite("@decorator1\n"
190 "@decorator2\n"
191 "class foo():pass")
192
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 Peterson6624a9f2008-11-03 15:14:51 +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 Dickinson75b44b32010-07-04 16:47:56 +0000226 def test_relative_imports(self):
227 self.check_suite("from . import name")
228 self.check_suite("from .. import name")
229 self.check_suite("from .pkg import name")
230 self.check_suite("from ..pkg import name")
231
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000232 def test_pep263(self):
233 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
234 "pass\n")
235
236 def test_assert(self):
237 self.check_suite("assert alo < ahi and blo < bhi\n")
238
Benjamin Peterson9dfe6a82008-11-24 04:09:03 +0000239 def test_with(self):
240 self.check_suite("with open('x'): pass\n")
241 self.check_suite("with open('x') as f: pass\n")
Georg Brandl944f6842009-05-25 21:02:56 +0000242 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson9dfe6a82008-11-24 04:09:03 +0000243
Georg Brandlfe879e82008-12-05 12:09:41 +0000244 def test_try_stmt(self):
245 self.check_suite("try: pass\nexcept: pass\n")
246 self.check_suite("try: pass\nfinally: pass\n")
247 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
248 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
249 "finally: pass\n")
250 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
251 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
252 "finally: pass\n")
253
Mark Dickinson070f0ab2010-06-30 16:27:57 +0000254 def test_except_clause(self):
255 self.check_suite("try: pass\nexcept: pass\n")
256 self.check_suite("try: pass\nexcept A: pass\n")
257 self.check_suite("try: pass\nexcept A, e: pass\n")
258 self.check_suite("try: pass\nexcept A as e: pass\n")
259
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000260 def test_position(self):
261 # An absolutely minimal test of position information. Better
262 # tests would be a big project.
Benjamin Petersona4a04d12009-12-06 21:24:30 +0000263 code = "def f(x):\n return x + 1"
Jeremy Hylton60e96f62006-08-22 20:46:00 +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
Tim Peters147f9ae2006-08-25 22:05:39 +0000276
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000277 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 Petersona4a04d12009-12-06 21:24:30 +0000292 (6, '', 2, -1),
293 (4, '', 2, -1),
294 (0, '', 2, -1)],
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000295 terminals)
296
297
Fred Drake79ca79d2000-08-21 22:30:53 +0000298#
299# Second, we take *invalid* trees and make sure we get ParserError
300# rejections for them.
301#
302
Fred Drake58422e52001-06-04 03:56:24 +0000303class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000304
Fred Drake58422e52001-06-04 03:56:24 +0000305 def check_bad_tree(self, tree, label):
306 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000307 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000308 except parser.ParserError:
309 pass
310 else:
311 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000312
Fred Drake58422e52001-06-04 03:56:24 +0000313 def test_junk(self):
314 # not even remotely valid:
315 self.check_bad_tree((1, 2, 3), "<junk>")
316
Fred Drakecf580c72001-07-17 03:01:29 +0000317 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000318 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000319 tree = \
320 (257,
321 (264,
322 (285,
323 (259,
324 (1, 'def'),
325 (1, 'f'),
326 (260, (7, '('), (8, ')')),
327 (11, ':'),
328 (291,
329 (4, ''),
330 (5, ''),
331 (264,
332 (265,
333 (266,
334 (272,
335 (275,
336 (1, 'return'),
337 (313,
338 (292,
339 (293,
340 (294,
341 (295,
342 (297,
343 (298,
344 (299,
345 (300,
346 (301,
347 (302, (303, (304, (305, (2, '1')))))))))))))))))),
348 (264,
349 (265,
350 (266,
351 (272,
352 (276,
353 (1, 'yield'),
354 (313,
355 (292,
356 (293,
357 (294,
358 (295,
359 (297,
360 (298,
361 (299,
362 (300,
363 (301,
364 (302,
365 (303, (304, (305, (2, '1')))))))))))))))))),
366 (4, ''))),
367 (6, ''))))),
368 (4, ''),
369 (0, ''))))
370 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
371
372 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000373 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000374 tree = \
375 (257,
376 (264,
377 (265,
378 (266,
379 (278,
380 (1, 'from'),
381 (281, (1, '__future__')),
382 (1, 'import'),
383 (279, (1, 'generators')))),
384 (4, ''))),
385 (264,
386 (285,
387 (259,
388 (1, 'def'),
389 (1, 'f'),
390 (260, (7, '('), (8, ')')),
391 (11, ':'),
392 (291,
393 (4, ''),
394 (5, ''),
395 (264,
396 (265,
397 (266,
398 (272,
399 (275,
400 (1, 'return'),
401 (313,
402 (292,
403 (293,
404 (294,
405 (295,
406 (297,
407 (298,
408 (299,
409 (300,
410 (301,
411 (302, (303, (304, (305, (2, '1')))))))))))))))))),
412 (264,
413 (265,
414 (266,
415 (272,
416 (276,
417 (1, 'yield'),
418 (313,
419 (292,
420 (293,
421 (294,
422 (295,
423 (297,
424 (298,
425 (299,
426 (300,
427 (301,
428 (302,
429 (303, (304, (305, (2, '1')))))))))))))))))),
430 (4, ''))),
431 (6, ''))))),
432 (4, ''),
433 (0, ''))))
434 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
435
Fred Drake58422e52001-06-04 03:56:24 +0000436 def test_print_chevron_comma(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000437 # Illegal input: print >>fp,
Fred Drake58422e52001-06-04 03:56:24 +0000438 tree = \
439 (257,
440 (264,
441 (265,
442 (266,
443 (268,
444 (1, 'print'),
445 (35, '>>'),
446 (290,
447 (291,
448 (292,
449 (293,
450 (295,
451 (296,
452 (297,
453 (298, (299, (300, (301, (302, (303, (1, 'fp')))))))))))))),
454 (12, ','))),
455 (4, ''))),
456 (0, ''))
457 self.check_bad_tree(tree, "print >>fp,")
458
459 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000460 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000461 tree = \
462 (258,
463 (311,
464 (290,
465 (291,
466 (292,
467 (293,
468 (295,
469 (296,
470 (297,
471 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
472 (12, ','),
473 (12, ','),
474 (290,
475 (291,
476 (292,
477 (293,
478 (295,
479 (296,
480 (297,
481 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
482 (4, ''),
483 (0, ''))
484 self.check_bad_tree(tree, "a,,c")
485
486 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000487 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000488 tree = \
489 (257,
490 (264,
491 (265,
492 (266,
493 (267,
494 (312,
495 (291,
496 (292,
497 (293,
498 (294,
499 (296,
500 (297,
501 (298,
502 (299,
503 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
504 (268, (37, '$=')),
505 (312,
506 (291,
507 (292,
508 (293,
509 (294,
510 (296,
511 (297,
512 (298,
513 (299,
514 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
515 (4, ''))),
516 (0, ''))
517 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000518
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000519 def test_malformed_global(self):
520 #doesn't have global keyword in ast
521 tree = (257,
522 (264,
523 (265,
524 (266,
525 (282, (1, 'foo'))), (4, ''))),
526 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000527 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000528 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000529
Mark Dickinson75b44b32010-07-04 16:47:56 +0000530 def test_missing_import_source(self):
531 # from import a
532 tree = \
533 (257,
534 (267,
535 (268,
536 (269,
537 (281,
538 (283, (1, 'from'), (1, 'import'),
539 (286, (284, (1, 'fred')))))),
540 (4, ''))),
541 (4, ''), (0, ''))
542 self.check_bad_tree(tree, "from import a")
543
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000544
545class CompileTestCase(unittest.TestCase):
546
547 # These tests are very minimal. :-(
548
549 def test_compile_expr(self):
550 st = parser.expr('2 + 3')
551 code = parser.compilest(st)
Ezio Melotti2623a372010-11-21 13:34:58 +0000552 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000553
554 def test_compile_suite(self):
555 st = parser.suite('x = 2; y = x + 3')
556 code = parser.compilest(st)
557 globs = {}
558 exec code in globs
Ezio Melotti2623a372010-11-21 13:34:58 +0000559 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000560
561 def test_compile_error(self):
562 st = parser.suite('1 = 3 + 4')
563 self.assertRaises(SyntaxError, parser.compilest, st)
564
Guido van Rossumb6ac23c2007-07-18 17:19:14 +0000565 def test_compile_badunicode(self):
566 st = parser.suite('a = u"\U12345678"')
567 self.assertRaises(SyntaxError, parser.compilest, st)
568 st = parser.suite('a = u"\u1"')
569 self.assertRaises(SyntaxError, parser.compilest, st)
570
Mark Dickinsonb1cc6aa2012-11-25 17:11:33 +0000571 def test_issue_9011(self):
572 # Issue 9011: compilation of an unary minus expression changed
573 # the meaning of the ST, so that a second compilation produced
574 # incorrect results.
575 st = parser.expr('-3')
576 code1 = parser.compilest(st)
577 self.assertEqual(eval(code1), -3)
578 code2 = parser.compilest(st)
579 self.assertEqual(eval(code2), -3)
580
581
Facundo Batistafc2d0102008-02-23 12:01:13 +0000582class ParserStackLimitTestCase(unittest.TestCase):
Ezio Melottida9eeae2013-03-09 22:17:33 +0200583 """try to push the parser to/over its limits.
Facundo Batistafc2d0102008-02-23 12:01:13 +0000584 see http://bugs.python.org/issue1881 for a discussion
585 """
586 def _nested_expression(self, level):
587 return "["*level+"]"*level
588
589 def test_deeply_nested_list(self):
590 e = self._nested_expression(99)
591 st = parser.expr(e)
592 st.compile()
593
594 def test_trigger_memory_error(self):
595 e = self._nested_expression(100)
Ezio Melottida9eeae2013-03-09 22:17:33 +0200596 rc, out, err = assert_python_failure('-c', e)
597 # parsing the expression will result in an error message
598 # followed by a MemoryError (see #11963)
Ezio Melottic5267042013-03-10 03:25:45 +0200599 self.assertIn(b's_push: parser stack overflow', err)
600 self.assertIn(b'MemoryError', err)
Facundo Batistafc2d0102008-02-23 12:01:13 +0000601
Jesus Cea3e3192d2012-08-03 14:25:53 +0200602class STObjectTestCase(unittest.TestCase):
603 """Test operations on ST objects themselves"""
604
605 check_sizeof = support.check_sizeof
606
607 @support.cpython_only
608 def test_sizeof(self):
609 def XXXROUNDUP(n):
610 if n <= 1:
611 return n
612 if n <= 128:
613 return (n + 3) & ~3
614 return 1 << (n - 1).bit_length()
615
616 basesize = support.calcobjsize('Pii')
617 nodesize = struct.calcsize('hP3iP0h')
618 def sizeofchildren(node):
619 if node is None:
620 return 0
621 res = 0
622 hasstr = len(node) > 1 and isinstance(node[-1], str)
623 if hasstr:
624 res += len(node[-1]) + 1
625 children = node[1:-1] if hasstr else node[1:]
626 if children:
627 res += XXXROUNDUP(len(children)) * nodesize
Jesus Cea3e3192d2012-08-03 14:25:53 +0200628 for child in children:
629 res += sizeofchildren(child)
630 return res
631
632 def check_st_sizeof(st):
633 self.check_sizeof(st, basesize + nodesize +
634 sizeofchildren(st.totuple()))
635
636 check_st_sizeof(parser.expr('2 + 3'))
637 check_st_sizeof(parser.expr('2 + 3 + 4'))
638 check_st_sizeof(parser.suite('x = 2 + 3'))
639 check_st_sizeof(parser.suite(''))
640 check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
641 check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
642
643
644 # XXX tests for pickling and unpickling of ST objects should go here
645
Fred Drake2e2be372001-09-20 21:33:42 +0000646def test_main():
Jesus Cea3e3192d2012-08-03 14:25:53 +0200647 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000648 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000649 IllegalSyntaxTestCase,
650 CompileTestCase,
Facundo Batistafc2d0102008-02-23 12:01:13 +0000651 ParserStackLimitTestCase,
Jesus Cea3e3192d2012-08-03 14:25:53 +0200652 STObjectTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000653 )
Fred Drake2e2be372001-09-20 21:33:42 +0000654
655
656if __name__ == "__main__":
657 test_main()