Debian Codegraph @

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