-
-
Notifications
You must be signed in to change notification settings - Fork 276
/
unittest_brain.py
3130 lines (2735 loc) · 95.6 KB
/
unittest_brain.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
# Copyright (c) 2013-2014 Google, Inc.
# Copyright (c) 2014-2020 Claudiu Popa <[email protected]>
# Copyright (c) 2015-2016 Ceridwen <[email protected]>
# Copyright (c) 2015 LOGILAB S.A. (Paris, FRANCE) <[email protected]>
# Copyright (c) 2015 raylu <[email protected]>
# Copyright (c) 2015 Philip Lorenz <[email protected]>
# Copyright (c) 2016 Florian Bruhin <[email protected]>
# Copyright (c) 2017-2018, 2020-2021 hippo91 <[email protected]>
# Copyright (c) 2017-2018 Bryce Guinta <[email protected]>
# Copyright (c) 2017 Łukasz Rogalski <[email protected]>
# Copyright (c) 2017 David Euresti <[email protected]>
# Copyright (c) 2017 Derek Gustafson <[email protected]>
# Copyright (c) 2018 Tomas Gavenciak <[email protected]>
# Copyright (c) 2018 David Poirier <[email protected]>
# Copyright (c) 2018 Ville Skyttä <[email protected]>
# Copyright (c) 2018 Nick Drozd <[email protected]>
# Copyright (c) 2018 Anthony Sottile <[email protected]>
# Copyright (c) 2018 Ioana Tagirta <[email protected]>
# Copyright (c) 2018 Ahmed Azzaoui <[email protected]>
# Copyright (c) 2019-2020 Bryce Guinta <[email protected]>
# Copyright (c) 2019 Ashley Whetter <[email protected]>
# Copyright (c) 2019 Tomas Novak <[email protected]>
# Copyright (c) 2019 Hugo van Kemenade <[email protected]>
# Copyright (c) 2019 Grygorii Iermolenko <[email protected]>
# Copyright (c) 2020 David Gilman <[email protected]>
# Copyright (c) 2020 Peter Kolbus <[email protected]>
# Copyright (c) 2021 Joshua Cannon <[email protected]>
# Copyright (c) 2021 Pierre Sassoulas <[email protected]>
# Copyright (c) 2021 Craig Franklin <[email protected]>
# Copyright (c) 2021 Marc Mueller <[email protected]>
# Copyright (c) 2021 Jonathan Striebel <[email protected]>
# Copyright (c) 2021 Daniël van Noord <[email protected]>
# Copyright (c) 2021 Dimitri Prybysh <[email protected]>
# Copyright (c) 2021 David Liu <[email protected]>
# Copyright (c) 2021 pre-commit-ci[bot] <[email protected]>
# Copyright (c) 2021 Alphadelta14 <[email protected]>
# Copyright (c) 2021 Tim Martin <[email protected]>
# Copyright (c) 2021 Andrew Haigh <[email protected]>
# Copyright (c) 2021 Artsiom Kaval <[email protected]>
# Copyright (c) 2021 Damien Baty <[email protected]>
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE
"""Tests for basic functionality in astroid.brain."""
import io
import queue
import re
import sys
import unittest
from typing import Any, List
import pytest
import astroid
from astroid import MANAGER, bases, builder, nodes, objects, test_utils, util
from astroid.bases import Instance
from astroid.const import PY37_PLUS
from astroid.exceptions import AttributeInferenceError, InferenceError
from astroid.nodes.node_classes import Const
from astroid.nodes.scoped_nodes import ClassDef
try:
import multiprocessing # pylint: disable=unused-import
HAS_MULTIPROCESSING = True
except ImportError:
HAS_MULTIPROCESSING = False
try:
import nose # pylint: disable=unused-import
HAS_NOSE = True
except ImportError:
HAS_NOSE = False
try:
import dateutil # pylint: disable=unused-import
HAS_DATEUTIL = True
except ImportError:
HAS_DATEUTIL = False
try:
import attr as attr_module # pylint: disable=unused-import
HAS_ATTR = True
except ImportError:
HAS_ATTR = False
try:
import six # pylint: disable=unused-import
HAS_SIX = True
except ImportError:
HAS_SIX = False
def assertEqualMro(klass: ClassDef, expected_mro: List[str]) -> None:
"""Check mro names."""
assert [member.qname() for member in klass.mro()] == expected_mro
class HashlibTest(unittest.TestCase):
def _assert_hashlib_class(self, class_obj: ClassDef) -> None:
self.assertIn("update", class_obj)
self.assertIn("digest", class_obj)
self.assertIn("hexdigest", class_obj)
self.assertIn("block_size", class_obj)
self.assertIn("digest_size", class_obj)
self.assertEqual(len(class_obj["__init__"].args.args), 2)
self.assertEqual(len(class_obj["__init__"].args.defaults), 1)
self.assertEqual(len(class_obj["update"].args.args), 2)
self.assertEqual(len(class_obj["digest"].args.args), 1)
self.assertEqual(len(class_obj["hexdigest"].args.args), 1)
def test_hashlib(self) -> None:
"""Tests that brain extensions for hashlib work."""
hashlib_module = MANAGER.ast_from_module_name("hashlib")
for class_name in ("md5", "sha1"):
class_obj = hashlib_module[class_name]
self._assert_hashlib_class(class_obj)
def test_hashlib_py36(self) -> None:
hashlib_module = MANAGER.ast_from_module_name("hashlib")
for class_name in ("sha3_224", "sha3_512", "shake_128"):
class_obj = hashlib_module[class_name]
self._assert_hashlib_class(class_obj)
for class_name in ("blake2b", "blake2s"):
class_obj = hashlib_module[class_name]
self.assertEqual(len(class_obj["__init__"].args.args), 2)
class CollectionsDequeTests(unittest.TestCase):
def _inferred_queue_instance(self) -> Instance:
node = builder.extract_node(
"""
import collections
q = collections.deque([])
q
"""
)
return next(node.infer())
def test_deque(self) -> None:
inferred = self._inferred_queue_instance()
self.assertTrue(inferred.getattr("__len__"))
def test_deque_py35methods(self) -> None:
inferred = self._inferred_queue_instance()
self.assertIn("copy", inferred.locals)
self.assertIn("insert", inferred.locals)
self.assertIn("index", inferred.locals)
@test_utils.require_version(maxver="3.8")
def test_deque_not_py39methods(self):
inferred = self._inferred_queue_instance()
with self.assertRaises(AttributeInferenceError):
inferred.getattr("__class_getitem__")
@test_utils.require_version(minver="3.9")
def test_deque_py39methods(self):
inferred = self._inferred_queue_instance()
self.assertTrue(inferred.getattr("__class_getitem__"))
class OrderedDictTest(unittest.TestCase):
def _inferred_ordered_dict_instance(self) -> Instance:
node = builder.extract_node(
"""
import collections
d = collections.OrderedDict()
d
"""
)
return next(node.infer())
def test_ordered_dict_py34method(self) -> None:
inferred = self._inferred_ordered_dict_instance()
self.assertIn("move_to_end", inferred.locals)
class NamedTupleTest(unittest.TestCase):
def test_namedtuple_base(self) -> None:
klass = builder.extract_node(
"""
from collections import namedtuple
class X(namedtuple("X", ["a", "b", "c"])):
pass
"""
)
assert isinstance(klass, nodes.ClassDef)
self.assertEqual(
[anc.name for anc in klass.ancestors()], ["X", "tuple", "object"]
)
for anc in klass.ancestors():
self.assertFalse(anc.parent is None)
def test_namedtuple_inference(self) -> None:
klass = builder.extract_node(
"""
from collections import namedtuple
name = "X"
fields = ["a", "b", "c"]
class X(namedtuple(name, fields)):
pass
"""
)
assert isinstance(klass, nodes.ClassDef)
base = next(base for base in klass.ancestors() if base.name == "X")
self.assertSetEqual({"a", "b", "c"}, set(base.instance_attrs))
def test_namedtuple_inference_failure(self) -> None:
klass = builder.extract_node(
"""
from collections import namedtuple
def foo(fields):
return __(namedtuple("foo", fields))
"""
)
self.assertIs(util.Uninferable, next(klass.infer()))
def test_namedtuple_advanced_inference(self) -> None:
# urlparse return an object of class ParseResult, which has a
# namedtuple call and a mixin as base classes
result = builder.extract_node(
"""
from urllib.parse import urlparse
result = __(urlparse('gopher://'))
"""
)
instance = next(result.infer())
self.assertGreaterEqual(len(instance.getattr("scheme")), 1)
self.assertGreaterEqual(len(instance.getattr("port")), 1)
with self.assertRaises(AttributeInferenceError):
instance.getattr("foo")
self.assertGreaterEqual(len(instance.getattr("geturl")), 1)
self.assertEqual(instance.name, "ParseResult")
def test_namedtuple_instance_attrs(self) -> None:
result = builder.extract_node(
"""
from collections import namedtuple
namedtuple('a', 'a b c')(1, 2, 3) #@
"""
)
inferred = next(result.infer())
for name, attr in inferred.instance_attrs.items():
self.assertEqual(attr[0].attrname, name)
def test_namedtuple_uninferable_fields(self) -> None:
node = builder.extract_node(
"""
x = [A] * 2
from collections import namedtuple
l = namedtuple('a', x)
l(1)
"""
)
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred)
def test_namedtuple_access_class_fields(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", "field other")
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIn("field", inferred.locals)
self.assertIn("other", inferred.locals)
def test_namedtuple_rename_keywords(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", "abc def", rename=True)
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIn("abc", inferred.locals)
self.assertIn("_1", inferred.locals)
def test_namedtuple_rename_duplicates(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", "abc abc abc", rename=True)
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIn("abc", inferred.locals)
self.assertIn("_1", inferred.locals)
self.assertIn("_2", inferred.locals)
def test_namedtuple_rename_uninferable(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", "a b c", rename=UNINFERABLE)
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIn("a", inferred.locals)
self.assertIn("b", inferred.locals)
self.assertIn("c", inferred.locals)
def test_namedtuple_func_form(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple(typename="Tuple", field_names="a b c", rename=UNINFERABLE)
Tuple #@
"""
)
inferred = next(node.infer())
self.assertEqual(inferred.name, "Tuple")
self.assertIn("a", inferred.locals)
self.assertIn("b", inferred.locals)
self.assertIn("c", inferred.locals)
def test_namedtuple_func_form_args_and_kwargs(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", field_names="a b c", rename=UNINFERABLE)
Tuple #@
"""
)
inferred = next(node.infer())
self.assertEqual(inferred.name, "Tuple")
self.assertIn("a", inferred.locals)
self.assertIn("b", inferred.locals)
self.assertIn("c", inferred.locals)
def test_namedtuple_bases_are_actually_names_not_nodes(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", field_names="a b c", rename=UNINFERABLE)
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIsInstance(inferred, astroid.ClassDef)
self.assertIsInstance(inferred.bases[0], astroid.Name)
self.assertEqual(inferred.bases[0].name, "tuple")
def test_invalid_label_does_not_crash_inference(self) -> None:
code = """
import collections
a = collections.namedtuple( 'a', ['b c'] )
a
"""
node = builder.extract_node(code)
inferred = next(node.infer())
assert isinstance(inferred, astroid.ClassDef)
assert "b" not in inferred.locals
assert "c" not in inferred.locals
def test_no_rename_duplicates_does_not_crash_inference(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", "abc abc")
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred) # would raise ValueError
def test_no_rename_keywords_does_not_crash_inference(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", "abc def")
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred) # would raise ValueError
def test_no_rename_nonident_does_not_crash_inference(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", "123 456")
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred) # would raise ValueError
def test_no_rename_underscore_does_not_crash_inference(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", "_1")
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred) # would raise ValueError
def test_invalid_typename_does_not_crash_inference(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("123", "abc")
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred) # would raise ValueError
def test_keyword_typename_does_not_crash_inference(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("while", "abc")
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred) # would raise ValueError
def test_typeerror_does_not_crash_inference(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
Tuple = namedtuple("Tuple", [123, 456])
Tuple #@
"""
)
inferred = next(node.infer())
# namedtuple converts all arguments to strings so these should be too
# and catch on the isidentifier() check
self.assertIs(util.Uninferable, inferred)
def test_pathological_str_does_not_crash_inference(self) -> None:
node = builder.extract_node(
"""
from collections import namedtuple
class Invalid:
def __str__(self):
return 123 # will raise TypeError
Tuple = namedtuple("Tuple", [Invalid()])
Tuple #@
"""
)
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred)
class DefaultDictTest(unittest.TestCase):
def test_1(self) -> None:
node = builder.extract_node(
"""
from collections import defaultdict
X = defaultdict(int)
X[0]
"""
)
inferred = next(node.infer())
self.assertIs(util.Uninferable, inferred)
class ModuleExtenderTest(unittest.TestCase):
def test_extension_modules(self) -> None:
transformer = MANAGER._transform
for extender, _ in transformer.transforms[nodes.Module]:
n = nodes.Module("__main__", None)
extender(n)
@unittest.skipUnless(HAS_NOSE, "This test requires nose library.")
class NoseBrainTest(unittest.TestCase):
def test_nose_tools(self):
methods = builder.extract_node(
"""
from nose.tools import assert_equal
from nose.tools import assert_equals
from nose.tools import assert_true
assert_equal = assert_equal #@
assert_true = assert_true #@
assert_equals = assert_equals #@
"""
)
assert isinstance(methods, list)
assert_equal = next(methods[0].value.infer())
assert_true = next(methods[1].value.infer())
assert_equals = next(methods[2].value.infer())
self.assertIsInstance(assert_equal, astroid.BoundMethod)
self.assertIsInstance(assert_true, astroid.BoundMethod)
self.assertIsInstance(assert_equals, astroid.BoundMethod)
self.assertEqual(assert_equal.qname(), "unittest.case.TestCase.assertEqual")
self.assertEqual(assert_true.qname(), "unittest.case.TestCase.assertTrue")
self.assertEqual(assert_equals.qname(), "unittest.case.TestCase.assertEqual")
@unittest.skipUnless(HAS_SIX, "These tests require the six library")
class SixBrainTest(unittest.TestCase):
def test_attribute_access(self) -> None:
ast_nodes = builder.extract_node(
"""
import six
six.moves.http_client #@
six.moves.urllib_parse #@
six.moves.urllib_error #@
six.moves.urllib.request #@
"""
)
assert isinstance(ast_nodes, list)
http_client = next(ast_nodes[0].infer())
self.assertIsInstance(http_client, nodes.Module)
self.assertEqual(http_client.name, "http.client")
urllib_parse = next(ast_nodes[1].infer())
self.assertIsInstance(urllib_parse, nodes.Module)
self.assertEqual(urllib_parse.name, "urllib.parse")
urljoin = next(urllib_parse.igetattr("urljoin"))
urlencode = next(urllib_parse.igetattr("urlencode"))
self.assertIsInstance(urljoin, nodes.FunctionDef)
self.assertEqual(urljoin.qname(), "urllib.parse.urljoin")
self.assertIsInstance(urlencode, nodes.FunctionDef)
self.assertEqual(urlencode.qname(), "urllib.parse.urlencode")
urllib_error = next(ast_nodes[2].infer())
self.assertIsInstance(urllib_error, nodes.Module)
self.assertEqual(urllib_error.name, "urllib.error")
urlerror = next(urllib_error.igetattr("URLError"))
self.assertIsInstance(urlerror, nodes.ClassDef)
content_too_short = next(urllib_error.igetattr("ContentTooShortError"))
self.assertIsInstance(content_too_short, nodes.ClassDef)
urllib_request = next(ast_nodes[3].infer())
self.assertIsInstance(urllib_request, nodes.Module)
self.assertEqual(urllib_request.name, "urllib.request")
urlopen = next(urllib_request.igetattr("urlopen"))
urlretrieve = next(urllib_request.igetattr("urlretrieve"))
self.assertIsInstance(urlopen, nodes.FunctionDef)
self.assertEqual(urlopen.qname(), "urllib.request.urlopen")
self.assertIsInstance(urlretrieve, nodes.FunctionDef)
self.assertEqual(urlretrieve.qname(), "urllib.request.urlretrieve")
def test_from_imports(self) -> None:
ast_node = builder.extract_node(
"""
from six.moves import http_client
http_client.HTTPSConnection #@
"""
)
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
qname = "http.client.HTTPSConnection"
self.assertEqual(inferred.qname(), qname)
def test_from_submodule_imports(self) -> None:
"""Make sure ulrlib submodules can be imported from
See PyCQA/pylint#1640 for relevant issue
"""
ast_node = builder.extract_node(
"""
from six.moves.urllib.parse import urlparse
urlparse #@
"""
)
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.FunctionDef)
def test_with_metaclass_subclasses_inheritance(self) -> None:
ast_node = builder.extract_node(
"""
class A(type):
def test(cls):
return cls
class C:
pass
import six
class B(six.with_metaclass(A, C)):
pass
B #@
"""
)
inferred = next(ast_node.infer())
self.assertIsInstance(inferred, nodes.ClassDef)
self.assertEqual(inferred.name, "B")
self.assertIsInstance(inferred.bases[0], nodes.Call)
ancestors = tuple(inferred.ancestors())
self.assertIsInstance(ancestors[0], nodes.ClassDef)
self.assertEqual(ancestors[0].name, "C")
self.assertIsInstance(ancestors[1], nodes.ClassDef)
self.assertEqual(ancestors[1].name, "object")
def test_six_with_metaclass_with_additional_transform(self) -> None:
def transform_class(cls: Any) -> ClassDef:
if cls.name == "A":
cls._test_transform = 314
return cls
MANAGER.register_transform(nodes.ClassDef, transform_class)
try:
ast_node = builder.extract_node(
"""
import six
class A(six.with_metaclass(type, object)):
pass
A #@
"""
)
inferred = next(ast_node.infer())
assert getattr(inferred, "_test_transform", None) == 314
finally:
MANAGER.unregister_transform(nodes.ClassDef, transform_class)
@unittest.skipUnless(
HAS_MULTIPROCESSING,
"multiprocesing is required for this test, but "
"on some platforms it is missing "
"(Jython for instance)",
)
class MultiprocessingBrainTest(unittest.TestCase):
def test_multiprocessing_module_attributes(self) -> None:
# Test that module attributes are working,
# especially on Python 3.4+, where they are obtained
# from a context.
module = builder.extract_node(
"""
import multiprocessing
"""
)
assert isinstance(module, nodes.Import)
module = module.do_import_module("multiprocessing")
cpu_count = next(module.igetattr("cpu_count"))
self.assertIsInstance(cpu_count, astroid.BoundMethod)
def test_module_name(self) -> None:
module = builder.extract_node(
"""
import multiprocessing
multiprocessing.SyncManager()
"""
)
inferred_sync_mgr = next(module.infer())
module = inferred_sync_mgr.root()
self.assertEqual(module.name, "multiprocessing.managers")
def test_multiprocessing_manager(self) -> None:
# Test that we have the proper attributes
# for a multiprocessing.managers.SyncManager
module = builder.parse(
"""
import multiprocessing
manager = multiprocessing.Manager()
queue = manager.Queue()
joinable_queue = manager.JoinableQueue()
event = manager.Event()
rlock = manager.RLock()
bounded_semaphore = manager.BoundedSemaphore()
condition = manager.Condition()
barrier = manager.Barrier()
pool = manager.Pool()
list = manager.list()
dict = manager.dict()
value = manager.Value()
array = manager.Array()
namespace = manager.Namespace()
"""
)
ast_queue = next(module["queue"].infer())
self.assertEqual(ast_queue.qname(), f"{queue.__name__}.Queue")
joinable_queue = next(module["joinable_queue"].infer())
self.assertEqual(joinable_queue.qname(), f"{queue.__name__}.Queue")
event = next(module["event"].infer())
event_name = "threading.Event"
self.assertEqual(event.qname(), event_name)
rlock = next(module["rlock"].infer())
rlock_name = "threading._RLock"
self.assertEqual(rlock.qname(), rlock_name)
bounded_semaphore = next(module["bounded_semaphore"].infer())
semaphore_name = "threading.BoundedSemaphore"
self.assertEqual(bounded_semaphore.qname(), semaphore_name)
pool = next(module["pool"].infer())
pool_name = "multiprocessing.pool.Pool"
self.assertEqual(pool.qname(), pool_name)
for attr in ("list", "dict"):
obj = next(module[attr].infer())
self.assertEqual(obj.qname(), f"builtins.{attr}")
# pypy's implementation of array.__spec__ return None. This causes problems for this inference.
if not hasattr(sys, "pypy_version_info"):
array = next(module["array"].infer())
self.assertEqual(array.qname(), "array.array")
manager = next(module["manager"].infer())
# Verify that we have these attributes
self.assertTrue(manager.getattr("start"))
self.assertTrue(manager.getattr("shutdown"))
class ThreadingBrainTest(unittest.TestCase):
def test_lock(self) -> None:
lock_instance = builder.extract_node(
"""
import threading
threading.Lock()
"""
)
inferred = next(lock_instance.infer())
self.assert_is_valid_lock(inferred)
acquire_method = inferred.getattr("acquire")[0]
parameters = [param.name for param in acquire_method.args.args[1:]]
assert parameters == ["blocking", "timeout"]
assert inferred.getattr("locked")
def test_rlock(self) -> None:
self._test_lock_object("RLock")
def test_semaphore(self) -> None:
self._test_lock_object("Semaphore")
def test_boundedsemaphore(self) -> None:
self._test_lock_object("BoundedSemaphore")
def _test_lock_object(self, object_name: str) -> None:
lock_instance = builder.extract_node(
f"""
import threading
threading.{object_name}()
"""
)
inferred = next(lock_instance.infer())
self.assert_is_valid_lock(inferred)
def assert_is_valid_lock(self, inferred: Instance) -> None:
self.assertIsInstance(inferred, astroid.Instance)
self.assertEqual(inferred.root().name, "threading")
for method in ("acquire", "release", "__enter__", "__exit__"):
self.assertIsInstance(next(inferred.igetattr(method)), astroid.BoundMethod)
class EnumBrainTest(unittest.TestCase):
def test_simple_enum(self) -> None:
module = builder.parse(
"""
import enum
class MyEnum(enum.Enum):
one = "one"
two = "two"
def mymethod(self, x):
return 5
"""
)
enumeration = next(module["MyEnum"].infer())
one = enumeration["one"]
self.assertEqual(one.pytype(), ".MyEnum.one")
for propname in ("name", "value"):
prop = next(iter(one.getattr(propname)))
self.assertIn("builtins.property", prop.decoratornames())
meth = one.getattr("mymethod")[0]
self.assertIsInstance(meth, astroid.FunctionDef)
def test_looks_like_enum_false_positive(self) -> None:
# Test that a class named Enumeration is not considered a builtin enum.
module = builder.parse(
"""
class Enumeration(object):
def __init__(self, name, enum_list):
pass
test = 42
"""
)
enumeration = module["Enumeration"]
test = next(enumeration.igetattr("test"))
self.assertEqual(test.value, 42)
def test_user_enum_false_positive(self) -> None:
# Test that a user-defined class named Enum is not considered a builtin enum.
ast_node = astroid.extract_node(
"""
class Enum:
pass
class Color(Enum):
red = 1
Color.red #@
"""
)
assert isinstance(ast_node, nodes.NodeNG)
inferred = ast_node.inferred()
self.assertEqual(len(inferred), 1)
self.assertIsInstance(inferred[0], astroid.Const)
self.assertEqual(inferred[0].value, 1)
def test_ignores_with_nodes_from_body_of_enum(self) -> None:
code = """
import enum
class Error(enum.Enum):
Foo = "foo"
Bar = "bar"
with "error" as err:
pass
"""
node = builder.extract_node(code)
inferred = next(node.infer())
assert "err" in inferred.locals
assert len(inferred.locals["err"]) == 1
def test_enum_multiple_base_classes(self) -> None:
module = builder.parse(
"""
import enum
class Mixin:
pass
class MyEnum(Mixin, enum.Enum):
one = 1
"""
)
enumeration = next(module["MyEnum"].infer())
one = enumeration["one"]
clazz = one.getattr("__class__")[0]
self.assertTrue(
clazz.is_subtype_of(".Mixin"),
"Enum instance should share base classes with generating class",
)
def test_int_enum(self) -> None:
module = builder.parse(
"""
import enum
class MyEnum(enum.IntEnum):
one = 1
"""
)
enumeration = next(module["MyEnum"].infer())
one = enumeration["one"]
clazz = one.getattr("__class__")[0]
self.assertTrue(
clazz.is_subtype_of("builtins.int"),
"IntEnum based enums should be a subtype of int",
)
def test_enum_func_form_is_class_not_instance(self) -> None:
cls, instance = builder.extract_node(
"""
from enum import Enum
f = Enum('Audience', ['a', 'b', 'c'])
f #@
f(1) #@
"""
)
inferred_cls = next(cls.infer())
self.assertIsInstance(inferred_cls, bases.Instance)
inferred_instance = next(instance.infer())
self.assertIsInstance(inferred_instance, bases.Instance)
self.assertIsInstance(next(inferred_instance.igetattr("name")), nodes.Const)
self.assertIsInstance(next(inferred_instance.igetattr("value")), nodes.Const)
def test_enum_func_form_iterable(self) -> None:
instance = builder.extract_node(
"""
from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')
Animal
"""
)
inferred = next(instance.infer())
self.assertIsInstance(inferred, astroid.Instance)
self.assertTrue(inferred.getattr("__iter__"))
def test_enum_func_form_subscriptable(self) -> None:
instance, name = builder.extract_node(
"""
from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')
Animal['ant'] #@
Animal['ant'].name #@
"""
)
instance = next(instance.infer())
self.assertIsInstance(instance, astroid.Instance)
inferred = next(name.infer())
self.assertIsInstance(inferred, astroid.Const)
def test_enum_func_form_has_dunder_members(self) -> None:
instance = builder.extract_node(
"""
from enum import Enum
Animal = Enum('Animal', 'ant bee cat dog')
for i in Animal.__members__:
i #@
"""
)
instance = next(instance.infer())
self.assertIsInstance(instance, astroid.Const)
self.assertIsInstance(instance.value, str)
def test_infer_enum_value_as_the_right_type(self) -> None:
string_value, int_value = builder.extract_node(
"""
from enum import Enum
class A(Enum):
a = 'a'
b = 1
A.a.value #@
A.b.value #@
"""
)
inferred_string = string_value.inferred()
assert any(
isinstance(elem, astroid.Const) and elem.value == "a"
for elem in inferred_string
)
inferred_int = int_value.inferred()
assert any(
isinstance(elem, astroid.Const) and elem.value == 1 for elem in inferred_int
)
def test_mingled_single_and_double_quotes_does_not_crash(self) -> None:
node = builder.extract_node(
"""
from enum import Enum
class A(Enum):
a = 'x"y"'
A.a.value #@
"""
)
inferred_string = next(node.infer())
assert inferred_string.value == 'x"y"'
def test_special_characters_does_not_crash(self) -> None:
node = builder.extract_node(
"""
import enum
class Example(enum.Enum):
NULL = '\\N{NULL}'
Example.NULL.value
"""
)
inferred_string = next(node.infer())
assert inferred_string.value == "\N{NULL}"
def test_dont_crash_on_for_loops_in_body(self) -> None:
node = builder.extract_node(
"""
class Commands(IntEnum):
_ignore_ = 'Commands index'
_init_ = 'value string'
BEL = 0x07, 'Bell'
Commands = vars()
for index in range(4):
Commands[f'DC{index + 1}'] = 0x11 + index, f'Device Control {index + 1}'
Commands
"""
)