test_typing.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. from __future__ import annotations
  2. import importlib.util
  3. import os
  4. import re
  5. import shutil
  6. from collections import defaultdict
  7. from typing import TYPE_CHECKING
  8. import pytest
  9. from numpy.typing.mypy_plugin import _EXTENDED_PRECISION_LIST
  10. # Only trigger a full `mypy` run if this environment variable is set
  11. # Note that these tests tend to take over a minute even on a macOS M1 CPU,
  12. # and more than that in CI.
  13. RUN_MYPY = "NPY_RUN_MYPY_IN_TESTSUITE" in os.environ
  14. if RUN_MYPY and RUN_MYPY not in ('0', '', 'false'):
  15. RUN_MYPY = True
  16. # Skips all functions in this file
  17. pytestmark = pytest.mark.skipif(
  18. not RUN_MYPY,
  19. reason="`NPY_RUN_MYPY_IN_TESTSUITE` not set"
  20. )
  21. try:
  22. from mypy import api
  23. except ImportError:
  24. NO_MYPY = True
  25. else:
  26. NO_MYPY = False
  27. if TYPE_CHECKING:
  28. from collections.abc import Iterator
  29. # We need this as annotation, but it's located in a private namespace.
  30. # As a compromise, do *not* import it during runtime
  31. from _pytest.mark.structures import ParameterSet
  32. DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
  33. PASS_DIR = os.path.join(DATA_DIR, "pass")
  34. FAIL_DIR = os.path.join(DATA_DIR, "fail")
  35. REVEAL_DIR = os.path.join(DATA_DIR, "reveal")
  36. MISC_DIR = os.path.join(DATA_DIR, "misc")
  37. MYPY_INI = os.path.join(DATA_DIR, "mypy.ini")
  38. CACHE_DIR = os.path.join(DATA_DIR, ".mypy_cache")
  39. #: A dictionary with file names as keys and lists of the mypy stdout as values.
  40. #: To-be populated by `run_mypy`.
  41. OUTPUT_MYPY: defaultdict[str, list[str]] = defaultdict(list)
  42. def _key_func(key: str) -> str:
  43. """Split at the first occurrence of the ``:`` character.
  44. Windows drive-letters (*e.g.* ``C:``) are ignored herein.
  45. """
  46. drive, tail = os.path.splitdrive(key)
  47. return os.path.join(drive, tail.split(":", 1)[0])
  48. def _strip_filename(msg: str) -> tuple[int, str]:
  49. """Strip the filename and line number from a mypy message."""
  50. _, tail = os.path.splitdrive(msg)
  51. _, lineno, msg = tail.split(":", 2)
  52. return int(lineno), msg.strip()
  53. def strip_func(match: re.Match[str]) -> str:
  54. """`re.sub` helper function for stripping module names."""
  55. return match.groups()[1]
  56. @pytest.fixture(scope="module", autouse=True)
  57. def run_mypy() -> None:
  58. """Clears the cache and run mypy before running any of the typing tests.
  59. The mypy results are cached in `OUTPUT_MYPY` for further use.
  60. The cache refresh can be skipped using
  61. NUMPY_TYPING_TEST_CLEAR_CACHE=0 pytest numpy/typing/tests
  62. """
  63. if (
  64. os.path.isdir(CACHE_DIR)
  65. and bool(os.environ.get("NUMPY_TYPING_TEST_CLEAR_CACHE", True))
  66. ):
  67. shutil.rmtree(CACHE_DIR)
  68. split_pattern = re.compile(r"(\s+)?\^(\~+)?")
  69. for directory in (PASS_DIR, REVEAL_DIR, FAIL_DIR, MISC_DIR):
  70. # Run mypy
  71. stdout, stderr, exit_code = api.run([
  72. "--config-file",
  73. MYPY_INI,
  74. "--cache-dir",
  75. CACHE_DIR,
  76. directory,
  77. ])
  78. if stderr:
  79. pytest.fail(f"Unexpected mypy standard error\n\n{stderr}")
  80. elif exit_code not in {0, 1}:
  81. pytest.fail(f"Unexpected mypy exit code: {exit_code}\n\n{stdout}")
  82. str_concat = ""
  83. filename: str | None = None
  84. for i in stdout.split("\n"):
  85. if "note:" in i:
  86. continue
  87. if filename is None:
  88. filename = _key_func(i)
  89. str_concat += f"{i}\n"
  90. if split_pattern.match(i) is not None:
  91. OUTPUT_MYPY[filename].append(str_concat)
  92. str_concat = ""
  93. filename = None
  94. def get_test_cases(directory: str) -> Iterator[ParameterSet]:
  95. for root, _, files in os.walk(directory):
  96. for fname in files:
  97. short_fname, ext = os.path.splitext(fname)
  98. if ext in (".pyi", ".py"):
  99. fullpath = os.path.join(root, fname)
  100. yield pytest.param(fullpath, id=short_fname)
  101. @pytest.mark.slow
  102. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  103. @pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
  104. def test_success(path) -> None:
  105. # Alias `OUTPUT_MYPY` so that it appears in the local namespace
  106. output_mypy = OUTPUT_MYPY
  107. if path in output_mypy:
  108. msg = "Unexpected mypy output\n\n"
  109. msg += "\n".join(_strip_filename(v)[1] for v in output_mypy[path])
  110. raise AssertionError(msg)
  111. @pytest.mark.slow
  112. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  113. @pytest.mark.parametrize("path", get_test_cases(FAIL_DIR))
  114. def test_fail(path: str) -> None:
  115. __tracebackhide__ = True
  116. with open(path) as fin:
  117. lines = fin.readlines()
  118. errors = defaultdict(lambda: "")
  119. output_mypy = OUTPUT_MYPY
  120. assert path in output_mypy
  121. for error_line in output_mypy[path]:
  122. lineno, error_line = _strip_filename(error_line)
  123. errors[lineno] += f'{error_line}\n'
  124. for i, line in enumerate(lines):
  125. lineno = i + 1
  126. if (
  127. line.startswith('#')
  128. or (" E:" not in line and lineno not in errors)
  129. ):
  130. continue
  131. target_line = lines[lineno - 1]
  132. if "# E:" in target_line:
  133. expression, _, marker = target_line.partition(" # E: ")
  134. error = errors[lineno].strip()
  135. expected_error = marker.strip()
  136. _test_fail(path, expression, error, expected_error, lineno)
  137. else:
  138. pytest.fail(
  139. f"Unexpected mypy output at line {lineno}\n\n{errors[lineno]}"
  140. )
  141. _FAIL_MSG1 = """Extra error at line {}
  142. Expression: {}
  143. Extra error: {!r}
  144. """
  145. _FAIL_MSG2 = """Error mismatch at line {}
  146. Expression: {}
  147. Expected error: {}
  148. Observed error: {!r}
  149. """
  150. def _test_fail(
  151. path: str,
  152. expression: str,
  153. error: str,
  154. expected_error: None | str,
  155. lineno: int,
  156. ) -> None:
  157. if expected_error is None:
  158. raise AssertionError(_FAIL_MSG1.format(lineno, expression, error))
  159. elif expected_error not in error:
  160. raise AssertionError(_FAIL_MSG2.format(
  161. lineno, expression, expected_error, error
  162. ))
  163. _REVEAL_MSG = """Reveal mismatch at line {}
  164. {}
  165. """
  166. @pytest.mark.slow
  167. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  168. @pytest.mark.parametrize("path", get_test_cases(REVEAL_DIR))
  169. def test_reveal(path: str) -> None:
  170. """Validate that mypy correctly infers the return-types of
  171. the expressions in `path`.
  172. """
  173. __tracebackhide__ = True
  174. output_mypy = OUTPUT_MYPY
  175. if path not in output_mypy:
  176. return
  177. for error_line in output_mypy[path]:
  178. lineno, error_line = _strip_filename(error_line)
  179. raise AssertionError(_REVEAL_MSG.format(lineno, error_line))
  180. @pytest.mark.slow
  181. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  182. @pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
  183. def test_code_runs(path: str) -> None:
  184. """Validate that the code in `path` properly during runtime."""
  185. path_without_extension, _ = os.path.splitext(path)
  186. dirname, filename = path.split(os.sep)[-2:]
  187. spec = importlib.util.spec_from_file_location(
  188. f"{dirname}.{filename}", path
  189. )
  190. assert spec is not None
  191. assert spec.loader is not None
  192. test_module = importlib.util.module_from_spec(spec)
  193. spec.loader.exec_module(test_module)
  194. LINENO_MAPPING = {
  195. 11: "uint128",
  196. 12: "uint256",
  197. 14: "int128",
  198. 15: "int256",
  199. 17: "float80",
  200. 18: "float96",
  201. 19: "float128",
  202. 20: "float256",
  203. 22: "complex160",
  204. 23: "complex192",
  205. 24: "complex256",
  206. 25: "complex512",
  207. }
  208. @pytest.mark.slow
  209. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  210. def test_extended_precision() -> None:
  211. path = os.path.join(MISC_DIR, "extended_precision.pyi")
  212. output_mypy = OUTPUT_MYPY
  213. assert path in output_mypy
  214. with open(path) as f:
  215. expression_list = f.readlines()
  216. for _msg in output_mypy[path]:
  217. lineno, msg = _strip_filename(_msg)
  218. expression = expression_list[lineno - 1].rstrip("\n")
  219. if LINENO_MAPPING[lineno] in _EXTENDED_PRECISION_LIST:
  220. raise AssertionError(_REVEAL_MSG.format(lineno, msg))
  221. elif "error" not in msg:
  222. _test_fail(
  223. path, expression, msg, 'Expression is of type "Any"', lineno
  224. )