test_runtime.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. """Test the runtime usage of `numpy.typing`."""
  2. from __future__ import annotations
  3. from typing import (
  4. get_type_hints,
  5. Union,
  6. NamedTuple,
  7. get_args,
  8. get_origin,
  9. Any,
  10. )
  11. import pytest
  12. import numpy as np
  13. import numpy.typing as npt
  14. import numpy._typing as _npt
  15. class TypeTup(NamedTuple):
  16. typ: type
  17. args: tuple[type, ...]
  18. origin: None | type
  19. NDArrayTup = TypeTup(npt.NDArray, npt.NDArray.__args__, np.ndarray)
  20. TYPES = {
  21. "ArrayLike": TypeTup(npt.ArrayLike, npt.ArrayLike.__args__, Union),
  22. "DTypeLike": TypeTup(npt.DTypeLike, npt.DTypeLike.__args__, Union),
  23. "NBitBase": TypeTup(npt.NBitBase, (), None),
  24. "NDArray": NDArrayTup,
  25. }
  26. @pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
  27. def test_get_args(name: type, tup: TypeTup) -> None:
  28. """Test `typing.get_args`."""
  29. typ, ref = tup.typ, tup.args
  30. out = get_args(typ)
  31. assert out == ref
  32. @pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
  33. def test_get_origin(name: type, tup: TypeTup) -> None:
  34. """Test `typing.get_origin`."""
  35. typ, ref = tup.typ, tup.origin
  36. out = get_origin(typ)
  37. assert out == ref
  38. @pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
  39. def test_get_type_hints(name: type, tup: TypeTup) -> None:
  40. """Test `typing.get_type_hints`."""
  41. typ = tup.typ
  42. # Explicitly set `__annotations__` in order to circumvent the
  43. # stringification performed by `from __future__ import annotations`
  44. def func(a): pass
  45. func.__annotations__ = {"a": typ, "return": None}
  46. out = get_type_hints(func)
  47. ref = {"a": typ, "return": type(None)}
  48. assert out == ref
  49. @pytest.mark.parametrize("name,tup", TYPES.items(), ids=TYPES.keys())
  50. def test_get_type_hints_str(name: type, tup: TypeTup) -> None:
  51. """Test `typing.get_type_hints` with string-representation of types."""
  52. typ_str, typ = f"npt.{name}", tup.typ
  53. # Explicitly set `__annotations__` in order to circumvent the
  54. # stringification performed by `from __future__ import annotations`
  55. def func(a): pass
  56. func.__annotations__ = {"a": typ_str, "return": None}
  57. out = get_type_hints(func)
  58. ref = {"a": typ, "return": type(None)}
  59. assert out == ref
  60. def test_keys() -> None:
  61. """Test that ``TYPES.keys()`` and ``numpy.typing.__all__`` are synced."""
  62. keys = TYPES.keys()
  63. ref = set(npt.__all__)
  64. assert keys == ref
  65. PROTOCOLS: dict[str, tuple[type[Any], object]] = {
  66. "_SupportsDType": (_npt._SupportsDType, np.int64(1)),
  67. "_SupportsArray": (_npt._SupportsArray, np.arange(10)),
  68. "_SupportsArrayFunc": (_npt._SupportsArrayFunc, np.arange(10)),
  69. "_NestedSequence": (_npt._NestedSequence, [1]),
  70. }
  71. @pytest.mark.parametrize("cls,obj", PROTOCOLS.values(), ids=PROTOCOLS.keys())
  72. class TestRuntimeProtocol:
  73. def test_isinstance(self, cls: type[Any], obj: object) -> None:
  74. assert isinstance(obj, cls)
  75. assert not isinstance(None, cls)
  76. def test_issubclass(self, cls: type[Any], obj: object) -> None:
  77. if cls is _npt._SupportsDType:
  78. pytest.xfail(
  79. "Protocols with non-method members don't support issubclass()"
  80. )
  81. assert issubclass(type(obj), cls)
  82. assert not issubclass(type(None), cls)