m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

342 lines
12 KiB

6 months ago
  1. import importlib.util
  2. import itertools
  3. import os
  4. import re
  5. import shutil
  6. from collections import defaultdict
  7. from typing import Optional, IO, Dict, List
  8. import pytest
  9. import numpy as np
  10. from numpy.typing.mypy_plugin import _PRECISION_DICT, _EXTENDED_PRECISION_LIST
  11. try:
  12. from mypy import api
  13. except ImportError:
  14. NO_MYPY = True
  15. else:
  16. NO_MYPY = False
  17. DATA_DIR = os.path.join(os.path.dirname(__file__), "data")
  18. PASS_DIR = os.path.join(DATA_DIR, "pass")
  19. FAIL_DIR = os.path.join(DATA_DIR, "fail")
  20. REVEAL_DIR = os.path.join(DATA_DIR, "reveal")
  21. MISC_DIR = os.path.join(DATA_DIR, "misc")
  22. MYPY_INI = os.path.join(DATA_DIR, "mypy.ini")
  23. CACHE_DIR = os.path.join(DATA_DIR, ".mypy_cache")
  24. #: A dictionary with file names as keys and lists of the mypy stdout as values.
  25. #: To-be populated by `run_mypy`.
  26. OUTPUT_MYPY: Dict[str, List[str]] = {}
  27. def _key_func(key: str) -> str:
  28. """Split at the first occurance of the ``:`` character.
  29. Windows drive-letters (*e.g.* ``C:``) are ignored herein.
  30. """
  31. drive, tail = os.path.splitdrive(key)
  32. return os.path.join(drive, tail.split(":", 1)[0])
  33. def _strip_filename(msg: str) -> str:
  34. """Strip the filename from a mypy message."""
  35. _, tail = os.path.splitdrive(msg)
  36. return tail.split(":", 1)[-1]
  37. @pytest.mark.slow
  38. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  39. @pytest.fixture(scope="module", autouse=True)
  40. def run_mypy() -> None:
  41. """Clears the cache and run mypy before running any of the typing tests.
  42. The mypy results are cached in `OUTPUT_MYPY` for further use.
  43. The cache refresh can be skipped using
  44. NUMPY_TYPING_TEST_CLEAR_CACHE=0 pytest numpy/typing/tests
  45. """
  46. if os.path.isdir(CACHE_DIR) and bool(os.environ.get("NUMPY_TYPING_TEST_CLEAR_CACHE", True)):
  47. shutil.rmtree(CACHE_DIR)
  48. for directory in (PASS_DIR, REVEAL_DIR, FAIL_DIR, MISC_DIR):
  49. # Run mypy
  50. stdout, stderr, exit_code = api.run([
  51. "--config-file",
  52. MYPY_INI,
  53. "--cache-dir",
  54. CACHE_DIR,
  55. directory,
  56. ])
  57. if stderr:
  58. pytest.fail(f"Unexpected mypy standard error\n\n{stderr}")
  59. elif exit_code not in {0, 1}:
  60. pytest.fail(f"Unexpected mypy exit code: {exit_code}\n\n{stdout}")
  61. stdout = stdout.replace('*', '')
  62. # Parse the output
  63. iterator = itertools.groupby(stdout.split("\n"), key=_key_func)
  64. OUTPUT_MYPY.update((k, list(v)) for k, v in iterator if k)
  65. def get_test_cases(directory):
  66. for root, _, files in os.walk(directory):
  67. for fname in files:
  68. if os.path.splitext(fname)[-1] == ".py":
  69. fullpath = os.path.join(root, fname)
  70. # Use relative path for nice py.test name
  71. relpath = os.path.relpath(fullpath, start=directory)
  72. yield pytest.param(
  73. fullpath,
  74. # Manually specify a name for the test
  75. id=relpath,
  76. )
  77. @pytest.mark.slow
  78. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  79. @pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
  80. def test_success(path):
  81. # Alias `OUTPUT_MYPY` so that it appears in the local namespace
  82. output_mypy = OUTPUT_MYPY
  83. if path in output_mypy:
  84. msg = "Unexpected mypy output\n\n"
  85. msg += "\n".join(_strip_filename(v) for v in output_mypy[path])
  86. raise AssertionError(msg)
  87. @pytest.mark.slow
  88. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  89. @pytest.mark.parametrize("path", get_test_cases(FAIL_DIR))
  90. def test_fail(path):
  91. __tracebackhide__ = True
  92. with open(path) as fin:
  93. lines = fin.readlines()
  94. errors = defaultdict(lambda: "")
  95. output_mypy = OUTPUT_MYPY
  96. assert path in output_mypy
  97. for error_line in output_mypy[path]:
  98. error_line = _strip_filename(error_line)
  99. match = re.match(
  100. r"(?P<lineno>\d+): (error|note): .+$",
  101. error_line,
  102. )
  103. if match is None:
  104. raise ValueError(f"Unexpected error line format: {error_line}")
  105. lineno = int(match.group('lineno'))
  106. errors[lineno] += f'{error_line}\n'
  107. for i, line in enumerate(lines):
  108. lineno = i + 1
  109. if line.startswith('#') or (" E:" not in line and lineno not in errors):
  110. continue
  111. target_line = lines[lineno - 1]
  112. if "# E:" in target_line:
  113. marker = target_line.split("# E:")[-1].strip()
  114. expected_error = errors.get(lineno)
  115. _test_fail(path, marker, expected_error, lineno)
  116. else:
  117. pytest.fail(f"Unexpected mypy output\n\n{errors[lineno]}")
  118. _FAIL_MSG1 = """Extra error at line {}
  119. Extra error: {!r}
  120. """
  121. _FAIL_MSG2 = """Error mismatch at line {}
  122. Expected error: {!r}
  123. Observed error: {!r}
  124. """
  125. def _test_fail(path: str, error: str, expected_error: Optional[str], lineno: int) -> None:
  126. if expected_error is None:
  127. raise AssertionError(_FAIL_MSG1.format(lineno, error))
  128. elif error not in expected_error:
  129. raise AssertionError(_FAIL_MSG2.format(lineno, expected_error, error))
  130. def _construct_format_dict():
  131. dct = {k.split(".")[-1]: v.replace("numpy", "numpy.typing") for
  132. k, v in _PRECISION_DICT.items()}
  133. return {
  134. "uint8": "numpy.unsignedinteger[numpy.typing._8Bit]",
  135. "uint16": "numpy.unsignedinteger[numpy.typing._16Bit]",
  136. "uint32": "numpy.unsignedinteger[numpy.typing._32Bit]",
  137. "uint64": "numpy.unsignedinteger[numpy.typing._64Bit]",
  138. "uint128": "numpy.unsignedinteger[numpy.typing._128Bit]",
  139. "uint256": "numpy.unsignedinteger[numpy.typing._256Bit]",
  140. "int8": "numpy.signedinteger[numpy.typing._8Bit]",
  141. "int16": "numpy.signedinteger[numpy.typing._16Bit]",
  142. "int32": "numpy.signedinteger[numpy.typing._32Bit]",
  143. "int64": "numpy.signedinteger[numpy.typing._64Bit]",
  144. "int128": "numpy.signedinteger[numpy.typing._128Bit]",
  145. "int256": "numpy.signedinteger[numpy.typing._256Bit]",
  146. "float16": "numpy.floating[numpy.typing._16Bit]",
  147. "float32": "numpy.floating[numpy.typing._32Bit]",
  148. "float64": "numpy.floating[numpy.typing._64Bit]",
  149. "float80": "numpy.floating[numpy.typing._80Bit]",
  150. "float96": "numpy.floating[numpy.typing._96Bit]",
  151. "float128": "numpy.floating[numpy.typing._128Bit]",
  152. "float256": "numpy.floating[numpy.typing._256Bit]",
  153. "complex64": "numpy.complexfloating[numpy.typing._32Bit, numpy.typing._32Bit]",
  154. "complex128": "numpy.complexfloating[numpy.typing._64Bit, numpy.typing._64Bit]",
  155. "complex160": "numpy.complexfloating[numpy.typing._80Bit, numpy.typing._80Bit]",
  156. "complex192": "numpy.complexfloating[numpy.typing._96Bit, numpy.typing._96Bit]",
  157. "complex256": "numpy.complexfloating[numpy.typing._128Bit, numpy.typing._128Bit]",
  158. "complex512": "numpy.complexfloating[numpy.typing._256Bit, numpy.typing._256Bit]",
  159. "ubyte": f"numpy.unsignedinteger[{dct['_NBitByte']}]",
  160. "ushort": f"numpy.unsignedinteger[{dct['_NBitShort']}]",
  161. "uintc": f"numpy.unsignedinteger[{dct['_NBitIntC']}]",
  162. "uintp": f"numpy.unsignedinteger[{dct['_NBitIntP']}]",
  163. "uint": f"numpy.unsignedinteger[{dct['_NBitInt']}]",
  164. "ulonglong": f"numpy.unsignedinteger[{dct['_NBitLongLong']}]",
  165. "byte": f"numpy.signedinteger[{dct['_NBitByte']}]",
  166. "short": f"numpy.signedinteger[{dct['_NBitShort']}]",
  167. "intc": f"numpy.signedinteger[{dct['_NBitIntC']}]",
  168. "intp": f"numpy.signedinteger[{dct['_NBitIntP']}]",
  169. "int_": f"numpy.signedinteger[{dct['_NBitInt']}]",
  170. "longlong": f"numpy.signedinteger[{dct['_NBitLongLong']}]",
  171. "half": f"numpy.floating[{dct['_NBitHalf']}]",
  172. "single": f"numpy.floating[{dct['_NBitSingle']}]",
  173. "double": f"numpy.floating[{dct['_NBitDouble']}]",
  174. "longdouble": f"numpy.floating[{dct['_NBitLongDouble']}]",
  175. "csingle": f"numpy.complexfloating[{dct['_NBitSingle']}, {dct['_NBitSingle']}]",
  176. "cdouble": f"numpy.complexfloating[{dct['_NBitDouble']}, {dct['_NBitDouble']}]",
  177. "clongdouble": f"numpy.complexfloating[{dct['_NBitLongDouble']}, {dct['_NBitLongDouble']}]",
  178. # numpy.typing
  179. "_NBitInt": dct['_NBitInt'],
  180. }
  181. #: A dictionary with all supported format keys (as keys)
  182. #: and matching values
  183. FORMAT_DICT: Dict[str, str] = _construct_format_dict()
  184. def _parse_reveals(file: IO[str]) -> List[str]:
  185. """Extract and parse all ``" # E: "`` comments from the passed file-like object.
  186. All format keys will be substituted for their respective value from `FORMAT_DICT`,
  187. *e.g.* ``"{float64}"`` becomes ``"numpy.floating[numpy.typing._64Bit]"``.
  188. """
  189. string = file.read().replace("*", "")
  190. # Grab all `# E:`-based comments
  191. comments_array = np.char.partition(string.split("\n"), sep=" # E: ")[:, 2]
  192. comments = "/n".join(comments_array)
  193. # Only search for the `{*}` pattern within comments,
  194. # otherwise there is the risk of accidently grabbing dictionaries and sets
  195. key_set = set(re.findall(r"\{(.*?)\}", comments))
  196. kwargs = {
  197. k: FORMAT_DICT.get(k, f"<UNRECOGNIZED FORMAT KEY {k!r}>") for k in key_set
  198. }
  199. fmt_str = comments.format(**kwargs)
  200. return fmt_str.split("/n")
  201. @pytest.mark.slow
  202. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  203. @pytest.mark.parametrize("path", get_test_cases(REVEAL_DIR))
  204. def test_reveal(path):
  205. __tracebackhide__ = True
  206. with open(path) as fin:
  207. lines = _parse_reveals(fin)
  208. output_mypy = OUTPUT_MYPY
  209. assert path in output_mypy
  210. for error_line in output_mypy[path]:
  211. error_line = _strip_filename(error_line)
  212. match = re.match(
  213. r"(?P<lineno>\d+): note: .+$",
  214. error_line,
  215. )
  216. if match is None:
  217. raise ValueError(f"Unexpected reveal line format: {error_line}")
  218. lineno = int(match.group('lineno')) - 1
  219. assert "Revealed type is" in error_line
  220. marker = lines[lineno]
  221. _test_reveal(path, marker, error_line, 1 + lineno)
  222. _REVEAL_MSG = """Reveal mismatch at line {}
  223. Expected reveal: {!r}
  224. Observed reveal: {!r}
  225. """
  226. def _test_reveal(path: str, reveal: str, expected_reveal: str, lineno: int) -> None:
  227. if reveal not in expected_reveal:
  228. raise AssertionError(_REVEAL_MSG.format(lineno, expected_reveal, reveal))
  229. @pytest.mark.slow
  230. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  231. @pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
  232. def test_code_runs(path):
  233. path_without_extension, _ = os.path.splitext(path)
  234. dirname, filename = path.split(os.sep)[-2:]
  235. spec = importlib.util.spec_from_file_location(f"{dirname}.{filename}", path)
  236. test_module = importlib.util.module_from_spec(spec)
  237. spec.loader.exec_module(test_module)
  238. LINENO_MAPPING = {
  239. 3: "uint128",
  240. 4: "uint256",
  241. 6: "int128",
  242. 7: "int256",
  243. 9: "float80",
  244. 10: "float96",
  245. 11: "float128",
  246. 12: "float256",
  247. 14: "complex160",
  248. 15: "complex192",
  249. 16: "complex256",
  250. 17: "complex512",
  251. }
  252. @pytest.mark.slow
  253. @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
  254. def test_extended_precision() -> None:
  255. path = os.path.join(MISC_DIR, "extended_precision.py")
  256. output_mypy = OUTPUT_MYPY
  257. assert path in output_mypy
  258. for _msg in output_mypy[path]:
  259. *_, _lineno, msg_typ, msg = _msg.split(":")
  260. msg = _strip_filename(msg)
  261. lineno = int(_lineno)
  262. msg_typ = msg_typ.strip()
  263. assert msg_typ in {"error", "note"}
  264. if LINENO_MAPPING[lineno] in _EXTENDED_PRECISION_LIST:
  265. if msg_typ == "error":
  266. raise ValueError(f"Unexpected reveal line format: {lineno}")
  267. else:
  268. marker = FORMAT_DICT[LINENO_MAPPING[lineno]]
  269. _test_reveal(path, marker, msg, lineno)
  270. else:
  271. if msg_typ == "error":
  272. marker = "Module has no attribute"
  273. _test_fail(path, marker, msg, lineno)