summaryrefslogtreecommitdiff
path: root/tests/brain/numpy/test_core_multiarray.py
blob: e7ccde31c898bb8ec5f493bd1098d4ad193f1c48 (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
# 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

import unittest

try:
    import numpy  # pylint: disable=unused-import

    HAS_NUMPY = True
except ImportError:
    HAS_NUMPY = False

from astroid import builder


@unittest.skipUnless(HAS_NUMPY, "This test requires the numpy library.")
class BrainNumpyCoreMultiarrayTest(unittest.TestCase):
    """Test the numpy core multiarray brain module."""

    numpy_functions_returning_array = (
        ("array", "[1, 2]"),
        ("bincount", "[1, 2]"),
        ("busday_count", "('2011-01', '2011-02')"),
        ("busday_offset", "'2012-03', -1, roll='forward'"),
        ("concatenate", "([1, 2], [1, 2])"),
        ("datetime_as_string", "['2012-02', '2012-03']"),
        ("dot", "[1, 2]", "[1, 2]"),
        ("empty_like", "[1, 2]"),
        ("inner", "[1, 2]", "[1, 2]"),
        ("is_busday", "['2011-07-01', '2011-07-02', '2011-07-18']"),
        ("lexsort", "(('toto', 'tutu'), ('riri', 'fifi'))"),
        ("packbits", "np.array([1, 2])"),
        ("unpackbits", "np.array([[1], [2], [3]], dtype=np.uint8)"),
        ("vdot", "[1, 2]", "[1, 2]"),
        ("where", "[True, False]", "[1, 2]", "[2, 1]"),
        ("empty", "[1, 2]"),
        ("zeros", "[1, 2]"),
    )

    numpy_functions_returning_bool = (
        ("can_cast", "np.int32, np.int64"),
        ("may_share_memory", "np.array([1, 2])", "np.array([3, 4])"),
        ("shares_memory", "np.array([1, 2])", "np.array([3, 4])"),
    )

    numpy_functions_returning_dtype = (
        # ("min_scalar_type", "10"),  # Not yet tested as it returns np.dtype
        # ("result_type", "'i4'", "'c8'"),  # Not yet tested as it returns np.dtype
    )

    numpy_functions_returning_none = (("copyto", "([1, 2], [1, 3])"),)

    numpy_functions_returning_tuple = (
        (
            "unravel_index",
            "[22, 33, 44]",
            "(6, 7)",
        ),  # Not yet tested as is returns a tuple
    )

    def _inferred_numpy_func_call(self, func_name, *func_args):
        node = builder.extract_node(
            f"""
        import numpy as np
        func = np.{func_name:s}
        func({','.join(func_args):s})
        """
        )
        return node.infer()

    def _inferred_numpy_no_alias_func_call(self, func_name, *func_args):
        node = builder.extract_node(
            f"""
        import numpy
        func = numpy.{func_name:s}
        func({','.join(func_args):s})
        """
        )
        return node.infer()

    def test_numpy_function_calls_inferred_as_ndarray(self):
        """Test that calls to numpy functions are inferred as numpy.ndarray."""
        for infer_wrapper in (
            self._inferred_numpy_func_call,
            self._inferred_numpy_no_alias_func_call,
        ):
            for func_ in self.numpy_functions_returning_array:
                with self.subTest(typ=func_):
                    inferred_values = list(infer_wrapper(*func_))
                    self.assertTrue(
                        len(inferred_values) == 1,
                        msg="Too much inferred values ({}) for {:s}".format(
                            inferred_values, func_[0]
                        ),
                    )
                    self.assertTrue(
                        inferred_values[-1].pytype() == ".ndarray",
                        msg="Illicit type for {:s} ({})".format(
                            func_[0], inferred_values[-1].pytype()
                        ),
                    )

    def test_numpy_function_calls_inferred_as_bool(self):
        """Test that calls to numpy functions are inferred as bool."""
        for infer_wrapper in (
            self._inferred_numpy_func_call,
            self._inferred_numpy_no_alias_func_call,
        ):
            for func_ in self.numpy_functions_returning_bool:
                with self.subTest(typ=func_):
                    inferred_values = list(infer_wrapper(*func_))
                    self.assertTrue(
                        len(inferred_values) == 1,
                        msg="Too much inferred values ({}) for {:s}".format(
                            inferred_values, func_[0]
                        ),
                    )
                    self.assertTrue(
                        inferred_values[-1].pytype() == "builtins.bool",
                        msg="Illicit type for {:s} ({})".format(
                            func_[0], inferred_values[-1].pytype()
                        ),
                    )

    def test_numpy_function_calls_inferred_as_dtype(self):
        """Test that calls to numpy functions are inferred as numpy.dtype."""
        for infer_wrapper in (
            self._inferred_numpy_func_call,
            self._inferred_numpy_no_alias_func_call,
        ):
            for func_ in self.numpy_functions_returning_dtype:
                with self.subTest(typ=func_):
                    inferred_values = list(infer_wrapper(*func_))
                    self.assertTrue(
                        len(inferred_values) == 1,
                        msg="Too much inferred values ({}) for {:s}".format(
                            inferred_values, func_[0]
                        ),
                    )
                    self.assertTrue(
                        inferred_values[-1].pytype() == "numpy.dtype",
                        msg="Illicit type for {:s} ({})".format(
                            func_[0], inferred_values[-1].pytype()
                        ),
                    )

    def test_numpy_function_calls_inferred_as_none(self):
        """Test that calls to numpy functions are inferred as None."""
        for infer_wrapper in (
            self._inferred_numpy_func_call,
            self._inferred_numpy_no_alias_func_call,
        ):
            for func_ in self.numpy_functions_returning_none:
                with self.subTest(typ=func_):
                    inferred_values = list(infer_wrapper(*func_))
                    self.assertTrue(
                        len(inferred_values) == 1,
                        msg="Too much inferred values ({}) for {:s}".format(
                            inferred_values, func_[0]
                        ),
                    )
                    self.assertTrue(
                        inferred_values[-1].pytype() == "builtins.NoneType",
                        msg="Illicit type for {:s} ({})".format(
                            func_[0], inferred_values[-1].pytype()
                        ),
                    )

    def test_numpy_function_calls_inferred_as_tuple(self):
        """Test that calls to numpy functions are inferred as tuple."""
        for infer_wrapper in (
            self._inferred_numpy_func_call,
            self._inferred_numpy_no_alias_func_call,
        ):
            for func_ in self.numpy_functions_returning_tuple:
                with self.subTest(typ=func_):
                    inferred_values = list(infer_wrapper(*func_))
                    self.assertTrue(
                        len(inferred_values) == 1,
                        msg="Too much inferred values ({}) for {:s}".format(
                            inferred_values, func_[0]
                        ),
                    )
                    self.assertTrue(
                        inferred_values[-1].pytype() == "builtins.tuple",
                        msg="Illicit type for {:s} ({})".format(
                            func_[0], inferred_values[-1].pytype()
                        ),
                    )