Debian Codegraph @

src/_pytest/stepwise.py

raw
1 from __future__ import annotations
2
3 import dataclasses
4 from datetime import datetime
5 from datetime import timedelta
6 from typing import Any
7 from typing import TYPE_CHECKING
8
9 from _pytest import nodes
10 from _pytest.cacheprovider import Cache
11 from _pytest.config import Config
12 from _pytest.config.argparsing import Parser
13 from _pytest.main import Session
14 from _pytest.reports import TestReport
15
16
17 if TYPE_CHECKING:
18 from typing_extensions import Self
19
20 STEPWISE_CACHE_DIR = "cache/stepwise"
21
22
23 def pytest_addoption(parser: Parser) -> None:
24 group = parser.getgroup("general")
25 group.addoption(
26 "--sw",
27 "--stepwise",
28 action="store_true",
29 default=False,
30 dest="stepwise",
31 help="Exit on test failure and continue from last failing test next time",
32 )
33 group.addoption(
34 "--sw-skip",
35 "--stepwise-skip",
36 action="store_true",
37 default=False,
38 dest="stepwise_skip",
39 help="Ignore the first failing test but stop on the next failing test. "
40 "Implicitly enables --stepwise.",
41 )
42 group.addoption(
43 "--sw-reset",
44 "--stepwise-reset",
45 action="store_true",
46 default=False,
47 dest="stepwise_reset",
48 help="Resets stepwise state, restarting the stepwise workflow. "
49 "Implicitly enables --stepwise.",
50 )
51
52
53 def pytest_configure(config: Config) -> None:
54 # --stepwise-skip/--stepwise-reset implies stepwise.
55 if config.option.stepwise_skip or config.option.stepwise_reset:
56 config.option.stepwise = True
57 if config.getoption("stepwise"):
58 config.pluginmanager.register(StepwisePlugin(config), "stepwiseplugin")
59
60
61 def pytest_sessionfinish(session: Session) -> None:
62 if not session.config.getoption("stepwise"):
63 assert session.config.cache is not None
64 if hasattr(session.config, "workerinput"):
65 # Do not update cache if this process is a xdist worker to prevent
66 # race conditions (#10641).
67 return
68
69
70 @dataclasses.dataclass
71 class StepwiseCacheInfo:
72 # The nodeid of the last failed test.
73 last_failed: str | None
74
75 # The number of tests in the last time --stepwise was run.
76 # We use this information as a simple way to invalidate the cache information, avoiding
77 # confusing behavior in case the cache is stale.
78 last_test_count: int | None
79
80 # The date when the cache was last updated, for information purposes only.
81 last_cache_date_str: str
82
83 @property
84 def last_cache_date(self) -> datetime:
85 return datetime.fromisoformat(self.last_cache_date_str)
86
87 @classmethod
88 def empty(cls) -> Self:
89 return cls(
90 last_failed=None,
91 last_test_count=None,
92 last_cache_date_str=datetime.now().isoformat(),
93 )
94
95 def update_date_to_now(self) -> None:
96 self.last_cache_date_str = datetime.now().isoformat()
97
98
99 class StepwisePlugin:
100 def __init__(self, config: Config) -> None:
101 self.config = config
102 self.session: Session | None = None
103 self.report_status: list[str] = []
104 assert config.cache is not None
105 self.cache: Cache = config.cache
106 self.skip: bool = config.getoption("stepwise_skip")
107 self.reset: bool = config.getoption("stepwise_reset")
108 self.cached_info = self._load_cached_info()
109
110 def _load_cached_info(self) -> StepwiseCacheInfo:
111 cached_dict: dict[str, Any] | None = self.cache.get(STEPWISE_CACHE_DIR, None)
112 if cached_dict:
113 try:
114 return StepwiseCacheInfo(
115 cached_dict["last_failed"],
116 cached_dict["last_test_count"],
117 cached_dict["last_cache_date_str"],
118 )
119 except (KeyError, TypeError) as e:
120 error = f"{type(e).__name__}: {e}"
121 self.report_status.append(f"error reading cache, discarding ({error})")
122
123 # Cache not found or error during load, return a new cache.
124 return StepwiseCacheInfo.empty()
125
126 def pytest_sessionstart(self, session: Session) -> None:
127 self.session = session
128
129 def pytest_collection_modifyitems(
130 self, config: Config, items: list[nodes.Item]
131 ) -> None:
132 last_test_count = self.cached_info.last_test_count
133 self.cached_info.last_test_count = len(items)
134
135 if self.reset:
136 self.report_status.append("resetting state, not skipping.")
137 self.cached_info.last_failed = None
138 return
139
140 if not self.cached_info.last_failed:
141 self.report_status.append("no previously failed tests, not skipping.")
142 return
143
144 if last_test_count is not None and last_test_count != len(items):
145 self.report_status.append(
146 f"test count changed, not skipping (now {len(items)} tests, previously {last_test_count})."
147 )
148 self.cached_info.last_failed = None
149 return
150
151 # Check all item nodes until we find a match on last failed.
152 failed_index = None
153 for index, item in enumerate(items):
154 if item.nodeid == self.cached_info.last_failed:
155 failed_index = index
156 break
157
158 # If the previously failed test was not found among the test items,
159 # do not skip any tests.
160 if failed_index is None:
161 self.report_status.append("previously failed test not found, not skipping.")
162 else:
163 cache_age = datetime.now() - self.cached_info.last_cache_date
164 # Round up to avoid showing microseconds.
165 cache_age = timedelta(seconds=int(cache_age.total_seconds()))
166 self.report_status.append(
167 f"skipping {failed_index} already passed items (cache from {cache_age} ago,"
168 f" use --sw-reset to discard)."
169 )
170 deselected = items[:failed_index]
171 del items[:failed_index]
172 config.hook.pytest_deselected(items=deselected)
173
174 def pytest_runtest_logreport(self, report: TestReport) -> None:
175 if report.failed:
176 if self.skip:
177 # Remove test from the failed ones (if it exists) and unset the skip option
178 # to make sure the following tests will not be skipped.
179 if report.nodeid == self.cached_info.last_failed:
180 self.cached_info.last_failed = None
181
182 self.skip = False
183 else:
184 # Mark test as the last failing and interrupt the test session.
185 self.cached_info.last_failed = report.nodeid
186 assert self.session is not None
187 self.session.shouldstop = (
188 "Test failed, continuing from this test next run."
189 )
190
191 else:
192 # If the test was actually run and did pass.
193 if report.when == "call":
194 # Remove test from the failed ones, if exists.
195 if report.nodeid == self.cached_info.last_failed:
196 self.cached_info.last_failed = None
197
198 def pytest_report_collectionfinish(self) -> list[str] | None:
199 if self.config.get_verbosity() >= 0 and self.report_status:
200 return [f"stepwise: {x}" for x in self.report_status]
201 return None
202
203 def pytest_sessionfinish(self) -> None:
204 if hasattr(self.config, "workerinput"):
205 # Do not update cache if this process is a xdist worker to prevent
206 # race conditions (#10641).
207 return
208 self.cached_info.update_date_to_now()
209 self.cache.set(STEPWISE_CACHE_DIR, dataclasses.asdict(self.cached_info))