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.

576 lines
20KB

  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. import py
  16. from .pathlib import resolve_from_str
  17. from .pathlib import rm_rf
  18. from .reports import CollectReport
  19. from _pytest import nodes
  20. from _pytest._io import TerminalWriter
  21. from _pytest.compat import final
  22. from _pytest.config import Config
  23. from _pytest.config import ExitCode
  24. from _pytest.config import hookimpl
  25. from _pytest.config.argparsing import Parser
  26. from _pytest.deprecated import check_ispytest
  27. from _pytest.fixtures import fixture
  28. from _pytest.fixtures import FixtureRequest
  29. from _pytest.main import Session
  30. from _pytest.python import Module
  31. from _pytest.python import Package
  32. from _pytest.reports import TestReport
  33. README_CONTENT = """\
  34. # pytest cache directory #
  35. This directory contains data from the pytest's cache plugin,
  36. which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
  37. **Do not** commit this to version control.
  38. See [the docs](https://docs.pytest.org/en/stable/cache.html) for more information.
  39. """
  40. CACHEDIR_TAG_CONTENT = b"""\
  41. Signature: 8a477f597d28d172789f06886806bc55
  42. # This file is a cache directory tag created by pytest.
  43. # For information about cache directory tags, see:
  44. # http://www.bford.info/cachedir/spec.html
  45. """
  46. @final
  47. @attr.s(init=False)
  48. class Cache:
  49. _cachedir = attr.ib(type=Path, repr=False)
  50. _config = attr.ib(type=Config, repr=False)
  51. # sub-directory under cache-dir for directories created by "makedir"
  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 makedir(self, name: str) -> py.path.local:
  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. :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 py.path.local(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, sort_keys=True)
  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, key=lambda x: 0 if Path(str(x.fspath)) in lf_paths else 1,
  185. )
  186. return
  187. elif isinstance(collector, Module):
  188. if Path(str(collector.fspath)) in self.lfplugin._last_failed_paths:
  189. out = yield
  190. res = out.get_result()
  191. result = res.result
  192. lastfailed = self.lfplugin.lastfailed
  193. # Only filter with known failures.
  194. if not self._collected_at_least_one_failure:
  195. if not any(x.nodeid in lastfailed for x in result):
  196. return
  197. self.lfplugin.config.pluginmanager.register(
  198. LFPluginCollSkipfiles(self.lfplugin), "lfplugin-collskip"
  199. )
  200. self._collected_at_least_one_failure = True
  201. session = collector.session
  202. result[:] = [
  203. x
  204. for x in result
  205. if x.nodeid in lastfailed
  206. # Include any passed arguments (not trivial to filter).
  207. or session.isinitpath(x.fspath)
  208. # Keep all sub-collectors.
  209. or isinstance(x, nodes.Collector)
  210. ]
  211. return
  212. yield
  213. class LFPluginCollSkipfiles:
  214. def __init__(self, lfplugin: "LFPlugin") -> None:
  215. self.lfplugin = lfplugin
  216. @hookimpl
  217. def pytest_make_collect_report(
  218. self, collector: nodes.Collector
  219. ) -> Optional[CollectReport]:
  220. # Packages are Modules, but _last_failed_paths only contains
  221. # test-bearing paths and doesn't try to include the paths of their
  222. # packages, so don't filter them.
  223. if isinstance(collector, Module) and not isinstance(collector, Package):
  224. if Path(str(collector.fspath)) not in self.lfplugin._last_failed_paths:
  225. self.lfplugin._skipped_files += 1
  226. return CollectReport(
  227. collector.nodeid, "passed", longrepr=None, result=[]
  228. )
  229. return None
  230. class LFPlugin:
  231. """Plugin which implements the --lf (run last-failing) option."""
  232. def __init__(self, config: Config) -> None:
  233. self.config = config
  234. active_keys = "lf", "failedfirst"
  235. self.active = any(config.getoption(key) for key in active_keys)
  236. assert config.cache
  237. self.lastfailed: Dict[str, bool] = config.cache.get("cache/lastfailed", {})
  238. self._previously_failed_count: Optional[int] = None
  239. self._report_status: Optional[str] = None
  240. self._skipped_files = 0 # count skipped files during collection due to --lf
  241. if config.getoption("lf"):
  242. self._last_failed_paths = self.get_last_failed_paths()
  243. config.pluginmanager.register(
  244. LFPluginCollWrapper(self), "lfplugin-collwrapper"
  245. )
  246. def get_last_failed_paths(self) -> Set[Path]:
  247. """Return a set with all Paths()s of the previously failed nodeids."""
  248. rootpath = self.config.rootpath
  249. result = {rootpath / nodeid.split("::")[0] for nodeid in self.lastfailed}
  250. return {x for x in result if x.exists()}
  251. def pytest_report_collectionfinish(self) -> Optional[str]:
  252. if self.active and self.config.getoption("verbose") >= 0:
  253. return "run-last-failure: %s" % self._report_status
  254. return None
  255. def pytest_runtest_logreport(self, report: TestReport) -> None:
  256. if (report.when == "call" and report.passed) or report.skipped:
  257. self.lastfailed.pop(report.nodeid, None)
  258. elif report.failed:
  259. self.lastfailed[report.nodeid] = True
  260. def pytest_collectreport(self, report: CollectReport) -> None:
  261. passed = report.outcome in ("passed", "skipped")
  262. if passed:
  263. if report.nodeid in self.lastfailed:
  264. self.lastfailed.pop(report.nodeid)
  265. self.lastfailed.update((item.nodeid, True) for item in report.result)
  266. else:
  267. self.lastfailed[report.nodeid] = True
  268. @hookimpl(hookwrapper=True, tryfirst=True)
  269. def pytest_collection_modifyitems(
  270. self, config: Config, items: List[nodes.Item]
  271. ) -> Generator[None, None, None]:
  272. yield
  273. if not self.active:
  274. return
  275. if self.lastfailed:
  276. previously_failed = []
  277. previously_passed = []
  278. for item in items:
  279. if item.nodeid in self.lastfailed:
  280. previously_failed.append(item)
  281. else:
  282. previously_passed.append(item)
  283. self._previously_failed_count = len(previously_failed)
  284. if not previously_failed:
  285. # Running a subset of all tests with recorded failures
  286. # only outside of it.
  287. self._report_status = "%d known failures not in selected tests" % (
  288. len(self.lastfailed),
  289. )
  290. else:
  291. if self.config.getoption("lf"):
  292. items[:] = previously_failed
  293. config.hook.pytest_deselected(items=previously_passed)
  294. else: # --failedfirst
  295. items[:] = previously_failed + previously_passed
  296. noun = "failure" if self._previously_failed_count == 1 else "failures"
  297. suffix = " first" if self.config.getoption("failedfirst") else ""
  298. self._report_status = "rerun previous {count} {noun}{suffix}".format(
  299. count=self._previously_failed_count, suffix=suffix, noun=noun
  300. )
  301. if self._skipped_files > 0:
  302. files_noun = "file" if self._skipped_files == 1 else "files"
  303. self._report_status += " (skipped {files} {files_noun})".format(
  304. files=self._skipped_files, files_noun=files_noun
  305. )
  306. else:
  307. self._report_status = "no previously failed tests, "
  308. if self.config.getoption("last_failed_no_failures") == "none":
  309. self._report_status += "deselecting all items."
  310. config.hook.pytest_deselected(items=items[:])
  311. items[:] = []
  312. else:
  313. self._report_status += "not deselecting items."
  314. def pytest_sessionfinish(self, session: Session) -> None:
  315. config = self.config
  316. if config.getoption("cacheshow") or hasattr(config, "workerinput"):
  317. return
  318. assert config.cache is not None
  319. saved_lastfailed = config.cache.get("cache/lastfailed", {})
  320. if saved_lastfailed != self.lastfailed:
  321. config.cache.set("cache/lastfailed", self.lastfailed)
  322. class NFPlugin:
  323. """Plugin which implements the --nf (run new-first) option."""
  324. def __init__(self, config: Config) -> None:
  325. self.config = config
  326. self.active = config.option.newfirst
  327. assert config.cache is not None
  328. self.cached_nodeids = set(config.cache.get("cache/nodeids", []))
  329. @hookimpl(hookwrapper=True, tryfirst=True)
  330. def pytest_collection_modifyitems(
  331. self, items: List[nodes.Item]
  332. ) -> Generator[None, None, None]:
  333. yield
  334. if self.active:
  335. new_items: Dict[str, nodes.Item] = {}
  336. other_items: Dict[str, nodes.Item] = {}
  337. for item in items:
  338. if item.nodeid not in self.cached_nodeids:
  339. new_items[item.nodeid] = item
  340. else:
  341. other_items[item.nodeid] = item
  342. items[:] = self._get_increasing_order(
  343. new_items.values()
  344. ) + self._get_increasing_order(other_items.values())
  345. self.cached_nodeids.update(new_items)
  346. else:
  347. self.cached_nodeids.update(item.nodeid for item in items)
  348. def _get_increasing_order(self, items: Iterable[nodes.Item]) -> List[nodes.Item]:
  349. return sorted(items, key=lambda item: item.fspath.mtime(), reverse=True) # type: ignore[no-any-return]
  350. def pytest_sessionfinish(self) -> None:
  351. config = self.config
  352. if config.getoption("cacheshow") or hasattr(config, "workerinput"):
  353. return
  354. if config.getoption("collectonly"):
  355. return
  356. assert config.cache is not None
  357. config.cache.set("cache/nodeids", sorted(self.cached_nodeids))
  358. def pytest_addoption(parser: Parser) -> None:
  359. group = parser.getgroup("general")
  360. group.addoption(
  361. "--lf",
  362. "--last-failed",
  363. action="store_true",
  364. dest="lf",
  365. help="rerun only the tests that failed "
  366. "at the last run (or all if none failed)",
  367. )
  368. group.addoption(
  369. "--ff",
  370. "--failed-first",
  371. action="store_true",
  372. dest="failedfirst",
  373. help="run all tests, but run the last failures first.\n"
  374. "This may re-order tests and thus lead to "
  375. "repeated fixture setup/teardown.",
  376. )
  377. group.addoption(
  378. "--nf",
  379. "--new-first",
  380. action="store_true",
  381. dest="newfirst",
  382. help="run tests from new files first, then the rest of the tests "
  383. "sorted by file mtime",
  384. )
  385. group.addoption(
  386. "--cache-show",
  387. action="append",
  388. nargs="?",
  389. dest="cacheshow",
  390. help=(
  391. "show cache contents, don't perform collection or tests. "
  392. "Optional argument: glob (default: '*')."
  393. ),
  394. )
  395. group.addoption(
  396. "--cache-clear",
  397. action="store_true",
  398. dest="cacheclear",
  399. help="remove all cache contents at start of test run.",
  400. )
  401. cache_dir_default = ".pytest_cache"
  402. if "TOX_ENV_DIR" in os.environ:
  403. cache_dir_default = os.path.join(os.environ["TOX_ENV_DIR"], cache_dir_default)
  404. parser.addini("cache_dir", default=cache_dir_default, help="cache directory path.")
  405. group.addoption(
  406. "--lfnf",
  407. "--last-failed-no-failures",
  408. action="store",
  409. dest="last_failed_no_failures",
  410. choices=("all", "none"),
  411. default="all",
  412. help="which tests to run with no previously (known) failures.",
  413. )
  414. def pytest_cmdline_main(config: Config) -> Optional[Union[int, ExitCode]]:
  415. if config.option.cacheshow:
  416. from _pytest.main import wrap_session
  417. return wrap_session(config, cacheshow)
  418. return None
  419. @hookimpl(tryfirst=True)
  420. def pytest_configure(config: Config) -> None:
  421. config.cache = Cache.for_config(config, _ispytest=True)
  422. config.pluginmanager.register(LFPlugin(config), "lfplugin")
  423. config.pluginmanager.register(NFPlugin(config), "nfplugin")
  424. @fixture
  425. def cache(request: FixtureRequest) -> Cache:
  426. """Return a cache object that can persist state between testing sessions.
  427. cache.get(key, default)
  428. cache.set(key, value)
  429. Keys must be ``/`` separated strings, where the first part is usually the
  430. name of your plugin or application to avoid clashes with other cache users.
  431. Values can be any object handled by the json stdlib module.
  432. """
  433. assert request.config.cache is not None
  434. return request.config.cache
  435. def pytest_report_header(config: Config) -> Optional[str]:
  436. """Display cachedir with --cache-show and if non-default."""
  437. if config.option.verbose > 0 or config.getini("cache_dir") != ".pytest_cache":
  438. assert config.cache is not None
  439. cachedir = config.cache._cachedir
  440. # TODO: evaluate generating upward relative paths
  441. # starting with .., ../.. if sensible
  442. try:
  443. displaypath = cachedir.relative_to(config.rootpath)
  444. except ValueError:
  445. displaypath = cachedir
  446. return f"cachedir: {displaypath}"
  447. return None
  448. def cacheshow(config: Config, session: Session) -> int:
  449. from pprint import pformat
  450. assert config.cache is not None
  451. tw = TerminalWriter()
  452. tw.line("cachedir: " + str(config.cache._cachedir))
  453. if not config.cache._cachedir.is_dir():
  454. tw.line("cache is empty")
  455. return 0
  456. glob = config.option.cacheshow[0]
  457. if glob is None:
  458. glob = "*"
  459. dummy = object()
  460. basedir = config.cache._cachedir
  461. vdir = basedir / Cache._CACHE_PREFIX_VALUES
  462. tw.sep("-", "cache values for %r" % glob)
  463. for valpath in sorted(x for x in vdir.rglob(glob) if x.is_file()):
  464. key = str(valpath.relative_to(vdir))
  465. val = config.cache.get(key, dummy)
  466. if val is dummy:
  467. tw.line("%s contains unreadable content, will be ignored" % key)
  468. else:
  469. tw.line("%s contains:" % key)
  470. for line in pformat(val).splitlines():
  471. tw.line(" " + line)
  472. ddir = basedir / Cache._CACHE_PREFIX_DIRS
  473. if ddir.is_dir():
  474. contents = sorted(ddir.rglob(glob))
  475. tw.sep("-", "cache directories for %r" % glob)
  476. for p in contents:
  477. # if p.check(dir=1):
  478. # print("%s/" % p.relto(basedir))
  479. if p.is_file():
  480. key = str(p.relative_to(basedir))
  481. tw.line(f"{key} is a file of length {p.stat().st_size:d}")
  482. return 0