summaryrefslogtreecommitdiff
path: root/tests/test_lookup.py
blob: 475516b60f55186ea8fb4071b34d8fbdaabe295e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
# Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt

"""Tests for the astroid variable lookup capabilities."""
import functools
import unittest

from astroid import builder, nodes, test_utils
from astroid.exceptions import (
    AttributeInferenceError,
    InferenceError,
    NameInferenceError,
)

from . import resources


class LookupTest(resources.SysPathSetup, unittest.TestCase):
    def setUp(self) -> None:
        super().setUp()
        self.module = resources.build_file("data/module.py", "data.module")
        self.module2 = resources.build_file("data/module2.py", "data.module2")
        self.nonregr = resources.build_file("data/nonregr.py", "data.nonregr")

    def test_limit(self) -> None:
        code = """
            l = [a
                 for a,b in list]

            a = 1
            b = a
            a = None

            def func():
                c = 1
        """
        astroid = builder.parse(code, __name__)
        # a & b
        a = next(astroid.nodes_of_class(nodes.Name))
        self.assertEqual(a.lineno, 2)
        self.assertEqual(len(astroid.lookup("b")[1]), 1)
        self.assertEqual(len(astroid.lookup("a")[1]), 1)
        b = astroid.locals["b"][0]
        stmts = a.lookup("a")[1]
        self.assertEqual(len(stmts), 1)
        self.assertEqual(b.lineno, 6)
        b_infer = b.infer()
        b_value = next(b_infer)
        self.assertEqual(b_value.value, 1)
        # c
        self.assertRaises(StopIteration, functools.partial(next, b_infer))
        func = astroid.locals["func"][0]
        self.assertEqual(len(func.lookup("c")[1]), 1)

    def test_module(self) -> None:
        astroid = builder.parse("pass", __name__)
        # built-in objects
        none = next(astroid.ilookup("None"))
        self.assertIsNone(none.value)
        obj = next(astroid.ilookup("object"))
        self.assertIsInstance(obj, nodes.ClassDef)
        self.assertEqual(obj.name, "object")
        self.assertRaises(
            InferenceError, functools.partial(next, astroid.ilookup("YOAA"))
        )

        # XXX
        self.assertEqual(len(list(self.nonregr.ilookup("enumerate"))), 2)

    def test_class_ancestor_name(self) -> None:
        code = """
            class A:
                pass

            class A(A):
                pass
        """
        astroid = builder.parse(code, __name__)
        cls1 = astroid.locals["A"][0]
        cls2 = astroid.locals["A"][1]
        name = next(cls2.nodes_of_class(nodes.Name))
        self.assertEqual(next(name.infer()), cls1)

    # backport those test to inline code
    def test_method(self) -> None:
        method = self.module["YOUPI"]["method"]
        my_dict = next(method.ilookup("MY_DICT"))
        self.assertTrue(isinstance(my_dict, nodes.Dict), my_dict)
        none = next(method.ilookup("None"))
        self.assertIsNone(none.value)
        self.assertRaises(
            InferenceError, functools.partial(next, method.ilookup("YOAA"))
        )

    def test_function_argument_with_default(self) -> None:
        make_class = self.module2["make_class"]
        base = next(make_class.ilookup("base"))
        self.assertTrue(isinstance(base, nodes.ClassDef), base.__class__)
        self.assertEqual(base.name, "YO")
        self.assertEqual(base.root().name, "data.module")

    def test_class(self) -> None:
        klass = self.module["YOUPI"]
        my_dict = next(klass.ilookup("MY_DICT"))
        self.assertIsInstance(my_dict, nodes.Dict)
        none = next(klass.ilookup("None"))
        self.assertIsNone(none.value)
        obj = next(klass.ilookup("object"))
        self.assertIsInstance(obj, nodes.ClassDef)
        self.assertEqual(obj.name, "object")
        self.assertRaises(
            InferenceError, functools.partial(next, klass.ilookup("YOAA"))
        )

    def test_inner_classes(self) -> None:
        ddd = list(self.nonregr["Ccc"].ilookup("Ddd"))
        self.assertEqual(ddd[0].name, "Ddd")

    def test_loopvar_hiding(self) -> None:
        astroid = builder.parse(
            """
            x = 10
            for x in range(5):
                print (x)

            if x > 0:
                print ('#' * x)
        """,
            __name__,
        )
        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
        # inside the loop, only one possible assignment
        self.assertEqual(len(xnames[0].lookup("x")[1]), 1)
        # outside the loop, two possible assignments
        self.assertEqual(len(xnames[1].lookup("x")[1]), 2)
        self.assertEqual(len(xnames[2].lookup("x")[1]), 2)

    def test_list_comps(self) -> None:
        astroid = builder.parse(
            """
            print ([ i for i in range(10) ])
            print ([ i for i in range(10) ])
            print ( list( i for i in range(10) ) )
        """,
            __name__,
        )
        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
        self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
        self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
        self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
        self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)
        self.assertEqual(len(xnames[2].lookup("i")[1]), 1)
        self.assertEqual(xnames[2].lookup("i")[1][0].lineno, 4)

    def test_list_comp_target(self) -> None:
        """Test the list comprehension target."""
        astroid = builder.parse(
            """
            ten = [ var for var in range(10) ]
            var
        """
        )
        var = astroid.body[1].value
        self.assertRaises(NameInferenceError, var.inferred)

    def test_dict_comps(self) -> None:
        astroid = builder.parse(
            """
            print ({ i: j for i in range(10) for j in range(10) })
            print ({ i: j for i in range(10) for j in range(10) })
        """,
            __name__,
        )
        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
        self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
        self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
        self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
        self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)

        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "j"]
        self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
        self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
        self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
        self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)

    def test_set_comps(self) -> None:
        astroid = builder.parse(
            """
            print ({ i for i in range(10) })
            print ({ i for i in range(10) })
        """,
            __name__,
        )
        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
        self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
        self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 2)
        self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
        self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)

    def test_set_comp_closure(self) -> None:
        astroid = builder.parse(
            """
            ten = { var for var in range(10) }
            var
        """
        )
        var = astroid.body[1].value
        self.assertRaises(NameInferenceError, var.inferred)

    def test_list_comp_nested(self) -> None:
        astroid = builder.parse(
            """
            x = [[i + j for j in range(20)]
                 for i in range(10)]
        """,
            __name__,
        )
        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
        self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
        self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 3)

    def test_dict_comp_nested(self) -> None:
        astroid = builder.parse(
            """
            x = {i: {i: j for j in range(20)}
                 for i in range(10)}
            x3 = [{i + j for j in range(20)}  # Can't do nested sets
                  for i in range(10)]
        """,
            __name__,
        )
        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
        self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
        self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 3)
        self.assertEqual(len(xnames[1].lookup("i")[1]), 1)
        self.assertEqual(xnames[1].lookup("i")[1][0].lineno, 3)

    def test_set_comp_nested(self) -> None:
        astroid = builder.parse(
            """
            x = [{i + j for j in range(20)}  # Can't do nested sets
                 for i in range(10)]
        """,
            __name__,
        )
        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "i"]
        self.assertEqual(len(xnames[0].lookup("i")[1]), 1)
        self.assertEqual(xnames[0].lookup("i")[1][0].lineno, 3)

    def test_lambda_nested(self) -> None:
        astroid = builder.parse(
            """
            f = lambda x: (
                    lambda y: x + y)
        """
        )
        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
        self.assertEqual(len(xnames[0].lookup("x")[1]), 1)
        self.assertEqual(xnames[0].lookup("x")[1][0].lineno, 2)

    def test_function_nested(self) -> None:
        astroid = builder.parse(
            """
            def f1(x):
                def f2(y):
                    return x + y

                return f2
        """
        )
        xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
        self.assertEqual(len(xnames[0].lookup("x")[1]), 1)
        self.assertEqual(xnames[0].lookup("x")[1][0].lineno, 2)

    def test_class_variables(self) -> None:
        # Class variables are NOT available within nested scopes.
        astroid = builder.parse(
            """
            class A:
                a = 10

                def f1(self):
                    return a  # a is not defined

                f2 = lambda: a  # a is not defined

                b = [a for _ in range(10)]  # a is not defined

                class _Inner:
                    inner_a = a + 1
            """
        )
        names = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "a"]
        self.assertEqual(len(names), 4)
        for name in names:
            self.assertRaises(NameInferenceError, name.inferred)

    def test_class_in_function(self) -> None:
        # Function variables are available within classes, including methods
        astroid = builder.parse(
            """
            def f():
                x = 10
                class A:
                    a = x

                    def f1(self):
                        return x

                    f2 = lambda: x

                    b = [x for _ in range(10)]

                    class _Inner:
                        inner_a = x + 1
        """
        )
        names = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]
        self.assertEqual(len(names), 5)
        for name in names:
            self.assertEqual(len(name.lookup("x")[1]), 1, repr(name))
            self.assertEqual(name.lookup("x")[1][0].lineno, 3, repr(name))

    def test_generator_attributes(self) -> None:
        tree = builder.parse(
            """
            def count():
                "test"
                yield 0

            iterer = count()
            num = iterer.next()
        """
        )
        next_node = tree.body[2].value.func
        gener = next_node.expr.inferred()[0]
        self.assertIsInstance(gener.getattr("__next__")[0], nodes.FunctionDef)
        self.assertIsInstance(gener.getattr("send")[0], nodes.FunctionDef)
        self.assertIsInstance(gener.getattr("throw")[0], nodes.FunctionDef)
        self.assertIsInstance(gener.getattr("close")[0], nodes.FunctionDef)

    def test_explicit___name__(self) -> None:
        code = """
            class Pouet:
                __name__ = "pouet"
            p1 = Pouet()

            class PouetPouet(Pouet): pass
            p2 = Pouet()

            class NoName: pass
            p3 = NoName()
        """
        astroid = builder.parse(code, __name__)
        p1 = next(astroid["p1"].infer())
        self.assertTrue(p1.getattr("__name__"))
        p2 = next(astroid["p2"].infer())
        self.assertTrue(p2.getattr("__name__"))
        self.assertTrue(astroid["NoName"].getattr("__name__"))
        p3 = next(astroid["p3"].infer())
        self.assertRaises(AttributeInferenceError, p3.getattr, "__name__")

    def test_function_module_special(self) -> None:
        astroid = builder.parse(
            '''
        def initialize(linter):
            """initialize linter with checkers in this package """
            package_load(linter, __path__[0])
        ''',
            "data.__init__",
        )
        path = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "__path__"][
            0
        ]
        self.assertEqual(len(path.lookup("__path__")[1]), 1)

    def test_builtin_lookup(self) -> None:
        self.assertEqual(nodes.builtin_lookup("__dict__")[1], ())
        intstmts = nodes.builtin_lookup("int")[1]
        self.assertEqual(len(intstmts), 1)
        self.assertIsInstance(intstmts[0], nodes.ClassDef)
        self.assertEqual(intstmts[0].name, "int")
        self.assertIs(intstmts[0], nodes.const_factory(1)._proxied)

    def test_decorator_arguments_lookup(self) -> None:
        code = """
            def decorator(value):
                def wrapper(function):
                    return function
                return wrapper

            class foo:
                member = 10  #@

                @decorator(member) #This will cause pylint to complain
                def test(self):
                    pass
        """

        node = builder.extract_node(code, __name__)
        assert isinstance(node, nodes.Assign)
        member = node.targets[0]
        it = member.infer()
        obj = next(it)
        self.assertIsInstance(obj, nodes.Const)
        self.assertEqual(obj.value, 10)
        self.assertRaises(StopIteration, functools.partial(next, it))

    def test_inner_decorator_member_lookup(self) -> None:
        code = """
            class FileA:
                def decorator(bla):
                    return bla

                @__(decorator)
                def funcA():
                    return 4
        """
        decname = builder.extract_node(code, __name__)
        it = decname.infer()
        obj = next(it)
        self.assertIsInstance(obj, nodes.FunctionDef)
        self.assertRaises(StopIteration, functools.partial(next, it))

    def test_static_method_lookup(self) -> None:
        code = """
            class FileA:
                @staticmethod
                def funcA():
                    return 4


            class Test:
                FileA = [1,2,3]

                def __init__(self):
                    print (FileA.funcA())
        """
        astroid = builder.parse(code, __name__)
        it = astroid["Test"]["__init__"].ilookup("FileA")
        obj = next(it)
        self.assertIsInstance(obj, nodes.ClassDef)
        self.assertRaises(StopIteration, functools.partial(next, it))

    def test_global_delete(self) -> None:
        code = """
            def run2():
                f = Frobble()

            class Frobble:
                pass
            Frobble.mumble = True

            del Frobble

            def run1():
                f = Frobble()
        """
        astroid = builder.parse(code, __name__)
        stmts = astroid["run2"].lookup("Frobbel")[1]
        self.assertEqual(len(stmts), 0)
        stmts = astroid["run1"].lookup("Frobbel")[1]
        self.assertEqual(len(stmts), 0)


