Debian Codegraph @

tests/brain/numpy/test_core_numeric.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 from __future__ import annotations
6
7 import unittest
8
9 import pytest
10
11 try:
12 import numpy # pylint: disable=unused-import
13
14 HAS_NUMPY = True
15 except ImportError:
16 HAS_NUMPY = False
17
18 from astroid import builder
19
20
21 @unittest.skipUnless(HAS_NUMPY, "This test requires the numpy library.")
22 class BrainNumpyCoreNumericTest(unittest.TestCase):
23 """Test the numpy core numeric brain module."""
24
25 numpy_functions = (
26 ("zeros_like", "[1, 2]"),
27 ("full_like", "[1, 2]", "4"),
28 ("ones_like", "[1, 2]"),
29 ("ones", "[1, 2]"),
30 )
31
32 def _inferred_numpy_func_call(self, func_name, *func_args):
33 node = builder.extract_node(f"""
34 import numpy as np
35 func = np.{func_name:s}
36 func({','.join(func_args):s})
37 """)
38 return node.infer()
39
40 def test_numpy_function_calls_inferred_as_ndarray(self):
41 """Test that calls to numpy functions are inferred as numpy.ndarray."""
42 licit_array_types = (".ndarray",)
43 for func_ in self.numpy_functions:
44 with self.subTest(typ=func_):
45 inferred_values = list(self._inferred_numpy_func_call(*func_))
46 self.assertTrue(
47 len(inferred_values) == 1,
48 msg=f"Too much inferred value for {func_[0]:s}",
49 )
50 self.assertTrue(
51 inferred_values[-1].pytype() in licit_array_types,
52 msg=f"Illicit type for {func_[0]:s} ({inferred_values[-1].pytype()})",
53 )
54
55
56 @pytest.mark.skipif(not HAS_NUMPY, reason="This test requires the numpy library.")
57 @pytest.mark.parametrize(
58 "method, expected_args",
59 [
60 ("zeros_like", ["a", "dtype", "order", "subok", "shape"]),
61 ("full_like", ["a", "fill_value", "dtype", "order", "subok", "shape"]),
62 ("ones_like", ["a", "dtype", "order", "subok", "shape"]),
63 ("ones", ["shape", "dtype", "order"]),
64 ],
65 )
66 def test_function_parameters(method: str, expected_args: list[str]) -> None:
67 instance = builder.extract_node(f"""
68 import numpy
69 numpy.{method} #@
70 """)
71 actual_args = instance.inferred()[0].args.args
72 assert [arg.name for arg in actual_args] == expected_args