Debian Codegraph @

tests/test_inference.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 inference capabilities."""
6
7 from __future__ import annotations
8
9 import sys
10 import textwrap
11 import unittest
12 from abc import ABCMeta
13 from collections.abc import Callable
14 from functools import partial
15 from pathlib import Path
16 from typing import Any
17 from unittest.mock import patch
18
19 import pytest
20
21 from astroid import (
22 Uninferable,
23 arguments,
24 manager,
25 nodes,
26 objects,
27 test_utils,
28 util,
29 )
30 from astroid import decorators as decoratorsmod
31 from astroid.arguments import CallSite
32 from astroid.bases import (
33 BoundMethod,
34 Generator,
35 Instance,
36 UnboundMethod,
37 UnionType,
38 _infer_stmts,
39 )
40 from astroid.builder import AstroidBuilder, _extract_single_node, extract_node, parse
41 from astroid.const import IS_PYPY, PY312_PLUS, PY314_PLUS, PY315_PLUS
42 from astroid.context import CallContext, InferenceContext
43 from astroid.exceptions import (
44 AstroidTypeError,
45 AttributeInferenceError,
46 InferenceError,
47 NoDefault,
48 NotFoundError,
49 )
50 from astroid.manager import AstroidManager
51 from astroid.objects import ExceptionInstance
52
53 from . import resources
54
55 try:
56 import six # type: ignore[import] # pylint: disable=unused-import
57
58 HAS_SIX = True
59 except ImportError:
60 HAS_SIX = False
61
62
63 def get_node_of_class(start_from: nodes.FunctionDef, klass: type) -> nodes.Attribute:
64 return next(start_from.nodes_of_class(klass))
65
66
67 builder = AstroidBuilder(AstroidManager())
68
69 DATA_DIR = Path(__file__).parent / "testdata" / "python3" / "data"
70
71
72 class InferenceUtilsTest(unittest.TestCase):
73 def test_path_wrapper(self) -> None:
74 def infer_default(self: Any, *args: InferenceContext) -> None:
75 raise InferenceError
76
77 infer_default = decoratorsmod.path_wrapper(infer_default)
78 infer_end = decoratorsmod.path_wrapper(nodes.Slice._infer)
79 with self.assertRaises(InferenceError):
80 next(infer_default(1))
81 self.assertEqual(next(infer_end(1)), 1)
82
83
84 def _assertInferElts(
85 node_type: ABCMeta,
86 self: InferenceTest,
87 node: Any,
88 elts: list[int] | list[str],
89 ) -> None:
90 inferred = next(node.infer())
91 self.assertIsInstance(inferred, node_type)
92 self.assertEqual(sorted(elt.value for elt in inferred.elts), elts)
93
94
95 def partialmethod(func, arg):
96 """similar to functools.partial but return a lambda instead of a class so returned value may be
97 turned into a method.
98 """
99 return lambda *args, **kwargs: func(arg, *args, **kwargs)
100
101
102 class InferenceTest(resources.SysPathSetup, unittest.TestCase):
103 # additional assertInfer* method for builtin types
104
105 def assertInferConst(self, node: nodes.Call, expected: str) -> None:
106 inferred = next(node.infer())
107 self.assertIsInstance(inferred, nodes.Const)
108 self.assertEqual(inferred.value, expected)
109
110 def assertInferDict(
111 self, node: nodes.Call | nodes.Dict | nodes.NodeNG, expected: Any
112 ) -> None:
113 inferred = next(node.infer())
114 self.assertIsInstance(inferred, nodes.Dict)
115
116 elts = {(key.value, value.value) for (key, value) in inferred.items}
117 self.assertEqual(sorted(elts), sorted(expected.items()))
118
119 assertInferTuple = partialmethod(_assertInferElts, nodes.Tuple)
120 assertInferList = partialmethod(_assertInferElts, nodes.List)
121 assertInferSet = partialmethod(_assertInferElts, nodes.Set)
122 assertInferFrozenSet = partialmethod(_assertInferElts, objects.FrozenSet)
123
124 CODE = """
125 class C(object):
126 "new style"
127 attr = 4
128
129 def meth1(self, arg1, optarg=0):
130 var = object()
131 print ("yo", arg1, optarg)
132 self.iattr = "hop"
133 return var
134
135 def meth2(self):
136 self.meth1(*self.meth3)
137
138 def meth3(self, d=attr):
139 b = self.attr
140 c = self.iattr
141 return b, c
142
143 ex = Exception("msg")
144 v = C().meth1(1)
145 m_unbound = C.meth1
146 m_bound = C().meth1
147 a, b, c = ex, 1, "bonjour"
148 [d, e, f] = [ex, 1.0, ("bonjour", v)]
149 g, h = f
150 i, (j, k) = "glup", f
151
152 a, b= b, a # Gasp !
153 """
154
155 ast = parse(CODE, __name__)
156
157 def test_arg_keyword_no_default_value(self):
158 node = extract_node("""
159 class Sensor:
160 def __init__(self, *, description): #@
161 self._id = description.key
162 """)
163 with self.assertRaises(NoDefault):
164 node.args.default_value("description")
165
166 node = extract_node("def apple(color, *args, name: str, **kwargs): ...")
167 with self.assertRaises(NoDefault):
168 node.args.default_value("name")
169
170 def test_infer_abstract_property_return_values(self) -> None:
171 module = parse("""
172 import abc
173
174 class A(object):
175 @abc.abstractproperty
176 def test(self):
177 return 42
178
179 a = A()
180 x = a.test
181 """)
182 inferred = next(module["x"].infer())
183 self.assertIsInstance(inferred, nodes.Const)
184 self.assertEqual(inferred.value, 42)
185
186 def test_module_inference(self) -> None:
187 inferred = self.ast.infer()
188 obj = next(inferred)
189 self.assertEqual(obj.name, __name__)
190 self.assertEqual(obj.root().name, __name__)
191 self.assertRaises(StopIteration, partial(next, inferred))
192
193 def test_class_inference(self) -> None:
194 inferred = self.ast["C"].infer()
195 obj = next(inferred)
196 self.assertEqual(obj.name, "C")
197 self.assertEqual(obj.root().name, __name__)
198 self.assertRaises(StopIteration, partial(next, inferred))
199
200 def test_function_inference(self) -> None:
201 inferred = self.ast["C"]["meth1"].infer()
202 obj = next(inferred)
203 self.assertEqual(obj.name, "meth1")
204 self.assertEqual(obj.root().name, __name__)
205 self.assertRaises(StopIteration, partial(next, inferred))
206
207 def test_builtin_name_inference(self) -> None:
208 inferred = self.ast["C"]["meth1"]["var"].infer()
209 var = next(inferred)
210 self.assertEqual(var.name, "object")
211 self.assertEqual(var.root().name, "builtins")
212 self.assertRaises(StopIteration, partial(next, inferred))
213
214 def test_tupleassign_name_inference(self) -> None:
215 inferred = self.ast["a"].infer()
216 exc = next(inferred)
217 self.assertIsInstance(exc, Instance)
218 self.assertEqual(exc.name, "Exception")
219 self.assertEqual(exc.root().name, "builtins")
220 self.assertRaises(StopIteration, partial(next, inferred))
221 inferred = self.ast["b"].infer()
222 const = next(inferred)
223 self.assertIsInstance(const, nodes.Const)
224 self.assertEqual(const.value, 1)
225 self.assertRaises(StopIteration, partial(next, inferred))
226 inferred = self.ast["c"].infer()
227 const = next(inferred)
228 self.assertIsInstance(const, nodes.Const)
229 self.assertEqual(const.value, "bonjour")
230 self.assertRaises(StopIteration, partial(next, inferred))
231
232 def test_listassign_name_inference(self) -> None:
233 inferred = self.ast["d"].infer()
234 exc = next(inferred)
235 self.assertIsInstance(exc, Instance)
236 self.assertEqual(exc.name, "Exception")
237 self.assertEqual(exc.root().name, "builtins")
238 self.assertRaises(StopIteration, partial(next, inferred))
239 inferred = self.ast["e"].infer()
240 const = next(inferred)
241 self.assertIsInstance(const, nodes.Const)
242 self.assertEqual(const.value, 1.0)
243 self.assertRaises(StopIteration, partial(next, inferred))
244 inferred = self.ast["f"].infer()
245 const = next(inferred)
246 self.assertIsInstance(const, nodes.Tuple)
247 self.assertRaises(StopIteration, partial(next, inferred))
248
249 def test_advanced_tupleassign_name_inference1(self) -> None:
250 inferred = self.ast["g"].infer()
251 const = next(inferred)
252 self.assertIsInstance(const, nodes.Const)
253 self.assertEqual(const.value, "bonjour")
254 self.assertRaises(StopIteration, partial(next, inferred))
255 inferred = self.ast["h"].infer()
256 var = next(inferred)
257 self.assertEqual(var.name, "object")
258 self.assertEqual(var.root().name, "builtins")
259 self.assertRaises(StopIteration, partial(next, inferred))
260
261 def test_advanced_tupleassign_name_inference2(self) -> None:
262 inferred = self.ast["i"].infer()
263 const = next(inferred)
264 self.assertIsInstance(const, nodes.Const)
265 self.assertEqual(const.value, "glup")
266 self.assertRaises(StopIteration, partial(next, inferred))
267 inferred = self.ast["j"].infer()
268 const = next(inferred)
269 self.assertIsInstance(const, nodes.Const)
270 self.assertEqual(const.value, "bonjour")
271 self.assertRaises(StopIteration, partial(next, inferred))
272 inferred = self.ast["k"].infer()
273 var = next(inferred)
274 self.assertEqual(var.name, "object")
275 self.assertEqual(var.root().name, "builtins")
276 self.assertRaises(StopIteration, partial(next, inferred))
277
278 def test_swap_assign_inference(self) -> None:
279 inferred = self.ast.locals["a"][1].infer()
280 const = next(inferred)
281 self.assertIsInstance(const, nodes.Const)
282 self.assertEqual(const.value, 1)
283 self.assertRaises(StopIteration, partial(next, inferred))
284 inferred = self.ast.locals["b"][1].infer()
285 exc = next(inferred)
286 self.assertIsInstance(exc, Instance)
287 self.assertEqual(exc.name, "Exception")
288 self.assertEqual(exc.root().name, "builtins")
289 self.assertRaises(StopIteration, partial(next, inferred))
290
291 def test_getattr_inference1(self) -> None:
292 inferred = self.ast["ex"].infer()
293 exc = next(inferred)
294 self.assertIsInstance(exc, Instance)
295 self.assertEqual(exc.name, "Exception")
296 self.assertEqual(exc.root().name, "builtins")
297 self.assertRaises(StopIteration, partial(next, inferred))
298
299 def test_getattr_inference2(self) -> None:
300 inferred = get_node_of_class(self.ast["C"]["meth2"], nodes.Attribute).infer()
301 meth1 = next(inferred)
302 self.assertEqual(meth1.name, "meth1")
303 self.assertEqual(meth1.root().name, __name__)
304 self.assertRaises(StopIteration, partial(next, inferred))
305
306 def test_getattr_inference3(self) -> None:
307 inferred = self.ast["C"]["meth3"]["b"].infer()
308 const = next(inferred)
309 self.assertIsInstance(const, nodes.Const)
310 self.assertEqual(const.value, 4)
311 self.assertRaises(StopIteration, partial(next, inferred))
312
313 def test_getattr_inference4(self) -> None:
314 inferred = self.ast["C"]["meth3"]["c"].infer()
315 const = next(inferred)
316 self.assertIsInstance(const, nodes.Const)
317 self.assertEqual(const.value, "hop")
318 self.assertRaises(StopIteration, partial(next, inferred))
319
320 def test_callfunc_inference(self) -> None:
321 inferred = self.ast["v"].infer()
322 meth1 = next(inferred)
323 self.assertIsInstance(meth1, Instance)
324 self.assertEqual(meth1.name, "object")
325 self.assertEqual(meth1.root().name, "builtins")
326 self.assertRaises(StopIteration, partial(next, inferred))
327
328 def test_unbound_method_inference(self) -> None:
329 inferred = self.ast["m_unbound"].infer()
330 meth1 = next(inferred)
331 self.assertIsInstance(meth1, UnboundMethod)
332 self.assertEqual(meth1.name, "meth1")
333 self.assertEqual(meth1.parent.frame().name, "C")
334 self.assertEqual(meth1.parent.frame().name, "C")
335 self.assertRaises(StopIteration, partial(next, inferred))
336
337 def test_bound_method_inference(self) -> None:
338 inferred = self.ast["m_bound"].infer()
339 meth1 = next(inferred)
340 self.assertIsInstance(meth1, BoundMethod)
341 self.assertEqual(meth1.name, "meth1")
342 self.assertEqual(meth1.parent.frame().name, "C")
343 self.assertEqual(meth1.parent.frame().name, "C")
344 self.assertRaises(StopIteration, partial(next, inferred))
345
346 def test_args_default_inference1(self) -> None:
347 optarg = test_utils.get_name_node(self.ast["C"]["meth1"], "optarg")
348 inferred = optarg.infer()
349 obj1 = next(inferred)
350 self.assertIsInstance(obj1, nodes.Const)
351 self.assertEqual(obj1.value, 0)
352 obj1 = next(inferred)
353 self.assertIs(obj1, util.Uninferable, obj1)
354 self.assertRaises(StopIteration, partial(next, inferred))
355
356 def test_args_default_inference2(self) -> None:
357 inferred = self.ast["C"]["meth3"].ilookup("d")
358 obj1 = next(inferred)
359 self.assertIsInstance(obj1, nodes.Const)
360 self.assertEqual(obj1.value, 4)
361 obj1 = next(inferred)
362 self.assertIs(obj1, util.Uninferable, obj1)
363 self.assertRaises(StopIteration, partial(next, inferred))
364
365 def test_inference_restrictions(self) -> None:
366 inferred = test_utils.get_name_node(self.ast["C"]["meth1"], "arg1").infer()
367 obj1 = next(inferred)
368 self.assertIs(obj1, util.Uninferable, obj1)
369 self.assertRaises(StopIteration, partial(next, inferred))
370
371 def test_ancestors_inference(self) -> None:
372 code = """
373 class A(object): #@
374 pass
375
376 class A(A): #@
377 pass
378 """
379 a1, a2 = extract_node(code, __name__)
380 a2_ancestors = list(a2.ancestors())
381 self.assertEqual(len(a2_ancestors), 2)
382 self.assertIs(a2_ancestors[0], a1)
383
384 def test_ancestors_inference2(self) -> None:
385 code = """
386 class A(object): #@
387 pass
388
389 class B(A): #@
390 pass
391
392 class A(B): #@
393 pass
394 """
395 a1, b, a2 = extract_node(code, __name__)
396 a2_ancestors = list(a2.ancestors())
397 self.assertEqual(len(a2_ancestors), 3)
398 self.assertIs(a2_ancestors[0], b)
399 self.assertIs(a2_ancestors[1], a1)
400
401 def test_f_arg_f(self) -> None:
402 code = """
403 def f(f=1):
404 return f
405
406 a = f()
407 """
408 ast = parse(code, __name__)
409 a = ast["a"]
410 a_inferred = a.inferred()
411 self.assertEqual(a_inferred[0].value, 1)
412 self.assertEqual(len(a_inferred), 1)
413
414 def test_exc_ancestors(self) -> None:
415 code = """
416 def f():
417 raise __(NotImplementedError)
418 """
419 error = extract_node(code, __name__)
420 nie = error.inferred()[0]
421 self.assertIsInstance(nie, nodes.ClassDef)
422 nie_ancestors = [c.name for c in nie.ancestors()]
423 expected = ["RuntimeError", "Exception", "BaseException", "object"]
424 self.assertEqual(nie_ancestors, expected)
425
426 def test_except_inference(self) -> None:
427 code = """
428 try:
429 print (hop)
430 except NameError as ex:
431 ex1 = ex
432 except Exception as ex:
433 ex2 = ex
434 raise
435 """
436 ast = parse(code, __name__)
437 ex1 = ast["ex1"]
438 ex1_infer = ex1.infer()
439 ex1 = next(ex1_infer)
440 self.assertIsInstance(ex1, Instance)
441 self.assertEqual(ex1.name, "NameError")
442 self.assertRaises(StopIteration, partial(next, ex1_infer))
443 ex2 = ast["ex2"]
444 ex2_infer = ex2.infer()
445 ex2 = next(ex2_infer)
446 self.assertIsInstance(ex2, Instance)
447 self.assertEqual(ex2.name, "Exception")
448 self.assertRaises(StopIteration, partial(next, ex2_infer))
449
450 def test_del1(self) -> None:
451 code = """
452 del undefined_attr
453 """
454 delete = extract_node(code, __name__)
455 self.assertRaises(InferenceError, next, delete.infer())
456
457 def test_del2(self) -> None:
458 code = """
459 a = 1
460 b = a
461 del a
462 c = a
463 a = 2
464 d = a
465 """
466 ast = parse(code, __name__)
467 n = ast["b"]
468 n_infer = n.infer()
469 inferred = next(n_infer)
470 self.assertIsInstance(inferred, nodes.Const)
471 self.assertEqual(inferred.value, 1)
472 self.assertRaises(StopIteration, partial(next, n_infer))
473 n = ast["c"]
474 n_infer = n.infer()
475 self.assertRaises(InferenceError, partial(next, n_infer))
476 n = ast["d"]
477 n_infer = n.infer()
478 inferred = next(n_infer)
479 self.assertIsInstance(inferred, nodes.Const)
480 self.assertEqual(inferred.value, 2)
481 self.assertRaises(StopIteration, partial(next, n_infer))
482
483 def test_builtin_types(self) -> None:
484 code = """
485 l = [1]
486 t = (2,)
487 d = {}
488 s = ''
489 s2 = '_'
490 """
491 ast = parse(code, __name__)
492 n = ast["l"]
493 inferred = next(n.infer())
494 self.assertIsInstance(inferred, nodes.List)
495 self.assertIsInstance(inferred, Instance)
496 self.assertEqual(inferred.getitem(nodes.Const(0)).value, 1)
497 self.assertIsInstance(inferred._proxied, nodes.ClassDef)
498 self.assertEqual(inferred._proxied.name, "list")
499 self.assertIn("append", inferred._proxied.locals)
500 n = ast["t"]
501 inferred = next(n.infer())
502 self.assertIsInstance(inferred, nodes.Tuple)
503 self.assertIsInstance(inferred, Instance)
504 self.assertEqual(inferred.getitem(nodes.Const(0)).value, 2)
505 self.assertIsInstance(inferred._proxied, nodes.ClassDef)
506 self.assertEqual(inferred._proxied.name, "tuple")
507 n = ast["d"]
508 inferred = next(n.infer())
509 self.assertIsInstance(inferred, nodes.Dict)
510 self.assertIsInstance(inferred, Instance)
511 self.assertIsInstance(inferred._proxied, nodes.ClassDef)
512 self.assertEqual(inferred._proxied.name, "dict")
513 self.assertIn("get", inferred._proxied.locals)
514 n = ast["s"]
515 inferred = next(n.infer())
516 self.assertIsInstance(inferred, nodes.Const)
517 self.assertIsInstance(inferred, Instance)
518 self.assertEqual(inferred.name, "str")
519 self.assertIn("lower", inferred._proxied.locals)
520 n = ast["s2"]
521 inferred = next(n.infer())
522 self.assertEqual(inferred.getitem(nodes.Const(0)).value, "_")
523
524 code = "s = {1}"
525 ast = parse(code, __name__)
526 n = ast["s"]
527 inferred = next(n.infer())
528 self.assertIsInstance(inferred, nodes.Set)
529 self.assertIsInstance(inferred, Instance)
530 self.assertEqual(inferred.name, "set")
531 self.assertIn("remove", inferred._proxied.locals)
532
533 @pytest.mark.xfail(reason="Descriptors are not properly inferred as callable")
534 def test_descriptor_are_callable(self):
535 code = """
536 class A:
537 statm = staticmethod(open)
538 clsm = classmethod('whatever')
539 """
540 ast = parse(code, __name__)
541 statm = next(ast["A"].igetattr("statm"))
542 self.assertTrue(statm.callable())
543 clsm = next(ast["A"].igetattr("clsm"))
544 self.assertFalse(clsm.callable())
545
546 def test_bt_ancestor_crash(self) -> None:
547 code = """
548 class Warning(Warning):
549 pass
550 """
551 ast = parse(code, __name__)
552 w = ast["Warning"]
553 ancestors = w.ancestors()
554 ancestor = next(ancestors)
555 self.assertEqual(ancestor.name, "Warning")
556 self.assertEqual(ancestor.root().name, "builtins")
557 ancestor = next(ancestors)
558 self.assertEqual(ancestor.name, "Exception")
559 self.assertEqual(ancestor.root().name, "builtins")
560 ancestor = next(ancestors)
561 self.assertEqual(ancestor.name, "BaseException")
562 self.assertEqual(ancestor.root().name, "builtins")
563 ancestor = next(ancestors)
564 self.assertEqual(ancestor.name, "object")
565 self.assertEqual(ancestor.root().name, "builtins")
566 self.assertRaises(StopIteration, partial(next, ancestors))
567
568 def test_method_argument(self) -> None:
569 code = '''
570 class ErudiEntitySchema:
571 """an entity has a type, a set of subject and or object relations"""
572 def __init__(self, e_type, **kwargs):
573 kwargs['e_type'] = e_type.capitalize().encode()
574
575 def meth(self, e_type, *args, **kwargs):
576 kwargs['e_type'] = e_type.capitalize().encode()
577 print(args)
578 '''
579 ast = parse(code, __name__)
580 arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["__init__"], "e_type")
581 self.assertEqual(
582 [n.__class__ for n in arg.infer()], [util.Uninferable.__class__]
583 )
584 arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["__init__"], "kwargs")
585 self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Dict])
586 arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["meth"], "e_type")
587 self.assertEqual(
588 [n.__class__ for n in arg.infer()], [util.Uninferable.__class__]
589 )
590 arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["meth"], "args")
591 self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Tuple])
592 arg = test_utils.get_name_node(ast["ErudiEntitySchema"]["meth"], "kwargs")
593 self.assertEqual([n.__class__ for n in arg.infer()], [nodes.Dict])
594
595 def test_tuple_then_list(self) -> None:
596 code = """
597 def test_view(rql, vid, tags=()):
598 tags = list(tags)
599 __(tags).append(vid)
600 """
601 name = extract_node(code, __name__)
602 it = name.infer()
603 tags = next(it)
604 self.assertIsInstance(tags, nodes.List)
605 self.assertEqual(tags.elts, [])
606 with self.assertRaises(StopIteration):
607 next(it)
608
609 def test_mulassign_inference(self) -> None:
610 code = '''
611 def first_word(line):
612 """Return the first word of a line"""
613
614 return line.split()[0]
615
616 def last_word(line):
617 """Return last word of a line"""
618
619 return line.split()[-1]
620
621 def process_line(word_pos):
622 """Silly function: returns (ok, callable) based on argument.
623
624 For test purpose only.
625 """
626
627 if word_pos > 0:
628 return (True, first_word)
629 elif word_pos < 0:
630 return (True, last_word)
631 else:
632 return (False, None)
633
634 if __name__ == '__main__':
635
636 line_number = 0
637 for a_line in file('test_callable.py'):
638 tupletest = process_line(line_number)
639 (ok, fct) = process_line(line_number)
640 if ok:
641 fct(a_line)
642 '''
643 ast = parse(code, __name__)
644 self.assertEqual(len(list(ast["process_line"].infer_call_result(None))), 3)
645 self.assertEqual(len(list(ast["tupletest"].infer())), 3)
646 values = [
647 "<FunctionDef.first_word",
648 "<FunctionDef.last_word",
649 "<Const.NoneType",
650 ]
651 self.assertTrue(
652 all(
653 repr(inferred).startswith(value)
654 for inferred, value in zip(ast["fct"].infer(), values)
655 )
656 )
657
658 def test_fstring_inference(self) -> None:
659 code = """
660 name = "John"
661 result = f"Hello {name}!"
662 """
663 ast = parse(code, __name__)
664 node = ast["result"]
665 inferred = node.inferred()
666 self.assertEqual(len(inferred), 1)
667 value_node = inferred[0]
668 self.assertIsInstance(value_node, nodes.Const)
669 self.assertEqual(value_node.value, "Hello John!")
670
671 def test_float_complex_ambiguity(self) -> None:
672 code = '''
673 def no_conjugate_member(magic_flag): #@
674 """should not raise E1101 on something.conjugate"""
675 if magic_flag:
676 something = 1.0
677 else:
678 something = 1.0j
679 if isinstance(something, float):
680 return something
681 return __(something).conjugate()
682 '''
683 func, retval = extract_node(code, __name__)
684 self.assertEqual([i.value for i in func.ilookup("something")], [1.0, 1.0j])
685 self.assertEqual([i.value for i in retval.infer()], [1.0, 1.0j])
686
687 def test_lookup_cond_branches(self) -> None:
688 code = '''
689 def no_conjugate_member(magic_flag):
690 """should not raise E1101 on something.conjugate"""
691 something = 1.0
692 if magic_flag:
693 something = 1.0j
694 return something.conjugate()
695 '''
696 ast = parse(code, __name__)
697 values = [
698 i.value for i in test_utils.get_name_node(ast, "something", -1).infer()
699 ]
700 self.assertEqual(values, [1.0, 1.0j])
701
702 def test_simple_subscript(self) -> None:
703 code = """
704 class A(object):
705 def __getitem__(self, index):
706 return index + 42
707 [1, 2, 3][0] #@
708 (1, 2, 3)[1] #@
709 (1, 2, 3)[-1] #@
710 [1, 2, 3][0] + (2, )[0] + (3, )[-1] #@
711 e = {'key': 'value'}
712 e['key'] #@
713 "first"[0] #@
714 list([1, 2, 3])[-1] #@
715 tuple((4, 5, 6))[2] #@
716 A()[0] #@
717 A()[-1] #@
718 """
719 ast_nodes = extract_node(code, __name__)
720 expected = [1, 2, 3, 6, "value", "f", 3, 6, 42, 41]
721 for node, expected_value in zip(ast_nodes, expected):
722 inferred = next(node.infer())
723 self.assertIsInstance(inferred, nodes.Const)
724 self.assertEqual(inferred.value, expected_value)
725
726 def test_invalid_subscripts(self) -> None:
727 ast_nodes = extract_node("""
728 class NoGetitem(object):
729 pass
730 class InvalidGetitem(object):
731 def __getitem__(self): pass
732 class InvalidGetitem2(object):
733 __getitem__ = 42
734 NoGetitem()[4] #@
735 InvalidGetitem()[5] #@
736 InvalidGetitem2()[10] #@
737 [1, 2, 3][None] #@
738 'lala'['bala'] #@
739 """)
740 for node in ast_nodes:
741 self.assertRaises(InferenceError, next, node.infer())
742
743 def test_bytes_subscript(self) -> None:
744 node = extract_node("""b'a'[0]""")
745 inferred = next(node.infer())
746 self.assertIsInstance(inferred, nodes.Const)
747 self.assertEqual(inferred.value, 97)
748
749 def test_subscript_multi_value(self) -> None:
750 code = """
751 def do_thing_with_subscript(magic_flag):
752 src = [3, 2, 1]
753 if magic_flag:
754 src = [1, 2, 3]
755 something = src[0]
756 return something
757 """
758 ast = parse(code, __name__)
759 values = [
760 i.value for i in test_utils.get_name_node(ast, "something", -1).infer()
761 ]
762 self.assertEqual(list(sorted(values)), [1, 3])
763
764 def test_subscript_multi_slice(self) -> None:
765 code = """
766 def zero_or_one(magic_flag):
767 if magic_flag:
768 return 1
769 return 0
770
771 def do_thing_with_subscript(magic_flag):
772 src = [3, 2, 1]
773 index = zero_or_one(magic_flag)
774 something = src[index]
775 return something
776 """
777 ast = parse(code, __name__)
778 values = [
779 i.value for i in test_utils.get_name_node(ast, "something", -1).infer()
780 ]
781 self.assertEqual(list(sorted(values)), [2, 3])
782
783 def test_simple_tuple(self) -> None:
784 module = parse("""
785 a = (1,)
786 b = (22,)
787 some = a + b #@
788 """)
789 ast = next(module["some"].infer())
790 self.assertIsInstance(ast, nodes.Tuple)
791 self.assertEqual(len(ast.elts), 2)
792 self.assertEqual(ast.elts[0].value, 1)
793 self.assertEqual(ast.elts[1].value, 22)
794
795 def test_simple_for(self) -> None:
796 code = """
797 for a in [1, 2, 3]:
798 print (a)
799 for b,c in [(1,2), (3,4)]:
800 print (b)
801 print (c)
802
803 print ([(d,e) for e,d in ([1,2], [3,4])])
804 """
805 ast = parse(code, __name__)
806 self.assertEqual(
807 [i.value for i in test_utils.get_name_node(ast, "a", -1).infer()], [1, 2, 3]
808 )
809 self.assertEqual(
810 [i.value for i in test_utils.get_name_node(ast, "b", -1).infer()], [1, 3]
811 )
812 self.assertEqual(
813 [i.value for i in test_utils.get_name_node(ast, "c", -1).infer()], [2, 4]
814 )
815 self.assertEqual(
816 [i.value for i in test_utils.get_name_node(ast, "d", -1).infer()], [2, 4]
817 )
818 self.assertEqual(
819 [i.value for i in test_utils.get_name_node(ast, "e", -1).infer()], [1, 3]
820 )
821
822 def test_simple_for_genexpr(self) -> None:
823 code = """
824 print ((d,e) for e,d in ([1,2], [3,4]))
825 """
826 ast = parse(code, __name__)
827 self.assertEqual(
828 [i.value for i in test_utils.get_name_node(ast, "d", -1).infer()], [2, 4]
829 )
830 self.assertEqual(
831 [i.value for i in test_utils.get_name_node(ast, "e", -1).infer()], [1, 3]
832 )
833
834 def test_for_dict(self) -> None:
835 code = """
836 for a, b in {1: 2, 3: 4}.items():
837 print(a)
838 print(b)
839
840 for c, (d, e) in {1: (2, 3), 4: (5, 6)}.items():
841 print(c)
842 print(d)
843 print(e)
844
845 print([(f, g, h) for f, (g, h) in {1: (2, 3), 4: (5, 6)}.items()])
846 """
847 ast = parse(code, __name__)
848 self.assertEqual(
849 [i.value for i in test_utils.get_name_node(ast, "a", -1).infer()], [1, 3]
850 )
851 self.assertEqual(
852 [i.value for i in test_utils.get_name_node(ast, "b", -1).infer()], [2, 4]
853 )
854 self.assertEqual(
855 [i.value for i in test_utils.get_name_node(ast, "c", -1).infer()], [1, 4]
856 )
857 self.assertEqual(
858 [i.value for i in test_utils.get_name_node(ast, "d", -1).infer()], [2, 5]
859 )
860 self.assertEqual(
861 [i.value for i in test_utils.get_name_node(ast, "e", -1).infer()], [3, 6]
862 )
863 self.assertEqual(
864 [i.value for i in test_utils.get_name_node(ast, "f", -1).infer()], [1, 4]
865 )
866 self.assertEqual(
867 [i.value for i in test_utils.get_name_node(ast, "g", -1).infer()], [2, 5]
868 )
869 self.assertEqual(
870 [i.value for i in test_utils.get_name_node(ast, "h", -1).infer()], [3, 6]
871 )
872
873 def test_builtin_help(self) -> None:
874 code = """
875 help()
876 """
877 # XXX failing since __builtin__.help assignment has
878 # been moved into a function...
879 node = extract_node(code, __name__)
880 inferred = list(node.func.infer())
881 self.assertEqual(len(inferred), 1, inferred)
882 self.assertIsInstance(inferred[0], Instance)
883 self.assertEqual(inferred[0].name, "_Helper")
884
885 def test_builtin_open(self) -> None:
886 code = """
887 open("toto.txt")
888 """
889 node = extract_node(code, __name__).func
890 inferred = list(node.infer())
891 self.assertEqual(len(inferred), 1)
892 self.assertIsInstance(inferred[0], nodes.FunctionDef)
893 self.assertEqual(inferred[0].name, "open")
894
895 def test_callfunc_context_func(self) -> None:
896 code = """
897 def mirror(arg=None):
898 return arg
899
900 un = mirror(1)
901 """
902 ast = parse(code, __name__)
903 inferred = list(ast.igetattr("un"))
904 self.assertEqual(len(inferred), 1)
905 self.assertIsInstance(inferred[0], nodes.Const)
906 self.assertEqual(inferred[0].value, 1)
907
908 def test_callfunc_context_lambda(self) -> None:
909 code = """
910 mirror = lambda x=None: x
911
912 un = mirror(1)
913 """
914 ast = parse(code, __name__)
915 inferred = list(ast.igetattr("mirror"))
916 self.assertEqual(len(inferred), 1)
917 self.assertIsInstance(inferred[0], nodes.Lambda)
918 inferred = list(ast.igetattr("un"))
919 self.assertEqual(len(inferred), 1)
920 self.assertIsInstance(inferred[0], nodes.Const)
921 self.assertEqual(inferred[0].value, 1)
922
923 def test_factory_method(self) -> None:
924 code = """
925 class Super(object):
926 @classmethod
927 def instance(cls):
928 return cls()
929
930 class Sub(Super):
931 def method(self):
932 print ('method called')
933
934 sub = Sub.instance()
935 """
936 ast = parse(code, __name__)
937 inferred = list(ast.igetattr("sub"))
938 self.assertEqual(len(inferred), 1)
939 self.assertIsInstance(inferred[0], Instance)
940 self.assertEqual(inferred[0]._proxied.name, "Sub")
941
942 def test_factory_methods_cls_call(self) -> None:
943 ast = extract_node(
944 """
945 class C:
946 @classmethod
947 def factory(cls):
948 return cls()
949
950 class D(C):
951 pass
952
953 C.factory() #@
954 D.factory() #@
955 """,
956 "module",
957 )
958 should_be_c = list(ast[0].infer())
959 should_be_d = list(ast[1].infer())
960 self.assertEqual(1, len(should_be_c))
961 self.assertEqual(1, len(should_be_d))
962 self.assertEqual("module.C", should_be_c[0].qname())
963 self.assertEqual("module.D", should_be_d[0].qname())
964
965 def test_factory_methods_object_new_call(self) -> None:
966 ast = extract_node(
967 """
968 class C:
969 @classmethod
970 def factory(cls):
971 return object.__new__(cls)
972
973 class D(C):
974 pass
975
976 C.factory() #@
977 D.factory() #@
978 """,
979 "module",
980 )
981 should_be_c = list(ast[0].infer())
982 should_be_d = list(ast[1].infer())
983 self.assertEqual(1, len(should_be_c))
984 self.assertEqual(1, len(should_be_d))
985 self.assertEqual("module.C", should_be_c[0].qname())
986 self.assertEqual("module.D", should_be_d[0].qname())
987
988 @pytest.mark.xfail(
989 reason="pathlib.Path cannot be inferred on Python 3.8",
990 )
991 def test_factory_methods_inside_binary_operation(self):
992 node = extract_node("""
993 from pathlib import Path
994 h = Path("/home")
995 u = h / "user"
996 u #@
997 """)
998 assert next(node.infer()).qname() == "pathlib.Path"
999
1000 def test_import_as(self) -> None:
1001 code = """
1002 import os.path as osp
1003 print (osp.dirname(__file__))
1004
1005 from os.path import exists as e
1006 assert e(__file__)
1007 """
1008 ast = parse(code, __name__)
1009 inferred = list(ast.igetattr("osp"))
1010 self.assertEqual(len(inferred), 1)
1011 self.assertIsInstance(inferred[0], nodes.Module)
1012 self.assertEqual(inferred[0].name, "os.path")
1013 inferred = list(ast.igetattr("e"))
1014 if PY312_PLUS and sys.platform.startswith("win"):
1015 # There are two os.path.exists exported, likely due to
1016 # https://github.com/python/cpython/pull/101324
1017 self.assertEqual(len(inferred), 2)
1018 else:
1019 self.assertEqual(len(inferred), 1)
1020 self.assertIsInstance(inferred[0], nodes.FunctionDef)
1021 self.assertEqual(inferred[0].name, "exists")
1022
1023 def test_do_import_module_performance(self) -> None:
1024 import_node = extract_node("import importlib")
1025 import_node.modname = ""
1026 import_node.do_import_module()
1027 # calling file_from_module_name() indicates we didn't hit the cache
1028 with unittest.mock.patch.object(
1029 manager.AstroidManager, "file_from_module_name", side_effect=AssertionError
1030 ):
1031 import_node.do_import_module()
1032
1033 def test_import_alias_shadowing_module(self) -> None:
1034 """An ``import x.y as x`` alias shadowing the head of its own dotted
1035 name must not poison the inference cache.
1036
1037 Regression test for pylint-dev/pylint#10193: inferring the alias
1038 name through ``_infer_stmts`` (which yields the real module ``x.y``)
1039 used to share a cache key with a direct ``Import._infer`` call
1040 (which is meant to resolve to the raw alias ``x``). The two
1041 distinct semantics were collapsed because the cache key omitted
1042 the differentiating kwarg, so the second call returned the cached
1043 module from the first regardless of which one ran first.
1044
1045 After hoisting the ``real_name`` translation into
1046 ``ImportNode._infer_name``, the two flows use distinct lookup
1047 names and therefore distinct cache keys.
1048 """
1049 import_node = extract_node("import os.path as os")
1050
1051 # _infer_stmts is the path used when resolving a Name reference. It
1052 # invokes ``_infer_name`` which now translates the alias before
1053 # ``_infer`` runs, so the result is the aliased module ``os.path``.
1054 translated_ctx = InferenceContext()
1055 translated_ctx.lookupname = "os"
1056 translated = list(_infer_stmts([import_node], translated_ctx))
1057 self.assertEqual(len(translated), 1)
1058 self.assertEqual(translated[0].name, "os.path")
1059
1060 # Direct ``Import._infer`` (the path pylint's
1061 # ``_infer_name_module`` uses) resolves the lookup name as-is,
1062 # yielding the raw stdlib ``os`` module. Pre-fix, this returned the
1063 # cached ``os.path`` from the previous call.
1064 raw_ctx = InferenceContext()
1065 raw_ctx.lookupname = "os"
1066 raw = list(import_node.infer(raw_ctx))
1067 self.assertEqual(len(raw), 1)
1068 self.assertEqual(raw[0].name, "os")
1069
1070 def _test_const_inferred(self, node: nodes.AssignName, value: float | str) -> None:
1071 inferred = list(node.infer())
1072 self.assertEqual(len(inferred), 1)
1073 self.assertIsInstance(inferred[0], nodes.Const)
1074 self.assertEqual(inferred[0].value, value)
1075
1076 def test_unary_not(self) -> None:
1077 for code in (
1078 "a = not (1,); b = not ()",
1079 "a = not {1:2}; b = not {}",
1080 "a = not [1, 2]; b = not []",
1081 "a = not {1, 2}; b = not set()",
1082 "a = not 1; b = not 0",
1083 'a = not "a"; b = not ""',
1084 'a = not b"a"; b = not b""',
1085 ):
1086 ast = builder.string_build(code, __name__, __file__)
1087 self._test_const_inferred(ast["a"], False)
1088 self._test_const_inferred(ast["b"], True)
1089
1090 def test_unary_op_numbers(self) -> None:
1091 ast_nodes = extract_node("""
1092 +1 #@
1093 -1 #@
1094 ~1 #@
1095 +2.0 #@
1096 -2.0 #@
1097 """)
1098 expected = [1, -1, -2, 2.0, -2.0]
1099 for node, expected_value in zip(ast_nodes, expected):
1100 inferred = next(node.infer())
1101 self.assertEqual(inferred.value, expected_value)
1102
1103 def test_matmul(self) -> None:
1104 node = extract_node("""
1105 class Array:
1106 def __matmul__(self, other):
1107 return 42
1108 Array() @ Array() #@
1109 """)
1110 inferred = next(node.infer())
1111 self.assertIsInstance(inferred, nodes.Const)
1112 self.assertEqual(inferred.value, 42)
1113
1114 def test_binary_op_int_add(self) -> None:
1115 ast = builder.string_build("a = 1 + 2", __name__, __file__)
1116 self._test_const_inferred(ast["a"], 3)
1117
1118 def test_binary_op_int_sub(self) -> None:
1119 ast = builder.string_build("a = 1 - 2", __name__, __file__)
1120 self._test_const_inferred(ast["a"], -1)
1121
1122 def test_binary_op_float_div(self) -> None:
1123 ast = builder.string_build("a = 1 / 2.", __name__, __file__)
1124 self._test_const_inferred(ast["a"], 1 / 2.0)
1125
1126 def test_binary_op_str_mul(self) -> None:
1127 ast = builder.string_build('a = "*" * 40', __name__, __file__)
1128 self._test_const_inferred(ast["a"], "*" * 40)
1129
1130 def test_binary_op_int_bitand(self) -> None:
1131 ast = builder.string_build("a = 23&20", __name__, __file__)
1132 self._test_const_inferred(ast["a"], 23 & 20)
1133
1134 def test_binary_op_int_bitor(self) -> None:
1135 ast = builder.string_build("a = 23|8", __name__, __file__)
1136 self._test_const_inferred(ast["a"], 23 | 8)
1137
1138 def test_binary_op_int_bitxor(self) -> None:
1139 ast = builder.string_build("a = 23^9", __name__, __file__)
1140 self._test_const_inferred(ast["a"], 23 ^ 9)
1141
1142 def test_binary_op_int_shiftright(self) -> None:
1143 ast = builder.string_build("a = 23 >>1", __name__, __file__)
1144 self._test_const_inferred(ast["a"], 23 >> 1)
1145
1146 def test_binary_op_int_shiftleft(self) -> None:
1147 ast = builder.string_build("a = 23 <<1", __name__, __file__)
1148 self._test_const_inferred(ast["a"], 23 << 1)
1149
1150 def test_binary_op_other_type(self) -> None:
1151 ast_nodes = extract_node("""
1152 class A:
1153 def __add__(self, other):
1154 return other + 42
1155 A() + 1 #@
1156 1 + A() #@
1157 """)
1158 assert isinstance(ast_nodes, list)
1159 first = next(ast_nodes[0].infer())
1160 self.assertIsInstance(first, nodes.Const)
1161 self.assertEqual(first.value, 43)
1162
1163 second = next(ast_nodes[1].infer())
1164 self.assertEqual(second, util.Uninferable)
1165
1166 def test_binary_op_other_type_using_reflected_operands(self) -> None:
1167 ast_nodes = extract_node("""
1168 class A(object):
1169 def __radd__(self, other):
1170 return other + 42
1171 A() + 1 #@
1172 1 + A() #@
1173 """)
1174 assert isinstance(ast_nodes, list)
1175 first = next(ast_nodes[0].infer())
1176 self.assertEqual(first, util.Uninferable)
1177
1178 second = next(ast_nodes[1].infer())
1179 self.assertIsInstance(second, nodes.Const)
1180 self.assertEqual(second.value, 43)
1181
1182 def test_binary_op_reflected_and_not_implemented_is_type_error(self) -> None:
1183 ast_node = extract_node("""
1184 class A(object):
1185 def __radd__(self, other): return NotImplemented
1186
1187 1 + A() #@
1188 """)
1189 first = next(ast_node.infer())
1190 self.assertEqual(first, util.Uninferable)
1191
1192 @pytest.mark.filterwarnings("error::DeprecationWarning")
1193 def test_binary_op_not_used_in_boolean_context(self) -> None:
1194 ast_node = extract_node("not NotImplemented")
1195 first = next(ast_node.infer())
1196 self.assertIsInstance(first, nodes.Const)
1197
1198 def test_binary_op_list_mul(self) -> None:
1199 for code in ("a = [[]] * 2", "a = 2 * [[]]"):
1200 ast = builder.string_build(code, __name__, __file__)
1201 inferred = list(ast["a"].infer())
1202 self.assertEqual(len(inferred), 1)
1203 self.assertIsInstance(inferred[0], nodes.List)
1204 self.assertEqual(len(inferred[0].elts), 2)
1205 self.assertIsInstance(inferred[0].elts[0], nodes.List)
1206 self.assertIsInstance(inferred[0].elts[1], nodes.List)
1207
1208 def test_binary_op_list_mul_none(self) -> None:
1209 """Test correct handling on list multiplied by None."""
1210 ast = builder.string_build('a = [1] * None\nb = [1] * "r"')
1211 inferred = ast["a"].inferred()
1212 self.assertEqual(len(inferred), 1)
1213 self.assertEqual(inferred[0], util.Uninferable)
1214 inferred = ast["b"].inferred()
1215 self.assertEqual(len(inferred), 1)
1216 self.assertEqual(inferred[0], util.Uninferable)
1217
1218 def test_binary_op_list_mul_int(self) -> None:
1219 """Test correct handling on list multiplied by int when there are more than one."""
1220 code = """
1221 from ctypes import c_int
1222 seq = [c_int()] * 4
1223 """
1224 ast = parse(code, __name__)
1225 inferred = ast["seq"].inferred()
1226 self.assertEqual(len(inferred), 1)
1227 listval = inferred[0]
1228 self.assertIsInstance(listval, nodes.List)
1229 self.assertEqual(len(listval.itered()), 4)
1230
1231 def test_binary_op_on_self(self) -> None:
1232 """Test correct handling of applying binary operator to self."""
1233 code = """
1234 import sys
1235 sys.path = ['foo'] + sys.path
1236 sys.path.insert(0, 'bar')
1237 path = sys.path
1238 """
1239 ast = parse(code, __name__)
1240 inferred = ast["path"].inferred()
1241 self.assertIsInstance(inferred[0], nodes.List)
1242
1243 def test_binary_op_tuple_add(self) -> None:
1244 ast = builder.string_build("a = (1,) + (2,)", __name__, __file__)
1245 inferred = list(ast["a"].infer())
1246 self.assertEqual(len(inferred), 1)
1247 self.assertIsInstance(inferred[0], nodes.Tuple)
1248 self.assertEqual(len(inferred[0].elts), 2)
1249 self.assertEqual(inferred[0].elts[0].value, 1)
1250 self.assertEqual(inferred[0].elts[1].value, 2)
1251
1252 def test_binary_op_custom_class(self) -> None:
1253 code = """
1254 class myarray:
1255 def __init__(self, array):
1256 self.array = array
1257 def __mul__(self, x):
1258 return myarray([2,4,6])
1259 def astype(self):
1260 return "ASTYPE"
1261
1262 def randint(maximum):
1263 if maximum is not None:
1264 return myarray([1,2,3]) * 2
1265 else:
1266 return int(5)
1267
1268 x = randint(1)
1269 """
1270 ast = parse(code, __name__)
1271 inferred = list(ast.igetattr("x"))
1272 self.assertEqual(len(inferred), 2)
1273 value = [str(v) for v in inferred]
1274 # The __name__ trick here makes it work when invoked directly
1275 # (__name__ == '__main__') and through pytest (__name__ ==
1276 # 'unittest_inference')
1277 self.assertEqual(
1278 value,
1279 [
1280 f"Instance of {__name__}.myarray",
1281 "Const.int(value=5,\n kind=None)",
1282 ],
1283 )
1284
1285 def test_binary_op_or_union_type(self) -> None:
1286 """Binary or union is only defined for Python 3.10+."""
1287 # pylint: disable = too-many-statements
1288 code = """
1289 class A: ...
1290
1291 int | 2 #@
1292 int | "Hello" #@
1293 int | ... #@
1294 int | A() #@
1295 int | None | 2 #@
1296 """
1297 ast_nodes = extract_node(code)
1298 for n in ast_nodes:
1299 assert n.inferred() == [util.Uninferable]
1300
1301 code = """
1302 from typing import List
1303
1304 class A: ...
1305 class B: ...
1306
1307 int | None #@
1308 int | str #@
1309 int | str | None #@
1310 A | B #@
1311 A | None #@
1312 List[int] | int #@
1313 tuple | int #@
1314 """
1315 ast_nodes = extract_node(code)
1316 i0 = ast_nodes[0].inferred()[0]
1317 assert isinstance(i0, UnionType)
1318 assert isinstance(i0.left, nodes.ClassDef)
1319 assert i0.left.name == "int"
1320 assert isinstance(i0.right, nodes.Const)
1321 assert i0.right.value is None
1322
1323 # Assert basic UnionType properties and methods
1324 assert i0.callable() is False
1325 assert i0.bool_value() is True
1326 assert i0.pytype() == "types.UnionType"
1327 assert i0.display_type() == "UnionType"
1328 if PY314_PLUS:
1329 assert str(i0) == "UnionType(Union)"
1330 assert repr(i0) == f"<UnionType(Union) l.0 at 0x{id(i0)}>"
1331 else:
1332 assert str(i0) == "UnionType(UnionType)"
1333 assert repr(i0) == f"<UnionType(UnionType) l.0 at 0x{id(i0)}>"
1334
1335 i1 = ast_nodes[1].inferred()[0]
1336 assert isinstance(i1, UnionType)
1337
1338 i2 = ast_nodes[2].inferred()[0]
1339 assert isinstance(i2, UnionType)
1340 assert isinstance(i2.left, UnionType)
1341 assert isinstance(i2.left.left, nodes.ClassDef)
1342 assert i2.left.left.name == "int"
1343 assert isinstance(i2.left.right, nodes.ClassDef)
1344 assert i2.left.right.name == "str"
1345 assert isinstance(i2.right, nodes.Const)
1346 assert i2.right.value is None
1347
1348 i3 = ast_nodes[3].inferred()[0]
1349 assert isinstance(i3, UnionType)
1350 assert isinstance(i3.left, nodes.ClassDef)
1351 assert i3.left.name == "A"
1352 assert isinstance(i3.right, nodes.ClassDef)
1353 assert i3.right.name == "B"
1354
1355 i4 = ast_nodes[4].inferred()[0]
1356 assert isinstance(i4, UnionType)
1357
1358 i5 = ast_nodes[5].inferred()[0]
1359 assert isinstance(i5, UnionType)
1360 assert isinstance(i5.left, nodes.ClassDef)
1361 assert i5.left.name == "List"
1362
1363 i6 = ast_nodes[6].inferred()[0]
1364 assert isinstance(i6, UnionType)
1365 assert isinstance(i6.left, nodes.ClassDef)
1366 assert i6.left.name == "tuple"
1367
1368 code = """
1369 from typing import List
1370
1371 Alias1 = List[int]
1372 Alias2 = str | int
1373
1374 Alias1 | int #@
1375 Alias2 | int #@
1376 Alias1 | Alias2 #@
1377 """
1378 ast_nodes = extract_node(code)
1379 i0 = ast_nodes[0].inferred()[0]
1380 assert isinstance(i0, UnionType)
1381 assert isinstance(i0.left, nodes.ClassDef)
1382 assert i0.left.name == "List"
1383
1384 i1 = ast_nodes[1].inferred()[0]
1385 assert isinstance(i1, UnionType)
1386 assert isinstance(i1.left, UnionType)
1387 assert isinstance(i1.left.left, nodes.ClassDef)
1388 assert i1.left.left.name == "str"
1389
1390 i2 = ast_nodes[2].inferred()[0]
1391 assert isinstance(i2, UnionType)
1392 assert isinstance(i2.left, nodes.ClassDef)
1393 assert i2.left.name == "List"
1394 assert isinstance(i2.right, UnionType)
1395
1396 def test_nonregr_lambda_arg(self) -> None:
1397 code = """
1398 def f(g = lambda: None):
1399 __(g()).x
1400 """
1401 callfuncnode = extract_node(code)
1402 inferred = list(callfuncnode.infer())
1403 self.assertEqual(len(inferred), 2, inferred)
1404 inferred.remove(util.Uninferable)
1405 self.assertIsInstance(inferred[0], nodes.Const)
1406 self.assertIsNone(inferred[0].value)
1407
1408 def test_nonregr_getitem_empty_tuple(self) -> None:
1409 code = """
1410 def f(x):
1411 a = ()[x]
1412 """
1413 ast = parse(code, __name__)
1414 inferred = list(ast["f"].ilookup("a"))
1415 self.assertEqual(len(inferred), 1)
1416 self.assertEqual(inferred[0], util.Uninferable)
1417
1418 def test_nonregr_instance_attrs(self) -> None:
1419 """Non regression for instance_attrs infinite loop : pylint / #4."""
1420
1421 code = """
1422 class Foo(object):
1423
1424 def set_42(self):
1425 self.attr = 42
1426
1427 class Bar(Foo):
1428
1429 def __init__(self):
1430 self.attr = 41
1431 """
1432 ast = parse(code, __name__)
1433 foo_class = ast["Foo"]
1434 bar_class = ast["Bar"]
1435 bar_self = ast["Bar"]["__init__"]["self"]
1436 assattr = bar_class.instance_attrs["attr"][0]
1437 self.assertEqual(len(foo_class.instance_attrs["attr"]), 1)
1438 self.assertEqual(len(bar_class.instance_attrs["attr"]), 1)
1439 self.assertEqual(bar_class.instance_attrs, {"attr": [assattr]})
1440 # call 'instance_attr' via 'Instance.getattr' to trigger the bug:
1441 instance = bar_self.inferred()[0]
1442 instance.getattr("attr")
1443 self.assertEqual(len(bar_class.instance_attrs["attr"]), 1)
1444 self.assertEqual(len(foo_class.instance_attrs["attr"]), 1)
1445 self.assertEqual(bar_class.instance_attrs, {"attr": [assattr]})
1446
1447 def test_nonregr_multi_referential_addition(self) -> None:
1448 """Regression test for https://github.com/pylint-dev/astroid/issues/483
1449 Make sure issue where referring to the same variable
1450 in the same inferred expression caused an uninferable result.
1451 """
1452 code = """
1453 b = 1
1454 a = b + b
1455 a #@
1456 """
1457 variable_a = extract_node(code)
1458 self.assertEqual(variable_a.inferred()[0].value, 2)
1459
1460 def test_nonregr_layed_dictunpack(self) -> None:
1461 """Regression test for https://github.com/pylint-dev/astroid/issues/483
1462 Make sure multiple dictunpack references are inferable.
1463 """
1464 code = """
1465 base = {'data': 0}
1466 new = {**base, 'data': 1}
1467 new3 = {**base, **new}
1468 new3 #@
1469 """
1470 ass = extract_node(code)
1471 self.assertIsInstance(ass.inferred()[0], nodes.Dict)
1472
1473 def test_nonregr_inference_modifying_col_offset(self) -> None:
1474 """Make sure inference doesn't improperly modify col_offset.
1475
1476 Regression test for https://github.com/pylint-dev/pylint/issues/1839
1477 """
1478
1479 code = """
1480 class F:
1481 def _(self):
1482 return type(self).f
1483 """
1484 mod = parse(code)
1485 cdef = mod.body[0]
1486 call = cdef.body[0].body[0].value.expr
1487 orig_offset = cdef.col_offset
1488 call.inferred()
1489 self.assertEqual(cdef.col_offset, orig_offset)
1490
1491 def test_no_runtime_error_in_repeat_inference(self) -> None:
1492 """Stop repeat inference attempt causing a RuntimeError in Python3.7.
1493
1494 See https://github.com/pylint-dev/pylint/issues/2317
1495 """
1496 code = """
1497
1498 class ContextMixin:
1499 def get_context_data(self, **kwargs):
1500 return kwargs
1501
1502 class DVM(ContextMixin):
1503 def get_context_data(self, **kwargs):
1504 ctx = super().get_context_data(**kwargs)
1505 return ctx
1506
1507
1508 class IFDVM(DVM):
1509 def get_context_data(self, **kwargs):
1510 ctx = super().get_context_data(**kwargs)
1511 ctx['bar'] = 'foo'
1512 ctx #@
1513 return ctx
1514 """
1515 node = extract_node(code)
1516 assert isinstance(node, nodes.NodeNG)
1517 results = node.inferred()
1518 assert len(results) == 2
1519 assert all(isinstance(result, nodes.Dict) for result in results)
1520
1521 def test_name_repeat_inference(self) -> None:
1522 node = extract_node("print")
1523 context = InferenceContext()
1524 _ = next(node.infer(context=context))
1525 with pytest.raises(InferenceError):
1526 next(node.infer(context=context))
1527
1528 def test_python25_no_relative_import(self) -> None:
1529 ast = resources.build_file("data/package/absimport.py")
1530 self.assertTrue(ast.absolute_import_activated())
1531 inferred = next(
1532 test_utils.get_name_node(ast, "import_package_subpackage_module").infer()
1533 )
1534 # failed to import since absolute_import is activated
1535 self.assertIs(inferred, util.Uninferable)
1536
1537 def test_nonregr_absolute_import(self) -> None:
1538 ast = resources.build_file("data/absimp/string.py", "data.absimp.string")
1539 self.assertTrue(ast.absolute_import_activated())
1540 inferred = next(test_utils.get_name_node(ast, "string").infer())
1541 self.assertIsInstance(inferred, nodes.Module)
1542 self.assertEqual(inferred.name, "string")
1543 self.assertIn("ascii_letters", inferred.locals)
1544
1545 def test_property(self) -> None:
1546 code = """
1547 from smtplib import SMTP
1548 class SendMailController(object):
1549
1550 @property
1551 def smtp(self):
1552 return SMTP(mailhost, port)
1553
1554 @property
1555 def me(self):
1556 return self
1557
1558 my_smtp = SendMailController().smtp
1559 my_me = SendMailController().me
1560 """
1561 decorators = {"builtins.property"}
1562 ast = parse(code, __name__)
1563 self.assertEqual(ast["SendMailController"]["smtp"].decoratornames(), decorators)
1564 propinferred = list(ast.body[2].value.infer())
1565 self.assertEqual(len(propinferred), 1)
1566 propinferred = propinferred[0]
1567 self.assertIsInstance(propinferred, Instance)
1568 self.assertEqual(propinferred.name, "SMTP")
1569 self.assertEqual(propinferred.root().name, "smtplib")
1570 self.assertEqual(ast["SendMailController"]["me"].decoratornames(), decorators)
1571 propinferred = list(ast.body[3].value.infer())
1572 self.assertEqual(len(propinferred), 1)
1573 propinferred = propinferred[0]
1574 self.assertIsInstance(propinferred, Instance)
1575 self.assertEqual(propinferred.name, "SendMailController")
1576 self.assertEqual(propinferred.root().name, __name__)
1577
1578 def test_im_func_unwrap(self) -> None:
1579 code = """
1580 class EnvBasedTC:
1581 def pactions(self):
1582 pass
1583 pactions = EnvBasedTC.pactions.im_func
1584 print (pactions)
1585
1586 class EnvBasedTC2:
1587 pactions = EnvBasedTC.pactions.im_func
1588 print (pactions)
1589 """
1590 ast = parse(code, __name__)
1591 pactions = test_utils.get_name_node(ast, "pactions")
1592 inferred = list(pactions.infer())
1593 self.assertEqual(len(inferred), 1)
1594 self.assertIsInstance(inferred[0], nodes.FunctionDef)
1595 pactions = test_utils.get_name_node(ast["EnvBasedTC2"], "pactions")
1596 inferred = list(pactions.infer())
1597 self.assertEqual(len(inferred), 1)
1598 self.assertIsInstance(inferred[0], nodes.FunctionDef)
1599
1600 def test_augassign(self) -> None:
1601 code = """
1602 a = 1
1603 a += 2
1604 print (a)
1605 """
1606 ast = parse(code, __name__)
1607 inferred = list(test_utils.get_name_node(ast, "a").infer())
1608
1609 self.assertEqual(len(inferred), 1)
1610 self.assertIsInstance(inferred[0], nodes.Const)
1611 self.assertEqual(inferred[0].value, 3)
1612
1613 def test_nonregr_func_arg(self) -> None:
1614 code = """
1615 def foo(self, bar):
1616 def baz():
1617 pass
1618 def qux():
1619 return baz
1620 spam = bar(None, qux)
1621 print (spam)
1622 """
1623 ast = parse(code, __name__)
1624 inferred = list(test_utils.get_name_node(ast["foo"], "spam").infer())
1625 self.assertEqual(len(inferred), 1)
1626 self.assertIs(inferred[0], util.Uninferable)
1627
1628 def test_nonregr_func_global(self) -> None:
1629 code = """
1630 active_application = None
1631
1632 def get_active_application():
1633 global active_application
1634 return active_application
1635
1636 class Application(object):
1637 def __init__(self):
1638 global active_application
1639 active_application = self
1640
1641 class DataManager(object):
1642 def __init__(self, app=None):
1643 self.app = get_active_application()
1644 def test(self):
1645 p = self.app
1646 print (p)
1647 """
1648 ast = parse(code, __name__)
1649 inferred = list(Instance(ast["DataManager"]).igetattr("app"))
1650 self.assertEqual(len(inferred), 2, inferred) # None / Instance(Application)
1651 inferred = list(
1652 test_utils.get_name_node(ast["DataManager"]["test"], "p").infer()
1653 )
1654 self.assertEqual(len(inferred), 2, inferred)
1655 for node in inferred:
1656 if isinstance(node, Instance) and node.name == "Application":
1657 break
1658 else:
1659 self.fail(f"expected to find an instance of Application in {inferred}")
1660
1661 def test_list_inference(self) -> None:
1662 code = """
1663 from unknown import Unknown
1664 A = []
1665 B = []
1666
1667 def test():
1668 xyz = [
1669 Unknown
1670 ] + A + B
1671 return xyz
1672
1673 Z = test()
1674 """
1675 ast = parse(code, __name__)
1676 inferred = next(ast["Z"].infer())
1677 self.assertIsInstance(inferred, nodes.List)
1678 self.assertEqual(len(inferred.elts), 1)
1679 self.assertIsInstance(inferred.elts[0], nodes.Unknown)
1680
1681 def test__new__(self) -> None:
1682 code = """
1683 class NewTest(object):
1684 "doc"
1685 def __new__(cls, arg):
1686 self = object.__new__(cls)
1687 self.arg = arg
1688 return self
1689
1690 n = NewTest()
1691 """
1692 ast = parse(code, __name__)
1693 self.assertRaises(InferenceError, list, ast["NewTest"].igetattr("arg"))
1694 n = next(ast["n"].infer())
1695 inferred = list(n.igetattr("arg"))
1696 self.assertEqual(len(inferred), 1, inferred)
1697
1698 def test__new__bound_methods(self) -> None:
1699 node = extract_node("""
1700 class cls(object): pass
1701 cls().__new__(cls) #@
1702 """)
1703 inferred = next(node.infer())
1704 self.assertIsInstance(inferred, Instance)
1705 self.assertEqual(inferred._proxied, node.root()["cls"])
1706
1707 def test_two_parents_from_same_module(self) -> None:
1708 code = """
1709 from data import nonregr
1710 class Xxx(nonregr.Aaa, nonregr.Ccc):
1711 "doc"
1712 """
1713 ast = parse(code, __name__)
1714 parents = list(ast["Xxx"].ancestors())
1715 self.assertEqual(len(parents), 3, parents) # Aaa, Ccc, object
1716
1717 def test_pluggable_inference(self) -> None:
1718 code = """
1719 from collections import namedtuple
1720 A = namedtuple('A', ['a', 'b'])
1721 B = namedtuple('B', 'a b')
1722 """
1723 ast = parse(code, __name__)
1724 aclass = ast["A"].inferred()[0]
1725 self.assertIsInstance(aclass, nodes.ClassDef)
1726 self.assertIn("a", aclass.instance_attrs)
1727 self.assertIn("b", aclass.instance_attrs)
1728 bclass = ast["B"].inferred()[0]
1729 self.assertIsInstance(bclass, nodes.ClassDef)
1730 self.assertIn("a", bclass.instance_attrs)
1731 self.assertIn("b", bclass.instance_attrs)
1732
1733 def test_infer_arguments(self) -> None:
1734 code = """
1735 class A(object):
1736 def first(self, arg1, arg2):
1737 return arg1
1738 @classmethod
1739 def method(cls, arg1, arg2):
1740 return arg2
1741 @classmethod
1742 def empty(cls):
1743 return 2
1744 @staticmethod
1745 def static(arg1, arg2):
1746 return arg1
1747 def empty_method(self):
1748 return []
1749 x = A().first(1, [])
1750 y = A.method(1, [])
1751 z = A.static(1, [])
1752 empty = A.empty()
1753 empty_list = A().empty_method()
1754 """
1755 ast = parse(code, __name__)
1756 int_node = ast["x"].inferred()[0]
1757 self.assertIsInstance(int_node, nodes.Const)
1758 self.assertEqual(int_node.value, 1)
1759 list_node = ast["y"].inferred()[0]
1760 self.assertIsInstance(list_node, nodes.List)
1761 int_node = ast["z"].inferred()[0]
1762 self.assertIsInstance(int_node, nodes.Const)
1763 self.assertEqual(int_node.value, 1)
1764 empty = ast["empty"].inferred()[0]
1765 self.assertIsInstance(empty, nodes.Const)
1766 self.assertEqual(empty.value, 2)
1767 empty_list = ast["empty_list"].inferred()[0]
1768 self.assertIsInstance(empty_list, nodes.List)
1769
1770 def test_infer_variable_arguments(self) -> None:
1771 code = """
1772 def test(*args, **kwargs):
1773 vararg = args
1774 kwarg = kwargs
1775 """
1776 ast = parse(code, __name__)
1777 func = ast["test"]
1778 vararg = func.body[0].value
1779 kwarg = func.body[1].value
1780
1781 kwarg_inferred = kwarg.inferred()[0]
1782 self.assertIsInstance(kwarg_inferred, nodes.Dict)
1783 self.assertIs(kwarg_inferred.parent, func.args)
1784
1785 vararg_inferred = vararg.inferred()[0]
1786 self.assertIsInstance(vararg_inferred, nodes.Tuple)
1787 self.assertIs(vararg_inferred.parent, func.args)
1788
1789 def test_infer_nested(self) -> None:
1790 code = """
1791 def nested():
1792 from threading import Thread
1793
1794 class NestedThread(Thread):
1795 def __init__(self):
1796 Thread.__init__(self)
1797 """
1798 # Test that inferring Thread.__init__ looks up in
1799 # the nested scope.
1800 ast = parse(code, __name__)
1801 callfunc = next(ast.nodes_of_class(nodes.Call))
1802 func = callfunc.func
1803 inferred = func.inferred()[0]
1804 self.assertIsInstance(inferred, UnboundMethod)
1805
1806 def test_instance_binary_operations(self) -> None:
1807 code = """
1808 class A(object):
1809 def __mul__(self, other):
1810 return 42
1811 a = A()
1812 b = A()
1813 sub = a - b
1814 mul = a * b
1815 """
1816 ast = parse(code, __name__)
1817 sub = ast["sub"].inferred()[0]
1818 mul = ast["mul"].inferred()[0]
1819 self.assertIs(sub, util.Uninferable)
1820 self.assertIsInstance(mul, nodes.Const)
1821 self.assertEqual(mul.value, 42)
1822
1823 def test_instance_binary_operations_parent(self) -> None:
1824 code = """
1825 class A(object):
1826 def __mul__(self, other):
1827 return 42
1828 class B(A):
1829 pass
1830 a = B()
1831 b = B()
1832 sub = a - b
1833 mul = a * b
1834 """
1835 ast = parse(code, __name__)
1836 sub = ast["sub"].inferred()[0]
1837 mul = ast["mul"].inferred()[0]
1838 self.assertIs(sub, util.Uninferable)
1839 self.assertIsInstance(mul, nodes.Const)
1840 self.assertEqual(mul.value, 42)
1841
1842 def test_instance_binary_operations_multiple_methods(self) -> None:
1843 code = """
1844 class A(object):
1845 def __mul__(self, other):
1846 return 42
1847 class B(A):
1848 def __mul__(self, other):
1849 return [42]
1850 a = B()
1851 b = B()
1852 sub = a - b
1853 mul = a * b
1854 """
1855 ast = parse(code, __name__)
1856 sub = ast["sub"].inferred()[0]
1857 mul = ast["mul"].inferred()[0]
1858 self.assertIs(sub, util.Uninferable)
1859 self.assertIsInstance(mul, nodes.List)
1860 self.assertIsInstance(mul.elts[0], nodes.Const)
1861 self.assertEqual(mul.elts[0].value, 42)
1862
1863 def test_infer_call_result_crash(self) -> None:
1864 code = """
1865 class A(object):
1866 def __mul__(self, other):
1867 return type.__new__()
1868
1869 a = A()
1870 b = A()
1871 c = a * b
1872 """
1873 ast = parse(code, __name__)
1874 node = ast["c"]
1875 assert isinstance(node, nodes.NodeNG)
1876 self.assertEqual(node.inferred(), [util.Uninferable])
1877
1878 def test_infer_empty_nodes(self) -> None:
1879 # Should not crash when trying to infer EmptyNodes.
1880 node = nodes.EmptyNode()
1881 assert isinstance(node, nodes.NodeNG)
1882 self.assertEqual(node.inferred(), [util.Uninferable])
1883
1884 def test_infinite_loop_for_decorators(self) -> None:
1885 # Issue https://bitbucket.org/logilab/astroid/issue/50
1886 # A decorator that returns itself leads to an infinite loop.
1887 code = """
1888 def decorator():
1889 def wrapper():
1890 return decorator()
1891 return wrapper
1892
1893 @decorator()
1894 def do_a_thing():
1895 pass
1896 """
1897 ast = parse(code, __name__)
1898 node = ast["do_a_thing"]
1899 self.assertEqual(node.type, "function")
1900
1901 @pytest.mark.skipif(
1902 IS_PYPY,
1903 reason="Persistent recursion error that we ignore and never fix",
1904 )
1905 def test_no_infinite_ancestor_loop(self) -> None:
1906 klass = extract_node("""
1907 import datetime
1908
1909 def method(self):
1910 datetime.datetime = something()
1911
1912 class something(datetime.datetime): #@
1913 pass
1914 """)
1915 ancestors = [base.name for base in klass.ancestors()]
1916 expected_subset = ["datetime", "date"]
1917 self.assertEqual(expected_subset, ancestors[:2])
1918
1919 def test_stop_iteration_leak(self) -> None:
1920 code = """
1921 class Test:
1922 def __init__(self):
1923 self.config = {0: self.config[0]}
1924 self.config[0].test() #@
1925 """
1926 ast = extract_node(code, __name__)
1927 expr = ast.func.expr
1928 self.assertIs(next(expr.infer()), util.Uninferable)
1929
1930 def test_tuple_builtin_inference(self) -> None:
1931 code = """
1932 var = (1, 2)
1933 tuple() #@
1934 tuple([1]) #@
1935 tuple({2}) #@
1936 tuple("abc") #@
1937 tuple({1: 2}) #@
1938 tuple(var) #@
1939 tuple(tuple([1])) #@
1940 tuple(frozenset((1, 2))) #@
1941
1942 tuple(None) #@
1943 tuple(1) #@
1944 tuple(1, 2) #@
1945 """
1946 ast = extract_node(code, __name__)
1947
1948 self.assertInferTuple(ast[0], [])
1949 self.assertInferTuple(ast[1], [1])
1950 self.assertInferTuple(ast[2], [2])
1951 self.assertInferTuple(ast[3], ["a", "b", "c"])
1952 self.assertInferTuple(ast[4], [1])
1953 self.assertInferTuple(ast[5], [1, 2])
1954 self.assertInferTuple(ast[6], [1])
1955 self.assertInferTuple(ast[7], [1, 2])
1956
1957 for node in ast[8:]:
1958 inferred = next(node.infer())
1959 self.assertIsInstance(inferred, Instance)
1960 self.assertEqual(inferred.qname(), "builtins.tuple")
1961
1962 def test_starred_in_tuple_literal(self) -> None:
1963 code = """
1964 var = (1, 2, 3)
1965 bar = (5, 6, 7)
1966 foo = [999, 1000, 1001]
1967 (0, *var) #@
1968 (0, *var, 4) #@
1969 (0, *var, 4, *bar) #@
1970 (0, *var, 4, *(*bar, 8)) #@
1971 (0, *var, 4, *(*bar, *foo)) #@
1972 """
1973 ast = extract_node(code, __name__)
1974 self.assertInferTuple(ast[0], [0, 1, 2, 3])
1975 self.assertInferTuple(ast[1], [0, 1, 2, 3, 4])
1976 self.assertInferTuple(ast[2], [0, 1, 2, 3, 4, 5, 6, 7])
1977 self.assertInferTuple(ast[3], [0, 1, 2, 3, 4, 5, 6, 7, 8])
1978 self.assertInferTuple(ast[4], [0, 1, 2, 3, 4, 5, 6, 7, 999, 1000, 1001])
1979
1980 def test_starred_in_list_literal(self) -> None:
1981 code = """
1982 var = (1, 2, 3)
1983 bar = (5, 6, 7)
1984 foo = [999, 1000, 1001]
1985 [0, *var] #@
1986 [0, *var, 4] #@
1987 [0, *var, 4, *bar] #@
1988 [0, *var, 4, *[*bar, 8]] #@
1989 [0, *var, 4, *[*bar, *foo]] #@
1990 """
1991 ast = extract_node(code, __name__)
1992 self.assertInferList(ast[0], [0, 1, 2, 3])
1993 self.assertInferList(ast[1], [0, 1, 2, 3, 4])
1994 self.assertInferList(ast[2], [0, 1, 2, 3, 4, 5, 6, 7])
1995 self.assertInferList(ast[3], [0, 1, 2, 3, 4, 5, 6, 7, 8])
1996 self.assertInferList(ast[4], [0, 1, 2, 3, 4, 5, 6, 7, 999, 1000, 1001])
1997
1998 def test_starred_in_set_literal(self) -> None:
1999 code = """
2000 var = (1, 2, 3)
2001 bar = (5, 6, 7)
2002 foo = [999, 1000, 1001]
2003 {0, *var} #@
2004 {0, *var, 4} #@
2005 {0, *var, 4, *bar} #@
2006 {0, *var, 4, *{*bar, 8}} #@
2007 {0, *var, 4, *{*bar, *foo}} #@
2008 """
2009 ast = extract_node(code, __name__)
2010 self.assertInferSet(ast[0], [0, 1, 2, 3])
2011 self.assertInferSet(ast[1], [0, 1, 2, 3, 4])
2012 self.assertInferSet(ast[2], [0, 1, 2, 3, 4, 5, 6, 7])
2013 self.assertInferSet(ast[3], [0, 1, 2, 3, 4, 5, 6, 7, 8])
2014 self.assertInferSet(ast[4], [0, 1, 2, 3, 4, 5, 6, 7, 999, 1000, 1001])
2015
2016 def test_starred_in_literals_inference_issues(self) -> None:
2017 code = """
2018 {0, *var} #@
2019 {0, *var, 4} #@
2020 {0, *var, 4, *bar} #@
2021 {0, *var, 4, *{*bar, 8}} #@
2022 {0, *var, 4, *{*bar, *foo}} #@
2023 """
2024 ast = extract_node(code, __name__)
2025 for node in ast:
2026 with self.assertRaises(InferenceError):
2027 next(node.infer())
2028
2029 def test_starred_in_mapping_literal(self) -> None:
2030 code = """
2031 var = {1: 'b', 2: 'c'}
2032 bar = {4: 'e', 5: 'f'}
2033 {0: 'a', **var} #@
2034 {0: 'a', **var, 3: 'd'} #@
2035 {0: 'a', **var, 3: 'd', **{**bar, 6: 'g'}} #@
2036 """
2037 ast = extract_node(code, __name__)
2038 self.assertInferDict(ast[0], {0: "a", 1: "b", 2: "c"})
2039 self.assertInferDict(ast[1], {0: "a", 1: "b", 2: "c", 3: "d"})
2040 self.assertInferDict(
2041 ast[2], {0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g"}
2042 )
2043
2044 def test_starred_in_mapping_literal_no_inference_possible(self) -> None:
2045 node = extract_node("""
2046 from unknown import unknown
2047
2048 def test(a):
2049 return a + 1
2050
2051 def func():
2052 a = {unknown: 'a'}
2053 return {0: 1, **a}
2054
2055 test(**func())
2056 """)
2057 self.assertEqual(next(node.infer()), util.Uninferable)
2058
2059 def test_starred_in_mapping_inference_issues(self) -> None:
2060 code = """
2061 {0: 'a', **var} #@
2062 {0: 'a', **var, 3: 'd'} #@
2063 {0: 'a', **var, 3: 'd', **{**bar, 6: 'g'}} #@
2064 """
2065 ast = extract_node(code, __name__)
2066 for node in ast:
2067 with self.assertRaises(InferenceError):
2068 next(node.infer())
2069
2070 def test_starred_in_mapping_literal_non_const_keys_values(self) -> None:
2071 code = """
2072 a, b, c, d, e, f, g, h, i, j = "ABCDEFGHIJ"
2073 var = {c: d, e: f}
2074 bar = {i: j}
2075 {a: b, **var} #@
2076 {a: b, **var, **{g: h, **bar}} #@
2077 """
2078 ast = extract_node(code, __name__)
2079 self.assertInferDict(ast[0], {"A": "B", "C": "D", "E": "F"})
2080 self.assertInferDict(ast[1], {"A": "B", "C": "D", "E": "F", "G": "H", "I": "J"})
2081
2082 def test_frozenset_builtin_inference(self) -> None:
2083 code = """
2084 var = (1, 2)
2085 frozenset() #@
2086 frozenset([1, 2, 1]) #@
2087 frozenset({2, 3, 1}) #@
2088 frozenset("abcab") #@
2089 frozenset({1: 2}) #@
2090 frozenset(var) #@
2091 frozenset(tuple([1])) #@
2092
2093 frozenset(set(tuple([4, 5, set([2])]))) #@
2094 frozenset(None) #@
2095 frozenset(1) #@
2096 frozenset(1, 2) #@
2097 """
2098 ast = extract_node(code, __name__)
2099
2100 self.assertInferFrozenSet(ast[0], [])
2101 self.assertInferFrozenSet(ast[1], [1, 2])
2102 self.assertInferFrozenSet(ast[2], [1, 2, 3])
2103 self.assertInferFrozenSet(ast[3], ["a", "b", "c"])
2104 self.assertInferFrozenSet(ast[4], [1])
2105 self.assertInferFrozenSet(ast[5], [1, 2])
2106 self.assertInferFrozenSet(ast[6], [1])
2107
2108 for node in ast[7:]:
2109 inferred = next(node.infer())
2110 self.assertIsInstance(inferred, Instance)
2111 self.assertEqual(inferred.qname(), "builtins.frozenset")
2112
2113 @pytest.mark.skipif(
2114 not PY315_PLUS, reason="frozendict builtin added in 3.15 (PEP 814)"
2115 )
2116 def test_frozendict_builtin_inference(self) -> None:
2117 node = extract_node("frozendict(x=1, y=2)")
2118 inferred = next(node.infer())
2119 self.assertIsInstance(inferred, Instance)
2120 self.assertEqual(inferred.qname(), "builtins.frozendict")
2121
2122 @pytest.mark.skipif(
2123 not PY315_PLUS, reason="sentinel builtin added in 3.15 (PEP 661)"
2124 )
2125 def test_sentinel_builtin_inference(self) -> None:
2126 node = extract_node("sentinel('MISSING')")
2127 inferred = next(node.infer())
2128 self.assertIsInstance(inferred, Instance)
2129 self.assertEqual(inferred.qname(), "builtins.sentinel")
2130
2131 def test_set_builtin_inference(self) -> None:
2132 code = """
2133 var = (1, 2)
2134 set() #@
2135 set([1, 2, 1]) #@
2136 set({2, 3, 1}) #@
2137 set("abcab") #@
2138 set({1: 2}) #@
2139 set(var) #@
2140 set(tuple([1])) #@
2141
2142 set(set(tuple([4, 5, set([2])]))) #@
2143 set(None) #@
2144 set(1) #@
2145 set(1, 2) #@
2146 """
2147 ast = extract_node(code, __name__)
2148
2149 self.assertInferSet(ast[0], [])
2150 self.assertInferSet(ast[1], [1, 2])
2151 self.assertInferSet(ast[2], [1, 2, 3])
2152 self.assertInferSet(ast[3], ["a", "b", "c"])
2153 self.assertInferSet(ast[4], [1])
2154 self.assertInferSet(ast[5], [1, 2])
2155 self.assertInferSet(ast[6], [1])
2156
2157 for node in ast[7:]:
2158 inferred = next(node.infer())
2159 self.assertIsInstance(inferred, Instance)
2160 self.assertEqual(inferred.qname(), "builtins.set")
2161
2162 def test_list_builtin_inference(self) -> None:
2163 code = """
2164 var = (1, 2)
2165 list() #@
2166 list([1, 2, 1]) #@
2167 list({2, 3, 1}) #@
2168 list("abcab") #@
2169 list({1: 2}) #@
2170 list(var) #@
2171 list(tuple([1])) #@
2172
2173 list(list(tuple([4, 5, list([2])]))) #@
2174 list(None) #@
2175 list(1) #@
2176 list(1, 2) #@
2177 """
2178 ast = extract_node(code, __name__)
2179 self.assertInferList(ast[0], [])
2180 self.assertInferList(ast[1], [1, 1, 2])
2181 self.assertInferList(ast[2], [1, 2, 3])
2182 self.assertInferList(ast[3], ["a", "a", "b", "b", "c"])
2183 self.assertInferList(ast[4], [1])
2184 self.assertInferList(ast[5], [1, 2])
2185 self.assertInferList(ast[6], [1])
2186
2187 for node in ast[7:]:
2188 inferred = next(node.infer())
2189 self.assertIsInstance(inferred, Instance)
2190 self.assertEqual(inferred.qname(), "builtins.list")
2191
2192 def test_conversion_of_dict_methods(self) -> None:
2193 ast_nodes = extract_node("""
2194 list({1:2, 2:3}.values()) #@
2195 list({1:2, 2:3}.keys()) #@
2196 tuple({1:2, 2:3}.values()) #@
2197 tuple({1:2, 3:4}.keys()) #@
2198 set({1:2, 2:4}.keys()) #@
2199 """)
2200 assert isinstance(ast_nodes, list)
2201 self.assertInferList(ast_nodes[0], [2, 3])
2202 self.assertInferList(ast_nodes[1], [1, 2])
2203 self.assertInferTuple(ast_nodes[2], [2, 3])
2204 self.assertInferTuple(ast_nodes[3], [1, 3])
2205 self.assertInferSet(ast_nodes[4], [1, 2])
2206
2207 def test_builtin_inference_py3k(self) -> None:
2208 code = """
2209 list(b"abc") #@
2210 tuple(b"abc") #@
2211 set(b"abc") #@
2212 """
2213 ast = extract_node(code, __name__)
2214 self.assertInferList(ast[0], [97, 98, 99])
2215 self.assertInferTuple(ast[1], [97, 98, 99])
2216 self.assertInferSet(ast[2], [97, 98, 99])
2217
2218 def test_dict_inference(self) -> None:
2219 code = """
2220 dict() #@
2221 dict(a=1, b=2, c=3) #@
2222 dict([(1, 2), (2, 3)]) #@
2223 dict([[1, 2], [2, 3]]) #@
2224 dict([(1, 2), [2, 3]]) #@
2225 dict([('a', 2)], b=2, c=3) #@
2226 dict({1: 2}) #@
2227 dict({'c': 2}, a=4, b=5) #@
2228 def func():
2229 return dict(a=1, b=2)
2230 func() #@
2231 var = {'x': 2, 'y': 3}
2232 dict(var, a=1, b=2) #@
2233
2234 dict([1, 2, 3]) #@
2235 dict([(1, 2), (1, 2, 3)]) #@
2236 dict({1: 2}, {1: 2}) #@
2237 dict({1: 2}, (1, 2)) #@
2238 dict({1: 2}, (1, 2), a=4) #@
2239 dict([(1, 2), ([4, 5], 2)]) #@
2240 dict([None, None]) #@
2241
2242 def using_unknown_kwargs(**kwargs):
2243 return dict(**kwargs)
2244 using_unknown_kwargs(a=1, b=2) #@
2245 """
2246 ast = extract_node(code, __name__)
2247 self.assertInferDict(ast[0], {})
2248 self.assertInferDict(ast[1], {"a": 1, "b": 2, "c": 3})
2249 for i in range(2, 5):
2250 self.assertInferDict(ast[i], {1: 2, 2: 3})
2251 self.assertInferDict(ast[5], {"a": 2, "b": 2, "c": 3})
2252 self.assertInferDict(ast[6], {1: 2})
2253 self.assertInferDict(ast[7], {"c": 2, "a": 4, "b": 5})
2254 self.assertInferDict(ast[8], {"a": 1, "b": 2})
2255 self.assertInferDict(ast[9], {"x": 2, "y": 3, "a": 1, "b": 2})
2256
2257 for node in ast[10:]:
2258 inferred = next(node.infer())
2259 self.assertIsInstance(inferred, Instance)
2260 self.assertEqual(inferred.qname(), "builtins.dict")
2261
2262 def test_dict_inference_kwargs(self) -> None:
2263 ast_node = extract_node("""dict(a=1, b=2, **{'c': 3})""")
2264 self.assertInferDict(ast_node, {"a": 1, "b": 2, "c": 3})
2265
2266 def test_dict_inference_for_multiple_starred(self) -> None:
2267 pairs = [
2268 ('dict(a=1, **{"b": 2}, **{"c":3})', {"a": 1, "b": 2, "c": 3}),
2269 ('dict(a=1, **{"b": 2}, d=4, **{"c":3})', {"a": 1, "b": 2, "c": 3, "d": 4}),
2270 ('dict({"a":1}, b=2, **{"c":3})', {"a": 1, "b": 2, "c": 3}),
2271 ]
2272 for code, expected_value in pairs:
2273 node = extract_node(code)
2274 self.assertInferDict(node, expected_value)
2275
2276 def test_dict_inference_unpack_repeated_key(self) -> None:
2277 """Make sure astroid does not infer repeated keys in a dictionary.
2278
2279 Regression test for https://github.com/pylint-dev/pylint/issues/1843
2280 """
2281 code = """
2282 base = {'data': 0}
2283 new = {**base, 'data': 1} #@
2284 new2 = {'data': 1, **base} #@ # Make sure overwrite works
2285 a = 'd' + 'ata'
2286 b3 = {**base, a: 3} #@ Make sure keys are properly inferred
2287 b4 = {a: 3, **base} #@
2288 """
2289 ast = extract_node(code)
2290 final_values = ("{'data': 1}", "{'data': 0}", "{'data': 3}", "{'data': 0}")
2291 for node, final_value in zip(ast, final_values):
2292 assert node.targets[0].inferred()[0].as_string() == final_value
2293
2294 def test_dict_invalid_args(self) -> None:
2295 invalid_values = ["dict(*1)", "dict(**lala)", "dict(**[])"]
2296 for invalid in invalid_values:
2297 ast_node = extract_node(invalid)
2298 inferred = next(ast_node.infer())
2299 self.assertIsInstance(inferred, Instance)
2300 self.assertEqual(inferred.qname(), "builtins.dict")
2301
2302 def test_copy_method_inference(self) -> None:
2303 code = """
2304 a_dict = {"b": 1, "c": 2}
2305 b_dict = a_dict.copy()
2306 b_dict #@
2307
2308 a_list = [1, 2, 3]
2309 b_list = a_list.copy()
2310 b_list #@
2311
2312 a_set = set([1, 2, 3])
2313 b_set = a_set.copy()
2314 b_set #@
2315
2316 a_frozenset = frozenset([1, 2, 3])
2317 b_frozenset = a_frozenset.copy()
2318 b_frozenset #@
2319
2320 a_unknown = unknown()
2321 b_unknown = a_unknown.copy()
2322 b_unknown #@
2323 """
2324 ast = extract_node(code, __name__)
2325 self.assertInferDict(ast[0], {"b": 1, "c": 2})
2326 self.assertInferList(ast[1], [1, 2, 3])
2327 self.assertInferSet(ast[2], [1, 2, 3])
2328 self.assertInferFrozenSet(ast[3], [1, 2, 3])
2329
2330 inferred_unknown = next(ast[4].infer())
2331 assert inferred_unknown == util.Uninferable
2332
2333 def test_str_methods(self) -> None:
2334 code = """
2335 ' '.decode() #@
2336 ' '.join('abcd') #@
2337 ' '.replace('a', 'b') #@
2338 ' '.capitalize() #@
2339 ' '.title() #@
2340 ' '.lower() #@
2341 ' '.upper() #@
2342 ' '.swapcase() #@
2343 ' '.strip() #@
2344 ' '.rstrip() #@
2345 ' '.lstrip() #@
2346 ' '.rjust() #@
2347 ' '.ljust() #@
2348 ' '.center() #@
2349
2350 ' '.index() #@
2351 ' '.find() #@
2352 ' '.count() #@
2353
2354 ' '.format('a') #@
2355 """
2356 ast = extract_node(code, __name__)
2357 self.assertInferConst(ast[0], "")
2358 for i in range(1, 14):
2359 self.assertInferConst(ast[i], "")
2360 for i in range(14, 17):
2361 self.assertInferConst(ast[i], 0)
2362 self.assertInferConst(ast[17], " ")
2363
2364 def test_unicode_methods(self) -> None:
2365 code = """
2366 u' '.decode() #@
2367 u' '.join('abcd') #@
2368 u' '.replace('a', 'b') #@
2369 u' '.capitalize() #@
2370 u' '.title() #@
2371 u' '.lower() #@
2372 u' '.upper() #@
2373 u' '.swapcase() #@
2374 u' '.strip() #@
2375 u' '.rstrip() #@
2376 u' '.lstrip() #@
2377 u' '.rjust() #@
2378 u' '.ljust() #@
2379 u' '.center() #@
2380
2381 u' '.index() #@
2382 u' '.find() #@
2383 u' '.count() #@
2384
2385 u' '.format('a') #@
2386 """
2387 ast = extract_node(code, __name__)
2388 self.assertInferConst(ast[0], "")
2389 for i in range(1, 14):
2390 self.assertInferConst(ast[i], "")
2391 for i in range(14, 17):
2392 self.assertInferConst(ast[i], 0)
2393 self.assertInferConst(ast[17], " ")
2394
2395 def test_scope_lookup_same_attributes(self) -> None:
2396 code = """
2397 import collections
2398 class Second(collections.Counter):
2399 def collections(self):
2400 return "second"
2401
2402 """
2403 ast = parse(code, __name__)
2404 bases = ast["Second"].bases[0]
2405 inferred = next(bases.infer())
2406 self.assertTrue(inferred)
2407 self.assertIsInstance(inferred, nodes.ClassDef)
2408 self.assertEqual(inferred.qname(), "collections.Counter")
2409
2410 def test_inferring_with_statement_failures(self) -> None:
2411 module = parse("""
2412 class NoEnter(object):
2413 pass
2414 class NoMethod(object):
2415 __enter__ = None
2416 class NoElts(object):
2417 def __enter__(self):
2418 return 42
2419
2420 with NoEnter() as no_enter:
2421 pass
2422 with NoMethod() as no_method:
2423 pass
2424 with NoElts() as (no_elts, no_elts1):
2425 pass
2426 """)
2427 self.assertRaises(InferenceError, next, module["no_enter"].infer())
2428 self.assertRaises(InferenceError, next, module["no_method"].infer())
2429 self.assertRaises(InferenceError, next, module["no_elts"].infer())
2430
2431 def test_inferring_with_statement(self) -> None:
2432 module = parse("""
2433 class SelfContext(object):
2434 def __enter__(self):
2435 return self
2436
2437 class OtherContext(object):
2438 def __enter__(self):
2439 return SelfContext()
2440
2441 class MultipleReturns(object):
2442 def __enter__(self):
2443 return SelfContext(), OtherContext()
2444
2445 class MultipleReturns2(object):
2446 def __enter__(self):
2447 return [1, [2, 3]]
2448
2449 with SelfContext() as self_context:
2450 pass
2451 with OtherContext() as other_context:
2452 pass
2453 with MultipleReturns(), OtherContext() as multiple_with:
2454 pass
2455 with MultipleReturns2() as (stdout, (stderr, stdin)):
2456 pass
2457 """)
2458 self_context = module["self_context"]
2459 inferred = next(self_context.infer())
2460 self.assertIsInstance(inferred, Instance)
2461 self.assertEqual(inferred.name, "SelfContext")
2462
2463 other_context = module["other_context"]
2464 inferred = next(other_context.infer())
2465 self.assertIsInstance(inferred, Instance)
2466 self.assertEqual(inferred.name, "SelfContext")
2467
2468 multiple_with = module["multiple_with"]
2469 inferred = next(multiple_with.infer())
2470 self.assertIsInstance(inferred, Instance)
2471 self.assertEqual(inferred.name, "SelfContext")
2472
2473 stdout = module["stdout"]
2474 inferred = next(stdout.infer())
2475 self.assertIsInstance(inferred, nodes.Const)
2476 self.assertEqual(inferred.value, 1)
2477 stderr = module["stderr"]
2478 inferred = next(stderr.infer())
2479 self.assertIsInstance(inferred, nodes.Const)
2480 self.assertEqual(inferred.value, 2)
2481
2482 def test_inferring_with_contextlib_contextmanager(self) -> None:
2483 module = parse("""
2484 import contextlib
2485 from contextlib import contextmanager
2486
2487 @contextlib.contextmanager
2488 def manager_none():
2489 try:
2490 yield
2491 finally:
2492 pass
2493
2494 @contextlib.contextmanager
2495 def manager_something():
2496 try:
2497 yield 42
2498 yield 24 # This should be ignored.
2499 finally:
2500 pass
2501
2502 @contextmanager
2503 def manager_multiple():
2504 with manager_none() as foo:
2505 with manager_something() as bar:
2506 yield foo, bar
2507
2508 with manager_none() as none:
2509 pass
2510 with manager_something() as something:
2511 pass
2512 with manager_multiple() as (first, second):
2513 pass
2514 """)
2515 none = module["none"]
2516 inferred = next(none.infer())
2517 self.assertIsInstance(inferred, nodes.Const)
2518 self.assertIsNone(inferred.value)
2519
2520 something = module["something"]
2521 inferred = something.inferred()
2522 self.assertEqual(len(inferred), 1)
2523 inferred = inferred[0]
2524 self.assertIsInstance(inferred, nodes.Const)
2525 self.assertEqual(inferred.value, 42)
2526
2527 first, second = module["first"], module["second"]
2528 first = next(first.infer())
2529 second = next(second.infer())
2530 self.assertIsInstance(first, nodes.Const)
2531 self.assertIsNone(first.value)
2532 self.assertIsInstance(second, nodes.Const)
2533 self.assertEqual(second.value, 42)
2534
2535 def test_inferring_context_manager_skip_index_error(self) -> None:
2536 # Raise an InferenceError when having multiple 'as' bindings
2537 # from a context manager, but its result doesn't have those
2538 # indices. This is the case of contextlib.nested, where the
2539 # result is a list, which is mutated later on, so it's
2540 # undetected by astroid.
2541 module = parse("""
2542 class Manager(object):
2543 def __enter__(self):
2544 return []
2545 with Manager() as (a, b, c):
2546 pass
2547 """)
2548 self.assertRaises(InferenceError, next, module["a"].infer())
2549
2550 def test_inferring_context_manager_unpacking_inference_error(self) -> None:
2551 # https://github.com/pylint-dev/pylint/issues/1463
2552 module = parse("""
2553 import contextlib
2554
2555 @contextlib.contextmanager
2556 def _select_source(a=None):
2557 with _select_source() as result:
2558 yield result
2559
2560 result = _select_source()
2561 with result as (a, b, c):
2562 pass
2563 """)
2564 self.assertRaises(InferenceError, next, module["a"].infer())
2565
2566 def test_inferring_with_contextlib_contextmanager_failures(self) -> None:
2567 module = parse("""
2568 from contextlib import contextmanager
2569
2570 def no_decorators_mgr():
2571 yield
2572 @no_decorators_mgr
2573 def other_decorators_mgr():
2574 yield
2575 @contextmanager
2576 def no_yield_mgr():
2577 pass
2578
2579 with no_decorators_mgr() as no_decorators:
2580 pass
2581 with other_decorators_mgr() as other_decorators:
2582 pass
2583 with no_yield_mgr() as no_yield:
2584 pass
2585 """)
2586 self.assertRaises(InferenceError, next, module["no_decorators"].infer())
2587 self.assertRaises(InferenceError, next, module["other_decorators"].infer())
2588 self.assertRaises(InferenceError, next, module["no_yield"].infer())
2589
2590 def test_nested_contextmanager(self) -> None:
2591 """Make sure contextmanager works with nested functions.
2592
2593 Previously contextmanager would retrieve
2594 the first yield instead of the yield in the
2595 proper scope
2596
2597 Fixes https://github.com/pylint-dev/pylint/issues/1746
2598 """
2599 code = """
2600 from contextlib import contextmanager
2601
2602 @contextmanager
2603 def outer():
2604 @contextmanager
2605 def inner():
2606 yield 2
2607 yield inner
2608
2609 with outer() as ctx:
2610 ctx #@
2611 with ctx() as val:
2612 val #@
2613 """
2614 context_node, value_node = extract_node(code)
2615 value = next(value_node.infer())
2616 context = next(context_node.infer())
2617 assert isinstance(context, nodes.FunctionDef)
2618 assert isinstance(value, nodes.Const)
2619
2620 def test_unary_op_leaks_stop_iteration(self) -> None:
2621 node = extract_node("+[] #@")
2622 self.assertEqual(util.Uninferable, next(node.infer()))
2623
2624 def test_unary_operands(self) -> None:
2625 ast_nodes = extract_node("""
2626 import os
2627 def func(): pass
2628 from missing import missing
2629 class GoodInstance(object):
2630 def __pos__(self):
2631 return 42
2632 def __neg__(self):
2633 return +self - 41
2634 def __invert__(self):
2635 return 42
2636 class BadInstance(object):
2637 def __pos__(self):
2638 return lala
2639 def __neg__(self):
2640 return missing
2641 class LambdaInstance(object):
2642 __pos__ = lambda self: self.lala
2643 __neg__ = lambda self: self.lala + 1
2644 @property
2645 def lala(self): return 24
2646 class InstanceWithAttr(object):
2647 def __init__(self):
2648 self.x = 42
2649 def __pos__(self):
2650 return self.x
2651 def __neg__(self):
2652 return +self - 41
2653 def __invert__(self):
2654 return self.x + 1
2655 instance = GoodInstance()
2656 lambda_instance = LambdaInstance()
2657 instance_with_attr = InstanceWithAttr()
2658 +instance #@
2659 -instance #@
2660 ~instance #@
2661 --instance #@
2662 +lambda_instance #@
2663 -lambda_instance #@
2664 +instance_with_attr #@
2665 -instance_with_attr #@
2666 ~instance_with_attr #@
2667
2668 bad_instance = BadInstance()
2669 +bad_instance #@
2670 -bad_instance #@
2671 ~bad_instance #@
2672
2673 # These should be TypeErrors.
2674 ~BadInstance #@
2675 ~os #@
2676 -func #@
2677 +BadInstance #@
2678 """)
2679 expected = [42, 1, 42, -1, 24, 25, 42, 1, 43]
2680 for node, value in zip(ast_nodes[:9], expected):
2681 inferred = next(node.infer())
2682 self.assertIsInstance(inferred, nodes.Const)
2683 self.assertEqual(inferred.value, value)
2684
2685 for bad_node in ast_nodes[9:]:
2686 inferred = next(bad_node.infer())
2687 self.assertEqual(inferred, util.Uninferable)
2688
2689 def test_unary_op_instance_method_not_callable(self) -> None:
2690 ast_node = extract_node("""
2691 class A:
2692 __pos__ = (i for i in range(10))
2693 +A() #@
2694 """)
2695 self.assertRaises(InferenceError, next, ast_node.infer())
2696
2697 def test_binary_op_type_errors(self) -> None:
2698 ast_nodes = extract_node("""
2699 import collections
2700 1 + "a" #@
2701 1 - [] #@
2702 1 * {} #@
2703 1 / collections #@
2704 1 ** (lambda x: x) #@
2705 {} * {} #@
2706 {} - {} #@
2707 {} >> {} #@
2708 [] + () #@
2709 () + [] #@
2710 [] * 2.0 #@
2711 () * 2.0 #@
2712 2.0 >> 2.0 #@
2713 class A(object): pass
2714 class B(object): pass
2715 A() + B() #@
2716 class A1(object):
2717 def __add__(self, other): return NotImplemented
2718 A1() + A1() #@
2719 class A(object):
2720 def __add__(self, other): return NotImplemented
2721 class B(object):
2722 def __radd__(self, other): return NotImplemented
2723 A() + B() #@
2724 class Parent(object):
2725 pass
2726 class Child(Parent):
2727 def __add__(self, other): return NotImplemented
2728 Child() + Parent() #@
2729 class A(object):
2730 def __add__(self, other): return NotImplemented
2731 class B(A):
2732 def __radd__(self, other):
2733 return NotImplemented
2734 A() + B() #@
2735 # Augmented
2736 f = 1
2737 f+=A() #@
2738 x = 1
2739 x+=[] #@
2740 """)
2741 msg = "unsupported operand type(s) for {op}: {lhs!r} and {rhs!r}"
2742 expected = [
2743 msg.format(op="+", lhs="int", rhs="str"),
2744 msg.format(op="-", lhs="int", rhs="list"),
2745 msg.format(op="*", lhs="int", rhs="dict"),
2746 msg.format(op="/", lhs="int", rhs="module"),
2747 msg.format(op="**", lhs="int", rhs="function"),
2748 msg.format(op="*", lhs="dict", rhs="dict"),
2749 msg.format(op="-", lhs="dict", rhs="dict"),
2750 msg.format(op=">>", lhs="dict", rhs="dict"),
2751 msg.format(op="+", lhs="list", rhs="tuple"),
2752 msg.format(op="+", lhs="tuple", rhs="list"),
2753 msg.format(op="*", lhs="list", rhs="float"),
2754 msg.format(op="*", lhs="tuple", rhs="float"),
2755 msg.format(op=">>", lhs="float", rhs="float"),
2756 msg.format(op="+", lhs="A", rhs="B"),
2757 msg.format(op="+", lhs="A1", rhs="A1"),
2758 msg.format(op="+", lhs="A", rhs="B"),
2759 msg.format(op="+", lhs="Child", rhs="Parent"),
2760 msg.format(op="+", lhs="A", rhs="B"),
2761 msg.format(op="+=", lhs="int", rhs="A"),
2762 msg.format(op="+=", lhs="int", rhs="list"),
2763 ]
2764
2765 for node, expected_value in zip(ast_nodes, expected):
2766 errors = node.type_errors()
2767 self.assertEqual(len(errors), 1)
2768 error = errors[0]
2769 self.assertEqual(str(error), expected_value)
2770
2771 def test_binary_type_errors_partially_uninferable(self) -> None:
2772 def patched_infer_binop(context):
2773 return iter([util.BadBinaryOperationMessage(None, None, None), Uninferable])
2774
2775 binary_op_node = extract_node("0 + 0")
2776 binary_op_node._infer_binop = patched_infer_binop
2777 errors = binary_op_node.type_errors()
2778 self.assertEqual(errors, [])
2779
2780 def test_unary_type_errors(self) -> None:
2781 ast_nodes = extract_node("""
2782 import collections
2783 ~[] #@
2784 ~() #@
2785 ~dict() #@
2786 ~{} #@
2787 ~set() #@
2788 -set() #@
2789 -"" #@
2790 ~"" #@
2791 +"" #@
2792 class A(object): pass
2793 ~(lambda: None) #@
2794 ~A #@
2795 ~A() #@
2796 ~collections #@
2797 ~2.0 #@
2798 """)
2799 msg = "bad operand type for unary {op}: {type}"
2800 expected = [
2801 msg.format(op="~", type="list"),
2802 msg.format(op="~", type="tuple"),
2803 msg.format(op="~", type="dict"),
2804 msg.format(op="~", type="dict"),
2805 msg.format(op="~", type="set"),
2806 msg.format(op="-", type="set"),
2807 msg.format(op="-", type="str"),
2808 msg.format(op="~", type="str"),
2809 msg.format(op="+", type="str"),
2810 msg.format(op="~", type="<lambda>"),
2811 msg.format(op="~", type="A"),
2812 msg.format(op="~", type="A"),
2813 msg.format(op="~", type="collections"),
2814 msg.format(op="~", type="float"),
2815 ]
2816 for node, expected_value in zip(ast_nodes, expected):
2817 errors = node.type_errors()
2818 self.assertEqual(len(errors), 1)
2819 error = errors[0]
2820 self.assertEqual(str(error), expected_value)
2821
2822 def test_unary_empty_type_errors(self) -> None:
2823 # These aren't supported right now
2824 ast_nodes = extract_node("""
2825 ~(2 and []) #@
2826 -(0 or {}) #@
2827 """)
2828 expected = [
2829 "bad operand type for unary ~: list",
2830 "bad operand type for unary -: dict",
2831 ]
2832 for node, expected_value in zip(ast_nodes, expected):
2833 errors = node.type_errors()
2834 self.assertEqual(len(errors), 1, (expected, node))
2835 self.assertEqual(str(errors[0]), expected_value)
2836
2837 def test_unary_type_errors_for_non_instance_objects(self) -> None:
2838 node = extract_node("~slice(1, 2, 3)")
2839 errors = node.type_errors()
2840 self.assertEqual(len(errors), 1)
2841 self.assertEqual(str(errors[0]), "bad operand type for unary ~: slice")
2842
2843 def test_unary_type_errors_partially_uninferable(self) -> None:
2844 def patched_infer_unary_op(context):
2845 return iter([util.BadUnaryOperationMessage(None, None, "msg"), Uninferable])
2846
2847 unary_op_node = extract_node("~0")
2848 unary_op_node._infer_unaryop = patched_infer_unary_op
2849 errors = unary_op_node.type_errors()
2850 self.assertEqual(errors, [])
2851
2852 def test_bool_value_recursive(self) -> None:
2853 pairs = [
2854 ("{}", False),
2855 ("{1:2}", True),
2856 ("()", False),
2857 ("(1, 2)", True),
2858 ("[]", False),
2859 ("[1,2]", True),
2860 ("frozenset()", False),
2861 ("frozenset((1, 2))", True),
2862 ]
2863 for code, expected in pairs:
2864 node = extract_node(code)
2865 inferred = next(node.infer())
2866 self.assertEqual(inferred.bool_value(), expected)
2867
2868 def test_genexpr_bool_value(self) -> None:
2869 node = extract_node("""(x for x in range(10))""")
2870 self.assertTrue(node.bool_value())
2871
2872 def test_name_bool_value(self) -> None:
2873 node = extract_node("""
2874 x = 42
2875 y = x
2876 y
2877 """)
2878 self.assertIs(node.bool_value(), util.Uninferable)
2879
2880 def test_bool_value(self) -> None:
2881 # Verify the truth value of nodes.
2882 module = parse("""
2883 import collections
2884 collections_module = collections
2885 def function(): pass
2886 class Class(object):
2887 def method(self): pass
2888 dict_comp = {x:y for (x, y) in ((1, 2), (2, 3))}
2889 set_comp = {x for x in range(10)}
2890 list_comp = [x for x in range(10)]
2891 lambda_func = lambda: None
2892 unbound_method = Class.method
2893 instance = Class()
2894 bound_method = instance.method
2895 def generator_func():
2896 yield
2897 def true_value():
2898 return True
2899 generator = generator_func()
2900 bin_op = 1 + 2
2901 bool_op = x and y
2902 callfunc = test()
2903 good_callfunc = true_value()
2904 compare = 2 < 3
2905 const_str_true = 'testconst'
2906 const_str_false = ''
2907 """)
2908 collections_module = next(module["collections_module"].infer())
2909 self.assertTrue(collections_module.bool_value())
2910 function = module["function"]
2911 self.assertTrue(function.bool_value())
2912 klass = module["Class"]
2913 self.assertTrue(klass.bool_value())
2914 dict_comp = next(module["dict_comp"].infer())
2915 self.assertEqual(dict_comp, util.Uninferable)
2916 set_comp = next(module["set_comp"].infer())
2917 self.assertEqual(set_comp, util.Uninferable)
2918 list_comp = next(module["list_comp"].infer())
2919 self.assertEqual(list_comp, util.Uninferable)
2920 lambda_func = next(module["lambda_func"].infer())
2921 self.assertTrue(lambda_func)
2922 unbound_method = next(module["unbound_method"].infer())
2923 self.assertTrue(unbound_method)
2924 bound_method = next(module["bound_method"].infer())
2925 self.assertTrue(bound_method)
2926 generator = next(module["generator"].infer())
2927 self.assertTrue(generator)
2928 bin_op = module["bin_op"].parent.value
2929 self.assertIs(bin_op.bool_value(), util.Uninferable)
2930 bool_op = module["bool_op"].parent.value
2931 self.assertEqual(bool_op.bool_value(), util.Uninferable)
2932 callfunc = module["callfunc"].parent.value
2933 self.assertEqual(callfunc.bool_value(), util.Uninferable)
2934 good_callfunc = next(module["good_callfunc"].infer())
2935 self.assertTrue(good_callfunc.bool_value())
2936 compare = module["compare"].parent.value
2937 self.assertEqual(compare.bool_value(), util.Uninferable)
2938
2939 def test_bool_value_instances(self) -> None:
2940 instances = extract_node("""
2941 class FalseBoolInstance(object):
2942 def __bool__(self):
2943 return False
2944 class TrueBoolInstance(object):
2945 def __bool__(self):
2946 return True
2947 class FalseLenInstance(object):
2948 def __len__(self):
2949 return 0
2950 class TrueLenInstance(object):
2951 def __len__(self):
2952 return 14
2953 class AlwaysTrueInstance(object):
2954 pass
2955 class ErrorInstance(object):
2956 def __bool__(self):
2957 return lala
2958 def __len__(self):
2959 return lala
2960 class NonMethods(object):
2961 __bool__ = 1
2962 __len__ = 2
2963 FalseBoolInstance() #@
2964 TrueBoolInstance() #@
2965 FalseLenInstance() #@
2966 TrueLenInstance() #@
2967 AlwaysTrueInstance() #@
2968 ErrorInstance() #@
2969 """)
2970 expected = (False, True, False, True, True, util.Uninferable, util.Uninferable)
2971 for node, expected_value in zip(instances, expected):
2972 inferred = next(node.infer())
2973 self.assertEqual(inferred.bool_value(), expected_value)
2974
2975 def test_bool_value_variable(self) -> None:
2976 instance = extract_node("""
2977 class VariableBoolInstance(object):
2978 def __init__(self, value):
2979 self.value = value
2980 def __bool__(self):
2981 return self.value
2982
2983 not VariableBoolInstance(True)
2984 """)
2985 inferred = next(instance.infer())
2986 self.assertIs(inferred.bool_value(), util.Uninferable)
2987
2988 def test_bool_value_not_implemented(self) -> None:
2989 node = extract_node("""NotImplemented""")
2990 inferred = next(node.infer())
2991 if PY314_PLUS:
2992 self.assertIs(inferred.bool_value(), util.Uninferable)
2993 else:
2994 self.assertIs(inferred.bool_value(), True)
2995
2996 def test_infer_coercion_rules_for_floats_complex(self) -> None:
2997 ast_nodes = extract_node("""
2998 1 + 1.0 #@
2999 1 * 1.0 #@
3000 2 - 1.0 #@
3001 2 / 2.0 #@
3002 1 + 1j #@
3003 2 * 1j #@
3004 2 - 1j #@
3005 3 / 1j #@
3006 """)
3007 expected_values = [2.0, 1.0, 1.0, 1.0, 1 + 1j, 2j, 2 - 1j, -3j]
3008 for node, expected in zip(ast_nodes, expected_values):
3009 inferred = next(node.infer())
3010 self.assertEqual(inferred.value, expected)
3011
3012 def test_binop_list_with_elts(self) -> None:
3013 ast_node = extract_node("""
3014 x = [A] * 1
3015 [1] + x
3016 """)
3017 inferred = next(ast_node.infer())
3018 self.assertIsInstance(inferred, nodes.List)
3019 self.assertEqual(len(inferred.elts), 2)
3020 self.assertIsInstance(inferred.elts[0], nodes.Const)
3021 self.assertIsInstance(inferred.elts[1], nodes.Unknown)
3022
3023 def test_binop_same_types(self) -> None:
3024 ast_nodes = extract_node("""
3025 class A(object):
3026 def __add__(self, other):
3027 return 42
3028 1 + 1 #@
3029 1 - 1 #@
3030 "a" + "b" #@
3031 A() + A() #@
3032 """)
3033 expected_values = [2, 0, "ab", 42]
3034 for node, expected in zip(ast_nodes, expected_values):
3035 inferred = next(node.infer())
3036 self.assertIsInstance(inferred, nodes.Const)
3037 self.assertEqual(inferred.value, expected)
3038
3039 def test_binop_different_types_reflected_only(self) -> None:
3040 node = extract_node("""
3041 class A(object):
3042 pass
3043 class B(object):
3044 def __radd__(self, other):
3045 return other
3046 A() + B() #@
3047 """)
3048 inferred = next(node.infer())
3049 self.assertIsInstance(inferred, Instance)
3050 self.assertEqual(inferred.name, "A")
3051
3052 def test_binop_different_types_unknown_bases(self) -> None:
3053 node = extract_node("""
3054 from foo import bar
3055
3056 class A(bar):
3057 pass
3058 class B(object):
3059 def __radd__(self, other):
3060 return other
3061 A() + B() #@
3062 """)
3063 inferred = next(node.infer())
3064 self.assertIs(inferred, util.Uninferable)
3065
3066 def test_binop_different_types_normal_not_implemented_and_reflected(self) -> None:
3067 node = extract_node("""
3068 class A(object):
3069 def __add__(self, other):
3070 return NotImplemented
3071 class B(object):
3072 def __radd__(self, other):
3073 return other
3074 A() + B() #@
3075 """)
3076 inferred = next(node.infer())
3077 self.assertIsInstance(inferred, Instance)
3078 self.assertEqual(inferred.name, "A")
3079
3080 def test_binop_different_types_no_method_implemented(self) -> None:
3081 node = extract_node("""
3082 class A(object):
3083 pass
3084 class B(object): pass
3085 A() + B() #@
3086 """)
3087 inferred = next(node.infer())
3088 self.assertEqual(inferred, util.Uninferable)
3089
3090 def test_binop_different_types_reflected_and_normal_not_implemented(self) -> None:
3091 node = extract_node("""
3092 class A(object):
3093 def __add__(self, other): return NotImplemented
3094 class B(object):
3095 def __radd__(self, other): return NotImplemented
3096 A() + B() #@
3097 """)
3098 inferred = next(node.infer())
3099 self.assertEqual(inferred, util.Uninferable)
3100
3101 def test_binop_subtype(self) -> None:
3102 node = extract_node("""
3103 class A(object): pass
3104 class B(A):
3105 def __add__(self, other): return other
3106 B() + A() #@
3107 """)
3108 inferred = next(node.infer())
3109 self.assertIsInstance(inferred, Instance)
3110 self.assertEqual(inferred.name, "A")
3111
3112 def test_binop_subtype_implemented_in_parent(self) -> None:
3113 node = extract_node("""
3114 class A(object):
3115 def __add__(self, other): return other
3116 class B(A): pass
3117 B() + A() #@
3118 """)
3119 inferred = next(node.infer())
3120 self.assertIsInstance(inferred, Instance)
3121 self.assertEqual(inferred.name, "A")
3122
3123 def test_binop_subtype_not_implemented(self) -> None:
3124 node = extract_node("""
3125 class A(object):
3126 pass
3127 class B(A):
3128 def __add__(self, other): return NotImplemented
3129 B() + A() #@
3130 """)
3131 inferred = next(node.infer())
3132 self.assertEqual(inferred, util.Uninferable)
3133
3134 def test_binop_supertype(self) -> None:
3135 node = extract_node("""
3136 class A(object):
3137 pass
3138 class B(A):
3139 def __radd__(self, other):
3140 return other
3141 A() + B() #@
3142 """)
3143 inferred = next(node.infer())
3144 self.assertIsInstance(inferred, Instance)
3145 self.assertEqual(inferred.name, "A")
3146
3147 def test_binop_supertype_rop_not_implemented(self) -> None:
3148 node = extract_node("""
3149 class A(object):
3150 def __add__(self, other):
3151 return other
3152 class B(A):
3153 def __radd__(self, other):
3154 return NotImplemented
3155 A() + B() #@
3156 """)
3157 inferred = next(node.infer())
3158 self.assertIsInstance(inferred, Instance)
3159 self.assertEqual(inferred.name, "B")
3160
3161 def test_binop_supertype_both_not_implemented(self) -> None:
3162 node = extract_node("""
3163 class A(object):
3164 def __add__(self): return NotImplemented
3165 class B(A):
3166 def __radd__(self, other):
3167 return NotImplemented
3168 A() + B() #@
3169 """)
3170 inferred = next(node.infer())
3171 self.assertEqual(inferred, util.Uninferable)
3172
3173 def test_binop_inference_errors(self) -> None:
3174 ast_nodes = extract_node("""
3175 from unknown import Unknown
3176 class A(object):
3177 def __add__(self, other): return NotImplemented
3178 class B(object):
3179 def __add__(self, other): return Unknown
3180 A() + Unknown #@
3181 Unknown + A() #@
3182 B() + A() #@
3183 A() + B() #@
3184 """)
3185 for node in ast_nodes:
3186 self.assertEqual(next(node.infer()), util.Uninferable)
3187
3188 def test_binop_ambiguity(self) -> None:
3189 ast_nodes = extract_node("""
3190 class A(object):
3191 def __add__(self, other):
3192 if isinstance(other, B):
3193 return NotImplemented
3194 if type(other) is type(self):
3195 return 42
3196 return NotImplemented
3197 class B(A): pass
3198 class C(object):
3199 def __radd__(self, other):
3200 if isinstance(other, B):
3201 return 42
3202 return NotImplemented
3203 A() + B() #@
3204 B() + A() #@
3205 A() + C() #@
3206 C() + A() #@
3207 """)
3208 for node in ast_nodes:
3209 self.assertEqual(next(node.infer()), util.Uninferable)
3210
3211 def test_binop_self_in_list(self) -> None:
3212 """If 'self' is referenced within a list it should not be bound by it.
3213
3214 Reported in https://github.com/pylint-dev/pylint/issues/4826.
3215 """
3216 ast_nodes = extract_node("""
3217 class A:
3218 def __init__(self):
3219 for a in [self] + []:
3220 print(a) #@
3221
3222 class B:
3223 def __init__(self):
3224 for b in [] + [self]:
3225 print(b) #@
3226 """)
3227 inferred_a = list(ast_nodes[0].args[0].infer())
3228 self.assertEqual(len(inferred_a), 1)
3229 self.assertIsInstance(inferred_a[0], Instance)
3230 self.assertEqual(inferred_a[0]._proxied.name, "A")
3231
3232 inferred_b = list(ast_nodes[1].args[0].infer())
3233 self.assertEqual(len(inferred_b), 1)
3234 self.assertIsInstance(inferred_b[0], Instance)
3235 self.assertEqual(inferred_b[0]._proxied.name, "B")
3236
3237 def test_metaclass__getitem__(self) -> None:
3238 ast_node = extract_node("""
3239 class Meta(type):
3240 def __getitem__(cls, arg):
3241 return 24
3242 class A(object, metaclass=Meta):
3243 pass
3244
3245 A['Awesome'] #@
3246 """)
3247 inferred = next(ast_node.infer())
3248 self.assertIsInstance(inferred, nodes.Const)
3249 self.assertEqual(inferred.value, 24)
3250
3251 @unittest.skipUnless(HAS_SIX, "These tests require the six library")
3252 def test_with_metaclass__getitem__(self):
3253 ast_node = extract_node("""
3254 class Meta(type):
3255 def __getitem__(cls, arg):
3256 return 24
3257 import six
3258 class A(six.with_metaclass(Meta)):
3259 pass
3260
3261 A['Awesome'] #@
3262 """)
3263 inferred = next(ast_node.infer())
3264 self.assertIsInstance(inferred, nodes.Const)
3265 self.assertEqual(inferred.value, 24)
3266
3267 def test_bin_op_classes(self) -> None:
3268 ast_node = extract_node("""
3269 class Meta(type):
3270 def __or__(self, other):
3271 return 24
3272 class A(object, metaclass=Meta):
3273 pass
3274
3275 A | A
3276 """)
3277 inferred = next(ast_node.infer())
3278 self.assertIsInstance(inferred, nodes.Const)
3279 self.assertEqual(inferred.value, 24)
3280
3281 @unittest.skipUnless(HAS_SIX, "These tests require the six library")
3282 def test_bin_op_classes_with_metaclass(self):
3283 ast_node = extract_node("""
3284 class Meta(type):
3285 def __or__(self, other):
3286 return 24
3287 import six
3288 class A(six.with_metaclass(Meta)):
3289 pass
3290
3291 A | A
3292 """)
3293 inferred = next(ast_node.infer())
3294 self.assertIsInstance(inferred, nodes.Const)
3295 self.assertEqual(inferred.value, 24)
3296
3297 def test_bin_op_supertype_more_complicated_example(self) -> None:
3298 ast_node = extract_node("""
3299 class A(object):
3300 def __init__(self):
3301 self.foo = 42
3302 def __add__(self, other):
3303 return other.bar + self.foo / 2
3304
3305 class B(A):
3306 def __init__(self):
3307 self.bar = 24
3308 def __radd__(self, other):
3309 return NotImplemented
3310
3311 A() + B() #@
3312 """)
3313 inferred = next(ast_node.infer())
3314 self.assertIsInstance(inferred, nodes.Const)
3315 self.assertEqual(int(inferred.value), 45)
3316
3317 def test_aug_op_same_type_not_implemented(self) -> None:
3318 ast_node = extract_node("""
3319 class A(object):
3320 def __iadd__(self, other): return NotImplemented
3321 def __add__(self, other): return NotImplemented
3322 A() + A() #@
3323 """)
3324 self.assertEqual(next(ast_node.infer()), util.Uninferable)
3325
3326 def test_aug_op_same_type_aug_implemented(self) -> None:
3327 ast_node = extract_node("""
3328 class A(object):
3329 def __iadd__(self, other): return other
3330 f = A()
3331 f += A() #@
3332 """)
3333 inferred = next(ast_node.infer())
3334 self.assertIsInstance(inferred, Instance)
3335 self.assertEqual(inferred.name, "A")
3336
3337 def test_aug_op_same_type_aug_not_implemented_normal_implemented(self) -> None:
3338 ast_node = extract_node("""
3339 class A(object):
3340 def __iadd__(self, other): return NotImplemented
3341 def __add__(self, other): return 42
3342 f = A()
3343 f += A() #@
3344 """)
3345 inferred = next(ast_node.infer())
3346 self.assertIsInstance(inferred, nodes.Const)
3347 self.assertEqual(inferred.value, 42)
3348
3349 def test_aug_op_subtype_both_not_implemented(self) -> None:
3350 ast_node = extract_node("""
3351 class A(object):
3352 def __iadd__(self, other): return NotImplemented
3353 def __add__(self, other): return NotImplemented
3354 class B(A):
3355 pass
3356 b = B()
3357 b+=A() #@
3358 """)
3359 self.assertEqual(next(ast_node.infer()), util.Uninferable)
3360
3361 def test_aug_op_subtype_aug_op_is_implemented(self) -> None:
3362 ast_node = extract_node("""
3363 class A(object):
3364 def __iadd__(self, other): return 42
3365 class B(A):
3366 pass
3367 b = B()
3368 b+=A() #@
3369 """)
3370 inferred = next(ast_node.infer())
3371 self.assertIsInstance(inferred, nodes.Const)
3372 self.assertEqual(inferred.value, 42)
3373
3374 def test_aug_op_subtype_normal_op_is_implemented(self) -> None:
3375 ast_node = extract_node("""
3376 class A(object):
3377 def __add__(self, other): return 42
3378 class B(A):
3379 pass
3380 b = B()
3381 b+=A() #@
3382 """)
3383 inferred = next(ast_node.infer())
3384 self.assertIsInstance(inferred, nodes.Const)
3385 self.assertEqual(inferred.value, 42)
3386
3387 def test_aug_different_types_no_method_implemented(self) -> None:
3388 ast_node = extract_node("""
3389 class A(object): pass
3390 class B(object): pass
3391 f = A()
3392 f += B() #@
3393 """)
3394 self.assertEqual(next(ast_node.infer()), util.Uninferable)
3395
3396 def test_aug_different_types_augop_implemented(self) -> None:
3397 ast_node = extract_node("""
3398 class A(object):
3399 def __iadd__(self, other): return other
3400 class B(object): pass
3401 f = A()
3402 f += B() #@
3403 """)
3404 inferred = next(ast_node.infer())
3405 self.assertIsInstance(inferred, Instance)
3406 self.assertEqual(inferred.name, "B")
3407
3408 def test_aug_different_types_aug_not_implemented(self) -> None:
3409 ast_node = extract_node("""
3410 class A(object):
3411 def __iadd__(self, other): return NotImplemented
3412 def __add__(self, other): return other
3413 class B(object): pass
3414 f = A()
3415 f += B() #@
3416 """)
3417 inferred = next(ast_node.infer())
3418 self.assertIsInstance(inferred, Instance)
3419 self.assertEqual(inferred.name, "B")
3420
3421 def test_aug_different_types_aug_not_implemented_rop_fallback(self) -> None:
3422 ast_node = extract_node("""
3423 class A(object):
3424 def __iadd__(self, other): return NotImplemented
3425 def __add__(self, other): return NotImplemented
3426 class B(object):
3427 def __radd__(self, other): return other
3428 f = A()
3429 f += B() #@
3430 """)
3431 inferred = next(ast_node.infer())
3432 self.assertIsInstance(inferred, Instance)
3433 self.assertEqual(inferred.name, "A")
3434
3435 def test_augop_supertypes_none_implemented(self) -> None:
3436 ast_node = extract_node("""
3437 class A(object): pass
3438 class B(object): pass
3439 a = A()
3440 a += B() #@
3441 """)
3442 self.assertEqual(next(ast_node.infer()), util.Uninferable)
3443
3444 def test_augop_supertypes_not_implemented_returned_for_all(self) -> None:
3445 ast_node = extract_node("""
3446 class A(object):
3447 def __iadd__(self, other): return NotImplemented
3448 def __add__(self, other): return NotImplemented
3449 class B(object):
3450 def __add__(self, other): return NotImplemented
3451 a = A()
3452 a += B() #@
3453 """)
3454 self.assertEqual(next(ast_node.infer()), util.Uninferable)
3455
3456 def test_augop_supertypes_augop_implemented(self) -> None:
3457 ast_node = extract_node("""
3458 class A(object):
3459 def __iadd__(self, other): return other
3460 class B(A): pass
3461 a = A()
3462 a += B() #@
3463 """)
3464 inferred = next(ast_node.infer())
3465 self.assertIsInstance(inferred, Instance)
3466 self.assertEqual(inferred.name, "B")
3467
3468 def test_augop_supertypes_reflected_binop_implemented(self) -> None:
3469 ast_node = extract_node("""
3470 class A(object):
3471 def __iadd__(self, other): return NotImplemented
3472 class B(A):
3473 def __radd__(self, other): return other
3474 a = A()
3475 a += B() #@
3476 """)
3477 inferred = next(ast_node.infer())
3478 self.assertIsInstance(inferred, Instance)
3479 self.assertEqual(inferred.name, "A")
3480
3481 def test_augop_supertypes_normal_binop_implemented(self) -> None:
3482 ast_node = extract_node("""
3483 class A(object):
3484 def __iadd__(self, other): return NotImplemented
3485 def __add__(self, other): return other
3486 class B(A):
3487 def __radd__(self, other): return NotImplemented
3488
3489 a = A()
3490 a += B() #@
3491 """)
3492 inferred = next(ast_node.infer())
3493 self.assertIsInstance(inferred, Instance)
3494 self.assertEqual(inferred.name, "B")
3495
3496 def test_augop_type_errors_partially_uninferable(self) -> None:
3497 def patched_infer_augassign(context) -> None:
3498 return iter([util.BadBinaryOperationMessage(None, None, None), Uninferable])
3499
3500 aug_op_node = extract_node("__name__ += 'test'")
3501 aug_op_node._infer_augassign = patched_infer_augassign
3502 errors = aug_op_node.type_errors()
3503 self.assertEqual(errors, [])
3504
3505 def test_string_interpolation(self):
3506 ast_nodes = extract_node("""
3507 "a%d%d" % (1, 2) #@
3508 "a%(x)s" % {"x": 42} #@
3509 """)
3510 expected = ["a12", "a42"]
3511 for node, expected_value in zip(ast_nodes, expected):
3512 inferred = next(node.infer())
3513 self.assertIsInstance(inferred, nodes.Const)
3514 self.assertEqual(inferred.value, expected_value)
3515
3516 def test_mul_list_supports__index__(self) -> None:
3517 ast_nodes = extract_node("""
3518 class Index(object):
3519 def __index__(self): return 2
3520 class NotIndex(object): pass
3521 class NotIndex2(object):
3522 def __index__(self): return None
3523 a = [1, 2]
3524 a * Index() #@
3525 a * NotIndex() #@
3526 a * NotIndex2() #@
3527 """)
3528 assert isinstance(ast_nodes, list)
3529 first = next(ast_nodes[0].infer())
3530 self.assertIsInstance(first, nodes.List)
3531 self.assertEqual([node.value for node in first.itered()], [1, 2, 1, 2])
3532 for rest in ast_nodes[1:]:
3533 inferred = next(rest.infer())
3534 self.assertEqual(inferred, util.Uninferable)
3535
3536 def test_subscript_supports__index__(self) -> None:
3537 ast_nodes = extract_node("""
3538 class Index(object):
3539 def __index__(self): return 2
3540 class LambdaIndex(object):
3541 __index__ = lambda self: self.foo
3542 @property
3543 def foo(self): return 1
3544 class NonIndex(object):
3545 __index__ = lambda self: None
3546 a = [1, 2, 3, 4]
3547 a[Index()] #@
3548 a[LambdaIndex()] #@
3549 a[NonIndex()] #@
3550 """)
3551 assert isinstance(ast_nodes, list)
3552 first = next(ast_nodes[0].infer())
3553 self.assertIsInstance(first, nodes.Const)
3554 self.assertEqual(first.value, 3)
3555 second = next(ast_nodes[1].infer())
3556 self.assertIsInstance(second, nodes.Const)
3557 self.assertEqual(second.value, 2)
3558 self.assertRaises(InferenceError, next, ast_nodes[2].infer())
3559
3560 def test_special_method_masquerading_as_another(self) -> None:
3561 ast_node = extract_node("""
3562 class Info(object):
3563 def __add__(self, other):
3564 return "lala"
3565 __or__ = __add__
3566
3567 f = Info()
3568 f | Info() #@
3569 """)
3570 inferred = next(ast_node.infer())
3571 self.assertIsInstance(inferred, nodes.Const)
3572 self.assertEqual(inferred.value, "lala")
3573
3574 def test_unary_op_assignment(self) -> None:
3575 ast_node = extract_node("""
3576 class A(object): pass
3577 def pos(self):
3578 return 42
3579 A.__pos__ = pos
3580 f = A()
3581 +f #@
3582 """)
3583 inferred = next(ast_node.infer())
3584 self.assertIsInstance(inferred, nodes.Const)
3585 self.assertEqual(inferred.value, 42)
3586
3587 def test_unary_op_classes(self) -> None:
3588 ast_node = extract_node("""
3589 class Meta(type):
3590 def __invert__(self):
3591 return 42
3592 class A(object, metaclass=Meta):
3593 pass
3594 ~A
3595 """)
3596 inferred = next(ast_node.infer())
3597 self.assertIsInstance(inferred, nodes.Const)
3598 self.assertEqual(inferred.value, 42)
3599
3600 @unittest.skipUnless(HAS_SIX, "These tests require the six library")
3601 def test_unary_op_classes_with_metaclass(self):
3602 ast_node = extract_node("""
3603 import six
3604 class Meta(type):
3605 def __invert__(self):
3606 return 42
3607 class A(six.with_metaclass(Meta)):
3608 pass
3609 ~A
3610 """)
3611 inferred = next(ast_node.infer())
3612 self.assertIsInstance(inferred, nodes.Const)
3613 self.assertEqual(inferred.value, 42)
3614
3615 def _slicing_test_helper(
3616 self,
3617 pairs: tuple[
3618 tuple[str, list[int] | str],
3619 tuple[str, list[int] | str],
3620 tuple[str, list[int] | str],
3621 tuple[str, list[int] | str],
3622 tuple[str, list[int] | str],
3623 tuple[str, list[int] | str],
3624 tuple[str, list[int] | str],
3625 tuple[str, list[int] | str],
3626 tuple[str, list[int] | str],
3627 tuple[str, list[int] | str],
3628 ],
3629 cls: ABCMeta | type,
3630 get_elts: Callable,
3631 ) -> None:
3632 for code, expected in pairs:
3633 ast_node = extract_node(code)
3634 inferred = next(ast_node.infer())
3635 self.assertIsInstance(inferred, cls)
3636 self.assertEqual(get_elts(inferred), expected, ast_node.as_string())
3637
3638 def test_slicing_list(self) -> None:
3639 pairs = (
3640 ("[1, 2, 3][:] #@", [1, 2, 3]),
3641 ("[1, 2, 3][0:] #@", [1, 2, 3]),
3642 ("[1, 2, 3][None:] #@", [1, 2, 3]),
3643 ("[1, 2, 3][None:None] #@", [1, 2, 3]),
3644 ("[1, 2, 3][0:-1] #@", [1, 2]),
3645 ("[1, 2, 3][0:2] #@", [1, 2]),
3646 ("[1, 2, 3][0:2:None] #@", [1, 2]),
3647 ("[1, 2, 3][::] #@", [1, 2, 3]),
3648 ("[1, 2, 3][::2] #@", [1, 3]),
3649 ("[1, 2, 3][::-1] #@", [3, 2, 1]),
3650 ("[1, 2, 3][0:2:2] #@", [1]),
3651 ("[1, 2, 3, 4, 5, 6][0:4-1:2+0] #@", [1, 3]),
3652 )
3653 self._slicing_test_helper(
3654 pairs, nodes.List, lambda inferred: [elt.value for elt in inferred.elts]
3655 )
3656
3657 def test_slicing_tuple(self) -> None:
3658 pairs = (
3659 ("(1, 2, 3)[:] #@", [1, 2, 3]),
3660 ("(1, 2, 3)[0:] #@", [1, 2, 3]),
3661 ("(1, 2, 3)[None:] #@", [1, 2, 3]),
3662 ("(1, 2, 3)[None:None] #@", [1, 2, 3]),
3663 ("(1, 2, 3)[0:-1] #@", [1, 2]),
3664 ("(1, 2, 3)[0:2] #@", [1, 2]),
3665 ("(1, 2, 3)[0:2:None] #@", [1, 2]),
3666 ("(1, 2, 3)[::] #@", [1, 2, 3]),
3667 ("(1, 2, 3)[::2] #@", [1, 3]),
3668 ("(1, 2, 3)[::-1] #@", [3, 2, 1]),
3669 ("(1, 2, 3)[0:2:2] #@", [1]),
3670 ("(1, 2, 3, 4, 5, 6)[0:4-1:2+0] #@", [1, 3]),
3671 )
3672 self._slicing_test_helper(
3673 pairs, nodes.Tuple, lambda inferred: [elt.value for elt in inferred.elts]
3674 )
3675
3676 def test_slicing_str(self) -> None:
3677 pairs = (
3678 ("'123'[:] #@", "123"),
3679 ("'123'[0:] #@", "123"),
3680 ("'123'[None:] #@", "123"),
3681 ("'123'[None:None] #@", "123"),
3682 ("'123'[0:-1] #@", "12"),
3683 ("'123'[0:2] #@", "12"),
3684 ("'123'[0:2:None] #@", "12"),
3685 ("'123'[::] #@", "123"),
3686 ("'123'[::2] #@", "13"),
3687 ("'123'[::-1] #@", "321"),
3688 ("'123'[0:2:2] #@", "1"),
3689 ("'123456'[0:4-1:2+0] #@", "13"),
3690 )
3691 self._slicing_test_helper(pairs, nodes.Const, lambda inferred: inferred.value)
3692
3693 def test_invalid_slicing_primaries(self) -> None:
3694 examples = [
3695 "(lambda x: x)[1:2]",
3696 "1[2]",
3697 "(1, 2, 3)[a:]",
3698 "(1, 2, 3)[object:object]",
3699 "(1, 2, 3)[1:object]",
3700 ]
3701 for code in examples:
3702 node = extract_node(code)
3703 self.assertRaises(InferenceError, next, node.infer())
3704
3705 def test_instance_slicing(self) -> None:
3706 ast_nodes = extract_node("""
3707 class A(object):
3708 def __getitem__(self, index):
3709 return [1, 2, 3, 4, 5][index]
3710 A()[1:] #@
3711 A()[:2] #@
3712 A()[1:4] #@
3713 """)
3714 expected_values = [[2, 3, 4, 5], [1, 2], [2, 3, 4]]
3715 for expected, node in zip(expected_values, ast_nodes):
3716 inferred = next(node.infer())
3717 self.assertIsInstance(inferred, nodes.List)
3718 self.assertEqual([elt.value for elt in inferred.elts], expected)
3719
3720 def test_instance_slicing_slices(self) -> None:
3721 ast_node = extract_node("""
3722 class A(object):
3723 def __getitem__(self, index):
3724 return index
3725 A()[1:] #@
3726 """)
3727 inferred = next(ast_node.infer())
3728 self.assertIsInstance(inferred, nodes.Slice)
3729 self.assertEqual(inferred.lower.value, 1)
3730 self.assertIsNone(inferred.upper)
3731
3732 def test_instance_slicing_fails(self) -> None:
3733 ast_nodes = extract_node("""
3734 class A(object):
3735 def __getitem__(self, index):
3736 return 1[index]
3737 A()[4:5] #@
3738 A()[2:] #@
3739 """)
3740 for node in ast_nodes:
3741 self.assertEqual(next(node.infer()), util.Uninferable)
3742
3743 def test_type__new__with_metaclass(self) -> None:
3744 ast_node = extract_node("""
3745 class Metaclass(type):
3746 pass
3747 class Entity(object):
3748 pass
3749 type.__new__(Metaclass, 'NewClass', (Entity,), {'a': 1}) #@
3750 """)
3751 inferred = next(ast_node.infer())
3752
3753 self.assertIsInstance(inferred, nodes.ClassDef)
3754 self.assertEqual(inferred.name, "NewClass")
3755 metaclass = inferred.metaclass()
3756 self.assertEqual(metaclass, inferred.root()["Metaclass"])
3757 ancestors = list(inferred.ancestors())
3758 self.assertEqual(len(ancestors), 2)
3759 self.assertEqual(ancestors[0], inferred.root()["Entity"])
3760 attributes = inferred.getattr("a")
3761 self.assertEqual(len(attributes), 1)
3762 self.assertIsInstance(attributes[0], nodes.Const)
3763 self.assertEqual(attributes[0].value, 1)
3764
3765 def test_type__new__not_enough_arguments(self) -> None:
3766 ast_nodes = extract_node("""
3767 type.__new__(type, 'foo') #@
3768 type.__new__(type, 'foo', ()) #@
3769 type.__new__(type, 'foo', (), {}, ()) #@
3770 """)
3771 for node in ast_nodes:
3772 with pytest.raises(InferenceError):
3773 next(node.infer())
3774
3775 def test_type__new__invalid_mcs_argument(self) -> None:
3776 ast_nodes = extract_node("""
3777 class Class(object): pass
3778 type.__new__(1, 2, 3, 4) #@
3779 type.__new__(Class, 2, 3, 4) #@
3780 """)
3781 for node in ast_nodes:
3782 with pytest.raises(InferenceError):
3783 next(node.infer())
3784
3785 def test_type__new__invalid_name(self) -> None:
3786 ast_nodes = extract_node("""
3787 class Class(type): pass
3788 type.__new__(Class, object, 1, 2) #@
3789 type.__new__(Class, 1, 1, 2) #@
3790 type.__new__(Class, [], 1, 2) #@
3791 """)
3792 for node in ast_nodes:
3793 with pytest.raises(InferenceError):
3794 next(node.infer())
3795
3796 def test_type__new__invalid_bases(self) -> None:
3797 ast_nodes = extract_node("""
3798 type.__new__(type, 'a', 1, 2) #@
3799 type.__new__(type, 'a', [], 2) #@
3800 type.__new__(type, 'a', {}, 2) #@
3801 type.__new__(type, 'a', (1, ), 2) #@
3802 type.__new__(type, 'a', (object, 1), 2) #@
3803 """)
3804 for node in ast_nodes:
3805 with pytest.raises(InferenceError):
3806 next(node.infer())
3807
3808 def test_type__new__invalid_attrs(self) -> None:
3809 type_error_nodes = extract_node("""
3810 type.__new__(type, 'a', (), ()) #@
3811 type.__new__(type, 'a', (), object) #@
3812 type.__new__(type, 'a', (), 1) #@
3813 """)
3814 for node in type_error_nodes:
3815 with pytest.raises(InferenceError):
3816 next(node.infer())
3817
3818 # Ignore invalid keys
3819 ast_nodes = extract_node("""
3820 type.__new__(type, 'a', (), {object: 1}) #@
3821 type.__new__(type, 'a', (), {1:2, "a":5}) #@
3822 """)
3823 for node in ast_nodes:
3824 inferred = next(node.infer())
3825 self.assertIsInstance(inferred, nodes.ClassDef)
3826
3827 def test_type__new__metaclass_lookup(self) -> None:
3828 ast_node = extract_node("""
3829 class Metaclass(type):
3830 def test(cls): pass
3831 @classmethod
3832 def test1(cls): pass
3833 attr = 42
3834 type.__new__(Metaclass, 'A', (), {}) #@
3835 """)
3836 inferred = next(ast_node.infer())
3837 self.assertIsInstance(inferred, nodes.ClassDef)
3838 test = inferred.getattr("test")
3839 self.assertEqual(len(test), 1)
3840 self.assertIsInstance(test[0], BoundMethod)
3841 self.assertIsInstance(test[0].bound, nodes.ClassDef)
3842 self.assertEqual(test[0].bound, inferred)
3843 test1 = inferred.getattr("test1")
3844 self.assertEqual(len(test1), 1)
3845 self.assertIsInstance(test1[0], BoundMethod)
3846 self.assertIsInstance(test1[0].bound, nodes.ClassDef)
3847 self.assertEqual(test1[0].bound, inferred.metaclass())
3848 attr = inferred.getattr("attr")
3849 self.assertEqual(len(attr), 1)
3850 self.assertIsInstance(attr[0], nodes.Const)
3851 self.assertEqual(attr[0].value, 42)
3852
3853 def test_type__new__metaclass_and_ancestors_lookup(self) -> None:
3854 ast_node = extract_node("""
3855 class Book(object):
3856 title = 'Ubik'
3857 class MetaBook(type):
3858 title = 'Grimus'
3859 type.__new__(MetaBook, 'book', (Book, ), {'title':'Catch 22'}) #@
3860 """)
3861 inferred = next(ast_node.infer())
3862 self.assertIsInstance(inferred, nodes.ClassDef)
3863 titles = [
3864 title.value
3865 for attr in inferred.getattr("title")
3866 for title in attr.inferred()
3867 ]
3868 self.assertEqual(titles, ["Catch 22", "Ubik", "Grimus"])
3869
3870 @staticmethod
3871 def test_builtin_new() -> None:
3872 ast_node = extract_node("int.__new__(int, 42)")
3873 inferred = next(ast_node.infer())
3874 assert isinstance(inferred, nodes.Const)
3875 assert inferred.value == 42
3876
3877 ast_node2 = extract_node("int.__new__(int)")
3878 inferred2 = next(ast_node2.infer())
3879 assert isinstance(inferred2, Instance)
3880 assert not isinstance(inferred2, nodes.Const)
3881 assert inferred2._proxied is inferred._proxied
3882
3883 ast_node3 = extract_node("""
3884 x = 43
3885 int.__new__(int, x) #@
3886 """)
3887 inferred3 = next(ast_node3.infer())
3888 assert isinstance(inferred3, nodes.Const)
3889 assert inferred3.value == 43
3890
3891 ast_node4 = extract_node("int.__new__()")
3892 with pytest.raises(InferenceError):
3893 next(ast_node4.infer())
3894
3895 ast_node5 = extract_node("""
3896 class A: pass
3897 A.__new__(A()) #@
3898 """)
3899 with pytest.raises(InferenceError):
3900 next(ast_node5.infer())
3901
3902 ast_nodes6 = extract_node("""
3903 class A: pass
3904 class B(A): pass
3905 class C: pass
3906 A.__new__(A) #@
3907 A.__new__(B) #@
3908 B.__new__(A) #@
3909 B.__new__(B) #@
3910 C.__new__(A) #@
3911 """)
3912 instance_A1 = next(ast_nodes6[0].infer())
3913 assert instance_A1._proxied.name == "A"
3914 instance_B1 = next(ast_nodes6[1].infer())
3915 assert instance_B1._proxied.name == "B"
3916 instance_A2 = next(ast_nodes6[2].infer())
3917 assert instance_A2._proxied.name == "A"
3918 instance_B2 = next(ast_nodes6[3].infer())
3919 assert instance_B2._proxied.name == "B"
3920 instance_A3 = next(ast_nodes6[4].infer())
3921 assert instance_A3._proxied.name == "A"
3922
3923 ast_nodes7 = extract_node("""
3924 import enum
3925 class A(enum.EnumMeta): pass
3926 class B(enum.EnumMeta):
3927 def __new__(mcs, value, **kwargs):
3928 return super().__new__(mcs, "str", (enum.Enum,), enum._EnumDict(), **kwargs)
3929 class C(enum.EnumMeta):
3930 def __new__(mcs, **kwargs):
3931 return super().__new__(A, "str", (enum.Enum,), enum._EnumDict(), **kwargs)
3932 B("") #@
3933 C() #@
3934 """)
3935 instance_B = next(ast_nodes7[0].infer())
3936 assert instance_B._proxied.name == "B"
3937 instance_C = next(ast_nodes7[1].infer())
3938 # TODO: This should be A. However, we don't infer EnumMeta.__new__
3939 # correctly.
3940 assert instance_C._proxied.name == "C"
3941
3942 @pytest.mark.xfail(reason="Does not support function metaclasses")
3943 def test_function_metaclasses(self):
3944 # These are not supported right now, although
3945 # they will be in the future.
3946 ast_node = extract_node("""
3947 class BookMeta(type):
3948 author = 'Rushdie'
3949
3950 def metaclass_function(*args):
3951 return BookMeta
3952
3953 class Book(object, metaclass=metaclass_function):
3954 pass
3955 Book #@
3956 """)
3957 inferred = next(ast_node.infer())
3958 metaclass = inferred.metaclass()
3959 self.assertIsInstance(metaclass, nodes.ClassDef)
3960 self.assertEqual(metaclass.name, "BookMeta")
3961 author = next(inferred.igetattr("author"))
3962 self.assertIsInstance(author, nodes.Const)
3963 self.assertEqual(author.value, "Rushdie")
3964
3965 def test_subscript_inference_error(self) -> None:
3966 # Used to raise StopIteration
3967 ast_node = extract_node("""
3968 class AttributeDict(dict):
3969 def __getitem__(self, name):
3970 return self
3971 flow = AttributeDict()
3972 flow['app'] = AttributeDict()
3973 flow['app']['config'] = AttributeDict()
3974 flow['app']['config']['doffing'] = AttributeDict() #@
3975 """)
3976 self.assertIsInstance(util.safe_infer(ast_node.targets[0]), Instance)
3977
3978 def test_classmethod_inferred_by_context(self) -> None:
3979 ast_node = extract_node("""
3980 class Super(object):
3981 def instance(cls):
3982 return cls()
3983 instance = classmethod(instance)
3984
3985 class Sub(Super):
3986 def method(self):
3987 return self
3988
3989 # should see the Sub.instance() is returning a Sub
3990 # instance, not a Super instance
3991 Sub.instance().method() #@
3992 """)
3993 inferred = next(ast_node.infer())
3994 self.assertIsInstance(inferred, Instance)
3995 self.assertEqual(inferred.name, "Sub")
3996
3997 def test_infer_call_result_invalid_dunder_call_on_instance(self) -> None:
3998 ast_nodes = extract_node("""
3999 class A:
4000 __call__ = 42
4001 class B:
4002 __call__ = A()
4003 class C:
4004 __call = None
4005 A() #@
4006 B() #@
4007 C() #@
4008 """)
4009 for node in ast_nodes:
4010 inferred = next(node.infer())
4011 self.assertRaises(InferenceError, next, inferred.infer_call_result(node))
4012
4013 def test_infer_call_result_same_proxied_class(self) -> None:
4014 node = extract_node("""
4015 class A:
4016 __call__ = A()
4017 A() #@
4018 """)
4019 inferred = next(node.infer())
4020 fully_evaluated_inference_results = list(inferred.infer_call_result(node))
4021 assert fully_evaluated_inference_results[0].name == "A"
4022
4023 def test_infer_call_result_with_metaclass(self) -> None:
4024 node = extract_node("def with_metaclass(meta, *bases): return 42")
4025 inferred = next(node.infer_call_result(caller=node))
4026 self.assertIsInstance(inferred, nodes.Const)
4027
4028 def test_context_call_for_context_managers(self) -> None:
4029 ast_nodes = extract_node("""
4030 class A:
4031 def __enter__(self):
4032 return self
4033 class B:
4034 __enter__ = lambda self: self
4035 class C:
4036 @property
4037 def a(self): return A()
4038 def __enter__(self):
4039 return self.a
4040 with A() as a:
4041 a #@
4042 with B() as b:
4043 b #@
4044 with C() as c:
4045 c #@
4046 """)
4047 assert isinstance(ast_nodes, list)
4048 first_a = next(ast_nodes[0].infer())
4049 self.assertIsInstance(first_a, Instance)
4050 self.assertEqual(first_a.name, "A")
4051 second_b = next(ast_nodes[1].infer())
4052 self.assertIsInstance(second_b, Instance)
4053 self.assertEqual(second_b.name, "B")
4054 third_c = next(ast_nodes[2].infer())
4055 self.assertIsInstance(third_c, Instance)
4056 self.assertEqual(third_c.name, "A")
4057
4058 def test_metaclass_subclasses_arguments_are_classes_not_instances(self) -> None:
4059 ast_node = extract_node("""
4060 class A(type):
4061 def test(cls):
4062 return cls
4063 class B(object, metaclass=A):
4064 pass
4065
4066 B.test() #@
4067 """)
4068 inferred = next(ast_node.infer())
4069 self.assertIsInstance(inferred, nodes.ClassDef)
4070 self.assertEqual(inferred.name, "B")
4071
4072 @unittest.skipUnless(HAS_SIX, "These tests require the six library")
4073 def test_with_metaclass_subclasses_arguments_are_classes_not_instances(self):
4074 ast_node = extract_node("""
4075 class A(type):
4076 def test(cls):
4077 return cls
4078 import six
4079 class B(six.with_metaclass(A)):
4080 pass
4081
4082 B.test() #@
4083 """)
4084 inferred = next(ast_node.infer())
4085 self.assertIsInstance(inferred, nodes.ClassDef)
4086 self.assertEqual(inferred.name, "B")
4087
4088 @unittest.skipUnless(HAS_SIX, "These tests require the six library")
4089 def test_with_metaclass_with_partial_imported_name(self):
4090 ast_node = extract_node("""
4091 class A(type):
4092 def test(cls):
4093 return cls
4094 from six import with_metaclass
4095 class B(with_metaclass(A)):
4096 pass
4097
4098 B.test() #@
4099 """)
4100 inferred = next(ast_node.infer())
4101 self.assertIsInstance(inferred, nodes.ClassDef)
4102 self.assertEqual(inferred.name, "B")
4103
4104 def test_infer_cls_in_class_methods(self) -> None:
4105 ast_nodes = extract_node("""
4106 class A(type):
4107 def __call__(cls):
4108 cls #@
4109 class B(object):
4110 def __call__(cls):
4111 cls #@
4112 """)
4113 assert isinstance(ast_nodes, list)
4114 first = next(ast_nodes[0].infer())
4115 self.assertIsInstance(first, nodes.ClassDef)
4116 second = next(ast_nodes[1].infer())
4117 self.assertIsInstance(second, Instance)
4118
4119 @pytest.mark.xfail(reason="Metaclass arguments not inferred as classes")
4120 def test_metaclass_arguments_are_classes_not_instances(self):
4121 ast_node = extract_node("""
4122 class A(type):
4123 def test(cls): return cls
4124 A.test() #@
4125 """)
4126 # This is not supported yet
4127 inferred = next(ast_node.infer())
4128 self.assertIsInstance(inferred, nodes.ClassDef)
4129 self.assertEqual(inferred.name, "A")
4130
4131 def test_metaclass_with_keyword_args(self) -> None:
4132 ast_node = extract_node("""
4133 class TestMetaKlass(type):
4134 def __new__(mcs, name, bases, ns, kwo_arg):
4135 return super().__new__(mcs, name, bases, ns)
4136
4137 class TestKlass(metaclass=TestMetaKlass, kwo_arg=42): #@
4138 pass
4139 """)
4140 inferred = next(ast_node.infer())
4141 self.assertIsInstance(inferred, nodes.ClassDef)
4142
4143 def test_metaclass_custom_dunder_call(self) -> None:
4144 """The Metaclass __call__ should take precedence
4145 over the default metaclass type call (initialization).
4146
4147 See https://github.com/pylint-dev/pylint/issues/2159
4148 """
4149 val = extract_node("""
4150 class _Meta(type):
4151 def __call__(cls):
4152 return 1
4153 class Clazz(metaclass=_Meta):
4154 def __call__(self):
4155 return 5.5
4156
4157 Clazz() #@
4158 """).inferred()[0].value
4159 assert val == 1
4160
4161 def test_metaclass_custom_dunder_call_boundnode(self) -> None:
4162 """The boundnode should be the calling class."""
4163 cls = extract_node("""
4164 class _Meta(type):
4165 def __call__(cls):
4166 return cls
4167 class Clazz(metaclass=_Meta):
4168 pass
4169 Clazz() #@
4170 """).inferred()[0]
4171 assert isinstance(cls, Instance) and cls.name == "Clazz"
4172
4173 def test_infer_subclass_attr_outer_class(self) -> None:
4174 node = extract_node("""
4175 class Outer:
4176 data = 123
4177
4178 class Test(Outer):
4179 pass
4180 Test.data
4181 """)
4182 inferred = next(node.infer())
4183 assert isinstance(inferred, nodes.Const)
4184 assert inferred.value == 123
4185
4186 def test_infer_subclass_attr_inner_class_works_indirectly(self) -> None:
4187 node = extract_node("""
4188 class Outer:
4189 class Inner:
4190 data = 123
4191 Inner = Outer.Inner
4192
4193 class Test(Inner):
4194 pass
4195 Test.data
4196 """)
4197 inferred = next(node.infer())
4198 assert isinstance(inferred, nodes.Const)
4199 assert inferred.value == 123
4200
4201 def test_infer_subclass_attr_inner_class(self) -> None:
4202 clsdef_node, attr_node = extract_node("""
4203 class Outer:
4204 class Inner:
4205 data = 123
4206
4207 class Test(Outer.Inner):
4208 pass
4209 Test #@
4210 Test.data #@
4211 """)
4212 clsdef = next(clsdef_node.infer())
4213 assert isinstance(clsdef, nodes.ClassDef)
4214 inferred = next(clsdef.igetattr("data"))
4215 assert isinstance(inferred, nodes.Const)
4216 assert inferred.value == 123
4217 # Inferring the value of .data via igetattr() worked before the
4218 # old_boundnode fixes in infer_subscript, so it should have been
4219 # possible to infer the subscript directly. It is the difference
4220 # between these two cases that led to the discovery of the cause of the
4221 # bug in https://github.com/pylint-dev/astroid/issues/904
4222 inferred = next(attr_node.infer())
4223 assert isinstance(inferred, nodes.Const)
4224 assert inferred.value == 123
4225
4226 def test_infer_method_empty_body(self) -> None:
4227 # https://github.com/PyCQA/astroid/issues/1015
4228 node = extract_node("""
4229 class A:
4230 def foo(self): ...
4231
4232 A().foo() #@
4233 """)
4234 inferred = next(node.infer())
4235 assert isinstance(inferred, nodes.Const)
4236 assert inferred.value is None
4237
4238 def test_infer_method_overload(self) -> None:
4239 # https://github.com/PyCQA/astroid/issues/1015
4240 node = extract_node("""
4241 class A:
4242 def foo(self): ...
4243
4244 def foo(self):
4245 yield
4246
4247 A().foo() #@
4248 """)
4249 inferred = list(node.infer())
4250 assert len(inferred) == 1
4251 assert isinstance(inferred[0], Generator)
4252
4253 def test_infer_function_under_if(self) -> None:
4254 node = extract_node("""
4255 if 1 in [1]:
4256 def func():
4257 return 42
4258 else:
4259 def func():
4260 return False
4261
4262 func() #@
4263 """)
4264 inferred = list(node.inferred())
4265 assert [const.value for const in inferred] == [42, False]
4266
4267 def test_infer_property_setter(self) -> None:
4268 node = extract_node("""
4269 class PropertyWithSetter:
4270 @property
4271 def host(self):
4272 return self._host
4273
4274 @host.setter
4275 def host(self, value: str):
4276 self._host = value
4277
4278 PropertyWithSetter().host #@
4279 """)
4280 assert not isinstance(next(node.infer()), Instance)
4281
4282 def test_delayed_attributes_without_slots(self) -> None:
4283 ast_node = extract_node("""
4284 class A(object):
4285 __slots__ = ('a', )
4286 a = A()
4287 a.teta = 24
4288 a.a = 24
4289 a #@
4290 """)
4291 inferred = next(ast_node.infer())
4292 with self.assertRaises(NotFoundError):
4293 inferred.getattr("teta")
4294 inferred.getattr("a")
4295
4296 def test_lambda_as_methods(self) -> None:
4297 ast_node = extract_node("""
4298 class X:
4299 m = lambda self, arg: self.z + arg
4300 z = 24
4301
4302 X().m(4) #@
4303 """)
4304 inferred = next(ast_node.infer())
4305 self.assertIsInstance(inferred, nodes.Const)
4306 self.assertEqual(inferred.value, 28)
4307
4308 def test_inner_value_redefined_by_subclass(self) -> None:
4309 ast_node = extract_node("""
4310 class X(object):
4311 M = lambda self, arg: "a"
4312 x = 24
4313 def __init__(self):
4314 x = 24
4315 self.m = self.M(x)
4316
4317 class Y(X):
4318 M = lambda self, arg: arg + 1
4319 def blurb(self):
4320 self.m #@
4321 """)
4322 inferred = next(ast_node.infer())
4323 self.assertIsInstance(inferred, nodes.Const)
4324 self.assertEqual(inferred.value, 25)
4325
4326 def test_inner_value_redefined_by_subclass_with_mro(self) -> None:
4327 ast_node = extract_node("""
4328 class X(object):
4329 M = lambda self, arg: arg + 1
4330 x = 24
4331 def __init__(self):
4332 y = self
4333 self.m = y.M(1) + y.z
4334
4335 class C(object):
4336 z = 24
4337
4338 class Y(X, C):
4339 M = lambda self, arg: arg + 1
4340 def blurb(self):
4341 self.m #@
4342 """)
4343 inferred = next(ast_node.infer())
4344 assert isinstance(inferred, nodes.Const)
4345 assert inferred.value == 26
4346
4347 def test_getitem_of_class_raised_type_error(self) -> None:
4348 # Test that we wrap an AttributeInferenceError
4349 # and reraise it as a TypeError in Class.getitem
4350 node = extract_node("""
4351 def test(): ...
4352 test()
4353 """)
4354 inferred = next(node.infer())
4355 with self.assertRaises(AstroidTypeError):
4356 inferred.getitem(nodes.Const("4"))
4357
4358 def test_getitem_of_class_with_non_class_metaclass(self) -> None:
4359 """A metaclass that infers to a non-class node has no MRO to search.
4360
4361 Regression test for https://github.com/pylint-dev/astroid/issues/3063
4362 """
4363 node = extract_node("""
4364 def fn():
4365 pass
4366 class C(metaclass=fn): #@
4367 pass
4368 """)
4369 with self.assertRaises(AstroidTypeError):
4370 node.getitem(nodes.Const(0))
4371
4372 def test_getitem_with_non_callable_class_getitem(self) -> None:
4373 """``__class_getitem__`` may resolve to a non-callable node (e.g. an
4374 ``AssignName`` or an ``Import``), which has no ``infer_call_result``.
4375
4376 Regression test for https://github.com/pylint-dev/astroid/issues/3064
4377 """
4378 for body in (
4379 "__class_getitem__ = classmethod(tuple)",
4380 "import os as __class_getitem__",
4381 "from os import getcwd as __class_getitem__",
4382 ):
4383 node = extract_node(f"""
4384 class C: #@
4385 {body}
4386 """)
4387 with self.assertRaises(AstroidTypeError):
4388 node.getitem(nodes.Const(0))
4389
4390 def test_infer_arg_called_type_is_uninferable(self) -> None:
4391 node = extract_node("""
4392 def func(type):
4393 type #@
4394 """)
4395 inferred = next(node.infer())
4396 assert inferred is util.Uninferable
4397
4398 def test_infer_arg_called_object_when_used_as_index_is_uninferable(self) -> None:
4399 node = extract_node("""
4400 def func(object):
4401 ['list'][
4402 object #@
4403 ]
4404 """)
4405 inferred = next(node.infer())
4406 assert inferred is util.Uninferable
4407
4408 def test_infer_arg_called_type_when_used_as_index_is_uninferable(self):
4409 # https://github.com/pylint-dev/astroid/pull/958
4410 node = extract_node("""
4411 def func(type):
4412 ['list'][
4413 type #@
4414 ]
4415 """)
4416 inferred = next(node.infer())
4417 assert not isinstance(inferred, nodes.ClassDef) # was inferred as builtins.type
4418 assert inferred is util.Uninferable
4419
4420 def test_infer_arg_called_type_when_used_as_subscript_is_uninferable(self):
4421 # https://github.com/pylint-dev/astroid/pull/958
4422 node = extract_node("""
4423 def func(type):
4424 type[0] #@
4425 """)
4426 inferred = next(node.infer())
4427 assert not isinstance(inferred, nodes.ClassDef) # was inferred as builtins.type
4428 assert inferred is util.Uninferable
4429
4430 def test_infer_arg_called_type_defined_in_outer_scope_is_uninferable(self):
4431 # https://github.com/pylint-dev/astroid/pull/958
4432 node = extract_node("""
4433 def outer(type):
4434 def inner():
4435 type[0] #@
4436 """)
4437 inferred = next(node.infer())
4438 assert not isinstance(inferred, nodes.ClassDef) # was inferred as builtins.type
4439 assert inferred is util.Uninferable
4440
4441 def test_infer_subclass_attr_instance_attr_indirect(self) -> None:
4442 node = extract_node("""
4443 class Parent:
4444 def __init__(self):
4445 self.data = 123
4446
4447 class Test(Parent):
4448 pass
4449 t = Test()
4450 t
4451 """)
4452 inferred = next(node.infer())
4453 assert isinstance(inferred, Instance)
4454 const = next(inferred.igetattr("data"))
4455 assert isinstance(const, nodes.Const)
4456 assert const.value == 123
4457
4458 def test_infer_subclass_attr_instance_attr(self) -> None:
4459 node = extract_node("""
4460 class Parent:
4461 def __init__(self):
4462 self.data = 123
4463
4464 class Test(Parent):
4465 pass
4466 t = Test()
4467 t.data
4468 """)
4469 inferred = next(node.infer())
4470 assert isinstance(inferred, nodes.Const)
4471 assert inferred.value == 123
4472
4473 def test_uninferable_type_subscript(self) -> None:
4474 node = extract_node("[type for type in [] if type['id']]")
4475 with self.assertRaises(InferenceError):
4476 _ = next(node.infer())
4477
4478
4479 class GetattrTest(unittest.TestCase):
4480 def test_yes_when_unknown(self) -> None:
4481 ast_nodes = extract_node("""
4482 from missing import Missing
4483 getattr(1, Unknown) #@
4484 getattr(Unknown, 'a') #@
4485 getattr(Unknown, Unknown) #@
4486 getattr(Unknown, Unknown, Unknown) #@
4487
4488 getattr(Missing, 'a') #@
4489 getattr(Missing, Missing) #@
4490 getattr('a', Missing) #@
4491 getattr('a', Missing, Missing) #@
4492 """)
4493 for node in ast_nodes[:4]:
4494 self.assertRaises(InferenceError, next, node.infer())
4495
4496 for node in ast_nodes[4:]:
4497 inferred = next(node.infer())
4498 self.assertEqual(inferred, util.Uninferable, node)
4499
4500 def test_attrname_not_string(self) -> None:
4501 ast_nodes = extract_node("""
4502 getattr(1, 1) #@
4503 c = int
4504 getattr(1, c) #@
4505 """)
4506 for node in ast_nodes:
4507 self.assertRaises(InferenceError, next, node.infer())
4508
4509 def test_attribute_missing(self) -> None:
4510 ast_nodes = extract_node("""
4511 getattr(1, 'ala') #@
4512 getattr(int, 'ala') #@
4513 getattr(float, 'bala') #@
4514 getattr({}, 'portocala') #@
4515 """)
4516 for node in ast_nodes:
4517 self.assertRaises(InferenceError, next, node.infer())
4518
4519 def test_default(self) -> None:
4520 ast_nodes = extract_node("""
4521 getattr(1, 'ala', None) #@
4522 getattr(int, 'bala', int) #@
4523 getattr(int, 'bala', getattr(int, 'portocala', None)) #@
4524 """)
4525 assert isinstance(ast_nodes, list)
4526 first = next(ast_nodes[0].infer())
4527 self.assertIsInstance(first, nodes.Const)
4528 self.assertIsNone(first.value)
4529
4530 second = next(ast_nodes[1].infer())
4531 self.assertIsInstance(second, nodes.ClassDef)
4532 self.assertEqual(second.qname(), "builtins.int")
4533
4534 third = next(ast_nodes[2].infer())
4535 self.assertIsInstance(third, nodes.Const)
4536 self.assertIsNone(third.value)
4537
4538 def test_lookup(self) -> None:
4539 ast_nodes = extract_node("""
4540 class A(object):
4541 def test(self): pass
4542 class B(A):
4543 def test_b(self): pass
4544 class C(A): pass
4545 class E(C, B):
4546 def test_e(self): pass
4547
4548 getattr(A(), 'test') #@
4549 getattr(A, 'test') #@
4550 getattr(E(), 'test_b') #@
4551 getattr(E(), 'test') #@
4552
4553 class X(object):
4554 def test(self):
4555 getattr(self, 'test') #@
4556 """)
4557 assert isinstance(ast_nodes, list)
4558 first = next(ast_nodes[0].infer())
4559 self.assertIsInstance(first, BoundMethod)
4560 self.assertEqual(first.bound.name, "A")
4561
4562 second = next(ast_nodes[1].infer())
4563 self.assertIsInstance(second, UnboundMethod)
4564 self.assertIsInstance(second.parent, nodes.ClassDef)
4565 self.assertEqual(second.parent.name, "A")
4566
4567 third = next(ast_nodes[2].infer())
4568 self.assertIsInstance(third, BoundMethod)
4569 # Bound to E, but the provider is B.
4570 self.assertEqual(third.bound.name, "E")
4571 self.assertEqual(third._proxied._proxied.parent.name, "B")
4572
4573 fourth = next(ast_nodes[3].infer())
4574 self.assertIsInstance(fourth, BoundMethod)
4575 self.assertEqual(fourth.bound.name, "E")
4576 self.assertEqual(third._proxied._proxied.parent.name, "B")
4577
4578 fifth = next(ast_nodes[4].infer())
4579 self.assertIsInstance(fifth, BoundMethod)
4580 self.assertEqual(fifth.bound.name, "X")
4581
4582 def test_lambda(self) -> None:
4583 node = extract_node("""
4584 getattr(lambda x: x, 'f') #@
4585 """)
4586 inferred = next(node.infer())
4587 self.assertEqual(inferred, util.Uninferable)
4588
4589
4590 class HasattrTest(unittest.TestCase):
4591 def test_inference_errors(self) -> None:
4592 ast_nodes = extract_node("""
4593 from missing import Missing
4594
4595 hasattr(Unknown, 'ala') #@
4596
4597 hasattr(Missing, 'bala') #@
4598 hasattr('portocala', Missing) #@
4599 """)
4600 for node in ast_nodes:
4601 inferred = next(node.infer())
4602 self.assertEqual(inferred, util.Uninferable)
4603
4604 def test_attribute_is_missing(self) -> None:
4605 ast_nodes = extract_node("""
4606 class A: pass
4607 hasattr(int, 'ala') #@
4608 hasattr({}, 'bala') #@
4609 hasattr(A(), 'portocala') #@
4610 """)
4611 for node in ast_nodes:
4612 inferred = next(node.infer())
4613 self.assertIsInstance(inferred, nodes.Const)
4614 self.assertFalse(inferred.value)
4615
4616 def test_attribute_is_not_missing(self) -> None:
4617 ast_nodes = extract_node("""
4618 class A(object):
4619 def test(self): pass
4620 class B(A):
4621 def test_b(self): pass
4622 class C(A): pass
4623 class E(C, B):
4624 def test_e(self): pass
4625
4626 hasattr(A(), 'test') #@
4627 hasattr(A, 'test') #@
4628 hasattr(E(), 'test_b') #@
4629 hasattr(E(), 'test') #@
4630
4631 class X(object):
4632 def test(self):
4633 hasattr(self, 'test') #@
4634 """)
4635 for node in ast_nodes:
4636 inferred = next(node.infer())
4637 self.assertIsInstance(inferred, nodes.Const)
4638 self.assertTrue(inferred.value)
4639
4640 def test_lambda(self) -> None:
4641 node = extract_node("""
4642 hasattr(lambda x: x, 'f') #@
4643 """)
4644 inferred = next(node.infer())
4645 self.assertIsInstance(inferred, nodes.Const)
4646 self.assertIs(inferred.value, False)
4647
4648
4649 class BoolOpTest(unittest.TestCase):
4650 def test_bool_ops(self) -> None:
4651 expected = [
4652 ("1 and 2", 2),
4653 ("0 and 2", 0),
4654 ("1 or 2", 1),
4655 ("0 or 2", 2),
4656 ("0 or 0 or 1", 1),
4657 ("1 and 2 and 3", 3),
4658 ("1 and 2 or 3", 2),
4659 ("1 and 0 or 3", 3),
4660 ("1 or 0 and 2", 1),
4661 ("(1 and 2) and (2 and 3)", 3),
4662 ("not 2 and 3", False),
4663 ("2 and not 3", False),
4664 ("not 0 and 3", 3),
4665 ("True and False", False),
4666 ("not (True or False) and True", False),
4667 ]
4668 for code, expected_value in expected:
4669 node = extract_node(code)
4670 inferred = next(node.infer())
4671 self.assertEqual(inferred.value, expected_value)
4672
4673 def test_yes_when_unknown(self) -> None:
4674 ast_nodes = extract_node("""
4675 from unknown import unknown, any, not_any
4676 0 and unknown #@
4677 unknown or 0 #@
4678 any or not_any and unknown #@
4679 """)
4680 for node in ast_nodes:
4681 inferred = next(node.infer())
4682 self.assertEqual(inferred, util.Uninferable)
4683
4684 def test_other_nodes(self) -> None:
4685 ast_nodes = extract_node("""
4686 def test(): pass
4687 test and 0 #@
4688 1 and test #@
4689 """)
4690 assert isinstance(ast_nodes, list)
4691 first = next(ast_nodes[0].infer())
4692 self.assertEqual(first.value, 0)
4693 second = next(ast_nodes[1].infer())
4694 self.assertIsInstance(second, nodes.FunctionDef)
4695 self.assertEqual(second.name, "test")
4696
4697
4698 class TestCallable(unittest.TestCase):
4699 def test_callable(self) -> None:
4700 expected = [
4701 ("callable(len)", True),
4702 ('callable("a")', False),
4703 ("callable(callable)", True),
4704 ("callable(lambda x, y: x+y)", True),
4705 ("import os; __(callable(os))", False),
4706 ("callable(int)", True),
4707 (
4708 """
4709 def test(): pass
4710 callable(test) #@""",
4711 True,
4712 ),
4713 (
4714 """
4715 class C1:
4716 def meth(self): pass
4717 callable(C1) #@""",
4718 True,
4719 ),
4720 ]
4721 for code, expected_value in expected:
4722 node = extract_node(code)
4723 inferred = next(node.infer())
4724 self.assertEqual(inferred.value, expected_value)
4725
4726 def test_callable_methods(self) -> None:
4727 ast_nodes = extract_node("""
4728 class C:
4729 def test(self): pass
4730 @staticmethod
4731 def static(): pass
4732 @classmethod
4733 def class_method(cls): pass
4734 def __call__(self): pass
4735 class D(C):
4736 pass
4737 class NotReallyCallableDueToPythonMisfeature(object):
4738 __call__ = 42
4739 callable(C.test) #@
4740 callable(C.static) #@
4741 callable(C.class_method) #@
4742 callable(C().test) #@
4743 callable(C().static) #@
4744 callable(C().class_method) #@
4745 C #@
4746 C() #@
4747 NotReallyCallableDueToPythonMisfeature() #@
4748 staticmethod #@
4749 classmethod #@
4750 property #@
4751 D #@
4752 D() #@
4753 """)
4754 for node in ast_nodes:
4755 inferred = next(node.infer())
4756 self.assertTrue(inferred)
4757
4758 def test_inference_errors(self) -> None:
4759 ast_nodes = extract_node("""
4760 from unknown import unknown
4761 callable(unknown) #@
4762 def test():
4763 return unknown
4764 callable(test()) #@
4765 """)
4766 for node in ast_nodes:
4767 inferred = next(node.infer())
4768 self.assertEqual(inferred, util.Uninferable)
4769
4770 def test_not_callable(self) -> None:
4771 ast_nodes = extract_node("""
4772 callable("") #@
4773 callable(1) #@
4774 callable(True) #@
4775 """)
4776 for node in ast_nodes:
4777 inferred = next(node.infer())
4778 self.assertFalse(inferred.value)
4779
4780
4781 class TestBool(unittest.TestCase):
4782 def test_bool(self) -> None:
4783 pairs = [
4784 ("bool()", False),
4785 ("bool(1)", True),
4786 ("bool(0)", False),
4787 ("bool([])", False),
4788 ("bool([1])", True),
4789 ("bool({})", False),
4790 ("bool(True)", True),
4791 ("bool(False)", False),
4792 ("bool(None)", False),
4793 ("from unknown import Unknown; __(bool(Unknown))", util.Uninferable),
4794 ]
4795 for code, expected in pairs:
4796 node = extract_node(code)
4797 inferred = next(node.infer())
4798 if expected is util.Uninferable:
4799 self.assertEqual(expected, inferred)
4800 else:
4801 self.assertEqual(inferred.value, expected)
4802
4803 def test_bool_bool_special_method(self) -> None:
4804 ast_nodes = extract_node("""
4805 class FalseClass:
4806 def __bool__(self):
4807 return False
4808 class TrueClass:
4809 def __bool__(self):
4810 return True
4811 class C(object):
4812 def __call__(self):
4813 return False
4814 class B(object):
4815 __bool__ = C()
4816 class LambdaBoolFalse(object):
4817 __bool__ = lambda self: self.foo
4818 @property
4819 def foo(self): return 0
4820 class FalseBoolLen(object):
4821 __len__ = lambda self: self.foo
4822 @property
4823 def foo(self): return 0
4824 bool(FalseClass) #@
4825 bool(TrueClass) #@
4826 bool(FalseClass()) #@
4827 bool(TrueClass()) #@
4828 bool(B()) #@
4829 bool(LambdaBoolFalse()) #@
4830 bool(FalseBoolLen()) #@
4831 """)
4832 expected = [True, True, False, True, False, False, False]
4833 for node, expected_value in zip(ast_nodes, expected):
4834 inferred = next(node.infer())
4835 self.assertEqual(inferred.value, expected_value)
4836
4837 def test_bool_instance_not_callable(self) -> None:
4838 ast_nodes = extract_node("""
4839 class BoolInvalid(object):
4840 __bool__ = 42
4841 class LenInvalid(object):
4842 __len__ = "a"
4843 bool(BoolInvalid()) #@
4844 bool(LenInvalid()) #@
4845 """)
4846 for node in ast_nodes:
4847 inferred = next(node.infer())
4848 self.assertEqual(inferred, util.Uninferable)
4849
4850 def test_class_subscript(self) -> None:
4851 node = extract_node("""
4852 class Foo:
4853 def __class_getitem__(cls, *args, **kwargs):
4854 return cls
4855
4856 Foo[int]
4857 """)
4858 inferred = next(node.infer())
4859 self.assertIsInstance(inferred, nodes.ClassDef)
4860 self.assertEqual(inferred.name, "Foo")
4861
4862 def test_class_subscript_inference_context(self) -> None:
4863 """Context path has a reference to any parents inferred by getitem()."""
4864 code = """
4865 class Parent: pass
4866
4867 class A(Parent):
4868 def __class_getitem__(self, value):
4869 return cls
4870 """
4871 klass = extract_node(code)
4872 context = InferenceContext()
4873 # For this test, we want a fresh inference, rather than a cache hit on
4874 # the inference done at brain time in _is_enum_subclass()
4875 context.lookupname = "Fresh lookup!"
4876 _ = klass.getitem(0, context=context)
4877
4878 assert next(iter(context.path))[0].name == "Parent"
4879
4880
4881 class TestType(unittest.TestCase):
4882 def test_type(self) -> None:
4883 pairs = [
4884 ("type(1)", "int"),
4885 ("type(type)", "type"),
4886 ("type(None)", "NoneType"),
4887 ("type(object)", "type"),
4888 ("type(dict())", "dict"),
4889 ("type({})", "dict"),
4890 ("type(frozenset())", "frozenset"),
4891 ]
4892 for code, expected in pairs:
4893 node = extract_node(code)
4894 inferred = next(node.infer())
4895 self.assertIsInstance(inferred, nodes.ClassDef)
4896 self.assertEqual(inferred.name, expected)
4897
4898
4899 class ArgumentsTest(unittest.TestCase):
4900 @staticmethod
4901 def _get_dict_value(
4902 inferred: dict,
4903 ) -> list[tuple[str, int]] | list[tuple[str, str]]:
4904 items = inferred.items
4905 return sorted((key.value, value.value) for key, value in items)
4906
4907 @staticmethod
4908 def _get_tuple_value(inferred: tuple) -> tuple[int, ...]:
4909 elts = inferred.elts
4910 return tuple(elt.value for elt in elts)
4911
4912 def test_args(self) -> None:
4913 expected_values = [
4914 (),
4915 (1,),
4916 (2, 3),
4917 (4, 5),
4918 (3,),
4919 (),
4920 (3, 4, 5),
4921 (),
4922 (),
4923 (4,),
4924 (4, 5),
4925 (),
4926 (3,),
4927 (),
4928 (),
4929 (3,),
4930 (42,),
4931 ]
4932 ast_nodes = extract_node("""
4933 def func(*args):
4934 return args
4935 func() #@
4936 func(1) #@
4937 func(2, 3) #@
4938 func(*(4, 5)) #@
4939 def func(a, b, *args):
4940 return args
4941 func(1, 2, 3) #@
4942 func(1, 2) #@
4943 func(1, 2, 3, 4, 5) #@
4944 def func(a, b, c=42, *args):
4945 return args
4946 func(1, 2) #@
4947 func(1, 2, 3) #@
4948 func(1, 2, 3, 4) #@
4949 func(1, 2, 3, 4, 5) #@
4950 func = lambda a, b, *args: args
4951 func(1, 2) #@
4952 func(1, 2, 3) #@
4953 func = lambda a, b=42, *args: args
4954 func(1) #@
4955 func(1, 2) #@
4956 func(1, 2, 3) #@
4957 func(1, 2, *(42, )) #@
4958 """)
4959 for node, expected_value in zip(ast_nodes, expected_values):
4960 inferred = next(node.infer())
4961 self.assertIsInstance(inferred, nodes.Tuple)
4962 self.assertEqual(self._get_tuple_value(inferred), expected_value)
4963
4964 def test_multiple_starred_args(self) -> None:
4965 expected_values = [(1, 2, 3), (1, 4, 2, 3, 5, 6, 7)]
4966 ast_nodes = extract_node("""
4967 def func(a, b, *args):
4968 return args
4969 func(1, 2, *(1, ), *(2, 3)) #@
4970 func(1, 2, *(1, ), 4, *(2, 3), 5, *(6, 7)) #@
4971 """)
4972 for node, expected_value in zip(ast_nodes, expected_values):
4973 inferred = next(node.infer())
4974 self.assertIsInstance(inferred, nodes.Tuple)
4975 self.assertEqual(self._get_tuple_value(inferred), expected_value)
4976
4977 def test_defaults(self) -> None:
4978 expected_values = [42, 3, 41, 42]
4979 ast_nodes = extract_node("""
4980 def func(a, b, c=42, *args):
4981 return c
4982 func(1, 2) #@
4983 func(1, 2, 3) #@
4984 func(1, 2, c=41) #@
4985 func(1, 2, 42, 41) #@
4986 """)
4987 for node, expected_value in zip(ast_nodes, expected_values):
4988 inferred = next(node.infer())
4989 self.assertIsInstance(inferred, nodes.Const)
4990 self.assertEqual(inferred.value, expected_value)
4991
4992 def test_kwonly_args(self) -> None:
4993 expected_values = [24, 24, 42, 23, 24, 24, 54]
4994 ast_nodes = extract_node("""
4995 def test(*, f, b): return f
4996 test(f=24, b=33) #@
4997 def test(a, *, f): return f
4998 test(1, f=24) #@
4999 def test(a, *, f=42): return f
5000 test(1) #@
5001 test(1, f=23) #@
5002 def test(a, b, c=42, *args, f=24):
5003 return f
5004 test(1, 2, 3) #@
5005 test(1, 2, 3, 4) #@
5006 test(1, 2, 3, 4, 5, f=54) #@
5007 """)
5008 for node, expected_value in zip(ast_nodes, expected_values):
5009 inferred = next(node.infer())
5010 self.assertIsInstance(inferred, nodes.Const)
5011 self.assertEqual(inferred.value, expected_value)
5012
5013 def test_kwargs(self) -> None:
5014 expected = [[("a", 1), ("b", 2), ("c", 3)], [("a", 1)], [("a", "b")]]
5015 ast_nodes = extract_node("""
5016 def test(**kwargs):
5017 return kwargs
5018 test(a=1, b=2, c=3) #@
5019 test(a=1) #@
5020 test(**{'a': 'b'}) #@
5021 """)
5022 for node, expected_value in zip(ast_nodes, expected):
5023 inferred = next(node.infer())
5024 self.assertIsInstance(inferred, nodes.Dict)
5025 value = self._get_dict_value(inferred)
5026 self.assertEqual(value, expected_value)
5027
5028 def test_kwargs_and_other_named_parameters(self) -> None:
5029 ast_nodes = extract_node("""
5030 def test(a=42, b=24, **kwargs):
5031 return kwargs
5032 test(42, 24, c=3, d=4) #@
5033 test(49, b=24, d=4) #@
5034 test(a=42, b=33, c=3, d=42) #@
5035 test(a=42, **{'c':42}) #@
5036 """)
5037 expected_values = [
5038 [("c", 3), ("d", 4)],
5039 [("d", 4)],
5040 [("c", 3), ("d", 42)],
5041 [("c", 42)],
5042 ]
5043 for node, expected_value in zip(ast_nodes, expected_values):
5044 inferred = next(node.infer())
5045 self.assertIsInstance(inferred, nodes.Dict)
5046 value = self._get_dict_value(inferred)
5047 self.assertEqual(value, expected_value)
5048
5049 def test_kwargs_access_by_name(self) -> None:
5050 expected_values = [42, 42, 42, 24]
5051 ast_nodes = extract_node("""
5052 def test(**kwargs):
5053 return kwargs['f']
5054 test(f=42) #@
5055 test(**{'f': 42}) #@
5056 test(**dict(f=42)) #@
5057 def test(f=42, **kwargs):
5058 return kwargs['l']
5059 test(l=24) #@
5060 """)
5061 for ast_node, value in zip(ast_nodes, expected_values):
5062 inferred = next(ast_node.infer())
5063 self.assertIsInstance(inferred, nodes.Const, inferred)
5064 self.assertEqual(inferred.value, value)
5065
5066 def test_multiple_kwargs(self) -> None:
5067 expected_value = [("a", 1), ("b", 2), ("c", 3), ("d", 4), ("f", 42)]
5068 ast_node = extract_node("""
5069 def test(**kwargs):
5070 return kwargs
5071 test(a=1, b=2, **{'c': 3}, **{'d': 4}, f=42) #@
5072 """)
5073 inferred = next(ast_node.infer())
5074 self.assertIsInstance(inferred, nodes.Dict)
5075 value = self._get_dict_value(inferred)
5076 self.assertEqual(value, expected_value)
5077
5078 def test_kwargs_are_overridden(self) -> None:
5079 ast_nodes = extract_node("""
5080 def test(f):
5081 return f
5082 test(f=23, **{'f': 34}) #@
5083 def test(f=None):
5084 return f
5085 test(f=23, **{'f':23}) #@
5086 """)
5087 for ast_node in ast_nodes:
5088 inferred = next(ast_node.infer())
5089 self.assertEqual(inferred, util.Uninferable)
5090
5091 def test_fail_to_infer_args(self) -> None:
5092 ast_nodes = extract_node("""
5093 def test(a, **kwargs): return a
5094 test(*missing) #@
5095 test(*object) #@
5096 test(*1) #@
5097
5098
5099 def test(**kwargs): return kwargs
5100 test(**miss) #@
5101 test(**(1, 2)) #@
5102 test(**1) #@
5103 test(**{misss:1}) #@
5104 test(**{object:1}) #@
5105 test(**{1:1}) #@
5106 test(**{'a':1, 'a':1}) #@
5107
5108 def test(a): return a
5109 test() #@
5110 test(1, 2, 3) #@
5111
5112 from unknown import unknown
5113 test(*unknown) #@
5114 def test(*args): return args
5115 test(*unknown) #@
5116 """)
5117 for node in ast_nodes:
5118 inferred = next(node.infer())
5119 self.assertEqual(inferred, util.Uninferable)
5120
5121 def test_args_overwritten(self) -> None:
5122 # https://github.com/pylint-dev/astroid/issues/180
5123 node = extract_node("""
5124 next = 42
5125 def wrapper(next=next):
5126 next = 24
5127 def test():
5128 return next
5129 return test
5130 wrapper()() #@
5131 """)
5132 assert isinstance(node, nodes.NodeNG)
5133 inferred = node.inferred()
5134 self.assertEqual(len(inferred), 1)
5135 self.assertIsInstance(inferred[0], nodes.Const, inferred[0])
5136 self.assertEqual(inferred[0].value, 24)
5137
5138
5139 class SliceTest(unittest.TestCase):
5140 def test_slice(self) -> None:
5141 ast_nodes = [
5142 ("[1, 2, 3][slice(None)]", [1, 2, 3]),
5143 ("[1, 2, 3][slice(None, None)]", [1, 2, 3]),
5144 ("[1, 2, 3][slice(None, None, None)]", [1, 2, 3]),
5145 ("[1, 2, 3][slice(1, None)]", [2, 3]),
5146 ("[1, 2, 3][slice(None, 1, None)]", [1]),
5147 ("[1, 2, 3][slice(0, 1)]", [1]),
5148 ("[1, 2, 3][slice(0, 3, 2)]", [1, 3]),
5149 ]
5150 for node, expected_value in ast_nodes:
5151 ast_node = extract_node(f"__({node})")
5152 inferred = next(ast_node.infer())
5153 self.assertIsInstance(inferred, nodes.List)
5154 self.assertEqual([elt.value for elt in inferred.elts], expected_value)
5155
5156 def test_slice_inference_error(self) -> None:
5157 ast_nodes = extract_node("""
5158 from unknown import unknown
5159 [1, 2, 3][slice(None, unknown, unknown)] #@
5160 [1, 2, 3][slice(None, missing, missing)] #@
5161 [1, 2, 3][slice(object, list, tuple)] #@
5162 [1, 2, 3][slice(b'a')] #@
5163 [1, 2, 3][slice(1, 'aa')] #@
5164 [1, 2, 3][slice(1, 2.0, 3.0)] #@
5165 [1, 2, 3][slice()] #@
5166 [1, 2, 3][slice(1, 2, 3, 4)] #@
5167 """)
5168 for node in ast_nodes:
5169 self.assertRaises(InferenceError, next, node.infer())
5170
5171 def test_slice_attributes(self) -> None:
5172 ast_nodes = [
5173 ("slice(2, 3, 4)", (2, 3, 4)),
5174 ("slice(None, None, 4)", (None, None, 4)),
5175 ("slice(None, 1, None)", (None, 1, None)),
5176 ]
5177 for code, values in ast_nodes:
5178 lower, upper, step = values
5179 node = extract_node(code)
5180 inferred = next(node.infer())
5181 self.assertIsInstance(inferred, nodes.Slice)
5182 lower_value = next(inferred.igetattr("start"))
5183 self.assertIsInstance(lower_value, nodes.Const)
5184 self.assertEqual(lower_value.value, lower)
5185 higher_value = next(inferred.igetattr("stop"))
5186 self.assertIsInstance(higher_value, nodes.Const)
5187 self.assertEqual(higher_value.value, upper)
5188 step_value = next(inferred.igetattr("step"))
5189 self.assertIsInstance(step_value, nodes.Const)
5190 self.assertEqual(step_value.value, step)
5191 self.assertEqual(inferred.pytype(), "builtins.slice")
5192
5193 def test_slice_type(self) -> None:
5194 ast_node = extract_node("type(slice(None, None, None))")
5195 inferred = next(ast_node.infer())
5196 self.assertIsInstance(inferred, nodes.ClassDef)
5197 self.assertEqual(inferred.name, "slice")
5198
5199
5200 class CallSiteTest(unittest.TestCase):
5201 @staticmethod
5202 def _call_site_from_call(call: nodes.Call) -> CallSite:
5203 return arguments.CallSite.from_call(call)
5204
5205 def _test_call_site_pair(
5206 self, code: str, expected_args: list[int], expected_keywords: dict[str, int]
5207 ) -> None:
5208 ast_node = extract_node(code)
5209 call_site = self._call_site_from_call(ast_node)
5210 self.assertEqual(len(call_site.positional_arguments), len(expected_args))
5211 self.assertEqual(
5212 [arg.value for arg in call_site.positional_arguments], expected_args
5213 )
5214 self.assertEqual(len(call_site.keyword_arguments), len(expected_keywords))
5215 for keyword, value in expected_keywords.items():
5216 self.assertIn(keyword, call_site.keyword_arguments)
5217 self.assertEqual(call_site.keyword_arguments[keyword].value, value)
5218
5219 def _test_call_site(
5220 self, pairs: list[tuple[str, list[int], dict[str, int]]]
5221 ) -> None:
5222 for pair in pairs:
5223 self._test_call_site_pair(*pair)
5224
5225 def test_call_site_starred_args(self) -> None:
5226 pairs = [
5227 (
5228 "f(*(1, 2), *(2, 3), *(3, 4), **{'a':1}, **{'b': 2})",
5229 [1, 2, 2, 3, 3, 4],
5230 {"a": 1, "b": 2},
5231 ),
5232 (
5233 "f(1, 2, *(3, 4), 5, *(6, 7), f=24, **{'c':3})",
5234 [1, 2, 3, 4, 5, 6, 7],
5235 {"f": 24, "c": 3},
5236 ),
5237 # Too many fs passed into.
5238 ("f(f=24, **{'f':24})", [], {}),
5239 ]
5240 self._test_call_site(pairs)
5241
5242 def test_call_site(self) -> None:
5243 pairs = [
5244 ("f(1, 2)", [1, 2], {}),
5245 ("f(1, 2, *(1, 2))", [1, 2, 1, 2], {}),
5246 ("f(a=1, b=2, c=3)", [], {"a": 1, "b": 2, "c": 3}),
5247 ]
5248 self._test_call_site(pairs)
5249
5250 def _test_call_site_valid_arguments(self, values: list[str], invalid: bool) -> None:
5251 for value in values:
5252 ast_node = extract_node(value)
5253 call_site = self._call_site_from_call(ast_node)
5254 self.assertEqual(call_site.has_invalid_arguments(), invalid)
5255
5256 def test_call_site_valid_arguments(self) -> None:
5257 values = ["f(*lala)", "f(*1)", "f(*object)"]
5258 self._test_call_site_valid_arguments(values, invalid=True)
5259 values = ["f()", "f(*(1, ))", "f(1, 2, *(2, 3))"]
5260 self._test_call_site_valid_arguments(values, invalid=False)
5261
5262 def test_duplicated_keyword_arguments(self) -> None:
5263 ast_node = extract_node('f(f=24, **{"f": 25})')
5264 site = self._call_site_from_call(ast_node)
5265 self.assertIn("f", site.duplicated_keywords)
5266
5267 def test_call_site_uninferable(self) -> None:
5268 code = """
5269 def get_nums():
5270 nums = ()
5271 if x == '1':
5272 nums = (1, 2)
5273 return nums
5274
5275 def add(x, y):
5276 return x + y
5277
5278 nums = get_nums()
5279
5280 if x:
5281 kwargs = {1: bar}
5282 else:
5283 kwargs = {}
5284
5285 if nums is not None:
5286 add(*nums)
5287 print(**kwargs)
5288 """
5289 # Test that `*nums` argument should be Uninferable
5290 ast = parse(code, __name__)
5291 *_, add_call, print_call = list(ast.nodes_of_class(nodes.Call))
5292 nums_arg = add_call.args[0]
5293 add_call_site = self._call_site_from_call(add_call)
5294 self.assertEqual(add_call_site._unpack_args([nums_arg]), [Uninferable])
5295
5296 print_call_site = self._call_site_from_call(print_call)
5297 keywords = CallContext(print_call.args, print_call.keywords).keywords
5298 self.assertEqual(
5299 print_call_site._unpack_keywords(keywords), {None: Uninferable}
5300 )
5301
5302
5303 class ObjectDunderNewTest(unittest.TestCase):
5304 def test_object_dunder_new_is_inferred_if_decorator(self) -> None:
5305 node = extract_node("""
5306 @object.__new__
5307 class instance(object):
5308 pass
5309 """)
5310 inferred = next(node.infer())
5311 self.assertIsInstance(inferred, Instance)
5312
5313
5314 @pytest.mark.parametrize(
5315 "code, result",
5316 [
5317 # regular f-string
5318 (
5319 """width = 10
5320 precision = 4
5321 value = 12.34567
5322 result = f"result: {value:{width}.{precision}}!"
5323 """,
5324 "result: 12.35!",
5325 ),
5326 # unsupported format
5327 (
5328 """width = None
5329 precision = 4
5330 value = 12.34567
5331 result = f"result: {value:{width}.{precision}}!"
5332 """,
5333 None,
5334 ),
5335 # unsupported value
5336 (
5337 """width = 10
5338 precision = 4
5339 value = None
5340 result = f"result: {value:{width}.{precision}}!"
5341 """,
5342 None,
5343 ),
5344 ],
5345 )
5346 def test_formatted_fstring_inference(code, result) -> None:
5347 ast = parse(code, __name__)
5348 node = ast["result"]
5349 inferred = node.inferred()
5350 assert len(inferred) == 1
5351 value_node = inferred[0]
5352 if result is None:
5353 assert value_node is util.Uninferable
5354 else:
5355 assert isinstance(value_node, nodes.Const)
5356 assert value_node.value == result
5357
5358
5359 def test_fstring_large_width_no_memory_error() -> None:
5360 """MemoryError should not crash inference for f-strings with huge width.
5361
5362 Regression test for https://github.com/pylint-dev/astroid/issues/2762
5363 """
5364
5365 class OOMInt(int):
5366 """An int whose __format__ raises MemoryError, simulating f'{0:>11111111111}'."""
5367
5368 def __format__(self, spec: str) -> str:
5369 raise MemoryError
5370
5371 node = extract_node("f'{0:>9}'")
5372 # Replace the Const value with our OOMInt so format() raises MemoryError
5373 # without actually allocating a huge string.
5374 fmt_value = node.values[0]
5375 fmt_value.value.value = OOMInt(0)
5376 inferred = node.inferred()
5377 assert len(inferred) == 1
5378 assert inferred[0] is util.Uninferable
5379
5380
5381 @pytest.mark.parametrize(
5382 "code",
5383 [
5384 "f'{1:>2000000000}'",
5385 "f'{0:030000000000}'",
5386 "f'{1.5:.2000000000f}'",
5387 ],
5388 )
5389 def test_fstring_oversized_width_uninferable(code: str) -> None:
5390 """A huge width/precision must not materialize a multi-gigabyte string."""
5391 node = extract_node(code)
5392 assert list(node.infer()) == [util.Uninferable]
5393
5394
5395 def test_augassign_recursion() -> None:
5396 """Make sure inference doesn't throw a RecursionError.
5397
5398 Regression test for augmented assign dropping context.path
5399 causing recursion errors
5400 """
5401 # infinitely recurses in python
5402 code = """
5403 def rec():
5404 a = 0
5405 a += rec()
5406 return a
5407 rec()
5408 """
5409 cls_node = extract_node(code)
5410 assert next(cls_node.infer()) is util.Uninferable
5411
5412
5413 def test_infer_custom_inherit_from_property() -> None:
5414 node = extract_node("""
5415 class custom_property(property):
5416 pass
5417
5418 class MyClass(object):
5419 @custom_property
5420 def my_prop(self):
5421 return 1
5422
5423 MyClass().my_prop
5424 """)
5425 inferred = next(node.infer())
5426 assert isinstance(inferred, nodes.Const)
5427 assert inferred.value == 1
5428
5429
5430 def test_cannot_infer_call_result_for_builtin_methods() -> None:
5431 node = extract_node("""
5432 a = "fast"
5433 a
5434 """)
5435 inferred = next(node.infer())
5436 lenmeth = next(inferred.igetattr("__len__"))
5437 # Builtin dunder methods now return Uninferable instead of raising InferenceError
5438 result = next(lenmeth.infer_call_result(None, None))
5439 assert result is util.Uninferable
5440
5441
5442 def test_unpack_dicts_in_assignment() -> None:
5443 ast_nodes = extract_node("""
5444 a, b = {1:2, 2:3}
5445 a #@
5446 b #@
5447 """)
5448 assert isinstance(ast_nodes, list)
5449 first_inferred = next(ast_nodes[0].infer())
5450 second_inferred = next(ast_nodes[1].infer())
5451 assert isinstance(first_inferred, nodes.Const)
5452 assert first_inferred.value == 1
5453 assert isinstance(second_inferred, nodes.Const)
5454 assert second_inferred.value == 2
5455
5456
5457 def test_slice_inference_in_for_loops() -> None:
5458 node = extract_node("""
5459 for a, (c, *b) in [(1, (2, 3, 4)), (4, (5, 6))]:
5460 b #@
5461 """)
5462 inferred = next(node.infer())
5463 assert isinstance(inferred, nodes.List)
5464 assert inferred.as_string() == "[3, 4]"
5465
5466 node = extract_node("""
5467 for a, *b in [(1, 2, 3, 4)]:
5468 b #@
5469 """)
5470 inferred = next(node.infer())
5471 assert isinstance(inferred, nodes.List)
5472 assert inferred.as_string() == "[2, 3, 4]"
5473
5474 node = extract_node("""
5475 for a, *b in [(1,)]:
5476 b #@
5477 """)
5478 inferred = next(node.infer())
5479 assert isinstance(inferred, nodes.List)
5480 assert inferred.as_string() == "[]"
5481
5482
5483 def test_slice_inference_in_for_loops_not_working() -> None:
5484 ast_nodes = extract_node("""
5485 from unknown import Unknown
5486 for a, *b in something:
5487 b #@
5488 for a, *b in Unknown:
5489 b #@
5490 for a, *b in (1):
5491 b #@
5492 """)
5493 for node in ast_nodes:
5494 inferred = next(node.infer())
5495 assert inferred == util.Uninferable
5496
5497
5498 def test_slice_zero_step_does_not_raise_ValueError() -> None:
5499 node = extract_node("x = [][::0]; x")
5500 assert next(node.infer()) == util.Uninferable
5501
5502
5503 def test_slice_zero_step_on_str_does_not_raise_ValueError() -> None:
5504 node = extract_node('x = ""[::0]; x')
5505 assert next(node.infer()) == util.Uninferable
5506
5507
5508 def test_unpacking_starred_and_dicts_in_assignment() -> None:
5509 node = extract_node("""
5510 a, *b = {1:2, 2:3, 3:4}
5511 b
5512 """)
5513 inferred = next(node.infer())
5514 assert isinstance(inferred, nodes.List)
5515 assert inferred.as_string() == "[2, 3]"
5516
5517 node = extract_node("""
5518 a, *b = {1:2}
5519 b
5520 """)
5521 inferred = next(node.infer())
5522 assert isinstance(inferred, nodes.List)
5523 assert inferred.as_string() == "[]"
5524
5525
5526 def test_unpacking_starred_empty_list_in_assignment() -> None:
5527 node = extract_node("""
5528 a, *b, c = [1, 2]
5529 b #@
5530 """)
5531 inferred = next(node.infer())
5532 assert isinstance(inferred, nodes.List)
5533 assert inferred.as_string() == "[]"
5534
5535
5536 def test_regression_infinite_loop_decorator() -> None:
5537 """Make sure decorators with the same names
5538 as a decorated method do not cause an infinite loop.
5539
5540 See https://github.com/pylint-dev/astroid/issues/375
5541 """
5542 code = """
5543 from functools import lru_cache
5544
5545 class Foo():
5546 @lru_cache()
5547 def lru_cache(self, value):
5548 print('Computing {}'.format(value))
5549 return value
5550 Foo().lru_cache(1)
5551 """
5552 node = extract_node(code)
5553 assert isinstance(node, nodes.NodeNG)
5554 [result] = node.inferred()
5555 assert result.value == 1
5556
5557
5558 def test_stop_iteration_in_int() -> None:
5559 """Handle StopIteration error in infer_int."""
5560 code = """
5561 def f(lst):
5562 if lst[0]:
5563 return f(lst)
5564 else:
5565 args = lst[:1]
5566 return int(args[0])
5567
5568 f([])
5569 """
5570 [first_result, second_result] = extract_node(code).inferred()
5571 assert first_result is util.Uninferable
5572 assert isinstance(second_result, Instance)
5573 assert second_result.name == "int"
5574
5575
5576 def test_call_on_instance_with_inherited_dunder_call_method() -> None:
5577 """Stop inherited __call__ method from incorrectly returning wrong class.
5578
5579 See https://github.com/pylint-dev/pylint/issues/2199
5580 """
5581 node = extract_node("""
5582 class Base:
5583 def __call__(self):
5584 return self
5585
5586 class Sub(Base):
5587 pass
5588 obj = Sub()
5589 val = obj()
5590 val #@
5591 """)
5592 assert isinstance(node, nodes.NodeNG)
5593 [val] = node.inferred()
5594 assert isinstance(val, Instance)
5595 assert val.name == "Sub"
5596
5597
5598 class TestInferencePropagation:
5599 """Make sure function argument values are properly
5600 propagated to sub functions.
5601 """
5602
5603 @pytest.mark.xfail(reason="Relying on path copy")
5604 def test_call_context_propagation(self):
5605 n = extract_node("""
5606 def chest(a):
5607 return a * a
5608 def best(a, b):
5609 return chest(a)
5610 def test(a, b, c):
5611 return best(a, b)
5612 test(4, 5, 6) #@
5613 """)
5614 assert next(n.infer()).as_string() == "16"
5615
5616 def test_call_starargs_propagation(self) -> None:
5617 code = """
5618 def foo(*args):
5619 return args
5620 def bar(*args):
5621 return foo(*args)
5622 bar(4, 5, 6, 7) #@
5623 """
5624 assert next(extract_node(code).infer()).as_string() == "(4, 5, 6, 7)"
5625
5626 def test_call_kwargs_propagation(self) -> None:
5627 code = """
5628 def b(**kwargs):
5629 return kwargs
5630 def f(**kwargs):
5631 return b(**kwargs)
5632 f(**{'f': 1}) #@
5633 """
5634 assert next(extract_node(code).infer()).as_string() == "{'f': 1}"
5635
5636
5637 @pytest.mark.parametrize(
5638 "op,result",
5639 [
5640 ("<", False),
5641 ("<=", True),
5642 ("==", True),
5643 (">=", True),
5644 (">", False),
5645 ("!=", False),
5646 ],
5647 )
5648 def test_compare(op, result) -> None:
5649 code = f"""
5650 123 {op} 123
5651 """
5652 node = extract_node(code)
5653 inferred = next(node.infer())
5654 assert inferred.value == result
5655
5656
5657 @pytest.mark.xfail(reason="uninferable")
5658 @pytest.mark.parametrize(
5659 "op,result",
5660 [
5661 ("is", True),
5662 ("is not", False),
5663 ],
5664 )
5665 def test_compare_identity(op, result) -> None:
5666 code = f"""
5667 obj = object()
5668 obj {op} obj
5669 """
5670 node = extract_node(code)
5671 inferred = next(node.infer())
5672 assert inferred.value == result
5673
5674
5675 @pytest.mark.parametrize(
5676 "op,result",
5677 [
5678 ("in", True),
5679 ("not in", False),
5680 ],
5681 )
5682 def test_compare_membership(op, result) -> None:
5683 code = f"""
5684 1 {op} [1, 2, 3]
5685 """
5686 node = extract_node(code)
5687 inferred = next(node.infer())
5688 assert inferred.value == result
5689
5690
5691 @pytest.mark.parametrize(
5692 "lhs,rhs,result",
5693 [
5694 (1, 1, True),
5695 (1, 1.1, True),
5696 (1.1, 1, False),
5697 (1.0, 1.0, True),
5698 ("abc", "def", True),
5699 ("abc", "", False),
5700 ([], [1], True),
5701 ((1, 2), (2, 3), True),
5702 ((1, 0), (1,), False),
5703 (True, True, True),
5704 (True, False, False),
5705 (False, 1, True),
5706 (1 + 0j, 2 + 0j, util.Uninferable),
5707 (+0.0, -0.0, True),
5708 (0, "1", util.Uninferable),
5709 (b"\x00", b"\x01", True),
5710 ],
5711 )
5712 def test_compare_lesseq_types(lhs, rhs, result) -> None:
5713 code = f"""
5714 {lhs!r} <= {rhs!r}
5715 """
5716 node = extract_node(code)
5717 inferred = next(node.infer())
5718 assert inferred.value == result
5719
5720
5721 def test_compare_chained() -> None:
5722 code = """
5723 3 < 5 > 3
5724 """
5725 node = extract_node(code)
5726 inferred = next(node.infer())
5727 assert inferred.value is True
5728
5729
5730 def test_compare_inferred_members() -> None:
5731 code = """
5732 a = 11
5733 b = 13
5734 a < b
5735 """
5736 node = extract_node(code)
5737 inferred = next(node.infer())
5738 assert inferred.value is True
5739
5740
5741 def test_compare_instance_members() -> None:
5742 code = """
5743 class A:
5744 value = 123
5745 class B:
5746 @property
5747 def value(self):
5748 return 456
5749 A().value < B().value
5750 """
5751 node = extract_node(code)
5752 inferred = next(node.infer())
5753 assert inferred.value is True
5754
5755
5756 @pytest.mark.xfail(reason="unimplemented")
5757 def test_compare_dynamic() -> None:
5758 code = """
5759 class A:
5760 def __le__(self, other):
5761 return True
5762 A() <= None
5763 """
5764 node = extract_node(code)
5765 inferred = next(node.infer())
5766 assert inferred.value is True
5767
5768
5769 def test_compare_uninferable_member() -> None:
5770 code = """
5771 from unknown import UNKNOWN
5772 0 <= UNKNOWN
5773 """
5774 node = extract_node(code)
5775 inferred = next(node.infer())
5776 assert inferred is util.Uninferable
5777
5778
5779 def test_compare_chained_comparisons_shortcircuit_on_false() -> None:
5780 code = """
5781 from unknown import UNKNOWN
5782 2 < 1 < UNKNOWN
5783 """
5784 node = extract_node(code)
5785 inferred = next(node.infer())
5786 assert inferred.value is False
5787
5788
5789 def test_compare_chained_comparisons_continue_on_true() -> None:
5790 code = """
5791 from unknown import UNKNOWN
5792 1 < 2 < UNKNOWN
5793 """
5794 node = extract_node(code)
5795 inferred = next(node.infer())
5796 assert inferred is util.Uninferable
5797
5798
5799 @pytest.mark.xfail(reason="unimplemented")
5800 def test_compare_known_false_branch() -> None:
5801 code = """
5802 a = 'hello'
5803 if 1 < 2:
5804 a = 'goodbye'
5805 a
5806 """
5807 node = extract_node(code)
5808 inferred = list(node.infer())
5809 assert len(inferred) == 1
5810 assert isinstance(inferred[0], nodes.Const)
5811 assert inferred[0].value == "hello"
5812
5813
5814 def test_compare_ifexp_constant() -> None:
5815 code = """
5816 a = 'hello' if 1 < 2 else 'goodbye'
5817 a
5818 """
5819 node = extract_node(code)
5820 inferred = list(node.infer())
5821 assert len(inferred) == 1
5822 assert isinstance(inferred[0], nodes.Const)
5823 assert inferred[0].value == "hello"
5824
5825
5826 def test_compare_typeerror() -> None:
5827 code = """
5828 123 <= "abc"
5829 """
5830 node = extract_node(code)
5831 inferred = list(node.infer())
5832 assert len(inferred) == 1
5833 assert inferred[0] is util.Uninferable
5834
5835
5836 def test_compare_multiple_possibilites() -> None:
5837 code = """
5838 from unknown import UNKNOWN
5839 a = 1
5840 if UNKNOWN:
5841 a = 2
5842 b = 3
5843 if UNKNOWN:
5844 b = 4
5845 a < b
5846 """
5847 node = extract_node(code)
5848 inferred = list(node.infer())
5849 assert len(inferred) == 1
5850 # All possible combinations are true: (1 < 3), (1 < 4), (2 < 3), (2 < 4)
5851 assert inferred[0].value is True
5852
5853
5854 def test_compare_ambiguous_multiple_possibilites() -> None:
5855 code = """
5856 from unknown import UNKNOWN
5857 a = 1
5858 if UNKNOWN:
5859 a = 3
5860 b = 2
5861 if UNKNOWN:
5862 b = 4
5863 a < b
5864 """
5865 node = extract_node(code)
5866 inferred = list(node.infer())
5867 assert len(inferred) == 1
5868 # Not all possible combinations are true: (1 < 2), (1 < 4), (3 !< 2), (3 < 4)
5869 assert inferred[0] is util.Uninferable
5870
5871
5872 def test_compare_nonliteral() -> None:
5873 code = """
5874 def func(a, b):
5875 return (a, b) <= (1, 2) #@
5876 """
5877 return_node = extract_node(code)
5878 node = return_node.value
5879 inferred = list(node.infer()) # should not raise ValueError
5880 assert len(inferred) == 1
5881 assert inferred[0] is util.Uninferable
5882
5883
5884 def test_compare_unknown() -> None:
5885 code = """
5886 def func(a):
5887 if tuple() + (a[1],) in set():
5888 raise Exception()
5889 """
5890 node = extract_node(code)
5891 inferred = list(node.infer())
5892 assert len(inferred) == 1
5893 assert isinstance(inferred[0], nodes.FunctionDef)
5894
5895
5896 def test_limit_inference_result_amount() -> None:
5897 """Test setting limit inference result amount."""
5898 code = """
5899 args = []
5900
5901 if True:
5902 args += ['a']
5903
5904 if True:
5905 args += ['b']
5906
5907 if True:
5908 args += ['c']
5909
5910 if True:
5911 args += ['d']
5912
5913 args #@
5914 """
5915 result = extract_node(code).inferred()
5916 assert len(result) == 16
5917 with patch("astroid.manager.AstroidManager.max_inferable_values", 4):
5918 result_limited = extract_node(code).inferred()
5919 # Can't guarantee exact size
5920 assert len(result_limited) < 16
5921 # Will not always be at the end
5922 assert util.Uninferable in result_limited
5923
5924
5925 def test_attribute_inference_should_not_access_base_classes() -> None:
5926 """Attributes of classes should mask ancestor attributes."""
5927 code = """
5928 type.__new__ #@
5929 """
5930 res = extract_node(code).inferred()
5931 assert len(res) == 1
5932 assert res[0].parent.name == "type"
5933
5934
5935 def test_attribute_mro_object_inference() -> None:
5936 """Inference should only infer results from the first available method."""
5937 inferred = extract_node("""
5938 class A:
5939 def foo(self):
5940 return 1
5941 class B(A):
5942 def foo(self):
5943 return 2
5944 B().foo() #@
5945 """).inferred()
5946 assert len(inferred) == 1
5947 assert inferred[0].value == 2
5948
5949
5950 def test_inferred_sequence_unpacking_works() -> None:
5951 inferred = next(extract_node("""
5952 def test(*args):
5953 return (1, *args)
5954 test(2) #@
5955 """).infer())
5956 assert isinstance(inferred, nodes.Tuple)
5957 assert len(inferred.elts) == 2
5958 assert [value.value for value in inferred.elts] == [1, 2]
5959
5960
5961 def test_recursion_error_inferring_slice() -> None:
5962 node = extract_node("""
5963 class MyClass:
5964 def __init__(self):
5965 self._slice = slice(0, 10)
5966
5967 def incr(self):
5968 self._slice = slice(0, self._slice.stop + 1)
5969
5970 def test(self):
5971 self._slice #@
5972 """)
5973 inferred = next(node.infer())
5974 assert isinstance(inferred, nodes.Slice)
5975
5976
5977 def test_exception_lookup_last_except_handler_wins() -> None:
5978 node = extract_node("""
5979 try:
5980 1/0
5981 except ValueError as exc:
5982 pass
5983 try:
5984 1/0
5985 except OSError as exc:
5986 exc #@
5987 """)
5988 assert isinstance(node, nodes.NodeNG)
5989 inferred = node.inferred()
5990 assert len(inferred) == 1
5991 inferred_exc = inferred[0]
5992 assert isinstance(inferred_exc, Instance)
5993 assert inferred_exc.name == "OSError"
5994
5995 # Two except handlers on the same Try work the same as separate
5996 node = extract_node("""
5997 try:
5998 1/0
5999 except ZeroDivisionError as exc:
6000 pass
6001 except ValueError as exc:
6002 exc #@
6003 """)
6004 assert isinstance(node, nodes.NodeNG)
6005 inferred = node.inferred()
6006 assert len(inferred) == 1
6007 inferred_exc = inferred[0]
6008 assert isinstance(inferred_exc, Instance)
6009 assert inferred_exc.name == "ValueError"
6010
6011
6012 def test_exception_lookup_name_bound_in_except_handler() -> None:
6013 node = extract_node("""
6014 try:
6015 1/0
6016 except ValueError:
6017 name = 1
6018 try:
6019 1/0
6020 except OSError:
6021 name = 2
6022 name #@
6023 """)
6024 assert isinstance(node, nodes.NodeNG)
6025 inferred = node.inferred()
6026 assert len(inferred) == 1
6027 inferred_exc = inferred[0]
6028 assert isinstance(inferred_exc, nodes.Const)
6029 assert inferred_exc.value == 2
6030
6031
6032 def test_builtin_inference_list_of_exceptions() -> None:
6033 node = extract_node("""
6034 tuple([ValueError, TypeError])
6035 """)
6036 inferred = next(node.infer())
6037 assert isinstance(inferred, nodes.Tuple)
6038 assert len(inferred.elts) == 2
6039 assert isinstance(inferred.elts[0], nodes.EvaluatedObject)
6040 assert isinstance(inferred.elts[0].value, nodes.ClassDef)
6041 assert inferred.elts[0].value.name == "ValueError"
6042 assert isinstance(inferred.elts[1], nodes.EvaluatedObject)
6043 assert isinstance(inferred.elts[1].value, nodes.ClassDef)
6044 assert inferred.elts[1].value.name == "TypeError"
6045
6046 # Test that inference of evaluated objects returns what is expected
6047 first_elem = next(inferred.elts[0].infer())
6048 assert isinstance(first_elem, nodes.ClassDef)
6049 assert first_elem.name == "ValueError"
6050
6051 second_elem = next(inferred.elts[1].infer())
6052 assert isinstance(second_elem, nodes.ClassDef)
6053 assert second_elem.name == "TypeError"
6054
6055 # Test that as_string() also works
6056 as_string = inferred.as_string()
6057 assert as_string.strip() == "(ValueError, TypeError)"
6058
6059
6060 def test_cannot_getattr_ann_assigns() -> None:
6061 node = extract_node("""
6062 class Cls:
6063 ann: int
6064 """)
6065 inferred = next(node.infer())
6066 with pytest.raises(AttributeInferenceError):
6067 inferred.getattr("ann")
6068
6069 # But if it had a value, then it would be okay.
6070 node = extract_node("""
6071 class Cls:
6072 ann: int = 0
6073 """)
6074 inferred = next(node.infer())
6075 values = inferred.getattr("ann")
6076 assert len(values) == 1
6077
6078
6079 def test_prevent_recursion_error_in_igetattr_and_context_manager_inference() -> None:
6080 code = """
6081 class DummyContext(object):
6082 def __enter__(self):
6083 return self
6084 def __exit__(self, ex_type, ex_value, ex_tb):
6085 return True
6086
6087 if False:
6088 with DummyContext() as con:
6089 pass
6090
6091 with DummyContext() as con:
6092 con.__enter__ #@
6093 """
6094 node = extract_node(code)
6095 # According to the original issue raised that introduced this test
6096 # (https://github.com/pylint-dev/astroid/663, see 55076ca), this test was a
6097 # non-regression check for StopIteration leaking out of inference and
6098 # causing a RuntimeError. Hence, here just consume the inferred value
6099 # without checking it and rely on pytest to fail on raise
6100 next(node.infer())
6101
6102
6103 def test_igetattr_idempotent() -> None:
6104 code = """
6105 class InferMeTwice:
6106 item = 10
6107
6108 InferMeTwice()
6109 """
6110 call = extract_node(code)
6111 instance = call.inferred()[0]
6112 context_to_be_used_twice = InferenceContext()
6113 assert util.Uninferable not in instance.igetattr("item", context_to_be_used_twice)
6114 assert util.Uninferable not in instance.igetattr("item", context_to_be_used_twice)
6115
6116
6117 def test_inference_context_str() -> None:
6118 """``str()`` of an ``InferenceContext`` renders each slot without crashing."""
6119 rendered = str(InferenceContext())
6120 assert rendered.startswith("InferenceContext(")
6121 assert rendered.endswith(")")
6122
6123
6124 @patch("astroid.nodes.Call._infer")
6125 def test_cache_usage_without_explicit_context(mock) -> None:
6126 code = """
6127 class InferMeTwice:
6128 item = 10
6129
6130 InferMeTwice()
6131 """
6132 call = extract_node(code)
6133 mock.return_value = [Uninferable]
6134
6135 # no explicit InferenceContext
6136 call.inferred()
6137 call.inferred()
6138
6139 mock.assert_called_once()
6140
6141
6142 def test_infer_context_manager_with_unknown_args() -> None:
6143 code = """
6144 class client_log(object):
6145 def __init__(self, client):
6146 self.client = client
6147 def __enter__(self):
6148 return self.client
6149 def __exit__(self, exc_type, exc_value, traceback):
6150 pass
6151
6152 with client_log(None) as c:
6153 c #@
6154 """
6155 node = extract_node(code)
6156 assert next(node.infer()) is util.Uninferable
6157
6158 # But if we know the argument, then it is easy
6159 code = """
6160 class client_log(object):
6161 def __init__(self, client=24):
6162 self.client = client
6163 def __enter__(self):
6164 return self.client
6165 def __exit__(self, exc_type, exc_value, traceback):
6166 pass
6167
6168 with client_log(None) as c:
6169 c #@
6170 """
6171 node = extract_node(code)
6172 assert isinstance(next(node.infer()), nodes.Const)
6173
6174
6175 @pytest.mark.parametrize(
6176 "code",
6177 [
6178 """
6179 class Error(Exception):
6180 pass
6181
6182 a = Error()
6183 a #@
6184 """,
6185 """
6186 class Error(Exception):
6187 def method(self):
6188 self #@
6189 """,
6190 ],
6191 )
6192 def test_subclass_of_exception(code) -> None:
6193 inferred = next(extract_node(code).infer())
6194 assert isinstance(inferred, Instance)
6195 args = next(inferred.igetattr("args"))
6196 assert isinstance(args, nodes.Tuple)
6197
6198
6199 def test_ifexp_inference() -> None:
6200 code = """
6201 def truth_branch():
6202 return 1 if True else 2
6203
6204 def false_branch():
6205 return 1 if False else 2
6206
6207 def both_branches():
6208 return 1 if unknown() else 2
6209
6210 truth_branch() #@
6211 false_branch() #@
6212 both_branches() #@
6213 """
6214 ast_nodes = extract_node(code)
6215 assert isinstance(ast_nodes, list)
6216 first = next(ast_nodes[0].infer())
6217 assert isinstance(first, nodes.Const)
6218 assert first.value == 1
6219
6220 second = next(ast_nodes[1].infer())
6221 assert isinstance(second, nodes.Const)
6222 assert second.value == 2
6223
6224 third = list(ast_nodes[2].infer())
6225 assert isinstance(third, list)
6226 assert [third[0].value, third[1].value] == [1, 2]
6227
6228
6229 def test_ifexp_with_default_arguments() -> None:
6230 code = """
6231 def with_default(foo: str | None = None):
6232 a = 1 if foo else "bar" #@
6233
6234 def without_default(foo: str):
6235 a = 1 if foo else "bar" #@
6236
6237 def some_ifexps(foo: str | None = None):
6238 a = 1 if foo else 2
6239 b = 3 if a else 4 #@
6240 c = 4 if b else 5 #@
6241 d = 5 if not foo else foo #@
6242 e = d if not foo else foo #@
6243 """
6244
6245 ast_nodes = extract_node(code)
6246
6247 first = ast_nodes[0].value.inferred()
6248 second = ast_nodes[1].value.inferred()
6249 third = ast_nodes[2].value.inferred()
6250 fourth = ast_nodes[3].value.inferred()
6251 fifth = ast_nodes[4].value.inferred()
6252 sixth = ast_nodes[5].value.inferred()
6253
6254 assert len(first) == 2
6255 assert [first[0].value, first[1].value] == [1, "bar"]
6256
6257 assert len(second) == 2
6258 assert [second[0].value, second[1].value] == [1, "bar"]
6259
6260 assert len(third) == 1
6261 assert third[0].value == 3
6262
6263 assert len(fourth) == 1
6264 assert fourth[0].value == 4
6265
6266 assert len(fifth) == 2
6267 assert [fifth[0].value, fifth[1].value] == [5, Uninferable]
6268
6269 assert len(sixth) == 3
6270 assert [sixth[0].value, sixth[1].value, sixth[2].value] == [
6271 5,
6272 Uninferable,
6273 Uninferable,
6274 ]
6275
6276
6277 def test_ifexp_with_uninferables() -> None:
6278 code = """
6279 def truthy_and_falsy():
6280 return False if unknown() else True
6281
6282 def truthy_and_uninferable():
6283 return False if unknown() else unknown()
6284
6285 def calls_truthy_and_falsy():
6286 return 1 if truthy_and_falsy() else 2
6287
6288 def calls_truthy_and_uninferable():
6289 return 1 if range(10) else truthy_and_uninferable()
6290
6291 truthy_and_falsy() #@
6292 truthy_and_uninferable() #@
6293 calls_truthy_and_falsy() #@
6294 calls_truthy_and_uninferable() #@
6295 """
6296
6297 ast_nodes = extract_node(code)
6298
6299 first = ast_nodes[0].inferred()
6300 second = ast_nodes[1].inferred()
6301 third = ast_nodes[2].inferred()
6302 fourth = ast_nodes[3].inferred()
6303
6304 assert len(first) == 2
6305 assert [first[0].value, first[1].value] == [False, True]
6306
6307 assert len(second) == 2
6308 assert [second[0].value, second[1].value] == [False, Uninferable]
6309
6310 assert len(third) == 2
6311 assert [third[0].value, third[1].value] == [1, 2]
6312
6313 assert len(fourth) == 3
6314 assert [fourth[0].value, fourth[1].value, fourth[2].value] == [
6315 1,
6316 False,
6317 Uninferable,
6318 ]
6319
6320
6321 def test_assert_last_function_returns_none_on_inference() -> None:
6322 code = """
6323 def check_equal(a, b):
6324 res = do_something_with_these(a, b)
6325 assert a == b == res
6326
6327 check_equal(a, b)
6328 """
6329 node = extract_node(code)
6330 inferred = next(node.infer())
6331 assert isinstance(inferred, nodes.Const)
6332 assert inferred.value is None
6333
6334
6335 def test_posonlyargs_inference() -> None:
6336 code = """
6337 class A:
6338 method = lambda self, b, /, c: b + c
6339
6340 def __init__(self, other=(), /, **kw):
6341 self #@
6342 A() #@
6343 A().method #@
6344
6345 """
6346 self_node, instance, lambda_method = extract_node(code)
6347 inferred = next(self_node.infer())
6348 assert isinstance(inferred, Instance)
6349 assert inferred.name == "A"
6350
6351 inferred = next(instance.infer())
6352 assert isinstance(inferred, Instance)
6353 assert inferred.name == "A"
6354
6355 inferred = next(lambda_method.infer())
6356 assert isinstance(inferred, BoundMethod)
6357 assert inferred.type == "method"
6358
6359
6360 def test_infer_args_unpacking_of_self() -> None:
6361 code = """
6362 class A:
6363 def __init__(*args, **kwargs):
6364 self, *args = args
6365 self.data = {1: 2}
6366 self #@
6367 A().data #@
6368 """
6369 self, data = extract_node(code)
6370 inferred_self = next(self.infer())
6371 assert isinstance(inferred_self, Instance)
6372 assert inferred_self.name == "A"
6373
6374 inferred_data = next(data.infer())
6375 assert isinstance(inferred_data, nodes.Dict)
6376 assert inferred_data.as_string() == "{1: 2}"
6377
6378
6379 def test_infer_exception_instance_attributes() -> None:
6380 code = """
6381 class UnsupportedFormatCharacter(Exception):
6382 def __init__(self, index):
6383 Exception.__init__(self, index)
6384 self.index = index
6385
6386 try:
6387 1/0
6388 except UnsupportedFormatCharacter as exc:
6389 exc #@
6390 """
6391 node = extract_node(code)
6392 inferred = next(node.infer())
6393 assert isinstance(inferred, ExceptionInstance)
6394 index = inferred.getattr("index")
6395 assert len(index) == 1
6396 assert isinstance(index[0], nodes.AssignAttr)
6397
6398
6399 def test_infer_assign_attr() -> None:
6400 code = """
6401 class Counter:
6402 def __init__(self):
6403 self.count = 0
6404
6405 def increment(self):
6406 self.count += 1 #@
6407 """
6408 node = extract_node(code)
6409 inferred = next(node.infer())
6410 assert inferred.value == 1
6411
6412
6413 @pytest.mark.parametrize(
6414 "code,instance_name",
6415 [
6416 (
6417 """
6418 class A:
6419 def __enter__(self):
6420 return self
6421 def __exit__(self, err_type, err, traceback):
6422 return
6423 class B(A):
6424 pass
6425 with B() as b:
6426 b #@
6427 """,
6428 "B",
6429 ),
6430 (
6431 """
6432 class A:
6433 def __enter__(self):
6434 return A()
6435 def __exit__(self, err_type, err, traceback):
6436 return
6437 class B(A):
6438 pass
6439 with B() as b:
6440 b #@
6441 """,
6442 "A",
6443 ),
6444 (
6445 """
6446 class A:
6447 def test(self):
6448 return A()
6449 class B(A):
6450 def test(self):
6451 return A.test(self)
6452 B().test()
6453 """,
6454 "A",
6455 ),
6456 ],
6457 )
6458 def test_inference_is_limited_to_the_boundnode(code, instance_name) -> None:
6459 node = extract_node(code)
6460 inferred = next(node.infer())
6461 assert isinstance(inferred, Instance)
6462 assert inferred.name == instance_name
6463
6464
6465 def test_classmethod_returned_tuple_subscript_ignores_unrelated_boundnode() -> None:
6466 node = extract_node("""
6467 class A:
6468 def b(self):
6469 return 0
6470
6471 @classmethod
6472 def c(cls):
6473 return cls(), 0
6474
6475 class D:
6476 def e(self):
6477 self.f = A.c()[0]
6478 self.f #@
6479 """)
6480
6481 inferred = next(node.infer())
6482
6483 assert isinstance(inferred, Instance)
6484 assert inferred.name == "A"
6485
6486
6487 def test_property_inference() -> None:
6488 code = """
6489 class A:
6490 @property
6491 def test(self):
6492 return 42
6493
6494 @test.setter
6495 def test(self, value):
6496 return "banco"
6497
6498 A.test #@
6499 A().test #@
6500 A.test.fget(A) #@
6501 A.test.fset(A, "a_value") #@
6502 A.test.setter #@
6503 A.test.getter #@
6504 A.test.deleter #@
6505 """
6506 (
6507 prop,
6508 prop_result,
6509 prop_fget_result,
6510 prop_fset_result,
6511 prop_setter,
6512 prop_getter,
6513 prop_deleter,
6514 ) = extract_node(code)
6515
6516 inferred = next(prop.infer())
6517 assert isinstance(inferred, objects.Property)
6518 assert inferred.pytype() == "builtins.property"
6519 assert inferred.type == "property"
6520
6521 inferred = next(prop_result.infer())
6522 assert isinstance(inferred, nodes.Const)
6523 assert inferred.value == 42
6524
6525 inferred = next(prop_fget_result.infer())
6526 assert isinstance(inferred, nodes.Const)
6527 assert inferred.value == 42
6528
6529 inferred = next(prop_fset_result.infer())
6530 assert isinstance(inferred, nodes.Const)
6531 assert inferred.value == "banco"
6532
6533 for prop_func in prop_setter, prop_getter, prop_deleter:
6534 inferred = next(prop_func.infer())
6535 assert isinstance(inferred, nodes.FunctionDef)
6536
6537
6538 def test_property_as_string() -> None:
6539 code = """
6540 class A:
6541 @property
6542 def test(self):
6543 return 42
6544
6545 A.test #@
6546 """
6547 node = extract_node(code)
6548 inferred = next(node.infer())
6549 assert isinstance(inferred, objects.Property)
6550 property_body = textwrap.dedent("""
6551 @property
6552 def test(self):
6553 return 42
6554 """)
6555 assert inferred.as_string().strip() == property_body.strip()
6556
6557
6558 def test_property_callable_inference() -> None:
6559 code = """
6560 class A:
6561 def func(self):
6562 return 42
6563 p = property(func)
6564 A().p
6565 """
6566 property_call = extract_node(code)
6567 inferred = next(property_call.infer())
6568 assert isinstance(inferred, nodes.Const)
6569 assert inferred.value == 42
6570
6571 # Try with lambda as well
6572 code = """
6573 class A:
6574 p = property(lambda self: 42)
6575 A().p
6576 """
6577 property_call = extract_node(code)
6578 inferred = next(property_call.infer())
6579 assert isinstance(inferred, nodes.Const)
6580 assert inferred.value == 42
6581
6582
6583 def test_property_docstring() -> None:
6584 code = """
6585 class A:
6586 @property
6587 def test(self):
6588 '''Docstring'''
6589 return 42
6590
6591 A.test #@
6592 """
6593 node = extract_node(code)
6594 inferred = next(node.infer())
6595 assert isinstance(inferred, objects.Property)
6596 assert isinstance(inferred.doc_node, nodes.Const)
6597 assert inferred.doc_node.value == "Docstring"
6598
6599
6600 def test_recursion_error_inferring_builtin_containers() -> None:
6601 node = extract_node("""
6602 class Foo:
6603 a = "foo"
6604 inst = Foo()
6605
6606 b = tuple([inst.a]) #@
6607 inst.a = b
6608 """)
6609 util.safe_infer(node.targets[0])
6610
6611
6612 def test_inferaugassign_picking_parent_instead_of_stmt() -> None:
6613 code = """
6614 from collections import namedtuple
6615 SomeClass = namedtuple('SomeClass', ['name'])
6616 items = [SomeClass(name='some name')]
6617
6618 some_str = ''
6619 some_str += ', '.join(__(item) for item in items)
6620 """
6621 # item needs to be inferrd as `SomeClass` but it was inferred
6622 # as a string because the entire `AugAssign` node was inferred
6623 # as a string.
6624 node = extract_node(code)
6625 inferred = next(node.infer())
6626 assert isinstance(inferred, Instance)
6627 assert inferred.name == "SomeClass"
6628
6629
6630 def test_classmethod_from_builtins_inferred_as_bound() -> None:
6631 code = """
6632 import builtins
6633
6634 class Foo():
6635 @classmethod
6636 def bar1(cls, text):
6637 pass
6638
6639 @builtins.classmethod
6640 def bar2(cls, text):
6641 pass
6642
6643 Foo.bar1 #@
6644 Foo.bar2 #@
6645 """
6646 first_node, second_node = extract_node(code)
6647 assert isinstance(next(first_node.infer()), BoundMethod)
6648 assert isinstance(next(second_node.infer()), BoundMethod)
6649
6650
6651 def test_infer_dict_passes_context() -> None:
6652 code = """
6653 k = {}
6654 (_ for k in __(dict(**k)))
6655 """
6656 node = extract_node(code)
6657 inferred = next(node.infer())
6658 assert isinstance(inferred, Instance)
6659 assert inferred.qname() == "builtins.dict"
6660
6661
6662 @pytest.mark.parametrize(
6663 "code,obj,obj_type",
6664 [
6665 (
6666 """
6667 def klassmethod1(method):
6668 @classmethod
6669 def inner(cls):
6670 return method(cls)
6671 return inner
6672
6673 class X(object):
6674 @klassmethod1
6675 def x(cls):
6676 return 'X'
6677 X.x
6678 """,
6679 BoundMethod,
6680 "classmethod",
6681 ),
6682 (
6683 """
6684 def staticmethod1(method):
6685 @staticmethod
6686 def inner(cls):
6687 return method(cls)
6688 return inner
6689
6690 class X(object):
6691 @staticmethod1
6692 def x(cls):
6693 return 'X'
6694 X.x
6695 """,
6696 nodes.FunctionDef,
6697 "staticmethod",
6698 ),
6699 (
6700 """
6701 def klassmethod1(method):
6702 def inner(cls):
6703 return method(cls)
6704 return classmethod(inner)
6705
6706 class X(object):
6707 @klassmethod1
6708 def x(cls):
6709 return 'X'
6710 X.x
6711 """,
6712 BoundMethod,
6713 "classmethod",
6714 ),
6715 (
6716 """
6717 def staticmethod1(method):
6718 def inner(cls):
6719 return method(cls)
6720 return staticmethod(inner)
6721
6722 class X(object):
6723 @staticmethod1
6724 def x(cls):
6725 return 'X'
6726 X.x
6727 """,
6728 nodes.FunctionDef,
6729 "staticmethod",
6730 ),
6731 ],
6732 )
6733 def test_custom_decorators_for_classmethod_and_staticmethods(code, obj, obj_type):
6734 node = extract_node(code)
6735 inferred = next(node.infer())
6736 assert isinstance(inferred, obj)
6737 assert inferred.type == obj_type
6738
6739
6740 def test_dataclasses_subscript_inference_recursion_error_39():
6741 code = """
6742 from dataclasses import dataclass, replace
6743
6744 @dataclass
6745 class ProxyConfig:
6746 auth: str = "/auth"
6747
6748
6749 a = ProxyConfig("")
6750 test_dict = {"proxy" : {"auth" : "", "bla" : "f"}}
6751
6752 foo = test_dict['proxy']
6753 replace(a, **test_dict['proxy']) # This fails
6754 """
6755 node = extract_node(code)
6756 infer_val = util.safe_infer(node)
6757 assert isinstance(infer_val, Instance)
6758 assert infer_val.pytype() == ".ProxyConfig"
6759
6760
6761 def test_self_reference_infer_does_not_trigger_recursion_error() -> None:
6762 # Prevents https://github.com/pylint-dev/pylint/issues/1285
6763 code = """
6764 def func(elems):
6765 return elems
6766
6767 class BaseModel(object):
6768
6769 def __init__(self, *args, **kwargs):
6770 self._reference = func(*self._reference.split('.'))
6771 BaseModel()._reference
6772 """
6773 node = extract_node(code)
6774 inferred = next(node.infer())
6775 assert inferred is util.Uninferable
6776
6777
6778 def test_inferring_properties_multiple_time_does_not_mutate_locals() -> None:
6779 code = """
6780 class A:
6781 @property
6782 def a(self):
6783 return 42
6784 """
6785 cls = extract_node(code)
6786 (prop,) = cls.getattr("a")
6787
6788 assert len(cls.locals["a"]) == 1
6789 for _ in range(3):
6790 prop.inferred()
6791 a_locals = cls.locals["a"]
6792 assert len(a_locals) == 1
6793
6794
6795 def test_getattr_fails_on_empty_values() -> None:
6796 code = """
6797 import collections
6798 collections
6799 """
6800 node = extract_node(code)
6801 inferred = next(node.infer())
6802 with pytest.raises(InferenceError):
6803 next(inferred.igetattr(""))
6804
6805 with pytest.raises(AttributeInferenceError):
6806 inferred.getattr("")
6807
6808
6809 def test_infer_first_argument_of_static_method_in_metaclass() -> None:
6810 code = """
6811 class My(type):
6812 @staticmethod
6813 def test(args):
6814 args #@
6815 """
6816 node = extract_node(code)
6817 inferred = next(node.infer())
6818 assert inferred is util.Uninferable
6819
6820
6821 def test_recursion_error_metaclass_monkeypatching() -> None:
6822 module = resources.build_file(
6823 "data/metaclass_recursion/monkeypatch.py", "data.metaclass_recursion"
6824 )
6825 cls = next(module.igetattr("MonkeyPatchClass"))
6826 assert isinstance(cls, nodes.ClassDef)
6827 assert cls.declared_metaclass() is None
6828
6829
6830 @pytest.mark.xfail(reason="Cannot fully infer all the base classes properly.")
6831 def test_recursion_error_self_reference_type_call() -> None:
6832 # Fix for https://github.com/pylint-dev/astroid/issues/199
6833 code = """
6834 class A(object):
6835 pass
6836 class SomeClass(object):
6837 route_class = A
6838 def __init__(self):
6839 self.route_class = type('B', (self.route_class, ), {})
6840 self.route_class() #@
6841 """
6842 node = extract_node(code)
6843 inferred = next(node.infer())
6844 assert isinstance(inferred, Instance)
6845 assert inferred.name == "B"
6846 # TODO: Cannot infer [B, A, object] but at least the recursion error is gone.
6847 assert [cls.name for cls in inferred.mro()] == ["B", "A", "object"]
6848
6849
6850 def test_allow_retrieving_instance_attrs_and_special_attrs_for_functions() -> None:
6851 code = """
6852 class A:
6853 def test(self):
6854 "a"
6855 # Add `__doc__` to `FunctionDef.instance_attrs` via an `AugAssign`
6856 test.__doc__ += 'b'
6857 test #@
6858 """
6859 node = extract_node(code)
6860 inferred = next(node.infer())
6861 attrs = inferred.getattr("__doc__")
6862 # One from the `AugAssign`, one from the special attributes
6863 assert len(attrs) == 2
6864
6865
6866 def test_implicit_parameters_bound_method() -> None:
6867 code = """
6868 class A(type):
6869 @classmethod
6870 def test(cls, first): return first
6871 def __new__(cls, name, bases, dictionary):
6872 return super().__new__(cls, name, bases, dictionary)
6873
6874 A.test #@
6875 A.__new__ #@
6876 """
6877 test, dunder_new = extract_node(code)
6878 test = next(test.infer())
6879 assert isinstance(test, BoundMethod)
6880 assert test.implicit_parameters() == 1
6881
6882 dunder_new = next(dunder_new.infer())
6883 assert isinstance(dunder_new, BoundMethod)
6884 assert dunder_new.implicit_parameters() == 0
6885
6886
6887 def test_super_inference_of_abstract_property() -> None:
6888 code = """
6889 from abc import abstractmethod
6890
6891 class A:
6892 @property
6893 def test(self):
6894 return "super"
6895
6896 class C:
6897 @property
6898 @abstractmethod
6899 def test(self):
6900 "abstract method"
6901
6902 class B(A, C):
6903
6904 @property
6905 def test(self):
6906 super() #@
6907
6908 """
6909 node = extract_node(code)
6910 inferred = next(node.infer())
6911 test = inferred.getattr("test")
6912 assert len(test) == 2
6913
6914
6915 def test_infer_generated_setter() -> None:
6916 code = """
6917 class A:
6918 @property
6919 def test(self):
6920 pass
6921 A.test.setter
6922 """
6923 node = extract_node(code)
6924 inferred = next(node.infer())
6925 assert isinstance(inferred, nodes.FunctionDef)
6926 assert isinstance(inferred.args, nodes.Arguments)
6927 # This line used to crash because property generated functions
6928 # did not have args properly set
6929 assert not list(inferred.nodes_of_class(nodes.Const))
6930
6931
6932 def test_infer_list_of_uninferables_does_not_crash() -> None:
6933 code = """
6934 x = [A] * 1
6935 f = [x, [A] * 2]
6936 x = list(f) + [] # List[Uninferable]
6937 tuple(x[0])
6938 """
6939 node = extract_node(code)
6940 inferred = next(node.infer())
6941 assert isinstance(inferred, nodes.Tuple)
6942 # Would not be able to infer the first element.
6943 assert not inferred.elts
6944
6945
6946 # https://github.com/pylint-dev/astroid/issues/926
6947 def test_issue926_infer_stmts_referencing_same_name_is_not_uninferable() -> None:
6948 code = """
6949 pair = [1, 2]
6950 ex = pair[0]
6951 if 1 + 1 == 2:
6952 ex = pair[1]
6953 ex
6954 """
6955 node = extract_node(code)
6956 inferred = list(node.infer())
6957 assert len(inferred) == 2
6958 assert isinstance(inferred[0], nodes.Const)
6959 assert inferred[0].value == 1
6960 assert isinstance(inferred[1], nodes.Const)
6961 assert inferred[1].value == 2
6962
6963
6964 # https://github.com/pylint-dev/astroid/issues/926
6965 def test_issue926_binop_referencing_same_name_is_not_uninferable() -> None:
6966 code = """
6967 pair = [1, 2]
6968 ex = pair[0] + pair[1]
6969 ex
6970 """
6971 node = extract_node(code)
6972 inferred = list(node.infer())
6973 assert len(inferred) == 1
6974 assert isinstance(inferred[0], nodes.Const)
6975 assert inferred[0].value == 3
6976
6977
6978 def test_pylint_issue_4692_attribute_inference_error_in_infer_import_from() -> None:
6979 """Https://github.com/pylint-dev/pylint/issues/4692."""
6980 code = """
6981 import click
6982
6983
6984 for name, item in click.__dict__.items():
6985 _ = isinstance(item, click.Command) and item != 'foo'
6986 """
6987 node = extract_node(code)
6988 with pytest.raises(InferenceError):
6989 list(node.infer())
6990
6991
6992 def test_issue_1090_infer_yield_type_base_class() -> None:
6993 code = """
6994 import contextlib
6995
6996 class A:
6997 @contextlib.contextmanager
6998 def get(self):
6999 yield self
7000
7001 class B(A):
7002 def play():
7003 pass
7004
7005 with B().get() as b:
7006 b
7007 b
7008 """
7009 node = extract_node(code)
7010 assert next(node.infer()).pytype() == ".B"
7011
7012
7013 def test_namespace_package() -> None:
7014 """Check that a file using namespace packages and relative imports is parseable."""
7015 resources.build_file("data/beyond_top_level/import_package.py")
7016
7017
7018 def test_namespace_package_same_name() -> None:
7019 """Check that a file using namespace packages and relative imports
7020 with similar names is parseable.
7021 """
7022 resources.build_file("data/beyond_top_level_two/a.py")
7023
7024
7025 def test_relative_imports_init_package() -> None:
7026 """Check that relative imports within a package that uses __init__.py
7027 still works.
7028 """
7029 resources.build_file(
7030 "data/beyond_top_level_three/module/sub_module/sub_sub_module/main.py"
7031 )
7032
7033
7034 def test_inference_of_items_on_module_dict() -> None:
7035 """Crash test for the inference of items() on a module's dict attribute.
7036
7037 Originally reported in https://github.com/pylint-dev/astroid/issues/1085
7038 """
7039 builder.file_build(str(DATA_DIR / "module_dict_items_call" / "test.py"), "models")
7040
7041
7042 def test_imported_module_var_inferable() -> None:
7043 """
7044 Module variables can be imported and inferred successfully as part of binary
7045 operators.
7046 """
7047 mod1 = parse(
7048 textwrap.dedent("""
7049 from top1.mod import v as z
7050 w = [1] + z
7051 """),
7052 module_name="top1",
7053 )
7054 parse("v = [2]", module_name="top1.mod")
7055 w_val = mod1.body[-1].value
7056 i_w_val = next(w_val.infer())
7057 assert i_w_val is not util.Uninferable
7058 assert i_w_val.as_string() == "[1, 2]"
7059
7060
7061 def test_imported_module_var_inferable2() -> None:
7062 """Version list of strings."""
7063 mod2 = parse(
7064 textwrap.dedent("""
7065 from top2.mod import v as z
7066 w = ['1'] + z
7067 """),
7068 module_name="top2",
7069 )
7070 parse("v = ['2']", module_name="top2.mod")
7071 w_val = mod2.body[-1].value
7072 i_w_val = next(w_val.infer())
7073 assert i_w_val is not util.Uninferable
7074 assert i_w_val.as_string() == "['1', '2']"
7075
7076
7077 def test_imported_module_var_inferable3() -> None:
7078 """Version list of strings with a __dunder__ name."""
7079 mod3 = parse(
7080 textwrap.dedent("""
7081 from top3.mod import __dunder_var__ as v
7082 __dunder_var__ = ['w'] + v
7083 """),
7084 module_name="top",
7085 )
7086 parse("__dunder_var__ = ['v']", module_name="top3.mod")
7087 w_val = mod3.body[-1].value
7088 i_w_val = next(w_val.infer())
7089 assert i_w_val is not util.Uninferable
7090 assert i_w_val.as_string() == "['w', 'v']"
7091
7092
7093 @pytest.mark.skipif(
7094 IS_PYPY, reason="Test run with coverage on PyPy sometimes raises a RecursionError"
7095 )
7096 def test_recursion_on_inference_tip() -> None:
7097 """Regression test for recursion in inference tip.
7098
7099 Originally reported in https://github.com/pylint-dev/pylint/issues/5408.
7100
7101 When run on PyPy with coverage enabled, the test can sometimes raise a RecursionError
7102 outside of the code that we actually want to test.
7103 As the issue seems to be with coverage, skip the test on PyPy.
7104 https://github.com/pylint-dev/astroid/pull/1984#issuecomment-1407720311
7105 """
7106 code = """
7107 class MyInnerClass:
7108 ...
7109
7110
7111 class MySubClass:
7112 inner_class = MyInnerClass
7113
7114
7115 class MyClass:
7116 sub_class = MySubClass()
7117
7118
7119 def get_unpatched_class(cls):
7120 return cls
7121
7122
7123 def get_unpatched(item):
7124 lookup = get_unpatched_class if isinstance(item, type) else lambda item: None
7125 return lookup(item)
7126
7127
7128 _Child = get_unpatched(MyClass.sub_class.inner_class)
7129
7130
7131 class Child(_Child):
7132 def patch(cls):
7133 MyClass.sub_class.inner_class = cls
7134 """
7135 module = parse(code)
7136 assert module
7137
7138
7139 def test_function_def_cached_generator() -> None:
7140 """Regression test for https://github.com/pylint-dev/astroid/issues/817."""
7141 funcdef: nodes.FunctionDef = extract_node("def func(): pass")
7142 next(funcdef._infer())
7143
7144
7145 class TestOldStyleStringFormatting:
7146 @pytest.mark.parametrize(
7147 "format_string",
7148 [
7149 pytest.param(
7150 """"My name is %s, I'm %s" % ("Daniel", 12)""", id="empty-indexes"
7151 ),
7152 pytest.param(
7153 """"My name is %0s, I'm %1s" % ("Daniel", 12)""",
7154 id="numbered-indexes",
7155 ),
7156 pytest.param(
7157 """
7158 fname = "Daniel"
7159 age = 12
7160 "My name is %s, I'm %s" % (fname, age)
7161 """,
7162 id="empty-indexes-from-positional",
7163 ),
7164 pytest.param(
7165 """
7166 fname = "Daniel"
7167 age = 12
7168 "My name is %0s, I'm %1s" % (fname, age)
7169 """,
7170 id="numbered-indexes-from-positionl",
7171 ),
7172 pytest.param(
7173 """
7174 fname = "Daniel"
7175 age = 12
7176 "My name is %(fname)s, I'm %(age)s" % {"fname": fname, "age": age}
7177 """,
7178 id="named-indexes-from-keyword",
7179 ),
7180 pytest.param(
7181 """
7182 string = "My name is %s, I'm %s"
7183 string % ("Daniel", 12)
7184 """,
7185 id="empty-indexes-on-variable",
7186 ),
7187 pytest.param(
7188 """"My name is Daniel, I'm %s" % 12""", id="empty-indexes-from-variable"
7189 ),
7190 pytest.param(
7191 """
7192 age = 12
7193 "My name is Daniel, I'm %s" % age
7194 """,
7195 id="empty-indexes-from-variable",
7196 ),
7197 ],
7198 )
7199 def test_old_style_string_formatting(self, format_string: str) -> None:
7200 node: nodes.Call = _extract_single_node(format_string)
7201 inferred = next(node.infer())
7202 assert isinstance(inferred, nodes.Const)
7203 assert inferred.value == "My name is Daniel, I'm 12"
7204
7205 @pytest.mark.parametrize(
7206 "format_string",
7207 [
7208 """
7209 from missing import Unknown
7210 fname = Unknown
7211 age = 12
7212 "My name is %(fname)s, I'm %(age)s" % {"fname": fname, "age": age}
7213 """,
7214 """
7215 from missing import fname
7216 age = 12
7217 "My name is %(fname)s, I'm %(age)s" % {"fname": fname, "age": age}
7218 """,
7219 """
7220 from missing import fname
7221 "My name is %s, I'm %s" % (fname, 12)
7222 """,
7223 """
7224 "My name is %0s, I'm %1s" % ("Daniel")
7225 """,
7226 """"I am %s" % ()""",
7227 """"I am %s" % Exception()""",
7228 """
7229 fsname = "Daniel"
7230 "My name is %(fname)s, I'm %(age)s" % {"fsname": fsname, "age": age}
7231 """,
7232 """
7233 "My name is %(fname)s, I'm %(age)s" % {Exception(): "Daniel", "age": age}
7234 """,
7235 """
7236 fname = "Daniel"
7237 age = 12
7238 "My name is %0s, I'm %(age)s" % (fname, age)
7239 """,
7240 """
7241 "My name is %s, I'm %s" % ((fname,)*2)
7242 """,
7243 """20 % 0""",
7244 """("%" + str(20)) % 0""",
7245 ],
7246 )
7247 def test_old_style_string_formatting_uninferable(self, format_string: str) -> None:
7248 node: nodes.Call = _extract_single_node(format_string)
7249 inferred = next(node.infer())
7250 assert inferred is util.Uninferable
7251
7252 def test_old_style_string_formatting_with_specs(self) -> None:
7253 node: nodes.Call = _extract_single_node(
7254 """"My name is %s, I'm %.2f" % ("Daniel", 12)"""
7255 )
7256 inferred = next(node.infer())
7257 assert isinstance(inferred, nodes.Const)
7258 assert inferred.value == "My name is Daniel, I'm 12.00"
7259
7260 @pytest.mark.parametrize(
7261 "format_string",
7262 [
7263 '"%1000000000d" % 1',
7264 '"%-1000000000s" % "x"',
7265 '"%.1000000000f" % 1.0',
7266 '"%*s" % (1000000000, "x")',
7267 '"%*s" % (-1000000000, "x")',
7268 '"%.*f" % (1000000000, 1.0)',
7269 '"%(x)1000000000s" % {"x": "y"}',
7270 '"%((x))1000000000s" % {"(x)": "y"}',
7271 'b"%1000000000d" % 1',
7272 'x = "%1000000000d"\nx %= 1\nx',
7273 ],
7274 )
7275 def test_old_style_string_formatting_oversized(self, format_string: str) -> None:
7276 # A tiny literal must not materialize a multi-gigabyte string.
7277 node = _extract_single_node(format_string)
7278 assert next(node.infer()) is util.Uninferable
7279
7280 def test_old_style_string_formatting_length_modifier(self) -> None:
7281 # h/l/L length modifiers are skipped and do not affect the size cap.
7282 node = _extract_single_node('"%ld" % 5')
7283 inferred = next(node.infer())
7284 assert isinstance(inferred, nodes.Const)
7285 assert inferred.value == "5"
7286
7287 def test_old_style_string_formatting_star_not_width(self) -> None:
7288 # Only arguments consumed by a * width/precision count toward the cap.
7289 node = _extract_single_node('"%*d %d" % (5, 7, 200000001)')
7290 inferred = next(node.infer())
7291 assert isinstance(inferred, nodes.Const)
7292 assert inferred.value == " 7 200000001"
7293
7294
7295 def test_sys_argv_uninferable() -> None:
7296 """Regression test for https://github.com/pylint-dev/pylint/issues/7710."""
7297 a: nodes.List = extract_node(textwrap.dedent("""
7298 import sys
7299
7300 sys.argv"""))
7301 sys_argv_value = list(a._infer())
7302 assert len(sys_argv_value) == 1
7303 assert sys_argv_value[0] is Uninferable
7304
7305
7306 def test_empty_format_spec() -> None:
7307 """Regression test for https://github.com/pylint-dev/pylint/issues/9945."""
7308 node = extract_node('f"{x:}"')
7309 assert isinstance(node, nodes.JoinedStr)
7310
7311 assert list(node.infer()) == [util.Uninferable]
7312
7313
7314 @pytest.mark.parametrize(
7315 "code",
7316 [
7317 '"{:>2000000000}".format("x")',
7318 '"{:.2000000000f}".format(1.5)',
7319 ],
7320 )
7321 def test_str_format_oversized_width_uninferable(code: str) -> None:
7322 """str.format() with a huge width/precision must stay Uninferable."""
7323 node = _extract_single_node(code)
7324 assert next(node.infer()) is util.Uninferable
7325
7326
7327 @pytest.mark.parametrize(
7328 "code",
7329 [
7330 '"{".format()',
7331 '"}{".format()',
7332 ],
7333 )
7334 def test_str_format_malformed_template_uninferable(code: str) -> None:
7335 """A template Formatter().parse() rejects must stay Uninferable."""
7336 node = _extract_single_node(code)
7337 assert next(node.infer()) is util.Uninferable
7338
7339
7340 @pytest.mark.parametrize(
7341 "source, expected",
7342 [
7343 (
7344 """
7345 class Cls:
7346 # pylint: disable=too-few-public-methods
7347 pass
7348
7349 c_obj = Cls()
7350
7351 s1 = f'{c_obj!r}' #@
7352 """,
7353 "<__main__.Cls",
7354 ),
7355 (
7356 "s1 = f'{5}' #@",
7357 "5",
7358 ),
7359 ("s1 = f'{missing}'", None),
7360 ("s1 = f'a/{missing}/b'", None),
7361 ],
7362 )
7363 def test_joined_str_returns_string(source, expected) -> None:
7364 """Regression test for https://github.com/pylint-dev/pylint/issues/9947."""
7365 node = extract_node(source)
7366 assert isinstance(node, nodes.Assign)
7367 target = node.targets[0]
7368 assert target
7369 inferred = list(target.inferred())
7370 assert len(inferred) == 1
7371 if expected:
7372 assert isinstance(inferred[0], nodes.Const)
7373 inferred[0].value.startswith(expected)
7374 else:
7375 assert inferred[0] is Uninferable
7376
7377
7378 def test_joined_str_uninferable() -> None:
7379 """`thing` is not known, therefore the joinedstring should be
7380 Uninferable
7381 """
7382 code = """
7383 def hey(thing):
7384 return thing
7385
7386 f"Hello {hey()}"
7387 """
7388 joined_str = extract_node(code)
7389 constant_value, formatted_value = joined_str.values
7390 assert constant_value.value == "Hello "
7391 assert formatted_value.value.as_string() == "hey()"
7392 inferred = next(joined_str.infer())
7393 assert inferred is util.Uninferable
7394
7395
7396 def test_overloaded_dunder_uses_implementation() -> None:
7397 """Overload stubs must not shadow the real dunder implementation.
7398
7399 https://github.com/pylint-dev/astroid/issues/2448
7400 """
7401 code = """
7402 from typing import overload
7403
7404 class Fraction:
7405 @overload
7406 def __truediv__(self, other: int) -> list: ...
7407 @overload
7408 def __truediv__(self, other: str) -> list: ...
7409 def __truediv__(self, other):
7410 return []
7411
7412 @overload
7413 def __neg__(self) -> list: ...
7414 def __neg__(self):
7415 return []
7416
7417 Fraction() / 1 #@
7418 -Fraction() #@
7419 """
7420 binop, unaryop = extract_node(code)
7421 assert isinstance(next(binop.infer()), nodes.List)
7422 assert isinstance(next(unaryop.infer()), nodes.List)
7423
7424
7425 def test_decimal_inference():
7426 """
7427 Test we can infer the Decimal class from both the decimal and _pydecimal modules.
7428
7429 decimal uses _decimal by default, but that can be unavailable. The fallback can't be inferred
7430 by default so we have a brain.
7431 """
7432 code = """
7433 from decimal import Decimal #@
7434 from _pydecimal import Decimal #@
7435 """
7436 for node in extract_node(code):
7437 module = node.do_import_module(node.modname)
7438 module.getattr(node.names[0][0])