class LookupControlFlowTest(unittest.TestCase):
    """Tests for lookup capabilities and control flow."""

    def test_consecutive_assign(self) -> None:
        """When multiple assignment statements are in the same block, only the last one
        is returned.
        """
        code = """
            x = 10
            x = 100
            print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 3)

    def test_assign_after_use(self) -> None:
        """An assignment statement appearing after the variable is not returned."""
        code = """
            print(x)
            x = 10
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 0)

    def test_del_removes_prior(self) -> None:
        """Delete statement removes any prior assignments."""
        code = """
            x = 10
            del x
            print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 0)

    def test_del_no_effect_after(self) -> None:
        """Delete statement doesn't remove future assignments."""
        code = """
            x = 10
            del x
            x = 100
            print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 4)

    def test_if_assign(self) -> None:
        """Assignment in if statement is added to lookup results, but does not replace
        prior assignments.
        """
        code = """
            def f(b):
                x = 10
                if b:
                    x = 100
                print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 2)
        self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 5])

    def test_if_assigns_same_branch(self) -> None:
        """When if branch has multiple assignment statements, only the last one
        is added.
        """
        code = """
            def f(b):
                x = 10
                if b:
                    x = 100
                    x = 1000
                print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 2)
        self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 6])

    def test_if_assigns_different_branch(self) -> None:
        """When different branches have assignment statements, the last one
        in each branch is added.
        """
        code = """
            def f(b):
                x = 10
                if b == 1:
                    x = 100
                    x = 1000
                elif b == 2:
                    x = 3
                elif b == 3:
                    x = 4
                print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 4)
        self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 6, 8, 10])

    def test_assign_exclusive(self) -> None:
        """When the variable appears inside a branch of an if statement,
        no assignment statements from other branches are returned.
        """
        code = """
            def f(b):
                x = 10
                if b == 1:
                    x = 100
                    x = 1000
                elif b == 2:
                    x = 3
                elif b == 3:
                    x = 4
                else:
                    print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 3)

    def test_assign_not_exclusive(self) -> None:
        """When the variable appears inside a branch of an if statement,
        only the last assignment statement in the same branch is returned.
        """
        code = """
            def f(b):
                x = 10
                if b == 1:
                    x = 100
                    x = 1000
                elif b == 2:
                    x = 3
                elif b == 3:
                    x = 4
                    print(x)
                else:
                    x = 5
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 10)

    def test_if_else(self) -> None:
        """When an assignment statement appears in both an if and else branch, both
        are added.

        This does NOT replace an assignment statement appearing before the
        if statement. (See issue #213)
        """
        code = """
            def f(b):
                x = 10
                if b:
                    x = 100
                else:
                    x = 1000
                print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 3)
        self.assertCountEqual([stmt.lineno for stmt in stmts], [3, 5, 7])

    def test_if_variable_in_condition_1(self) -> None:
        """Test lookup works correctly when a variable appears in an if condition."""
        code = """
            x = 10
            if x > 10:
                print('a')
            elif x > 0:
                print('b')
        """
        astroid = builder.parse(code)
        x_name1, x_name2 = (
            n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"
        )

        _, stmts1 = x_name1.lookup("x")
        self.assertEqual(len(stmts1), 1)
        self.assertEqual(stmts1[0].lineno, 2)

        _, stmts2 = x_name2.lookup("x")
        self.assertEqual(len(stmts2), 1)
        self.assertEqual(stmts2[0].lineno, 2)

    def test_if_variable_in_condition_2(self) -> None:
        """Test lookup works correctly when a variable appears in an if condition,
        and the variable is reassigned in each branch.

        This is based on pylint-dev/pylint issue #3711.
        """
        code = """
            x = 10
            if x > 10:
                x = 100
            elif x > 0:
                x = 200
            elif x > -10:
                x = 300
            else:
                x = 400
        """
        astroid = builder.parse(code)
        x_names = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"]

        # All lookups should refer only to the initial x = 10.
        for x_name in x_names:
            _, stmts = x_name.lookup("x")
            self.assertEqual(len(stmts), 1)
            self.assertEqual(stmts[0].lineno, 2)

    def test_del_not_exclusive(self) -> None:
        """A delete statement in an if statement branch removes all previous
        assignment statements when the delete statement is not exclusive with
        the variable (e.g., when the variable is used below the if statement).
        """
        code = """
            def f(b):
                x = 10
                if b == 1:
                    x = 100
                elif b == 2:
                    del x
                elif b == 3:
                    x = 4  # Only this assignment statement is returned
                print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 9)

    def test_del_exclusive(self) -> None:
        """A delete statement in an if statement branch that is exclusive with the
        variable does not remove previous assignment statements.
        """
        code = """
            def f(b):
                x = 10
                if b == 1:
                    x = 100
                elif b == 2:
                    del x
                else:
                    print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 3)

    def test_assign_after_param(self) -> None:
        """When an assignment statement overwrites a function parameter, only the
        assignment is returned, even when the variable and assignment do not have
        the same parent.
        """
        code = """
            def f1(x):
                x = 100
                print(x)

            def f2(x):
                x = 100
                if True:
                    print(x)
        """
        astroid = builder.parse(code)
        x_name1, x_name2 = (
            n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"
        )
        _, stmts1 = x_name1.lookup("x")
        self.assertEqual(len(stmts1), 1)
        self.assertEqual(stmts1[0].lineno, 3)

        _, stmts2 = x_name2.lookup("x")
        self.assertEqual(len(stmts2), 1)
        self.assertEqual(stmts2[0].lineno, 7)

    def test_assign_after_kwonly_param(self) -> None:
        """When an assignment statement overwrites a function keyword-only parameter,
        only the assignment is returned, even when the variable and assignment do
        not have the same parent.
        """
        code = """
            def f1(*, x):
                x = 100
                print(x)

            def f2(*, x):
                x = 100
                if True:
                    print(x)
        """
        astroid = builder.parse(code)
        x_name1, x_name2 = (
            n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"
        )
        _, stmts1 = x_name1.lookup("x")
        self.assertEqual(len(stmts1), 1)
        self.assertEqual(stmts1[0].lineno, 3)

        _, stmts2 = x_name2.lookup("x")
        self.assertEqual(len(stmts2), 1)
        self.assertEqual(stmts2[0].lineno, 7)

    @test_utils.require_version(minver="3.8")
    def test_assign_after_posonly_param(self):
        """When an assignment statement overwrites a function positional-only parameter,
        only the assignment is returned, even when the variable and assignment do
        not have the same parent.
        """
        code = """
            def f1(x, /):
                x = 100
                print(x)

            def f2(x, /):
                x = 100
                if True:
                    print(x)
        """
        astroid = builder.parse(code)
        x_name1, x_name2 = (
            n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"
        )
        _, stmts1 = x_name1.lookup("x")
        self.assertEqual(len(stmts1), 1)
        self.assertEqual(stmts1[0].lineno, 3)

        _, stmts2 = x_name2.lookup("x")
        self.assertEqual(len(stmts2), 1)
        self.assertEqual(stmts2[0].lineno, 7)

    def test_assign_after_args_param(self) -> None:
        """When an assignment statement overwrites a function parameter, only the
        assignment is returned.
        """
        code = """
            def f(*args, **kwargs):
                args = [100]
                kwargs = {}
                if True:
                    print(args, kwargs)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "args"][0]
        _, stmts1 = x_name.lookup("args")
        self.assertEqual(len(stmts1), 1)
        self.assertEqual(stmts1[0].lineno, 3)

        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "kwargs"][
            0
        ]
        _, stmts2 = x_name.lookup("kwargs")
        self.assertEqual(len(stmts2), 1)
        self.assertEqual(stmts2[0].lineno, 4)

    def test_except_var_in_block(self) -> None:
        """When the variable bound to an exception in an except clause, it is returned
        when that variable is used inside the except block.
        """
        code = """
            try:
                1 / 0
            except ZeroDivisionError as e:
                print(e)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e"][0]
        _, stmts = x_name.lookup("e")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 4)

    def test_except_var_in_block_overwrites(self) -> None:
        """When the variable bound to an exception in an except clause, it is returned
        when that variable is used inside the except block, and replaces any previous
        assignments.
        """
        code = """
            e = 0
            try:
                1 / 0
            except ZeroDivisionError as e:
                print(e)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e"][0]
        _, stmts = x_name.lookup("e")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 5)

    def test_except_var_in_multiple_blocks(self) -> None:
        """When multiple variables with the same name are bound to an exception
        in an except clause, and the variable is used inside the except block,
        only the assignment from the corresponding except clause is returned.
        """
        code = """
            e = 0
            try:
                1 / 0
            except ZeroDivisionError as e:
                print(e)
            except NameError as e:
                print(e)
        """
        astroid = builder.parse(code)
        x_names = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e"]

        _, stmts1 = x_names[0].lookup("e")
        self.assertEqual(len(stmts1), 1)
        self.assertEqual(stmts1[0].lineno, 5)

        _, stmts2 = x_names[1].lookup("e")
        self.assertEqual(len(stmts2), 1)
        self.assertEqual(stmts2[0].lineno, 7)

    def test_except_var_after_block_single(self) -> None:
        """When the variable bound to an exception in an except clause, it is NOT returned
        when that variable is used after the except block.
        """
        code = """
            try:
                1 / 0
            except NameError as e:
                pass
            print(e)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e"][0]
        _, stmts = x_name.lookup("e")
        self.assertEqual(len(stmts), 0)

    def test_except_var_after_block_multiple(self) -> None:
        """When the variable bound to an exception in multiple except clauses, it is NOT returned
        when that variable is used after the except blocks.
        """
        code = """
            try:
                1 / 0
            except NameError as e:
                pass
            except ZeroDivisionError as e:
                pass
            print(e)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "e"][0]
        _, stmts = x_name.lookup("e")
        self.assertEqual(len(stmts), 0)

    def test_except_assign_in_block(self) -> None:
        """When a variable is assigned in an except block, it is returned
        when that variable is used in the except block.
        """
        code = """
            try:
                1 / 0
            except ZeroDivisionError as e:
                x = 10
                print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 5)

    def test_except_assign_in_block_multiple(self) -> None:
        """When a variable is assigned in multiple except blocks, and the variable is
        used in one of the blocks, only the assignments in that block are returned.
        """
        code = """
            try:
                1 / 0
            except ZeroDivisionError:
                x = 10
            except NameError:
                x = 100
                print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 7)

    def test_except_assign_after_block(self) -> None:
        """When a variable is assigned in an except clause, it is returned
        when that variable is used after the except block.
        """
        code = """
            try:
                1 / 0
            except ZeroDivisionError:
                x = 10
            except NameError:
                x = 100
            print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 2)
        self.assertCountEqual([stmt.lineno for stmt in stmts], [5, 7])

    def test_except_assign_after_block_overwritten(self) -> None:
        """When a variable is assigned in an except clause, it is not returned
        when it is reassigned and used after the except block.
        """
        code = """
            try:
                1 / 0
            except ZeroDivisionError:
                x = 10
            except NameError:
                x = 100
            x = 1000
            print(x)
        """
        astroid = builder.parse(code)
        x_name = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == "x"][0]
        _, stmts = x_name.lookup("x")
        self.assertEqual(len(stmts), 1)
        self.assertEqual(stmts[0].lineno, 8)