codekingpro/portable-devtools
115k
1"""Test the runtime usage of `numpy.typing`."""
2
3from typing import (
4 Any,
5 NamedTuple,
6 Union, # pyright: ignore[reportDeprecated]
7 get_args,
8 get_origin,
9 get_type_hints,
10)
11
12import pytest
13
14import numpy as np
15import numpy._typing as _npt
16import numpy.typing as npt
17
18
19class TypeTup(NamedTuple):
20 typ: type
21 args: tuple[type, ...]
22 origin: type | None
23
24
25def _flatten_type_alias(t: Any) -> Any:
26 # "flattens" a TypeAliasType to its underlying type alias
27 return getattr(t, "__value__", t)
28
29
30NDArrayTup = TypeTup(npt.NDArray, npt.NDArray.__args__, np.ndarray)
31
32TYPES = {
33 "ArrayLike": TypeTup(
34 _flatten_type_alias(npt.ArrayLike),
35 _flatten_type_alias(npt.ArrayLike).__args__,
36 Union,
37 ),
38 "DTypeLike": TypeTup(
39 _flatten_type_alias(npt.DTypeLike),
40 _flatten_type_alias(npt.DTypeLike).__args__,
41 Union,
42 ),
43 "NBitBase": TypeTup(npt.NBitBase, (), None), # type: ignore[deprecated] # pyright: ignore[reportDeprecated]
44 "NDArray": NDArrayTup,
45}
46
47
48@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
49def test_get_args(name: type, tup: TypeTup) -> None:
50 """Test `typing.get_args`."""
51 typ, ref = tup.typ, tup.args
52 out = get_args(typ)
53 assert out == ref
54
55
56@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
57def test_get_origin(name: type, tup: TypeTup) -> None:
58 """Test `typing.get_origin`."""
59 typ, ref = tup.typ, tup.origin
60 out = get_origin(typ)
61 assert out == ref
62
63
64@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
65def test_get_type_hints(name: type, tup: TypeTup) -> None:
66 """Test `typing.get_type_hints`."""
67 typ = tup.typ
68
69 def func(a: typ) -> None: pass
70
71 out = get_type_hints(func)
72 ref = {"a": typ, "return": type(None)}
73 assert out == ref
74
75
76@pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
77def test_get_type_hints_str(name: type, tup: TypeTup) -> None:
78 """Test `typing.get_type_hints` with string-representation of types."""
79 typ_str, typ = f"npt.{name}", tup.typ
80
81 def func(a: typ_str) -> None: pass
82
83 out = get_type_hints(func)
84 ref = {"a": getattr(npt, str(name)), "return": type(None)}
85 assert out == ref
86
87
88def test_keys() -> None:
89 """Test that ``TYPES.keys()`` and ``numpy.typing.__all__`` are synced."""
90 keys = TYPES.keys()
91 ref = set(npt.__all__)
92 assert keys == ref
93
94
95PROTOCOLS: dict[str, tuple[type[Any], object]] = {
96 "_SupportsArray": (_npt._SupportsArray, np.arange(10)),
97 "_SupportsArrayFunc": (_npt._SupportsArrayFunc, np.arange(10)),
98 "_NestedSequence": (_npt._NestedSequence, [1]),
99}
100
101
102@pytest.mark.parametrize("cls,obj", PROTOCOLS.values(), ids=PROTOCOLS.keys())
103class TestRuntimeProtocol:
104 def test_isinstance(self, cls: type[Any], obj: object) -> None:
105 assert isinstance(obj, cls)
106 assert not isinstance(None, cls)
107
108 def test_issubclass(self, cls: type[Any], obj: object) -> None:
109 assert issubclass(type(obj), cls)
110 assert not issubclass(type(None), cls)
111 