data.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806
  1. """Utilities for processing .test files containing test case descriptions."""
  2. from __future__ import annotations
  3. import os
  4. import os.path
  5. import posixpath
  6. import re
  7. import shutil
  8. import sys
  9. import tempfile
  10. from abc import abstractmethod
  11. from dataclasses import dataclass
  12. from pathlib import Path
  13. from typing import Any, Iterator, NamedTuple, Pattern, Union
  14. from typing_extensions import Final, TypeAlias as _TypeAlias
  15. import pytest
  16. from mypy.test.config import PREFIX, test_data_prefix, test_temp_dir
  17. root_dir = os.path.normpath(PREFIX)
  18. # Debuggers that we support for debugging mypyc run tests
  19. # implementation of using each of these debuggers is in test_run.py
  20. # TODO: support more debuggers
  21. SUPPORTED_DEBUGGERS: Final = ["gdb", "lldb"]
  22. # File modify/create operation: copy module contents from source_path.
  23. class UpdateFile(NamedTuple):
  24. module: str
  25. content: str
  26. target_path: str
  27. # File delete operation: delete module file.
  28. class DeleteFile(NamedTuple):
  29. module: str
  30. path: str
  31. FileOperation: _TypeAlias = Union[UpdateFile, DeleteFile]
  32. def _file_arg_to_module(filename: str) -> str:
  33. filename, _ = os.path.splitext(filename)
  34. parts = filename.split("/") # not os.sep since it comes from test data
  35. if parts[-1] == "__init__":
  36. parts.pop()
  37. return ".".join(parts)
  38. def parse_test_case(case: DataDrivenTestCase) -> None:
  39. """Parse and prepare a single case from suite with test case descriptions.
  40. This method is part of the setup phase, just before the test case is run.
  41. """
  42. test_items = parse_test_data(case.data, case.name)
  43. base_path = case.suite.base_path
  44. if case.suite.native_sep:
  45. join = os.path.join
  46. else:
  47. join = posixpath.join
  48. out_section_missing = case.suite.required_out_section
  49. normalize_output = True
  50. files: list[tuple[str, str]] = [] # path and contents
  51. output_files: list[tuple[str, str | Pattern[str]]] = [] # output path and contents
  52. output: list[str] = [] # Regular output errors
  53. output2: dict[int, list[str]] = {} # Output errors for incremental, runs 2+
  54. deleted_paths: dict[int, set[str]] = {} # from run number of paths
  55. stale_modules: dict[int, set[str]] = {} # from run number to module names
  56. rechecked_modules: dict[int, set[str]] = {} # from run number module names
  57. triggered: list[str] = [] # Active triggers (one line per incremental step)
  58. targets: dict[int, list[str]] = {} # Fine-grained targets (per fine-grained update)
  59. test_modules: list[str] = [] # Modules which are deemed "test" (vs "fixture")
  60. # Process the parsed items. Each item has a header of form [id args],
  61. # optionally followed by lines of text.
  62. item = first_item = test_items[0]
  63. test_modules.append("__main__")
  64. for item in test_items[1:]:
  65. if item.id in {"file", "fixture", "outfile", "outfile-re"}:
  66. # Record an extra file needed for the test case.
  67. assert item.arg is not None
  68. contents = expand_variables("\n".join(item.data))
  69. path = join(base_path, item.arg)
  70. if item.id != "fixture":
  71. test_modules.append(_file_arg_to_module(item.arg))
  72. if item.id in {"file", "fixture"}:
  73. files.append((path, contents))
  74. elif item.id == "outfile-re":
  75. output_files.append((path, re.compile(contents.rstrip(), re.S)))
  76. elif item.id == "outfile":
  77. output_files.append((path, contents))
  78. elif item.id == "builtins":
  79. # Use an alternative stub file for the builtins module.
  80. assert item.arg is not None
  81. mpath = join(os.path.dirname(case.file), item.arg)
  82. with open(mpath, encoding="utf8") as f:
  83. files.append((join(base_path, "builtins.pyi"), f.read()))
  84. elif item.id == "typing":
  85. # Use an alternative stub file for the typing module.
  86. assert item.arg is not None
  87. src_path = join(os.path.dirname(case.file), item.arg)
  88. with open(src_path, encoding="utf8") as f:
  89. files.append((join(base_path, "typing.pyi"), f.read()))
  90. elif item.id == "_typeshed":
  91. # Use an alternative stub file for the _typeshed module.
  92. assert item.arg is not None
  93. src_path = join(os.path.dirname(case.file), item.arg)
  94. with open(src_path, encoding="utf8") as f:
  95. files.append((join(base_path, "_typeshed.pyi"), f.read()))
  96. elif re.match(r"stale[0-9]*$", item.id):
  97. passnum = 1 if item.id == "stale" else int(item.id[len("stale") :])
  98. assert passnum > 0
  99. modules = set() if item.arg is None else {t.strip() for t in item.arg.split(",")}
  100. stale_modules[passnum] = modules
  101. elif re.match(r"rechecked[0-9]*$", item.id):
  102. passnum = 1 if item.id == "rechecked" else int(item.id[len("rechecked") :])
  103. assert passnum > 0
  104. modules = set() if item.arg is None else {t.strip() for t in item.arg.split(",")}
  105. rechecked_modules[passnum] = modules
  106. elif re.match(r"targets[0-9]*$", item.id):
  107. passnum = 1 if item.id == "targets" else int(item.id[len("targets") :])
  108. assert passnum > 0
  109. reprocessed = [] if item.arg is None else [t.strip() for t in item.arg.split(",")]
  110. targets[passnum] = reprocessed
  111. elif item.id == "delete":
  112. # File/directory to delete during a multi-step test case
  113. assert item.arg is not None
  114. m = re.match(r"(.*)\.([0-9]+)$", item.arg)
  115. assert m, f"Invalid delete section: {item.arg}"
  116. num = int(m.group(2))
  117. assert num >= 2, f"Can't delete during step {num}"
  118. full = join(base_path, m.group(1))
  119. deleted_paths.setdefault(num, set()).add(full)
  120. elif re.match(r"out[0-9]*$", item.id):
  121. if item.arg is None:
  122. args = []
  123. else:
  124. args = item.arg.split(",")
  125. version_check = True
  126. for arg in args:
  127. if arg == "skip-path-normalization":
  128. normalize_output = False
  129. if arg.startswith("version"):
  130. compare_op = arg[7:9]
  131. if compare_op not in {">=", "=="}:
  132. raise ValueError(
  133. "{}, line {}: Only >= and == version checks are currently supported".format(
  134. case.file, item.line
  135. )
  136. )
  137. version_str = arg[9:]
  138. try:
  139. version = tuple(int(x) for x in version_str.split("."))
  140. except ValueError:
  141. raise ValueError(
  142. '{}, line {}: "{}" is not a valid python version'.format(
  143. case.file, item.line, version_str
  144. )
  145. )
  146. if compare_op == ">=":
  147. version_check = sys.version_info >= version
  148. elif compare_op == "==":
  149. if not 1 < len(version) < 4:
  150. raise ValueError(
  151. "{}, line {}: Only minor or patch version checks "
  152. 'are currently supported with "==": "{}"'.format(
  153. case.file, item.line, version_str
  154. )
  155. )
  156. version_check = sys.version_info[: len(version)] == version
  157. if version_check:
  158. tmp_output = [expand_variables(line) for line in item.data]
  159. if os.path.sep == "\\" and normalize_output:
  160. tmp_output = [fix_win_path(line) for line in tmp_output]
  161. if item.id == "out" or item.id == "out1":
  162. output = tmp_output
  163. else:
  164. passnum = int(item.id[len("out") :])
  165. assert passnum > 1
  166. output2[passnum] = tmp_output
  167. out_section_missing = False
  168. elif item.id == "triggered" and item.arg is None:
  169. triggered = item.data
  170. else:
  171. raise ValueError(f"Invalid section header {item.id} in {case.file}:{item.line}")
  172. if out_section_missing:
  173. raise ValueError(f"{case.file}, line {first_item.line}: Required output section not found")
  174. for passnum in stale_modules.keys():
  175. if passnum not in rechecked_modules:
  176. # If the set of rechecked modules isn't specified, make it the same as the set
  177. # of modules with a stale public interface.
  178. rechecked_modules[passnum] = stale_modules[passnum]
  179. if (
  180. passnum in stale_modules
  181. and passnum in rechecked_modules
  182. and not stale_modules[passnum].issubset(rechecked_modules[passnum])
  183. ):
  184. raise ValueError(
  185. (
  186. "Stale modules after pass {} must be a subset of rechecked modules ({}:{})"
  187. ).format(passnum, case.file, first_item.line)
  188. )
  189. output_inline_start = len(output)
  190. input = first_item.data
  191. expand_errors(input, output, "main")
  192. for file_path, contents in files:
  193. expand_errors(contents.split("\n"), output, file_path)
  194. seen_files = set()
  195. for file, _ in files:
  196. if file in seen_files:
  197. raise ValueError(
  198. f"{case.file}, line {first_item.line}: Duplicated filename {file}. Did you include"
  199. " it multiple times?"
  200. )
  201. seen_files.add(file)
  202. case.input = input
  203. case.output = output
  204. case.output_inline_start = output_inline_start
  205. case.output2 = output2
  206. case.last_line = case.line + item.line + len(item.data) - 2
  207. case.files = files
  208. case.output_files = output_files
  209. case.expected_stale_modules = stale_modules
  210. case.expected_rechecked_modules = rechecked_modules
  211. case.deleted_paths = deleted_paths
  212. case.triggered = triggered or []
  213. case.normalize_output = normalize_output
  214. case.expected_fine_grained_targets = targets
  215. case.test_modules = test_modules
  216. class DataDrivenTestCase(pytest.Item):
  217. """Holds parsed data-driven test cases, and handles directory setup and teardown."""
  218. # Override parent member type
  219. parent: DataSuiteCollector
  220. input: list[str]
  221. output: list[str] # Output for the first pass
  222. output_inline_start: int
  223. output2: dict[int, list[str]] # Output for runs 2+, indexed by run number
  224. # full path of test suite
  225. file = ""
  226. line = 0
  227. # (file path, file content) tuples
  228. files: list[tuple[str, str]]
  229. # Modules which is to be considered "test" rather than "fixture"
  230. test_modules: list[str]
  231. expected_stale_modules: dict[int, set[str]]
  232. expected_rechecked_modules: dict[int, set[str]]
  233. expected_fine_grained_targets: dict[int, list[str]]
  234. # Whether or not we should normalize the output to standardize things like
  235. # forward vs backward slashes in file paths for Windows vs Linux.
  236. normalize_output = True
  237. # Extra attributes used by some tests.
  238. last_line: int
  239. output_files: list[tuple[str, str | Pattern[str]]] # Path and contents for output files
  240. deleted_paths: dict[int, set[str]] # Mapping run number -> paths
  241. triggered: list[str] # Active triggers (one line per incremental step)
  242. def __init__(
  243. self,
  244. parent: DataSuiteCollector,
  245. suite: DataSuite,
  246. file: str,
  247. name: str,
  248. writescache: bool,
  249. only_when: str,
  250. platform: str | None,
  251. skip: bool,
  252. xfail: bool,
  253. data: str,
  254. line: int,
  255. ) -> None:
  256. super().__init__(name, parent)
  257. self.suite = suite
  258. self.file = file
  259. self.writescache = writescache
  260. self.only_when = only_when
  261. if (platform == "windows" and sys.platform != "win32") or (
  262. platform == "posix" and sys.platform == "win32"
  263. ):
  264. skip = True
  265. self.skip = skip
  266. self.xfail = xfail
  267. self.data = data
  268. self.line = line
  269. self.old_cwd: str | None = None
  270. self.tmpdir: tempfile.TemporaryDirectory[str] | None = None
  271. def runtest(self) -> None:
  272. if self.skip:
  273. pytest.skip()
  274. # TODO: add a better error message for when someone uses skip and xfail at the same time
  275. elif self.xfail:
  276. self.add_marker(pytest.mark.xfail)
  277. parent = self.getparent(DataSuiteCollector)
  278. assert parent is not None, "Should not happen"
  279. suite = parent.obj()
  280. suite.setup()
  281. try:
  282. suite.run_case(self)
  283. except Exception:
  284. # As a debugging aid, support copying the contents of the tmp directory somewhere
  285. save_dir: str | None = self.config.getoption("--save-failures-to", None)
  286. if save_dir:
  287. assert self.tmpdir is not None
  288. target_dir = os.path.join(save_dir, os.path.basename(self.tmpdir.name))
  289. print(f"Copying data from test {self.name} to {target_dir}")
  290. if not os.path.isabs(target_dir):
  291. assert self.old_cwd
  292. target_dir = os.path.join(self.old_cwd, target_dir)
  293. shutil.copytree(self.tmpdir.name, target_dir)
  294. raise
  295. def setup(self) -> None:
  296. parse_test_case(case=self)
  297. self.old_cwd = os.getcwd()
  298. self.tmpdir = tempfile.TemporaryDirectory(prefix="mypy-test-")
  299. os.chdir(self.tmpdir.name)
  300. os.mkdir(test_temp_dir)
  301. # Precalculate steps for find_steps()
  302. steps: dict[int, list[FileOperation]] = {}
  303. for path, content in self.files:
  304. m = re.match(r".*\.([0-9]+)$", path)
  305. if m:
  306. # Skip writing subsequent incremental steps - rather
  307. # store them as operations.
  308. num = int(m.group(1))
  309. assert num >= 2
  310. target_path = re.sub(r"\.[0-9]+$", "", path)
  311. module = module_from_path(target_path)
  312. operation = UpdateFile(module, content, target_path)
  313. steps.setdefault(num, []).append(operation)
  314. else:
  315. # Write the first incremental steps
  316. dir = os.path.dirname(path)
  317. os.makedirs(dir, exist_ok=True)
  318. with open(path, "w", encoding="utf8") as f:
  319. f.write(content)
  320. for num, paths in self.deleted_paths.items():
  321. assert num >= 2
  322. for path in paths:
  323. module = module_from_path(path)
  324. steps.setdefault(num, []).append(DeleteFile(module, path))
  325. max_step = max(steps) if steps else 2
  326. self.steps = [steps.get(num, []) for num in range(2, max_step + 1)]
  327. def teardown(self) -> None:
  328. assert self.old_cwd is not None and self.tmpdir is not None, "test was not properly set up"
  329. os.chdir(self.old_cwd)
  330. try:
  331. self.tmpdir.cleanup()
  332. except OSError:
  333. pass
  334. self.old_cwd = None
  335. self.tmpdir = None
  336. def reportinfo(self) -> tuple[str, int, str]:
  337. return self.file, self.line, self.name
  338. def repr_failure(self, excinfo: Any, style: Any | None = None) -> str:
  339. if isinstance(excinfo.value, SystemExit):
  340. # We assume that before doing exit() (which raises SystemExit) we've printed
  341. # enough context about what happened so that a stack trace is not useful.
  342. # In particular, uncaught exceptions during semantic analysis or type checking
  343. # call exit() and they already print out a stack trace.
  344. excrepr = excinfo.exconly()
  345. elif isinstance(excinfo.value, pytest.fail.Exception) and not excinfo.value.pytrace:
  346. excrepr = excinfo.exconly()
  347. else:
  348. self.parent._prunetraceback(excinfo)
  349. excrepr = excinfo.getrepr(style="short")
  350. return f"data: {self.file}:{self.line}:\n{excrepr}"
  351. def find_steps(self) -> list[list[FileOperation]]:
  352. """Return a list of descriptions of file operations for each incremental step.
  353. The first list item corresponds to the first incremental step, the second for the
  354. second step, etc. Each operation can either be a file modification/creation (UpdateFile)
  355. or deletion (DeleteFile).
  356. Defaults to having two steps if there aern't any operations.
  357. """
  358. return self.steps
  359. def module_from_path(path: str) -> str:
  360. path = re.sub(r"\.pyi?$", "", path)
  361. # We can have a mix of Unix-style and Windows-style separators.
  362. parts = re.split(r"[/\\]", path)
  363. del parts[0]
  364. module = ".".join(parts)
  365. module = re.sub(r"\.__init__$", "", module)
  366. return module
  367. @dataclass
  368. class TestItem:
  369. """Parsed test caseitem.
  370. An item is of the form
  371. [id arg]
  372. .. data ..
  373. """
  374. id: str
  375. arg: str | None
  376. # Processed, collapsed text data
  377. data: list[str]
  378. # Start line: 1-based, inclusive, relative to testcase
  379. line: int
  380. # End line: 1-based, exclusive, relative to testcase; not same as `line + len(test_item.data)` due to collapsing
  381. end_line: int
  382. @property
  383. def trimmed_newlines(self) -> int: # compensates for strip_list
  384. return self.end_line - self.line - len(self.data)
  385. def parse_test_data(raw_data: str, name: str) -> list[TestItem]:
  386. """Parse a list of lines that represent a sequence of test items."""
  387. lines = ["", "[case " + name + "]"] + raw_data.split("\n")
  388. ret: list[TestItem] = []
  389. data: list[str] = []
  390. id: str | None = None
  391. arg: str | None = None
  392. i = 0
  393. i0 = 0
  394. while i < len(lines):
  395. s = lines[i].strip()
  396. if lines[i].startswith("[") and s.endswith("]"):
  397. if id:
  398. data = collapse_line_continuation(data)
  399. data = strip_list(data)
  400. ret.append(TestItem(id, arg, data, i0 + 1, i))
  401. i0 = i
  402. id = s[1:-1]
  403. arg = None
  404. if " " in id:
  405. arg = id[id.index(" ") + 1 :]
  406. id = id[: id.index(" ")]
  407. data = []
  408. elif lines[i].startswith("\\["):
  409. data.append(lines[i][1:])
  410. elif not lines[i].startswith("--"):
  411. data.append(lines[i])
  412. elif lines[i].startswith("----"):
  413. data.append(lines[i][2:])
  414. i += 1
  415. # Process the last item.
  416. if id:
  417. data = collapse_line_continuation(data)
  418. data = strip_list(data)
  419. ret.append(TestItem(id, arg, data, i0 + 1, i - 1))
  420. return ret
  421. def strip_list(l: list[str]) -> list[str]:
  422. """Return a stripped copy of l.
  423. Strip whitespace at the end of all lines, and strip all empty
  424. lines from the end of the array.
  425. """
  426. r: list[str] = []
  427. for s in l:
  428. # Strip spaces at end of line
  429. r.append(re.sub(r"\s+$", "", s))
  430. while r and r[-1] == "":
  431. r.pop()
  432. return r
  433. def collapse_line_continuation(l: list[str]) -> list[str]:
  434. r: list[str] = []
  435. cont = False
  436. for s in l:
  437. ss = re.sub(r"\\$", "", s)
  438. if cont:
  439. r[-1] += re.sub("^ +", "", ss)
  440. else:
  441. r.append(ss)
  442. cont = s.endswith("\\")
  443. return r
  444. def expand_variables(s: str) -> str:
  445. return s.replace("<ROOT>", root_dir)
  446. def expand_errors(input: list[str], output: list[str], fnam: str) -> None:
  447. """Transform comments such as '# E: message' or
  448. '# E:3: message' in input.
  449. The result is lines like 'fnam:line: error: message'.
  450. """
  451. for i in range(len(input)):
  452. # The first in the split things isn't a comment
  453. for possible_err_comment in input[i].split(" # ")[1:]:
  454. m = re.search(
  455. r"^([ENW]):((?P<col>\d+):)? (?P<message>.*)$", possible_err_comment.strip()
  456. )
  457. if m:
  458. if m.group(1) == "E":
  459. severity = "error"
  460. elif m.group(1) == "N":
  461. severity = "note"
  462. elif m.group(1) == "W":
  463. severity = "warning"
  464. col = m.group("col")
  465. message = m.group("message")
  466. message = message.replace("\\#", "#") # adds back escaped # character
  467. if col is None:
  468. output.append(f"{fnam}:{i + 1}: {severity}: {message}")
  469. else:
  470. output.append(f"{fnam}:{i + 1}:{col}: {severity}: {message}")
  471. def fix_win_path(line: str) -> str:
  472. r"""Changes Windows paths to Linux paths in error messages.
  473. E.g. foo\bar.py -> foo/bar.py.
  474. """
  475. line = line.replace(root_dir, root_dir.replace("\\", "/"))
  476. m = re.match(r"^([\S/]+):(\d+:)?(\s+.*)", line)
  477. if not m:
  478. return line
  479. else:
  480. filename, lineno, message = m.groups()
  481. return "{}:{}{}".format(filename.replace("\\", "/"), lineno or "", message)
  482. def fix_cobertura_filename(line: str) -> str:
  483. r"""Changes filename paths to Linux paths in Cobertura output files.
  484. E.g. filename="pkg\subpkg\a.py" -> filename="pkg/subpkg/a.py".
  485. """
  486. m = re.search(r'<class .* filename="(?P<filename>.*?)"', line)
  487. if not m:
  488. return line
  489. return "{}{}{}".format(
  490. line[: m.start(1)], m.group("filename").replace("\\", "/"), line[m.end(1) :]
  491. )
  492. ##
  493. #
  494. # pytest setup
  495. #
  496. ##
  497. # This function name is special to pytest. See
  498. # https://docs.pytest.org/en/latest/reference.html#initialization-hooks
  499. def pytest_addoption(parser: Any) -> None:
  500. group = parser.getgroup("mypy")
  501. group.addoption(
  502. "--update-data",
  503. action="store_true",
  504. default=False,
  505. help="Update test data to reflect actual output (supported only for certain tests)",
  506. )
  507. group.addoption(
  508. "--save-failures-to",
  509. default=None,
  510. help="Copy the temp directories from failing tests to a target directory",
  511. )
  512. group.addoption(
  513. "--mypy-verbose", action="count", help="Set the verbose flag when creating mypy Options"
  514. )
  515. group.addoption(
  516. "--mypyc-showc",
  517. action="store_true",
  518. default=False,
  519. help="Display C code on mypyc test failures",
  520. )
  521. group.addoption(
  522. "--mypyc-debug",
  523. default=None,
  524. dest="debugger",
  525. choices=SUPPORTED_DEBUGGERS,
  526. help="Run the first mypyc run test with the specified debugger",
  527. )
  528. # This function name is special to pytest. See
  529. # https://doc.pytest.org/en/latest/how-to/writing_plugins.html#collection-hooks
  530. def pytest_pycollect_makeitem(collector: Any, name: str, obj: object) -> Any | None:
  531. """Called by pytest on each object in modules configured in conftest.py files.
  532. collector is pytest.Collector, returns Optional[pytest.Class]
  533. """
  534. if isinstance(obj, type):
  535. # Only classes derived from DataSuite contain test cases, not the DataSuite class itself
  536. if issubclass(obj, DataSuite) and obj is not DataSuite:
  537. # Non-None result means this obj is a test case.
  538. # The collect method of the returned DataSuiteCollector instance will be called later,
  539. # with self.obj being obj.
  540. return DataSuiteCollector.from_parent( # type: ignore[no-untyped-call]
  541. parent=collector, name=name
  542. )
  543. return None
  544. def split_test_cases(
  545. parent: DataFileCollector, suite: DataSuite, file: str
  546. ) -> Iterator[DataDrivenTestCase]:
  547. """Iterate over raw test cases in file, at collection time, ignoring sub items.
  548. The collection phase is slow, so any heavy processing should be deferred to after
  549. uninteresting tests are filtered (when using -k PATTERN switch).
  550. """
  551. with open(file, encoding="utf-8") as f:
  552. data = f.read()
  553. # number of groups in the below regex
  554. NUM_GROUPS = 7
  555. cases = re.split(
  556. r"^\[case ([a-zA-Z_0-9]+)"
  557. r"(-writescache)?"
  558. r"(-only_when_cache|-only_when_nocache)?"
  559. r"(-posix|-windows)?"
  560. r"(-skip)?"
  561. r"(-xfail)?"
  562. r"\][ \t]*$\n",
  563. data,
  564. flags=re.DOTALL | re.MULTILINE,
  565. )
  566. line_no = cases[0].count("\n") + 1
  567. test_names = set()
  568. for i in range(1, len(cases), NUM_GROUPS):
  569. name, writescache, only_when, platform_flag, skip, xfail, data = cases[i : i + NUM_GROUPS]
  570. if name in test_names:
  571. raise RuntimeError(
  572. 'Found a duplicate test name "{}" in {} on line {}'.format(
  573. name, parent.name, line_no
  574. )
  575. )
  576. platform = platform_flag[1:] if platform_flag else None
  577. yield DataDrivenTestCase.from_parent(
  578. parent=parent,
  579. suite=suite,
  580. file=file,
  581. name=add_test_name_suffix(name, suite.test_name_suffix),
  582. writescache=bool(writescache),
  583. only_when=only_when,
  584. platform=platform,
  585. skip=bool(skip),
  586. xfail=bool(xfail),
  587. data=data,
  588. line=line_no,
  589. )
  590. line_no += data.count("\n") + 1
  591. # Record existing tests to prevent duplicates:
  592. test_names.update({name})
  593. class DataSuiteCollector(pytest.Class):
  594. def collect(self) -> Iterator[DataFileCollector]:
  595. """Called by pytest on each of the object returned from pytest_pycollect_makeitem"""
  596. # obj is the object for which pytest_pycollect_makeitem returned self.
  597. suite: DataSuite = self.obj
  598. assert os.path.isdir(
  599. suite.data_prefix
  600. ), f"Test data prefix ({suite.data_prefix}) not set correctly"
  601. for data_file in suite.files:
  602. yield DataFileCollector.from_parent(parent=self, name=data_file)
  603. class DataFileFix(NamedTuple):
  604. lineno: int # 1-offset, inclusive
  605. end_lineno: int # 1-offset, exclusive
  606. lines: list[str]
  607. class DataFileCollector(pytest.Collector):
  608. """Represents a single `.test` data driven test file.
  609. More context: https://github.com/python/mypy/issues/11662
  610. """
  611. parent: DataSuiteCollector
  612. _fixes: list[DataFileFix]
  613. @classmethod # We have to fight with pytest here:
  614. def from_parent(
  615. cls, parent: DataSuiteCollector, *, name: str # type: ignore[override]
  616. ) -> DataFileCollector:
  617. collector = super().from_parent(parent, name=name)
  618. assert isinstance(collector, DataFileCollector)
  619. return collector
  620. def collect(self) -> Iterator[DataDrivenTestCase]:
  621. yield from split_test_cases(
  622. parent=self,
  623. suite=self.parent.obj,
  624. file=os.path.join(self.parent.obj.data_prefix, self.name),
  625. )
  626. def setup(self) -> None:
  627. super().setup()
  628. self._fixes = []
  629. def teardown(self) -> None:
  630. super().teardown()
  631. self._apply_fixes()
  632. def enqueue_fix(self, fix: DataFileFix) -> None:
  633. self._fixes.append(fix)
  634. def _apply_fixes(self) -> None:
  635. if not self._fixes:
  636. return
  637. data_path = Path(self.parent.obj.data_prefix) / self.name
  638. lines = data_path.read_text().split("\n")
  639. # start from end to prevent line offsets from shifting as we update
  640. for fix in sorted(self._fixes, reverse=True):
  641. lines[fix.lineno - 1 : fix.end_lineno - 1] = fix.lines
  642. data_path.write_text("\n".join(lines))
  643. def add_test_name_suffix(name: str, suffix: str) -> str:
  644. # Find magic suffix of form "-foobar" (used for things like "-skip").
  645. m = re.search(r"-[-A-Za-z0-9]+$", name)
  646. if m:
  647. # Insert suite-specific test name suffix before the magic suffix
  648. # which must be the last thing in the test case name since we
  649. # are using endswith() checks.
  650. magic_suffix = m.group(0)
  651. return name[: -len(magic_suffix)] + suffix + magic_suffix
  652. else:
  653. return name + suffix
  654. def is_incremental(testcase: DataDrivenTestCase) -> bool:
  655. return "incremental" in testcase.name.lower() or "incremental" in testcase.file
  656. def has_stable_flags(testcase: DataDrivenTestCase) -> bool:
  657. if any(re.match(r"# flags[2-9]:", line) for line in testcase.input):
  658. return False
  659. for filename, contents in testcase.files:
  660. if os.path.basename(filename).startswith("mypy.ini."):
  661. return False
  662. return True
  663. class DataSuite:
  664. # option fields - class variables
  665. files: list[str]
  666. base_path = test_temp_dir
  667. # Allow external users of the test code to override the data prefix
  668. data_prefix = test_data_prefix
  669. required_out_section = False
  670. native_sep = False
  671. # Name suffix automatically added to each test case in the suite (can be
  672. # used to distinguish test cases in suites that share data files)
  673. test_name_suffix = ""
  674. def setup(self) -> None:
  675. """Setup fixtures (ad-hoc)"""
  676. @abstractmethod
  677. def run_case(self, testcase: DataDrivenTestCase) -> None:
  678. raise NotImplementedError