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