Debian Codegraph @

tests/test_object_model.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 import unittest
6 import xml
7
8 import pytest
9
10 import astroid
11 from astroid import bases, builder, nodes, objects, util
12 from astroid.const import PY311_PLUS
13 from astroid.exceptions import InferenceError
14
15 try:
16 import six # type: ignore[import] # pylint: disable=unused-import
17
18 HAS_SIX = True
19 except ImportError:
20 HAS_SIX = False
21
22
23 class InstanceModelTest(unittest.TestCase):
24 def test_instance_special_model(self) -> None:
25 ast_nodes = builder.extract_node(
26 """
27 class A:
28 "test"
29 def __init__(self):
30 self.a = 42
31 a = A()
32 a.__class__ #@
33 a.__module__ #@
34 a.__doc__ #@
35 a.__dict__ #@
36 """,
37 module_name="fake_module",
38 )
39 assert isinstance(ast_nodes, list)
40 cls = next(ast_nodes[0].infer())
41 self.assertIsInstance(cls, nodes.ClassDef)
42 self.assertEqual(cls.name, "A")
43
44 module = next(ast_nodes[1].infer())
45 self.assertIsInstance(module, nodes.Const)
46 self.assertEqual(module.value, "fake_module")
47
48 doc = next(ast_nodes[2].infer())
49 self.assertIsInstance(doc, nodes.Const)
50 self.assertEqual(doc.value, "test")
51
52 dunder_dict = next(ast_nodes[3].infer())
53 self.assertIsInstance(dunder_dict, nodes.Dict)
54 attr = next(dunder_dict.getitem(nodes.Const("a")).infer())
55 self.assertIsInstance(attr, nodes.Const)
56 self.assertEqual(attr.value, 42)
57
58 @pytest.mark.xfail(reason="Instance lookup cannot override object model")
59 def test_instance_local_attributes_overrides_object_model(self):
60 # The instance lookup needs to be changed in order for this to work.
61 ast_node = builder.extract_node("""
62 class A:
63 @property
64 def __dict__(self):
65 return []
66 A().__dict__
67 """)
68 inferred = next(ast_node.infer())
69 self.assertIsInstance(inferred, nodes.List)
70 self.assertEqual(inferred.elts, [])
71
72
73 class BoundMethodModelTest(unittest.TestCase):
74 def test_bound_method_model(self) -> None:
75 ast_nodes = builder.extract_node("""
76 class A:
77 def test(self): pass
78 a = A()
79 a.test.__func__ #@
80 a.test.__self__ #@
81 """)
82 assert isinstance(ast_nodes, list)
83 func = next(ast_nodes[0].infer())
84 self.assertIsInstance(func, nodes.FunctionDef)
85 self.assertEqual(func.name, "test")
86
87 self_ = next(ast_nodes[1].infer())
88 self.assertIsInstance(self_, astroid.Instance)
89 self.assertEqual(self_.name, "A")
90
91 def test_bound_method_model_classmethod_on_class(self) -> None:
92 """A classmethod accessed on its class proxies the function directly.
93
94 Reported in https://github.com/pylint-dev/pylint/issues/11198, where
95 ``getattr()`` on ``__func__`` aborted the whole pylint run.
96 """
97 ast_nodes = builder.extract_node("""
98 class A:
99 @classmethod
100 def test(cls): pass
101 A.test.__func__ #@
102 getattr(A.test, "__func__") #@
103 A.test.__self__ #@
104 """)
105 assert isinstance(ast_nodes, list)
106 for node in ast_nodes[:2]:
107 func = next(node.infer())
108 self.assertIsInstance(func, nodes.FunctionDef)
109 self.assertEqual(func.name, "test")
110
111 self_ = next(ast_nodes[2].infer())
112 self.assertIsInstance(self_, nodes.ClassDef)
113 self.assertEqual(self_.name, "A")
114
115 def test_bound_method_model_lambda_class_attribute(self) -> None:
116 """A lambda assigned as a class attribute is proxied directly too."""
117 ast_nodes = builder.extract_node("""
118 class A:
119 test = lambda self: 1
120 a = A()
121 a.test.__func__ #@
122 getattr(a.test, "__func__") #@
123 """)
124 assert isinstance(ast_nodes, list)
125 for node in ast_nodes:
126 func = next(node.infer())
127 self.assertIsInstance(func, nodes.Lambda)
128
129
130 class UnboundMethodModelTest(unittest.TestCase):
131 def test_unbound_method_model(self) -> None:
132 ast_nodes = builder.extract_node("""
133 class A:
134 def test(self): pass
135 t = A.test
136 t.__class__ #@
137 t.__func__ #@
138 t.__self__ #@
139 t.im_class #@
140 t.im_func #@
141 t.im_self #@
142 t.__doc__ #@
143 """)
144 assert isinstance(ast_nodes, list)
145 cls = next(ast_nodes[0].infer())
146 self.assertIsInstance(cls, nodes.ClassDef)
147 unbound_name = "function"
148
149 self.assertEqual(cls.name, unbound_name)
150
151 func = next(ast_nodes[1].infer())
152 self.assertIsInstance(func, nodes.FunctionDef)
153 self.assertEqual(func.name, "test")
154
155 self_ = next(ast_nodes[2].infer())
156 self.assertIsInstance(self_, nodes.Const)
157 self.assertIsNone(self_.value)
158
159 self.assertEqual(cls.name, next(ast_nodes[3].infer()).name)
160 self.assertEqual(func, next(ast_nodes[4].infer()))
161 self.assertIsNone(next(ast_nodes[5].infer()).value)
162
163 doc = next(ast_nodes[6].infer())
164 self.assertIsInstance(doc, nodes.Const)
165 self.assertIsNone(doc.value)
166
167
168 class ClassModelTest(unittest.TestCase):
169 def test_priority_to_local_defined_values(self) -> None:
170 ast_node = builder.extract_node("""
171 class A:
172 __doc__ = "first"
173 A.__doc__ #@
174 """)
175 inferred = next(ast_node.infer())
176 self.assertIsInstance(inferred, nodes.Const)
177 self.assertEqual(inferred.value, "first")
178
179 def test_class_model_correct_mro_subclasses_proxied(self) -> None:
180 ast_nodes = builder.extract_node("""
181 class A(object):
182 pass
183 A.mro #@
184 A.__subclasses__ #@
185 """)
186 for node in ast_nodes:
187 inferred = next(node.infer())
188 self.assertIsInstance(inferred, astroid.BoundMethod)
189 self.assertIsInstance(inferred._proxied, nodes.FunctionDef)
190 self.assertIsInstance(inferred.bound, nodes.ClassDef)
191 self.assertEqual(inferred.bound.name, "type")
192
193 def test_class_model(self) -> None:
194 ast_nodes = builder.extract_node(
195 """
196 class A(object):
197 "test"
198
199 class B(A): pass
200 class C(A): pass
201
202 A.__module__ #@
203 A.__name__ #@
204 A.__qualname__ #@
205 A.__doc__ #@
206 A.__mro__ #@
207 A.mro() #@
208 A.__bases__ #@
209 A.__class__ #@
210 A.__dict__ #@
211 A.__subclasses__() #@
212 """,
213 module_name="fake_module",
214 )
215 assert isinstance(ast_nodes, list)
216 module = next(ast_nodes[0].infer())
217 self.assertIsInstance(module, nodes.Const)
218 self.assertEqual(module.value, "fake_module")
219
220 name = next(ast_nodes[1].infer())
221 self.assertIsInstance(name, nodes.Const)
222 self.assertEqual(name.value, "A")
223
224 qualname = next(ast_nodes[2].infer())
225 self.assertIsInstance(qualname, nodes.Const)
226 self.assertEqual(qualname.value, "fake_module.A")
227
228 doc = next(ast_nodes[3].infer())
229 self.assertIsInstance(doc, nodes.Const)
230 self.assertEqual(doc.value, "test")
231
232 mro = next(ast_nodes[4].infer())
233 self.assertIsInstance(mro, nodes.Tuple)
234 self.assertEqual([cls.name for cls in mro.elts], ["A", "object"])
235
236 called_mro = next(ast_nodes[5].infer())
237 self.assertEqual(called_mro.elts, mro.elts)
238
239 base_nodes = next(ast_nodes[6].infer())
240 self.assertIsInstance(base_nodes, nodes.Tuple)
241 self.assertEqual([cls.name for cls in base_nodes.elts], ["object"])
242
243 cls = next(ast_nodes[7].infer())
244 self.assertIsInstance(cls, nodes.ClassDef)
245 self.assertEqual(cls.name, "type")
246
247 cls_dict = next(ast_nodes[8].infer())
248 self.assertIsInstance(cls_dict, nodes.Dict)
249
250 subclasses = next(ast_nodes[9].infer())
251 self.assertIsInstance(subclasses, nodes.List)
252 self.assertEqual([cls.name for cls in subclasses.elts], ["B", "C"])
253
254
255 class ModuleModelTest(unittest.TestCase):
256 def test_priority_to_local_defined_values(self) -> None:
257 ast_node = astroid.parse("""
258 __file__ = "mine"
259 """)
260 file_value = next(ast_node.igetattr("__file__"))
261 self.assertIsInstance(file_value, nodes.Const)
262 self.assertEqual(file_value.value, "mine")
263
264 def test__path__not_a_package(self) -> None:
265 ast_node = builder.extract_node("""
266 import sys
267 sys.__path__ #@
268 """)
269 with self.assertRaises(InferenceError):
270 next(ast_node.infer())
271
272 def test_module_model(self) -> None:
273 ast_nodes = builder.extract_node("""
274 import xml
275 xml.__path__ #@
276 xml.__name__ #@
277 xml.__doc__ #@
278 xml.__file__ #@
279 xml.__spec__ #@
280 xml.__loader__ #@
281 xml.__cached__ #@
282 xml.__package__ #@
283 xml.__dict__ #@
284 xml.__init__ #@
285 xml.__new__ #@
286
287 xml.__subclasshook__ #@
288 xml.__str__ #@
289 xml.__sizeof__ #@
290 xml.__repr__ #@
291 xml.__reduce__ #@
292
293 xml.__setattr__ #@
294 xml.__reduce_ex__ #@
295 xml.__lt__ #@
296 xml.__le__ #@
297 xml.__eq__ #@
298 xml.__ne__ #@
299 xml.__ge__ #@
300 xml.__gt__ #@
301 xml.__format__ #@
302 xml.__delattr__ #@
303 xml.__getattribute__ #@
304 xml.__hash__ #@
305 xml.__dir__ #@
306 xml.__call__ #@
307 xml.__closure__ #@
308 """)
309 assert isinstance(ast_nodes, list)
310 path = next(ast_nodes[0].infer())
311 self.assertIsInstance(path, nodes.List)
312 self.assertIsInstance(path.elts[0], nodes.Const)
313 self.assertEqual(path.elts[0].value, xml.__path__[0])
314
315 name = next(ast_nodes[1].infer())
316 self.assertIsInstance(name, nodes.Const)
317 self.assertEqual(name.value, "xml")
318
319 doc = next(ast_nodes[2].infer())
320 self.assertIsInstance(doc, nodes.Const)
321 self.assertEqual(doc.value, xml.__doc__)
322
323 file_ = next(ast_nodes[3].infer())
324 self.assertIsInstance(file_, nodes.Const)
325 self.assertEqual(file_.value, xml.__file__.replace(".pyc", ".py"))
326
327 for ast_node in ast_nodes[4:7]:
328 inferred = next(ast_node.infer())
329 self.assertIs(inferred, astroid.Uninferable)
330
331 package = next(ast_nodes[7].infer())
332 self.assertIsInstance(package, nodes.Const)
333 self.assertEqual(package.value, "xml")
334
335 dict_ = next(ast_nodes[8].infer())
336 self.assertIsInstance(dict_, nodes.Dict)
337
338 init_ = next(ast_nodes[9].infer())
339 assert isinstance(init_, bases.BoundMethod)
340 init_result = next(
341 init_.infer_call_result(
342 nodes.Call(
343 parent=None,
344 lineno=None,
345 col_offset=None,
346 end_lineno=None,
347 end_col_offset=None,
348 )
349 )
350 )
351 assert isinstance(init_result, nodes.Const)
352 assert init_result.value is None
353
354 new_ = next(ast_nodes[10].infer())
355 assert isinstance(new_, bases.BoundMethod)
356
357 # Inherited attributes return Uninferable.
358 for ast_node in ast_nodes[11:29]:
359 inferred = next(ast_node.infer())
360 self.assertIs(inferred, astroid.Uninferable)
361
362 # Attributes that don't exist on modules raise InferenceError.
363 for ast_node in ast_nodes[29:31]:
364 with pytest.raises(InferenceError):
365 next(ast_node.infer())
366
367
368 class FunctionModelTest(unittest.TestCase):
369 def test_partial_descriptor_support(self) -> None:
370 bound, result = builder.extract_node("""
371 class A(object): pass
372 def test(self): return 42
373 f = test.__get__(A(), A)
374 f #@
375 f() #@
376 """)
377 bound = next(bound.infer())
378 self.assertIsInstance(bound, astroid.BoundMethod)
379 self.assertEqual(bound._proxied._proxied.name, "test")
380 result = next(result.infer())
381 self.assertIsInstance(result, nodes.Const)
382 self.assertEqual(result.value, 42)
383
384 def test___get__has_extra_params_defined(self) -> None:
385 node = builder.extract_node("""
386 def test(self): return 42
387 test.__get__
388 """)
389 inferred = next(node.infer())
390 self.assertIsInstance(inferred, astroid.BoundMethod)
391 args = inferred.args.args
392 self.assertEqual(len(args), 2)
393 self.assertEqual([arg.name for arg in args], ["self", "type"])
394
395 def test__get__and_positional_only_args(self):
396 node = builder.extract_node("""
397 def test(self, a, b, /, c): return a + b + c
398 test.__get__(test)(1, 2, 3)
399 """)
400 inferred = next(node.infer())
401 assert inferred is util.Uninferable
402
403 @pytest.mark.xfail(reason="Descriptors cannot infer what self is")
404 def test_descriptor_not_inferrring_self(self):
405 # We can't infer __get__(X, Y)() when the bounded function
406 # uses self, because of the tree's parent not being propagating good enough.
407 result = builder.extract_node("""
408 class A(object):
409 x = 42
410 def test(self): return self.x
411 f = test.__get__(A(), A)
412 f() #@
413 """)
414 result = next(result.infer())
415 self.assertIsInstance(result, nodes.Const)
416 self.assertEqual(result.value, 42)
417
418 def test_descriptors_binding_invalid(self) -> None:
419 ast_nodes = builder.extract_node("""
420 class A: pass
421 def test(self): return 42
422 test.__get__()() #@
423 test.__get__(2, 3, 4) #@
424 """)
425 for node in ast_nodes:
426 with self.assertRaises(InferenceError):
427 next(node.infer())
428
429 def test_descriptor_error_regression(self) -> None:
430 """Make sure the following code does node cause an exception."""
431 node = builder.extract_node("""
432 class MyClass:
433 text = "MyText"
434
435 def mymethod1(self):
436 return self.text
437
438 def mymethod2(self):
439 return self.mymethod1.__get__(self, MyClass)
440
441
442 cl = MyClass().mymethod2()()
443 cl #@
444 """)
445 assert isinstance(node, nodes.NodeNG)
446 [const] = node.inferred()
447 assert const.value == "MyText"
448
449 def test_function_model(self) -> None:
450 ast_nodes = builder.extract_node(
451 '''
452 def func(a=1, b=2):
453 """test"""
454 func.__name__ #@
455 func.__doc__ #@
456 func.__qualname__ #@
457 func.__module__ #@
458 func.__defaults__ #@
459 func.__dict__ #@
460 func.__globals__ #@
461 func.__code__ #@
462 func.__closure__ #@
463 func.__init__ #@
464 func.__new__ #@
465
466 func.__subclasshook__ #@
467 func.__str__ #@
468 func.__sizeof__ #@
469 func.__repr__ #@
470 func.__reduce__ #@
471
472 func.__reduce_ex__ #@
473 func.__lt__ #@
474 func.__le__ #@
475 func.__eq__ #@
476 func.__ne__ #@
477 func.__ge__ #@
478 func.__gt__ #@
479 func.__format__ #@
480 func.__delattr__ #@
481 func.__getattribute__ #@
482 func.__hash__ #@
483 func.__dir__ #@
484 func.__class__ #@
485
486 func.__setattr__ #@
487 func.__builtins__ #@
488 func.__getstate__ #@
489 func.__init_subclass__ #@
490 func.__type_params__ #@
491 ''',
492 module_name="fake_module",
493 )
494 assert isinstance(ast_nodes, list)
495 name = next(ast_nodes[0].infer())
496 self.assertIsInstance(name, nodes.Const)
497 self.assertEqual(name.value, "func")
498
499 doc = next(ast_nodes[1].infer())
500 self.assertIsInstance(doc, nodes.Const)
501 self.assertEqual(doc.value, "test")
502
503 qualname = next(ast_nodes[2].infer())
504 self.assertIsInstance(qualname, nodes.Const)
505 self.assertEqual(qualname.value, "fake_module.func")
506
507 module = next(ast_nodes[3].infer())
508 self.assertIsInstance(module, nodes.Const)
509 self.assertEqual(module.value, "fake_module")
510
511 defaults = next(ast_nodes[4].infer())
512 self.assertIsInstance(defaults, nodes.Tuple)
513 self.assertEqual([default.value for default in defaults.elts], [1, 2])
514
515 dict_ = next(ast_nodes[5].infer())
516 self.assertIsInstance(dict_, nodes.Dict)
517
518 globals_ = next(ast_nodes[6].infer())
519 self.assertIsInstance(globals_, nodes.Dict)
520
521 for ast_node in ast_nodes[7:9]:
522 self.assertIs(next(ast_node.infer()), astroid.Uninferable)
523
524 init_ = next(ast_nodes[9].infer())
525 assert isinstance(init_, bases.BoundMethod)
526 init_result = next(
527 init_.infer_call_result(
528 nodes.Call(
529 parent=None,
530 lineno=None,
531 col_offset=None,
532 end_lineno=None,
533 end_col_offset=None,
534 )
535 )
536 )
537 assert isinstance(init_result, nodes.Const)
538 assert init_result.value is None
539
540 new_ = next(ast_nodes[10].infer())
541 assert isinstance(new_, bases.BoundMethod)
542
543 # Remaining attributes return Uninferable.
544 for ast_node in ast_nodes[11:34]:
545 inferred = next(ast_node.infer())
546 assert inferred is util.Uninferable
547
548 def test_empty_return_annotation(self) -> None:
549 ast_node = builder.extract_node("""
550 def test(): pass
551 test.__annotations__
552 """)
553 annotations = next(ast_node.infer())
554 self.assertIsInstance(annotations, nodes.Dict)
555 self.assertEqual(len(annotations.items), 0)
556
557 def test_builtin_dunder_init_does_not_crash_when_accessing_annotations(
558 self,
559 ) -> None:
560 ast_node = builder.extract_node("""
561 class Class:
562 @classmethod
563 def class_method(cls):
564 cls.__init__.__annotations__ #@
565 """)
566 inferred = next(ast_node.infer())
567 self.assertIsInstance(inferred, nodes.Dict)
568 self.assertEqual(len(inferred.items), 0)
569
570 def test_annotations_kwdefaults(self) -> None:
571 ast_node = builder.extract_node("""
572 def test(a: 1, *args: 2, f:4='lala', **kwarg:3)->2: pass
573 test.__annotations__ #@
574 test.__kwdefaults__ #@
575 """)
576 annotations = next(ast_node[0].infer())
577 self.assertIsInstance(annotations, nodes.Dict)
578 self.assertIsInstance(annotations.getitem(nodes.Const("return")), nodes.Const)
579 self.assertEqual(annotations.getitem(nodes.Const("return")).value, 2)
580 self.assertIsInstance(annotations.getitem(nodes.Const("a")), nodes.Const)
581 self.assertEqual(annotations.getitem(nodes.Const("a")).value, 1)
582 self.assertEqual(annotations.getitem(nodes.Const("args")).value, 2)
583 self.assertEqual(annotations.getitem(nodes.Const("kwarg")).value, 3)
584
585 self.assertEqual(annotations.getitem(nodes.Const("f")).value, 4)
586
587 kwdefaults = next(ast_node[1].infer())
588 self.assertIsInstance(kwdefaults, nodes.Dict)
589 # self.assertEqual(kwdefaults.getitem('f').value, 'lala')
590
591 def test_annotation_positional_only(self):
592 ast_node = builder.extract_node("""
593 def test(a: 1, b: 2, /, c: 3): pass
594 test.__annotations__ #@
595 """)
596 annotations = next(ast_node.infer())
597 self.assertIsInstance(annotations, nodes.Dict)
598
599 self.assertIsInstance(annotations.getitem(nodes.Const("a")), nodes.Const)
600 self.assertEqual(annotations.getitem(nodes.Const("a")).value, 1)
601 self.assertEqual(annotations.getitem(nodes.Const("b")).value, 2)
602 self.assertEqual(annotations.getitem(nodes.Const("c")).value, 3)
603
604 def test_is_not_lambda(self):
605 ast_node = builder.extract_node("def func(): pass")
606 self.assertIs(ast_node.is_lambda, False)
607
608
609 class TestContextManagerModel:
610 def test_model(self) -> None:
611 """We use a generator to test this model."""
612 ast_nodes = builder.extract_node("""
613 def test():
614 "a"
615 yield
616
617 gen = test()
618 gen.__enter__ #@
619 gen.__exit__ #@
620 """)
621 assert isinstance(ast_nodes, list)
622
623 enter = next(ast_nodes[0].infer())
624 assert isinstance(enter, astroid.BoundMethod)
625 # Test that the method is correctly bound
626 assert isinstance(enter.bound, bases.Generator)
627 assert enter.bound._proxied.qname() == "builtins.generator"
628 # Test that thet FunctionDef accepts no arguments except self
629 # NOTE: This probably shouldn't be double proxied, but this is a
630 # quirck of the current model implementations.
631 assert isinstance(enter._proxied._proxied, nodes.FunctionDef)
632 assert len(enter._proxied._proxied.args.args) == 1
633 assert enter._proxied._proxied.args.args[0].name == "self"
634
635 exit_node = next(ast_nodes[1].infer())
636 assert isinstance(exit_node, astroid.BoundMethod)
637 # Test that the FunctionDef accepts the arguments as defiend in the ObjectModel
638 assert isinstance(exit_node._proxied._proxied, nodes.FunctionDef)
639 assert len(exit_node._proxied._proxied.args.args) == 4
640 assert exit_node._proxied._proxied.args.args[0].name == "self"
641 assert exit_node._proxied._proxied.args.args[1].name == "exc_type"
642 assert exit_node._proxied._proxied.args.args[2].name == "exc_value"
643 assert exit_node._proxied._proxied.args.args[3].name == "traceback"
644
645
646 class GeneratorModelTest(unittest.TestCase):
647 def test_model(self) -> None:
648 ast_nodes = builder.extract_node("""
649 def test():
650 "a"
651 yield
652
653 gen = test()
654 gen.__name__ #@
655 gen.__doc__ #@
656 gen.gi_code #@
657 gen.gi_frame #@
658 gen.send #@
659 gen.__enter__ #@
660 gen.__exit__ #@
661 """)
662 assert isinstance(ast_nodes, list)
663 name = next(ast_nodes[0].infer())
664 self.assertEqual(name.value, "test")
665
666 doc = next(ast_nodes[1].infer())
667 self.assertEqual(doc.value, "a")
668
669 # ``gi_code`` and ``gi_frame`` are data descriptors, so they resolve but
670 # the values they return are not statically known.
671 gi_code = next(ast_nodes[2].infer())
672 self.assertIs(gi_code, util.Uninferable)
673
674 gi_frame = next(ast_nodes[3].infer())
675 self.assertIs(gi_frame, util.Uninferable)
676
677 send = next(ast_nodes[4].infer())
678 self.assertIsInstance(send, astroid.BoundMethod)
679
680 enter = next(ast_nodes[5].infer())
681 assert isinstance(enter, astroid.BoundMethod)
682
683 exit_node = next(ast_nodes[6].infer())
684 assert isinstance(exit_node, astroid.BoundMethod)
685
686
687 class ExceptionModelTest(unittest.TestCase):
688 @staticmethod
689 def test_valueerror_py3() -> None:
690 ast_nodes = builder.extract_node("""
691 try:
692 x[42]
693 except ValueError as err:
694 err.args #@
695 err.__traceback__ #@
696
697 err.message #@
698 """)
699 assert isinstance(ast_nodes, list)
700 args = next(ast_nodes[0].infer())
701 assert isinstance(args, nodes.Tuple)
702 tb = next(ast_nodes[1].infer())
703 # Python 3.11: If 'contextlib' is loaded, '__traceback__'
704 # could be set inside '__exit__' method in
705 # which case 'err.__traceback__' will be 'Uninferable'
706 try:
707 assert isinstance(tb, astroid.Instance)
708 assert tb.name == "traceback"
709 except AssertionError:
710 if PY311_PLUS:
711 assert tb == util.Uninferable
712 else:
713 raise
714
715 with pytest.raises(InferenceError):
716 next(ast_nodes[2].infer())
717
718 def test_syntax_error(self) -> None:
719 ast_node = builder.extract_node("""
720 try:
721 x[42]
722 except SyntaxError as err:
723 err.text #@
724 """)
725 inferred = next(ast_node.infer())
726 assert isinstance(inferred, nodes.Const)
727
728 @unittest.skipIf(HAS_SIX, "This test fails if the six library is installed")
729 def test_oserror(self) -> None:
730 ast_nodes = builder.extract_node("""
731 try:
732 raise OSError("a")
733 except OSError as err:
734 err.filename #@
735 err.filename2 #@
736 err.errno #@
737 """)
738 expected_values = ["", "", 0]
739 for node, value in zip(ast_nodes, expected_values):
740 inferred = next(node.infer())
741 assert isinstance(inferred, nodes.Const)
742 assert inferred.value == value
743
744 @staticmethod
745 def test_traceback_frame_attribute() -> None:
746 """The frame a traceback exposes is a data descriptor, so its value is
747 unknown rather than a class named after the attribute.
748
749 Closes https://github.com/pylint-dev/pylint/issues/11218
750 """
751 node = builder.extract_node("""
752 try:
753 raise ValueError("a")
754 except ValueError as err:
755 err.__traceback__.tb_frame.f_locals #@
756 """)
757 assert node.inferred() == [util.Uninferable]
758
759 def test_unicodedecodeerror(self) -> None:
760 code = """
761 try:
762 raise UnicodeDecodeError("utf-8", b"blob", 0, 1, "reason")
763 except UnicodeDecodeError as error:
764 error.object #@
765 """
766 node = builder.extract_node(code)
767 inferred = next(node.infer())
768 assert isinstance(inferred, nodes.Const)
769 assert inferred.value == b""
770
771 def test_import_error(self) -> None:
772 ast_nodes = builder.extract_node("""
773 try:
774 raise ImportError("a")
775 except ImportError as err:
776 err.name #@
777 err.path #@
778 """)
779 for node in ast_nodes:
780 inferred = next(node.infer())
781 assert isinstance(inferred, nodes.Const)
782 assert inferred.value == ""
783
784 def test_exception_instance_correctly_instantiated(self) -> None:
785 ast_node = builder.extract_node("""
786 try:
787 raise ImportError("a")
788 except ImportError as err:
789 err #@
790 """)
791 inferred = next(ast_node.infer())
792 assert isinstance(inferred, astroid.Instance)
793 cls = next(inferred.igetattr("__class__"))
794 assert isinstance(cls, nodes.ClassDef)
795
796
797 class DictObjectModelTest(unittest.TestCase):
798 def test__class__(self) -> None:
799 ast_node = builder.extract_node("{}.__class__")
800 inferred = next(ast_node.infer())
801 self.assertIsInstance(inferred, nodes.ClassDef)
802 self.assertEqual(inferred.name, "dict")
803
804 def test_attributes_inferred_as_methods(self) -> None:
805 ast_nodes = builder.extract_node("""
806 {}.values #@
807 {}.items #@
808 {}.keys #@
809 """)
810 for node in ast_nodes:
811 inferred = next(node.infer())
812 self.assertIsInstance(inferred, astroid.BoundMethod)
813
814 def test_wrapper_objects_for_dict_methods_python3(self) -> None:
815 ast_nodes = builder.extract_node("""
816 {1:1, 2:3}.values() #@
817 {1:1, 2:3}.keys() #@
818 {1:1, 2:3}.items() #@
819 """)
820 assert isinstance(ast_nodes, list)
821 values = next(ast_nodes[0].infer())
822 self.assertIsInstance(values, objects.DictValues)
823 self.assertEqual([elt.value for elt in values.elts], [1, 3])
824 keys = next(ast_nodes[1].infer())
825 self.assertIsInstance(keys, objects.DictKeys)
826 self.assertEqual([elt.value for elt in keys.elts], [1, 2])
827 items = next(ast_nodes[2].infer())
828 self.assertIsInstance(items, objects.DictItems)
829
830
831 class TestExceptionInstanceModel:
832 """Tests for ExceptionInstanceModel."""
833
834 def test_str_argument_not_required(self) -> None:
835 """Test that the first argument to an exception does not need to be a str."""
836 ast_node = builder.extract_node("""
837 BaseException() #@
838 """)
839 args: nodes.Tuple = next(ast_node.infer()).getattr("args")[0]
840 # BaseException doesn't have any required args, not even a string
841 assert not args.elts
842
843
844 @pytest.mark.parametrize("parentheses", (True, False))
845 def test_lru_cache(parentheses) -> None:
846 ast_nodes = builder.extract_node(f"""
847 import functools
848 class Foo(object):
849 @functools.lru_cache{"()" if parentheses else ""}
850 def foo():
851 pass
852 f = Foo()
853 f.foo.cache_clear #@
854 f.foo.__wrapped__ #@
855 f.foo.cache_info() #@
856 """)
857 assert isinstance(ast_nodes, list)
858 cache_clear = next(ast_nodes[0].infer())
859 assert isinstance(cache_clear, astroid.BoundMethod)
860 wrapped = next(ast_nodes[1].infer())
861 assert isinstance(wrapped, nodes.FunctionDef)
862 assert wrapped.name == "foo"
863 cache_info = next(ast_nodes[2].infer())
864 assert isinstance(cache_info, astroid.Instance)
865
866
867 def test_class_annotations() -> None:
868 """Test that the `__annotations__` attribute is avaiable in the class scope"""
869 annotations, klass_attribute = builder.extract_node("""
870 class Test:
871 __annotations__ #@
872 Test.__annotations__ #@
873 """)
874 # Test that `__annotations__` attribute is available in the class scope:
875 assert isinstance(annotations, nodes.Name)
876 # The `__annotations__` attribute is `Uninferable`:
877 assert next(annotations.infer()) is astroid.Uninferable
878
879 # Test that we can access the class annotations:
880 assert isinstance(klass_attribute, nodes.Attribute)
881
882
883 def test_class_annotations_typed_dict() -> None:
884 """Test that we can access class annotations on various TypedDicts"""
885 apple, pear = builder.extract_node("""
886 from typing import TypedDict
887
888
889 class Apple(TypedDict):
890 a: int
891 b: str
892
893
894 Pear = TypedDict('OtherTypedDict', {'a': int, 'b': str})
895
896
897 Apple.__annotations__ #@
898 Pear.__annotations__ #@
899 """)
900
901 assert isinstance(apple, nodes.Attribute)
902 assert next(apple.infer()) is astroid.Uninferable
903 assert isinstance(pear, nodes.Attribute)
904 assert next(pear.infer()) is astroid.Uninferable
905
906
907 def test_object_dunder_methods_can_be_overridden() -> None:
908 """Test that ObjectModel dunders don't block class overrides."""
909 # Test instance method override
910 eq_result = builder.extract_node("""
911 class MyClass:
912 def __eq__(self, other):
913 return "custom equality"
914
915 MyClass().__eq__(None) #@
916 """)
917 inferred = next(eq_result.infer())
918 assert isinstance(inferred, nodes.Const)
919 assert inferred.value == "custom equality"
920
921 # Test that __eq__ on instance returns a bound method
922 eq_method = builder.extract_node("""
923 class MyClass:
924 def __eq__(self, other):
925 return True
926
927 MyClass().__eq__ #@
928 """)
929 inferred = next(eq_method.infer())
930 assert isinstance(inferred, astroid.BoundMethod)
931
932 # Test other commonly overridden dunders
933 for dunder, return_val in (
934 ("__ne__", "not equal"),
935 ("__lt__", "less than"),
936 ("__le__", "less or equal"),
937 ("__gt__", "greater than"),
938 ("__ge__", "greater or equal"),
939 ("__str__", "string repr"),
940 ("__repr__", "repr"),
941 ("__hash__", 42),
942 ):
943 node = builder.extract_node(f"""
944 class MyClass:
945 def {dunder}(self, *args):
946 return {return_val!r}
947
948 MyClass().{dunder}() #@
949 """)
950 inferred = next(node.infer())
951 assert isinstance(inferred, nodes.Const), f"{dunder} failed to infer correctly"
952 assert inferred.value == return_val, f"{dunder} returned wrong value"
953
954
955 def test_unoverridden_object_dunders_return_uninferable() -> None:
956 """Test that un-overridden object dunders return Uninferable when called."""
957 for dunder in (
958 "__eq__",
959 "__hash__",
960 "__lt__",
961 "__le__",
962 "__gt__",
963 "__ge__",
964 "__ne__",
965 ):
966 node = builder.extract_node(f"""
967 class MyClass:
968 pass
969
970 MyClass().{dunder}(None) if "{dunder}" != "__hash__" else MyClass().{dunder}() #@
971 """)
972 result = next(node.infer())
973 assert result is util.Uninferable
974
975
976 def test_all_object_dunders_accessible() -> None:
977 """Test that object dunders are accessible on classes and instances."""
978 # Use actual dunders from object in the current Python version
979 object_dunders = [attr for attr in dir(object) if attr.startswith("__")]
980
981 cls, instance = builder.extract_node("""
982 class MyClass:
983 pass
984
985 MyClass #@
986 MyClass() #@
987 """)
988 cls = next(cls.infer())
989 instance = next(instance.infer())
990
991 for dunder in object_dunders:
992 assert cls.getattr(dunder)
993 assert instance.getattr(dunder)
994
995
996 def test_hash_none_for_unhashable_builtins() -> None:
997 """Test that unhashable builtin types have __hash__ = None."""
998 for type_name in ("list", "dict", "set"):
999 node = builder.extract_node(f"{type_name} #@")
1000 cls = next(node.infer())
1001 hash_attr = cls.getattr("__hash__")[0]
1002 assert isinstance(hash_attr, nodes.Const)
1003 assert hash_attr.value is None
1004
1005
1006 def test_unbound_method_object_dunders_return_uninferable() -> None:
1007 """Test that ObjectModel-only dunders on unbound methods return Uninferable."""
1008 node = builder.extract_node("""
1009 class A:
1010 def test(self): pass
1011 A.test #@
1012 """)
1013 unbound = next(node.infer())
1014 assert isinstance(unbound, bases.UnboundMethod)
1015
1016 for dunder in (
1017 "__eq__",
1018 "__ne__",
1019 "__lt__",
1020 "__le__",
1021 "__gt__",
1022 "__ge__",
1023 "__repr__",
1024 "__str__",
1025 "__hash__",
1026 ):
1027 inferred = next(unbound.igetattr(dunder))
1028 assert inferred is util.Uninferable, f"{dunder} should be Uninferable"
1029
1030 attrs = unbound.getattr(dunder)
1031 assert attrs, f"{dunder} getattr should return results"
1032
1033
1034 def test_super_special_attributes_fallback() -> None:
1035 """Test that super() special attributes use the fallback path correctly."""
1036 doc_node = builder.extract_node("""
1037 class Base:
1038 def method(self):
1039 return super().__doc__
1040 Base().method() #@
1041 """)
1042 doc_inferred = next(doc_node.infer())
1043 assert doc_inferred is util.Uninferable
1044
1045 thisclass_node = builder.extract_node("""
1046 class Base:
1047 def method(self):
1048 return super().__thisclass__
1049 Base().method() #@
1050 """)
1051 thisclass_inferred = next(thisclass_node.infer())
1052 assert isinstance(thisclass_inferred, nodes.ClassDef)
1053 assert thisclass_inferred.name == "Base"
1054
1055
1056 @pytest.mark.parametrize(
1057 "attr",
1058 [
1059 "__get__",
1060 "__defaults__",
1061 "__annotations__",
1062 "__dict__",
1063 "__globals__",
1064 "__kwdefaults__",
1065 ],
1066 )
1067 def test_builtin_func_no_descriptor_attrs(attr: str) -> None:
1068 """Test builtin functions lack descriptor protocol attributes."""
1069 node = builder.extract_node(f"eval.{attr}")
1070 with pytest.raises(InferenceError):
1071 next(node.infer())
1072
1073
1074 def test_getattr_on_property_fset_with_annassign_does_not_crash() -> None:
1075 """Test that getattr on property fset doesn't crash with AnnAssign."""
1076 node = builder.extract_node("""
1077 from typing import TypeVar, Generic
1078
1079 T = TypeVar('T')
1080
1081 class Base:
1082 _x: object
1083 @property
1084 def x(self):
1085 return self._x
1086 @x.setter
1087 def x(self, val):
1088 self._x = val
1089
1090 class Child(Base, Generic[T]):
1091 _x: T
1092 @property
1093 def x(self) -> T:
1094 return self._x
1095 @x.setter
1096 def x(self, val):
1097 getattr(Base.x, "fset", None) #@
1098 """)
1099 next(node.infer())