Debian Codegraph @

tests/test_builder.py

raw
1 # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2 # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3 # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5 """Tests for the astroid builder and rebuilder module."""
6
7 import collections
8 import importlib
9 import os
10 import pathlib
11 import py_compile
12 import socket
13 import sys
14 import tempfile
15 import textwrap
16 import unittest
17 import unittest.mock
18
19 import pytest
20
21 from astroid import Instance, builder, nodes, test_utils, util
22 from astroid.const import IS_PYPY
23 from astroid.exceptions import (
24 AstroidBuildingError,
25 AstroidSyntaxError,
26 AttributeInferenceError,
27 InferenceError,
28 StatementMissing,
29 )
30 from astroid.manager import AstroidManager
31 from astroid.nodes.scoped_nodes import Module
32
33 from . import resources
34
35
36 class FromToLineNoTest(unittest.TestCase):
37 def setUp(self) -> None:
38 self.astroid = resources.build_file("data/format.py")
39
40 def test_callfunc_lineno(self) -> None:
41 stmts = self.astroid.body
42 # on line 4:
43 # function('aeozrijz\
44 # earzer', hop)
45 discard = stmts[0]
46 self.assertIsInstance(discard, nodes.Expr)
47 self.assertEqual(discard.fromlineno, 4)
48 self.assertEqual(discard.tolineno, 5)
49 callfunc = discard.value
50 self.assertIsInstance(callfunc, nodes.Call)
51 self.assertEqual(callfunc.fromlineno, 4)
52 self.assertEqual(callfunc.tolineno, 5)
53 name = callfunc.func
54 self.assertIsInstance(name, nodes.Name)
55 self.assertEqual(name.fromlineno, 4)
56 self.assertEqual(name.tolineno, 4)
57 strarg = callfunc.args[0]
58 self.assertIsInstance(strarg, nodes.Const)
59 if IS_PYPY:
60 self.assertEqual(strarg.fromlineno, 4)
61 self.assertEqual(strarg.tolineno, 5)
62 else:
63 self.assertEqual(strarg.fromlineno, 4)
64 self.assertEqual(strarg.tolineno, 5)
65 namearg = callfunc.args[1]
66 self.assertIsInstance(namearg, nodes.Name)
67 self.assertEqual(namearg.fromlineno, 5)
68 self.assertEqual(namearg.tolineno, 5)
69 # on line 10:
70 # fonction(1,
71 # 2,
72 # 3,
73 # 4)
74 discard = stmts[2]
75 self.assertIsInstance(discard, nodes.Expr)
76 self.assertEqual(discard.fromlineno, 10)
77 self.assertEqual(discard.tolineno, 13)
78 callfunc = discard.value
79 self.assertIsInstance(callfunc, nodes.Call)
80 self.assertEqual(callfunc.fromlineno, 10)
81 self.assertEqual(callfunc.tolineno, 13)
82 name = callfunc.func
83 self.assertIsInstance(name, nodes.Name)
84 self.assertEqual(name.fromlineno, 10)
85 self.assertEqual(name.tolineno, 10)
86 for i, arg in enumerate(callfunc.args):
87 self.assertIsInstance(arg, nodes.Const)
88 self.assertEqual(arg.fromlineno, 10 + i)
89 self.assertEqual(arg.tolineno, 10 + i)
90
91 def test_function_lineno(self) -> None:
92 stmts = self.astroid.body
93 # on line 15:
94 # def definition(a,
95 # b,
96 # c):
97 # return a + b + c
98 function = stmts[3]
99 self.assertIsInstance(function, nodes.FunctionDef)
100 self.assertEqual(function.fromlineno, 15)
101 self.assertEqual(function.tolineno, 18)
102 return_ = function.body[0]
103 self.assertIsInstance(return_, nodes.Return)
104 self.assertEqual(return_.fromlineno, 18)
105 self.assertEqual(return_.tolineno, 18)
106
107 def test_decorated_function_lineno(self) -> None:
108 astroid = builder.parse(
109 """
110 @decorator
111 def function(
112 arg):
113 print (arg)
114 """,
115 __name__,
116 )
117 function = astroid["function"]
118 # XXX discussable, but that's what is expected by pylint right now, similar to ClassDef
119 self.assertEqual(function.fromlineno, 3)
120 self.assertEqual(function.tolineno, 5)
121 self.assertEqual(function.decorators.fromlineno, 2)
122 self.assertEqual(function.decorators.tolineno, 2)
123
124 @staticmethod
125 def test_decorated_class_lineno() -> None:
126 code = textwrap.dedent("""
127 class A: # L2
128 ...
129
130 @decorator
131 class B: # L6
132 ...
133
134 @deco1
135 @deco2(
136 var=42
137 )
138 class C: # L13
139 ...
140 """)
141
142 ast_module: nodes.Module = builder.parse(code) # type: ignore[assignment]
143
144 a = ast_module.body[0]
145 assert isinstance(a, nodes.ClassDef)
146 assert a.fromlineno == 2
147 assert a.tolineno == 3
148
149 b = ast_module.body[1]
150 assert isinstance(b, nodes.ClassDef)
151 assert b.fromlineno == 6
152 assert b.tolineno == 7
153
154 c = ast_module.body[2]
155 assert isinstance(c, nodes.ClassDef)
156 assert c.fromlineno == 13
157 assert c.tolineno == 14
158
159 @staticmethod
160 def test_class_with_docstring() -> None:
161 """Test class nodes which only have docstrings."""
162 code = textwrap.dedent('''\
163 class A:
164 """My docstring"""
165 var = 1
166
167 class B:
168 """My docstring"""
169
170 class C:
171 """My docstring
172 is long."""
173
174 class D:
175 """My docstring
176 is long.
177 """
178
179 class E:
180 ...
181 ''')
182
183 ast_module = builder.parse(code)
184
185 a = ast_module.body[0]
186 assert isinstance(a, nodes.ClassDef)
187 assert a.fromlineno == 1
188 assert a.tolineno == 3
189
190 b = ast_module.body[1]
191 assert isinstance(b, nodes.ClassDef)
192 assert b.fromlineno == 5
193 assert b.tolineno == 6
194
195 c = ast_module.body[2]
196 assert isinstance(c, nodes.ClassDef)
197 assert c.fromlineno == 8
198 assert c.tolineno == 10
199
200 d = ast_module.body[3]
201 assert isinstance(d, nodes.ClassDef)
202 assert d.fromlineno == 12
203 assert d.tolineno == 15
204
205 e = ast_module.body[4]
206 assert isinstance(d, nodes.ClassDef)
207 assert e.fromlineno == 17
208 assert e.tolineno == 18
209
210 @staticmethod
211 def test_function_with_docstring() -> None:
212 """Test function defintions with only docstrings."""
213 code = textwrap.dedent('''\
214 def a():
215 """My docstring"""
216 var = 1
217
218 def b():
219 """My docstring"""
220
221 def c():
222 """My docstring
223 is long."""
224
225 def d():
226 """My docstring
227 is long.
228 """
229
230 def e(a, b):
231 """My docstring
232 is long.
233 """
234 ''')
235
236 ast_module = builder.parse(code)
237
238 a = ast_module.body[0]
239 assert isinstance(a, nodes.FunctionDef)
240 assert a.fromlineno == 1
241 assert a.tolineno == 3
242
243 b = ast_module.body[1]
244 assert isinstance(b, nodes.FunctionDef)
245 assert b.fromlineno == 5
246 assert b.tolineno == 6
247
248 c = ast_module.body[2]
249 assert isinstance(c, nodes.FunctionDef)
250 assert c.fromlineno == 8
251 assert c.tolineno == 10
252
253 d = ast_module.body[3]
254 assert isinstance(d, nodes.FunctionDef)
255 assert d.fromlineno == 12
256 assert d.tolineno == 15
257
258 e = ast_module.body[4]
259 assert isinstance(e, nodes.FunctionDef)
260 assert e.fromlineno == 17
261 assert e.tolineno == 20
262
263 def test_class_lineno(self) -> None:
264 stmts = self.astroid.body
265 # on line 20:
266 # class debile(dict,
267 # object):
268 # pass
269 class_ = stmts[4]
270 self.assertIsInstance(class_, nodes.ClassDef)
271 self.assertEqual(class_.fromlineno, 20)
272 self.assertEqual(class_.tolineno, 22)
273 self.assertEqual(class_.blockstart_tolineno, 21)
274 pass_ = class_.body[0]
275 self.assertIsInstance(pass_, nodes.Pass)
276 self.assertEqual(pass_.fromlineno, 22)
277 self.assertEqual(pass_.tolineno, 22)
278
279 def test_if_lineno(self) -> None:
280 stmts = self.astroid.body
281 # on line 20:
282 # if aaaa: pass
283 # else:
284 # aaaa,bbbb = 1,2
285 # aaaa,bbbb = bbbb,aaaa
286 if_ = stmts[5]
287 self.assertIsInstance(if_, nodes.If)
288 self.assertEqual(if_.fromlineno, 24)
289 self.assertEqual(if_.tolineno, 27)
290 self.assertEqual(if_.blockstart_tolineno, 24)
291 self.assertEqual(if_.orelse[0].fromlineno, 26)
292 self.assertEqual(if_.orelse[1].tolineno, 27)
293
294 def test_for_while_lineno(self) -> None:
295 for code in (
296 """
297 for a in range(4):
298 print (a)
299 break
300 else:
301 print ("bouh")
302 """,
303 """
304 while a:
305 print (a)
306 break
307 else:
308 print ("bouh")
309 """,
310 ):
311 astroid = builder.parse(code, __name__)
312 stmt = astroid.body[0]
313 self.assertEqual(stmt.fromlineno, 2)
314 self.assertEqual(stmt.tolineno, 6)
315 self.assertEqual(stmt.blockstart_tolineno, 2)
316 self.assertEqual(stmt.orelse[0].fromlineno, 6) # XXX
317 self.assertEqual(stmt.orelse[0].tolineno, 6)
318
319 def test_try_except_lineno(self) -> None:
320 astroid = builder.parse(
321 """
322 try:
323 print (a)
324 except:
325 pass
326 else:
327 print ("bouh")
328 """,
329 __name__,
330 )
331 try_ = astroid.body[0]
332 self.assertEqual(try_.fromlineno, 2)
333 self.assertEqual(try_.tolineno, 7)
334 self.assertEqual(try_.blockstart_tolineno, 2)
335 self.assertEqual(try_.orelse[0].fromlineno, 7) # XXX
336 self.assertEqual(try_.orelse[0].tolineno, 7)
337 hdlr = try_.handlers[0]
338 self.assertEqual(hdlr.fromlineno, 4)
339 self.assertEqual(hdlr.tolineno, 5)
340 self.assertEqual(hdlr.blockstart_tolineno, 4)
341
342 def test_try_finally_lineno(self) -> None:
343 astroid = builder.parse(
344 """
345 try:
346 print (a)
347 finally:
348 print ("bouh")
349 """,
350 __name__,
351 )
352 try_ = astroid.body[0]
353 self.assertEqual(try_.fromlineno, 2)
354 self.assertEqual(try_.tolineno, 5)
355 self.assertEqual(try_.blockstart_tolineno, 2)
356 self.assertEqual(try_.finalbody[0].fromlineno, 5) # XXX
357 self.assertEqual(try_.finalbody[0].tolineno, 5)
358
359 def test_try_finally_25_lineno(self) -> None:
360 astroid = builder.parse(
361 """
362 try:
363 print (a)
364 except:
365 pass
366 finally:
367 print ("bouh")
368 """,
369 __name__,
370 )
371 try_ = astroid.body[0]
372 self.assertEqual(try_.fromlineno, 2)
373 self.assertEqual(try_.tolineno, 7)
374 self.assertEqual(try_.blockstart_tolineno, 2)
375 self.assertEqual(try_.finalbody[0].fromlineno, 7) # XXX
376 self.assertEqual(try_.finalbody[0].tolineno, 7)
377
378 def test_with_lineno(self) -> None:
379 astroid = builder.parse(
380 """
381 from __future__ import with_statement
382 with file("/tmp/pouet") as f:
383 print (f)
384 """,
385 __name__,
386 )
387 with_ = astroid.body[1]
388 self.assertEqual(with_.fromlineno, 3)
389 self.assertEqual(with_.tolineno, 4)
390 self.assertEqual(with_.blockstart_tolineno, 3)
391
392
393 class BuilderTest(unittest.TestCase):
394 def setUp(self) -> None:
395 self.manager = test_utils.brainless_manager()
396 self.builder = builder.AstroidBuilder(self.manager)
397
398 def test_data_build_null_bytes(self) -> None:
399 with self.assertRaises(AstroidSyntaxError):
400 self.builder.string_build("\x00")
401
402 def test_data_build_invalid_x_escape(self) -> None:
403 with self.assertRaises(AstroidSyntaxError):
404 self.builder.string_build('"\\x1"')
405
406 def test_data_build_error_filename(self) -> None:
407 """Check that error filename is set to modname if given."""
408 with pytest.raises(AstroidSyntaxError, match="invalid escape sequence") as ctx:
409 self.builder.string_build("'\\d+\\.\\d+'")
410 assert isinstance(ctx.value.error, SyntaxError)
411 assert ctx.value.error.filename == "<unknown>"
412
413 with pytest.raises(AstroidSyntaxError, match="invalid escape sequence") as ctx:
414 self.builder.string_build("'\\d+\\.\\d+'", modname="mymodule")
415 assert isinstance(ctx.value.error, SyntaxError)
416 assert ctx.value.error.filename == "mymodule"
417
418 def test_missing_newline(self) -> None:
419 """Check that a file with no trailing new line is parseable."""
420 resources.build_file("data/noendingnewline.py")
421
422 def test_missing_file(self) -> None:
423 with self.assertRaises(AstroidBuildingError):
424 resources.build_file("data/inexistent.py")
425
426 def test_inspect_build0(self) -> None:
427 """Test astroid tree build from a living object."""
428 builtin_ast = self.manager.ast_from_module_name("builtins")
429 # just check type and object are there
430 builtin_ast.getattr("type")
431 objectastroid = builtin_ast.getattr("object")[0]
432 self.assertIsInstance(objectastroid.getattr("__new__")[0], nodes.FunctionDef)
433 # check open file alias
434 builtin_ast.getattr("open")
435 # check 'help' is there (defined dynamically by site.py)
436 builtin_ast.getattr("help")
437 # check property has __init__
438 pclass = builtin_ast["property"]
439 self.assertIn("__init__", pclass)
440 self.assertIsInstance(builtin_ast["None"], nodes.Const)
441 self.assertIsInstance(builtin_ast["True"], nodes.Const)
442 self.assertIsInstance(builtin_ast["False"], nodes.Const)
443 self.assertIsInstance(builtin_ast["Exception"], nodes.ClassDef)
444 self.assertIsInstance(builtin_ast["NotImplementedError"], nodes.ClassDef)
445
446 def test_inspect_build1(self) -> None:
447 time_ast = self.manager.ast_from_module_name("time")
448 self.assertTrue(time_ast)
449 self.assertEqual(time_ast["time"].args.defaults, None)
450
451 def test_inspect_build3(self) -> None:
452 self.builder.inspect_build(unittest)
453
454 def test_inspect_build_type_object(self) -> None:
455 builtin_ast = self.manager.ast_from_module_name("builtins")
456
457 inferred = list(builtin_ast.igetattr("object"))
458 self.assertEqual(len(inferred), 1)
459 inferred = inferred[0]
460 self.assertEqual(inferred.name, "object")
461 inferred.as_string() # no crash test
462
463 inferred = list(builtin_ast.igetattr("type"))
464 self.assertEqual(len(inferred), 1)
465 inferred = inferred[0]
466 self.assertEqual(inferred.name, "type")
467 inferred.as_string() # no crash test
468
469 def test_inspect_transform_module(self) -> None:
470 # ensure no cached version of the time module
471 self.manager._mod_file_cache.pop(("time", None), None)
472 self.manager.astroid_cache.pop("time", None)
473
474 def transform_time(node: Module) -> None:
475 if node.name == "time":
476 node.transformed = True
477
478 self.manager.register_transform(nodes.Module, transform_time)
479 try:
480 time_ast = self.manager.ast_from_module_name("time")
481 self.assertTrue(getattr(time_ast, "transformed", False))
482 finally:
483 self.manager.unregister_transform(nodes.Module, transform_time)
484
485 def test_package_name(self) -> None:
486 """Test base properties and method of an astroid module."""
487 datap = resources.build_file("data/__init__.py", "data")
488 self.assertEqual(datap.name, "data")
489 self.assertEqual(datap.package, 1)
490 datap = resources.build_file("data/__init__.py", "data.__init__")
491 self.assertEqual(datap.name, "data")
492 self.assertEqual(datap.package, 1)
493 datap = resources.build_file("data/tmp__init__.py", "data.tmp__init__")
494 self.assertEqual(datap.name, "data.tmp__init__")
495 self.assertEqual(datap.package, 0)
496
497 def test_yield_parent(self) -> None:
498 """Check if we added discard nodes as yield parent (w/ compiler)."""
499 code = """
500 def yiell(): #@
501 yield 0
502 if noe:
503 yield more
504 """
505 func = builder.extract_node(code)
506 self.assertIsInstance(func, nodes.FunctionDef)
507 stmt = func.body[0]
508 self.assertIsInstance(stmt, nodes.Expr)
509 self.assertIsInstance(stmt.value, nodes.Yield)
510 self.assertIsInstance(func.body[1].body[0], nodes.Expr)
511 self.assertIsInstance(func.body[1].body[0].value, nodes.Yield)
512
513 def test_object(self) -> None:
514 obj_ast = self.builder.inspect_build(object)
515 self.assertIn("__setattr__", obj_ast)
516
517 def test_globals(self) -> None:
518 data = """
519 CSTE = 1
520
521 def update_global():
522 global CSTE
523 CSTE += 1
524
525 def global_no_effect():
526 global CSTE2
527 print (CSTE)
528 """
529 astroid = builder.parse(data, __name__)
530 self.assertEqual(len(astroid.getattr("CSTE")), 2)
531 self.assertIsInstance(astroid.getattr("CSTE")[0], nodes.AssignName)
532 self.assertEqual(astroid.getattr("CSTE")[0].fromlineno, 2)
533 self.assertEqual(astroid.getattr("CSTE")[1].fromlineno, 6)
534 with self.assertRaises(AttributeInferenceError):
535 astroid.getattr("CSTE2")
536 with self.assertRaises(InferenceError):
537 next(astroid["global_no_effect"].ilookup("CSTE2"))
538
539 def test_socket_build(self) -> None:
540 astroid = self.builder.module_build(socket)
541 # XXX just check the first one. Actually 3 objects are inferred (look at
542 # the socket module) but the last one as those attributes dynamically
543 # set and astroid is missing this.
544 for fclass in astroid.igetattr("socket"):
545 self.assertIn("connect", fclass)
546 self.assertIn("send", fclass)
547 self.assertIn("close", fclass)
548 break
549
550 def test_gen_expr_var_scope(self) -> None:
551 data = "l = list(n for n in range(10))\n"
552 astroid = builder.parse(data, __name__)
553 # n unavailable outside gen expr scope
554 self.assertNotIn("n", astroid)
555 # test n is inferable anyway
556 n = test_utils.get_name_node(astroid, "n")
557 self.assertIsNot(n.scope(), astroid)
558 self.assertEqual([i.__class__ for i in n.infer()], [util.Uninferable.__class__])
559
560 def test_no_future_imports(self) -> None:
561 mod = builder.parse("import sys")
562 self.assertEqual(set(), mod.future_imports)
563
564 def test_future_imports(self) -> None:
565 mod = builder.parse("from __future__ import print_function")
566 self.assertEqual({"print_function"}, mod.future_imports)
567
568 def test_two_future_imports(self) -> None:
569 mod = builder.parse("""
570 from __future__ import print_function
571 from __future__ import absolute_import
572 """)
573 self.assertEqual({"print_function", "absolute_import"}, mod.future_imports)
574
575 def test_inferred_build(self) -> None:
576 code = """
577 class A: pass
578 A.type = "class"
579
580 def A_assign_type(self):
581 print (self)
582 A.assign_type = A_assign_type
583 """
584 astroid = builder.parse(code)
585 lclass = list(astroid.igetattr("A"))
586 self.assertEqual(len(lclass), 1)
587 lclass = lclass[0]
588 self.assertIn("assign_type", lclass.locals)
589 self.assertIn("type", lclass.locals)
590
591 def test_infer_can_assign_regular_object(self) -> None:
592 mod = builder.parse("""
593 class A:
594 pass
595 a = A()
596 a.value = "is set"
597 a.other = "is set"
598 """)
599 obj = list(mod.igetattr("a"))
600 self.assertEqual(len(obj), 1)
601 obj = obj[0]
602 self.assertIsInstance(obj, Instance)
603 self.assertIn("value", obj.instance_attrs)
604 self.assertIn("other", obj.instance_attrs)
605
606 def test_infer_can_assign_has_slots(self) -> None:
607 mod = builder.parse("""
608 class A:
609 __slots__ = ('value',)
610 a = A()
611 a.value = "is set"
612 a.other = "not set"
613 """)
614 obj = list(mod.igetattr("a"))
615 self.assertEqual(len(obj), 1)
616 obj = obj[0]
617 self.assertIsInstance(obj, Instance)
618 self.assertIn("value", obj.instance_attrs)
619 self.assertNotIn("other", obj.instance_attrs)
620
621 def test_infer_can_assign_no_classdict(self) -> None:
622 mod = builder.parse("""
623 a = object()
624 a.value = "not set"
625 """)
626 obj = list(mod.igetattr("a"))
627 self.assertEqual(len(obj), 1)
628 obj = obj[0]
629 self.assertIsInstance(obj, Instance)
630 self.assertNotIn("value", obj.instance_attrs)
631
632 def test_augassign_attr(self) -> None:
633 builder.parse(
634 """
635 class Counter:
636 v = 0
637 def inc(self):
638 self.v += 1
639 """,
640 __name__,
641 )
642 # TODO: Check self.v += 1 generate AugAssign(AssAttr(...)),
643 # not AugAssign(GetAttr(AssName...))
644
645 def test_inferred_dont_pollute(self) -> None:
646 code = """
647 def func(a=None):
648 a.custom_attr = 0
649 def func2(a={}):
650 a.custom_attr = 0
651 """
652 builder.parse(code)
653 nonetype = nodes.const_factory(None)
654 self.assertNotIn("custom_attr", nonetype.locals)
655 self.assertNotIn("custom_attr", nonetype.instance_attrs)
656 nonetype = nodes.const_factory({})
657 self.assertNotIn("custom_attr", nonetype.locals)
658 self.assertNotIn("custom_attr", nonetype.instance_attrs)
659
660 def test_asstuple(self) -> None:
661 code = "a, b = range(2)"
662 astroid = builder.parse(code)
663 self.assertIn("b", astroid.locals)
664 code = """
665 def visit_if(self, node):
666 node.test, body = node.tests[0]
667 """
668 astroid = builder.parse(code)
669 self.assertIn("body", astroid["visit_if"].locals)
670
671 def test_build_constants(self) -> None:
672 """Test expected values of constants after rebuilding."""
673 code = """
674 def func():
675 return None
676 return
677 return 'None'
678 """
679 astroid = builder.parse(code)
680 none, nothing, chain = (ret.value for ret in astroid.body[0].body)
681 self.assertIsInstance(none, nodes.Const)
682 self.assertIsNone(none.value)
683 self.assertIsNone(nothing)
684 self.assertIsInstance(chain, nodes.Const)
685 self.assertEqual(chain.value, "None")
686
687 def test_not_implemented(self) -> None:
688 node = builder.extract_node("""
689 NotImplemented #@
690 """)
691 inferred = next(node.infer())
692 self.assertIsInstance(inferred, nodes.Const)
693 self.assertEqual(inferred.value, NotImplemented)
694
695 def test_type_comments_without_content(self) -> None:
696 node = builder.parse("""
697 a = 1 # type: # any comment
698 """)
699 assert node
700
701
702 class FileBuildTest(unittest.TestCase):
703 def setUp(self) -> None:
704 self.module = resources.build_file("data/module.py", "data.module")
705
706 def test_module_base_props(self) -> None:
707 """Test base properties and method of an astroid module."""
708 module = self.module
709 self.assertEqual(module.name, "data.module")
710 assert isinstance(module.doc_node, nodes.Const)
711 self.assertEqual(module.doc_node.value, "test module for astroid\n")
712 self.assertEqual(module.fromlineno, 0)
713 self.assertIsNone(module.parent)
714 self.assertEqual(module.frame(), module)
715 self.assertEqual(module.frame(), module)
716 self.assertEqual(module.root(), module)
717 self.assertEqual(module.file, os.path.abspath(resources.find("data/module.py")))
718 self.assertEqual(module.pure_python, 1)
719 self.assertEqual(module.package, 0)
720 self.assertFalse(module.is_statement)
721 with self.assertRaises(StatementMissing):
722 module.statement()
723
724 def test_module_locals(self) -> None:
725 """Test the 'locals' dictionary of an astroid module."""
726 module = self.module
727 _locals = module.locals
728 self.assertIs(_locals, module.globals)
729 keys = sorted(_locals.keys())
730 should = [
731 "MY_DICT",
732 "NameNode",
733 "YO",
734 "YOUPI",
735 "__revision__",
736 "global_access",
737 "modutils",
738 "four_args",
739 "os",
740 "redirect",
741 ]
742 should.sort()
743 self.assertEqual(keys, sorted(should))
744
745 def test_function_base_props(self) -> None:
746 """Test base properties and method of an astroid function."""
747 module = self.module
748 function = module["global_access"]
749 self.assertEqual(function.name, "global_access")
750 assert isinstance(function.doc_node, nodes.Const)
751 self.assertEqual(function.doc_node.value, "function test")
752 self.assertEqual(function.fromlineno, 11)
753 self.assertTrue(function.parent)
754 self.assertEqual(function.frame(), function)
755 self.assertEqual(function.parent.frame(), module)
756 self.assertEqual(function.frame(), function)
757 self.assertEqual(function.parent.frame(), module)
758 self.assertEqual(function.root(), module)
759 self.assertEqual([n.name for n in function.args.args], ["key", "val"])
760 self.assertEqual(function.type, "function")
761
762 def test_function_locals(self) -> None:
763 """Test the 'locals' dictionary of an astroid function."""
764 _locals = self.module["global_access"].locals
765 self.assertEqual(sorted(_locals.keys()), ["i", "key", "local", "val"])
766
767 def test_class_base_props(self) -> None:
768 """Test base properties and method of an astroid class."""
769 module = self.module
770 klass = module["YO"]
771 self.assertEqual(klass.name, "YO")
772 assert isinstance(klass.doc_node, nodes.Const)
773 self.assertEqual(klass.doc_node.value, "hehe\n haha")
774 self.assertEqual(klass.fromlineno, 25)
775 self.assertTrue(klass.parent)
776 self.assertEqual(klass.frame(), klass)
777 self.assertEqual(klass.parent.frame(), module)
778 self.assertEqual(klass.frame(), klass)
779 self.assertEqual(klass.parent.frame(), module)
780 self.assertEqual(klass.root(), module)
781 self.assertEqual(klass.basenames, [])
782
783 def test_class_locals(self) -> None:
784 """Test the 'locals' dictionary of an astroid class."""
785 module = self.module
786 assert_keys = ["__annotations__", "__init__", "__module__", "__qualname__", "a"]
787 self.assertEqual(sorted(module["YO"].locals.keys()), assert_keys)
788 assert_keys = [
789 "__annotations__",
790 "__init__",
791 "__module__",
792 "__qualname__",
793 "class_attr",
794 "class_method",
795 "method",
796 "static_method",
797 ]
798 self.assertEqual(sorted(module["YOUPI"].locals.keys()), assert_keys)
799
800 def test_class_instance_attrs(self) -> None:
801 module = self.module
802 self.assertEqual(list(module["YO"].instance_attrs.keys()), ["yo"])
803 self.assertEqual(list(module["YOUPI"].instance_attrs.keys()), ["member"])
804
805 def test_class_basenames(self) -> None:
806 module = self.module
807 self.assertEqual(module["YO"].basenames, [])
808 self.assertEqual(module["YOUPI"].basenames, ["YO"])
809
810 def test_method_base_props(self) -> None:
811 """Test base properties and method of an astroid method."""
812 method = self.module["YOUPI"]["method"]
813 self.assertEqual(method.name, "method")
814 self.assertEqual([n.name for n in method.args.args], ["self"])
815 assert isinstance(method.doc_node, nodes.Const)
816 self.assertEqual(method.doc_node.value, "method\n test")
817 self.assertEqual(method.fromlineno, 48)
818 self.assertEqual(method.type, "method")
819
820 def test_class_method_base_props(self) -> None:
821 method = self.module["YOUPI"]["class_method"]
822 self.assertEqual([n.name for n in method.args.args], ["cls"])
823 self.assertEqual(method.type, "classmethod")
824
825 def test_static_method_base_props(self) -> None:
826 method = self.module["YOUPI"]["static_method"]
827 self.assertEqual(method.args.args, [])
828 self.assertEqual(method.type, "staticmethod")
829
830 def test_method_locals(self) -> None:
831 """Test the 'locals' dictionary of an astroid method."""
832 method = self.module["YOUPI"]["method"]
833 # ListComp variables are not accessible outside
834 self.assertEqual(sorted(method.locals), ["a", "autre", "local", "self"])
835
836 def test_unknown_encoding(self) -> None:
837 with self.assertRaises(AstroidSyntaxError):
838 resources.build_file("data/invalid_encoding.py")
839
840
841 def test_module_build_dunder_file() -> None:
842 """Test that module_build() can work with modules that have the *__file__*
843 attribute.
844 """
845 module = builder.AstroidBuilder(AstroidManager()).module_build(collections)
846 assert module.path[0] == collections.__file__
847
848
849 def test_parse_module_with_invalid_type_comments_does_not_crash():
850 node = builder.parse("""
851 # op {
852 # name: "AssignAddVariableOp"
853 # input_arg {
854 # name: "resource"
855 # type: DT_RESOURCE
856 # }
857 # input_arg {
858 # name: "value"
859 # type_attr: "dtype"
860 # }
861 # attr {
862 # name: "dtype"
863 # type: "type"
864 # }
865 # is_stateful: true
866 # }
867 a, b = 2
868 """)
869 assert isinstance(node, nodes.Module)
870
871
872 def test_arguments_of_signature() -> None:
873 """Test that arguments is None for function without an inferable signature."""
874 node = builder.extract_node("int")
875 classdef: nodes.ClassDef = next(node.infer())
876 assert all(i.args.args is None for i in classdef.getattr("__dir__"))
877
878
879 class HermeticInterpreterTest(unittest.TestCase):
880 """Modeled on https://github.com/pylint-dev/astroid/pull/1207#issuecomment-951455588."""
881
882 @classmethod
883 def setUpClass(cls):
884 """Simulate a hermetic interpreter environment having no code on the filesystem."""
885 with tempfile.TemporaryDirectory() as tmp_dir:
886 sys.path.append(tmp_dir)
887
888 # Write a python file and compile it to .pyc
889 # To make this test have even more value, we would need to come up with some
890 # code that gets inferred differently when we get its "partial representation".
891 # This code is too simple for that. But we can't use builtins either, because we would
892 # have to delete builtins from the filesystem. But even if we engineered that,
893 # the difference might evaporate over time as inference changes.
894 cls.code_snippet = "def func(): return 42"
895 with tempfile.NamedTemporaryFile(
896 mode="w", dir=tmp_dir, suffix=".py", delete=False
897 ) as tmp:
898 tmp.write(cls.code_snippet)
899 pyc_file = py_compile.compile(tmp.name)
900 cls.pyc_name = tmp.name.replace(".py", ".pyc")
901 os.remove(tmp.name)
902 os.rename(pyc_file, cls.pyc_name)
903
904 # Import the module
905 cls.imported_module_path = pathlib.Path(cls.pyc_name)
906 cls.imported_module = importlib.import_module(cls.imported_module_path.stem)
907
908 # Delete source code from module object, filesystem, and path
909 del cls.imported_module.__file__
910 os.remove(cls.imported_module_path)
911 sys.path.remove(tmp_dir)
912
913 def test_build_from_live_module_without_source_file(self) -> None:
914 """Assert that inspect_build() is not called.
915
916 See comment in module_build() before the call to inspect_build():
917 "get a partial representation by introspection"
918
919 This "partial representation" was presumably causing unexpected behavior.
920 """
921 # Sanity check
922 self.assertIsNone(
923 self.imported_module.__loader__.get_source(self.imported_module_path.stem)
924 )
925 with self.assertRaises(AttributeError):
926 _ = self.imported_module.__file__
927
928 my_builder = builder.AstroidBuilder(AstroidManager())
929 with unittest.mock.patch.object(
930 self.imported_module.__loader__,
931 "get_source",
932 return_value=self.code_snippet,
933 ):
934 with unittest.mock.patch.object(
935 my_builder, "inspect_build", side_effect=AssertionError
936 ):
937 my_builder.module_build(
938 self.imported_module, modname=self.imported_module_path.stem
939 )