Debian Codegraph @

src/syrupy/session.py

raw
1 import os
2 from collections import defaultdict
3 from collections.abc import Iterable
4 from dataclasses import (
5 dataclass,
6 field,
7 )
8 from enum import Enum
9 from pathlib import Path
10 from typing import (
11 TYPE_CHECKING,
12 Any,
13 Literal,
14 Optional,
15 )
16
17 import pytest
18
19 from .constants import EXIT_STATUS_FAIL_UNUSED
20 from .data import SnapshotCollections
21 from .exceptions import FailedToLoadModuleMember
22 from .location import PyTestLocation
23 from .report import SnapshotReport
24 from .types import (
25 SerializedData,
26 SnapshotIndex,
27 )
28 from .utils import (
29 import_module_member,
30 is_xdist_worker,
31 )
32
33 # Snapshot collections on the report that are merged across pytest-xdist workers.
34 _MERGED_COLLECTIONS = ("discovered", "created", "failed", "matched", "updated", "used")
35
36
37 class _ReconstructedObject:
38 """Stand-in for ``item.obj`` rebuilt from a worker's serialized item."""
39
40 def __init__(self, modulename: str, methodname: str) -> None:
41 self.__module__ = modulename
42 self.__name__ = methodname
43
44
45 class _ReconstructedItem:
46 """
47 Stand-in for a ``pytest.Item`` rebuilt on the controller from a worker.
48
49 The controller never collects items itself, so to reuse the regular unused
50 snapshot detection we recreate just enough of the pytest item for
51 ``PyTestLocation`` to resolve snapshot names and locations.
52 """
53
54 def __init__(self, data: dict[str, str]) -> None:
55 self.nodeid = data["nodeid"]
56 self.name = data["name"]
57 self.path = Path(data["path"])
58 self.obj = _ReconstructedObject(data["modulename"], data["methodname"])
59
60
61 if TYPE_CHECKING:
62 from .assertion import SnapshotAssertion
63 from .extensions.base import AbstractSyrupyExtension
64
65
66 class ItemStatus(Enum):
67 NOT_RUN = False
68 PASSED = "passed"
69 FAILED = "failed"
70 SKIPPED = "skipped"
71
72
73 _QueuedWriteExtensionKey = tuple[type["AbstractSyrupyExtension"], str]
74 _QueuedWriteTestLocationKey = tuple["PyTestLocation", "SnapshotIndex"]
75
76
77 @dataclass
78 class SnapshotSession:
79 pytest_session: "pytest.Session"
80
81 # List of file extensions to ignore during discovery/processing
82 ignore_file_extensions: list[str] | None = None
83
84 # Snapshot report generated on finish
85 report: Optional["SnapshotReport"] = None
86 # All the collected test items
87 _collected_items: set["pytest.Item"] = field(default_factory=set)
88 # All the selected test items. Will be set to False until the test item is run.
89 _selected_items: dict[str, ItemStatus] = field(default_factory=dict)
90 _assertions: list["SnapshotAssertion"] = field(default_factory=list)
91 _extensions: dict[str, "AbstractSyrupyExtension"] = field(default_factory=dict)
92 # Reports published by pytest-xdist workers, collected on the controller.
93 _worker_reports: list[dict[str, Any]] = field(default_factory=list)
94
95 _locations_discovered: defaultdict[str, set[Any]] = field(
96 default_factory=lambda: defaultdict(set)
97 )
98
99 # For performance, we buffer snapshot writes in memory before flushing them to disk. In
100 # particular, we want to be able to write to a file on disk only once, rather than having to
101 # repeatedly rewrite it.
102 #
103 # That batching leads to using two layers of dicts here: the outer layer represents the
104 # extension/file-location pair that will be written, and the inner layer represents the
105 # snapshots within that, "indexed" to allow efficient recall.
106 _queued_snapshot_writes: defaultdict[
107 _QueuedWriteExtensionKey,
108 dict[_QueuedWriteTestLocationKey, "SerializedData"],
109 ] = field(default_factory=lambda: defaultdict(dict))
110
111 def _snapshot_write_queue_keys(
112 self,
113 extension: "AbstractSyrupyExtension",
114 test_location: "PyTestLocation",
115 index: "SnapshotIndex",
116 ) -> tuple[_QueuedWriteExtensionKey, _QueuedWriteTestLocationKey]:
117 snapshot_location = extension.get_location(
118 test_location=test_location, index=index
119 )
120 return (extension.__class__, snapshot_location), (test_location, index)
121
122 def queue_snapshot_write(
123 self,
124 extension: "AbstractSyrupyExtension",
125 test_location: "PyTestLocation",
126 data: "SerializedData",
127 index: "SnapshotIndex",
128 ) -> None:
129 ext_key, loc_key = self._snapshot_write_queue_keys(
130 extension, test_location, index
131 )
132 self._queued_snapshot_writes[ext_key][loc_key] = data
133
134 def flush_snapshot_write_queue(self) -> None:
135 for (
136 extension_class,
137 snapshot_location,
138 ), queued_write in self._queued_snapshot_writes.items():
139 if queued_write:
140 extension_class.write_snapshot(
141 snapshot_location=snapshot_location,
142 snapshots=[
143 (data, loc, index)
144 for (loc, index), data in queued_write.items()
145 ],
146 )
147 self._queued_snapshot_writes.clear()
148
149 def recall_snapshot(
150 self,
151 extension: "AbstractSyrupyExtension",
152 test_location: "PyTestLocation",
153 index: "SnapshotIndex",
154 ) -> Optional["SerializedData"]:
155 """Find the current value of the snapshot, for this session, either a pending write or the actual snapshot."""
156
157 ext_key, loc_key = self._snapshot_write_queue_keys(
158 extension, test_location, index
159 )
160 data = self._queued_snapshot_writes[ext_key].get(loc_key)
161 if data is not None:
162 return data
163
164 # No matching write queued, so just read the snapshot directly:
165 return extension.read_snapshot(
166 test_location=test_location, index=index, session_id=str(id(self))
167 )
168
169 @property
170 def update_snapshots(self) -> bool:
171 return bool(self.pytest_session.config.option.update_snapshots)
172
173 @property
174 def warn_unused_snapshots(self) -> bool:
175 return bool(self.pytest_session.config.option.warn_unused_snapshots)
176
177 def collect_items(self, items: list["pytest.Item"]) -> None:
178 self._collected_items.update(self.filter_valid_items(items))
179
180 def select_items(self, items: list["pytest.Item"]) -> None:
181 for item in self.filter_valid_items(items):
182 self._selected_items[getattr(item, "nodeid")] = ( # noqa: B009
183 ItemStatus.NOT_RUN
184 )
185
186 def start(self) -> None:
187 self.report = None
188 self._collected_items = set()
189 self._selected_items = {}
190 self._assertions = []
191 self._extensions = {}
192 self._locations_discovered = defaultdict(set)
193
194 def ran_item(
195 self, nodeid: str, outcome: Literal["passed", "skipped", "failed"]
196 ) -> None:
197 if nodeid in self._selected_items:
198 try:
199 self._selected_items[nodeid] = ItemStatus(outcome)
200 except ValueError:
201 pass # if we don't understand the outcome, leave the item as "not run"
202
203 @staticmethod
204 def _serialize_item(item: "pytest.Item") -> dict[str, str]:
205 obj = item.obj # type: ignore[attr-defined]
206 return {
207 "nodeid": item.nodeid,
208 "name": item.name,
209 "path": str(item.path),
210 "modulename": obj.__module__,
211 "methodname": obj.__name__,
212 }
213
214 def _publish_worker_report(self) -> None:
215 """Stash this worker's report on ``config.workeroutput`` for the controller."""
216 output = getattr(self.pytest_session.config, "workeroutput", None)
217 if output is None or self.report is None:
218 return
219 payload: dict[str, Any] = {
220 "collections": {
221 name: getattr(self.report, name).serialize()
222 for name in _MERGED_COLLECTIONS
223 },
224 "num_xfails": self.report._num_xfails,
225 "selected": {
226 nodeid: status.value for nodeid, status in self._selected_items.items()
227 },
228 "extensions": {
229 location: (
230 f"{extension.__class__.__module__}"
231 f".{extension.__class__.__qualname__}"
232 )
233 for location, extension in self._extensions.items()
234 },
235 }
236 # Every worker collects the identical full set of items, so only one
237 # worker needs to send it to avoid transmitting it once per worker.
238 if os.getenv("PYTEST_XDIST_WORKER") == "gw0":
239 payload["collected"] = [
240 self._serialize_item(item) for item in self._collected_items
241 ]
242 output["syrupy_report"] = payload
243
244 def add_worker_report(self, report: dict[str, Any]) -> None:
245 """Called on the controller for each worker as it shuts down."""
246 self._worker_reports.append(report)
247
248 def _merge_worker_reports(self) -> None:
249 assert self.report is not None
250 selected: dict[str, ItemStatus] = {}
251 for report in self._worker_reports:
252 self.report._num_xfails += report["num_xfails"]
253 for name, serialized in report["collections"].items():
254 getattr(self.report, name).merge_serialized(serialized)
255 for nodeid, value in report["selected"].items():
256 status = ItemStatus(value)
257 # Prefer a concrete run status over NOT_RUN from another worker.
258 if selected.get(nodeid, ItemStatus.NOT_RUN) == ItemStatus.NOT_RUN:
259 selected[nodeid] = status
260 for location, member in report.get("extensions", {}).items():
261 if location not in self._extensions:
262 try:
263 self._extensions[location] = import_module_member(member)()
264 except FailedToLoadModuleMember:
265 pass
266 if "collected" in report:
267 self.report.collected_items = {
268 _ReconstructedItem(item) # type: ignore[misc]
269 for item in report["collected"]
270 }
271 self.report.selected_items = selected
272
273 def finish(self) -> int:
274 exitstatus = 0
275 self.flush_snapshot_write_queue()
276 self.report = SnapshotReport(
277 base_dir=self.pytest_session.config.rootpath,
278 collected_items=self._collected_items,
279 selected_items=self._selected_items,
280 assertions=self._assertions,
281 options=self.pytest_session.config.option,
282 )
283
284 if is_xdist_worker():
285 # Publish this worker's report so the controller can combine the
286 # reports of all workers and handle unused snapshot detection.
287 self._publish_worker_report()
288 return exitstatus
289
290 # On the pytest-xdist controller no tests run locally, so the report is
291 # rebuilt from the reports published by each worker.
292 if self._worker_reports:
293 self._merge_worker_reports()
294
295 if self.report.num_unused:
296 if self.report.should_delete_unused_snapshots:
297 self.remove_unused_snapshots(
298 unused_snapshot_collections=self.report.unused,
299 used_snapshot_collections=self.report.used,
300 )
301 elif not self.update_snapshots and not self.warn_unused_snapshots:
302 exitstatus |= EXIT_STATUS_FAIL_UNUSED
303 return exitstatus
304
305 def register_request(self, assertion: "SnapshotAssertion") -> None:
306 self._assertions.append(assertion)
307
308 test_location = assertion.test_location.filepath
309 extension_class = assertion.extension.__class__
310 if extension_class not in self._locations_discovered[test_location]:
311 self._locations_discovered[test_location].add(extension_class)
312 discovered_extensions = {
313 discovered.location: assertion.extension
314 for discovered in assertion.extension.discover_snapshots(
315 test_location=assertion.test_location,
316 ignore_extensions=self.ignore_file_extensions,
317 )
318 if discovered.has_snapshots
319 }
320 self._extensions.update(discovered_extensions)
321
322 def remove_unused_snapshots(
323 self,
324 unused_snapshot_collections: "SnapshotCollections",
325 used_snapshot_collections: "SnapshotCollections",
326 ) -> None:
327 """
328 Remove all unused snapshots using the registed extension for the collection file
329 If there is not registered extension and the location is unused delete the file
330 """
331 for unused_snapshot_collection in unused_snapshot_collections:
332 snapshot_location = unused_snapshot_collection.location
333
334 extension = self._extensions.get(snapshot_location)
335 if extension:
336 extension.delete_snapshots(
337 snapshot_location=snapshot_location,
338 snapshot_names={
339 snapshot.name for snapshot in unused_snapshot_collection
340 },
341 )
342 elif snapshot_location not in used_snapshot_collections:
343 Path(snapshot_location).unlink()
344
345 @staticmethod
346 def filter_valid_items(items: list["pytest.Item"]) -> Iterable["pytest.Item"]:
347 return (item for item in items if isinstance(item, pytest.Function))