blob: c22d0d47c6fe7163025b34078087f1dabe4d302f [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
143 def test_nodeclasses(self):
Georg Brandl0c77a822008-06-10 16:37:50 +0000144 x = ast.BinOp(1, 2, 3, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000145 self.assertEquals(x.left, 1)
146 self.assertEquals(x.op, 2)
147 self.assertEquals(x.right, 3)
148 self.assertEquals(x.lineno, 0)
149
150 # node raises exception when not given enough arguments
Georg Brandl0c77a822008-06-10 16:37:50 +0000151 self.assertRaises(TypeError, ast.BinOp, 1, 2)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000152
153 # can set attributes through kwargs too
Georg Brandl0c77a822008-06-10 16:37:50 +0000154 x = ast.BinOp(left=1, op=2, right=3, lineno=0)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000155 self.assertEquals(x.left, 1)
156 self.assertEquals(x.op, 2)
157 self.assertEquals(x.right, 3)
158 self.assertEquals(x.lineno, 0)
159
160 # this used to fail because Sub._fields was None
Georg Brandl0c77a822008-06-10 16:37:50 +0000161 x = ast.Sub()
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000162
163 def test_pickling(self):
164 import pickle
165 mods = [pickle]
166 try:
167 import cPickle
168 mods.append(cPickle)
169 except ImportError:
170 pass
171 protocols = [0, 1, 2]
172 for mod in mods:
173 for protocol in protocols:
174 for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
175 ast2 = mod.loads(mod.dumps(ast, protocol))
176 self.assertEquals(to_tuple(ast2), to_tuple(ast))
177
Georg Brandl0c77a822008-06-10 16:37:50 +0000178
179class ASTHelpers_Test(unittest.TestCase):
180
181 def test_parse(self):
182 a = ast.parse('foo(1 + 1)')
183 b = compile('foo(1 + 1)', '<unknown>', 'exec', ast.PyCF_ONLY_AST)
184 self.assertEqual(ast.dump(a), ast.dump(b))
185
186 def test_dump(self):
187 node = ast.parse('spam(eggs, "and cheese")')
188 self.assertEqual(ast.dump(node),
189 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), "
190 "args=[Name(id='eggs', ctx=Load()), Str(s='and cheese')], "
191 "keywords=[], starargs=None, kwargs=None))])"
192 )
193 self.assertEqual(ast.dump(node, annotate_fields=False),
194 "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), "
195 "Str('and cheese')], [], None, None))])"
196 )
197 self.assertEqual(ast.dump(node, include_attributes=True),
198 "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), "
199 "lineno=1, col_offset=0), args=[Name(id='eggs', ctx=Load(), "
200 "lineno=1, col_offset=5), Str(s='and cheese', lineno=1, "
201 "col_offset=11)], keywords=[], starargs=None, kwargs=None, "
202 "lineno=1, col_offset=0), lineno=1, col_offset=0)])"
203 )
204
205 def test_copy_location(self):
206 src = ast.parse('1 + 1', mode='eval')
207 src.body.right = ast.copy_location(ast.Num(2), src.body.right)
208 self.assertEqual(ast.dump(src, include_attributes=True),
209 'Expression(body=BinOp(left=Num(n=1, lineno=1, col_offset=0), '
210 'op=Add(), right=Num(n=2, lineno=1, col_offset=4), lineno=1, '
211 'col_offset=0))'
212 )
213
214 def test_fix_missing_locations(self):
215 src = ast.parse('write("spam")')
216 src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()),
217 [ast.Str('eggs')], [], None, None)))
218 self.assertEqual(src, ast.fix_missing_locations(src))
219 self.assertEqual(ast.dump(src, include_attributes=True),
220 "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
221 "lineno=1, col_offset=0), args=[Str(s='spam', lineno=1, "
222 "col_offset=6)], keywords=[], starargs=None, kwargs=None, "
223 "lineno=1, col_offset=0), lineno=1, col_offset=0), "
224 "Expr(value=Call(func=Name(id='spam', ctx=Load(), lineno=1, "
225 "col_offset=0), args=[Str(s='eggs', lineno=1, col_offset=0)], "
226 "keywords=[], starargs=None, kwargs=None, lineno=1, "
227 "col_offset=0), lineno=1, col_offset=0)])"
228 )
229
230 def test_increment_lineno(self):
231 src = ast.parse('1 + 1', mode='eval')
232 self.assertEqual(ast.increment_lineno(src, n=3), src)
233 self.assertEqual(ast.dump(src, include_attributes=True),
234 'Expression(body=BinOp(left=Num(n=1, lineno=4, col_offset=0), '
235 'op=Add(), right=Num(n=1, lineno=4, col_offset=4), lineno=4, '
236 'col_offset=0))'
237 )
238
239 def test_iter_fields(self):
240 node = ast.parse('foo()', mode='eval')
241 d = dict(ast.iter_fields(node.body))
242 self.assertEqual(d.pop('func').id, 'foo')
243 self.assertEqual(d, {'keywords': [], 'kwargs': None,
244 'args': [], 'starargs': None})
245
246 def test_iter_child_nodes(self):
247 node = ast.parse("spam(23, 42, eggs='leek')", mode='eval')
248 self.assertEqual(len(list(ast.iter_child_nodes(node.body))), 4)
249 iterator = ast.iter_child_nodes(node.body)
250 self.assertEqual(next(iterator).id, 'spam')
251 self.assertEqual(next(iterator).n, 23)
252 self.assertEqual(next(iterator).n, 42)
253 self.assertEqual(ast.dump(next(iterator)),
254 "keyword(arg='eggs', value=Str(s='leek'))"
255 )
256
257 def test_get_docstring(self):
258 node = ast.parse('def foo():\n """line one\n line two"""')
259 self.assertEqual(ast.get_docstring(node.body[0]),
260 'line one\nline two')
261
262 def test_literal_eval(self):
263 self.assertEqual(ast.literal_eval('[1, 2, 3]'), [1, 2, 3])
264 self.assertEqual(ast.literal_eval('{"foo": 42}'), {"foo": 42})
265 self.assertEqual(ast.literal_eval('(True, False, None)'), (True, False, None))
266 self.assertRaises(ValueError, ast.literal_eval, 'foo()')
267
Benjamin Peterson058e31e2009-01-16 03:54:08 +0000268 def test_literal_eval_issue4907(self):
269 self.assertEqual(ast.literal_eval('2j'), 2j)
270 self.assertEqual(ast.literal_eval('10 + 2j'), 10 + 2j)
271 self.assertEqual(ast.literal_eval('1.5 - 2j'), 1.5 - 2j)
272 self.assertRaises(ValueError, ast.literal_eval, '2 + (3 + 4j)')
273
Georg Brandl0c77a822008-06-10 16:37:50 +0000274
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000275def test_main():
Georg Brandl0c77a822008-06-10 16:37:50 +0000276 support.run_unittest(AST_Tests, ASTHelpers_Test)
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000277
278def main():
279 if __name__ != '__main__':
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000280 return
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000281 if sys.argv[1:] == ['-g']:
282 for statements, kind in ((exec_tests, "exec"), (single_tests, "single"),
283 (eval_tests, "eval")):
284 print(kind+"_results = [")
285 for s in statements:
286 print(repr(to_tuple(compile(s, "?", kind, 0x400)))+",")
287 print("]")
288 print("main()")
289 raise SystemExit
290 test_main()
Tim Peters400cbc32006-02-28 18:44:41 +0000291
292#### EVERYTHING BELOW IS GENERATED #####
293exec_results = [
Neal Norwitzc1505362006-12-28 06:47:50 +0000294('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]),
Neal Norwitzad74aa82008-03-31 05:14:30 +0000295('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [])]),
Neal Norwitzc1505362006-12-28 06:47:50 +0000296('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 +0000297('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
298('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000299('Module', [('AugAssign', (1, 0), ('Name', (1, 0), 'v', ('Store',)), ('Add',), ('Num', (1, 5), 1))]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000300('Module', [('For', (1, 0), ('Name', (1, 4), 'v', ('Store',)), ('Name', (1, 9), 'v', ('Load',)), [('Pass', (1, 11))], [])]),
301('Module', [('While', (1, 0), ('Name', (1, 6), 'v', ('Load',)), [('Pass', (1, 8))], [])]),
302('Module', [('If', (1, 0), ('Name', (1, 3), 'v', ('Load',)), [('Pass', (1, 5))], [])]),
Collin Winter828f04a2007-08-31 00:04:24 +0000303('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 +0000304('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 +0000305('Module', [('TryFinally', (1, 0), [('Pass', (2, 2))], [('Pass', (4, 2))])]),
306('Module', [('Assert', (1, 0), ('Name', (1, 7), 'v', ('Load',)), None)]),
307('Module', [('Import', (1, 0), [('alias', 'sys', None)])]),
308('Module', [('ImportFrom', (1, 0), 'sys', [('alias', 'v', None)], 0)]),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000309('Module', [('Global', (1, 0), ['v'])]),
310('Module', [('Expr', (1, 0), ('Num', (1, 0), 1))]),
311('Module', [('Pass', (1, 0))]),
312('Module', [('Break', (1, 0))]),
313('Module', [('Continue', (1, 0))]),
Tim Peters400cbc32006-02-28 18:44:41 +0000314]
315single_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000316('Interactive', [('Expr', (1, 0), ('BinOp', (1, 0), ('Num', (1, 0), 1), ('Add',), ('Num', (1, 2), 2)))]),
Tim Peters400cbc32006-02-28 18:44:41 +0000317]
318eval_results = [
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000319('Expression', ('BoolOp', (1, 0), ('And',), [('Name', (1, 0), 'a', ('Load',)), ('Name', (1, 6), 'b', ('Load',))])),
320('Expression', ('BinOp', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Add',), ('Name', (1, 4), 'b', ('Load',)))),
321('Expression', ('UnaryOp', (1, 0), ('Not',), ('Name', (1, 4), 'v', ('Load',)))),
Neal Norwitzc1505362006-12-28 06:47:50 +0000322('Expression', ('Lambda', (1, 0), ('arguments', [], None, None, [], None, None, [], []), ('Name', (1, 7), 'None', ('Load',)))),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000323('Expression', ('Dict', (1, 0), [('Num', (1, 2), 1)], [('Num', (1, 4), 2)])),
324('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',))])])),
325('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',))])])),
326('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])),
327('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 +0000328('Expression', ('Num', (1, 0), 10)),
Martin v. Löwis49c5da12006-03-01 22:49:05 +0000329('Expression', ('Str', (1, 0), 'string')),
330('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))),
331('Expression', ('Subscript', (1, 0), ('Name', (1, 0), 'a', ('Load',)), ('Slice', ('Name', (1, 2), 'b', ('Load',)), ('Name', (1, 4), 'c', ('Load',)), None), ('Load',))),
332('Expression', ('Name', (1, 0), 'v', ('Load',))),
333('Expression', ('List', (1, 0), [('Num', (1, 1), 1), ('Num', (1, 3), 2), ('Num', (1, 5), 3)], ('Load',))),
334('Expression', ('Tuple', (1, 0), [('Num', (1, 0), 1), ('Num', (1, 2), 2), ('Num', (1, 4), 3)], ('Load',))),
335('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 +0000336]
Neal Norwitzee9b10a2008-03-31 05:29:39 +0000337main()