forked from pylint-dev/astroid
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_nodes.py
2025 lines (1722 loc) · 64.5 KB
/
test_nodes.py
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
# 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 specific behaviour of astroid nodes."""
from __future__ import annotations
import copy
import inspect
import os
import random
import sys
import textwrap
import unittest
from typing import Any
import pytest
import astroid
from astroid import (
Uninferable,
bases,
builder,
extract_node,
nodes,
parse,
transforms,
util,
)
from astroid.const import IS_PYPY, PY310_PLUS, PY312_PLUS, Context
from astroid.context import InferenceContext
from astroid.exceptions import (
AstroidBuildingError,
AstroidSyntaxError,
AttributeInferenceError,
ParentMissingError,
StatementMissing,
)
from astroid.nodes.node_classes import (
AssignAttr,
AssignName,
Attribute,
Call,
ImportFrom,
Tuple,
)
from astroid.nodes.scoped_nodes import ClassDef, FunctionDef, GeneratorExp, Module
from tests.testdata.python3.recursion_error import LONG_CHAINED_METHOD_CALL
from . import resources
abuilder = builder.AstroidBuilder()
class AsStringTest(resources.SysPathSetup, unittest.TestCase):
def test_tuple_as_string(self) -> None:
def build(string: str) -> Tuple:
return abuilder.string_build(string).body[0].value
self.assertEqual(build("1,").as_string(), "(1, )")
self.assertEqual(build("1, 2, 3").as_string(), "(1, 2, 3)")
self.assertEqual(build("(1, )").as_string(), "(1, )")
self.assertEqual(build("1, 2, 3").as_string(), "(1, 2, 3)")
def test_func_signature_issue_185(self) -> None:
code = textwrap.dedent(
"""
def test(a, b, c=42, *, x=42, **kwargs):
print(a, b, c, args)
"""
)
node = parse(code)
self.assertEqual(node.as_string().strip(), code.strip())
def test_as_string_for_list_containing_uninferable(self) -> None:
node = builder.extract_node(
"""
def foo():
bar = [arg] * 1
"""
)
binop = node.body[0].value
inferred = next(binop.infer())
self.assertEqual(inferred.as_string(), "[Uninferable]")
self.assertEqual(binop.as_string(), "[arg] * 1")
def test_frozenset_as_string(self) -> None:
ast_nodes = builder.extract_node(
"""
frozenset((1, 2, 3)) #@
frozenset({1, 2, 3}) #@
frozenset([1, 2, 3,]) #@
frozenset(None) #@
frozenset(1) #@
"""
)
ast_nodes = [next(node.infer()) for node in ast_nodes]
assert isinstance(ast_nodes, list)
self.assertEqual(ast_nodes[0].as_string(), "frozenset((1, 2, 3))")
self.assertEqual(ast_nodes[1].as_string(), "frozenset({1, 2, 3})")
self.assertEqual(ast_nodes[2].as_string(), "frozenset([1, 2, 3])")
self.assertNotEqual(ast_nodes[3].as_string(), "frozenset(None)")
self.assertNotEqual(ast_nodes[4].as_string(), "frozenset(1)")
def test_varargs_kwargs_as_string(self) -> None:
ast = abuilder.string_build("raise_string(*args, **kwargs)").body[0]
self.assertEqual(ast.as_string(), "raise_string(*args, **kwargs)")
def test_module_as_string(self) -> None:
"""Check as_string on a whole module prepared to be returned identically."""
module = resources.build_file("data/module.py", "data.module")
with open(resources.find("data/module.py"), encoding="utf-8") as fobj:
self.assertMultiLineEqual(module.as_string(), fobj.read())
def test_module2_as_string(self) -> None:
"""Check as_string on a whole module prepared to be returned identically."""
module2 = resources.build_file("data/module2.py", "data.module2")
with open(resources.find("data/module2.py"), encoding="utf-8") as fobj:
self.assertMultiLineEqual(module2.as_string(), fobj.read())
def test_as_string(self) -> None:
"""Check as_string for python syntax >= 2.7."""
code = """one_two = {1, 2}
b = {v: k for (k, v) in enumerate('string')}
cdd = {k for k in b}\n\n"""
ast = abuilder.string_build(code)
self.assertMultiLineEqual(ast.as_string(), code)
def test_3k_as_string(self) -> None:
"""Check as_string for python 3k syntax."""
code = """print()
def function(var):
nonlocal counter
try:
hello
except NameError as nexc:
(*hell, o) = b'hello'
raise AttributeError from nexc
\n"""
ast = abuilder.string_build(code)
self.assertEqual(ast.as_string(), code)
def test_3k_annotations_and_metaclass(self) -> None:
code = '''
def function(var: int):
nonlocal counter
class Language(metaclass=Natural):
"""natural language"""
'''
code_annotations = textwrap.dedent(code)
expected = '''\
def function(var: int):
nonlocal counter
class Language(metaclass=Natural):
"""natural language"""'''
ast = abuilder.string_build(code_annotations)
self.assertEqual(ast.as_string().strip(), expected)
def test_ellipsis(self) -> None:
ast = abuilder.string_build("a[...]").body[0]
self.assertEqual(ast.as_string(), "a[...]")
def test_slices(self) -> None:
for code in (
"a[0]",
"a[1:3]",
"a[:-1:step]",
"a[:, newaxis]",
"a[newaxis, :]",
"del L[::2]",
"del A[1]",
"del Br[:]",
):
ast = abuilder.string_build(code).body[0]
self.assertEqual(ast.as_string(), code)
def test_slice_and_subscripts(self) -> None:
code = """a[:1] = bord[2:]
a[:1] = bord[2:]
del bree[3:d]
bord[2:]
del av[d::f], a[df:]
a[:1] = bord[2:]
del SRC[::1, newaxis, 1:]
tous[vals] = 1010
del thousand[key]
del a[::2], a[:-1:step]
del Fee.form[left:]
aout.vals = miles.of_stuff
del (ccok, (name.thing, foo.attrib.value)), Fee.form[left:]
if all[1] == bord[0:]:
pass\n\n"""
ast = abuilder.string_build(code)
self.assertEqual(ast.as_string(), code)
def test_int_attribute(self) -> None:
code = """
x = (-3).real
y = (3).imag
"""
ast = abuilder.string_build(code)
self.assertEqual(ast.as_string().strip(), code.strip())
def test_operator_precedence(self) -> None:
with open(resources.find("data/operator_precedence.py"), encoding="utf-8") as f:
for code in f:
self.check_as_string_ast_equality(code)
@staticmethod
def check_as_string_ast_equality(code: str) -> None:
"""
Check that as_string produces source code with exactly the same
semantics as the source it was originally parsed from.
"""
pre = builder.parse(code)
post = builder.parse(pre.as_string())
pre_repr = pre.repr_tree()
post_repr = post.repr_tree()
assert pre_repr == post_repr
assert pre.as_string().strip() == code.strip()
def test_class_def(self) -> None:
code = """
import abc
from typing import Tuple
class A:
pass
class B(metaclass=A, x=1):
pass
class C(B):
pass
class D(metaclass=abc.ABCMeta):
pass
def func(param: Tuple):
pass
"""
ast = abuilder.string_build(code)
self.assertEqual(ast.as_string().strip(), code.strip())
def test_f_strings(self):
code = r'''
a = f"{'a'}"
b = f'{{b}}'
c = f""" "{'c'}" """
d = f'{d!r} {d!s} {d!a}'
e = f'{e:.3}'
f = f'{f:{x}.{y}}'
n = f'\n'
everything = f""" " \' \r \t \\ {{ }} {'x' + x!r:a} {["'"]!s:{a}}"""
'''
ast = abuilder.string_build(code)
self.assertEqual(ast.as_string().strip(), code.strip())
@staticmethod
def test_as_string_unknown() -> None:
assert nodes.Unknown().as_string() == "Unknown.Unknown()"
assert nodes.Unknown(lineno=1, col_offset=0).as_string() == "Unknown.Unknown()"
@staticmethod
@pytest.mark.skipif(
IS_PYPY,
reason="Test requires manipulating the recursion limit, which cannot "
"be undone in a finally block without polluting other tests on PyPy.",
)
def test_recursion_error_trapped() -> None:
with pytest.warns(UserWarning, match="unable to transform"):
ast = abuilder.string_build(LONG_CHAINED_METHOD_CALL)
attribute = ast.body[1].value.func
with pytest.raises(UserWarning):
attribute.as_string()
@pytest.mark.skipif(not PY312_PLUS, reason="Uses 3.12 type param nodes")
class AsStringTypeParamNodes(unittest.TestCase):
@staticmethod
def test_as_string_type_alias() -> None:
ast = abuilder.string_build("type Point = tuple[float, float]")
type_alias = ast.body[0]
assert type_alias.as_string().strip() == "Point"
@staticmethod
def test_as_string_type_var() -> None:
ast = abuilder.string_build("type Point[T] = tuple[float, float]")
type_var = ast.body[0].type_params[0]
assert type_var.as_string().strip() == "T"
@staticmethod
def test_as_string_type_var_tuple() -> None:
ast = abuilder.string_build("type Alias[*Ts] = tuple[*Ts]")
type_var_tuple = ast.body[0].type_params[0]
assert type_var_tuple.as_string().strip() == "*Ts"
@staticmethod
def test_as_string_param_spec() -> None:
ast = abuilder.string_build("type Alias[**P] = Callable[P, int]")
param_spec = ast.body[0].type_params[0]
assert param_spec.as_string().strip() == "P"
class _NodeTest(unittest.TestCase):
"""Test transformation of If Node."""
CODE = ""
@property
def astroid(self) -> Module:
try:
return self.__class__.__dict__["CODE_Astroid"]
except KeyError:
module = builder.parse(self.CODE)
self.__class__.CODE_Astroid = module
return module
class IfNodeTest(_NodeTest):
"""Test transformation of If Node."""
CODE = """
if 0:
print()
if True:
print()
else:
pass
if "":
print()
elif []:
raise
if 1:
print()
elif True:
print()
elif func():
pass
else:
raise
"""
def test_if_elif_else_node(self) -> None:
"""Test transformation for If node."""
self.assertEqual(len(self.astroid.body), 4)
for stmt in self.astroid.body:
self.assertIsInstance(stmt, nodes.If)
self.assertFalse(self.astroid.body[0].orelse) # simple If
self.assertIsInstance(self.astroid.body[1].orelse[0], nodes.Pass) # If / else
self.assertIsInstance(self.astroid.body[2].orelse[0], nodes.If) # If / elif
self.assertIsInstance(self.astroid.body[3].orelse[0].orelse[0], nodes.If)
def test_block_range(self) -> None:
# XXX ensure expected values
self.assertEqual(self.astroid.block_range(1), (0, 22))
self.assertEqual(self.astroid.block_range(10), (0, 22)) # XXX (10, 22) ?
self.assertEqual(self.astroid.body[1].block_range(5), (5, 6))
self.assertEqual(self.astroid.body[1].block_range(6), (6, 6))
self.assertEqual(self.astroid.body[1].orelse[0].block_range(7), (7, 8))
self.assertEqual(self.astroid.body[1].orelse[0].block_range(8), (8, 8))
class TryNodeTest(_NodeTest):
CODE = """
try: # L2
print("Hello")
except IOError:
pass
except UnicodeError:
pass
else:
print()
finally:
print()
"""
def test_block_range(self) -> None:
try_node = self.astroid.body[0]
assert try_node.block_range(1) == (1, 11)
assert try_node.block_range(2) == (2, 2)
assert try_node.block_range(3) == (3, 3)
assert try_node.block_range(4) == (4, 4)
assert try_node.block_range(5) == (5, 5)
assert try_node.block_range(6) == (6, 6)
assert try_node.block_range(7) == (7, 7)
assert try_node.block_range(8) == (8, 8)
assert try_node.block_range(9) == (9, 9)
assert try_node.block_range(10) == (10, 10)
assert try_node.block_range(11) == (11, 11)
class TryExceptNodeTest(_NodeTest):
CODE = """
try:
print ('pouet')
except IOError:
pass
except UnicodeError:
print()
else:
print()
"""
def test_block_range(self) -> None:
# XXX ensure expected values
self.assertEqual(self.astroid.body[0].block_range(1), (1, 9))
self.assertEqual(self.astroid.body[0].block_range(2), (2, 2))
self.assertEqual(self.astroid.body[0].block_range(3), (3, 3))
self.assertEqual(self.astroid.body[0].block_range(4), (4, 4))
self.assertEqual(self.astroid.body[0].block_range(5), (5, 5))
self.assertEqual(self.astroid.body[0].block_range(6), (6, 6))
self.assertEqual(self.astroid.body[0].block_range(7), (7, 7))
self.assertEqual(self.astroid.body[0].block_range(8), (8, 8))
self.assertEqual(self.astroid.body[0].block_range(9), (9, 9))
class TryFinallyNodeTest(_NodeTest):
CODE = """
try:
print ('pouet')
finally:
print ('pouet')
"""
def test_block_range(self) -> None:
# XXX ensure expected values
self.assertEqual(self.astroid.body[0].block_range(1), (1, 5))
self.assertEqual(self.astroid.body[0].block_range(2), (2, 2))
self.assertEqual(self.astroid.body[0].block_range(3), (3, 3))
self.assertEqual(self.astroid.body[0].block_range(4), (4, 4))
self.assertEqual(self.astroid.body[0].block_range(5), (5, 5))
class TryExceptFinallyNodeTest(_NodeTest):
CODE = """
try:
print('pouet')
except Exception:
print ('oops')
finally:
print ('pouet')
"""
def test_block_range(self) -> None:
# XXX ensure expected values
self.assertEqual(self.astroid.body[0].block_range(1), (1, 7))
self.assertEqual(self.astroid.body[0].block_range(2), (2, 2))
self.assertEqual(self.astroid.body[0].block_range(3), (3, 3))
self.assertEqual(self.astroid.body[0].block_range(4), (4, 4))
self.assertEqual(self.astroid.body[0].block_range(5), (5, 5))
self.assertEqual(self.astroid.body[0].block_range(6), (6, 6))
self.assertEqual(self.astroid.body[0].block_range(7), (7, 7))
class ImportNodeTest(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")
def test_import_self_resolve(self) -> None:
myos = next(self.module2.igetattr("myos"))
self.assertTrue(isinstance(myos, nodes.Module), myos)
self.assertEqual(myos.name, "os")
self.assertEqual(myos.qname(), "os")
self.assertEqual(myos.pytype(), "builtins.module")
def test_from_self_resolve(self) -> None:
namenode = next(self.module.igetattr("NameNode"))
self.assertTrue(isinstance(namenode, nodes.ClassDef), namenode)
self.assertEqual(namenode.root().name, "astroid.nodes.node_classes")
self.assertEqual(namenode.qname(), "astroid.nodes.node_classes.Name")
self.assertEqual(namenode.pytype(), "builtins.type")
abspath = next(self.module2.igetattr("abspath"))
self.assertTrue(isinstance(abspath, nodes.FunctionDef), abspath)
self.assertEqual(abspath.root().name, "os.path")
self.assertEqual(abspath.pytype(), "builtins.function")
if sys.platform != "win32":
# Not sure what is causing this check to fail on Windows.
# For some reason the abspath() inference returns a different
# path than expected:
# AssertionError: 'os.path._abspath_fallback' != 'os.path.abspath'
self.assertEqual(abspath.qname(), "os.path.abspath")
def test_real_name(self) -> None:
from_ = self.module["NameNode"]
self.assertEqual(from_.real_name("NameNode"), "Name")
imp_ = self.module["os"]
self.assertEqual(imp_.real_name("os"), "os")
self.assertRaises(AttributeInferenceError, imp_.real_name, "os.path")
imp_ = self.module["NameNode"]
self.assertEqual(imp_.real_name("NameNode"), "Name")
self.assertRaises(AttributeInferenceError, imp_.real_name, "Name")
imp_ = self.module2["YO"]
self.assertEqual(imp_.real_name("YO"), "YO")
self.assertRaises(AttributeInferenceError, imp_.real_name, "data")
def test_as_string(self) -> None:
ast = self.module["modutils"]
self.assertEqual(ast.as_string(), "from astroid import modutils")
ast = self.module["NameNode"]
self.assertEqual(
ast.as_string(), "from astroid.nodes.node_classes import Name as NameNode"
)
ast = self.module["os"]
self.assertEqual(ast.as_string(), "import os.path")
code = """from . import here
from .. import door
from .store import bread
from ..cave import wine\n\n"""
ast = abuilder.string_build(code)
self.assertMultiLineEqual(ast.as_string(), code)
def test_bad_import_inference(self) -> None:
# Explication of bug
"""When we import PickleError from nonexistent, a call to the infer
method of this From node will be made by unpack_infer.
inference.infer_from will try to import this module, which will fail and
raise a InferenceException (by ImportNode.do_import_module). The infer_name
will catch this exception and yield and Uninferable instead.
"""
code = """
try:
from pickle import PickleError
except ImportError:
from nonexistent import PickleError
try:
pass
except PickleError:
pass
"""
module = builder.parse(code)
handler_type = module.body[1].handlers[0].type
excs = list(nodes.unpack_infer(handler_type))
# The number of returned object can differ on Python 2
# and Python 3. In one version, an additional item will
# be returned, from the _pickle module, which is not
# present in the other version.
self.assertIsInstance(excs[0], nodes.ClassDef)
self.assertEqual(excs[0].name, "PickleError")
self.assertIs(excs[-1], util.Uninferable)
def test_absolute_import(self) -> None:
module = resources.build_file("data/absimport.py")
ctx = InferenceContext()
# will fail if absolute import failed
ctx.lookupname = "message"
next(module["message"].infer(ctx))
ctx.lookupname = "email"
m = next(module["email"].infer(ctx))
self.assertFalse(m.file.startswith(os.path.join("data", "email.py")))
def test_more_absolute_import(self) -> None:
module = resources.build_file("data/module1abs/__init__.py", "data.module1abs")
self.assertIn("sys", module.locals)
_pickle_names = ("dump",) # "dumps", "load", "loads")
def test_conditional(self) -> None:
module = resources.build_file("data/conditional_import/__init__.py")
ctx = InferenceContext()
for name in self._pickle_names:
ctx.lookupname = name
some = list(module[name].infer(ctx))
assert Uninferable not in some, name
def test_conditional_import(self) -> None:
module = resources.build_file("data/conditional.py")
ctx = InferenceContext()
for name in self._pickle_names:
ctx.lookupname = name
some = list(module[name].infer(ctx))
assert Uninferable not in some, name
class CmpNodeTest(unittest.TestCase):
def test_as_string(self) -> None:
ast = abuilder.string_build("a == 2").body[0]
self.assertEqual(ast.as_string(), "a == 2")
class ConstNodeTest(unittest.TestCase):
def _test(self, value: Any) -> None:
node = nodes.const_factory(value)
self.assertIsInstance(node._proxied, nodes.ClassDef)
self.assertEqual(node._proxied.name, value.__class__.__name__)
self.assertIs(node.value, value)
self.assertTrue(node._proxied.parent)
self.assertEqual(node._proxied.root().name, value.__class__.__module__)
with self.assertRaises(StatementMissing):
with pytest.warns(DeprecationWarning) as records:
node.statement(future=True)
assert len(records) == 1
with self.assertRaises(StatementMissing):
node.statement()
with self.assertRaises(ParentMissingError):
with pytest.warns(DeprecationWarning) as records:
node.frame(future=True)
assert len(records) == 1
with self.assertRaises(ParentMissingError):
node.frame()
def test_none(self) -> None:
self._test(None)
def test_bool(self) -> None:
self._test(True)
def test_int(self) -> None:
self._test(1)
def test_float(self) -> None:
self._test(1.0)
def test_complex(self) -> None:
self._test(1.0j)
def test_str(self) -> None:
self._test("a")
def test_unicode(self) -> None:
self._test("a")
def test_str_kind(self):
node = builder.extract_node(
"""
const = u"foo"
"""
)
assert isinstance(node.value, nodes.Const)
assert node.value.value == "foo"
assert node.value.kind, "u"
def test_copy(self) -> None:
"""Make sure copying a Const object doesn't result in infinite recursion."""
const = copy.copy(nodes.Const(1))
assert const.value == 1
class NameNodeTest(unittest.TestCase):
def test_assign_to_true(self) -> None:
"""Test that True and False assignments don't crash."""
code = """
True = False
def hello(False):
pass
del True
"""
with self.assertRaises(AstroidBuildingError):
builder.parse(code)
class TestNamedExprNode:
"""Tests for the NamedExpr node."""
@staticmethod
def test_frame() -> None:
"""Test if the frame of NamedExpr is correctly set for certain types
of parent nodes.
"""
module = builder.parse(
"""
def func(var_1):
pass
def func_two(var_2, var_2 = (named_expr_1 := "walrus")):
pass
class MyBaseClass:
pass
class MyInheritedClass(MyBaseClass, var_3=(named_expr_2 := "walrus")):
pass
VAR = lambda y = (named_expr_3 := "walrus"): print(y)
def func_with_lambda(
var_5 = (
named_expr_4 := lambda y = (named_expr_5 := "walrus"): y
)
):
pass
COMPREHENSION = [y for i in (1, 2) if (y := i ** 2)]
"""
)
function = module.body[0]
assert function.args.frame() == function
assert function.args.frame() == function
function_two = module.body[1]
assert function_two.args.args[0].frame() == function_two
assert function_two.args.args[0].frame() == function_two
assert function_two.args.args[1].frame() == function_two
assert function_two.args.args[1].frame() == function_two
assert function_two.args.defaults[0].frame() == module
assert function_two.args.defaults[0].frame() == module
inherited_class = module.body[3]
assert inherited_class.keywords[0].frame() == inherited_class
assert inherited_class.keywords[0].frame() == inherited_class
assert inherited_class.keywords[0].value.frame() == module
assert inherited_class.keywords[0].value.frame() == module
lambda_assignment = module.body[4].value
assert lambda_assignment.args.args[0].frame() == lambda_assignment
assert lambda_assignment.args.args[0].frame() == lambda_assignment
assert lambda_assignment.args.defaults[0].frame() == module
assert lambda_assignment.args.defaults[0].frame() == module
lambda_named_expr = module.body[5].args.defaults[0]
assert lambda_named_expr.value.args.defaults[0].frame() == module
assert lambda_named_expr.value.args.defaults[0].frame() == module
comprehension = module.body[6].value
assert comprehension.generators[0].ifs[0].frame() == module
assert comprehension.generators[0].ifs[0].frame() == module
@staticmethod
def test_scope() -> None:
"""Test if the scope of NamedExpr is correctly set for certain types
of parent nodes.
"""
module = builder.parse(
"""
def func(var_1):
pass
def func_two(var_2, var_2 = (named_expr_1 := "walrus")):
pass
class MyBaseClass:
pass
class MyInheritedClass(MyBaseClass, var_3=(named_expr_2 := "walrus")):
pass
VAR = lambda y = (named_expr_3 := "walrus"): print(y)
def func_with_lambda(
var_5 = (
named_expr_4 := lambda y = (named_expr_5 := "walrus"): y
)
):
pass
COMPREHENSION = [y for i in (1, 2) if (y := i ** 2)]
"""
)
function = module.body[0]
assert function.args.scope() == function
function_two = module.body[1]
assert function_two.args.args[0].scope() == function_two
assert function_two.args.args[1].scope() == function_two
assert function_two.args.defaults[0].scope() == module
inherited_class = module.body[3]
assert inherited_class.keywords[0].scope() == inherited_class
assert inherited_class.keywords[0].value.scope() == module
lambda_assignment = module.body[4].value
assert lambda_assignment.args.args[0].scope() == lambda_assignment
assert lambda_assignment.args.defaults[0].scope()
lambda_named_expr = module.body[5].args.defaults[0]
assert lambda_named_expr.value.args.defaults[0].scope() == module
comprehension = module.body[6].value
assert comprehension.generators[0].ifs[0].scope() == module
class AnnAssignNodeTest(unittest.TestCase):
def test_primitive(self) -> None:
code = textwrap.dedent(
"""
test: int = 5
"""
)
assign = builder.extract_node(code)
self.assertIsInstance(assign, nodes.AnnAssign)
self.assertEqual(assign.target.name, "test")
self.assertEqual(assign.annotation.name, "int")
self.assertEqual(assign.value.value, 5)
self.assertEqual(assign.simple, 1)
def test_primitive_without_initial_value(self) -> None:
code = textwrap.dedent(
"""
test: str
"""
)
assign = builder.extract_node(code)
self.assertIsInstance(assign, nodes.AnnAssign)
self.assertEqual(assign.target.name, "test")
self.assertEqual(assign.annotation.name, "str")
self.assertEqual(assign.value, None)
def test_complex(self) -> None:
code = textwrap.dedent(
"""
test: Dict[List[str]] = {}
"""
)
assign = builder.extract_node(code)
self.assertIsInstance(assign, nodes.AnnAssign)
self.assertEqual(assign.target.name, "test")
self.assertIsInstance(assign.annotation, astroid.Subscript)
self.assertIsInstance(assign.value, astroid.Dict)
def test_as_string(self) -> None:
code = textwrap.dedent(
"""
print()
test: int = 5
test2: str
test3: List[Dict[str, str]] = []
"""
)
ast = abuilder.string_build(code)
self.assertEqual(ast.as_string().strip(), code.strip())
class ArgumentsNodeTC(unittest.TestCase):
def test_linenumbering(self) -> None:
ast = builder.parse(
"""
def func(a,
b): pass
x = lambda x: None
"""
)
self.assertEqual(ast["func"].args.fromlineno, 2)
self.assertFalse(ast["func"].args.is_statement)
xlambda = next(ast["x"].infer())
self.assertEqual(xlambda.args.fromlineno, 4)
self.assertEqual(xlambda.args.tolineno, 4)
self.assertFalse(xlambda.args.is_statement)
def test_kwoargs(self) -> None:
ast = builder.parse(
"""
def func(*, x):
pass
"""
)
args = ast["func"].args
assert isinstance(args, nodes.Arguments)
assert args.is_argument("x")
assert args.kw_defaults == [None]
ast = builder.parse(
"""
def func(*, x = "default"):
pass
"""
)
args = ast["func"].args
assert isinstance(args, nodes.Arguments)
assert args.is_argument("x")
assert len(args.kw_defaults) == 1
assert isinstance(args.kw_defaults[0], nodes.Const)
assert args.kw_defaults[0].value == "default"
def test_positional_only(self):
ast = builder.parse(
"""
def func(x, /, y):
pass
"""
)
args = ast["func"].args
self.assertTrue(args.is_argument("x"))
self.assertTrue(args.is_argument("y"))
index, node = args.find_argname("x")
self.assertEqual(index, 0)
self.assertIsNotNone(node)
class UnboundMethodNodeTest(unittest.TestCase):
def test_no_super_getattr(self) -> None:
# This is a test for issue
# https://bitbucket.org/logilab/astroid/issue/91, which tests
# that UnboundMethod doesn't call super when doing .getattr.
ast = builder.parse(
"""
class A(object):
def test(self):
pass
meth = A.test
"""
)
node = next(ast["meth"].infer())
with self.assertRaises(AttributeInferenceError):
node.getattr("__missssing__")
name = node.getattr("__name__")[0]
self.assertIsInstance(name, nodes.Const)
self.assertEqual(name.value, "test")
class BoundMethodNodeTest(unittest.TestCase):
def test_is_property(self) -> None:
ast = builder.parse(
"""
import abc
def cached_property():
# Not a real decorator, but we don't care
pass
def reify():
# Same as cached_property
pass
def lazy_property():
pass
def lazyproperty():
pass
def lazy(): pass
class A(object):
@property
def builtin_property(self):
return 42
@abc.abstractproperty
def abc_property(self):
return 42
@cached_property
def cached_property(self): return 42
@reify
def reified(self): return 42
@lazy_property
def lazy_prop(self): return 42
@lazyproperty
def lazyprop(self): return 42
def not_prop(self): pass
@lazy
def decorated_with_lazy(self): return 42
cls = A()
builtin_property = cls.builtin_property
abc_property = cls.abc_property
cached_p = cls.cached_property
reified = cls.reified
not_prop = cls.not_prop
lazy_prop = cls.lazy_prop
lazyprop = cls.lazyprop
decorated_with_lazy = cls.decorated_with_lazy
"""
)
for prop in (
"builtin_property",
"abc_property",
"cached_p",
"reified",
"lazy_prop",
"lazyprop",
"decorated_with_lazy",
):
inferred = next(ast[prop].infer())
self.assertIsInstance(inferred, nodes.Const, prop)
self.assertEqual(inferred.value, 42, prop)
inferred = next(ast["not_prop"].infer())
self.assertIsInstance(inferred, bases.BoundMethod)
class AliasesTest(unittest.TestCase):
def setUp(self) -> None:
self.transformer = transforms.TransformVisitor()
def parse_transform(self, code: str) -> Module:
module = parse(code, apply_transforms=False)