cacheprovider.py 20 KB

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