Debian Codegraph @

tests/test_regrtest.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 platform
6 import sys
7 import textwrap
8 import unittest
9 from unittest import mock
10
11 import pytest
12
13 from astroid import MANAGER, Instance, bases, manager, nodes, parse, test_utils
14 from astroid.builder import AstroidBuilder, _extract_single_node, extract_node
15 from astroid.const import PY312_PLUS, PY315_PLUS
16 from astroid.context import InferenceContext
17 from astroid.exceptions import AstroidSyntaxError, InferenceError
18 from astroid.manager import AstroidManager
19 from astroid.raw_building import build_module
20 from astroid.util import Uninferable
21
22 from . import resources
23
24 try:
25 import numpy # pylint: disable=unused-import
26 except ImportError:
27 HAS_NUMPY = False
28 else:
29 HAS_NUMPY = True
30
31
32 class NonRegressionTests(unittest.TestCase):
33 def setUp(self) -> None:
34 sys.path.insert(0, resources.find("data"))
35 MANAGER.always_load_extensions = True
36 self.addCleanup(MANAGER.clear_cache)
37
38 def tearDown(self) -> None:
39 MANAGER.always_load_extensions = False
40 sys.path.pop(0)
41 sys.path_importer_cache.pop(resources.find("data"), None)
42
43 def test_manager_instance_attributes_reference_global_MANAGER(self) -> None:
44 for expected in (True, False):
45 with mock.patch.dict(
46 manager.AstroidManager.brain,
47 values={"always_load_extensions": expected},
48 ):
49 assert (
50 MANAGER.always_load_extensions
51 == manager.AstroidManager.brain["always_load_extensions"]
52 )
53 with mock.patch.dict(
54 manager.AstroidManager.brain,
55 values={"optimize_ast": expected},
56 ):
57 assert (
58 MANAGER.optimize_ast == manager.AstroidManager.brain["optimize_ast"]
59 )
60
61 def test_module_path(self) -> None:
62 man = test_utils.brainless_manager()
63 mod = man.ast_from_module_name("package.import_package_subpackage_module")
64 package = next(mod.igetattr("package"))
65 self.assertEqual(package.name, "package")
66 subpackage = next(package.igetattr("subpackage"))
67 self.assertIsInstance(subpackage, nodes.Module)
68 self.assertTrue(subpackage.package)
69 self.assertEqual(subpackage.name, "package.subpackage")
70 module = next(subpackage.igetattr("module"))
71 self.assertEqual(module.name, "package.subpackage.module")
72
73 def test_package_sidepackage(self) -> None:
74 brainless_manager = test_utils.brainless_manager()
75 assert "package.sidepackage" not in MANAGER.astroid_cache
76 package = brainless_manager.ast_from_module_name("absimp")
77 self.assertIsInstance(package, nodes.Module)
78 self.assertTrue(package.package)
79 subpackage = next(package.getattr("sidepackage")[0].infer())
80 self.assertIsInstance(subpackage, nodes.Module)
81 self.assertTrue(subpackage.package)
82 self.assertEqual(subpackage.name, "absimp.sidepackage")
83
84 def test_living_property(self) -> None:
85 builder = AstroidBuilder(AstroidManager())
86 builder._done = {}
87 builder._module = sys.modules[__name__]
88 builder.object_build(build_module("module_name", ""), Whatever)
89
90 @unittest.skipIf(not HAS_NUMPY, "Needs numpy")
91 def test_numpy_crash(self):
92 """Test don't crash on numpy."""
93 # a crash occurred somewhere in the past, and an
94 # InferenceError instead of a crash was better, but now we even infer!
95 builder = AstroidBuilder(AstroidManager())
96 data = """
97 from numpy import multiply
98
99 multiply([1, 2], [3, 4])
100 """
101 astroid = builder.string_build(data, __name__, __file__)
102 callfunc = astroid.body[1].value.func
103 inferred = callfunc.inferred()
104 self.assertEqual(len(inferred), 1)
105
106 @unittest.skipUnless(HAS_NUMPY and not PY312_PLUS, "Needs numpy and < Python 3.12")
107 def test_numpy_distutils(self):
108 """Special handling of virtualenv's patching of distutils shouldn't interfere
109 with numpy.distutils.
110
111 PY312_PLUS -- This test will likely become unnecessary when Python 3.12 is
112 numpy's minimum version. (numpy.distutils will be removed then.)
113 """
114 node = extract_node("""
115 from numpy.distutils.misc_util import is_sequence
116 is_sequence("ABC") #@
117 """)
118 inferred = node.inferred()
119 self.assertIsInstance(inferred[0], nodes.Const)
120
121 def test_nameconstant(self) -> None:
122 # used to fail for Python 3.4
123 builder = AstroidBuilder(AstroidManager())
124 astroid = builder.string_build("def test(x=True): pass")
125 default = astroid.body[0].args.args[0]
126 self.assertEqual(default.name, "x")
127 self.assertEqual(next(default.infer()).value, True)
128
129 def test_recursion_regression_issue25(self) -> None:
130 builder = AstroidBuilder(AstroidManager())
131 data = """
132 import recursion as base
133
134 _real_Base = base.Base
135
136 class Derived(_real_Base):
137 pass
138
139 def run():
140 base.Base = Derived
141 """
142 astroid = builder.string_build(data, __name__, __file__)
143 # Used to crash in _is_metaclass, due to wrong
144 # ancestors chain
145 classes = astroid.nodes_of_class(nodes.ClassDef)
146 for klass in classes:
147 # triggers the _is_metaclass call
148 klass.type # pylint: disable=pointless-statement # noqa: B018
149
150 def test_decorator_callchain_issue42(self) -> None:
151 builder = AstroidBuilder(AstroidManager())
152 data = """
153
154 def test():
155 def factory(func):
156 def newfunc():
157 func()
158 return newfunc
159 return factory
160
161 @test()
162 def crash():
163 pass
164 """
165 astroid = builder.string_build(data, __name__, __file__)
166 self.assertEqual(astroid["crash"].type, "function")
167
168 def test_filter_stmts_scoping(self) -> None:
169 builder = AstroidBuilder(AstroidManager())
170 data = """
171 def test():
172 compiler = int()
173 class B(compiler.__class__):
174 pass
175 compiler = B()
176 return compiler
177 """
178 astroid = builder.string_build(data, __name__, __file__)
179 test = astroid["test"]
180 result = next(test.infer_call_result(astroid))
181 self.assertIsInstance(result, Instance)
182 base = next(result._proxied.bases[0].infer())
183 self.assertEqual(base.name, "int")
184
185 def test_filter_stmts_nested_if(self) -> None:
186 builder = AstroidBuilder(AstroidManager())
187 data = """
188 def test(val):
189 variable = None
190
191 if val == 1:
192 variable = "value"
193 if variable := "value":
194 pass
195
196 elif val == 2:
197 variable = "value_two"
198 variable = "value_two"
199
200 return variable
201 """
202 module = builder.string_build(data, __name__, __file__)
203 test_func = module["test"]
204 result = list(test_func.infer_call_result(module))
205 assert len(result) == 3
206 assert isinstance(result[0], nodes.Const)
207 assert result[0].value is None
208 assert result[0].lineno == 3
209 assert isinstance(result[1], nodes.Const)
210 assert result[1].value == "value"
211 assert result[1].lineno == 7
212 assert isinstance(result[1], nodes.Const)
213 assert result[2].value == "value_two"
214 assert result[2].lineno == 12
215
216 def test_ancestors_patching_class_recursion(self) -> None:
217 node = AstroidBuilder(AstroidManager()).string_build(textwrap.dedent("""
218 import string
219 Template = string.Template
220
221 class A(Template):
222 pass
223
224 class B(A):
225 pass
226
227 def test(x=False):
228 if x:
229 string.Template = A
230 else:
231 string.Template = B
232 """))
233 klass = node["A"]
234 ancestors = list(klass.ancestors())
235 self.assertEqual(ancestors[0].qname(), "string.Template")
236
237 def test_ancestors_yes_in_bases(self) -> None:
238 # Test for issue https://bitbucket.org/logilab/astroid/issue/84
239 # This used to crash astroid with a TypeError, because an Uninferable
240 # node was present in the bases
241 node = extract_node("""
242 def with_metaclass(meta, *bases):
243 class metaclass(meta):
244 def __new__(cls, name, this_bases, d):
245 return meta(name, bases, d)
246 return type.__new__(metaclass, 'temporary_class', (), {})
247
248 import lala
249
250 class A(with_metaclass(object, lala.lala)): #@
251 pass
252 """)
253 ancestors = list(node.ancestors())
254 self.assertEqual(len(ancestors), 1)
255 self.assertEqual(ancestors[0].qname(), "builtins.object")
256
257 def test_ancestors_missing_from_function(self) -> None:
258 # Test for https://www.logilab.org/ticket/122793
259 node = extract_node("""
260 def gen(): yield
261 GEN = gen()
262 next(GEN)
263 """)
264 self.assertRaises(InferenceError, next, node.infer())
265
266 def test_unicode_in_docstring(self) -> None:
267 # Crashed for astroid==1.4.1
268 # Test for https://bitbucket.org/logilab/astroid/issues/273/
269
270 # In a regular file, "coding: utf-8" would have been used.
271 node = extract_node(f"""
272 from __future__ import unicode_literals
273
274 class MyClass(object):
275 def method(self):
276 "With unicode : {'’'} "
277
278 instance = MyClass()
279 """)
280
281 next(node.value.infer()).as_string()
282
283 def test_binop_generates_nodes_with_parents(self) -> None:
284 node = extract_node("""
285 def no_op(*args):
286 pass
287 def foo(*args):
288 def inner(*more_args):
289 args + more_args #@
290 return inner
291 """)
292 inferred = next(node.infer())
293 self.assertIsInstance(inferred, nodes.Tuple)
294 self.assertIsNotNone(inferred.parent)
295 self.assertIsInstance(inferred.parent, nodes.BinOp)
296
297 def test_decorator_names_inference_error_leaking(self) -> None:
298 node = extract_node("""
299 class Parent(object):
300 @property
301 def foo(self):
302 pass
303
304 class Child(Parent):
305 @Parent.foo.getter
306 def foo(self): #@
307 return super(Child, self).foo + ['oink']
308 """)
309 inferred = next(node.infer())
310 self.assertEqual(inferred.decoratornames(), {".Parent.foo.getter"})
311
312 @unittest.skipUnless(PY312_PLUS, "Uses 3.12 type param syntax")
313 def test_decorator_names_type_param(self) -> None:
314 node = extract_node("""
315 class Basket[T]:
316 @T
317 def apple(self): #@
318 pass
319 """)
320
321 self.assertEqual(node.decoratornames(), {"typing.TypeVar"})
322 self.assertIs(next(node.infer()), node)
323
324 def test_decorator_names_slice(self) -> None:
325 node = extract_node("""
326 @slice(0)
327 def f(): #@
328 pass
329 """)
330
331 self.assertEqual(node.decoratornames(), {"builtins.slice"})
332 self.assertIs(next(node.infer()), node)
333
334 def test_recursive_property_method(self) -> None:
335 node = extract_node("""
336 class APropert():
337 @property
338 def property(self):
339 return self
340 APropert().property
341 """)
342 next(node.infer())
343
344 def test_uninferable_string_argument_of_namedtuple(self) -> None:
345 node = extract_node("""
346 import collections
347 collections.namedtuple('{}'.format("a"), '')()
348 """)
349 next(node.infer())
350
351 def test_regression_inference_of_self_in_lambda(self) -> None:
352 code = """
353 class A:
354 @b(lambda self: __(self))
355 def d(self):
356 pass
357 """
358 node = extract_node(code)
359 inferred = next(node.infer())
360 assert isinstance(inferred, Instance)
361 assert inferred.qname() == ".A"
362
363 def test_inference_context_consideration(self) -> None:
364 """https://github.com/PyCQA/astroid/issues/1828"""
365 code = """
366 class Base:
367 def return_type(self):
368 return type(self)()
369 class A(Base):
370 def method(self):
371 return self.return_type()
372 class B(Base):
373 def method(self):
374 return self.return_type()
375 A().method() #@
376 B().method() #@
377 """
378 node1, node2 = extract_node(code)
379 inferred1 = next(node1.infer())
380 assert inferred1.qname() == ".A"
381 inferred2 = next(node2.infer())
382 assert inferred2.qname() == ".B"
383
384
385 class Whatever:
386 a = property(lambda x: x, lambda x: x) # type: ignore[misc]
387
388
389 def test_ancestor_looking_up_redefined_function() -> None:
390 code = """
391 class Foo:
392 def _format(self):
393 pass
394
395 def format(self):
396 self.format = self._format
397 self.format()
398 Foo
399 """
400 node = extract_node(code)
401 inferred = next(node.infer())
402 ancestor = next(inferred.ancestors())
403 _, found = ancestor.lookup("format")
404 assert len(found) == 1
405 assert isinstance(found[0], nodes.FunctionDef)
406
407
408 def test_crash_in_dunder_inference_prevented() -> None:
409 code = """
410 class MyClass():
411 def fu(self, objects):
412 delitem = dict.__delitem__.__get__(self, dict)
413 delitem #@
414 """
415 inferred = next(extract_node(code).infer())
416 assert inferred.qname() == "builtins.dict.__delitem__"
417
418
419 def test_regression_crash_classmethod() -> None:
420 """Regression test for a crash reported in
421 https://github.com/pylint-dev/pylint/issues/4982.
422 """
423 code = """
424 class Base:
425 @classmethod
426 def get_first_subclass(cls):
427 for subclass in cls.__subclasses__():
428 return subclass
429 return object
430
431
432 subclass = Base.get_first_subclass()
433
434
435 class Another(subclass):
436 pass
437 """
438 parse(code)
439
440
441 def test_max_inferred_for_complicated_class_hierarchy() -> None:
442 """Regression test for a crash reported in
443 https://github.com/pylint-dev/pylint/issues/5679.
444
445 The class hierarchy of 'sqlalchemy' is so intricate that it becomes uninferable with
446 the standard max_inferred of 100. We used to crash when this happened.
447 """
448 # Create module and get relevant nodes
449 module = resources.build_file(
450 str(resources.RESOURCE_PATH / "max_inferable_limit_for_classes" / "main.py")
451 )
452 init_attr_node = module.body[-1].body[0].body[0].value.func
453 init_object_node = module.body[-1].mro()[-1]["__init__"]
454 super_node = next(init_attr_node.expr.infer())
455
456 # Arbitrarily limit the max number of infered nodes per context
457 InferenceContext.max_inferred = -1
458 context = InferenceContext()
459
460 # Try to infer 'object.__init__' > because of limit is impossible
461 for inferred in bases._infer_stmts([init_object_node], context, frame=super):
462 assert inferred == Uninferable
463
464 # Reset inference limit
465 InferenceContext.max_inferred = 100
466 # Check that we don't crash on a previously uninferable node
467 assert super_node.getattr("__init__", context=context)[0] == Uninferable
468
469
470 @mock.patch(
471 "astroid.nodes.ImportFrom._infer",
472 side_effect=RecursionError,
473 )
474 def test_recursion_during_inference(mocked) -> None:
475 """Check that we don't crash if we hit the recursion limit during inference."""
476 node: nodes.Call = _extract_single_node("""
477 from module import something
478 something()
479 """)
480 with pytest.raises(InferenceError) as error:
481 next(node.infer())
482 assert error.value.message.startswith("RecursionError raised")
483
484
485 def test_regression_missing_callcontext() -> None:
486 node: nodes.Attribute = _extract_single_node(textwrap.dedent("""
487 import functools
488
489 class MockClass:
490 def _get_option(self, option):
491 return "mystr"
492
493 enabled = property(functools.partial(_get_option, option='myopt'))
494
495 MockClass().enabled
496 """))
497 assert node.inferred()[0].value == "mystr"
498
499
500 def test_regression_root_is_not_a_module() -> None:
501 """Regression test for #2672."""
502 node: nodes.ClassDef = _extract_single_node(textwrap.dedent("""
503 a=eval.__get__(1).__gt__
504
505 @a
506 class c: ...
507 """))
508 assert node.name == "c"
509
510
511 def test_regression_eval_get_of_arg() -> None:
512 """Regression test for #2743."""
513 node = _extract_single_node("eval.__get__(1)")
514 with pytest.raises(InferenceError):
515 next(node.infer())
516
517
518 def test_regression_no_crash_during_build() -> None:
519 node: nodes.Attribute = extract_node("__()")
520 assert node.args == []
521 assert node.as_string() == "__()"
522
523
524 def test_regression_no_crash_on_called_slice() -> None:
525 """Regression test for issue #2721."""
526 node: nodes.Attribute = extract_node(textwrap.dedent("""
527 s = slice(-2)
528 @s()
529 @six.add_metaclass()
530 class a: ...
531 """))
532 assert isinstance(node, nodes.ClassDef)
533 assert node.name == "a"
534
535
536 def test_regression_infer_dict_literal_comparison_uninferable() -> None:
537 """Regression test for issue #2522."""
538 node = extract_node("{{}}>0")
539 inferred = next(node.infer())
540 assert inferred.value == Uninferable
541
542
543 def test_regression_infer_namedtuple_invalid_fieldname_error() -> None:
544 """Regression test for issue #2519."""
545 code = """
546 from collections import namedtuple
547 namedtuple('a','}')
548 """
549 node = extract_node(code)
550 inferred = next(node.infer())
551 assert inferred.value == Uninferable
552
553
554 def test_regression_infer_namedtuple_nfkc_normalized_fieldname() -> None:
555 """Regression test for pylint-dev/pylint#8746.
556
557 ``namedtuple`` accepts any identifier as a field name, but the parser stores
558 identifiers in their NFKC-normalized form, so a field written as "\u00b5"
559 (MICRO SIGN) ends up under "\u03bc" (GREEK SMALL LETTER MU).
560 """
561 code = """
562 from collections import namedtuple
563 namedtuple('mu', ['\u00b5'])
564 """
565 node = extract_node(code)
566 inferred = next(node.infer())
567 assert isinstance(inferred, nodes.ClassDef)
568 assert "\u03bc" in inferred.locals
569
570
571 # On Python 3.15+ the parser emits a regular SyntaxError instead of a MemoryError for deeply nested
572 # parentheses, so the special-case test here is no longer needed.
573 @pytest.mark.skipif(PY315_PLUS, reason="No longer a MemoryError on Python 3.15+")
574 def test_regression_parse_deeply_nested_parentheses() -> None:
575 """Regression test for issue #2643."""
576 with pytest.raises(AstroidSyntaxError, match="Parsing Python code failed:") as ctx:
577 extract_node(
578 "A=((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((c,j=t"
579 )
580 expected = (
581 SyntaxError if platform.python_implementation() == "PyPy" else MemoryError
582 )
583 assert isinstance(ctx.value.error, expected)