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