blob: b809d24c007318990485d042806a5ea64e88ce25 [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, ())
199
200 with self.assertRaises(AttributeError):
201 x.vararg
202
203 with self.assertRaises(AttributeError):
204 x.foobar = 21
205
206 with self.assertRaises(AttributeError):
207 ast.AST(lineno=2)
208
209 with self.assertRaises(TypeError):
210 # "_ast.AST constructor takes 0 positional arguments"
211 ast.AST(2)
212
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000213 def test_snippets(self):
214 for input, output, kind in ((exec_tests, exec_results, "exec"),
215 (single_tests, single_results, "single"),
216 (eval_tests, eval_results, "eval")):
217 for i, o in zip(input, output):
Georg Brandl0c77a822008-06-10 16:37:50 +0000218 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000219 self.assertEqual(to_tuple(ast_tree), o)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000220 self._assertTrueorder(ast_tree, (0, 0))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000221
Benjamin Peterson78565b22009-06-28 19:19:51 +0000222 def test_slice(self):
223 slc = ast.parse("x[::]").body[0].value.slice
224 self.assertIsNone(slc.upper)
225 self.assertIsNone(slc.lower)
226 self.assertIsNone(slc.step)
227
228 def test_from_import(self):
229 im = ast.parse("from . import y").body[0]
230 self.assertIsNone(im.module)
231
Benjamin Petersona0dfa822009-11-13 02:25:08 +0000232 def test_base_classes(self):
233 self.assertTrue(issubclass(ast.For, ast.stmt))
234 self.assertTrue(issubclass(ast.Name, ast.expr))
235 self.assertTrue(issubclass(ast.stmt, ast.AST))
236 self.assertTrue(issubclass(ast.expr, ast.AST))
237 self.assertTrue(issubclass(ast.comprehension, ast.AST))
238 self.assertTrue(issubclass(ast.Gt, ast.AST))
239
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500240 def test_field_attr_existence(self):
241 for name, item in ast.__dict__.items():
242 if isinstance(item, type) and name != 'AST' and name[0].isupper():
243 x = item()
244 if isinstance(x, ast.AST):
245 self.assertEqual(type(x._fields), tuple)
246
247 def test_arguments(self):
248 x = ast.arguments()
249 self.assertEqual(x._fields, ('args', 'vararg', 'varargannotation',
250 'kwonlyargs', 'kwarg', 'kwargannotation',
251 'defaults', 'kw_defaults'))
252
253 with self.assertRaises(AttributeError):
254 x.vararg
255
256 x = ast.arguments(*range(1, 9))
257 self.assertEqual(x.vararg, 2)
258
259 def test_field_attr_writable(self):
260 x = ast.Num()
261 # We can assign to _fields
262 x._fields = 666
263 self.assertEqual(x._fields, 666)
264
265 def test_classattrs(self):
266 x = ast.Num()
267 self.assertEqual(x._fields, ('n',))
268
269 with self.assertRaises(AttributeError):
270 x.n
271
272 x = ast.Num(42)
273 self.assertEqual(x.n, 42)
274
275 with self.assertRaises(AttributeError):
276 x.lineno
277
278 with self.assertRaises(AttributeError):
279 x.foobar
280
281 x = ast.Num(lineno=2)
282 self.assertEqual(x.lineno, 2)
283
284 x = ast.Num(42, lineno=0)
285 self.assertEqual(x.lineno, 0)
286 self.assertEqual(x._fields, ('n',))
287 self.assertEqual(x.n, 42)
288
289 self.assertRaises(TypeError, ast.Num, 1, 2)
290 self.assertRaises(TypeError, ast.Num, 1, 2, lineno=0)
291
292 def test_module(self):
293 body = [ast.Num(42)]
294 x = ast.Module(body)
295 self.assertEqual(x.body, body)
296
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000297 def test_nodeclasses(self):
Florent Xicluna992d9e02011-11-11 19:35:42 +0100298 # Zero arguments constructor explicitly allowed
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500299 x = ast.BinOp()
300 self.assertEqual(x._fields, ('left', 'op', 'right'))
301
302 # Random attribute allowed too
303 x.foobarbaz = 5
304 self.assertEqual(x.foobarbaz, 5)
305
306 n1 = ast.Num(1)
307 n3 = ast.Num(3)
308 addop = ast.Add()
309 x = ast.BinOp(n1, addop, n3)
310 self.assertEqual(x.left, n1)
311 self.assertEqual(x.op, addop)
312 self.assertEqual(x.right, n3)
Benjamin Peterson68b543a2011-06-27 17:51:18 -0500313
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500314 x = ast.BinOp(1, 2, 3)
315 self.assertEqual(x.left, 1)
316 self.assertEqual(x.op, 2)
317 self.assertEqual(x.right, 3)
318
Georg Brandl0c77a822008-06-10 16:37:50 +0000319 x = ast.BinOp(1, 2, 3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000320 self.assertEqual(x.left, 1)
321 self.assertEqual(x.op, 2)
322 self.assertEqual(x.right, 3)
323 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000324
325 # node raises exception when not given enough arguments
Georg Brandl0c77a822008-06-10 16:37:50 +0000326 self.assertRaises(TypeError, ast.BinOp, 1, 2)
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500327 # node raises exception when given too many arguments
328 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4)
329 # node raises exception when not given enough arguments
330 self.assertRaises(TypeError, ast.BinOp, 1, 2, lineno=0)
331 # node raises exception when given too many arguments
332 self.assertRaises(TypeError, ast.BinOp, 1, 2, 3, 4, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000333
334 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000335 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000336 self.assertEqual(x.left, 1)
337 self.assertEqual(x.op, 2)
338 self.assertEqual(x.right, 3)
339 self.assertEqual(x.lineno, 0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000340
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500341 # Random kwargs also allowed
342 x = ast.BinOp(1, 2, 3, foobarbaz=42)
343 self.assertEqual(x.foobarbaz, 42)
344
345 def test_no_fields(self):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000346 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000347 x = ast.Sub()
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500348 self.assertEqual(x._fields, ())
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000349
350 def test_pickling(self):
351 import pickle
352 mods = [pickle]
353 try:
354 import cPickle
355 mods.append(cPickle)
356 except ImportError:
357 pass
358 protocols = [0, 1, 2]
359 for mod in mods:
360 for protocol in protocols:
361 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
362 ast2 = mod.loads(mod.dumps(ast, protocol))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000363 self.assertEqual(to_tuple(ast2), to_tuple(ast))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000364
Benjamin Peterson5b066812010-11-20 01:38:49 +0000365 def test_invalid_sum(self):
366 pos = dict(lineno=2, col_offset=3)
367 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
368 with self.assertRaises(TypeError) as cm:
369 compile(m, "<test>", "exec")
370 self.assertIn("but got <_ast.expr", str(cm.exception))
371
Benjamin Peterson2193d2b2011-07-22 10:50:23 -0500372 def test_invalid_identitifer(self):
373 m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
374 ast.fix_missing_locations(m)
375 with self.assertRaises(TypeError) as cm:
376 compile(m, "<test>", "exec")
377 self.assertIn("identifier must be of type str", str(cm.exception))
378
379 def test_invalid_string(self):
380 m = ast.Module([ast.Expr(ast.Str(42))])
381 ast.fix_missing_locations(m)
382 with self.assertRaises(TypeError) as cm:
383 compile(m, "<test>", "exec")
384 self.assertIn("string must be of type str", str(cm.exception))
385
Georg Brandl0c77a822008-06-10 16:37:50 +0000386
387class ASTHelpers_Test(unittest.TestCase):
388
389 def test_parse(self):
390 a = ast.parse('foo(1 + 1)')
391 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
392 self.assertEqual(ast.dump(a), ast.dump(b))
393
394 def test_dump(self):
395 node = ast.parse('spam(eggs, "and cheese")')
396 self.assertEqual(ast.dump(node),
397 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
398 "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
399 "keywords=[], starargs=None, kwargs=None))])"
400 )
401 self.assertEqual(ast.dump(node, annotate_fields=False),
402 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
403 "Str('and cheese')], [], None, None))])"
404 )
405 self.assertEqual(ast.dump(node, include_attributes=True),
406 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
407 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
408 "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
409 "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
410 "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
411 )
412
413 def test_copy_location(self):
414 src = ast.parse('1 + 1', mode='eval')
415 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
416 self.assertEqual(ast.dump(src, include_attributes=True),
417 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
418 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
419 'col_offset=0))'
420 )
421
422 def test_fix_missing_locations(self):
423 src = ast.parse('write("spam")')
424 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
425 [ast.Str('eggs')], [], None, None)))
426 self.assertEqual(src, ast.fix_missing_locations(src))
427 self.assertEqual(ast.dump(src, include_attributes=True),
428 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
429 "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, "
430 "col_offset=6)], keywords=[], starargs=None, kwargs=None, "
431 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
432 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
433 "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], "
434 "keywords=[], starargs=None, kwargs=None, lineno=1, "
435 "col_offset=0), lineno=1, col_offset=0)])"
436 )
437
438 def test_increment_lineno(self):
439 src = ast.parse('1 + 1', mode='eval')
440 self.assertEqual(ast.increment_lineno(src, n=3), src)
441 self.assertEqual(ast.dump(src, include_attributes=True),
442 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
443 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
444 'col_offset=0))'
445 )
Georg Brandl619e7ba2011-01-09 07:38:51 +0000446 # issue10869: do not increment lineno of root twice
Georg Brandlefb69022011-01-09 07:50:48 +0000447 src = ast.parse('1 + 1', mode='eval')
Georg Brandl619e7ba2011-01-09 07:38:51 +0000448 self.assertEqual(ast.increment_lineno(src.body, n=3), src.body)
449 self.assertEqual(ast.dump(src, include_attributes=True),
450 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
451 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
452 'col_offset=0))'
453 )
Georg Brandl0c77a822008-06-10 16:37:50 +0000454
455 def test_iter_fields(self):
456 node = ast.parse('foo()', mode='eval')
457 d = dict(ast.iter_fields(node.body))
458 self.assertEqual(d.pop('func').id, 'foo')
459 self.assertEqual(d, {'keywords': [], 'kwargs': None,
460 'args': [], 'starargs': None})
461
462 def test_iter_child_nodes(self):
463 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
464 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
465 iterator = ast.iter_child_nodes(node.body)
466 self.assertEqual(next(iterator).id, 'spam')
467 self.assertEqual(next(iterator).n, 23)
468 self.assertEqual(next(iterator).n, 42)
469 self.assertEqual(ast.dump(next(iterator)),
470 "keyword(arg='eggs', value=Str(s='leek'))"
471 )
472
473 def test_get_docstring(self):
474 node = ast.parse('def foo():\n """line one\n line two"""')
475 self.assertEqual(ast.get_docstring(node.body[0]),
476 'line one\nline two')
477
478 def test_literal_eval(self):
479 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
480 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
481 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
Benjamin Peterson3e742892010-07-11 12:59:24 +0000482 self.assertEqual(ast.literal_eval('{1, 2, 3}'), {1, 2, 3})
Benjamin Peterson5ef96e52010-07-11 23:06:06 +0000483 self.assertEqual(ast.literal_eval('b"hi"'), b"hi")
Georg Brandl0c77a822008-06-10 16:37:50 +0000484 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
Raymond Hettingerbc959732010-10-08 00:47:45 +0000485 self.assertEqual(ast.literal_eval('-6'), -6)
486 self.assertEqual(ast.literal_eval('-6j+3'), 3-6j)
487 self.assertEqual(ast.literal_eval('3.25'), 3.25)
Georg Brandl0c77a822008-06-10 16:37:50 +0000488
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000489 def test_literal_eval_issue4907(self):
490 self.assertEqual(ast.literal_eval('2j'), 2j)
491 self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
492 self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000493
Amaury Forgeot d'Arc58e87612011-11-22 21:51:55 +0100494 def test_bad_integer(self):
495 # issue13436: Bad error message with invalid numeric values
496 body = [ast.ImportFrom(module='time',
497 names=[ast.alias(name='sleep')],
498 level=None,
499 lineno=None, col_offset=None)]
500 mod = ast.Module(body)
501 with self.assertRaises(ValueError) as cm:
502 compile(mod, 'test', 'exec')
503 self.assertIn("invalid integer value: None", str(cm.exception))
504
Georg Brandl0c77a822008-06-10 16:37:50 +0000505
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500506class ASTValidatorTests(unittest.TestCase):
507
508 def mod(self, mod, msg=None, mode="exec", *, exc=ValueError):
509 mod.lineno = mod.col_offset = 0
510 ast.fix_missing_locations(mod)
511 with self.assertRaises(exc) as cm:
512 compile(mod, "<test>", mode)
513 if msg is not None:
514 self.assertIn(msg, str(cm.exception))
515
516 def expr(self, node, msg=None, *, exc=ValueError):
517 mod = ast.Module([ast.Expr(node)])
518 self.mod(mod, msg, exc=exc)
519
520 def stmt(self, stmt, msg=None):
521 mod = ast.Module([stmt])
522 self.mod(mod, msg)
523
524 def test_module(self):
525 m = ast.Interactive([ast.Expr(ast.Name("x", ast.Store()))])
526 self.mod(m, "must have Load context", "single")
527 m = ast.Expression(ast.Name("x", ast.Store()))
528 self.mod(m, "must have Load context", "eval")
529
530 def _check_arguments(self, fac, check):
531 def arguments(args=None, vararg=None, varargannotation=None,
532 kwonlyargs=None, kwarg=None, kwargannotation=None,
533 defaults=None, kw_defaults=None):
534 if args is None:
535 args = []
536 if kwonlyargs is None:
537 kwonlyargs = []
538 if defaults is None:
539 defaults = []
540 if kw_defaults is None:
541 kw_defaults = []
542 args = ast.arguments(args, vararg, varargannotation, kwonlyargs,
543 kwarg, kwargannotation, defaults, kw_defaults)
544 return fac(args)
545 args = [ast.arg("x", ast.Name("x", ast.Store()))]
546 check(arguments(args=args), "must have Load context")
547 check(arguments(varargannotation=ast.Num(3)),
548 "varargannotation but no vararg")
549 check(arguments(varargannotation=ast.Name("x", ast.Store()), vararg="x"),
550 "must have Load context")
551 check(arguments(kwonlyargs=args), "must have Load context")
552 check(arguments(kwargannotation=ast.Num(42)),
553 "kwargannotation but no kwarg")
554 check(arguments(kwargannotation=ast.Name("x", ast.Store()),
555 kwarg="x"), "must have Load context")
556 check(arguments(defaults=[ast.Num(3)]),
557 "more positional defaults than args")
558 check(arguments(kw_defaults=[ast.Num(4)]),
559 "length of kwonlyargs is not the same as kw_defaults")
560 args = [ast.arg("x", ast.Name("x", ast.Load()))]
561 check(arguments(args=args, defaults=[ast.Name("x", ast.Store())]),
562 "must have Load context")
563 args = [ast.arg("a", ast.Name("x", ast.Load())),
564 ast.arg("b", ast.Name("y", ast.Load()))]
565 check(arguments(kwonlyargs=args,
566 kw_defaults=[None, ast.Name("x", ast.Store())]),
567 "must have Load context")
568
569 def test_funcdef(self):
570 a = ast.arguments([], None, None, [], None, None, [], [])
571 f = ast.FunctionDef("x", a, [], [], None)
572 self.stmt(f, "empty body on FunctionDef")
573 f = ast.FunctionDef("x", a, [ast.Pass()], [ast.Name("x", ast.Store())],
574 None)
575 self.stmt(f, "must have Load context")
576 f = ast.FunctionDef("x", a, [ast.Pass()], [],
577 ast.Name("x", ast.Store()))
578 self.stmt(f, "must have Load context")
579 def fac(args):
580 return ast.FunctionDef("x", args, [ast.Pass()], [], None)
581 self._check_arguments(fac, self.stmt)
582
583 def test_classdef(self):
584 def cls(bases=None, keywords=None, starargs=None, kwargs=None,
585 body=None, decorator_list=None):
586 if bases is None:
587 bases = []
588 if keywords is None:
589 keywords = []
590 if body is None:
591 body = [ast.Pass()]
592 if decorator_list is None:
593 decorator_list = []
594 return ast.ClassDef("myclass", bases, keywords, starargs,
595 kwargs, body, decorator_list)
596 self.stmt(cls(bases=[ast.Name("x", ast.Store())]),
597 "must have Load context")
598 self.stmt(cls(keywords=[ast.keyword("x", ast.Name("x", ast.Store()))]),
599 "must have Load context")
600 self.stmt(cls(starargs=ast.Name("x", ast.Store())),
601 "must have Load context")
602 self.stmt(cls(kwargs=ast.Name("x", ast.Store())),
603 "must have Load context")
604 self.stmt(cls(body=[]), "empty body on ClassDef")
605 self.stmt(cls(body=[None]), "None disallowed")
606 self.stmt(cls(decorator_list=[ast.Name("x", ast.Store())]),
607 "must have Load context")
608
609 def test_delete(self):
610 self.stmt(ast.Delete([]), "empty targets on Delete")
611 self.stmt(ast.Delete([None]), "None disallowed")
612 self.stmt(ast.Delete([ast.Name("x", ast.Load())]),
613 "must have Del context")
614
615 def test_assign(self):
616 self.stmt(ast.Assign([], ast.Num(3)), "empty targets on Assign")
617 self.stmt(ast.Assign([None], ast.Num(3)), "None disallowed")
618 self.stmt(ast.Assign([ast.Name("x", ast.Load())], ast.Num(3)),
619 "must have Store context")
620 self.stmt(ast.Assign([ast.Name("x", ast.Store())],
621 ast.Name("y", ast.Store())),
622 "must have Load context")
623
624 def test_augassign(self):
625 aug = ast.AugAssign(ast.Name("x", ast.Load()), ast.Add(),
626 ast.Name("y", ast.Load()))
627 self.stmt(aug, "must have Store context")
628 aug = ast.AugAssign(ast.Name("x", ast.Store()), ast.Add(),
629 ast.Name("y", ast.Store()))
630 self.stmt(aug, "must have Load context")
631
632 def test_for(self):
633 x = ast.Name("x", ast.Store())
634 y = ast.Name("y", ast.Load())
635 p = ast.Pass()
636 self.stmt(ast.For(x, y, [], []), "empty body on For")
637 self.stmt(ast.For(ast.Name("x", ast.Load()), y, [p], []),
638 "must have Store context")
639 self.stmt(ast.For(x, ast.Name("y", ast.Store()), [p], []),
640 "must have Load context")
641 e = ast.Expr(ast.Name("x", ast.Store()))
642 self.stmt(ast.For(x, y, [e], []), "must have Load context")
643 self.stmt(ast.For(x, y, [p], [e]), "must have Load context")
644
645 def test_while(self):
646 self.stmt(ast.While(ast.Num(3), [], []), "empty body on While")
647 self.stmt(ast.While(ast.Name("x", ast.Store()), [ast.Pass()], []),
648 "must have Load context")
649 self.stmt(ast.While(ast.Num(3), [ast.Pass()],
650 [ast.Expr(ast.Name("x", ast.Store()))]),
651 "must have Load context")
652
653 def test_if(self):
654 self.stmt(ast.If(ast.Num(3), [], []), "empty body on If")
655 i = ast.If(ast.Name("x", ast.Store()), [ast.Pass()], [])
656 self.stmt(i, "must have Load context")
657 i = ast.If(ast.Num(3), [ast.Expr(ast.Name("x", ast.Store()))], [])
658 self.stmt(i, "must have Load context")
659 i = ast.If(ast.Num(3), [ast.Pass()],
660 [ast.Expr(ast.Name("x", ast.Store()))])
661 self.stmt(i, "must have Load context")
662
663 def test_with(self):
664 p = ast.Pass()
665 self.stmt(ast.With([], [p]), "empty items on With")
666 i = ast.withitem(ast.Num(3), None)
667 self.stmt(ast.With([i], []), "empty body on With")
668 i = ast.withitem(ast.Name("x", ast.Store()), None)
669 self.stmt(ast.With([i], [p]), "must have Load context")
670 i = ast.withitem(ast.Num(3), ast.Name("x", ast.Load()))
671 self.stmt(ast.With([i], [p]), "must have Store context")
672
673 def test_raise(self):
674 r = ast.Raise(None, ast.Num(3))
675 self.stmt(r, "Raise with cause but no exception")
676 r = ast.Raise(ast.Name("x", ast.Store()), None)
677 self.stmt(r, "must have Load context")
678 r = ast.Raise(ast.Num(4), ast.Name("x", ast.Store()))
679 self.stmt(r, "must have Load context")
680
681 def test_try(self):
682 p = ast.Pass()
683 t = ast.Try([], [], [], [p])
684 self.stmt(t, "empty body on Try")
685 t = ast.Try([ast.Expr(ast.Name("x", ast.Store()))], [], [], [p])
686 self.stmt(t, "must have Load context")
687 t = ast.Try([p], [], [], [])
688 self.stmt(t, "Try has neither except handlers nor finalbody")
689 t = ast.Try([p], [], [p], [p])
690 self.stmt(t, "Try has orelse but no except handlers")
691 t = ast.Try([p], [ast.ExceptHandler(None, "x", [])], [], [])
692 self.stmt(t, "empty body on ExceptHandler")
693 e = [ast.ExceptHandler(ast.Name("x", ast.Store()), "y", [p])]
694 self.stmt(ast.Try([p], e, [], []), "must have Load context")
695 e = [ast.ExceptHandler(None, "x", [p])]
696 t = ast.Try([p], e, [ast.Expr(ast.Name("x", ast.Store()))], [p])
697 self.stmt(t, "must have Load context")
698 t = ast.Try([p], e, [p], [ast.Expr(ast.Name("x", ast.Store()))])
699 self.stmt(t, "must have Load context")
700
701 def test_assert(self):
702 self.stmt(ast.Assert(ast.Name("x", ast.Store()), None),
703 "must have Load context")
704 assrt = ast.Assert(ast.Name("x", ast.Load()),
705 ast.Name("y", ast.Store()))
706 self.stmt(assrt, "must have Load context")
707
708 def test_import(self):
709 self.stmt(ast.Import([]), "empty names on Import")
710
711 def test_importfrom(self):
712 imp = ast.ImportFrom(None, [ast.alias("x", None)], -42)
713 self.stmt(imp, "level less than -1")
714 self.stmt(ast.ImportFrom(None, [], 0), "empty names on ImportFrom")
715
716 def test_global(self):
717 self.stmt(ast.Global([]), "empty names on Global")
718
719 def test_nonlocal(self):
720 self.stmt(ast.Nonlocal([]), "empty names on Nonlocal")
721
722 def test_expr(self):
723 e = ast.Expr(ast.Name("x", ast.Store()))
724 self.stmt(e, "must have Load context")
725
726 def test_boolop(self):
727 b = ast.BoolOp(ast.And(), [])
728 self.expr(b, "less than 2 values")
729 b = ast.BoolOp(ast.And(), [ast.Num(3)])
730 self.expr(b, "less than 2 values")
731 b = ast.BoolOp(ast.And(), [ast.Num(4), None])
732 self.expr(b, "None disallowed")
733 b = ast.BoolOp(ast.And(), [ast.Num(4), ast.Name("x", ast.Store())])
734 self.expr(b, "must have Load context")
735
736 def test_unaryop(self):
737 u = ast.UnaryOp(ast.Not(), ast.Name("x", ast.Store()))
738 self.expr(u, "must have Load context")
739
740 def test_lambda(self):
741 a = ast.arguments([], None, None, [], None, None, [], [])
742 self.expr(ast.Lambda(a, ast.Name("x", ast.Store())),
743 "must have Load context")
744 def fac(args):
745 return ast.Lambda(args, ast.Name("x", ast.Load()))
746 self._check_arguments(fac, self.expr)
747
748 def test_ifexp(self):
749 l = ast.Name("x", ast.Load())
750 s = ast.Name("y", ast.Store())
751 for args in (s, l, l), (l, s, l), (l, l, s):
Benjamin Peterson71ce8972011-08-09 16:17:12 -0500752 self.expr(ast.IfExp(*args), "must have Load context")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500753
754 def test_dict(self):
755 d = ast.Dict([], [ast.Name("x", ast.Load())])
756 self.expr(d, "same number of keys as values")
757 d = ast.Dict([None], [ast.Name("x", ast.Load())])
758 self.expr(d, "None disallowed")
759 d = ast.Dict([ast.Name("x", ast.Load())], [None])
760 self.expr(d, "None disallowed")
761
762 def test_set(self):
763 self.expr(ast.Set([None]), "None disallowed")
764 s = ast.Set([ast.Name("x", ast.Store())])
765 self.expr(s, "must have Load context")
766
767 def _check_comprehension(self, fac):
768 self.expr(fac([]), "comprehension with no generators")
769 g = ast.comprehension(ast.Name("x", ast.Load()),
770 ast.Name("x", ast.Load()), [])
771 self.expr(fac([g]), "must have Store context")
772 g = ast.comprehension(ast.Name("x", ast.Store()),
773 ast.Name("x", ast.Store()), [])
774 self.expr(fac([g]), "must have Load context")
775 x = ast.Name("x", ast.Store())
776 y = ast.Name("y", ast.Load())
777 g = ast.comprehension(x, y, [None])
778 self.expr(fac([g]), "None disallowed")
779 g = ast.comprehension(x, y, [ast.Name("x", ast.Store())])
780 self.expr(fac([g]), "must have Load context")
781
782 def _simple_comp(self, fac):
783 g = ast.comprehension(ast.Name("x", ast.Store()),
784 ast.Name("x", ast.Load()), [])
785 self.expr(fac(ast.Name("x", ast.Store()), [g]),
786 "must have Load context")
787 def wrap(gens):
788 return fac(ast.Name("x", ast.Store()), gens)
789 self._check_comprehension(wrap)
790
791 def test_listcomp(self):
792 self._simple_comp(ast.ListComp)
793
794 def test_setcomp(self):
795 self._simple_comp(ast.SetComp)
796
797 def test_generatorexp(self):
798 self._simple_comp(ast.GeneratorExp)
799
800 def test_dictcomp(self):
801 g = ast.comprehension(ast.Name("y", ast.Store()),
802 ast.Name("p", ast.Load()), [])
803 c = ast.DictComp(ast.Name("x", ast.Store()),
804 ast.Name("y", ast.Load()), [g])
805 self.expr(c, "must have Load context")
806 c = ast.DictComp(ast.Name("x", ast.Load()),
807 ast.Name("y", ast.Store()), [g])
808 self.expr(c, "must have Load context")
809 def factory(comps):
810 k = ast.Name("x", ast.Load())
811 v = ast.Name("y", ast.Load())
812 return ast.DictComp(k, v, comps)
813 self._check_comprehension(factory)
814
815 def test_yield(self):
Benjamin Peterson527c6222012-01-14 08:58:23 -0500816 self.expr(ast.Yield(ast.Name("x", ast.Store())), "must have Load")
817 self.expr(ast.YieldFrom(ast.Name("x", ast.Store())), "must have Load")
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500818
819 def test_compare(self):
820 left = ast.Name("x", ast.Load())
821 comp = ast.Compare(left, [ast.In()], [])
822 self.expr(comp, "no comparators")
823 comp = ast.Compare(left, [ast.In()], [ast.Num(4), ast.Num(5)])
824 self.expr(comp, "different number of comparators and operands")
825 comp = ast.Compare(ast.Num("blah"), [ast.In()], [left])
826 self.expr(comp, "non-numeric", exc=TypeError)
827 comp = ast.Compare(left, [ast.In()], [ast.Num("blah")])
828 self.expr(comp, "non-numeric", exc=TypeError)
829
830 def test_call(self):
831 func = ast.Name("x", ast.Load())
832 args = [ast.Name("y", ast.Load())]
833 keywords = [ast.keyword("w", ast.Name("z", ast.Load()))]
834 stararg = ast.Name("p", ast.Load())
835 kwarg = ast.Name("q", ast.Load())
836 call = ast.Call(ast.Name("x", ast.Store()), args, keywords, stararg,
837 kwarg)
838 self.expr(call, "must have Load context")
839 call = ast.Call(func, [None], keywords, stararg, kwarg)
840 self.expr(call, "None disallowed")
841 bad_keywords = [ast.keyword("w", ast.Name("z", ast.Store()))]
842 call = ast.Call(func, args, bad_keywords, stararg, kwarg)
843 self.expr(call, "must have Load context")
844 call = ast.Call(func, args, keywords, ast.Name("z", ast.Store()), kwarg)
845 self.expr(call, "must have Load context")
846 call = ast.Call(func, args, keywords, stararg,
847 ast.Name("w", ast.Store()))
848 self.expr(call, "must have Load context")
849
850 def test_num(self):
851 class subint(int):
852 pass
853 class subfloat(float):
854 pass
855 class subcomplex(complex):
856 pass
857 for obj in "0", "hello", subint(), subfloat(), subcomplex():
858 self.expr(ast.Num(obj), "non-numeric", exc=TypeError)
859
860 def test_attribute(self):
861 attr = ast.Attribute(ast.Name("x", ast.Store()), "y", ast.Load())
862 self.expr(attr, "must have Load context")
863
864 def test_subscript(self):
865 sub = ast.Subscript(ast.Name("x", ast.Store()), ast.Index(ast.Num(3)),
866 ast.Load())
867 self.expr(sub, "must have Load context")
868 x = ast.Name("x", ast.Load())
869 sub = ast.Subscript(x, ast.Index(ast.Name("y", ast.Store())),
870 ast.Load())
871 self.expr(sub, "must have Load context")
872 s = ast.Name("x", ast.Store())
873 for args in (s, None, None), (None, s, None), (None, None, s):
874 sl = ast.Slice(*args)
875 self.expr(ast.Subscript(x, sl, ast.Load()),
876 "must have Load context")
877 sl = ast.ExtSlice([])
878 self.expr(ast.Subscript(x, sl, ast.Load()), "empty dims on ExtSlice")
879 sl = ast.ExtSlice([ast.Index(s)])
880 self.expr(ast.Subscript(x, sl, ast.Load()), "must have Load context")
881
882 def test_starred(self):
883 left = ast.List([ast.Starred(ast.Name("x", ast.Load()), ast.Store())],
884 ast.Store())
885 assign = ast.Assign([left], ast.Num(4))
886 self.stmt(assign, "must have Store context")
887
888 def _sequence(self, fac):
889 self.expr(fac([None], ast.Load()), "None disallowed")
890 self.expr(fac([ast.Name("x", ast.Store())], ast.Load()),
891 "must have Load context")
892
893 def test_list(self):
894 self._sequence(ast.List)
895
896 def test_tuple(self):
897 self._sequence(ast.Tuple)
898
899 def test_stdlib_validates(self):
900 stdlib = os.path.dirname(ast.__file__)
901 tests = [fn for fn in os.listdir(stdlib) if fn.endswith(".py")]
902 tests.extend(["test/test_grammar.py", "test/test_unpack_ex.py"])
903 for module in tests:
904 fn = os.path.join(stdlib, module)
905 with open(fn, "r", encoding="utf-8") as fp:
906 source = fp.read()
907 mod = ast.parse(source)
908 compile(mod, fn, "exec")
909
910
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000911def test_main():
Benjamin Peterson832bfe22011-08-09 16:15:04 -0500912 support.run_unittest(AST_Tests, ASTHelpers_Test, ASTValidatorTests)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000913
914def main():
915 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000916 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000917 if sys.argv[1:] == ['-g']:
918 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
919 (eval_tests, "eval")):
920 print(kind+"_results = [")
921 for s in statements:
922 print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
923 print("]")
924 print("main()")
925 raise SystemExit
926 test_main()
Tim Peters400cbc32006-02-28 18:44:41 +0000927
928#### EVERYTHING BELOW IS GENERATED #####
929exec_results = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500930('Module', [('Expr', (1, 0), ('Name', (1, 0), 'None', ('Load',)))]),
Neal Norwitzc1505362006-12-28 06:47:50 +0000931('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500932('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', 'a', None)], None, None, [], None, None, [], []), [('Pass', (1, 10))], [], None)]),
933('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [('arg', 'a', None)], None, None, [], None, None, [('Num', (1, 8), 0)], []), [('Pass', (1, 12))], [], None)]),
934('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], 'args', None, [], None, None, [], []), [('Pass', (1, 14))], [], None)]),
935('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], 'kwargs', None, [], []), [('Pass', (1, 17))], [], None)]),
936('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 +0000937('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [])]),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500938('Module', [('ClassDef', (1, 0), 'C', [('Name', (1, 8), 'object', ('Load',))], [], None, None, [('Pass', (1, 17))], [])]),
Neal Norwitzc1505362006-12-28 06:47:50 +0000939('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 +0000940('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
941('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000942('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000943('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
944('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
945('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
Benjamin Petersonaeabd5f2011-05-27 15:02:03 -0500946('Module', [('With', (1, 0), [('withitem', ('Name', (1, 5), 'x', ('Load',)), ('Name', (1, 10), 'y', ('Store',)))], [('Pass', (1, 13))])]),
947('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 +0000948('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 -0500949('Module', [('Try', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [], [])]),
950('Module', [('Try', (1, 0), [('Pass', (2, 2))], [], [], [('Pass', (4, 2))])]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000951('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
952('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
953('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000954('Module', [('Global', (1, 0), ['v'])]),
955('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))]),
956('Module', [('Pass', (1, 0))]),
957('Module', [('Break', (1, 0))]),
958('Module', [('Continue', (1, 0))]),
Benjamin Peterson2e4b0e12009-09-11 22:36:20 +0000959('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))], [])]),
960('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',)), [])]))]),
961('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 -0500962('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',)), [])]))]),
963('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',)), [])]))]),
964('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',))])]))]),
965('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',)), [])]))]),
966('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',))])]))]),
967('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 +0000968]
969single_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000970('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +0000971]
972eval_results = [
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500973('Expression', ('Name', (1, 0), 'None', ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000974('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
975('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
976('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Neal Norwitzc1505362006-12-28 06:47:50 +0000977('Expression', ('Lambda', (1, 0), ('arguments', [], None, None, [], None, None, [], []), ('Name', (1, 7), 'None', ('Load',)))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000978('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500979('Expression', ('Dict', (1, 0), [], [])),
980('Expression', ('Set', (1, 0), [('Name', (1, 1), 'None', ('Load',))])),
981('Expression', ('Dict', (1, 0), [('Num', (2, 6), 1)], [('Num', (4, 10), 2)])),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000982('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',))])])),
983('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',))])])),
984('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])),
985('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 +0000986('Expression', ('Num', (1, 0), 10)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000987('Expression', ('Str', (1, 0), 'string')),
988('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
989('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))),
990('Expression', ('Name', (1, 0), 'v', ('Load',))),
991('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500992('Expression', ('List', (1, 0), [], ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000993('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))),
Benjamin Peterson6ccfe852011-06-27 17:46:06 -0500994('Expression', ('Tuple', (1, 1), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
995('Expression', ('Tuple', (1, 0), [], ('Load',))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000996('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 +0000997]
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000998main()