testcheck.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. """Type checker test cases"""
  2. from __future__ import annotations
  3. import os
  4. import re
  5. import sys
  6. from mypy import build
  7. from mypy.build import Graph
  8. from mypy.errors import CompileError
  9. from mypy.modulefinder import BuildSource, FindModuleCache, SearchPaths
  10. from mypy.options import TYPE_VAR_TUPLE, UNPACK
  11. from mypy.test.config import test_data_prefix, test_temp_dir
  12. from mypy.test.data import DataDrivenTestCase, DataSuite, FileOperation, module_from_path
  13. from mypy.test.helpers import (
  14. assert_module_equivalence,
  15. assert_string_arrays_equal,
  16. assert_target_equivalence,
  17. check_test_output_files,
  18. find_test_files,
  19. normalize_error_messages,
  20. parse_options,
  21. perform_file_operations,
  22. )
  23. from mypy.test.update_data import update_testcase_output
  24. try:
  25. import lxml # type: ignore[import]
  26. except ImportError:
  27. lxml = None
  28. import pytest
  29. # List of files that contain test case descriptions.
  30. # Includes all check-* files with the .test extension in the test-data/unit directory
  31. typecheck_files = find_test_files(pattern="check-*.test")
  32. # Tests that use Python version specific features:
  33. if sys.version_info < (3, 9):
  34. typecheck_files.remove("check-python39.test")
  35. if sys.version_info < (3, 10):
  36. typecheck_files.remove("check-python310.test")
  37. if sys.version_info < (3, 11):
  38. typecheck_files.remove("check-python311.test")
  39. # Special tests for platforms with case-insensitive filesystems.
  40. if sys.platform not in ("darwin", "win32"):
  41. typecheck_files.remove("check-modules-case.test")
  42. class TypeCheckSuite(DataSuite):
  43. files = typecheck_files
  44. def run_case(self, testcase: DataDrivenTestCase) -> None:
  45. if lxml is None and os.path.basename(testcase.file) == "check-reports.test":
  46. pytest.skip("Cannot import lxml. Is it installed?")
  47. incremental = (
  48. "incremental" in testcase.name.lower()
  49. or "incremental" in testcase.file
  50. or "serialize" in testcase.file
  51. )
  52. if incremental:
  53. # Incremental tests are run once with a cold cache, once with a warm cache.
  54. # Expect success on first run, errors from testcase.output (if any) on second run.
  55. num_steps = max([2] + list(testcase.output2.keys()))
  56. # Check that there are no file changes beyond the last run (they would be ignored).
  57. for dn, dirs, files in os.walk(os.curdir):
  58. for file in files:
  59. m = re.search(r"\.([2-9])$", file)
  60. if m and int(m.group(1)) > num_steps:
  61. raise ValueError(
  62. "Output file {} exists though test case only has {} runs".format(
  63. file, num_steps
  64. )
  65. )
  66. steps = testcase.find_steps()
  67. for step in range(1, num_steps + 1):
  68. idx = step - 2
  69. ops = steps[idx] if idx < len(steps) and idx >= 0 else []
  70. self.run_case_once(testcase, ops, step)
  71. else:
  72. self.run_case_once(testcase)
  73. def _sort_output_if_needed(self, testcase: DataDrivenTestCase, a: list[str]) -> None:
  74. idx = testcase.output_inline_start
  75. if not testcase.files or idx == len(testcase.output):
  76. return
  77. def _filename(_msg: str) -> str:
  78. return _msg.partition(":")[0]
  79. file_weights = {file: idx for idx, file in enumerate(_filename(msg) for msg in a)}
  80. testcase.output[idx:] = sorted(
  81. testcase.output[idx:], key=lambda msg: file_weights.get(_filename(msg), -1)
  82. )
  83. def run_case_once(
  84. self,
  85. testcase: DataDrivenTestCase,
  86. operations: list[FileOperation] = [],
  87. incremental_step: int = 0,
  88. ) -> None:
  89. original_program_text = "\n".join(testcase.input)
  90. module_data = self.parse_module(original_program_text, incremental_step)
  91. # Unload already loaded plugins, they may be updated.
  92. for file, _ in testcase.files:
  93. module = module_from_path(file)
  94. if module.endswith("_plugin") and module in sys.modules:
  95. del sys.modules[module]
  96. if incremental_step == 0 or incremental_step == 1:
  97. # In run 1, copy program text to program file.
  98. for module_name, program_path, program_text in module_data:
  99. if module_name == "__main__":
  100. with open(program_path, "w", encoding="utf8") as f:
  101. f.write(program_text)
  102. break
  103. elif incremental_step > 1:
  104. # In runs 2+, copy *.[num] files to * files.
  105. perform_file_operations(operations)
  106. # Parse options after moving files (in case mypy.ini is being moved).
  107. options = parse_options(original_program_text, testcase, incremental_step)
  108. options.use_builtins_fixtures = True
  109. if not testcase.name.endswith("_no_incomplete"):
  110. options.enable_incomplete_feature = [TYPE_VAR_TUPLE, UNPACK]
  111. options.show_traceback = True
  112. # Enable some options automatically based on test file name.
  113. if "columns" in testcase.file:
  114. options.show_column_numbers = True
  115. if "errorcodes" in testcase.file:
  116. options.hide_error_codes = False
  117. if "abstract" not in testcase.file:
  118. options.allow_empty_bodies = not testcase.name.endswith("_no_empty")
  119. if "lowercase" not in testcase.file:
  120. options.force_uppercase_builtins = True
  121. if "union-error" not in testcase.file:
  122. options.force_union_syntax = True
  123. if incremental_step and options.incremental:
  124. # Don't overwrite # flags: --no-incremental in incremental test cases
  125. options.incremental = True
  126. else:
  127. options.incremental = False
  128. # Don't waste time writing cache unless we are specifically looking for it
  129. if not testcase.writescache:
  130. options.cache_dir = os.devnull
  131. sources = []
  132. for module_name, program_path, program_text in module_data:
  133. # Always set to none so we're forced to reread the module in incremental mode
  134. sources.append(
  135. BuildSource(program_path, module_name, None if incremental_step else program_text)
  136. )
  137. plugin_dir = os.path.join(test_data_prefix, "plugins")
  138. sys.path.insert(0, plugin_dir)
  139. res = None
  140. try:
  141. res = build.build(sources=sources, options=options, alt_lib_path=test_temp_dir)
  142. a = res.errors
  143. except CompileError as e:
  144. a = e.messages
  145. finally:
  146. assert sys.path[0] == plugin_dir
  147. del sys.path[0]
  148. if testcase.normalize_output:
  149. a = normalize_error_messages(a)
  150. # Make sure error messages match
  151. if incremental_step < 2:
  152. if incremental_step == 1:
  153. msg = "Unexpected type checker output in incremental, run 1 ({}, line {})"
  154. else:
  155. assert incremental_step == 0
  156. msg = "Unexpected type checker output ({}, line {})"
  157. self._sort_output_if_needed(testcase, a)
  158. output = testcase.output
  159. else:
  160. msg = (
  161. f"Unexpected type checker output in incremental, run {incremental_step}"
  162. + " ({}, line {})"
  163. )
  164. output = testcase.output2.get(incremental_step, [])
  165. if output != a and testcase.config.getoption("--update-data", False):
  166. update_testcase_output(testcase, a, incremental_step=incremental_step)
  167. assert_string_arrays_equal(output, a, msg.format(testcase.file, testcase.line))
  168. if res:
  169. if options.cache_dir != os.devnull:
  170. self.verify_cache(module_data, res.errors, res.manager, res.graph)
  171. name = "targets"
  172. if incremental_step:
  173. name += str(incremental_step + 1)
  174. expected = testcase.expected_fine_grained_targets.get(incremental_step + 1)
  175. actual = [
  176. target
  177. for module, target in res.manager.processed_targets
  178. if module in testcase.test_modules
  179. ]
  180. if expected is not None:
  181. assert_target_equivalence(name, expected, actual)
  182. if incremental_step > 1:
  183. suffix = "" if incremental_step == 2 else str(incremental_step - 1)
  184. expected_rechecked = testcase.expected_rechecked_modules.get(incremental_step - 1)
  185. if expected_rechecked is not None:
  186. assert_module_equivalence(
  187. "rechecked" + suffix, expected_rechecked, res.manager.rechecked_modules
  188. )
  189. expected_stale = testcase.expected_stale_modules.get(incremental_step - 1)
  190. if expected_stale is not None:
  191. assert_module_equivalence(
  192. "stale" + suffix, expected_stale, res.manager.stale_modules
  193. )
  194. if testcase.output_files:
  195. check_test_output_files(testcase, incremental_step, strip_prefix="tmp/")
  196. def verify_cache(
  197. self,
  198. module_data: list[tuple[str, str, str]],
  199. a: list[str],
  200. manager: build.BuildManager,
  201. graph: Graph,
  202. ) -> None:
  203. # There should be valid cache metadata for each module except
  204. # for those that had an error in themselves or one of their
  205. # dependencies.
  206. error_paths = self.find_error_message_paths(a)
  207. busted_paths = {m.path for id, m in manager.modules.items() if graph[id].transitive_error}
  208. modules = self.find_module_files(manager)
  209. modules.update({module_name: path for module_name, path, text in module_data})
  210. missing_paths = self.find_missing_cache_files(modules, manager)
  211. # We would like to assert error_paths.issubset(busted_paths)
  212. # but this runs into trouble because while some 'notes' are
  213. # really errors that cause an error to be marked, many are
  214. # just notes attached to other errors.
  215. assert error_paths or not busted_paths, "Some modules reported error despite no errors"
  216. if not missing_paths == busted_paths:
  217. raise AssertionError(f"cache data discrepancy {missing_paths} != {busted_paths}")
  218. assert os.path.isfile(os.path.join(manager.options.cache_dir, ".gitignore"))
  219. cachedir_tag = os.path.join(manager.options.cache_dir, "CACHEDIR.TAG")
  220. assert os.path.isfile(cachedir_tag)
  221. with open(cachedir_tag) as f:
  222. assert f.read().startswith("Signature: 8a477f597d28d172789f06886806bc55")
  223. def find_error_message_paths(self, a: list[str]) -> set[str]:
  224. hits = set()
  225. for line in a:
  226. m = re.match(r"([^\s:]+):(\d+:)?(\d+:)? (error|warning|note):", line)
  227. if m:
  228. p = m.group(1)
  229. hits.add(p)
  230. return hits
  231. def find_module_files(self, manager: build.BuildManager) -> dict[str, str]:
  232. return {id: module.path for id, module in manager.modules.items()}
  233. def find_missing_cache_files(
  234. self, modules: dict[str, str], manager: build.BuildManager
  235. ) -> set[str]:
  236. ignore_errors = True
  237. missing = {}
  238. for id, path in modules.items():
  239. meta = build.find_cache_meta(id, path, manager)
  240. if not build.validate_meta(meta, id, path, ignore_errors, manager):
  241. missing[id] = path
  242. return set(missing.values())
  243. def parse_module(
  244. self, program_text: str, incremental_step: int = 0
  245. ) -> list[tuple[str, str, str]]:
  246. """Return the module and program names for a test case.
  247. Normally, the unit tests will parse the default ('__main__')
  248. module and follow all the imports listed there. You can override
  249. this behavior and instruct the tests to check multiple modules
  250. by using a comment like this in the test case input:
  251. # cmd: mypy -m foo.bar foo.baz
  252. You can also use `# cmdN:` to have a different cmd for incremental
  253. step N (2, 3, ...).
  254. Return a list of tuples (module name, file name, program text).
  255. """
  256. m = re.search("# cmd: mypy -m ([a-zA-Z0-9_. ]+)$", program_text, flags=re.MULTILINE)
  257. if incremental_step > 1:
  258. alt_regex = f"# cmd{incremental_step}: mypy -m ([a-zA-Z0-9_. ]+)$"
  259. alt_m = re.search(alt_regex, program_text, flags=re.MULTILINE)
  260. if alt_m is not None:
  261. # Optionally return a different command if in a later step
  262. # of incremental mode, otherwise default to reusing the
  263. # original cmd.
  264. m = alt_m
  265. if m:
  266. # The test case wants to use a non-default main
  267. # module. Look up the module and give it as the thing to
  268. # analyze.
  269. module_names = m.group(1)
  270. out = []
  271. search_paths = SearchPaths((test_temp_dir,), (), (), ())
  272. cache = FindModuleCache(search_paths, fscache=None, options=None)
  273. for module_name in module_names.split(" "):
  274. path = cache.find_module(module_name)
  275. assert isinstance(path, str), f"Can't find ad hoc case file: {module_name}"
  276. with open(path, encoding="utf8") as f:
  277. program_text = f.read()
  278. out.append((module_name, path, program_text))
  279. return out
  280. else:
  281. return [("__main__", "main", program_text)]