blob: 77839c20381927f9de0d148d637fb04496fb091b [file] [log] [blame]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001import sys, unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Georg Brandl0c77a822008-06-10 16:37:50 +00003import ast
Tim Peters400cbc32006-02-28 18:44:41 +00004
5def to_tuple(t):
Guido van Rossum3172c5d2007-10-16 18:12:55 +00006 if t is None or isinstance(t, (str, int, complex)):
Tim Peters400cbc32006-02-28 18:44:41 +00007 return t
8 elif isinstance(t, list):
9 return [to_tuple(e) for e in t]
10 result = [t.__class__.__name__]
Martin v. Löwis49c5da12006-03-01 22:49:05 +000011 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
12 result.append((t.lineno, t.col_offset))
Tim Peters400cbc32006-02-28 18:44:41 +000013 if t._fields is None:
14 return tuple(result)
15 for f in t._fields:
16 result.append(to_tuple(getattr(t, f)))
17 return tuple(result)
18
Neal Norwitzee9b10a2008-03-31 05:29:39 +000019
Tim Peters400cbc32006-02-28 18:44:41 +000020# These tests are compiled through "exec"
21# There should be atleast one test per statement
22exec_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050023 # None
24 "None",
Tim Peters400cbc32006-02-28 18:44:41 +000025 # FunctionDef
26 "def f(): pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050027 # FunctionDef with arg
28 "def f(a): pass",
29 # FunctionDef with arg and default value
30 "def f(a=0): pass",
31 # FunctionDef with varargs
32 "def f(*args): pass",
33 # FunctionDef with kwargs
34 "def f(**kwargs): pass",
35 # FunctionDef with all kind of args
36 "def f(a, b=1, c=None, d=[], e={}, *args, **kwargs): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000037 # ClassDef
38 "class C:pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050039 # ClassDef, new style class
40 "class C(object): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000041 # Return
42 "def f():return 1",
43 # Delete
44 "del v",
45 # Assign
46 "v = 1",
47 # AugAssign
48 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000049 # For
50 "for v in v:pass",
51 # While
52 "while v:pass",
53 # If
54 "if v:pass",
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -050055 # With
56 "with x as y: pass",
57 "with x as y, z as q: pass",
Tim Peters400cbc32006-02-28 18:44:41 +000058 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000059 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000060 # TryExcept
61 "try:\n pass\nexcept Exception:\n pass",
62 # TryFinally
63 "try:\n pass\nfinally:\n pass",
64 # Assert
65 "assert v",
66 # Import
67 "import sys",
68 # ImportFrom
69 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000070 # Global
71 "global v",
72 # Expr
73 "1",
74 # Pass,
75 "pass",
76 # Break
77 "break",
78 # Continue
79 "continue",
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +000080 # for statements with naked tuples (see http://bugs.python.org/issue6704)
81 "for a,b in c: pass",
82 "[(a,b) for a,b in c]",
83 "((a,b) for a,b in c)",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050084 "((a,b) for (a,b) in c)",
85 # Multiline generator expression (test for .lineno & .col_offset)
86 """(
87 (
88 Aa
89 ,
90 Bb
91 )
92 for
93 Aa
94 ,
95 Bb in Cc
96 )""",
97 # dictcomp
98 "{a : b for w in x for m in p if g}",
99 # dictcomp with naked tuple
100 "{a : b for v,w in x}",
101 # setcomp
102 "{r for l in x if g}",
103 # setcomp with naked tuple
104 "{r for l,m in x}",
Tim Peters400cbc32006-02-28 18:44:41 +0000105]
106
107# These are compiled through "single"
108# because of overlap with "eval", it just tests what
109# can't be tested with "eval"
110single_tests = [
111 "1+2"
112]
113
114# These are compiled through "eval"
115# It should test all expressions
116eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500117 # None
118 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000119 # BoolOp
120 "a and b",
121 # BinOp
122 "a + b",
123 # UnaryOp
124 "not v",
125 # Lambda
126 "lambda:None",
127 # Dict
128 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500129 # Empty dict
130 "{}",
131 # Set
132 "{None,}",
133 # Multiline dict (test for .lineno & .col_offset)
134 """{
135 1
136 :
137 2
138 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000139 # ListComp
140 "[a for b in c if d]",
141 # GeneratorExp
142 "(a for b in c if d)",
143 # Yield - yield expressions can't work outside a function
144 #
145 # Compare
146 "1 < 2 < 3",
147 # Call
148 "f(1,2,c=3,*d,**e)",
Tim Peters400cbc32006-02-28 18:44:41 +0000149 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000150 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000151 # Str
152 "'string'",
153 # Attribute
154 "a.b",
155 # Subscript
156 "a[b:c]",
157 # Name
158 "v",
159 # List
160 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500161 # Empty list
162 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000163 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000164 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500165 # Tuple
166 "(1,2,3)",
167 # Empty tuple
168 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000169 # Combination
170 "a.b.c.d(a.b[1:2])",
171
Tim Peters400cbc32006-02-28 18:44:41 +0000172]
173
174# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
175# excepthandler, arguments, keywords, alias
176
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000177class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000178
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000179 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000180 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000181 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000182 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000183 node_pos = (ast_node.lineno, ast_node.col_offset)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000184 self.assertTrue(node_pos >= parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000185 parent_pos = (ast_node.lineno, ast_node.col_offset)
186 for name in ast_node._fields:
187 value = getattr(ast_node, name)
188 if isinstance(value, list):
189 for child in value:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000190 self._assertTrueorder(child, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000191 elif value is not None:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000192 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000193
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500194 def test_AST_objects(self):
195 x = ast.AST()
196 self.assertEqual(x._fields, ())
197
198 with self.assertRaises(AttributeError):
199 x.vararg
200
201 with self.assertRaises(AttributeError):
202 x.foobar = 21
203
204 with self.assertRaises(AttributeError):
205 ast.AST(lineno=2)
206
207 with self.assertRaises(TypeError):
208 # "_ast.AST constructor takes 0 positional arguments"
209 ast.AST(2)
210
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000211 def test_snippets(self):
212 for input, output, kind in ((exec_tests, exec_results, "exec"),
213 (single_tests, single_results, "single"),
214 (eval_tests, eval_results, "eval")):
215 for i, o in zip(input, output):
Georg Brandl0c77a822008-06-10 16:37:50 +0000216 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000217 self.assertEqual(to_tuple(ast_tree), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000218 self._assertTrueorder(ast_tree, (0, 0))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000219
Benjamin Peterson78565b22009-06-28 19:19:51 +0000220 def test_slice(self):
221 slc = ast.parse("x[::]").body[0].value.slice
222 self.assertIsNone(slc.upper)
223 self.assertIsNone(slc.lower)
224 self.assertIsNone(slc.step)
225
226 def test_from_import(self):
227 im = ast.parse("from . import y").body[0]
228 self.assertIsNone(im.module)
229
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000230 def test_base_classes(self):
231 self.assertTrue(issubclass(ast.For, ast.stmt))
232 self.assertTrue(issubclass(ast.Name, ast.expr))
233 self.assertTrue(issubclass(ast.stmt, ast.AST))
234 self.assertTrue(issubclass(ast.expr, ast.AST))
235 self.assertTrue(issubclass(ast.comprehension, ast.AST))
236 self.assertTrue(issubclass(ast.Gt, ast.AST))
237
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500238 def test_field_attr_existence(self):
239 for name, item in ast.__dict__.items():
240 if isinstance(item, type) and name != 'AST' and name[0].isupper():
241 x = item()
242 if isinstance(x, ast.AST):
243 self.assertEqual(type(x._fields), tuple)
244
245 def test_arguments(self):
246 x = ast.arguments()
247 self.assertEqual(x._fields, ('args', 'vararg', 'varargannotation',
248 'kwonlyargs', 'kwarg', 'kwargannotation',
249 'defaults', 'kw_defaults'))
250
251 with self.assertRaises(AttributeError):
252 x.vararg
253
254 x = ast.arguments(*range(1, 9))
255 self.assertEqual(x.vararg, 2)
256
257 def test_field_attr_writable(self):
258 x = ast.Num()
259 # We can assign to _fields
260 x._fields = 666
261 self.assertEqual(x._fields, 666)
262
263 def test_classattrs(self):
264 x = ast.Num()
265 self.assertEqual(x._fields, ('n',))
266
267 with self.assertRaises(AttributeError):
268 x.n
269
270 x = ast.Num(42)
271 self.assertEqual(x.n, 42)
272
273 with self.assertRaises(AttributeError):
274 x.lineno
275
276 with self.assertRaises(AttributeError):
277 x.foobar
278
279 x = ast.Num(lineno=2)
280 self.assertEqual(x.lineno, 2)
281
282 x = ast.Num(42, lineno=0)
283 self.assertEqual(x.lineno, 0)
284 self.assertEqual(x._fields, ('n',))
285 self.assertEqual(x.n, 42)
286
287 self.assertRaises(TypeError, ast.Num, 1, 2)
288 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
289
290 def test_module(self):
291 body = [ast.Num(42)]
292 x = ast.Module(body)
293 self.assertEqual(x.body, body)
294
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000295 def test_nodeclasses(self):
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500296 # Zero arguments constructor explicitely allowed
297 x = ast.BinOp()
298 self.assertEqual(x._fields, ('left', 'op', 'right'))
299
300 # Random attribute allowed too
301 x.foobarbaz = 5
302 self.assertEqual(x.foobarbaz, 5)
303
304 n1 = ast.Num(1)
305 n3 = ast.Num(3)
306 addop = ast.Add()
307 x = ast.BinOp(n1, addop, n3)
308 self.assertEqual(x.left, n1)
309 self.assertEqual(x.op, addop)
310 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500311
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500312 x = ast.BinOp(1, 2, 3)
313 self.assertEqual(x.left, 1)
314 self.assertEqual(x.op, 2)
315 self.assertEqual(x.right, 3)
316
Georg Brandl0c77a822008-06-10 16:37:50 +0000317 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000318 self.assertEqual(x.left, 1)
319 self.assertEqual(x.op, 2)
320 self.assertEqual(x.right, 3)
321 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000322
323 # node raises exception when not given enough arguments
Georg Brandl0c77a822008-06-10 16:37:50 +0000324 self.assertRaises(TypeError, ast.BinOp, 1, 2)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500325 # node raises exception when given too many arguments
326 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
327 # node raises exception when not given enough arguments
328 self.assertRaises(TypeError, ast.BinOp, 1, 2, lineno=0)
329 # node raises exception when given too many arguments
330 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000331
332 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000333 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000334 self.assertEqual(x.left, 1)
335 self.assertEqual(x.op, 2)
336 self.assertEqual(x.right, 3)
337 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000338
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500339 # Random kwargs also allowed
340 x = ast.BinOp(1, 2, 3, foobarbaz=42)
341 self.assertEqual(x.foobarbaz, 42)
342
343 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000344 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000345 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500346 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000347
348 def test_pickling(self):
349 import pickle
350 mods = [pickle]
351 try:
352 import cPickle
353 mods.append(cPickle)
354 except ImportError:
355 pass
356 protocols = [0, 1, 2]
357 for mod in mods:
358 for protocol in protocols:
359 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
360 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000361 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000362
Benjamin Peterson5b066812010-11-20 01:38:49 +0000363 def test_invalid_sum(self):
364 pos = dict(lineno=2, col_offset=3)
365 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
366 with self.assertRaises(TypeError) as cm:
367 compile(m, "<test>", "exec")
368 self.assertIn("but got <_ast.expr", str(cm.exception))
369
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500370 def test_invalid_identitifer(self):
371 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
372 ast.fix_missing_locations(m)
373 with self.assertRaises(TypeError) as cm:
374 compile(m, "<test>", "exec")
375 self.assertIn("identifier must be of type str", str(cm.exception))
376
377 def test_invalid_string(self):
378 m = ast.Module([ast.Expr(ast.Str(42))])
379 ast.fix_missing_locations(m)
380 with self.assertRaises(TypeError) as cm:
381 compile(m, "<test>", "exec")
382 self.assertIn("string must be of type str", str(cm.exception))
383
Georg Brandl0c77a822008-06-10 16:37:50 +0000384
385class ASTHelpers_Test(unittest.TestCase):
386
387 def test_parse(self):
388 a = ast.parse('foo(1 + 1)')
389 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
390 self.assertEqual(ast.dump(a), ast.dump(b))
391
392 def test_dump(self):
393 node = ast.parse('spam(eggs, "and cheese")')
394 self.assertEqual(ast.dump(node),
395 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
396 "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
397 "keywords=[], starargs=None, kwargs=None))])"
398 )
399 self.assertEqual(ast.dump(node, annotate_fields=False),
400 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
401 "Str('and cheese')], [], None, None))])"
402 )
403 self.assertEqual(ast.dump(node, include_attributes=True),
404 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
405 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
406 "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
407 "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
408 "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
409 )
410
411 def test_copy_location(self):
412 src = ast.parse('1 + 1', mode='eval')
413 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
414 self.assertEqual(ast.dump(src, include_attributes=True),
415 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
416 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
417 'col_offset=0))'
418 )
419
420 def test_fix_missing_locations(self):
421 src = ast.parse('write("spam")')
422 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
423 [ast.Str('eggs')], [], None, None)))
424 self.assertEqual(src, ast.fix_missing_locations(src))
425 self.assertEqual(ast.dump(src, include_attributes=True),
426 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
427 "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, "
428 "col_offset=6)], keywords=[], starargs=None, kwargs=None, "
429 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
430 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
431 "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], "
432 "keywords=[], starargs=None, kwargs=None, lineno=1, "
433 "col_offset=0), lineno=1, col_offset=0)])"
434 )
435
436 def test_increment_lineno(self):
437 src = ast.parse('1 + 1', mode='eval')
438 self.assertEqual(ast.increment_lineno(src, n=3), src)
439 self.assertEqual(ast.dump(src, include_attributes=True),
440 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
441 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
442 'col_offset=0))'
443 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000444 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000445 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000446 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
447 self.assertEqual(ast.dump(src, include_attributes=True),
448 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
449 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
450 'col_offset=0))'
451 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000452
453 def test_iter_fields(self):
454 node = ast.parse('foo()', mode='eval')
455 d = dict(ast.iter_fields(node.body))
456 self.assertEqual(d.pop('func').id, 'foo')
457 self.assertEqual(d, {'keywords': [], 'kwargs': None,
458 'args': [], 'starargs': None})
459
460 def test_iter_child_nodes(self):
461 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
462 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
463 iterator = ast.iter_child_nodes(node.body)
464 self.assertEqual(next(iterator).id, 'spam')
465 self.assertEqual(next(iterator).n, 23)
466 self.assertEqual(next(iterator).n, 42)
467 self.assertEqual(ast.dump(next(iterator)),
468 "keyword(arg='eggs', value=Str(s='leek'))"
469 )
470
471 def test_get_docstring(self):
472 node = ast.parse('def foo():\n """line one\n line two"""')
473 self.assertEqual(ast.get_docstring(node.body[0]),
474 'line one\nline two')
475
476 def test_literal_eval(self):
477 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
478 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
479 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000480 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000481 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000482 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Raymond Hettingerbc959732010-10-08 00:47:45 +0000483 self.assertEqual(ast.literal_eval('-6'), -6)
484 self.assertEqual(ast.literal_eval('-6j+3'), 3-6j)
485 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Georg Brandl0c77a822008-06-10 16:37:50 +0000486
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000487 def test_literal_eval_issue4907(self):
488 self.assertEqual(ast.literal_eval('2j'), 2j)
489 self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
490 self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000491
Georg Brandl0c77a822008-06-10 16:37:50 +0000492
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000493def test_main():
Georg Brandl0c77a822008-06-10 16:37:50 +0000494 support.run_unittest(AST_Tests, ASTHelpers_Test)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000495
496def main():
497 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000498 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000499 if sys.argv[1:] == ['-g']:
500 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
501 (eval_tests, "eval")):
502 print(kind+"_results = [")
503 for s in statements:
504 print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
505 print("]")
506 print("main()")
507 raise SystemExit
508 test_main()
Tim Peters400cbc32006-02-28 18:44:41 +0000509
510#### EVERYTHING BELOW IS GENERATED #####
511exec_results = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500512('Module', [('Expr', (1, 0), ('Name', (1, 0), 'None', ('Load',)))]),
Neal Norwitzc1505362006-12-28 06:47:50 +0000513('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500514('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', 'a', None)], None, None, [], None, None, [], []), [('Pass', (1, 10))], [], None)]),
515('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', 'a', None)], None, None, [], None, None, [('Num', (1, 8), 0)], []), [('Pass', (1, 12))], [], None)]),
516('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], 'args', None, [], None, None, [], []), [('Pass', (1, 14))], [], None)]),
517('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], 'kwargs', None, [], []), [('Pass', (1, 17))], [], None)]),
518('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', 'a', None), ('arg', 'b', None), ('arg', 'c', None), ('arg', 'd', None), ('arg', 'e', None)], 'args', None, [], 'kwargs', None, [('Num', (1, 11), 1), ('Name', (1, 16), 'None', ('Load',)), ('List', (1, 24), [], ('Load',)), ('Dict', (1, 30), [], [])], []), [('Pass', (1, 52))], [], None)]),
Neal Norwitzad74aa82008-03-31 05:14:30 +0000519('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [])]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500520('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], None, None, [('Pass', (1, 17))], [])]),
Neal Norwitzc1505362006-12-28 06:47:50 +0000521('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Return', (1, 8), ('Num', (1, 15), 1))], [], None)]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000522('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
523('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000524('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000525('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
526('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
527('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -0500528('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])]),
529('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',))), ('withitem', ('Name', (1, 13), 'z', ('Load',)), ('Name', (1, 18), 'q', ('Store',)))], [('Pass', (1, 21))])]),
Collin Winter828f04a2007-08-31 00:04:24 +0000530('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Str', (1, 16), 'string')], [], None, None), None)]),
Benjamin Peterson43af12b2011-05-29 11:43:10 -0500531('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])]),
532('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000533('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
534('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
535('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000536('Module', [('Global', (1, 0), ['v'])]),
537('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))]),
538('Module', [('Pass', (1, 0))]),
539('Module', [('Break', (1, 0))]),
540('Module', [('Continue', (1, 0))]),
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +0000541('Module', [('For', (1, 0), ('Tuple', (1, 4), [('Name', (1, 4), 'a', ('Store',)), ('Name', (1, 6), 'b', ('Store',))], ('Store',)), ('Name', (1, 11), 'c', ('Load',)), [('Pass', (1, 14))], [])]),
542('Module', [('Expr', (1, 0), ('ListComp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [])]))]),
543('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'a', ('Store',)), ('Name', (1, 13), 'b', ('Store',))], ('Store',)), ('Name', (1, 18), 'c', ('Load',)), [])]))]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500544('Module', [('Expr', (1, 0), ('GeneratorExp', (1, 1), ('Tuple', (1, 2), [('Name', (1, 2), 'a', ('Load',)), ('Name', (1, 4), 'b', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (1, 12), [('Name', (1, 12), 'a', ('Store',)), ('Name', (1, 14), 'b', ('Store',))], ('Store',)), ('Name', (1, 20), 'c', ('Load',)), [])]))]),
545('Module', [('Expr', (1, 0), ('GeneratorExp', (2, 4), ('Tuple', (3, 4), [('Name', (3, 4), 'Aa', ('Load',)), ('Name', (5, 7), 'Bb', ('Load',))], ('Load',)), [('comprehension', ('Tuple', (8, 4), [('Name', (8, 4), 'Aa', ('Store',)), ('Name', (10, 4), 'Bb', ('Store',))], ('Store',)), ('Name', (10, 10), 'Cc', ('Load',)), [])]))]),
546('Module', [('Expr', (1, 0), ('DictComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Name', (1, 11), 'w', ('Store',)), ('Name', (1, 16), 'x', ('Load',)), []), ('comprehension', ('Name', (1, 22), 'm', ('Store',)), ('Name', (1, 27), 'p', ('Load',)), [('Name', (1, 32), 'g', ('Load',))])]))]),
547('Module', [('Expr', (1, 0), ('DictComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), ('Name', (1, 5), 'b', ('Load',)), [('comprehension', ('Tuple', (1, 11), [('Name', (1, 11), 'v', ('Store',)), ('Name', (1, 13), 'w', ('Store',))], ('Store',)), ('Name', (1, 18), 'x', ('Load',)), [])]))]),
548('Module', [('Expr', (1, 0), ('SetComp', (1, 1), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 12), 'x', ('Load',)), [('Name', (1, 17), 'g', ('Load',))])]))]),
549('Module', [('Expr', (1, 0), ('SetComp', (1, 1), ('Name', (1, 1), 'r', ('Load',)), [('comprehension', ('Tuple', (1, 7), [('Name', (1, 7), 'l', ('Store',)), ('Name', (1, 9), 'm', ('Store',))], ('Store',)), ('Name', (1, 14), 'x', ('Load',)), [])]))]),
Tim Peters400cbc32006-02-28 18:44:41 +0000550]
551single_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000552('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +0000553]
554eval_results = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500555('Expression', ('Name', (1, 0), 'None', ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000556('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
557('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
558('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Neal Norwitzc1505362006-12-28 06:47:50 +0000559('Expression', ('Lambda', (1, 0), ('arguments', [], None, None, [], None, None, [], []), ('Name', (1, 7), 'None', ('Load',)))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000560('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500561('Expression', ('Dict', (1, 0), [], [])),
562('Expression', ('Set', (1, 0), [('Name', (1, 1), 'None', ('Load',))])),
563('Expression', ('Dict', (1, 0), [('Num', (2, 6), 1)], [('Num', (4, 10), 2)])),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000564('Expression', ('ListComp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))])])),
565('Expression', ('GeneratorExp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))])])),
566('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])),
567('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('Num', (1, 2), 1), ('Num', (1, 4), 2)], [('keyword', 'c', ('Num', (1, 8), 3))], ('Name', (1, 11), 'd', ('Load',)), ('Name', (1, 15), 'e', ('Load',)))),
Neal Norwitzc1505362006-12-28 06:47:50 +0000568('Expression', ('Num', (1, 0), 10)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000569('Expression', ('Str', (1, 0), 'string')),
570('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
571('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))),
572('Expression', ('Name', (1, 0), 'v', ('Load',))),
573('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500574('Expression', ('List', (1, 0), [], ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000575('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500576('Expression', ('Tuple', (1, 1), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
577('Expression', ('Tuple', (1, 0), [], ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000578('Expression', ('Call', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',)), 'c', ('Load',)), 'd', ('Load',)), [('Subscript', (1, 8), ('Attribute', (1, 8), ('Name', (1, 8), 'a', ('Load',)), 'b', ('Load',)), ('Slice', ('Num', (1, 12), 1), ('Num', (1, 14), 2), None), ('Load',))], [], None, None)),
Tim Peters400cbc32006-02-28 18:44:41 +0000579]
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000580main()