cacheprovider.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. """Implementation of the cache provider."""
  2. # This plugin was not named "cache" to avoid conflicts with the external
  3. # pytest-cache version.
  4. import dataclasses
  5. import json
  6. import os
  7. from pathlib import Path
  8. from typing import Dict
  9. from typing import Generator
  10. from typing import Iterable
  11. from typing import List
  12. from typing import Optional
  13. from typing import Set
  14. from typing import Union
  15. from .pathlib import resolve_from_str
  16. from .pathlib import rm_rf
  17. from .reports import CollectReport
  18. from _pytest import nodes
  19. from _pytest._io import TerminalWriter
  20. from _pytest.compat import final
  21. from _pytest.config import Config
  22. from _pytest.config import ExitCode
  23. from _pytest.config import hookimpl
  24. from _pytest.config.argparsing import Parser
  25. from _pytest.deprecated import check_ispytest
  26. from _pytest.fixtures import fixture
  27. from _pytest.fixtures import FixtureRequest
  28. from _pytest.main import Session
  29. from _pytest.nodes import File
  30. from _pytest.python import Package
  31. from _pytest.reports import TestReport
  32. README_CONTENT = """\
  33. # pytest cache directory #
  34. This directory contains data from the pytest's cache plugin,
  35. which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
  36. **Do not** commit this to version control.
  37. See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
  38. """
  39. CACHEDIR_TAG_CONTENT = b"""\
  40. Signature: 8a477f597d28d172789f06886806bc55
  41. # This file is a cache directory tag created by pytest.
  42. # For information about cache directory tags, see:
  43. # https://bford.info/cachedir/spec.html
  44. """
  45. @final
  46. @dataclasses.dataclass
  47. class Cache:
  48. """Instance of the `cache` fixture."""
  49. _cachedir: Path = dataclasses.field(repr=False)
  50. _config: Config = dataclasses.field(repr=False)
  51. # Sub-directory under cache-dir for directories created by `mkdir()`.
  52. _CACHE_PREFIX_DIRS = "d"
  53. # Sub-directory under cache-dir for values created by `set()`.
  54. _CACHE_PREFIX_VALUES = "v"
  55. def __init__(
  56. self, cachedir: Path, config: Config, *, _ispytest: bool = False
  57. ) -> None:
  58. check_ispytest(_ispytest)
  59. self._cachedir = cachedir
  60. self._config = config
  61. @classmethod
  62. def for_config(cls, config: Config, *, _ispytest: bool = False) -> "Cache":
  63. """Create the Cache instance for a Config.
  64. :meta private:
  65. """
  66. check_ispytest(_ispytest)
  67. cachedir = cls.cache_dir_from_config(config, _ispytest=True)
  68. if config.getoption("cacheclear") and cachedir.is_dir():
  69. cls.clear_cache(cachedir, _ispytest=True)
  70. return cls(cachedir, config, _ispytest=True)
  71. @classmethod
  72. def clear_cache(cls, cachedir: Path, _ispytest: bool = False) -> None:
  73. """Clear the sub-directories used to hold cached directories and values.
  74. :meta private:
  75. """
  76. check_ispytest(_ispytest)
  77. for prefix in (cls._CACHE_PREFIX_DIRS, cls._CACHE_PREFIX_VALUES):
  78. d = cachedir / prefix
  79. if d.is_dir():
  80. rm_rf(d)
  81. @staticmethod
  82. def cache_dir_from_config(config: Config, *, _ispytest: bool = False) -> Path:
  83. """Get the path to the cache directory for a Config.
  84. :meta private:
  85. """
  86. check_ispytest(_ispytest)
  87. return resolve_from_str(config.getini("cache_dir"), config.rootpath)
  88. def warn(self, fmt: str, *, _ispytest: bool = False, **args: object) -> None:
  89. """Issue a cache warning.
  90. :meta private:
  91. """
  92. check_ispytest(_ispytest)
  93. import warnings
  94. from _pytest.warning_types import PytestCacheWarning
  95. warnings.warn(
  96. PytestCacheWarning(fmt.format(**args) if args else fmt),
  97. self._config.hook,
  98. stacklevel=3,
  99. )
  100. def mkdir(self, name: str) -> Path:
  101. """Return a directory path object with the given name.
  102. If the directory does not yet exist, it will be created. You can use
  103. it to manage files to e.g. store/retrieve database dumps across test
  104. sessions.
  105. .. versionadded:: 7.0
  106. :param name:
  107. Must be a string not containing a ``/`` separator.
  108. Make sure the name contains your plugin or application
  109. identifiers to prevent clashes with other cache users.
  110. """
  111. path = Path(name)
  112. if len(path.parts) > 1:
  113. raise ValueError("name is not allowed to contain path separators")
  114. res = self._cachedir.joinpath(self._CACHE_PREFIX_DIRS, path)
  115. res.mkdir(exist_ok=True, parents=True)
  116. return res
  117. def _getvaluepath(self, key: str) -> Path:
  118. return self._cachedir.joinpath(self._CACHE_PREFIX_VALUES, Path(key))
  119. def get(self, key: str, default):
  120. """Return the cached value for the given key.
  121. If no value was yet cached or the value cannot be read, the specified
  122. default is returned.
  123. :param key:
  124. Must be a ``/`` separated value. Usually the first
  125. name is the name of your plugin or your application.
  126. :param default:
  127. The value to return in case of a cache-miss or invalid cache value.
  128. """
  129. path = self._getvaluepath(key)
  130. try:
  131. with path.open("r", encoding="UTF-8") as f:
  132. return json.load(f)
  133. except (ValueError, OSError):
  134. return default
  135. def set(self, key: str, value: object) -> None:
  136. """Save value for the given key.
  137. :param key:
  138. Must be a ``/`` separated value. Usually the first
  139. name is the name of your plugin or your application.
  140. :param value:
  141. Must be of any combination of basic python types,
  142. including nested types like lists of dictionaries.
  143. """
  144. path = self._getvaluepath(key)
  145. try:
  146. if path.parent.is_dir():
  147. cache_dir_exists_already = True
  148. else:
  149. cache_dir_exists_already = self._cachedir.exists()
  150. path.parent.mkdir(exist_ok=True, parents=True)
  151. except OSError as exc:
  152. self.warn(
  153. f"could not create cache path {path}: {exc}",
  154. _ispytest=True,
  155. )
  156. return
  157. if not cache_dir_exists_already:
  158. self._ensure_supporting_files()
  159. data = json.dumps(value, ensure_ascii=False, indent=2)
  160. try:
  161. f = path.open("w", encoding="UTF-8")
  162. except OSError as exc:
  163. self.warn(
  164. f"cache could not write path {path}: {exc}",
  165. _ispytest=True,
  166. )
  167. else:
  168. with f:
  169. f.write(data)
  170. def _ensure_supporting_files(self) -> None:
  171. """Create supporting files in the cache dir that are not really part of the cache."""
  172. readme_path = self._cachedir / "README.md"
  173. readme_path.write_text(README_CONTENT, encoding="UTF-8")
  174. gitignore_path = self._cachedir.joinpath(".gitignore")
  175. msg = "# Created by pytest automatically.\n*\n"
  176. gitignore_path.write_text(msg, encoding="UTF-8")
  177. cachedir_tag_path = self._cachedir.joinpath("CACHEDIR.TAG")
  178. cachedir_tag_path.write_bytes(CACHEDIR_TAG_CONTENT)
  179. class LFPluginCollWrapper:
  180. def __init__(self, lfplugin: "LFPlugin") -> None:
  181. self.lfplugin = lfplugin
  182. self._collected_at_least_one_failure = False
  183. @hookimpl(hookwrapper=True)
  184. def pytest_make_collect_report(self, collector: nodes.Collector):
  185. if isinstance(collector, (Session, Package)):
  186. out = yield
  187. res: CollectReport = out.get_result()
  188. # Sort any lf-paths to the beginning.
  189. lf_paths = self.lfplugin._last_failed_paths
  190. # Use stable sort to priorize last failed.
  191. def sort_key(node: Union[nodes.Item, nodes.Collector]) -> bool:
  192. # Package.path is the __init__.py file, we need the directory.
  193. if isinstance(node, Package):
  194. path = node.path.parent
  195. else:
  196. path = node.path
  197. return path in lf_paths
  198. res.result = sorted(
  199. res.result,
  200. key=sort_key,
  201. reverse=True,
  202. )
  203. return
  204. elif isinstance(collector, File):
  205. if collector.path in self.lfplugin._last_failed_paths:
  206. out = yield
  207. res = out.get_result()
  208. result = res.result
  209. lastfailed = self.lfplugin.lastfailed
  210. # Only filter with known failures.
  211. if not self._collected_at_least_one_failure:
  212. if not any(x.nodeid in lastfailed for x in result):
  213. return
  214. self.lfplugin.config.pluginmanager.register(
  215. LFPluginCollSkipfiles(self.lfplugin), "lfplugin-collskip"
  216. )
  217. self._collected_at_least_one_failure = True
  218. session = collector.session
  219. result[:] = [
  220. x
  221. for x in result
  222. if x.nodeid in lastfailed
  223. # Include any passed arguments (not trivial to filter).
  224. or session.isinitpath(x.path)
  225. # Keep all sub-collectors.
  226. or isinstance(x, nodes.Collector)
  227. ]
  228. return
  229. yield
  230. class LFPluginCollSkipfiles:
  231. def __init__(self, lfplugin: "LFPlugin") -> None:
  232. self.lfplugin = lfplugin
  233. @hookimpl
  234. def pytest_make_collect_report(
  235. self, collector: nodes.Collector
  236. ) -> Optional[CollectReport]:
  237. # Packages are Files, but we only want to skip test-bearing Files,
  238. # so don't filter Packages.
  239. if isinstance(collector, File) and not isinstance(collector, Package):
  240. if collector.path not in self.lfplugin._last_failed_paths:
  241. self.lfplugin._skipped_files += 1
  242. return CollectReport(
  243. collector.nodeid, "passed", longrepr=None, result=[]
  244. )
  245. return None
  246. class LFPlugin:
  247. """Plugin which implements the --lf (run last-failing) option."""
  248. def __init__(self, config: Config) -> None:
  249. self.config = config
  250. active_keys = "lf", "failedfirst"
  251. self.active = any(config.getoption(key) for key in active_keys)
  252. assert config.cache
  253. self.lastfailed: Dict[str, bool] = config.cache.get("cache/lastfailed", {})
  254. self._previously_failed_count: Optional[int] = None
  255. self._report_status: Optional[str] = None
  256. self._skipped_files = 0 # count skipped files during collection due to --lf
  257. if config.getoption("lf"):
  258. self._last_failed_paths = self.get_last_failed_paths()
  259. config.pluginmanager.register(
  260. LFPluginCollWrapper(self), "lfplugin-collwrapper"
  261. )
  262. def get_last_failed_paths(self) -> Set[Path]:
  263. """Return a set with all Paths of the previously failed nodeids and
  264. their parents."""
  265. rootpath = self.config.rootpath
  266. result = set()
  267. for nodeid in self.lastfailed:
  268. path = rootpath / nodeid.split("::")[0]
  269. result.add(path)
  270. result.update(path.parents)
  271. return {x for x in result if x.exists()}
  272. def pytest_report_collectionfinish(self) -> Optional[str]:
  273. if self.active and self.config.getoption("verbose") >= 0:
  274. return "run-last-failure: %s" % self._report_status
  275. return None
  276. def pytest_runtest_logreport(self, report: TestReport) -> None:
  277. if (report.when == "call" and report.passed) or report.skipped:
  278. self.lastfailed.pop(report.nodeid, None)
  279. elif report.failed:
  280. self.lastfailed[report.nodeid] = True
  281. def pytest_collectreport(self, report: CollectReport) -> None:
  282. passed = report.outcome in ("passed", "skipped")
  283. if passed:
  284. if report.nodeid in self.lastfailed:
  285. self.lastfailed.pop(report.nodeid)
  286. self.lastfailed.update((item.nodeid, True) for item in report.result)
  287. else:
  288. self.lastfailed[report.nodeid] = True
  289. @hookimpl(hookwrapper=True, tryfirst=True)
  290. def pytest_collection_modifyitems(
  291. self, config: Config, items: List[nodes.Item]
  292. ) -> Generator[None, None, None]:
  293. yield
  294. if not self.active:
  295. return
  296. if self.lastfailed:
  297. previously_failed = []
  298. previously_passed = []
  299. for item in items:
  300. if item.nodeid in self.lastfailed:
  301. previously_failed.append(item)
  302. else:
  303. previously_passed.append(item)
  304. self._previously_failed_count = len(previously_failed)
  305. if not previously_failed:
  306. # Running a subset of all tests with recorded failures
  307. # only outside of it.
  308. self._report_status = "%d known failures not in selected tests" % (
  309. len(self.lastfailed),
  310. )
  311. else:
  312. if self.config.getoption("lf"):
  313. items[:] = previously_failed
  314. config.hook.pytest_deselected(items=previously_passed)
  315. else: # --failedfirst
  316. items[:] = previously_failed + previously_passed
  317. noun = "failure" if self._previously_failed_count == 1 else "failures"
  318. suffix = " first" if self.config.getoption("failedfirst") else ""
  319. self._report_status = "rerun previous {count} {noun}{suffix}".format(
  320. count=self._previously_failed_count, suffix=suffix, noun=noun
  321. )
  322. if self._skipped_files > 0:
  323. files_noun = "file" if self._skipped_files == 1 else "files"
  324. self._report_status += " (skipped {files} {files_noun})".format(
  325. files=self._skipped_files, files_noun=files_noun
  326. )
  327. else:
  328. self._report_status = "no previously failed tests, "
  329. if self.config.getoption("last_failed_no_failures") == "none":
  330. self._report_status += "deselecting all items."
  331. config.hook.pytest_deselected(items=items[:])
  332. items[:] = []
  333. else:
  334. self._report_status += "not deselecting items."
  335. def pytest_sessionfinish(self, session: Session) -> None:
  336. config = self.config
  337. if config.getoption("cacheshow") or hasattr(config, "workerinput"):
  338. return
  339. assert config.cache is not None
  340. saved_lastfailed = config.cache.get("cache/lastfailed", {})
  341. if saved_lastfailed != self.lastfailed:
  342. config.cache.set("cache/lastfailed", self.lastfailed)
  343. class NFPlugin:
  344. """Plugin which implements the --nf (run new-first) option."""
  345. def __init__(self, config: Config) -> None:
  346. self.config = config
  347. self.active = config.option.newfirst
  348. assert config.cache is not None
  349. self.cached_nodeids = set(config.cache.get("cache/nodeids", []))
  350. @hookimpl(hookwrapper=True, tryfirst=True)
  351. def pytest_collection_modifyitems(
  352. self, items: List[nodes.Item]
  353. ) -> Generator[None, None, None]:
  354. yield
  355. if self.active:
  356. new_items: Dict[str, nodes.Item] = {}
  357. other_items: Dict[str, nodes.Item] = {}
  358. for item in items:
  359. if item.nodeid not in self.cached_nodeids:
  360. new_items[item.nodeid] = item
  361. else:
  362. other_items[item.nodeid] = item
  363. items[:] = self._get_increasing_order(
  364. new_items.values()
  365. ) + self._get_increasing_order(other_items.values())
  366. self.cached_nodeids.update(new_items)
  367. else:
  368. self.cached_nodeids.update(item.nodeid for item in items)
  369. def _get_increasing_order(self, items: Iterable[nodes.Item]) -> List[nodes.Item]:
  370. return sorted(items, key=lambda item: item.path.stat().st_mtime, reverse=True) # type: ignore[no-any-return]
  371. def pytest_sessionfinish(self) -> None:
  372. config = self.config
  373. if config.getoption("cacheshow") or hasattr(config, "workerinput"):
  374. return
  375. if config.getoption("collectonly"):
  376. return
  377. assert config.cache is not None
  378. config.cache.set("cache/nodeids", sorted(self.cached_nodeids))
  379. def pytest_addoption(parser: Parser) -> None:
  380. group = parser.getgroup("general")
  381. group.addoption(
  382. "--lf",
  383. "--last-failed",
  384. action="store_true",
  385. dest="lf",
  386. help="Rerun only the tests that failed "
  387. "at the last run (or all if none failed)",
  388. )
  389. group.addoption(
  390. "--ff",
  391. "--failed-first",
  392. action="store_true",
  393. dest="failedfirst",
  394. help="Run all tests, but run the last failures first. "
  395. "This may re-order tests and thus lead to "
  396. "repeated fixture setup/teardown.",
  397. )
  398. group.addoption(
  399. "--nf",
  400. "--new-first",
  401. action="store_true",
  402. dest="newfirst",
  403. help="Run tests from new files first, then the rest of the tests "
  404. "sorted by file mtime",
  405. )
  406. group.addoption(
  407. "--cache-show",
  408. action="append",
  409. nargs="?",
  410. dest="cacheshow",
  411. help=(
  412. "Show cache contents, don't perform collection or tests. "
  413. "Optional argument: glob (default: '*')."
  414. ),
  415. )
  416. group.addoption(
  417. "--cache-clear",
  418. action="store_true",
  419. dest="cacheclear",
  420. help="Remove all cache contents at start of test run",
  421. )
  422. cache_dir_default = ".pytest_cache"
  423. if "TOX_ENV_DIR" in os.environ:
  424. cache_dir_default = os.path.join(os.environ["TOX_ENV_DIR"], cache_dir_default)
  425. parser.addini("cache_dir", default=cache_dir_default, help="Cache directory path")
  426. group.addoption(
  427. "--lfnf",
  428. "--last-failed-no-failures",
  429. action="store",
  430. dest="last_failed_no_failures",
  431. choices=("all", "none"),
  432. default="all",
  433. help="With ``--lf``, determines whether to execute tests when there "
  434. "are no previously (known) failures or when no "
  435. "cached ``lastfailed`` data was found. "
  436. "``all`` (the default) runs the full test suite again. "
  437. "``none`` just emits a message about no known failures and exits successfully.",
  438. )
  439. def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
  440. if config.option.cacheshow and not config.option.help:
  441. from _pytest.main import wrap_session
  442. return wrap_session(config, cacheshow)
  443. return None
  444. @hookimpl(tryfirst=True)
  445. def pytest_configure(config: Config) -> None:
  446. config.cache = Cache.for_config(config, _ispytest=True)
  447. config.pluginmanager.register(LFPlugin(config), "lfplugin")
  448. config.pluginmanager.register(NFPlugin(config), "nfplugin")
  449. @fixture
  450. def cache(request: FixtureRequest) -> Cache:
  451. """Return a cache object that can persist state between testing sessions.
  452. cache.get(key, default)
  453. cache.set(key, value)
  454. Keys must be ``/`` separated strings, where the first part is usually the
  455. name of your plugin or application to avoid clashes with other cache users.
  456. Values can be any object handled by the json stdlib module.
  457. """
  458. assert request.config.cache is not None
  459. return request.config.cache
  460. def pytest_report_header(config: Config) -> Optional[str]:
  461. """Display cachedir with --cache-show and if non-default."""
  462. if config.option.verbose > 0 or config.getini("cache_dir") != ".pytest_cache":
  463. assert config.cache is not None
  464. cachedir = config.cache._cachedir
  465. # TODO: evaluate generating upward relative paths
  466. # starting with .., ../.. if sensible
  467. try:
  468. displaypath = cachedir.relative_to(config.rootpath)
  469. except ValueError:
  470. displaypath = cachedir
  471. return f"cachedir: {displaypath}"
  472. return None
  473. def cacheshow(config: Config, session: Session) -> int:
  474. from pprint import pformat
  475. assert config.cache is not None
  476. tw = TerminalWriter()
  477. tw.line("cachedir: " + str(config.cache._cachedir))
  478. if not config.cache._cachedir.is_dir():
  479. tw.line("cache is empty")
  480. return 0
  481. glob = config.option.cacheshow[0]
  482. if glob is None:
  483. glob = "*"
  484. dummy = object()
  485. basedir = config.cache._cachedir
  486. vdir = basedir / Cache._CACHE_PREFIX_VALUES
  487. tw.sep("-", "cache values for %r" % glob)
  488. for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):
  489. key = str(valpath.relative_to(vdir))
  490. val = config.cache.get(key, dummy)
  491. if val is dummy:
  492. tw.line("%s contains unreadable content, will be ignored" % key)
  493. else:
  494. tw.line("%s contains:" % key)
  495. for line in pformat(val).splitlines():
  496. tw.line(" " + line)
  497. ddir = basedir / Cache._CACHE_PREFIX_DIRS
  498. if ddir.is_dir():
  499. contents = sorted(ddir.rglob(glob))
  500. tw.sep("-", "cache directories for %r" % glob)
  501. for p in contents:
  502. # if p.is_dir():
  503. # print("%s/" % p.relative_to(basedir))
  504. if p.is_file():
  505. key = str(p.relative_to(basedir))
  506. tw.line(f"{key} is a file of length {p.stat().st_size:d}")
  507. return 0