blob: c6900de634444f51375c5c2a36c983d9b0c11f4e [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
Fred Drake79ca79d2000-08-21 22:30:53 +00006
7#
8# First, we test that we can generate trees from valid source fragments,
9# and that these valid trees are indeed allowed by the tree-loading side
10# of the parser module.
11#
12
Fred Drake58422e52001-06-04 03:56:24 +000013class RoundtripLegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +000014
Fred Drake58422e52001-06-04 03:56:24 +000015 def roundtrip(self, f, s):
16 st1 = f(s)
17 t = st1.totuple()
18 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +000019 st2 = parser.sequence2st(t)
Anthony Baxterc2a5a632004-08-02 06:10:11 +000020 except parser.ParserError, why:
21 self.fail("could not roundtrip %r: %s" % (s, why))
Fred Drake79ca79d2000-08-21 22:30:53 +000022
Ezio Melotti2623a372010-11-21 13:34:58 +000023 self.assertEqual(t, st2.totuple(),
24 "could not re-generate syntax tree")
Fred Drake28f739a2000-08-25 22:42:40 +000025
Fred Drake58422e52001-06-04 03:56:24 +000026 def check_expr(self, s):
27 self.roundtrip(parser.expr, s)
Fred Drake28f739a2000-08-25 22:42:40 +000028
Benjamin Petersondcee09d2008-10-31 02:16:05 +000029 def test_flags_passed(self):
30 # The unicode literals flags has to be passed from the paser to AST
31 # generation.
32 suite = parser.suite("from __future__ import unicode_literals; x = ''")
33 code = suite.compile()
34 scope = {}
35 exec code in scope
Ezio Melottib0f5adc2010-01-24 16:58:36 +000036 self.assertIsInstance(scope["x"], unicode)
Benjamin Petersondcee09d2008-10-31 02:16:05 +000037
Fred Drake58422e52001-06-04 03:56:24 +000038 def check_suite(self, s):
39 self.roundtrip(parser.suite, s)
Fred Drake28f739a2000-08-25 22:42:40 +000040
Fred Drakecf580c72001-07-17 03:01:29 +000041 def test_yield_statement(self):
Tim Peters496563a2002-04-01 00:28:59 +000042 self.check_suite("def f(): yield 1")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000043 self.check_suite("def f(): yield")
44 self.check_suite("def f(): x += yield")
45 self.check_suite("def f(): x = yield 1")
46 self.check_suite("def f(): x = y = yield 1")
47 self.check_suite("def f(): x = yield")
48 self.check_suite("def f(): x = y = yield")
49 self.check_suite("def f(): 1 + (yield)*2")
50 self.check_suite("def f(): (yield 1)*2")
Tim Peters496563a2002-04-01 00:28:59 +000051 self.check_suite("def f(): return; yield 1")
52 self.check_suite("def f(): yield 1; return")
53 self.check_suite("def f():\n"
Fred Drakecf580c72001-07-17 03:01:29 +000054 " for x in range(30):\n"
55 " yield x\n")
Phillip J. Eby0d6615f2005-08-02 00:46:46 +000056 self.check_suite("def f():\n"
57 " if (yield):\n"
58 " yield x\n")
Fred Drakecf580c72001-07-17 03:01:29 +000059
Fred Drake58422e52001-06-04 03:56:24 +000060 def test_expressions(self):
61 self.check_expr("foo(1)")
Alexandre Vassalottiee936a22010-01-09 23:35:54 +000062 self.check_expr("{1:1}")
63 self.check_expr("{1:1, 2:2, 3:3}")
64 self.check_expr("{1:1, 2:2, 3:3,}")
65 self.check_expr("{1}")
66 self.check_expr("{1, 2, 3}")
67 self.check_expr("{1, 2, 3,}")
68 self.check_expr("[]")
69 self.check_expr("[1]")
Fred Drake58422e52001-06-04 03:56:24 +000070 self.check_expr("[1, 2, 3]")
Alexandre Vassalottiee936a22010-01-09 23:35:54 +000071 self.check_expr("[1, 2, 3,]")
72 self.check_expr("()")
73 self.check_expr("(1,)")
74 self.check_expr("(1, 2, 3)")
75 self.check_expr("(1, 2, 3,)")
Fred Drake58422e52001-06-04 03:56:24 +000076 self.check_expr("[x**3 for x in range(20)]")
77 self.check_expr("[x**3 for x in range(20) if x % 3]")
Neal Norwitzd3a91622006-04-12 05:27:46 +000078 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
Alexandre Vassalottib6465472010-01-11 22:36:12 +000079 self.check_expr("[x+y for x in range(30) for y in range(20) if x % 2 if y % 3]")
80 #self.check_expr("[x for x in lambda: True, lambda: False if x()]")
Neal Norwitzd3a91622006-04-12 05:27:46 +000081 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)")
Alexandre Vassalottib6465472010-01-11 22:36:12 +000084 self.check_expr("list(x+y for x in range(30) for y in range(20) if x % 2 if y % 3)")
85 self.check_expr("{x**3 for x in range(30)}")
86 self.check_expr("{x**3 for x in range(30) if x % 3}")
87 self.check_expr("{x**3 for x in range(30) if x % 2 if x % 3}")
88 self.check_expr("{x+y for x in range(30) for y in range(20) if x % 2 if y % 3}")
89 self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30))}")
90 self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30)) if x % 3}")
91 self.check_expr("{x**3: y**2 for x, y in zip(range(30), range(30)) if x % 3 if y % 3}")
92 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 +000093 self.check_expr("foo(*args)")
94 self.check_expr("foo(*args, **kw)")
95 self.check_expr("foo(**kw)")
96 self.check_expr("foo(key=value)")
97 self.check_expr("foo(key=value, *args)")
98 self.check_expr("foo(key=value, *args, **kw)")
99 self.check_expr("foo(key=value, **kw)")
100 self.check_expr("foo(a, b, c, *args)")
101 self.check_expr("foo(a, b, c, *args, **kw)")
102 self.check_expr("foo(a, b, c, **kw)")
Benjamin Petersonbd6a05f2008-08-19 22:06:11 +0000103 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +0000104 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000105 self.check_expr("foo - bar")
106 self.check_expr("foo * bar")
107 self.check_expr("foo / bar")
108 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +0000109 self.check_expr("lambda: 0")
110 self.check_expr("lambda x: 0")
111 self.check_expr("lambda *y: 0")
112 self.check_expr("lambda *y, **z: 0")
113 self.check_expr("lambda **z: 0")
114 self.check_expr("lambda x, y: 0")
115 self.check_expr("lambda foo=bar: 0")
116 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
117 self.check_expr("lambda foo=bar, **z: 0")
118 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
119 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
120 self.check_expr("lambda x, *y, **z: 0")
Alexandre Vassalottib6465472010-01-11 22:36:12 +0000121 self.check_expr("lambda x: 5 if x else 2")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000122 self.check_expr("(x for x in range(10))")
123 self.check_expr("foo(x for x in range(10))")
Fred Drake79ca79d2000-08-21 22:30:53 +0000124
Fred Drake58422e52001-06-04 03:56:24 +0000125 def test_print(self):
126 self.check_suite("print")
127 self.check_suite("print 1")
128 self.check_suite("print 1,")
129 self.check_suite("print >>fp")
130 self.check_suite("print >>fp, 1")
131 self.check_suite("print >>fp, 1,")
Fred Drake79ca79d2000-08-21 22:30:53 +0000132
Fred Drake58422e52001-06-04 03:56:24 +0000133 def test_simple_expression(self):
134 # expr_stmt
135 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000136
Fred Drake58422e52001-06-04 03:56:24 +0000137 def test_simple_assignments(self):
138 self.check_suite("a = b")
139 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000140
Fred Drake58422e52001-06-04 03:56:24 +0000141 def test_simple_augmented_assignments(self):
142 self.check_suite("a += b")
143 self.check_suite("a -= b")
144 self.check_suite("a *= b")
145 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000146 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000147 self.check_suite("a %= b")
148 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")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000154
Fred Drake58422e52001-06-04 03:56:24 +0000155 def test_function_defs(self):
156 self.check_suite("def f(): pass")
157 self.check_suite("def f(*args): pass")
158 self.check_suite("def f(*args, **kw): pass")
159 self.check_suite("def f(**kw): pass")
160 self.check_suite("def f(foo=bar): pass")
161 self.check_suite("def f(foo=bar, *args): pass")
162 self.check_suite("def f(foo=bar, *args, **kw): pass")
163 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000164
Fred Drake58422e52001-06-04 03:56:24 +0000165 self.check_suite("def f(a, b): pass")
166 self.check_suite("def f(a, b, *args): pass")
167 self.check_suite("def f(a, b, *args, **kw): pass")
168 self.check_suite("def f(a, b, **kw): pass")
169 self.check_suite("def f(a, b, foo=bar): pass")
170 self.check_suite("def f(a, b, foo=bar, *args): pass")
171 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
172 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000173
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000174 self.check_suite("@staticmethod\n"
175 "def f(): pass")
176 self.check_suite("@staticmethod\n"
177 "@funcattrs(x, y)\n"
178 "def f(): pass")
179 self.check_suite("@funcattrs()\n"
180 "def f(): pass")
181
Brett Cannonf4189912005-04-09 02:30:16 +0000182 def test_class_defs(self):
183 self.check_suite("class foo():pass")
Mark Dickinsona7ee59b2010-07-04 16:23:54 +0000184 self.check_suite("@class_decorator\n"
185 "class foo():pass")
186 self.check_suite("@class_decorator(arg)\n"
187 "class foo():pass")
188 self.check_suite("@decorator1\n"
189 "@decorator2\n"
190 "class foo():pass")
191
Tim Peterse8906822005-04-20 17:45:13 +0000192
Fred Drake58422e52001-06-04 03:56:24 +0000193 def test_import_from_statement(self):
194 self.check_suite("from sys.path import *")
195 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000196 self.check_suite("from sys.path import (dirname)")
197 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000198 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000199 self.check_suite("from sys.path import (dirname as my_dirname)")
200 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000201 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000202 self.check_suite("from sys.path import (dirname, basename)")
203 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000204 self.check_suite(
205 "from sys.path import dirname as my_dirname, basename")
206 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000207 "from sys.path import (dirname as my_dirname, basename)")
208 self.check_suite(
209 "from sys.path import (dirname as my_dirname, basename,)")
210 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000211 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000212 self.check_suite(
213 "from sys.path import (dirname, basename as my_basename)")
214 self.check_suite(
215 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Peterson6624a9f2008-11-03 15:14:51 +0000216 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000217
Fred Drake58422e52001-06-04 03:56:24 +0000218 def test_basic_import_statement(self):
219 self.check_suite("import sys")
220 self.check_suite("import sys as system")
221 self.check_suite("import sys, math")
222 self.check_suite("import sys as system, math")
223 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000224
Mark Dickinson75b44b32010-07-04 16:47:56 +0000225 def test_relative_imports(self):
226 self.check_suite("from . import name")
227 self.check_suite("from .. import name")
228 self.check_suite("from .pkg import name")
229 self.check_suite("from ..pkg import name")
230
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000231 def test_pep263(self):
232 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
233 "pass\n")
234
235 def test_assert(self):
236 self.check_suite("assert alo < ahi and blo < bhi\n")
237
Benjamin Peterson9dfe6a82008-11-24 04:09:03 +0000238 def test_with(self):
239 self.check_suite("with open('x'): pass\n")
240 self.check_suite("with open('x') as f: pass\n")
Georg Brandl944f6842009-05-25 21:02:56 +0000241 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson9dfe6a82008-11-24 04:09:03 +0000242
Georg Brandlfe879e82008-12-05 12:09:41 +0000243 def test_try_stmt(self):
244 self.check_suite("try: pass\nexcept: pass\n")
245 self.check_suite("try: pass\nfinally: pass\n")
246 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
247 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
248 "finally: pass\n")
249 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
250 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
251 "finally: pass\n")
252
Mark Dickinson070f0ab2010-06-30 16:27:57 +0000253 def test_except_clause(self):
254 self.check_suite("try: pass\nexcept: pass\n")
255 self.check_suite("try: pass\nexcept A: pass\n")
256 self.check_suite("try: pass\nexcept A, e: pass\n")
257 self.check_suite("try: pass\nexcept A as e: pass\n")
258
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000259 def test_position(self):
260 # An absolutely minimal test of position information. Better
261 # tests would be a big project.
Benjamin Petersona4a04d12009-12-06 21:24:30 +0000262 code = "def f(x):\n return x + 1"
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000263 st1 = parser.suite(code)
264 st2 = st1.totuple(line_info=1, col_info=1)
265
266 def walk(tree):
267 node_type = tree[0]
268 next = tree[1]
269 if isinstance(next, tuple):
270 for elt in tree[1:]:
271 for x in walk(elt):
272 yield x
273 else:
274 yield tree
Tim Peters147f9ae2006-08-25 22:05:39 +0000275
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000276 terminals = list(walk(st2))
277 self.assertEqual([
278 (1, 'def', 1, 0),
279 (1, 'f', 1, 4),
280 (7, '(', 1, 5),
281 (1, 'x', 1, 6),
282 (8, ')', 1, 7),
283 (11, ':', 1, 8),
284 (4, '', 1, 9),
285 (5, '', 2, -1),
286 (1, 'return', 2, 4),
287 (1, 'x', 2, 11),
288 (14, '+', 2, 13),
289 (2, '1', 2, 15),
290 (4, '', 2, 16),
Benjamin Petersona4a04d12009-12-06 21:24:30 +0000291 (6, '', 2, -1),
292 (4, '', 2, -1),
293 (0, '', 2, -1)],
Jeremy Hylton60e96f62006-08-22 20:46:00 +0000294 terminals)
295
296
Fred Drake79ca79d2000-08-21 22:30:53 +0000297#
298# Second, we take *invalid* trees and make sure we get ParserError
299# rejections for them.
300#
301
Fred Drake58422e52001-06-04 03:56:24 +0000302class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000303
Fred Drake58422e52001-06-04 03:56:24 +0000304 def check_bad_tree(self, tree, label):
305 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000306 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000307 except parser.ParserError:
308 pass
309 else:
310 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000311
Fred Drake58422e52001-06-04 03:56:24 +0000312 def test_junk(self):
313 # not even remotely valid:
314 self.check_bad_tree((1, 2, 3), "<junk>")
315
Fred Drakecf580c72001-07-17 03:01:29 +0000316 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000317 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000318 tree = \
319 (257,
320 (264,
321 (285,
322 (259,
323 (1, 'def'),
324 (1, 'f'),
325 (260, (7, '('), (8, ')')),
326 (11, ':'),
327 (291,
328 (4, ''),
329 (5, ''),
330 (264,
331 (265,
332 (266,
333 (272,
334 (275,
335 (1, 'return'),
336 (313,
337 (292,
338 (293,
339 (294,
340 (295,
341 (297,
342 (298,
343 (299,
344 (300,
345 (301,
346 (302, (303, (304, (305, (2, '1')))))))))))))))))),
347 (264,
348 (265,
349 (266,
350 (272,
351 (276,
352 (1, 'yield'),
353 (313,
354 (292,
355 (293,
356 (294,
357 (295,
358 (297,
359 (298,
360 (299,
361 (300,
362 (301,
363 (302,
364 (303, (304, (305, (2, '1')))))))))))))))))),
365 (4, ''))),
366 (6, ''))))),
367 (4, ''),
368 (0, ''))))
369 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
370
371 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000372 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000373 tree = \
374 (257,
375 (264,
376 (265,
377 (266,
378 (278,
379 (1, 'from'),
380 (281, (1, '__future__')),
381 (1, 'import'),
382 (279, (1, 'generators')))),
383 (4, ''))),
384 (264,
385 (285,
386 (259,
387 (1, 'def'),
388 (1, 'f'),
389 (260, (7, '('), (8, ')')),
390 (11, ':'),
391 (291,
392 (4, ''),
393 (5, ''),
394 (264,
395 (265,
396 (266,
397 (272,
398 (275,
399 (1, 'return'),
400 (313,
401 (292,
402 (293,
403 (294,
404 (295,
405 (297,
406 (298,
407 (299,
408 (300,
409 (301,
410 (302, (303, (304, (305, (2, '1')))))))))))))))))),
411 (264,
412 (265,
413 (266,
414 (272,
415 (276,
416 (1, 'yield'),
417 (313,
418 (292,
419 (293,
420 (294,
421 (295,
422 (297,
423 (298,
424 (299,
425 (300,
426 (301,
427 (302,
428 (303, (304, (305, (2, '1')))))))))))))))))),
429 (4, ''))),
430 (6, ''))))),
431 (4, ''),
432 (0, ''))))
433 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
434
Fred Drake58422e52001-06-04 03:56:24 +0000435 def test_print_chevron_comma(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000436 # Illegal input: print >>fp,
Fred Drake58422e52001-06-04 03:56:24 +0000437 tree = \
438 (257,
439 (264,
440 (265,
441 (266,
442 (268,
443 (1, 'print'),
444 (35, '>>'),
445 (290,
446 (291,
447 (292,
448 (293,
449 (295,
450 (296,
451 (297,
452 (298, (299, (300, (301, (302, (303, (1, 'fp')))))))))))))),
453 (12, ','))),
454 (4, ''))),
455 (0, ''))
456 self.check_bad_tree(tree, "print >>fp,")
457
458 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000459 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000460 tree = \
461 (258,
462 (311,
463 (290,
464 (291,
465 (292,
466 (293,
467 (295,
468 (296,
469 (297,
470 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
471 (12, ','),
472 (12, ','),
473 (290,
474 (291,
475 (292,
476 (293,
477 (295,
478 (296,
479 (297,
480 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
481 (4, ''),
482 (0, ''))
483 self.check_bad_tree(tree, "a,,c")
484
485 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000486 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000487 tree = \
488 (257,
489 (264,
490 (265,
491 (266,
492 (267,
493 (312,
494 (291,
495 (292,
496 (293,
497 (294,
498 (296,
499 (297,
500 (298,
501 (299,
502 (300, (301, (302, (303, (304, (1, 'a'))))))))))))))),
503 (268, (37, '$=')),
504 (312,
505 (291,
506 (292,
507 (293,
508 (294,
509 (296,
510 (297,
511 (298,
512 (299,
513 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
514 (4, ''))),
515 (0, ''))
516 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000517
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000518 def test_malformed_global(self):
519 #doesn't have global keyword in ast
520 tree = (257,
521 (264,
522 (265,
523 (266,
524 (282, (1, 'foo'))), (4, ''))),
525 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000526 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000527 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000528
Mark Dickinson75b44b32010-07-04 16:47:56 +0000529 def test_missing_import_source(self):
530 # from import a
531 tree = \
532 (257,
533 (267,
534 (268,
535 (269,
536 (281,
537 (283, (1, 'from'), (1, 'import'),
538 (286, (284, (1, 'fred')))))),
539 (4, ''))),
540 (4, ''), (0, ''))
541 self.check_bad_tree(tree, "from import a")
542
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000543
544class CompileTestCase(unittest.TestCase):
545
546 # These tests are very minimal. :-(
547
548 def test_compile_expr(self):
549 st = parser.expr('2 + 3')
550 code = parser.compilest(st)
Ezio Melotti2623a372010-11-21 13:34:58 +0000551 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000552
553 def test_compile_suite(self):
554 st = parser.suite('x = 2; y = x + 3')
555 code = parser.compilest(st)
556 globs = {}
557 exec code in globs
Ezio Melotti2623a372010-11-21 13:34:58 +0000558 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000559
560 def test_compile_error(self):
561 st = parser.suite('1 = 3 + 4')
562 self.assertRaises(SyntaxError, parser.compilest, st)
563
Guido van Rossumb6ac23c2007-07-18 17:19:14 +0000564 def test_compile_badunicode(self):
565 st = parser.suite('a = u"\U12345678"')
566 self.assertRaises(SyntaxError, parser.compilest, st)
567 st = parser.suite('a = u"\u1"')
568 self.assertRaises(SyntaxError, parser.compilest, st)
569
Facundo Batistafc2d0102008-02-23 12:01:13 +0000570class ParserStackLimitTestCase(unittest.TestCase):
571 """try to push the parser to/over it's limits.
572 see http://bugs.python.org/issue1881 for a discussion
573 """
574 def _nested_expression(self, level):
575 return "["*level+"]"*level
576
577 def test_deeply_nested_list(self):
578 e = self._nested_expression(99)
579 st = parser.expr(e)
580 st.compile()
581
582 def test_trigger_memory_error(self):
583 e = self._nested_expression(100)
Martin v. Löwis66e26632008-03-18 13:16:05 +0000584 print >>sys.stderr, "Expecting 's_push: parser stack overflow' in next line"
Facundo Batistafc2d0102008-02-23 12:01:13 +0000585 self.assertRaises(MemoryError, parser.expr, e)
586
Jesus Cea3e3192d2012-08-03 14:25:53 +0200587class STObjectTestCase(unittest.TestCase):
588 """Test operations on ST objects themselves"""
589
590 check_sizeof = support.check_sizeof
591
592 @support.cpython_only
593 def test_sizeof(self):
594 def XXXROUNDUP(n):
595 if n <= 1:
596 return n
597 if n <= 128:
598 return (n + 3) & ~3
599 return 1 << (n - 1).bit_length()
600
601 basesize = support.calcobjsize('Pii')
602 nodesize = struct.calcsize('hP3iP0h')
603 def sizeofchildren(node):
604 if node is None:
605 return 0
606 res = 0
607 hasstr = len(node) > 1 and isinstance(node[-1], str)
608 if hasstr:
609 res += len(node[-1]) + 1
610 children = node[1:-1] if hasstr else node[1:]
611 if children:
612 res += XXXROUNDUP(len(children)) * nodesize
613 res1 = res
614 if children:
615 for child in children:
616 res += sizeofchildren(child)
617 return res
618
619 def check_st_sizeof(st):
620 self.check_sizeof(st, basesize + nodesize +
621 sizeofchildren(st.totuple()))
622
623 check_st_sizeof(parser.expr('2 + 3'))
624 check_st_sizeof(parser.expr('2 + 3 + 4'))
625 check_st_sizeof(parser.suite('x = 2 + 3'))
626 check_st_sizeof(parser.suite(''))
627 check_st_sizeof(parser.suite('# -*- coding: utf-8 -*-'))
628 check_st_sizeof(parser.expr('[' + '2,' * 1000 + ']'))
629
630
631 # XXX tests for pickling and unpickling of ST objects should go here
632
Fred Drake2e2be372001-09-20 21:33:42 +0000633def test_main():
Jesus Cea3e3192d2012-08-03 14:25:53 +0200634 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000635 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000636 IllegalSyntaxTestCase,
637 CompileTestCase,
Facundo Batistafc2d0102008-02-23 12:01:13 +0000638 ParserStackLimitTestCase,
Jesus Cea3e3192d2012-08-03 14:25:53 +0200639 STObjectTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000640 )
Fred Drake2e2be372001-09-20 21:33:42 +0000641
642
643if __name__ == "__main__":
644 test_main()