blob: 064c669d7fe4e76e50a7e10b6a871f45b4eddd11 [file] [log] [blame]
Benjamin Peterson832bfe22011-08-09 16:15:04 -05001import os
2import sys
3import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Georg Brandl0c77a822008-06-10 16:37:50 +00005import ast
Tim Peters400cbc32006-02-28 18:44:41 +00006
7def to_tuple(t):
Guido van Rossum3172c5d2007-10-16 18:12:55 +00008 if t is None or isinstance(t, (str, int, complex)):
Tim Peters400cbc32006-02-28 18:44:41 +00009 return t
10 elif isinstance(t, list):
11 return [to_tuple(e) for e in t]
12 result = [t.__class__.__name__]
Martin v. Löwis49c5da12006-03-01 22:49:05 +000013 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
14 result.append((t.lineno, t.col_offset))
Tim Peters400cbc32006-02-28 18:44:41 +000015 if t._fields is None:
16 return tuple(result)
17 for f in t._fields:
18 result.append(to_tuple(getattr(t, f)))
19 return tuple(result)
20
Neal Norwitzee9b10a2008-03-31 05:29:39 +000021
Tim Peters400cbc32006-02-28 18:44:41 +000022# These tests are compiled through "exec"
23# There should be atleast one test per statement
24exec_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050025 # None
26 "None",
Tim Peters400cbc32006-02-28 18:44:41 +000027 # FunctionDef
28 "def f(): pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050029 # FunctionDef with arg
30 "def f(a): pass",
31 # FunctionDef with arg and default value
32 "def f(a=0): pass",
33 # FunctionDef with varargs
34 "def f(*args): pass",
35 # FunctionDef with kwargs
36 "def f(**kwargs): pass",
37 # FunctionDef with all kind of args
38 "def f(a, b=1, c=None, d=[], e={}, *args, **kwargs): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000039 # ClassDef
40 "class C:pass",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050041 # ClassDef, new style class
42 "class C(object): pass",
Tim Peters400cbc32006-02-28 18:44:41 +000043 # Return
44 "def f():return 1",
45 # Delete
46 "del v",
47 # Assign
48 "v = 1",
49 # AugAssign
50 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000051 # For
52 "for v in v:pass",
53 # While
54 "while v:pass",
55 # If
56 "if v:pass",
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -050057 # With
58 "with x as y: pass",
59 "with x as y, z as q: pass",
Tim Peters400cbc32006-02-28 18:44:41 +000060 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000061 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000062 # TryExcept
63 "try:\n pass\nexcept Exception:\n pass",
64 # TryFinally
65 "try:\n pass\nfinally:\n pass",
66 # Assert
67 "assert v",
68 # Import
69 "import sys",
70 # ImportFrom
71 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000072 # Global
73 "global v",
74 # Expr
75 "1",
76 # Pass,
77 "pass",
78 # Break
79 "break",
80 # Continue
81 "continue",
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +000082 # for statements with naked tuples (see http://bugs.python.org/issue6704)
83 "for a,b in c: pass",
84 "[(a,b) for a,b in c]",
85 "((a,b) for a,b in c)",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -050086 "((a,b) for (a,b) in c)",
87 # Multiline generator expression (test for .lineno & .col_offset)
88 """(
89 (
90 Aa
91 ,
92 Bb
93 )
94 for
95 Aa
96 ,
97 Bb in Cc
98 )""",
99 # dictcomp
100 "{a : b for w in x for m in p if g}",
101 # dictcomp with naked tuple
102 "{a : b for v,w in x}",
103 # setcomp
104 "{r for l in x if g}",
105 # setcomp with naked tuple
106 "{r for l,m in x}",
Tim Peters400cbc32006-02-28 18:44:41 +0000107]
108
109# These are compiled through "single"
110# because of overlap with "eval", it just tests what
111# can't be tested with "eval"
112single_tests = [
113 "1+2"
114]
115
116# These are compiled through "eval"
117# It should test all expressions
118eval_tests = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500119 # None
120 "None",
Tim Peters400cbc32006-02-28 18:44:41 +0000121 # BoolOp
122 "a and b",
123 # BinOp
124 "a + b",
125 # UnaryOp
126 "not v",
127 # Lambda
128 "lambda:None",
129 # Dict
130 "{ 1:2 }",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500131 # Empty dict
132 "{}",
133 # Set
134 "{None,}",
135 # Multiline dict (test for .lineno & .col_offset)
136 """{
137 1
138 :
139 2
140 }""",
Tim Peters400cbc32006-02-28 18:44:41 +0000141 # ListComp
142 "[a for b in c if d]",
143 # GeneratorExp
144 "(a for b in c if d)",
145 # Yield - yield expressions can't work outside a function
146 #
147 # Compare
148 "1 < 2 < 3",
149 # Call
150 "f(1,2,c=3,*d,**e)",
Tim Peters400cbc32006-02-28 18:44:41 +0000151 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +0000152 "10",
Tim Peters400cbc32006-02-28 18:44:41 +0000153 # Str
154 "'string'",
155 # Attribute
156 "a.b",
157 # Subscript
158 "a[b:c]",
159 # Name
160 "v",
161 # List
162 "[1,2,3]",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500163 # Empty list
164 "[]",
Tim Peters400cbc32006-02-28 18:44:41 +0000165 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000166 "1,2,3",
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500167 # Tuple
168 "(1,2,3)",
169 # Empty tuple
170 "()",
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000171 # Combination
172 "a.b.c.d(a.b[1:2])",
173
Tim Peters400cbc32006-02-28 18:44:41 +0000174]
175
176# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
177# excepthandler, arguments, keywords, alias
178
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000179class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000180
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000181 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000182 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000183 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000184 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000185 node_pos = (ast_node.lineno, ast_node.col_offset)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000186 self.assertTrue(node_pos >= parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000187 parent_pos = (ast_node.lineno, ast_node.col_offset)
188 for name in ast_node._fields:
189 value = getattr(ast_node, name)
190 if isinstance(value, list):
191 for child in value:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000192 self._assertTrueorder(child, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000193 elif value is not None:
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000194 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000195
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500196 def test_AST_objects(self):
197 x = ast.AST()
198 self.assertEqual(x._fields, ())
Benjamin Peterson7e0dbfb2012-03-12 09:46:44 -0700199 x.foobar = 42
200 self.assertEqual(x.foobar, 42)
201 self.assertEqual(x.__dict__["foobar"], 42)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500202
203 with self.assertRaises(AttributeError):
204 x.vararg
205
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500206 with self.assertRaises(TypeError):
207 # "_ast.AST constructor takes 0 positional arguments"
208 ast.AST(2)
209
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000210 def test_snippets(self):
211 for input, output, kind in ((exec_tests, exec_results, "exec"),
212 (single_tests, single_results, "single"),
213 (eval_tests, eval_results, "eval")):
214 for i, o in zip(input, output):
Georg Brandl0c77a822008-06-10 16:37:50 +0000215 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000216 self.assertEqual(to_tuple(ast_tree), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000217 self._assertTrueorder(ast_tree, (0, 0))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000218
Benjamin Peterson78565b22009-06-28 19:19:51 +0000219 def test_slice(self):
220 slc = ast.parse("x[::]").body[0].value.slice
221 self.assertIsNone(slc.upper)
222 self.assertIsNone(slc.lower)
223 self.assertIsNone(slc.step)
224
225 def test_from_import(self):
226 im = ast.parse("from . import y").body[0]
227 self.assertIsNone(im.module)
228
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000229 def test_base_classes(self):
230 self.assertTrue(issubclass(ast.For, ast.stmt))
231 self.assertTrue(issubclass(ast.Name, ast.expr))
232 self.assertTrue(issubclass(ast.stmt, ast.AST))
233 self.assertTrue(issubclass(ast.expr, ast.AST))
234 self.assertTrue(issubclass(ast.comprehension, ast.AST))
235 self.assertTrue(issubclass(ast.Gt, ast.AST))
236
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500237 def test_field_attr_existence(self):
238 for name, item in ast.__dict__.items():
239 if isinstance(item, type) and name != 'AST' and name[0].isupper():
240 x = item()
241 if isinstance(x, ast.AST):
242 self.assertEqual(type(x._fields), tuple)
243
244 def test_arguments(self):
245 x = ast.arguments()
246 self.assertEqual(x._fields, ('args', 'vararg', 'varargannotation',
247 'kwonlyargs', 'kwarg', 'kwargannotation',
248 'defaults', 'kw_defaults'))
249
250 with self.assertRaises(AttributeError):
251 x.vararg
252
253 x = ast.arguments(*range(1, 9))
254 self.assertEqual(x.vararg, 2)
255
256 def test_field_attr_writable(self):
257 x = ast.Num()
258 # We can assign to _fields
259 x._fields = 666
260 self.assertEqual(x._fields, 666)
261
262 def test_classattrs(self):
263 x = ast.Num()
264 self.assertEqual(x._fields, ('n',))
265
266 with self.assertRaises(AttributeError):
267 x.n
268
269 x = ast.Num(42)
270 self.assertEqual(x.n, 42)
271
272 with self.assertRaises(AttributeError):
273 x.lineno
274
275 with self.assertRaises(AttributeError):
276 x.foobar
277
278 x = ast.Num(lineno=2)
279 self.assertEqual(x.lineno, 2)
280
281 x = ast.Num(42, lineno=0)
282 self.assertEqual(x.lineno, 0)
283 self.assertEqual(x._fields, ('n',))
284 self.assertEqual(x.n, 42)
285
286 self.assertRaises(TypeError, ast.Num, 1, 2)
287 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
288
289 def test_module(self):
290 body = [ast.Num(42)]
291 x = ast.Module(body)
292 self.assertEqual(x.body, body)
293
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000294 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100295 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500296 x = ast.BinOp()
297 self.assertEqual(x._fields, ('left', 'op', 'right'))
298
299 # Random attribute allowed too
300 x.foobarbaz = 5
301 self.assertEqual(x.foobarbaz, 5)
302
303 n1 = ast.Num(1)
304 n3 = ast.Num(3)
305 addop = ast.Add()
306 x = ast.BinOp(n1, addop, n3)
307 self.assertEqual(x.left, n1)
308 self.assertEqual(x.op, addop)
309 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500310
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500311 x = ast.BinOp(1, 2, 3)
312 self.assertEqual(x.left, 1)
313 self.assertEqual(x.op, 2)
314 self.assertEqual(x.right, 3)
315
Georg Brandl0c77a822008-06-10 16:37:50 +0000316 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000317 self.assertEqual(x.left, 1)
318 self.assertEqual(x.op, 2)
319 self.assertEqual(x.right, 3)
320 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000321
322 # node raises exception when not given enough arguments
Georg Brandl0c77a822008-06-10 16:37:50 +0000323 self.assertRaises(TypeError, ast.BinOp, 1, 2)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500324 # node raises exception when given too many arguments
325 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
326 # node raises exception when not given enough arguments
327 self.assertRaises(TypeError, ast.BinOp, 1, 2, lineno=0)
328 # node raises exception when given too many arguments
329 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000330
331 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000332 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000333 self.assertEqual(x.left, 1)
334 self.assertEqual(x.op, 2)
335 self.assertEqual(x.right, 3)
336 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000337
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500338 # Random kwargs also allowed
339 x = ast.BinOp(1, 2, 3, foobarbaz=42)
340 self.assertEqual(x.foobarbaz, 42)
341
342 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000343 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000344 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500345 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000346
347 def test_pickling(self):
348 import pickle
349 mods = [pickle]
350 try:
351 import cPickle
352 mods.append(cPickle)
353 except ImportError:
354 pass
355 protocols = [0, 1, 2]
356 for mod in mods:
357 for protocol in protocols:
358 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
359 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000360 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000361
Benjamin Peterson5b066812010-11-20 01:38:49 +0000362 def test_invalid_sum(self):
363 pos = dict(lineno=2, col_offset=3)
364 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
365 with self.assertRaises(TypeError) as cm:
366 compile(m, "<test>", "exec")
367 self.assertIn("but got <_ast.expr", str(cm.exception))
368
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500369 def test_invalid_identitifer(self):
370 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
371 ast.fix_missing_locations(m)
372 with self.assertRaises(TypeError) as cm:
373 compile(m, "<test>", "exec")
374 self.assertIn("identifier must be of type str", str(cm.exception))
375
376 def test_invalid_string(self):
377 m = ast.Module([ast.Expr(ast.Str(42))])
378 ast.fix_missing_locations(m)
379 with self.assertRaises(TypeError) as cm:
380 compile(m, "<test>", "exec")
381 self.assertIn("string must be of type str", str(cm.exception))
382
Georg Brandl0c77a822008-06-10 16:37:50 +0000383
384class ASTHelpers_Test(unittest.TestCase):
385
386 def test_parse(self):
387 a = ast.parse('foo(1 + 1)')
388 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
389 self.assertEqual(ast.dump(a), ast.dump(b))
390
391 def test_dump(self):
392 node = ast.parse('spam(eggs, "and cheese")')
393 self.assertEqual(ast.dump(node),
394 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
395 "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
396 "keywords=[], starargs=None, kwargs=None))])"
397 )
398 self.assertEqual(ast.dump(node, annotate_fields=False),
399 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
400 "Str('and cheese')], [], None, None))])"
401 )
402 self.assertEqual(ast.dump(node, include_attributes=True),
403 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
404 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
405 "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
406 "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
407 "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
408 )
409
410 def test_copy_location(self):
411 src = ast.parse('1 + 1', mode='eval')
412 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
413 self.assertEqual(ast.dump(src, include_attributes=True),
414 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
415 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
416 'col_offset=0))'
417 )
418
419 def test_fix_missing_locations(self):
420 src = ast.parse('write("spam")')
421 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
422 [ast.Str('eggs')], [], None, None)))
423 self.assertEqual(src, ast.fix_missing_locations(src))
424 self.assertEqual(ast.dump(src, include_attributes=True),
425 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
426 "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, "
427 "col_offset=6)], keywords=[], starargs=None, kwargs=None, "
428 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
429 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
430 "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], "
431 "keywords=[], starargs=None, kwargs=None, lineno=1, "
432 "col_offset=0), lineno=1, col_offset=0)])"
433 )
434
435 def test_increment_lineno(self):
436 src = ast.parse('1 + 1', mode='eval')
437 self.assertEqual(ast.increment_lineno(src, n=3), src)
438 self.assertEqual(ast.dump(src, include_attributes=True),
439 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
440 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
441 'col_offset=0))'
442 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000443 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000444 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000445 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
446 self.assertEqual(ast.dump(src, include_attributes=True),
447 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
448 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
449 'col_offset=0))'
450 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000451
452 def test_iter_fields(self):
453 node = ast.parse('foo()', mode='eval')
454 d = dict(ast.iter_fields(node.body))
455 self.assertEqual(d.pop('func').id, 'foo')
456 self.assertEqual(d, {'keywords': [], 'kwargs': None,
457 'args': [], 'starargs': None})
458
459 def test_iter_child_nodes(self):
460 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
461 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
462 iterator = ast.iter_child_nodes(node.body)
463 self.assertEqual(next(iterator).id, 'spam')
464 self.assertEqual(next(iterator).n, 23)
465 self.assertEqual(next(iterator).n, 42)
466 self.assertEqual(ast.dump(next(iterator)),
467 "keyword(arg='eggs', value=Str(s='leek'))"
468 )
469
470 def test_get_docstring(self):
471 node = ast.parse('def foo():\n """line one\n line two"""')
472 self.assertEqual(ast.get_docstring(node.body[0]),
473 'line one\nline two')
474
475 def test_literal_eval(self):
476 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
477 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
478 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000479 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000480 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000481 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Raymond Hettingerbc959732010-10-08 00:47:45 +0000482 self.assertEqual(ast.literal_eval('-6'), -6)
483 self.assertEqual(ast.literal_eval('-6j+3'), 3-6j)
484 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Georg Brandl0c77a822008-06-10 16:37:50 +0000485
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000486 def test_literal_eval_issue4907(self):
487 self.assertEqual(ast.literal_eval('2j'), 2j)
488 self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
489 self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000490
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100491 def test_bad_integer(self):
492 # issue13436: Bad error message with invalid numeric values
493 body = [ast.ImportFrom(module='time',
494 names=[ast.alias(name='sleep')],
495 level=None,
496 lineno=None, col_offset=None)]
497 mod = ast.Module(body)
498 with self.assertRaises(ValueError) as cm:
499 compile(mod, 'test', 'exec')
500 self.assertIn("invalid integer value: None", str(cm.exception))
501
Georg Brandl0c77a822008-06-10 16:37:50 +0000502
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500503class ASTValidatorTests(unittest.TestCase):
504
505 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
506 mod.lineno = mod.col_offset = 0
507 ast.fix_missing_locations(mod)
508 with self.assertRaises(exc) as cm:
509 compile(mod, "<test>", mode)
510 if msg is not None:
511 self.assertIn(msg, str(cm.exception))
512
513 def expr(self, node, msg=None, *, exc=ValueError):
514 mod = ast.Module([ast.Expr(node)])
515 self.mod(mod, msg, exc=exc)
516
517 def stmt(self, stmt, msg=None):
518 mod = ast.Module([stmt])
519 self.mod(mod, msg)
520
521 def test_module(self):
522 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
523 self.mod(m, "must have Load context", "single")
524 m = ast.Expression(ast.Name("x", ast.Store()))
525 self.mod(m, "must have Load context", "eval")
526
527 def _check_arguments(self, fac, check):
528 def arguments(args=None, vararg=None, varargannotation=None,
529 kwonlyargs=None, kwarg=None, kwargannotation=None,
530 defaults=None, kw_defaults=None):
531 if args is None:
532 args = []
533 if kwonlyargs is None:
534 kwonlyargs = []
535 if defaults is None:
536 defaults = []
537 if kw_defaults is None:
538 kw_defaults = []
539 args = ast.arguments(args, vararg, varargannotation, kwonlyargs,
540 kwarg, kwargannotation, defaults, kw_defaults)
541 return fac(args)
542 args = [ast.arg("x", ast.Name("x", ast.Store()))]
543 check(arguments(args=args), "must have Load context")
544 check(arguments(varargannotation=ast.Num(3)),
545 "varargannotation but no vararg")
546 check(arguments(varargannotation=ast.Name("x", ast.Store()), vararg="x"),
547 "must have Load context")
548 check(arguments(kwonlyargs=args), "must have Load context")
549 check(arguments(kwargannotation=ast.Num(42)),
550 "kwargannotation but no kwarg")
551 check(arguments(kwargannotation=ast.Name("x", ast.Store()),
552 kwarg="x"), "must have Load context")
553 check(arguments(defaults=[ast.Num(3)]),
554 "more positional defaults than args")
555 check(arguments(kw_defaults=[ast.Num(4)]),
556 "length of kwonlyargs is not the same as kw_defaults")
557 args = [ast.arg("x", ast.Name("x", ast.Load()))]
558 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
559 "must have Load context")
560 args = [ast.arg("a", ast.Name("x", ast.Load())),
561 ast.arg("b", ast.Name("y", ast.Load()))]
562 check(arguments(kwonlyargs=args,
563 kw_defaults=[None, ast.Name("x", ast.Store())]),
564 "must have Load context")
565
566 def test_funcdef(self):
567 a = ast.arguments([], None, None, [], None, None, [], [])
568 f = ast.FunctionDef("x", a, [], [], None)
569 self.stmt(f, "empty body on FunctionDef")
570 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
571 None)
572 self.stmt(f, "must have Load context")
573 f = ast.FunctionDef("x", a, [ast.Pass()], [],
574 ast.Name("x", ast.Store()))
575 self.stmt(f, "must have Load context")
576 def fac(args):
577 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
578 self._check_arguments(fac, self.stmt)
579
580 def test_classdef(self):
581 def cls(bases=None, keywords=None, starargs=None, kwargs=None,
582 body=None, decorator_list=None):
583 if bases is None:
584 bases = []
585 if keywords is None:
586 keywords = []
587 if body is None:
588 body = [ast.Pass()]
589 if decorator_list is None:
590 decorator_list = []
591 return ast.ClassDef("myclass", bases, keywords, starargs,
592 kwargs, body, decorator_list)
593 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
594 "must have Load context")
595 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
596 "must have Load context")
597 self.stmt(cls(starargs=ast.Name("x", ast.Store())),
598 "must have Load context")
599 self.stmt(cls(kwargs=ast.Name("x", ast.Store())),
600 "must have Load context")
601 self.stmt(cls(body=[]), "empty body on ClassDef")
602 self.stmt(cls(body=[None]), "None disallowed")
603 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
604 "must have Load context")
605
606 def test_delete(self):
607 self.stmt(ast.Delete([]), "empty targets on Delete")
608 self.stmt(ast.Delete([None]), "None disallowed")
609 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
610 "must have Del context")
611
612 def test_assign(self):
613 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
614 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
615 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
616 "must have Store context")
617 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
618 ast.Name("y", ast.Store())),
619 "must have Load context")
620
621 def test_augassign(self):
622 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
623 ast.Name("y", ast.Load()))
624 self.stmt(aug, "must have Store context")
625 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
626 ast.Name("y", ast.Store()))
627 self.stmt(aug, "must have Load context")
628
629 def test_for(self):
630 x = ast.Name("x", ast.Store())
631 y = ast.Name("y", ast.Load())
632 p = ast.Pass()
633 self.stmt(ast.For(x, y, [], []), "empty body on For")
634 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
635 "must have Store context")
636 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
637 "must have Load context")
638 e = ast.Expr(ast.Name("x", ast.Store()))
639 self.stmt(ast.For(x, y, [e], []), "must have Load context")
640 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
641
642 def test_while(self):
643 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
644 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
645 "must have Load context")
646 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
647 [ast.Expr(ast.Name("x", ast.Store()))]),
648 "must have Load context")
649
650 def test_if(self):
651 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
652 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
653 self.stmt(i, "must have Load context")
654 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
655 self.stmt(i, "must have Load context")
656 i = ast.If(ast.Num(3), [ast.Pass()],
657 [ast.Expr(ast.Name("x", ast.Store()))])
658 self.stmt(i, "must have Load context")
659
660 def test_with(self):
661 p = ast.Pass()
662 self.stmt(ast.With([], [p]), "empty items on With")
663 i = ast.withitem(ast.Num(3), None)
664 self.stmt(ast.With([i], []), "empty body on With")
665 i = ast.withitem(ast.Name("x", ast.Store()), None)
666 self.stmt(ast.With([i], [p]), "must have Load context")
667 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
668 self.stmt(ast.With([i], [p]), "must have Store context")
669
670 def test_raise(self):
671 r = ast.Raise(None, ast.Num(3))
672 self.stmt(r, "Raise with cause but no exception")
673 r = ast.Raise(ast.Name("x", ast.Store()), None)
674 self.stmt(r, "must have Load context")
675 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
676 self.stmt(r, "must have Load context")
677
678 def test_try(self):
679 p = ast.Pass()
680 t = ast.Try([], [], [], [p])
681 self.stmt(t, "empty body on Try")
682 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
683 self.stmt(t, "must have Load context")
684 t = ast.Try([p], [], [], [])
685 self.stmt(t, "Try has neither except handlers nor finalbody")
686 t = ast.Try([p], [], [p], [p])
687 self.stmt(t, "Try has orelse but no except handlers")
688 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
689 self.stmt(t, "empty body on ExceptHandler")
690 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
691 self.stmt(ast.Try([p], e, [], []), "must have Load context")
692 e = [ast.ExceptHandler(None, "x", [p])]
693 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
694 self.stmt(t, "must have Load context")
695 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
696 self.stmt(t, "must have Load context")
697
698 def test_assert(self):
699 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
700 "must have Load context")
701 assrt = ast.Assert(ast.Name("x", ast.Load()),
702 ast.Name("y", ast.Store()))
703 self.stmt(assrt, "must have Load context")
704
705 def test_import(self):
706 self.stmt(ast.Import([]), "empty names on Import")
707
708 def test_importfrom(self):
709 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
710 self.stmt(imp, "level less than -1")
711 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
712
713 def test_global(self):
714 self.stmt(ast.Global([]), "empty names on Global")
715
716 def test_nonlocal(self):
717 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
718
719 def test_expr(self):
720 e = ast.Expr(ast.Name("x", ast.Store()))
721 self.stmt(e, "must have Load context")
722
723 def test_boolop(self):
724 b = ast.BoolOp(ast.And(), [])
725 self.expr(b, "less than 2 values")
726 b = ast.BoolOp(ast.And(), [ast.Num(3)])
727 self.expr(b, "less than 2 values")
728 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
729 self.expr(b, "None disallowed")
730 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
731 self.expr(b, "must have Load context")
732
733 def test_unaryop(self):
734 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
735 self.expr(u, "must have Load context")
736
737 def test_lambda(self):
738 a = ast.arguments([], None, None, [], None, None, [], [])
739 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
740 "must have Load context")
741 def fac(args):
742 return ast.Lambda(args, ast.Name("x", ast.Load()))
743 self._check_arguments(fac, self.expr)
744
745 def test_ifexp(self):
746 l = ast.Name("x", ast.Load())
747 s = ast.Name("y", ast.Store())
748 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -0500749 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500750
751 def test_dict(self):
752 d = ast.Dict([], [ast.Name("x", ast.Load())])
753 self.expr(d, "same number of keys as values")
754 d = ast.Dict([None], [ast.Name("x", ast.Load())])
755 self.expr(d, "None disallowed")
756 d = ast.Dict([ast.Name("x", ast.Load())], [None])
757 self.expr(d, "None disallowed")
758
759 def test_set(self):
760 self.expr(ast.Set([None]), "None disallowed")
761 s = ast.Set([ast.Name("x", ast.Store())])
762 self.expr(s, "must have Load context")
763
764 def _check_comprehension(self, fac):
765 self.expr(fac([]), "comprehension with no generators")
766 g = ast.comprehension(ast.Name("x", ast.Load()),
767 ast.Name("x", ast.Load()), [])
768 self.expr(fac([g]), "must have Store context")
769 g = ast.comprehension(ast.Name("x", ast.Store()),
770 ast.Name("x", ast.Store()), [])
771 self.expr(fac([g]), "must have Load context")
772 x = ast.Name("x", ast.Store())
773 y = ast.Name("y", ast.Load())
774 g = ast.comprehension(x, y, [None])
775 self.expr(fac([g]), "None disallowed")
776 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())])
777 self.expr(fac([g]), "must have Load context")
778
779 def _simple_comp(self, fac):
780 g = ast.comprehension(ast.Name("x", ast.Store()),
781 ast.Name("x", ast.Load()), [])
782 self.expr(fac(ast.Name("x", ast.Store()), [g]),
783 "must have Load context")
784 def wrap(gens):
785 return fac(ast.Name("x", ast.Store()), gens)
786 self._check_comprehension(wrap)
787
788 def test_listcomp(self):
789 self._simple_comp(ast.ListComp)
790
791 def test_setcomp(self):
792 self._simple_comp(ast.SetComp)
793
794 def test_generatorexp(self):
795 self._simple_comp(ast.GeneratorExp)
796
797 def test_dictcomp(self):
798 g = ast.comprehension(ast.Name("y", ast.Store()),
799 ast.Name("p", ast.Load()), [])
800 c = ast.DictComp(ast.Name("x", ast.Store()),
801 ast.Name("y", ast.Load()), [g])
802 self.expr(c, "must have Load context")
803 c = ast.DictComp(ast.Name("x", ast.Load()),
804 ast.Name("y", ast.Store()), [g])
805 self.expr(c, "must have Load context")
806 def factory(comps):
807 k = ast.Name("x", ast.Load())
808 v = ast.Name("y", ast.Load())
809 return ast.DictComp(k, v, comps)
810 self._check_comprehension(factory)
811
812 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -0500813 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
814 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500815
816 def test_compare(self):
817 left = ast.Name("x", ast.Load())
818 comp = ast.Compare(left, [ast.In()], [])
819 self.expr(comp, "no comparators")
820 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
821 self.expr(comp, "different number of comparators and operands")
822 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
823 self.expr(comp, "non-numeric", exc=TypeError)
824 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
825 self.expr(comp, "non-numeric", exc=TypeError)
826
827 def test_call(self):
828 func = ast.Name("x", ast.Load())
829 args = [ast.Name("y", ast.Load())]
830 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
831 stararg = ast.Name("p", ast.Load())
832 kwarg = ast.Name("q", ast.Load())
833 call = ast.Call(ast.Name("x", ast.Store()), args, keywords, stararg,
834 kwarg)
835 self.expr(call, "must have Load context")
836 call = ast.Call(func, [None], keywords, stararg, kwarg)
837 self.expr(call, "None disallowed")
838 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
839 call = ast.Call(func, args, bad_keywords, stararg, kwarg)
840 self.expr(call, "must have Load context")
841 call = ast.Call(func, args, keywords, ast.Name("z", ast.Store()), kwarg)
842 self.expr(call, "must have Load context")
843 call = ast.Call(func, args, keywords, stararg,
844 ast.Name("w", ast.Store()))
845 self.expr(call, "must have Load context")
846
847 def test_num(self):
848 class subint(int):
849 pass
850 class subfloat(float):
851 pass
852 class subcomplex(complex):
853 pass
854 for obj in "0", "hello", subint(), subfloat(), subcomplex():
855 self.expr(ast.Num(obj), "non-numeric", exc=TypeError)
856
857 def test_attribute(self):
858 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
859 self.expr(attr, "must have Load context")
860
861 def test_subscript(self):
862 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
863 ast.Load())
864 self.expr(sub, "must have Load context")
865 x = ast.Name("x", ast.Load())
866 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
867 ast.Load())
868 self.expr(sub, "must have Load context")
869 s = ast.Name("x", ast.Store())
870 for args in (s, None, None), (None, s, None), (None, None, s):
871 sl = ast.Slice(*args)
872 self.expr(ast.Subscript(x, sl, ast.Load()),
873 "must have Load context")
874 sl = ast.ExtSlice([])
875 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
876 sl = ast.ExtSlice([ast.Index(s)])
877 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
878
879 def test_starred(self):
880 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
881 ast.Store())
882 assign = ast.Assign([left], ast.Num(4))
883 self.stmt(assign, "must have Store context")
884
885 def _sequence(self, fac):
886 self.expr(fac([None], ast.Load()), "None disallowed")
887 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
888 "must have Load context")
889
890 def test_list(self):
891 self._sequence(ast.List)
892
893 def test_tuple(self):
894 self._sequence(ast.Tuple)
895
896 def test_stdlib_validates(self):
897 stdlib = os.path.dirname(ast.__file__)
898 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
899 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
900 for module in tests:
901 fn = os.path.join(stdlib, module)
902 with open(fn, "r", encoding="utf-8") as fp:
903 source = fp.read()
904 mod = ast.parse(source)
905 compile(mod, fn, "exec")
906
907
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000908def test_main():
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500909 support.run_unittest(AST_Tests, ASTHelpers_Test, ASTValidatorTests)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000910
911def main():
912 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000913 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000914 if sys.argv[1:] == ['-g']:
915 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
916 (eval_tests, "eval")):
917 print(kind+"_results = [")
918 for s in statements:
919 print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
920 print("]")
921 print("main()")
922 raise SystemExit
923 test_main()
Tim Peters400cbc32006-02-28 18:44:41 +0000924
925#### EVERYTHING BELOW IS GENERATED #####
926exec_results = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500927('Module', [('Expr', (1, 0), ('Name', (1, 0), 'None', ('Load',)))]),
Neal Norwitzc1505362006-12-28 06:47:50 +0000928('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500929('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', 'a', None)], None, None, [], None, None, [], []), [('Pass', (1, 10))], [], None)]),
930('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', 'a', None)], None, None, [], None, None, [('Num', (1, 8), 0)], []), [('Pass', (1, 12))], [], None)]),
931('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], 'args', None, [], None, None, [], []), [('Pass', (1, 14))], [], None)]),
932('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], 'kwargs', None, [], []), [('Pass', (1, 17))], [], None)]),
933('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 +0000934('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [])]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500935('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], None, None, [('Pass', (1, 17))], [])]),
Neal Norwitzc1505362006-12-28 06:47:50 +0000936('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 +0000937('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
938('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000939('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000940('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
941('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
942('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -0500943('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])]),
944('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 +0000945('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 -0500946('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])]),
947('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000948('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
949('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
950('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000951('Module', [('Global', (1, 0), ['v'])]),
952('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))]),
953('Module', [('Pass', (1, 0))]),
954('Module', [('Break', (1, 0))]),
955('Module', [('Continue', (1, 0))]),
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +0000956('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))], [])]),
957('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',)), [])]))]),
958('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 -0500959('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',)), [])]))]),
960('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',)), [])]))]),
961('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',))])]))]),
962('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',)), [])]))]),
963('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',))])]))]),
964('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 +0000965]
966single_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000967('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +0000968]
969eval_results = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500970('Expression', ('Name', (1, 0), 'None', ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000971('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
972('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
973('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Neal Norwitzc1505362006-12-28 06:47:50 +0000974('Expression', ('Lambda', (1, 0), ('arguments', [], None, None, [], None, None, [], []), ('Name', (1, 7), 'None', ('Load',)))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000975('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500976('Expression', ('Dict', (1, 0), [], [])),
977('Expression', ('Set', (1, 0), [('Name', (1, 1), 'None', ('Load',))])),
978('Expression', ('Dict', (1, 0), [('Num', (2, 6), 1)], [('Num', (4, 10), 2)])),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000979('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',))])])),
980('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',))])])),
981('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])),
982('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 +0000983('Expression', ('Num', (1, 0), 10)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000984('Expression', ('Str', (1, 0), 'string')),
985('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
986('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))),
987('Expression', ('Name', (1, 0), 'v', ('Load',))),
988('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500989('Expression', ('List', (1, 0), [], ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000990('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500991('Expression', ('Tuple', (1, 1), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
992('Expression', ('Tuple', (1, 0), [], ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000993('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 +0000994]
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000995main()