|
| 1 | +"""Tests for the optional typing-extensions dependency.""" |
| 2 | + |
| 3 | +import sys |
| 4 | +import types |
| 5 | +import inspect |
| 6 | +import importlib |
| 7 | + |
| 8 | +import typing_extensions |
| 9 | +import numpy.typing as npt |
| 10 | + |
| 11 | + |
| 12 | +def _is_sub_module(obj: object) -> bool: |
| 13 | + """Check if `obj` is a `numpy.typing` submodule.""" |
| 14 | + return inspect.ismodule(obj) and obj.__name__.startswith("numpy.typing") |
| 15 | + |
| 16 | + |
| 17 | +def _is_dunder(name: str) -> bool: |
| 18 | + """Check whether `name` is a dunder.""" |
| 19 | + return name.startswith("__") and name.endswith("__") |
| 20 | + |
| 21 | + |
| 22 | +def _clear_attr(module: types.ModuleType) -> None: |
| 23 | + """Clear all (non-dunder) module-level attributes.""" |
| 24 | + del_names = [name for name in vars(module) if not _is_dunder(name)] |
| 25 | + for name in del_names: |
| 26 | + delattr(module, name) |
| 27 | + |
| 28 | + |
| 29 | +MODULES = {"numpy.typing": npt} |
| 30 | +MODULES.update({ |
| 31 | + f"numpy.typing.{k}": v for k, v in vars(npt).items() if _is_sub_module(v) |
| 32 | +}) |
| 33 | + |
| 34 | + |
| 35 | +def test_no_typing_extensions() -> None: |
| 36 | + """Import `numpy.typing` in the absence of typing-extensions. |
| 37 | +
|
| 38 | + Notes |
| 39 | + ----- |
| 40 | + Ideally, we'd just run the normal typing tests in an environment where |
| 41 | + typing-extensions is not installed, but unfortunatelly this is currently |
| 42 | + impossible as it is an indirect hard dependency of pytest. |
| 43 | +
|
| 44 | + """ |
| 45 | + assert "typing_extensions" in sys.modules |
| 46 | + |
| 47 | + try: |
| 48 | + sys.modules["typing_extensions"] = None |
| 49 | + for name, module in MODULES.items(): |
| 50 | + _clear_attr(module) |
| 51 | + assert importlib.reload(module), name |
| 52 | + finally: |
| 53 | + sys.modules["typing_extensions"] = typing_extensions |
| 54 | + for module in MODULES.values(): |
| 55 | + _clear_attr(module) |
| 56 | + importlib.reload(module) |
0 commit comments