|
| 1 | +# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html |
| 2 | +# For details: https://github.com/PyCQA/astroid/blob/main/LICENSE |
| 3 | +# Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +import pytest |
| 8 | + |
| 9 | +from astroid import builder, nodes |
| 10 | + |
| 11 | +try: |
| 12 | + import numpy # pylint: disable=unused-import |
| 13 | + |
| 14 | + HAS_NUMPY = True |
| 15 | +except ImportError: |
| 16 | + HAS_NUMPY = False |
| 17 | + |
| 18 | + |
| 19 | +def _inferred_numpy_func_call(func_name: str, *func_args: str) -> nodes.FunctionDef: |
| 20 | + node = builder.extract_node( |
| 21 | + f""" |
| 22 | + import numpy as np |
| 23 | + func = np.{func_name:s} |
| 24 | + func({','.join(func_args):s}) |
| 25 | + """ |
| 26 | + ) |
| 27 | + return node.infer() |
| 28 | + |
| 29 | + |
| 30 | +@pytest.mark.skipif(not HAS_NUMPY, reason="This test requires the numpy library.") |
| 31 | +def test_numpy_function_calls_inferred_as_ndarray() -> None: |
| 32 | + """ |
| 33 | + Test that calls to numpy functions are inferred as numpy.ndarray |
| 34 | + """ |
| 35 | + method = "einsum" |
| 36 | + inferred_values = list( |
| 37 | + _inferred_numpy_func_call(method, "ii, np.arange(25).reshape(5, 5)") |
| 38 | + ) |
| 39 | + |
| 40 | + assert len(inferred_values) == 1, f"Too much inferred value for {method:s}" |
| 41 | + assert inferred_values[-1].pytype() in ( |
| 42 | + ".ndarray", |
| 43 | + ), f"Illicit type for {method:s} ({inferred_values[-1].pytype()})" |
| 44 | + |
| 45 | + |
| 46 | +@pytest.mark.skipif(not HAS_NUMPY, reason="This test requires the numpy library.") |
| 47 | +def test_function_parameters() -> None: |
| 48 | + instance = builder.extract_node( |
| 49 | + f""" |
| 50 | + import numpy |
| 51 | + numpy.einsum #@ |
| 52 | + """ |
| 53 | + ) |
| 54 | + actual_args = instance.inferred()[0].args |
| 55 | + |
| 56 | + assert actual_args.vararg == "operands" |
| 57 | + assert [arg.name for arg in actual_args.kwonlyargs] == ["out", "optimize"] |
| 58 | + assert actual_args.kwarg == "kwargs" |
0 commit comments