blob: 01c4ba38ca034da1416d3ead274c3e55c41d15eb [file] [log] [blame]
Neal Norwitzee9b10a2008-03-31 05:29:39 +00001import sys, unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Georg Brandl0c77a822008-06-10 16:37:50 +00003import ast
Tim Peters400cbc32006-02-28 18:44:41 +00004
5def to_tuple(t):
Guido van Rossum3172c5d2007-10-16 18:12:55 +00006 if t is None or isinstance(t, (str, int, complex)):
Tim Peters400cbc32006-02-28 18:44:41 +00007 return t
8 elif isinstance(t, list):
9 return [to_tuple(e) for e in t]
10 result = [t.__class__.__name__]
Martin v. Löwis49c5da12006-03-01 22:49:05 +000011 if hasattr(t, 'lineno') and hasattr(t, 'col_offset'):
12 result.append((t.lineno, t.col_offset))
Tim Peters400cbc32006-02-28 18:44:41 +000013 if t._fields is None:
14 return tuple(result)
15 for f in t._fields:
16 result.append(to_tuple(getattr(t, f)))
17 return tuple(result)
18
Neal Norwitzee9b10a2008-03-31 05:29:39 +000019
Tim Peters400cbc32006-02-28 18:44:41 +000020# These tests are compiled through "exec"
21# There should be atleast one test per statement
22exec_tests = [
23 # FunctionDef
24 "def f(): pass",
25 # ClassDef
26 "class C:pass",
27 # Return
28 "def f():return 1",
29 # Delete
30 "del v",
31 # Assign
32 "v = 1",
33 # AugAssign
34 "v += 1",
Tim Peters400cbc32006-02-28 18:44:41 +000035 # For
36 "for v in v:pass",
37 # While
38 "while v:pass",
39 # If
40 "if v:pass",
41 # Raise
Collin Winter828f04a2007-08-31 00:04:24 +000042 "raise Exception('string')",
Tim Peters400cbc32006-02-28 18:44:41 +000043 # TryExcept
44 "try:\n pass\nexcept Exception:\n pass",
45 # TryFinally
46 "try:\n pass\nfinally:\n pass",
47 # Assert
48 "assert v",
49 # Import
50 "import sys",
51 # ImportFrom
52 "from sys import v",
Tim Peters400cbc32006-02-28 18:44:41 +000053 # Global
54 "global v",
55 # Expr
56 "1",
57 # Pass,
58 "pass",
59 # Break
60 "break",
61 # Continue
62 "continue",
63]
64
65# These are compiled through "single"
66# because of overlap with "eval", it just tests what
67# can't be tested with "eval"
68single_tests = [
69 "1+2"
70]
71
72# These are compiled through "eval"
73# It should test all expressions
74eval_tests = [
75 # BoolOp
76 "a and b",
77 # BinOp
78 "a + b",
79 # UnaryOp
80 "not v",
81 # Lambda
82 "lambda:None",
83 # Dict
84 "{ 1:2 }",
85 # ListComp
86 "[a for b in c if d]",
87 # GeneratorExp
88 "(a for b in c if d)",
89 # Yield - yield expressions can't work outside a function
90 #
91 # Compare
92 "1 < 2 < 3",
93 # Call
94 "f(1,2,c=3,*d,**e)",
Tim Peters400cbc32006-02-28 18:44:41 +000095 # Num
Guido van Rossume2a383d2007-01-15 16:59:06 +000096 "10",
Tim Peters400cbc32006-02-28 18:44:41 +000097 # Str
98 "'string'",
99 # Attribute
100 "a.b",
101 # Subscript
102 "a[b:c]",
103 # Name
104 "v",
105 # List
106 "[1,2,3]",
107 # Tuple
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000108 "1,2,3",
109 # Combination
110 "a.b.c.d(a.b[1:2])",
111
Tim Peters400cbc32006-02-28 18:44:41 +0000112]
113
114# TODO: expr_context, slice, boolop, operator, unaryop, cmpop, comprehension
115# excepthandler, arguments, keywords, alias
116
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000117class AST_Tests(unittest.TestCase):
Tim Peters400cbc32006-02-28 18:44:41 +0000118
Georg Brandlab91fde2009-08-13 08:51:18 +0000119 def _assertTrueorder(self, ast_node, parent_pos):
Georg Brandl0c77a822008-06-10 16:37:50 +0000120 if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000121 return
Georg Brandl0c77a822008-06-10 16:37:50 +0000122 if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000123 node_pos = (ast_node.lineno, ast_node.col_offset)
Georg Brandlab91fde2009-08-13 08:51:18 +0000124 self.assertTrue(node_pos >= parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000125 parent_pos = (ast_node.lineno, ast_node.col_offset)
126 for name in ast_node._fields:
127 value = getattr(ast_node, name)
128 if isinstance(value, list):
129 for child in value:
Georg Brandlab91fde2009-08-13 08:51:18 +0000130 self._assertTrueorder(child, parent_pos)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000131 elif value is not None:
Georg Brandlab91fde2009-08-13 08:51:18 +0000132 self._assertTrueorder(value, parent_pos)
Tim Peters5ddfe412006-03-01 23:02:57 +0000133
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000134 def test_snippets(self):
135 for input, output, kind in ((exec_tests, exec_results, "exec"),
136 (single_tests, single_results, "single"),
137 (eval_tests, eval_results, "eval")):
138 for i, o in zip(input, output):
Georg Brandl0c77a822008-06-10 16:37:50 +0000139 ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000140 self.assertEquals(to_tuple(ast_tree), o)
Georg Brandlab91fde2009-08-13 08:51:18 +0000141 self._assertTrueorder(ast_tree, (0, 0))
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000142
Benjamin Peterson8f6713f2009-11-13 02:29:35 +0000143 def test_base_classes(self):
144 self.assertTrue(issubclass(ast.For, ast.stmt))
145 self.assertTrue(issubclass(ast.Name, ast.expr))
146 self.assertTrue(issubclass(ast.stmt, ast.AST))
147 self.assertTrue(issubclass(ast.expr, ast.AST))
148 self.assertTrue(issubclass(ast.comprehension, ast.AST))
149 self.assertTrue(issubclass(ast.Gt, ast.AST))
150
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000151 def test_nodeclasses(self):
Georg Brandl0c77a822008-06-10 16:37:50 +0000152 x = ast.BinOp(1, 2, 3, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000153 self.assertEquals(x.left, 1)
154 self.assertEquals(x.op, 2)
155 self.assertEquals(x.right, 3)
156 self.assertEquals(x.lineno, 0)
157
158 # node raises exception when not given enough arguments
Georg Brandl0c77a822008-06-10 16:37:50 +0000159 self.assertRaises(TypeError, ast.BinOp, 1, 2)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000160
161 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000162 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000163 self.assertEquals(x.left, 1)
164 self.assertEquals(x.op, 2)
165 self.assertEquals(x.right, 3)
166 self.assertEquals(x.lineno, 0)
167
168 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000169 x = ast.Sub()
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000170
171 def test_pickling(self):
172 import pickle
173 mods = [pickle]
174 try:
175 import cPickle
176 mods.append(cPickle)
177 except ImportError:
178 pass
179 protocols = [0, 1, 2]
180 for mod in mods:
181 for protocol in protocols:
182 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
183 ast2 = mod.loads(mod.dumps(ast, protocol))
184 self.assertEquals(to_tuple(ast2), to_tuple(ast))
185
Benjamin Petersonaab95852010-11-20 01:48:38 +0000186 def test_invalid_sum(self):
187 pos = dict(lineno=2, col_offset=3)
188 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
189 try:
190 compile(m, "<test>", "exec")
191 except TypeError as exc:
192 self.assertIn("but got <_ast.expr", str(exc))
193 else:
194 self.fail("needed TypeError")
195
Georg Brandl0c77a822008-06-10 16:37:50 +0000196
197class ASTHelpers_Test(unittest.TestCase):
198
199 def test_parse(self):
200 a = ast.parse('foo(1 + 1)')
201 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
202 self.assertEqual(ast.dump(a), ast.dump(b))
203
204 def test_dump(self):
205 node = ast.parse('spam(eggs, "and cheese")')
206 self.assertEqual(ast.dump(node),
207 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
208 "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
209 "keywords=[], starargs=None, kwargs=None))])"
210 )
211 self.assertEqual(ast.dump(node, annotate_fields=False),
212 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
213 "Str('and cheese')], [], None, None))])"
214 )
215 self.assertEqual(ast.dump(node, include_attributes=True),
216 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
217 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
218 "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
219 "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
220 "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
221 )
222
223 def test_copy_location(self):
224 src = ast.parse('1 + 1', mode='eval')
225 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
226 self.assertEqual(ast.dump(src, include_attributes=True),
227 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
228 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
229 'col_offset=0))'
230 )
231
232 def test_fix_missing_locations(self):
233 src = ast.parse('write("spam")')
234 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
235 [ast.Str('eggs')], [], None, None)))
236 self.assertEqual(src, ast.fix_missing_locations(src))
237 self.assertEqual(ast.dump(src, include_attributes=True),
238 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
239 "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, "
240 "col_offset=6)], keywords=[], starargs=None, kwargs=None, "
241 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
242 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
243 "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], "
244 "keywords=[], starargs=None, kwargs=None, lineno=1, "
245 "col_offset=0), lineno=1, col_offset=0)])"
246 )
247
248 def test_increment_lineno(self):
249 src = ast.parse('1 + 1', mode='eval')
250 self.assertEqual(ast.increment_lineno(src, n=3), src)
251 self.assertEqual(ast.dump(src, include_attributes=True),
252 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
253 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
254 'col_offset=0))'
255 )
256
257 def test_iter_fields(self):
258 node = ast.parse('foo()', mode='eval')
259 d = dict(ast.iter_fields(node.body))
260 self.assertEqual(d.pop('func').id, 'foo')
261 self.assertEqual(d, {'keywords': [], 'kwargs': None,
262 'args': [], 'starargs': None})
263
264 def test_iter_child_nodes(self):
265 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
266 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
267 iterator = ast.iter_child_nodes(node.body)
268 self.assertEqual(next(iterator).id, 'spam')
269 self.assertEqual(next(iterator).n, 23)
270 self.assertEqual(next(iterator).n, 42)
271 self.assertEqual(ast.dump(next(iterator)),
272 "keyword(arg='eggs', value=Str(s='leek'))"
273 )
274
275 def test_get_docstring(self):
276 node = ast.parse('def foo():\n """line one\n line two"""')
277 self.assertEqual(ast.get_docstring(node.body[0]),
278 'line one\nline two')
279
280 def test_literal_eval(self):
281 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
282 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
283 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
284 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
285
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000286 def test_literal_eval_issue4907(self):
287 self.assertEqual(ast.literal_eval('2j'), 2j)
288 self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
289 self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
290 self.assertRaises(ValueError, ast.literal_eval, '2 + (3 + 4j)')
291
Georg Brandl0c77a822008-06-10 16:37:50 +0000292
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000293def test_main():
Georg Brandl0c77a822008-06-10 16:37:50 +0000294 support.run_unittest(AST_Tests, ASTHelpers_Test)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000295
296def main():
297 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000298 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000299 if sys.argv[1:] == ['-g']:
300 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
301 (eval_tests, "eval")):
302 print(kind+"_results = [")
303 for s in statements:
304 print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
305 print("]")
306 print("main()")
307 raise SystemExit
308 test_main()
Tim Peters400cbc32006-02-28 18:44:41 +0000309
310#### EVERYTHING BELOW IS GENERATED #####
311exec_results = [
Neal Norwitzc1505362006-12-28 06:47:50 +0000312('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]),
Neal Norwitzad74aa82008-03-31 05:14:30 +0000313('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [])]),
Neal Norwitzc1505362006-12-28 06:47:50 +0000314('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 +0000315('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
316('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000317('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000318('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
319('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
320('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
Collin Winter828f04a2007-08-31 00:04:24 +0000321('Module', [('Raise', (1, 0), ('Call', (1, 6), ('Name', (1, 6), 'Exception', ('Load',)), [('Str', (1, 16), 'string')], [], None, None), None)]),
Neal Norwitzad74aa82008-03-31 05:14:30 +0000322('Module', [('TryExcept', (1, 0), [('Pass', (2, 2))], [('ExceptHandler', (3, 0), ('Name', (3, 7), 'Exception', ('Load',)), None, [('Pass', (4, 2))])], [])]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000323('Module', [('TryFinally', (1, 0), [('Pass', (2, 2))], [('Pass', (4, 2))])]),
324('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
325('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
326('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000327('Module', [('Global', (1, 0), ['v'])]),
328('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))]),
329('Module', [('Pass', (1, 0))]),
330('Module', [('Break', (1, 0))]),
331('Module', [('Continue', (1, 0))]),
Tim Peters400cbc32006-02-28 18:44:41 +0000332]
333single_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000334('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +0000335]
336eval_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000337('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
338('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
339('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Neal Norwitzc1505362006-12-28 06:47:50 +0000340('Expression', ('Lambda', (1, 0), ('arguments', [], None, None, [], None, None, [], []), ('Name', (1, 7), 'None', ('Load',)))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000341('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])),
342('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',))])])),
343('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',))])])),
344('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])),
345('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 +0000346('Expression', ('Num', (1, 0), 10)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000347('Expression', ('Str', (1, 0), 'string')),
348('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
349('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))),
350('Expression', ('Name', (1, 0), 'v', ('Load',))),
351('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
352('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))),
353('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 +0000354]
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000355main()