Debian Codegraph @

tests/test_lookup.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 variable lookup capabilities."""
6
7 import functools
8 import unittest
9
10 from astroid import builder, nodes
11 from astroid.exceptions import (
12 AttributeInferenceError,
13 InferenceError,
14 NameInferenceError,
15 )
16
17 from . import resources
18
19
20 class LookupTest(resources.SysPathSetup, unittest.TestCase):
21 def setUp(self) -> None:
22 super().setUp()
23 self.module = resources.build_file("data/module.py", "data.module")
24 self.module2 = resources.build_file("data/module2.py", "data.module2")
25 self.nonregr = resources.build_file("data/nonregr.py", "data.nonregr")
26
27 def test_limit(self) -> None:
28 code = """
29 l = [a
30 for a,b in list]
31
32 a = 1
33 b = a
34 a = None
35
36 def func():
37 c = 1
38 """
39 astroid = builder.parse(code, __name__)
40 # a & b
41 a = next(astroid.nodes_of_class(nodes.Name))
42 self.assertEqual(a.lineno, 2)
43 self.assertEqual(len(astroid.lookup("b")[1]), 1)
44 self.assertEqual(len(astroid.lookup("a")[1]), 1)
45 b = astroid.locals["b"][0]
46 stmts = a.lookup("a")[1]
47 self.assertEqual(len(stmts), 1)
48 self.assertEqual(b.lineno, 6)
49 b_infer = b.infer()
50 b_value = next(b_infer)
51 self.assertEqual(b_value.value, 1)
52 # c
53 self.assertRaises(StopIteration, functools.partial(next, b_infer))
54 func = astroid.locals["func"][0]
55 self.assertEqual(len(func.lookup("c")[1]), 1)
56
57 def test_module(self) -> None:
58 astroid = builder.parse("pass", __name__)
59 # built-in objects
60 none = next(astroid.ilookup("None"))
61 self.assertIsNone(none.value)
62 obj = next(astroid.ilookup("object"))
63 self.assertIsInstance(obj, nodes.ClassDef)
64 self.assertEqual(obj.name, "object")
65 self.assertRaises(
66 InferenceError, functools.partial(next, astroid.ilookup("YOAA"))
67 )
68
69 # XXX
70 self.assertEqual(len(list(self.nonregr.ilookup("enumerate"))), 2)
71
72 def test_class_ancestor_name(self) -> None:
73 code = """
74 class A:
75 pass
76
77 class A(A):
78 pass
79 """
80 astroid = builder.parse(code, __name__)
81 cls1 = astroid.locals["A"][0]
82 cls2 = astroid.locals["A"][1]
83 name = next(cls2.nodes_of_class(nodes.Name))
84 self.assertEqual(next(name.infer()), cls1)
85
86 # backport those test to inline code
87 def test_method(self) -> None:
88 method = self.module["YOUPI"]["method"]
89 my_dict = next(method.ilookup("MY_DICT"))
90 self.assertTrue(isinstance(my_dict, nodes.Dict), my_dict)
91 none = next(method.ilookup("None"))
92 self.assertIsNone(none.value)
93 self.assertRaises(
94 InferenceError, functools.partial(next, method.ilookup("YOAA"))
95 )
96
97 def test_function_argument_with_default(self) -> None:
98 make_class = self.module2["make_class"]
99 base = next(make_class.ilookup("base"))
100 self.assertTrue(isinstance(base, nodes.ClassDef), base.__class__)
101 self.assertEqual(base.name, "YO")
102 self.assertEqual(base.root().name, "data.module")
103
104 def test_class(self) -> None:
105 klass = self.module["YOUPI"]
106 my_dict = next(klass.ilookup("MY_DICT"))
107 self.assertIsInstance(my_dict, nodes.Dict)
108 none = next(klass.ilookup("None"))
109 self.assertIsNone(none.value)
110 obj = next(klass.ilookup("object"))
111 self.assertIsInstance(obj, nodes.ClassDef)
112 self.assertEqual(obj.name, "object")
113 self.assertRaises(
114 InferenceError, functools.partial(next, klass.ilookup("YOAA"))
115 )
116
117 def test_inner_classes(self) -> None:
118 ddd = list(self.nonregr["Ccc"].ilookup("Ddd"))
119 self.assertEqual(ddd[0].name, "Ddd")
120
121 def test_loopvar_hiding(self) -> None:
122 astroid = builder.parse(
123 """
124 x = 10
125 for x in range(5):
126 print (x)
127
128 if x > 0:
129 print ('#' * x)
130 """,
131 __name__,
132 )
133 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
134 # inside the loop, only one possible assignment
135 self.assertEqual(len(xnames[0].lookup("x")[1]), 1)
136 # outside the loop, two possible assignments
137 self.assertEqual(len(xnames[1].lookup("x")[1]), 2)
138 self.assertEqual(len(xnames[2].lookup("x")[1]), 2)
139
140 def test_list_comps(self) -> None:
141 astroid = builder.parse(
142 """
143 print ([ i for i in range(10) ])
144 print ([ i for i in range(10) ])
145 print ( list( i for i in range(10) ) )
146 """,
147 __name__,
148 )
149 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
150 self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
151 self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
152 self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
153 self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
154 self.assertEqual(len(xnames[2].lookup("i")[1]), 1)
155 self.assertEqual(xnames[2].lookup("i")[1][0].lineno, 4)
156
157 def test_list_comp_target(self) -> None:
158 """Test the list comprehension target."""
159 astroid = builder.parse("""
160 ten = [ var for var in range(10) ]
161 var
162 """)
163 var = astroid.body[1].value
164 self.assertRaises(NameInferenceError, var.inferred)
165
166 def test_dict_comps(self) -> None:
167 astroid = builder.parse(
168 """
169 print ({ i: j for i in range(10) for j in range(10) })
170 print ({ i: j for i in range(10) for j in range(10) })
171 """,
172 __name__,
173 )
174 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
175 self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
176 self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
177 self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
178 self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
179
180 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "j"]
181 self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
182 self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
183 self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
184 self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
185
186 def test_set_comps(self) -> None:
187 astroid = builder.parse(
188 """
189 print ({ i for i in range(10) })
190 print ({ i for i in range(10) })
191 """,
192 __name__,
193 )
194 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
195 self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
196 self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
197 self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
198 self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
199
200 def test_set_comp_closure(self) -> None:
201 astroid = builder.parse("""
202 ten = { var for var in range(10) }
203 var
204 """)
205 var = astroid.body[1].value
206 self.assertRaises(NameInferenceError, var.inferred)
207
208 def test_list_comp_nested(self) -> None:
209 astroid = builder.parse(
210 """
211 x = [[i + j for j in range(20)]
212 for i in range(10)]
213 """,
214 __name__,
215 )
216 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
217 self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
218 self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 3)
219
220 def test_dict_comp_nested(self) -> None:
221 astroid = builder.parse(
222 """
223 x = {i: {i: j for j in range(20)}
224 for i in range(10)}
225 x3 = [{i + j for j in range(20)} # Can't do nested sets
226 for i in range(10)]
227 """,
228 __name__,
229 )
230 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
231 self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
232 self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 3)
233 self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
234 self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
235
236 def test_set_comp_nested(self) -> None:
237 astroid = builder.parse(
238 """
239 x = [{i + j for j in range(20)} # Can't do nested sets
240 for i in range(10)]
241 """,
242 __name__,
243 )
244 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
245 self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
246 self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 3)
247
248 def test_lambda_nested(self) -> None:
249 astroid = builder.parse("""
250 f = lambda x: (
251 lambda y: x + y)
252 """)
253 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
254 self.assertEqual(len(xnames[0].lookup("x")[1]), 1)
255 self.assertEqual(xnames[0].lookup("x")[1][0].lineno, 2)
256
257 def test_function_nested(self) -> None:
258 astroid = builder.parse("""
259 def f1(x):
260 def f2(y):
261 return x + y
262
263 return f2
264 """)
265 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
266 self.assertEqual(len(xnames[0].lookup("x")[1]), 1)
267 self.assertEqual(xnames[0].lookup("x")[1][0].lineno, 2)
268
269 def test_class_variables(self) -> None:
270 # Class variables are NOT available within nested scopes.
271 astroid = builder.parse("""
272 class A:
273 a = 10
274
275 def f1(self):
276 return a # a is not defined
277
278 f2 = lambda: a # a is not defined
279
280 b = [a for _ in range(10)] # a is not defined
281
282 class _Inner:
283 inner_a = a + 1
284 """)
285 names = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "a"]
286 self.assertEqual(len(names), 4)
287 for name in names:
288 self.assertRaises(NameInferenceError, name.inferred)
289
290 def test_class_in_function(self) -> None:
291 # Function variables are available within classes, including methods
292 astroid = builder.parse("""
293 def f():
294 x = 10
295 class A:
296 a = x
297
298 def f1(self):
299 return x
300
301 f2 = lambda: x
302
303 b = [x for _ in range(10)]
304
305 class _Inner:
306 inner_a = x + 1
307 """)
308 names = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
309 self.assertEqual(len(names), 5)
310 for name in names:
311 self.assertEqual(len(name.lookup("x")[1]), 1, repr(name))
312 self.assertEqual(name.lookup("x")[1][0].lineno, 3, repr(name))
313
314 def test_explicit___name__(self) -> None:
315 code = """
316 class Pouet:
317 __name__ = "pouet"
318 p1 = Pouet()
319
320 class PouetPouet(Pouet): pass
321 p2 = Pouet()
322
323 class NoName: pass
324 p3 = NoName()
325 """
326 astroid = builder.parse(code, __name__)
327 p1 = next(astroid["p1"].infer())
328 self.assertTrue(p1.getattr("__name__"))
329 p2 = next(astroid["p2"].infer())
330 self.assertTrue(p2.getattr("__name__"))
331 self.assertTrue(astroid["NoName"].getattr("__name__"))
332 p3 = next(astroid["p3"].infer())
333 self.assertRaises(AttributeInferenceError, p3.getattr, "__name__")
334
335 def test_function_module_special(self) -> None:
336 astroid = builder.parse(
337 '''
338 def initialize(linter):
339 """initialize linter with checkers in this package """
340 package_load(linter, __path__[0])
341 ''',
342 "data.__init__",
343 )
344 path = next(
345 n for n in astroid.nodes_of_class(nodes.Name) if n.name == "__path__"
346 )
347 self.assertEqual(len(path.lookup("__path__")[1]), 1)
348
349 def test_builtin_lookup(self) -> None:
350 self.assertEqual(nodes.builtin_lookup("__dict__")[1], ())
351 intstmts = nodes.builtin_lookup("int")[1]
352 self.assertEqual(len(intstmts), 1)
353 self.assertIsInstance(intstmts[0], nodes.ClassDef)
354 self.assertEqual(intstmts[0].name, "int")
355 self.assertIs(intstmts[0], nodes.const_factory(1)._proxied)
356
357 def test_decorator_arguments_lookup(self) -> None:
358 code = """
359 def decorator(value):
360 def wrapper(function):
361 return function
362 return wrapper
363
364 class foo:
365 member = 10 #@
366
367 @decorator(member) #This will cause pylint to complain
368 def test(self):
369 pass
370 """
371
372 node = builder.extract_node(code, __name__)
373 assert isinstance(node, nodes.Assign)
374 member = node.targets[0]
375 it = member.infer()
376 obj = next(it)
377 self.assertIsInstance(obj, nodes.Const)
378 self.assertEqual(obj.value, 10)
379 self.assertRaises(StopIteration, functools.partial(next, it))
380
381 def test_inner_decorator_member_lookup(self) -> None:
382 code = """
383 class FileA:
384 def decorator(bla):
385 return bla
386
387 @__(decorator)
388 def funcA():
389 return 4
390 """
391 decname = builder.extract_node(code, __name__)
392 it = decname.infer()
393 obj = next(it)
394 self.assertIsInstance(obj, nodes.FunctionDef)
395 self.assertRaises(StopIteration, functools.partial(next, it))
396
397 def test_static_method_lookup(self) -> None:
398 code = """
399 class FileA:
400 @staticmethod
401 def funcA():
402 return 4
403
404
405 class Test:
406 FileA = [1,2,3]
407
408 def __init__(self):
409 print (FileA.funcA())
410 """
411 astroid = builder.parse(code, __name__)
412 it = astroid["Test"]["__init__"].ilookup("FileA")
413 obj = next(it)
414 self.assertIsInstance(obj, nodes.ClassDef)
415 self.assertRaises(StopIteration, functools.partial(next, it))
416
417 def test_global_delete(self) -> None:
418 code = """
419 def run2():
420 f = Frobble()
421
422 class Frobble:
423 pass
424 Frobble.mumble = True
425
426 del Frobble
427
428 def run1():
429 f = Frobble()
430 """
431 astroid = builder.parse(code, __name__)
432 stmts = astroid["run2"].lookup("Frobbel")[1]
433 self.assertEqual(len(stmts), 0)
434 stmts = astroid["run1"].lookup("Frobbel")[1]
435 self.assertEqual(len(stmts), 0)
436
437
438 class LookupControlFlowTest(unittest.TestCase):
439 """Tests for lookup capabilities and control flow."""
440
441 def test_consecutive_assign(self) -> None:
442 """When multiple assignment statements are in the same block, only the last one
443 is returned.
444 """
445 code = """
446 x = 10
447 x = 100
448 print(x)
449 """
450 astroid = builder.parse(code)
451 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
452 _, stmts = x_name.lookup("x")
453 self.assertEqual(len(stmts), 1)
454 self.assertEqual(stmts[0].lineno, 3)
455
456 def test_assign_after_use(self) -> None:
457 """An assignment statement appearing after the variable is not returned."""
458 code = """
459 print(x)
460 x = 10
461 """
462 astroid = builder.parse(code)
463 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
464 _, stmts = x_name.lookup("x")
465 self.assertEqual(len(stmts), 0)
466
467 def test_del_removes_prior(self) -> None:
468 """Delete statement removes any prior assignments."""
469 code = """
470 x = 10
471 del x
472 print(x)
473 """
474 astroid = builder.parse(code)
475 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
476 _, stmts = x_name.lookup("x")
477 self.assertEqual(len(stmts), 0)
478
479 def test_del_no_effect_after(self) -> None:
480 """Delete statement doesn't remove future assignments."""
481 code = """
482 x = 10
483 del x
484 x = 100
485 print(x)
486 """
487 astroid = builder.parse(code)
488 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
489 _, stmts = x_name.lookup("x")
490 self.assertEqual(len(stmts), 1)
491 self.assertEqual(stmts[0].lineno, 4)
492
493 def test_if_assign(self) -> None:
494 """Assignment in if statement is added to lookup results, but does not replace
495 prior assignments.
496 """
497 code = """
498 def f(b):
499 x = 10
500 if b:
501 x = 100
502 print(x)
503 """
504 astroid = builder.parse(code)
505 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
506 _, stmts = x_name.lookup("x")
507 self.assertEqual(len(stmts), 2)
508 self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 5])
509
510 def test_if_assigns_same_branch(self) -> None:
511 """When if branch has multiple assignment statements, only the last one
512 is added.
513 """
514 code = """
515 def f(b):
516 x = 10
517 if b:
518 x = 100
519 x = 1000
520 print(x)
521 """
522 astroid = builder.parse(code)
523 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
524 _, stmts = x_name.lookup("x")
525 self.assertEqual(len(stmts), 2)
526 self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 6])
527
528 def test_if_assigns_different_branch(self) -> None:
529 """When different branches have assignment statements, the last one
530 in each branch is added.
531 """
532 code = """
533 def f(b):
534 x = 10
535 if b == 1:
536 x = 100
537 x = 1000
538 elif b == 2:
539 x = 3
540 elif b == 3:
541 x = 4
542 print(x)
543 """
544 astroid = builder.parse(code)
545 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
546 _, stmts = x_name.lookup("x")
547 self.assertEqual(len(stmts), 4)
548 self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 6, 8, 10])
549
550 def test_assign_exclusive(self) -> None:
551 """When the variable appears inside a branch of an if statement,
552 no assignment statements from other branches are returned.
553 """
554 code = """
555 def f(b):
556 x = 10
557 if b == 1:
558 x = 100
559 x = 1000
560 elif b == 2:
561 x = 3
562 elif b == 3:
563 x = 4
564 else:
565 print(x)
566 """
567 astroid = builder.parse(code)
568 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
569 _, stmts = x_name.lookup("x")
570 self.assertEqual(len(stmts), 1)
571 self.assertEqual(stmts[0].lineno, 3)
572
573 def test_assign_not_exclusive(self) -> None:
574 """When the variable appears inside a branch of an if statement,
575 only the last assignment statement in the same branch is returned.
576 """
577 code = """
578 def f(b):
579 x = 10
580 if b == 1:
581 x = 100
582 x = 1000
583 elif b == 2:
584 x = 3
585 elif b == 3:
586 x = 4
587 print(x)
588 else:
589 x = 5
590 """
591 astroid = builder.parse(code)
592 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
593 _, stmts = x_name.lookup("x")
594 self.assertEqual(len(stmts), 1)
595 self.assertEqual(stmts[0].lineno, 10)
596
597 def test_if_else(self) -> None:
598 """When an assignment statement appears in both an if and else branch, both
599 are added.
600
601 This does NOT replace an assignment statement appearing before the
602 if statement. (See issue #213)
603 """
604 code = """
605 def f(b):
606 x = 10
607 if b:
608 x = 100
609 else:
610 x = 1000
611 print(x)
612 """
613 astroid = builder.parse(code)
614 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
615 _, stmts = x_name.lookup("x")
616 self.assertEqual(len(stmts), 3)
617 self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 5, 7])
618
619 def test_if_variable_in_condition_1(self) -> None:
620 """Test lookup works correctly when a variable appears in an if condition."""
621 code = """
622 x = 10
623 if x > 10:
624 print('a')
625 elif x > 0:
626 print('b')
627 """
628 astroid = builder.parse(code)
629 x_name1, x_name2 = (
630 n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"
631 )
632
633 _, stmts1 = x_name1.lookup("x")
634 self.assertEqual(len(stmts1), 1)
635 self.assertEqual(stmts1[0].lineno, 2)
636
637 _, stmts2 = x_name2.lookup("x")
638 self.assertEqual(len(stmts2), 1)
639 self.assertEqual(stmts2[0].lineno, 2)
640
641 def test_if_variable_in_condition_2(self) -> None:
642 """Test lookup works correctly when a variable appears in an if condition,
643 and the variable is reassigned in each branch.
644
645 This is based on pylint-dev/pylint issue #3711.
646 """
647 code = """
648 x = 10
649 if x > 10:
650 x = 100
651 elif x > 0:
652 x = 200
653 elif x > -10:
654 x = 300
655 else:
656 x = 400
657 """
658 astroid = builder.parse(code)
659 x_names = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
660
661 # All lookups should refer only to the initial x = 10.
662 for x_name in x_names:
663 _, stmts = x_name.lookup("x")
664 self.assertEqual(len(stmts), 1)
665 self.assertEqual(stmts[0].lineno, 2)
666
667 def test_del_not_exclusive(self) -> None:
668 """A delete statement in an if statement branch removes all previous
669 assignment statements when the delete statement is not exclusive with
670 the variable (e.g., when the variable is used below the if statement).
671 """
672 code = """
673 def f(b):
674 x = 10
675 if b == 1:
676 x = 100
677 elif b == 2:
678 del x
679 elif b == 3:
680 x = 4 # Only this assignment statement is returned
681 print(x)
682 """
683 astroid = builder.parse(code)
684 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
685 _, stmts = x_name.lookup("x")
686 self.assertEqual(len(stmts), 1)
687 self.assertEqual(stmts[0].lineno, 9)
688
689 def test_del_exclusive(self) -> None:
690 """A delete statement in an if statement branch that is exclusive with the
691 variable does not remove previous assignment statements.
692 """
693 code = """
694 def f(b):
695 x = 10
696 if b == 1:
697 x = 100
698 elif b == 2:
699 del x
700 else:
701 print(x)
702 """
703 astroid = builder.parse(code)
704 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
705 _, stmts = x_name.lookup("x")
706 self.assertEqual(len(stmts), 1)
707 self.assertEqual(stmts[0].lineno, 3)
708
709 def test_assign_after_param(self) -> None:
710 """When an assignment statement overwrites a function parameter, only the
711 assignment is returned, even when the variable and assignment do not have
712 the same parent.
713 """
714 code = """
715 def f1(x):
716 x = 100
717 print(x)
718
719 def f2(x):
720 x = 100
721 if True:
722 print(x)
723 """
724 astroid = builder.parse(code)
725 x_name1, x_name2 = (
726 n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"
727 )
728 _, stmts1 = x_name1.lookup("x")
729 self.assertEqual(len(stmts1), 1)
730 self.assertEqual(stmts1[0].lineno, 3)
731
732 _, stmts2 = x_name2.lookup("x")
733 self.assertEqual(len(stmts2), 1)
734 self.assertEqual(stmts2[0].lineno, 7)
735
736 def test_assign_after_kwonly_param(self) -> None:
737 """When an assignment statement overwrites a function keyword-only parameter,
738 only the assignment is returned, even when the variable and assignment do
739 not have the same parent.
740 """
741 code = """
742 def f1(*, x):
743 x = 100
744 print(x)
745
746 def f2(*, x):
747 x = 100
748 if True:
749 print(x)
750 """
751 astroid = builder.parse(code)
752 x_name1, x_name2 = (
753 n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"
754 )
755 _, stmts1 = x_name1.lookup("x")
756 self.assertEqual(len(stmts1), 1)
757 self.assertEqual(stmts1[0].lineno, 3)
758
759 _, stmts2 = x_name2.lookup("x")
760 self.assertEqual(len(stmts2), 1)
761 self.assertEqual(stmts2[0].lineno, 7)
762
763 def test_assign_after_posonly_param(self):
764 """When an assignment statement overwrites a function positional-only parameter,
765 only the assignment is returned, even when the variable and assignment do
766 not have the same parent.
767 """
768 code = """
769 def f1(x, /):
770 x = 100
771 print(x)
772
773 def f2(x, /):
774 x = 100
775 if True:
776 print(x)
777 """
778 astroid = builder.parse(code)
779 x_name1, x_name2 = (
780 n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"
781 )
782 _, stmts1 = x_name1.lookup("x")
783 self.assertEqual(len(stmts1), 1)
784 self.assertEqual(stmts1[0].lineno, 3)
785
786 _, stmts2 = x_name2.lookup("x")
787 self.assertEqual(len(stmts2), 1)
788 self.assertEqual(stmts2[0].lineno, 7)
789
790 def test_assign_after_args_param(self) -> None:
791 """When an assignment statement overwrites a function parameter, only the
792 assignment is returned.
793 """
794 code = """
795 def f(*args, **kwargs):
796 args = [100]
797 kwargs = {}
798 if True:
799 print(args, kwargs)
800 """
801 astroid = builder.parse(code)
802 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "args")
803 _, stmts1 = x_name.lookup("args")
804 self.assertEqual(len(stmts1), 1)
805 self.assertEqual(stmts1[0].lineno, 3)
806
807 x_name = next(
808 n for n in astroid.nodes_of_class(nodes.Name) if n.name == "kwargs"
809 )
810 _, stmts2 = x_name.lookup("kwargs")
811 self.assertEqual(len(stmts2), 1)
812 self.assertEqual(stmts2[0].lineno, 4)
813
814 def test_except_var_in_block(self) -> None:
815 """When the variable bound to an exception in an except clause, it is returned
816 when that variable is used inside the except block.
817 """
818 code = """
819 try:
820 1 / 0
821 except ZeroDivisionError as e:
822 print(e)
823 """
824 astroid = builder.parse(code)
825 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e")
826 _, stmts = x_name.lookup("e")
827 self.assertEqual(len(stmts), 1)
828 self.assertEqual(stmts[0].lineno, 4)
829
830 def test_except_var_in_block_overwrites(self) -> None:
831 """When the variable bound to an exception in an except clause, it is returned
832 when that variable is used inside the except block, and replaces any previous
833 assignments.
834 """
835 code = """
836 e = 0
837 try:
838 1 / 0
839 except ZeroDivisionError as e:
840 print(e)
841 """
842 astroid = builder.parse(code)
843 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e")
844 _, stmts = x_name.lookup("e")
845 self.assertEqual(len(stmts), 1)
846 self.assertEqual(stmts[0].lineno, 5)
847
848 def test_except_var_in_multiple_blocks(self) -> None:
849 """When multiple variables with the same name are bound to an exception
850 in an except clause, and the variable is used inside the except block,
851 only the assignment from the corresponding except clause is returned.
852 """
853 code = """
854 e = 0
855 try:
856 1 / 0
857 except ZeroDivisionError as e:
858 print(e)
859 except NameError as e:
860 print(e)
861 """
862 astroid = builder.parse(code)
863 x_names = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e"]
864
865 _, stmts1 = x_names[0].lookup("e")
866 self.assertEqual(len(stmts1), 1)
867 self.assertEqual(stmts1[0].lineno, 5)
868
869 _, stmts2 = x_names[1].lookup("e")
870 self.assertEqual(len(stmts2), 1)
871 self.assertEqual(stmts2[0].lineno, 7)
872
873 def test_except_var_after_block_single(self) -> None:
874 """When the variable bound to an exception in an except clause, it is NOT returned
875 when that variable is used after the except block.
876 """
877 code = """
878 try:
879 1 / 0
880 except NameError as e:
881 pass
882 print(e)
883 """
884 astroid = builder.parse(code)
885 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e")
886 _, stmts = x_name.lookup("e")
887 self.assertEqual(len(stmts), 0)
888
889 def test_except_var_after_block_multiple(self) -> None:
890 """When the variable bound to an exception in multiple except clauses, it is NOT returned
891 when that variable is used after the except blocks.
892 """
893 code = """
894 try:
895 1 / 0
896 except NameError as e:
897 pass
898 except ZeroDivisionError as e:
899 pass
900 print(e)
901 """
902 astroid = builder.parse(code)
903 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e")
904 _, stmts = x_name.lookup("e")
905 self.assertEqual(len(stmts), 0)
906
907 def test_except_assign_in_block(self) -> None:
908 """When a variable is assigned in an except block, it is returned
909 when that variable is used in the except block.
910 """
911 code = """
912 try:
913 1 / 0
914 except ZeroDivisionError as e:
915 x = 10
916 print(x)
917 """
918 astroid = builder.parse(code)
919 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
920 _, stmts = x_name.lookup("x")
921 self.assertEqual(len(stmts), 1)
922 self.assertEqual(stmts[0].lineno, 5)
923
924 def test_except_assign_in_block_multiple(self) -> None:
925 """When a variable is assigned in multiple except blocks, and the variable is
926 used in one of the blocks, only the assignments in that block are returned.
927 """
928 code = """
929 try:
930 1 / 0
931 except ZeroDivisionError:
932 x = 10
933 except NameError:
934 x = 100
935 print(x)
936 """
937 astroid = builder.parse(code)
938 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
939 _, stmts = x_name.lookup("x")
940 self.assertEqual(len(stmts), 1)
941 self.assertEqual(stmts[0].lineno, 7)
942
943 def test_except_assign_after_block(self) -> None:
944 """When a variable is assigned in an except clause, it is returned
945 when that variable is used after the except block.
946 """
947 code = """
948 try:
949 1 / 0
950 except ZeroDivisionError:
951 x = 10
952 except NameError:
953 x = 100
954 print(x)
955 """
956 astroid = builder.parse(code)
957 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
958 _, stmts = x_name.lookup("x")
959 self.assertEqual(len(stmts), 2)
960 self.assertCountEqual([stmt.lineno for stmt in stmts], [5, 7])
961
962 def test_except_assign_after_block_overwritten(self) -> None:
963 """When a variable is assigned in an except clause, it is not returned
964 when it is reassigned and used after the except block.
965 """
966 code = """
967 try:
968 1 / 0
969 except ZeroDivisionError:
970 x = 10
971 except NameError:
972 x = 100
973 x = 1000
974 print(x)
975 """
976 astroid = builder.parse(code)
977 x_name = next(n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x")
978 _, stmts = x_name.lookup("x")
979 self.assertEqual(len(stmts), 1)
980 self.assertEqual(stmts[0].lineno, 8)