Debian Codegraph @

src/_pytest/cacheprovider.py

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