blob: 50dc8d14fdf45fdc4559cc5cdb0784d44e4586e3 [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +00005from test import 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)
Guido van Rossumb940e112007-01-10 16:19:56 +000020 except parser.ParserError as why:
Anthony Baxterc2a5a632004-08-02 06:10:11 +000021 self.fail("could not roundtrip %r: %s" % (s, why))
Fred Drake79ca79d2000-08-21 22:30:53 +000022
Ezio Melottib3aedd42010-11-20 19:04:17 +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 Petersonf216c942008-10-31 02:28: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, {}, scope)
Ezio Melottie9615932010-01-24 19:26:24 +000036 self.assertIsInstance(scope["x"], str)
Benjamin Petersonf216c942008-10-31 02:28: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
Mark Dickinson407b3bd2012-04-29 22:18:31 +010060 def test_nonlocal_statement(self):
61 self.check_suite("def f():\n"
62 " x = 0\n"
63 " def g():\n"
64 " nonlocal x\n")
65 self.check_suite("def f():\n"
66 " x = y = 0\n"
67 " def g():\n"
68 " nonlocal x, y\n")
69
Fred Drake58422e52001-06-04 03:56:24 +000070 def test_expressions(self):
71 self.check_expr("foo(1)")
72 self.check_expr("[1, 2, 3]")
73 self.check_expr("[x**3 for x in range(20)]")
74 self.check_expr("[x**3 for x in range(20) if x % 3]")
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000075 self.check_expr("[x**3 for x in range(20) if x % 2 if x % 3]")
76 self.check_expr("list(x**3 for x in range(20))")
77 self.check_expr("list(x**3 for x in range(20) if x % 3)")
78 self.check_expr("list(x**3 for x in range(20) if x % 2 if x % 3)")
Fred Drake58422e52001-06-04 03:56:24 +000079 self.check_expr("foo(*args)")
80 self.check_expr("foo(*args, **kw)")
81 self.check_expr("foo(**kw)")
82 self.check_expr("foo(key=value)")
83 self.check_expr("foo(key=value, *args)")
84 self.check_expr("foo(key=value, *args, **kw)")
85 self.check_expr("foo(key=value, **kw)")
86 self.check_expr("foo(a, b, c, *args)")
87 self.check_expr("foo(a, b, c, *args, **kw)")
88 self.check_expr("foo(a, b, c, **kw)")
Benjamin Peterson3938a902008-08-20 02:33:00 +000089 self.check_expr("foo(a, *args, keyword=23)")
Fred Drake58422e52001-06-04 03:56:24 +000090 self.check_expr("foo + bar")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +000091 self.check_expr("foo - bar")
92 self.check_expr("foo * bar")
93 self.check_expr("foo / bar")
94 self.check_expr("foo // bar")
Fred Drake58422e52001-06-04 03:56:24 +000095 self.check_expr("lambda: 0")
96 self.check_expr("lambda x: 0")
97 self.check_expr("lambda *y: 0")
98 self.check_expr("lambda *y, **z: 0")
99 self.check_expr("lambda **z: 0")
100 self.check_expr("lambda x, y: 0")
101 self.check_expr("lambda foo=bar: 0")
102 self.check_expr("lambda foo=bar, spaz=nifty+spit: 0")
103 self.check_expr("lambda foo=bar, **z: 0")
104 self.check_expr("lambda foo=bar, blaz=blat+2, **z: 0")
105 self.check_expr("lambda foo=bar, blaz=blat+2, *y, **z: 0")
106 self.check_expr("lambda x, *y, **z: 0")
Raymond Hettinger354433a2004-05-19 08:20:33 +0000107 self.check_expr("(x for x in range(10))")
108 self.check_expr("foo(x for x in range(10))")
Fred Drake79ca79d2000-08-21 22:30:53 +0000109
Fred Drake58422e52001-06-04 03:56:24 +0000110 def test_simple_expression(self):
111 # expr_stmt
112 self.check_suite("a")
Fred Drake79ca79d2000-08-21 22:30:53 +0000113
Fred Drake58422e52001-06-04 03:56:24 +0000114 def test_simple_assignments(self):
115 self.check_suite("a = b")
116 self.check_suite("a = b = c = d = e")
Fred Drake28f739a2000-08-25 22:42:40 +0000117
Fred Drake58422e52001-06-04 03:56:24 +0000118 def test_simple_augmented_assignments(self):
119 self.check_suite("a += b")
120 self.check_suite("a -= b")
121 self.check_suite("a *= b")
122 self.check_suite("a /= b")
Michael W. Hudson5e83b7a2003-01-29 14:20:23 +0000123 self.check_suite("a //= b")
Fred Drake58422e52001-06-04 03:56:24 +0000124 self.check_suite("a %= b")
125 self.check_suite("a &= b")
126 self.check_suite("a |= b")
127 self.check_suite("a ^= b")
128 self.check_suite("a <<= b")
129 self.check_suite("a >>= b")
130 self.check_suite("a **= b")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000131
Fred Drake58422e52001-06-04 03:56:24 +0000132 def test_function_defs(self):
133 self.check_suite("def f(): pass")
134 self.check_suite("def f(*args): pass")
135 self.check_suite("def f(*args, **kw): pass")
136 self.check_suite("def f(**kw): pass")
137 self.check_suite("def f(foo=bar): pass")
138 self.check_suite("def f(foo=bar, *args): pass")
139 self.check_suite("def f(foo=bar, *args, **kw): pass")
140 self.check_suite("def f(foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000141
Fred Drake58422e52001-06-04 03:56:24 +0000142 self.check_suite("def f(a, b): pass")
143 self.check_suite("def f(a, b, *args): pass")
144 self.check_suite("def f(a, b, *args, **kw): pass")
145 self.check_suite("def f(a, b, **kw): pass")
146 self.check_suite("def f(a, b, foo=bar): pass")
147 self.check_suite("def f(a, b, foo=bar, *args): pass")
148 self.check_suite("def f(a, b, foo=bar, *args, **kw): pass")
149 self.check_suite("def f(a, b, foo=bar, **kw): pass")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000150
Anthony Baxterc2a5a632004-08-02 06:10:11 +0000151 self.check_suite("@staticmethod\n"
152 "def f(): pass")
153 self.check_suite("@staticmethod\n"
154 "@funcattrs(x, y)\n"
155 "def f(): pass")
156 self.check_suite("@funcattrs()\n"
157 "def f(): pass")
158
Mark Dickinsonea7e9f92012-04-29 18:34:40 +0100159 # keyword-only arguments
160 self.check_suite("def f(*, a): pass")
161 self.check_suite("def f(*, a = 5): pass")
162 self.check_suite("def f(*, a = 5, b): pass")
163 self.check_suite("def f(*, a, b = 5): pass")
164 self.check_suite("def f(*, a, b = 5, **kwds): pass")
165 self.check_suite("def f(*args, a): pass")
166 self.check_suite("def f(*args, a = 5): pass")
167 self.check_suite("def f(*args, a = 5, b): pass")
168 self.check_suite("def f(*args, a, b = 5): pass")
169 self.check_suite("def f(*args, a, b = 5, **kwds): pass")
170
171 # function annotations
172 self.check_suite("def f(a: int): pass")
173 self.check_suite("def f(a: int = 5): pass")
174 self.check_suite("def f(*args: list): pass")
175 self.check_suite("def f(**kwds: dict): pass")
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() -> int: pass")
179
Brett Cannonf4189912005-04-09 02:30:16 +0000180 def test_class_defs(self):
181 self.check_suite("class foo():pass")
Guido van Rossumfc158e22007-11-15 19:17:28 +0000182 self.check_suite("class foo(object):pass")
Mark Dickinson2bd61a92010-07-04 16:37:31 +0000183 self.check_suite("@class_decorator\n"
184 "class foo():pass")
185 self.check_suite("@class_decorator(arg)\n"
186 "class foo():pass")
187 self.check_suite("@decorator1\n"
188 "@decorator2\n"
189 "class foo():pass")
Tim Peterse8906822005-04-20 17:45:13 +0000190
Fred Drake58422e52001-06-04 03:56:24 +0000191 def test_import_from_statement(self):
192 self.check_suite("from sys.path import *")
193 self.check_suite("from sys.path import dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000194 self.check_suite("from sys.path import (dirname)")
195 self.check_suite("from sys.path import (dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000196 self.check_suite("from sys.path import dirname as my_dirname")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000197 self.check_suite("from sys.path import (dirname as my_dirname)")
198 self.check_suite("from sys.path import (dirname as my_dirname,)")
Fred Drake58422e52001-06-04 03:56:24 +0000199 self.check_suite("from sys.path import dirname, basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000200 self.check_suite("from sys.path import (dirname, basename)")
201 self.check_suite("from sys.path import (dirname, basename,)")
Fred Drake58422e52001-06-04 03:56:24 +0000202 self.check_suite(
203 "from sys.path import dirname as my_dirname, basename")
204 self.check_suite(
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000205 "from sys.path import (dirname as my_dirname, basename)")
206 self.check_suite(
207 "from sys.path import (dirname as my_dirname, basename,)")
208 self.check_suite(
Fred Drake58422e52001-06-04 03:56:24 +0000209 "from sys.path import dirname, basename as my_basename")
Anthony Baxter1a4ddae2004-08-31 10:07:13 +0000210 self.check_suite(
211 "from sys.path import (dirname, basename as my_basename)")
212 self.check_suite(
213 "from sys.path import (dirname, basename as my_basename,)")
Benjamin Petersonc0747cf2008-11-03 20:31:38 +0000214 self.check_suite("from .bogus import x")
Fred Drakee3fb18c2001-01-07 06:02:19 +0000215
Fred Drake58422e52001-06-04 03:56:24 +0000216 def test_basic_import_statement(self):
217 self.check_suite("import sys")
218 self.check_suite("import sys as system")
219 self.check_suite("import sys, math")
220 self.check_suite("import sys as system, math")
221 self.check_suite("import sys, math as my_math")
Fred Drake79ca79d2000-08-21 22:30:53 +0000222
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000223 def test_relative_imports(self):
224 self.check_suite("from . import name")
225 self.check_suite("from .. import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000226 # check all the way up to '....', since '...' is tokenized
227 # differently from '.' (it's an ellipsis token).
228 self.check_suite("from ... import name")
229 self.check_suite("from .... import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000230 self.check_suite("from .pkg import name")
231 self.check_suite("from ..pkg import name")
Mark Dickinsonfeb3b752010-07-04 18:38:57 +0000232 self.check_suite("from ...pkg import name")
233 self.check_suite("from ....pkg import name")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000234
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000235 def test_pep263(self):
236 self.check_suite("# -*- coding: iso-8859-1 -*-\n"
237 "pass\n")
238
239 def test_assert(self):
240 self.check_suite("assert alo < ahi and blo < bhi\n")
241
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000242 def test_with(self):
243 self.check_suite("with open('x'): pass\n")
244 self.check_suite("with open('x') as f: pass\n")
Georg Brandl0c315622009-05-25 21:10:36 +0000245 self.check_suite("with open('x') as f, open('y') as g: pass\n")
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000246
Georg Brandleee31162008-12-07 15:15:22 +0000247 def test_try_stmt(self):
248 self.check_suite("try: pass\nexcept: pass\n")
249 self.check_suite("try: pass\nfinally: pass\n")
250 self.check_suite("try: pass\nexcept A: pass\nfinally: pass\n")
251 self.check_suite("try: pass\nexcept A: pass\nexcept: pass\n"
252 "finally: pass\n")
253 self.check_suite("try: pass\nexcept: pass\nelse: pass\n")
254 self.check_suite("try: pass\nexcept: pass\nelse: pass\n"
255 "finally: pass\n")
256
Thomas Wouters89f507f2006-12-13 04:49:30 +0000257 def test_position(self):
258 # An absolutely minimal test of position information. Better
259 # tests would be a big project.
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000260 code = "def f(x):\n return x + 1"
Thomas Wouters89f507f2006-12-13 04:49:30 +0000261 st1 = parser.suite(code)
262 st2 = st1.totuple(line_info=1, col_info=1)
263
264 def walk(tree):
265 node_type = tree[0]
266 next = tree[1]
267 if isinstance(next, tuple):
268 for elt in tree[1:]:
269 for x in walk(elt):
270 yield x
271 else:
272 yield tree
273
274 terminals = list(walk(st2))
275 self.assertEqual([
276 (1, 'def', 1, 0),
277 (1, 'f', 1, 4),
278 (7, '(', 1, 5),
279 (1, 'x', 1, 6),
280 (8, ')', 1, 7),
281 (11, ':', 1, 8),
282 (4, '', 1, 9),
283 (5, '', 2, -1),
284 (1, 'return', 2, 4),
285 (1, 'x', 2, 11),
286 (14, '+', 2, 13),
287 (2, '1', 2, 15),
288 (4, '', 2, 16),
Benjamin Peterson8f326b22009-12-13 02:10:36 +0000289 (6, '', 2, -1),
290 (4, '', 2, -1),
291 (0, '', 2, -1)],
Thomas Wouters89f507f2006-12-13 04:49:30 +0000292 terminals)
293
Benjamin Peterson4905e802009-09-27 02:43:28 +0000294 def test_extended_unpacking(self):
295 self.check_suite("*a = y")
296 self.check_suite("x, *b, = m")
297 self.check_suite("[*a, *b] = y")
298 self.check_suite("for [*x, b] in x: pass")
299
Mark Dickinsoncf360b92012-05-07 12:01:27 +0100300 def test_raise_statement(self):
301 self.check_suite("raise\n")
302 self.check_suite("raise e\n")
303 self.check_suite("try:\n"
304 " suite\n"
305 "except Exception as e:\n"
306 " raise ValueError from e\n")
307
Mark Dickinson11c1dee2012-05-07 16:34:34 +0100308 def test_set_displays(self):
309 self.check_expr('{2}')
310 self.check_expr('{2,}')
311 self.check_expr('{2, 3}')
312 self.check_expr('{2, 3,}')
313
314 def test_dict_displays(self):
315 self.check_expr('{}')
316 self.check_expr('{a:b}')
317 self.check_expr('{a:b,}')
318 self.check_expr('{a:b, c:d}')
319 self.check_expr('{a:b, c:d,}')
320
321 def test_set_comprehensions(self):
322 self.check_expr('{x for x in seq}')
323 self.check_expr('{f(x) for x in seq}')
324 self.check_expr('{f(x) for x in seq if condition(x)}')
325
326 def test_dict_comprehensions(self):
327 self.check_expr('{x:x for x in seq}')
328 self.check_expr('{x**2:x[3] for x in seq if condition(x)}')
329 self.check_expr('{x:x for x in seq1 for y in seq2 if condition(x, y)}')
330
Thomas Wouters89f507f2006-12-13 04:49:30 +0000331
Fred Drake79ca79d2000-08-21 22:30:53 +0000332#
333# Second, we take *invalid* trees and make sure we get ParserError
334# rejections for them.
335#
336
Fred Drake58422e52001-06-04 03:56:24 +0000337class IllegalSyntaxTestCase(unittest.TestCase):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000338
Fred Drake58422e52001-06-04 03:56:24 +0000339 def check_bad_tree(self, tree, label):
340 try:
Fred Drake6e4f2c02001-07-17 19:33:25 +0000341 parser.sequence2st(tree)
Fred Drake58422e52001-06-04 03:56:24 +0000342 except parser.ParserError:
343 pass
344 else:
345 self.fail("did not detect invalid tree for %r" % label)
Fred Drake79ca79d2000-08-21 22:30:53 +0000346
Fred Drake58422e52001-06-04 03:56:24 +0000347 def test_junk(self):
348 # not even remotely valid:
349 self.check_bad_tree((1, 2, 3), "<junk>")
350
Fred Drakecf580c72001-07-17 03:01:29 +0000351 def test_illegal_yield_1(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000352 # Illegal yield statement: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000353 tree = \
354 (257,
355 (264,
356 (285,
357 (259,
358 (1, 'def'),
359 (1, 'f'),
360 (260, (7, '('), (8, ')')),
361 (11, ':'),
362 (291,
363 (4, ''),
364 (5, ''),
365 (264,
366 (265,
367 (266,
368 (272,
369 (275,
370 (1, 'return'),
371 (313,
372 (292,
373 (293,
374 (294,
375 (295,
376 (297,
377 (298,
378 (299,
379 (300,
380 (301,
381 (302, (303, (304, (305, (2, '1')))))))))))))))))),
382 (264,
383 (265,
384 (266,
385 (272,
386 (276,
387 (1, 'yield'),
388 (313,
389 (292,
390 (293,
391 (294,
392 (295,
393 (297,
394 (298,
395 (299,
396 (300,
397 (301,
398 (302,
399 (303, (304, (305, (2, '1')))))))))))))))))),
400 (4, ''))),
401 (6, ''))))),
402 (4, ''),
403 (0, ''))))
404 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
405
406 def test_illegal_yield_2(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000407 # Illegal return in generator: def f(): return 1; yield 1
Fred Drakecf580c72001-07-17 03:01:29 +0000408 tree = \
409 (257,
410 (264,
411 (265,
412 (266,
413 (278,
414 (1, 'from'),
415 (281, (1, '__future__')),
416 (1, 'import'),
417 (279, (1, 'generators')))),
418 (4, ''))),
419 (264,
420 (285,
421 (259,
422 (1, 'def'),
423 (1, 'f'),
424 (260, (7, '('), (8, ')')),
425 (11, ':'),
426 (291,
427 (4, ''),
428 (5, ''),
429 (264,
430 (265,
431 (266,
432 (272,
433 (275,
434 (1, 'return'),
435 (313,
436 (292,
437 (293,
438 (294,
439 (295,
440 (297,
441 (298,
442 (299,
443 (300,
444 (301,
445 (302, (303, (304, (305, (2, '1')))))))))))))))))),
446 (264,
447 (265,
448 (266,
449 (272,
450 (276,
451 (1, 'yield'),
452 (313,
453 (292,
454 (293,
455 (294,
456 (295,
457 (297,
458 (298,
459 (299,
460 (300,
461 (301,
462 (302,
463 (303, (304, (305, (2, '1')))))))))))))))))),
464 (4, ''))),
465 (6, ''))))),
466 (4, ''),
467 (0, ''))))
468 self.check_bad_tree(tree, "def f():\n return 1\n yield 1")
469
Fred Drake58422e52001-06-04 03:56:24 +0000470 def test_a_comma_comma_c(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000471 # Illegal input: a,,c
Fred Drake58422e52001-06-04 03:56:24 +0000472 tree = \
473 (258,
474 (311,
475 (290,
476 (291,
477 (292,
478 (293,
479 (295,
480 (296,
481 (297,
482 (298, (299, (300, (301, (302, (303, (1, 'a')))))))))))))),
483 (12, ','),
484 (12, ','),
485 (290,
486 (291,
487 (292,
488 (293,
489 (295,
490 (296,
491 (297,
492 (298, (299, (300, (301, (302, (303, (1, 'c'))))))))))))))),
493 (4, ''),
494 (0, ''))
495 self.check_bad_tree(tree, "a,,c")
496
497 def test_illegal_operator(self):
Guido van Rossum32c2ae72002-08-22 19:45:32 +0000498 # Illegal input: a $= b
Fred Drake58422e52001-06-04 03:56:24 +0000499 tree = \
500 (257,
501 (264,
502 (265,
503 (266,
504 (267,
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, 'a'))))))))))))))),
515 (268, (37, '$=')),
516 (312,
517 (291,
518 (292,
519 (293,
520 (294,
521 (296,
522 (297,
523 (298,
524 (299,
525 (300, (301, (302, (303, (304, (1, 'b'))))))))))))))))),
526 (4, ''))),
527 (0, ''))
528 self.check_bad_tree(tree, "a $= b")
Fred Drake79ca79d2000-08-21 22:30:53 +0000529
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000530 def test_malformed_global(self):
531 #doesn't have global keyword in ast
532 tree = (257,
533 (264,
534 (265,
535 (266,
536 (282, (1, 'foo'))), (4, ''))),
537 (4, ''),
Tim Petersf2715e02003-02-19 02:35:07 +0000538 (0, ''))
Neal Norwitz9caf9c02003-02-10 01:54:06 +0000539 self.check_bad_tree(tree, "malformed global ast")
Fred Drake79ca79d2000-08-21 22:30:53 +0000540
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000541 def test_missing_import_source(self):
Mark Dickinson3445b482010-07-04 18:15:26 +0000542 # from import fred
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000543 tree = \
544 (257,
Mark Dickinson3445b482010-07-04 18:15:26 +0000545 (268,
546 (269,
547 (270,
548 (282,
549 (284, (1, 'from'), (1, 'import'),
550 (287, (285, (1, 'fred')))))),
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000551 (4, ''))),
552 (4, ''), (0, ''))
Mark Dickinson3445b482010-07-04 18:15:26 +0000553 self.check_bad_tree(tree, "from import fred")
Mark Dickinson2cc8a5e2010-07-04 18:11:51 +0000554
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000555
556class CompileTestCase(unittest.TestCase):
557
558 # These tests are very minimal. :-(
559
560 def test_compile_expr(self):
561 st = parser.expr('2 + 3')
562 code = parser.compilest(st)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000563 self.assertEqual(eval(code), 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000564
565 def test_compile_suite(self):
566 st = parser.suite('x = 2; y = x + 3')
567 code = parser.compilest(st)
568 globs = {}
Georg Brandl7cae87c2006-09-06 06:51:57 +0000569 exec(code, globs)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000570 self.assertEqual(globs['y'], 5)
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000571
572 def test_compile_error(self):
573 st = parser.suite('1 = 3 + 4')
574 self.assertRaises(SyntaxError, parser.compilest, st)
575
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000576 def test_compile_badunicode(self):
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000577 st = parser.suite('a = "\\U12345678"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000578 self.assertRaises(SyntaxError, parser.compilest, st)
Guido van Rossum7eb6ca52007-07-18 21:00:22 +0000579 st = parser.suite('a = "\\u1"')
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000580 self.assertRaises(SyntaxError, parser.compilest, st)
581
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000582 def test_issue_9011(self):
583 # Issue 9011: compilation of an unary minus expression changed
584 # the meaning of the ST, so that a second compilation produced
585 # incorrect results.
586 st = parser.expr('-3')
587 code1 = parser.compilest(st)
588 self.assertEqual(eval(code1), -3)
589 code2 = parser.compilest(st)
590 self.assertEqual(eval(code2), -3)
591
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000592class ParserStackLimitTestCase(unittest.TestCase):
Mark Dickinsond35a32e2010-06-17 12:33:22 +0000593 """try to push the parser to/over its limits.
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000594 see http://bugs.python.org/issue1881 for a discussion
595 """
596 def _nested_expression(self, level):
597 return "["*level+"]"*level
598
599 def test_deeply_nested_list(self):
600 # XXX used to be 99 levels in 2.x
601 e = self._nested_expression(93)
602 st = parser.expr(e)
603 st.compile()
604
605 def test_trigger_memory_error(self):
606 e = self._nested_expression(100)
Christian Heimesb186d002008-03-18 15:15:01 +0000607 print("Expecting 's_push: parser stack overflow' in next line",
608 file=sys.stderr)
Antoine Pitrou88909542009-06-29 13:54:42 +0000609 sys.stderr.flush()
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000610 self.assertRaises(MemoryError, parser.expr, e)
611
Mark Dickinson211c6252009-02-01 10:28:51 +0000612class STObjectTestCase(unittest.TestCase):
613 """Test operations on ST objects themselves"""
614
615 def test_comparisons(self):
616 # ST objects should support order and equality comparisons
617 st1 = parser.expr('2 + 3')
618 st2 = parser.suite('x = 2; y = x + 3')
619 st3 = parser.expr('list(x**3 for x in range(20))')
620 st1_copy = parser.expr('2 + 3')
621 st2_copy = parser.suite('x = 2; y = x + 3')
622 st3_copy = parser.expr('list(x**3 for x in range(20))')
623
624 # exercise fast path for object identity
Ezio Melottib3aedd42010-11-20 19:04:17 +0000625 self.assertEqual(st1 == st1, True)
626 self.assertEqual(st2 == st2, True)
627 self.assertEqual(st3 == st3, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000628 # slow path equality
629 self.assertEqual(st1, st1_copy)
630 self.assertEqual(st2, st2_copy)
631 self.assertEqual(st3, st3_copy)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000632 self.assertEqual(st1 == st2, False)
633 self.assertEqual(st1 == st3, False)
634 self.assertEqual(st2 == st3, False)
635 self.assertEqual(st1 != st1, False)
636 self.assertEqual(st2 != st2, False)
637 self.assertEqual(st3 != st3, False)
638 self.assertEqual(st1 != st1_copy, False)
639 self.assertEqual(st2 != st2_copy, False)
640 self.assertEqual(st3 != st3_copy, False)
641 self.assertEqual(st2 != st1, True)
642 self.assertEqual(st1 != st3, True)
643 self.assertEqual(st3 != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000644 # we don't particularly care what the ordering is; just that
645 # it's usable and self-consistent
Ezio Melottib3aedd42010-11-20 19:04:17 +0000646 self.assertEqual(st1 < st2, not (st2 <= st1))
647 self.assertEqual(st1 < st3, not (st3 <= st1))
648 self.assertEqual(st2 < st3, not (st3 <= st2))
649 self.assertEqual(st1 < st2, st2 > st1)
650 self.assertEqual(st1 < st3, st3 > st1)
651 self.assertEqual(st2 < st3, st3 > st2)
652 self.assertEqual(st1 <= st2, st2 >= st1)
653 self.assertEqual(st3 <= st1, st1 >= st3)
654 self.assertEqual(st2 <= st3, st3 >= st2)
Mark Dickinson211c6252009-02-01 10:28:51 +0000655 # transitivity
656 bottom = min(st1, st2, st3)
657 top = max(st1, st2, st3)
658 mid = sorted([st1, st2, st3])[1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000659 self.assertTrue(bottom < mid)
660 self.assertTrue(bottom < top)
661 self.assertTrue(mid < top)
662 self.assertTrue(bottom <= mid)
663 self.assertTrue(bottom <= top)
664 self.assertTrue(mid <= top)
665 self.assertTrue(bottom <= bottom)
666 self.assertTrue(mid <= mid)
667 self.assertTrue(top <= top)
Mark Dickinson211c6252009-02-01 10:28:51 +0000668 # interaction with other types
Ezio Melottib3aedd42010-11-20 19:04:17 +0000669 self.assertEqual(st1 == 1588.602459, False)
670 self.assertEqual('spanish armada' != st2, True)
Mark Dickinson211c6252009-02-01 10:28:51 +0000671 self.assertRaises(TypeError, operator.ge, st3, None)
672 self.assertRaises(TypeError, operator.le, False, st1)
673 self.assertRaises(TypeError, operator.lt, st1, 1815)
674 self.assertRaises(TypeError, operator.gt, b'waterloo', st2)
675
676
677 # XXX tests for pickling and unpickling of ST objects should go here
678
679
Fred Drake2e2be372001-09-20 21:33:42 +0000680def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000681 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000682 RoundtripLegalSyntaxTestCase,
Jeremy Hylton3e0055f2005-10-20 19:59:25 +0000683 IllegalSyntaxTestCase,
684 CompileTestCase,
Christian Heimes90c3d9b2008-02-23 13:18:03 +0000685 ParserStackLimitTestCase,
Mark Dickinson211c6252009-02-01 10:28:51 +0000686 STObjectTestCase,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000687 )
Fred Drake2e2be372001-09-20 21:33:42 +0000688
689
690if __name__ == "__main__":
691 test_main()