Debian Codegraph @

tests/brain/numpy/test_ndarray.py

raw
1 # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2 # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3 # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5 import unittest
6
7 try:
8 import numpy # pylint: disable=unused-import
9
10 HAS_NUMPY = True
11 except ImportError:
12 HAS_NUMPY = False
13
14 from astroid import builder, nodes
15 from astroid.brain.brain_numpy_utils import (
16 NUMPY_VERSION_TYPE_HINTS_SUPPORT,
17 numpy_supports_type_hints,
18 )
19
20
21 @unittest.skipUnless(HAS_NUMPY, "This test requires the numpy library.")
22 class NumpyBrainNdarrayTest(unittest.TestCase):
23 """Test that calls to numpy functions returning arrays are correctly inferred."""
24
25 ndarray_returning_ndarray_methods = (
26 "__abs__",
27 "__add__",
28 "__and__",
29 "__array__",
30 "__array_wrap__",
31 "__copy__",
32 "__deepcopy__",
33 "__eq__",
34 "__floordiv__",
35 "__ge__",
36 "__gt__",
37 "__iadd__",
38 "__iand__",
39 "__ifloordiv__",
40 "__ilshift__",
41 "__imod__",
42 "__imul__",
43 "__invert__",
44 "__ior__",
45 "__ipow__",
46 "__irshift__",
47 "__isub__",
48 "__itruediv__",
49 "__ixor__",
50 "__le__",
51 "__lshift__",
52 "__lt__",
53 "__matmul__",
54 "__mod__",
55 "__mul__",
56 "__ne__",
57 "__neg__",
58 "__or__",
59 "__pos__",
60 "__pow__",
61 "__rshift__",
62 "__sub__",
63 "__truediv__",
64 "__xor__",
65 "all",
66 "any",
67 "argmax",
68 "argmin",
69 "argpartition",
70 "argsort",
71 "astype",
72 "byteswap",
73 "choose",
74 "clip",
75 "compress",
76 "conj",
77 "conjugate",
78 "copy",
79 "cumprod",
80 "cumsum",
81 "diagonal",
82 "dot",
83 "flatten",
84 "getfield",
85 "max",
86 "mean",
87 "min",
88 "newbyteorder",
89 "prod",
90 "ptp",
91 "ravel",
92 "repeat",
93 "reshape",
94 "round",
95 "searchsorted",
96 "squeeze",
97 "std",
98 "sum",
99 "swapaxes",
100 "take",
101 "trace",
102 "transpose",
103 "var",
104 "view",
105 )
106
107 def _inferred_ndarray_method_call(self, func_name):
108 node = builder.extract_node(f"""
109 import numpy as np
110 test_array = np.ndarray((2, 2))
111 test_array.{func_name:s}()
112 """)
113 return node.infer()
114
115 def _inferred_ndarray_attribute(self, attr_name):
116 node = builder.extract_node(f"""
117 import numpy as np
118 test_array = np.ndarray((2, 2))
119 test_array.{attr_name:s}
120 """)
121 return node.infer()
122
123 def test_numpy_function_calls_inferred_as_ndarray(self):
124 """Test that some calls to numpy functions are inferred as numpy.ndarray."""
125 licit_array_types = ".ndarray"
126 for func_ in self.ndarray_returning_ndarray_methods:
127 with self.subTest(typ=func_):
128 inferred_values = list(self._inferred_ndarray_method_call(func_))
129 self.assertTrue(
130 len(inferred_values) == 1,
131 msg=f"Too much inferred value for {func_:s}",
132 )
133 self.assertTrue(
134 inferred_values[-1].pytype() in licit_array_types,
135 msg=f"Illicit type for {func_:s} ({inferred_values[-1].pytype()})",
136 )
137
138 def test_numpy_ndarray_attribute_inferred_as_ndarray(self):
139 """Test that some numpy ndarray attributes are inferred as numpy.ndarray."""
140 licit_array_types = ".ndarray"
141 for attr_ in ("real", "imag", "shape", "T"):
142 with self.subTest(typ=attr_):
143 inferred_values = list(self._inferred_ndarray_attribute(attr_))
144 self.assertTrue(
145 len(inferred_values) == 1,
146 msg=f"Too much inferred value for {attr_:s}",
147 )
148 self.assertTrue(
149 inferred_values[-1].pytype() in licit_array_types,
150 msg=f"Illicit type for {attr_:s} ({inferred_values[-1].pytype()})",
151 )
152
153 @unittest.skipUnless(
154 HAS_NUMPY and numpy_supports_type_hints(),
155 f"This test requires the numpy library with a version above {NUMPY_VERSION_TYPE_HINTS_SUPPORT}",
156 )
157 def test_numpy_ndarray_class_support_type_indexing(self):
158 """Test that numpy ndarray class can be subscripted (type hints)."""
159 src = """
160 import numpy as np
161 np.ndarray[int]
162 """
163 node = builder.extract_node(src)
164 cls_node = node.inferred()[0]
165 self.assertIsInstance(cls_node, nodes.ClassDef)
166 self.assertEqual(cls_node.name, "ndarray")