Debian Codegraph @

pypy/module/_ast/test/test_ast.py

raw symbols SCIP
1 # encoding: utf-8
2 import py
3
4
5 class AppTestAST:
6 spaceconfig = {
7 "usemodules": ['struct', 'binascii'],
8 }
9
10 def setup_class(cls):
11 cls.w_ast = cls.space.getbuiltinmodule('_ast')
12
13 def w_get_ast(self, source, mode="exec", flags=0, feature_version=-1):
14 ast = self.ast
15 mod = compile(source, "<test>", mode, ast.PyCF_ONLY_AST | flags, _feature_version=feature_version)
16 assert isinstance(mod, ast.mod)
17 return mod
18
19 def test_module(self):
20 ast = self.ast
21 assert isinstance(ast.__version__, str)
22
23 def test_flags(self):
24 from copyreg import _HEAPTYPE
25 assert self.ast.AST.__flags__ & _HEAPTYPE == 0
26 assert self.ast.Module.__flags__ & _HEAPTYPE == _HEAPTYPE
27
28 def test_build_ast(self):
29 ast = self.ast
30 mod = self.get_ast("x = 4")
31 assert isinstance(mod, ast.Module)
32 assert len(mod.body) == 1
33
34 def test_simple_sums(self):
35 ast = self.ast
36 mod = self.get_ast("x = 4 + 5")
37 expr = mod.body[0].value
38 assert isinstance(expr, ast.BinOp)
39 assert isinstance(expr.op, ast.Add)
40 expr.op = ast.Sub()
41 assert isinstance(expr.op, ast.Sub)
42 co = compile(mod, "<example>", "exec")
43 ns = {}
44 exec(co, ns)
45 assert ns["x"] == -1
46 mod = self.get_ast("4 < 5 < 6", "eval")
47 assert isinstance(mod.body, ast.Compare)
48 assert len(mod.body.ops) == 2
49 for op in mod.body.ops:
50 assert isinstance(op, ast.Lt)
51 mod.body.ops[0] = ast.Gt()
52 co = compile(mod, "<string>", "eval")
53 assert not eval(co)
54
55 def test_string(self):
56 mod = self.get_ast("'hi'", "eval")
57 s = mod.body
58 assert s.value == "hi"
59 s.value = "pypy"
60 assert eval(compile(mod, "<test>", "eval")) == "pypy"
61
62 def test_empty_initialization(self):
63 ast = self.ast
64 def com(node):
65 return compile(node, "<test>", "exec")
66 mod = ast.Module()
67 raises(AttributeError, getattr, mod, "body")
68 exc = raises(TypeError, com, mod).value
69 assert str(exc) == "required field 'body' missing from Module"
70 expr = ast.Name()
71 expr.id = "hi"
72 expr.ctx = ast.Load()
73 expr.lineno = 4
74 exc = raises(TypeError, com, ast.Module([ast.Expr(expr)], [])).value
75 assert (str(exc) == "required field \"lineno\" missing from stmt" or # cpython
76 str(exc) == "required field 'lineno' missing from Expr") # pypy, better
77
78 def test_int(self):
79 ast = self.ast
80 imp = ast.ImportFrom("", ["apples"], -1)
81 assert imp.level == -1
82 imp.level = 3
83 assert imp.level == 3
84
85 body = [ast.ImportFrom(module='time',
86 names=[ast.alias(name='sleep', lineno=1, col_offset=1)],
87 level=None,
88 lineno=1, col_offset=2)]
89 mod = ast.Module(body, [])
90 compile(mod, 'test', 'exec')
91
92 def test_bad_int(self):
93 ast = self.ast
94 body = [ast.ImportFrom(module='time',
95 names=[ast.alias(name='sleep', lineno=1, col_offset=1)],
96 level='A',
97 lineno=1, col_offset=2)]
98 mod = ast.Module(body, [])
99 exc = raises(ValueError, compile, mod, 'test', 'exec')
100 assert str(exc.value) == "invalid integer value: 'A'"
101
102 def test_identifier(self):
103 ast = self.ast
104 name = ast.Name("name_word", ast.Load())
105 assert name.id == "name_word"
106 name.id = "hi"
107 assert name.id == "hi"
108
109 def test_name_pep3131(self):
110 name = self.get_ast("日本", "eval").body
111 assert isinstance(name, self.ast.Name)
112 assert name.id == "日本"
113
114 def test_function_pep3131(self):
115 fn = self.get_ast("def µ(µ='foo'): pass").body[0]
116 assert isinstance(fn, self.ast.FunctionDef)
117 # µ normalized to NFKC
118 expected = '\u03bc'
119 assert fn.name == expected
120 assert fn.args.args[0].arg == expected
121
122 def test_import_pep3131(self):
123 ast = self.ast
124 im = self.get_ast("from packageµ import modµ as µ").body[0]
125 assert isinstance(im, ast.ImportFrom)
126 expected = '\u03bc'
127 assert im.module == 'package' + expected
128 alias = im.names[0]
129 assert alias.name == 'mod' + expected
130 assert alias.asname == expected
131
132 def test_object(self):
133 ast = self.ast
134 const = ast.Constant(4, None)
135 assert const.value == 4
136 assert const.kind is None
137 const.value = 5
138 assert const.value == 5
139
140 def test_optional(self):
141 mod = self.get_ast("x(32)", "eval")
142 call = mod.body
143 assert len(call.args) == 1
144 assert call.args[0].value == 32
145 co = compile(mod, "<test>", "eval")
146 ns = {"x" : lambda x: x}
147 assert eval(co, ns) == 32
148
149 def test_list_syncing(self):
150 ast = self.ast
151 mod = ast.Module([ast.Lt()], [])
152 raises(TypeError, compile, mod, "<string>", "exec")
153 mod = self.get_ast("x = y = 3")
154 assign = mod.body[0]
155 assert len(assign.targets) == 2
156 assign.targets[1] = ast.Name("lemon", ast.Store(),
157 lineno=0, col_offset=0)
158 name = ast.Name("apple", ast.Store(),
159 lineno=0, col_offset=0)
160 mod.body.append(ast.Assign([name], ast.Constant(4, None, lineno=0, col_offset=0), None,
161 lineno=0, col_offset=0))
162 co = compile(mod, "<test>", "exec")
163 ns = {}
164 exec(co, ns)
165 assert "y" not in ns
166 assert ns["x"] == ns["lemon"] == 3
167 assert ns["apple"] == 4
168
169 def test_empty_module(self):
170 compile(self.ast.Module([], []), "<test>", "exec")
171
172 def test_ast_types(self):
173 ast = self.ast
174 expr = ast.Expr()
175 expr.value = ast.Lt()
176
177 def test_abstract_ast_types(self):
178 ast = self.ast
179 ast.expr()
180 ast.AST()
181 class X(ast.AST):
182 pass
183 X()
184 class Y(ast.expr):
185 pass
186 Y()
187 exc = raises(TypeError, ast.AST, 2)
188 assert exc.value.args[0] == "_ast.AST constructor takes at most 0 positional argument"
189
190 def test_constructor(self):
191 ast = self.ast
192 body = []
193 mod = ast.Module(body, [])
194 assert mod.body is body
195 target = ast.Name("hi", ast.Store())
196 expr = ast.Name("apples", ast.Load())
197 otherwise = []
198 fr = ast.For(target, expr, body, otherwise, None, lineno=0, col_offset=1)
199 assert fr.target is target
200 assert fr.iter is expr
201 assert fr.orelse is otherwise
202 assert fr.body is body
203 assert fr.lineno == 0
204 assert fr.col_offset == 1
205 fr = ast.For(body=body, target=target, iter=expr, col_offset=1,
206 type_comment = None, lineno=0, orelse=otherwise)
207 assert fr.target is target
208 assert fr.iter is expr
209 assert fr.orelse is otherwise
210 assert fr.body is body
211 assert fr.lineno == 0
212 assert fr.col_offset == 1
213 exc = raises(TypeError, ast.Module, 1, 2, 3).value
214 msg = str(exc)
215 assert msg == "Module constructor takes at most 2 positional argument"
216 ast.Module(nothing=23)
217
218 def test_future(self):
219 mod = self.get_ast("from __future__ import with_statement")
220 compile(mod, "<test>", "exec")
221 mod = self.get_ast(""""I am a docstring."\n
222 from __future__ import generators""")
223 compile(mod, "<test>", "exec")
224 mod = self.get_ast("from __future__ import with_statement; import y; " \
225 "from __future__ import nested_scopes")
226 raises(SyntaxError, compile, mod, "<test>", "exec")
227 mod = self.get_ast("from __future__ import division\nx = 1/2")
228 co = compile(mod, "<test>", "exec")
229 ns = {}
230 exec(co, ns)
231 assert ns["x"] == .5
232
233 def test_field_attr_writable(self):
234 import _ast as ast
235 x = ast.Constant()
236 # We can assign to _fields
237 x._fields = 666
238 assert x._fields == 666
239
240 def test_pickle(self):
241 import _pickle as pickle
242 mod = self.get_ast("if y: x = 4")
243 co = compile(mod, "<example>", "exec")
244
245 s = pickle.dumps(mod)
246 mod2 = pickle.loads(s)
247 ns = {"y" : 1}
248 co2 = compile(mod2, "<example>", "exec")
249 exec(co2, ns)
250 assert ns["x"] == 4
251
252 def test_classattrs(self):
253 import _ast as ast
254 x = ast.Constant()
255 assert x._fields == ('value', 'kind')
256 exc = raises(AttributeError, getattr, x, 'value')
257 assert str(exc.value) == "'Constant' object has no attribute 'value'"
258
259 x = ast.Constant(42)
260 assert x.value == 42
261 exc = raises(AttributeError, getattr, x, 'lineno')
262 assert str(exc.value) == "'Constant' object has no attribute 'lineno'"
263
264 y = ast.Constant()
265 x.lineno = y
266 assert x.lineno == y
267
268 exc = raises(AttributeError, getattr, x, 'foobar')
269 assert str(exc.value) == "'Constant' object has no attribute 'foobar'"
270
271 x = ast.Constant(lineno=2)
272 assert x.lineno == 2
273
274 x = ast.Constant(42, None, lineno=0)
275 assert x.lineno == 0
276 assert x._fields == ('value', 'kind')
277 assert x.value == 42
278 assert x.kind is None
279
280 raises(TypeError, ast.Constant, 1, 2, 3)
281 raises(TypeError, ast.Constant, 1, 2, 3, lineno=0)
282
283 def test_issue1680_nonseq(self):
284 # Test deleting an attribute manually
285
286 _ast = self.ast
287 mod = self.get_ast("self.attr")
288 assert isinstance(mod, _ast.Module)
289 assert len(mod.body) == 1
290 assert isinstance(mod.body[0], _ast.Expr)
291 assert isinstance(mod.body[0].value, _ast.Attribute)
292 assert isinstance(mod.body[0].value.value, _ast.Name)
293 attr = mod.body[0].value
294 assert hasattr(attr, 'value')
295 delattr(attr, 'value')
296 assert not hasattr(attr, 'value')
297
298 # Test using a node transformer to delete an attribute
299
300 tree = self.get_ast("self.attr2")
301
302 import ast
303 class RemoveSelf( ast.NodeTransformer ):
304 """NodeTransformer class to remove all references to 'self' in the ast"""
305 def visit_Name( self, node ):
306 if node.id == 'self':
307 return None
308 return node
309
310 assert hasattr(tree.body[0].value, 'value')
311 #print ast.dump( tree )
312 new_tree = RemoveSelf().visit( tree )
313 #print ast.dump( new_tree )
314 assert not hasattr(new_tree.body[0].value, 'value')
315
316 # Setting an attribute manually, then deleting it
317
318 mod = self.get_ast("class MyClass(object): pass")
319 import ast
320 assert isinstance(mod.body[0], _ast.ClassDef)
321 mod.body[0].name = 42
322 delattr(mod.body[0], 'name')
323 assert not hasattr(mod.body[0], 'name')
324
325 def test_issue1680_seq(self):
326 # Test deleting an attribute manually
327
328 _ast = self.ast
329 mod = self.get_ast("self.attr")
330 assert isinstance(mod, _ast.Module)
331 assert len(mod.body) == 1
332 assert isinstance(mod.body[0], _ast.Expr)
333 assert isinstance(mod.body[0].value, _ast.Attribute)
334 assert isinstance(mod.body[0].value.value, _ast.Name)
335 assert hasattr(mod, 'body')
336 delattr(mod, 'body')
337 assert not hasattr(mod, 'body')
338
339 def test_node_identity(self):
340 import _ast as ast
341 n1 = ast.Constant(1, None)
342 n3 = ast.Constant(3, None)
343 addop = ast.Add()
344 x = ast.BinOp(n1, addop, n3)
345 assert x.left == n1
346 assert x.op == addop
347 assert x.right == n3
348
349 def test_functiondef(self):
350 import ast as ast_utils
351 import _ast as ast
352 fAst = ast.FunctionDef(
353 name="foo",
354 args=ast.arguments(
355 args=[], vararg=None, kwarg=None, defaults=[],
356 kwonlyargs=[], kw_defaults=[], posonlyargs=[]),
357 body=[ast.Expr(ast.Constant('docstring', None))],
358 decorator_list=[], lineno=5, col_offset=0)
359 exprAst = ast.Interactive(body=[fAst])
360 ast_utils.fix_missing_locations(exprAst)
361 compiled = compile(exprAst, "<foo>", "single")
362 #
363 d = {}
364 eval(compiled, d, d)
365 assert type(d['foo']) is type(lambda: 42)
366 assert d['foo']() is None
367
368 def test_decorated_def(self):
369 src = """
370 @deco(a, b)
371 @deco2
372 @deco3()
373 def f():
374 pass
375 """
376 mod = self.get_ast(src)
377 assert mod.body[0].lineno == 5
378 assert mod.body[0].decorator_list[0].lineno == 2
379 for dec in mod.body[0].decorator_list:
380 assert dec.col_offset == 1
381
382 def test_missing_name(self):
383 import _ast as ast
384 n = ast.FunctionDef(name=None)
385 n.name = "foo"
386 n.name = "foo"
387 n.name = "foo"
388 assert n.name == "foo"
389
390 def test_issue793(self):
391 import _ast as ast
392 body = ast.Module([
393 ast.Try([ast.Pass(lineno=2, col_offset=4)],
394 [ast.ExceptHandler(ast.Name('Exception', ast.Load(),
395 lineno=3, col_offset=0),
396 None, [ast.Pass(lineno=4, col_offset=0)],
397 lineno=4, col_offset=0)],
398 [], [], lineno=1, col_offset=0)
399 ], [])
400 exec(compile(body, '<string>', 'exec'))
401
402 def test_empty_set(self):
403 import ast as ast_utils
404 import _ast as ast
405 m = ast.Module(body=[ast.Expr(value=ast.Set(elts=[]))], type_ignores=[])
406 ast_utils.fix_missing_locations(m)
407 compile(m, "<test>", "exec")
408
409 def test_invalid_sum(self):
410 import _ast as ast
411 pos = dict(lineno=2, col_offset=3)
412 m = ast.Module([ast.Expr(ast.expr(**pos), **pos)], [])
413 exc = raises(TypeError, compile, m, "<test>", "exec")
414
415 def test_invalid_identitifer(self):
416 import ast as ast_utils
417 import _ast as ast
418 m = ast.Module([ast.Expr(ast.Name(b"x", ast.Load()))], [])
419 ast_utils.fix_missing_locations(m)
420 exc = raises(TypeError, compile, m, "<test>", "exec")
421
422 def test_invalid_constant(self):
423 import ast as ast_utils
424 import _ast as ast
425 m = ast.Module([ast.Expr(ast.Constant(ast.List([], ast.Load()), None))], [])
426 ast_utils.fix_missing_locations(m)
427 exc = raises(TypeError, compile, m, "<test>", "exec")
428
429 def test_hacked_lineno(self):
430 import _ast
431 stmt = '''if 1:
432 try:
433 foo
434 except Exception as error:
435 bar
436 except Baz as error:
437 bar
438 '''
439 mod = compile(stmt, "<test>", "exec", _ast.PyCF_ONLY_AST)
440 # These lineno are invalid, but should not crash the interpreter.
441 mod.body[0].body[0].handlers[0].lineno = 7
442 mod.body[0].body[0].handlers[1].lineno = 6
443 code = compile(mod, "<test>", "exec")
444
445 def test_dict_astNode(self):
446 import _ast as ast
447 num_node = ast.Constant(value=2, kind=None, lineno=2, col_offset=3)
448 dict_res = num_node.__dict__
449 assert dict_res == {'value':2, 'kind': None, 'lineno':2, 'col_offset':3}
450
451 def test_issue1673_Num_notfullinit(self):
452 import _ast as ast
453 import copy
454 num_node = ast.Constant(value=2,lineno=2)
455 num_node2 = copy.deepcopy(num_node)
456 assert num_node2.value == 2
457 assert num_node2.lineno == 2
458
459 def test_issue1673_Num_fullinit(self):
460 import _ast as ast
461 import copy
462 num_node = ast.Constant(value=2,kind=None,lineno=2,col_offset=3)
463 num_node2 = copy.deepcopy(num_node)
464 assert num_node.value == num_node2.value
465 assert num_node.kind is num_node2.kind
466 assert num_node.lineno == num_node2.lineno
467 assert num_node.col_offset == num_node2.col_offset
468 dict_res = num_node2.__dict__
469 assert dict_res == {'value':2, 'kind': None, 'lineno':2, 'col_offset':3}
470
471 def test_issue1673_Str(self):
472 import _ast as ast
473 import copy
474 str_node = ast.Constant(value=2,kind=None,lineno=2)
475 assert str_node.value == 2
476 assert str_node.lineno == 2
477 str_node2 = copy.deepcopy(str_node)
478 str_node2.kind = 'u'
479 dict_res = str_node2.__dict__
480 assert dict_res == {'value':2, 'kind': 'u', 'lineno':2}
481
482 def test_bug_null_in_objspace_type(self):
483 import _ast as ast
484 code = ast.Expression(lineno=1, col_offset=1, body=ast.ListComp(lineno=1, col_offset=1, elt=ast.Call(lineno=1, col_offset=1, func=ast.Name(lineno=1, col_offset=1, id='str', ctx=ast.Load(lineno=1, col_offset=1)), args=[ast.Name(lineno=1, col_offset=1, id='x', ctx=ast.Load(lineno=1, col_offset=1))], keywords=[]), generators=[ast.comprehension(lineno=1, col_offset=1, target=ast.Name(lineno=1, col_offset=1, id='x', ctx=ast.Store(lineno=1, col_offset=1)), iter=ast.List(lineno=1, col_offset=1, elts=[ast.Constant(lineno=1, col_offset=1, value=23)], ctx=ast.Load(lineno=1, col_offset=1, )), ifs=[], is_async=False)]))
485 compile(code, '<template>', 'eval')
486
487 def test_empty_yield_from(self):
488 # Issue 16546: yield from value is not optional.
489 import ast
490 empty_yield_from = ast.parse("def f():\n yield from g()")
491 empty_yield_from.body[0].body[0].value.value = None
492 exc = raises(ValueError, compile, empty_yield_from, "<test>", "exec")
493 assert "field 'value' is required for YieldFrom" in str(exc.value)
494
495 def test_compare(self):
496 import ast as ast_utils
497 import _ast as ast
498
499 def _mod(mod, msg=None, mode="exec", exc=ValueError):
500 mod.lineno = mod.col_offset = 0
501 ast_utils.fix_missing_locations(mod)
502 exc = raises(exc, compile, mod, "<test>", mode)
503 if msg is not None:
504 assert msg in str(exc.value)
505 def _expr(node, msg=None, exc=ValueError):
506 mod = ast.Module([ast.Expr(node)], [])
507 _mod(mod, msg, exc=exc)
508 left = ast.Name("x", ast.Load())
509 comp = ast.Compare(left, [ast.In()], [])
510 _expr(comp, "no comparators")
511 comp = ast.Compare(left, [ast.In()], [ast.Constant(4, None), ast.Constant(5, None)])
512 _expr(comp, "different number of comparators and operands")
513
514 def test_dict_unpacking(self):
515 self.get_ast("{**{1:2}, 2:3}")
516
517 def test_type_comments(self):
518 mod = self.get_ast("a = 5 # type: int", flags=self.ast.PyCF_TYPE_COMMENTS)
519 assert mod.body[0].type_comment == "int"
520
521 mod = self.get_ast("a = 5 # type: ignore", flags=self.ast.PyCF_TYPE_COMMENTS)
522 assert len(mod.type_ignores) == 1
523 assert mod.type_ignores[0].tag == ""
524 assert mod.type_ignores[0].lineno == 1
525
526 mod = self.get_ast("a = 5")
527 assert mod.body[0].type_comment is None
528
529 def test_type_comments_are_None_by_default(self):
530 mod = self.get_ast("a = 5 # type: int")
531 assert mod.body[0].type_comment is None
532
533 mod = self.get_ast("a = 5 # type: int")
534 assert mod.body[0].type_comment is None
535 mod = self.get_ast("""def fkwo(
536 a, # type: 1
537 *,
538 b # type: 2
539 ):
540 pass
541 """)
542 assert mod.body[0].args.args[0].type_comment is None
543
544 def test_ast_initalization(self):
545 import _ast as ast
546
547 zero = ast.Module()
548 assert not hasattr(zero, "body")
549 assert not hasattr(zero, "type_ignores")
550
551 one = ast.Module(1)
552 assert one.body == 1
553 assert not hasattr(one, "type_ignores")
554
555 full = ast.Module(1, 2)
556 assert full.body == 1
557 assert full.type_ignores == 2
558
559 exc = raises(TypeError, ast.Module, 1, 2, 3).value
560 msg = str(exc)
561 assert msg == "Module constructor takes at most 2 positional argument"
562
563 raises(TypeError, ast.Module, 1, 2, type_ignores=3)
564
565 def test_ast_feature_version(self):
566 raises(SyntaxError, self.get_ast, "await = x")
567 raises(SyntaxError, self.get_ast, "await = x", feature_version=9)
568 raises(SyntaxError, self.get_ast, "await = x", feature_version=-1)
569
570 tree_36 = self.get_ast("await = x", feature_version=6)
571 assert tree_36.body[0].targets[0].id == 'await'
572
573 tree_35 = self.get_ast("await = x", feature_version=5)
574 assert tree_35.body[0].targets[0].id == 'await'
575
576 def test_ast_feature_version_with_type_comments(self):
577
578 import ast
579 import textwrap
580
581 ignores = textwrap.dedent("""\
582 def foo():
583 pass # type: ignore
584
585 def bar():
586 x = 1 # type: ignore
587
588 def baz():
589 pass # type: ignore[excuse]
590 pass # type: ignore=excuse
591 pass # type: ignore [excuse]
592 x = 1 # type: ignore whatever
593 """)
594
595 for version in range(9):
596 tree_1 = ast.parse(ignores, type_comments=True, feature_version=version)
597 tree_2 = ast.parse(ignores, type_comments=True, feature_version=(3, version))
598
599 assert len(tree_1.type_ignores) == 6
600 assert len(tree_2.type_ignores) == 6
601
602 def test_fstring_self_documenting_feature_version(self):
603 raises(SyntaxError, self.get_ast, "f'{x=}'", feature_version=7)
604 self.get_ast("'f{x=}'", feature_version=7)
605
606 def test_ast_feature_version_asynccomp_bug(self):
607 import ast
608 raises(SyntaxError, ast.parse, 'async def foo(xs):\n [x async for x in xs]\n', feature_version=(3, 4))
609
610 def test_ast_feature_version_underscore_number(self):
611 import ast
612 raises(SyntaxError, ast.parse, '12_12', feature_version=(3, 4))
613
614 def test_crash_bug(self):
615 import ast
616 raises(SyntaxError, ast.parse, 'def fa(\n a = 1, # type: A\n /\n):\n pass\n\ndef fab(\n a, # type: A\n /,\n b, # type: B\n):\n pass\n\ndef fav(\n a, # type: A\n /,\n *v, # type: V\n):\n pass\n\ndef fak(\n a, # type: A\n /,\n **k, # type: K\n):\n pass\n\ndef favk(\n a, # type: A\n /,\n *v, # type: V\n **k, # type: K\n):\n pass\n\n', feature_version=4)
617
618 def test_module(self):
619 import ast
620 assert ast.expr.__module__ == 'ast'