Debian Codegraph @

src/syrupy/report.py

raw
1 import importlib
2 from collections import defaultdict
3 from collections.abc import Callable, Generator, Iterator
4 from dataclasses import (
5 dataclass,
6 field,
7 )
8 from functools import cache, cached_property
9 from gettext import (
10 gettext,
11 ngettext,
12 )
13 from pathlib import Path
14 from typing import (
15 TYPE_CHECKING,
16 Any,
17 )
18
19 from _pytest.mark.expression import Expression as PytestExpression
20 from _pytest.skipping import xfailed_key
21
22 from .constants import PYTEST_NODE_SEP
23 from .data import (
24 Snapshot,
25 SnapshotCollection,
26 SnapshotCollections,
27 SnapshotUnknownCollection,
28 )
29 from .location import PyTestLocation
30 from .terminal import (
31 bold,
32 error_style,
33 green,
34 success_style,
35 warning_style,
36 )
37
38 if TYPE_CHECKING:
39 import argparse
40
41 import pytest
42
43 from .assertion import SnapshotAssertion
44 from .session import ItemStatus
45
46
47 @dataclass
48 class SnapshotReport:
49 """
50 This class is responsible for determining the test summary and post execution
51 results. It will provide the lines of the report to be printed as well as the
52 information used for removal of unused or orphaned snapshots and collections.
53 """
54
55 # Initial arguments to the report
56 base_dir: Path
57 collected_items: set["pytest.Item"]
58 selected_items: dict[str, "ItemStatus"]
59 options: "argparse.Namespace"
60 assertions: list["SnapshotAssertion"]
61
62 # All of these are derived from the initial arguments and via walking the filesystem
63 discovered: "SnapshotCollections" = field(default_factory=SnapshotCollections)
64 created: "SnapshotCollections" = field(default_factory=SnapshotCollections)
65 failed: "SnapshotCollections" = field(default_factory=SnapshotCollections)
66 matched: "SnapshotCollections" = field(default_factory=SnapshotCollections)
67 updated: "SnapshotCollections" = field(default_factory=SnapshotCollections)
68 used: "SnapshotCollections" = field(default_factory=SnapshotCollections)
69 _provided_test_paths: dict[str, list[str]] = field(default_factory=dict)
70 _keyword_expressions: set["Expression"] = field(default_factory=set)
71 _num_xfails: int = field(default=0)
72
73 @property
74 def update_snapshots(self) -> bool:
75 return bool(self.options.update_snapshots)
76
77 @property
78 def warn_unused_snapshots(self) -> bool:
79 return bool(self.options.warn_unused_snapshots)
80
81 @property
82 def should_delete_unused_snapshots(self) -> bool:
83 # Unused snapshots are only removed while updating, unless the user
84 # opted out of cleanup with --snapshot-no-cleanup.
85 return self.update_snapshots and not bool(self.options.no_cleanup)
86
87 @property
88 def include_snapshot_details(self) -> bool:
89 return bool(self.options.include_snapshot_details)
90
91 @cached_property
92 def _collected_items_by_nodeid(self) -> dict[str, "pytest.Item"]:
93 return {item.nodeid: item for item in self.collected_items}
94
95 def _has_xfail(self, item: "pytest.Item") -> bool:
96 # xfailed_key is 'private'. I'm open to a better way to do this:
97 if xfailed_key in item.stash:
98 result = item.stash[xfailed_key]
99 if result:
100 return result.run
101 return False
102
103 def __post_init__(self) -> None:
104 self.__parse_invocation_args()
105
106 # We only need to discover snapshots once per test file, not once per assertion.
107 locations_discovered: defaultdict[str, set[Any]] = defaultdict(set)
108 for assertion in self.assertions:
109 test_location = assertion.test_location.filepath
110 extension_class = assertion.extension.__class__
111 if extension_class not in locations_discovered[test_location]:
112 locations_discovered[test_location].add(extension_class)
113 self.discovered.merge(
114 assertion.extension.discover_snapshots(
115 test_location=assertion.test_location,
116 ignore_extensions=assertion.session.ignore_file_extensions,
117 )
118 )
119
120 for result in assertion.executions.values():
121 snapshot_collection = SnapshotCollection(
122 location=result.snapshot_location
123 )
124 snapshot_collection.add(
125 Snapshot(name=result.snapshot_name, data=result.final_data)
126 )
127 self.used.update(snapshot_collection)
128
129 if result.created:
130 self.created.update(snapshot_collection)
131 elif result.updated:
132 self.updated.update(snapshot_collection)
133 elif result.success:
134 self.matched.update(snapshot_collection)
135 else:
136 has_xfail = self._has_xfail(item=result.test_location.item)
137 if has_xfail:
138 self._num_xfails += 1
139 self.failed.update(snapshot_collection)
140
141 def __parse_invocation_args(self) -> None:
142 """
143 Parse the invocation arguments to extract some information for test selection
144 This compiles and saves values from `-k`, `--pyargs` and test dir path
145
146 https://docs.pytest.org/en/stable/reference.html#command-line-flags
147 https://docs.pytest.org/en/stable/reference.html#config
148
149 Summary
150 -k: is evaluated and used to match against snapshot names when present
151 -m: is ignored for now as markers are not matched to snapshot names
152 --pyargs: arguments are imported to get their file locations
153 [args]: a path provided e.g. tests/test_file.py::TestClass::test_method
154 would result in `"tests/test_file.py"` being stored as the location in a
155 dictionary with `["TestClass", "test_method"]` being the test node path
156 """
157
158 if self.options.keyword:
159 self._keyword_expressions.add(Expression.compose(self.options.keyword))
160 for file_or_dir in self.options.file_or_dir:
161 parts = file_or_dir.split(PYTEST_NODE_SEP)
162 package_or_filepath = parts[0].strip()
163 filepath = Path(package_or_filepath)
164 if self.options.pyargs:
165 try:
166 mod = importlib.import_module(package_or_filepath)
167 if mod.__file__ is not None:
168 filepath = Path(mod.__file__)
169 except Exception:
170 pass
171 filepath_abs = str(
172 filepath if filepath.is_absolute() else filepath.absolute()
173 )
174 self._provided_test_paths[filepath_abs] = parts[1:]
175
176 @property
177 def num_created(self) -> int:
178 return self._count_snapshots(self.created)
179
180 @cached_property
181 def num_failed(self) -> int:
182 return self._count_snapshots(self.failed)
183
184 @property
185 def num_matched(self) -> int:
186 return self._count_snapshots(self.matched)
187
188 @property
189 def num_updated(self) -> int:
190 return self._count_snapshots(self.updated)
191
192 @property
193 def num_unused(self) -> int:
194 return self._count_snapshots(self.unused)
195
196 @property
197 def selected_all_collected_items(self) -> bool:
198 return self._collected_items_by_nodeid.keys() == self.selected_items.keys()
199
200 @property
201 def skipped_items(self) -> Iterator["pytest.Item"]:
202 return (
203 self._collected_items_by_nodeid[nodeid]
204 for nodeid in self.selected_items
205 if self.selected_items[nodeid].value == "skipped"
206 )
207
208 @property
209 def ran_items(self) -> Iterator["pytest.Item"]:
210 return (
211 self._collected_items_by_nodeid[nodeid]
212 for nodeid in self.selected_items
213 if self.selected_items[nodeid]
214 )
215
216 @property
217 def unused(self) -> "SnapshotCollections":
218 """
219 Iterate over each snapshot that was discovered but never used and compute
220 if the snapshot was unused because the test attached to it was never run,
221 or if the snapshot is obsolete and therefore is a candidate for removal.
222
223 Summary, if a snapshot was supposed to be run based on the invocation args
224 and it was not, then it should be marked as unused otherwise ignored.
225 """
226 unused_collections = SnapshotCollections()
227 for unused_snapshot_collection in self._diff_snapshot_collections(
228 self.discovered, self.used
229 ):
230 snapshot_location = unused_snapshot_collection.location
231 if self._provided_test_paths and not self._ran_items_match_location(
232 snapshot_location
233 ):
234 # Paths/Packages were provided to pytest and the snapshot location does
235 # not match any of ran tests therefore ignore this unused snapshot file
236 continue
237
238 provided_nodes = self._get_matching_path_nodes(snapshot_location)
239 if self.selected_all_collected_items and not any(provided_nodes):
240 # All collected tests were run and files were not filtered by ::node
241 # therefore the snapshot collection file at this location can be deleted
242 unused_snapshots = {
243 snapshot
244 for snapshot in unused_snapshot_collection
245 if not self._skipped_items_match_name(
246 snapshot_location=snapshot_location, snapshot_name=snapshot.name
247 )
248 }
249 mark_for_removal = snapshot_location not in self.used
250 else:
251 unused_snapshots = {
252 snapshot
253 for snapshot in unused_snapshot_collection
254 if self._selected_items_match_name(
255 snapshot_location=snapshot_location, snapshot_name=snapshot.name
256 )
257 and self._provided_nodes_match_name(
258 snapshot_location=snapshot_location,
259 snapshot_name=snapshot.name,
260 provided_nodes=provided_nodes,
261 )
262 and not self._skipped_items_match_name(
263 snapshot_location=snapshot_location, snapshot_name=snapshot.name
264 )
265 }
266 mark_for_removal = False
267
268 if unused_snapshots:
269 marked_unused_snapshot_collection = SnapshotCollection(
270 location=snapshot_location
271 )
272 for snapshot in unused_snapshots:
273 marked_unused_snapshot_collection.add(snapshot)
274 unused_collections.add(marked_unused_snapshot_collection)
275 elif mark_for_removal:
276 unused_collections.add(
277 SnapshotUnknownCollection(location=snapshot_location)
278 )
279 return unused_collections
280
281 @property
282 def lines(self) -> Iterator[str]:
283 """
284 These are the lines printed at the end of a test run. Example:
285 ```
286 2 snapshots passed. 5 snapshots generated. 1 unused snapshot deleted.
287
288 Re-run pytest with --snapshot-update to delete unused snapshots.
289 ```
290 """
291 summary_lines: list[str] = []
292 if self.num_failed and self._num_xfails < self.num_failed:
293 summary_lines.append(
294 ngettext(
295 "{} snapshot failed.",
296 "{} snapshots failed.",
297 self.num_failed - self._num_xfails,
298 ).format(error_style(self.num_failed - self._num_xfails)),
299 )
300 if self._num_xfails:
301 summary_lines.append(
302 ngettext(
303 "{} snapshot xfailed.",
304 "{} snapshots xfailed.",
305 self._num_xfails,
306 ).format(warning_style(self._num_xfails)),
307 )
308 if self.num_matched:
309 summary_lines.append(
310 ngettext(
311 "{} snapshot passed.",
312 "{} snapshots passed.",
313 self.num_matched,
314 ).format(success_style(self.num_matched))
315 )
316 if self.num_created:
317 summary_lines.append(
318 ngettext(
319 "{} snapshot generated.",
320 "{} snapshots generated.",
321 self.num_created,
322 ).format(green(self.num_created))
323 )
324 if self.num_updated:
325 summary_lines.append(
326 ngettext(
327 "{} snapshot updated.",
328 "{} snapshots updated.",
329 self.num_updated,
330 ).format(green(self.num_updated))
331 )
332 if self.num_unused:
333 if self.should_delete_unused_snapshots:
334 text_singular = "{} unused snapshot deleted."
335 text_plural = "{} unused snapshots deleted."
336 else:
337 text_singular = "{} snapshot unused."
338 text_plural = "{} snapshots unused."
339 if self.update_snapshots or self.warn_unused_snapshots:
340 text_count = warning_style(self.num_unused)
341 else:
342 text_count = error_style(self.num_unused)
343 summary_lines.append(
344 ngettext(text_singular, text_plural, self.num_unused).format(text_count)
345 )
346 yield " ".join(summary_lines)
347
348 if self.num_unused:
349 yield ""
350 if self.update_snapshots or self.include_snapshot_details:
351 base_message = (
352 "Deleted" if self.should_delete_unused_snapshots else "Unused"
353 )
354 for snapshots, path_to_file in self.__iterate_snapshot_collection(
355 self.unused
356 ):
357 unused_snapshots = ", ".join(map(bold, sorted(snapshots)))
358 yield (
359 warning_style(gettext(base_message))
360 + f" {unused_snapshots} ({path_to_file})"
361 )
362 if not self.update_snapshots:
363 message = gettext(
364 "Re-run pytest with --snapshot-update to delete unused snapshots."
365 )
366 if self.warn_unused_snapshots:
367 yield warning_style(message)
368 else:
369 yield error_style(message)
370
371 if self.num_created and self.update_snapshots and self.include_snapshot_details:
372 yield ""
373 for snapshots, path_to_file in self.__iterate_snapshot_collection(
374 self.created
375 ):
376 created_snapshots = ", ".join(map(bold, sorted(snapshots)))
377 yield (
378 warning_style(gettext("Generated"))
379 + f" {created_snapshots} ({path_to_file})"
380 )
381
382 if self.num_updated and self.update_snapshots and self.include_snapshot_details:
383 yield ""
384 for snapshots, path_to_file in self.__iterate_snapshot_collection(
385 self.updated
386 ):
387 updated_snapshots = ", ".join(map(bold, sorted(snapshots)))
388 yield (
389 warning_style(gettext("Updated"))
390 + f" {updated_snapshots} ({path_to_file})"
391 )
392
393 def __iterate_snapshot_collection(
394 self, collection: "SnapshotCollections"
395 ) -> Generator[tuple[Generator[str, None, None], str], Any, None]:
396 for snapshot_collection in collection:
397 filepath = snapshot_collection.location
398 snapshots = (snapshot.name for snapshot in snapshot_collection)
399
400 try:
401 path_to_file = str(Path(filepath).relative_to(self.base_dir))
402 except ValueError:
403 # this is just used for display, so better to fallback to
404 # something vaguely reasonable (the full path) than give up
405 path_to_file = filepath
406
407 yield (snapshots, path_to_file)
408
409 def _diff_snapshot_collections(
410 self,
411 snapshot_collections1: "SnapshotCollections",
412 snapshot_collections2: "SnapshotCollections",
413 ) -> "SnapshotCollections":
414 """
415 Find the difference between two collections of snapshot collections. While
416 preserving the location site to all collections in the first collections.
417 That is a collection with collection sites {A{1,2}, B{3,4}, C{5,6}} with
418 snapshot collections when diffed with another collection with snapshots
419 {A{1,2}, B{3,4}, D{7,8}} will result in a collection with the contents
420 {A{}, B{}, C{5,6}}.
421 """
422 diffed_snapshot_collections = SnapshotCollections()
423 for snapshot_collection1 in snapshot_collections1:
424 snapshot_collection2 = snapshot_collections2.get(
425 snapshot_collection1.location
426 ) or SnapshotCollection(location=snapshot_collection1.location)
427 diffed_snapshot_collection = SnapshotCollection(
428 location=snapshot_collection1.location
429 )
430 for snapshot in snapshot_collection1:
431 if not snapshot_collection2.get(snapshot.name):
432 diffed_snapshot_collection.add(snapshot)
433 diffed_snapshot_collections.add(diffed_snapshot_collection)
434 return diffed_snapshot_collections
435
436 def _count_snapshots(self, snapshot_collections: "SnapshotCollections") -> int:
437 """
438 Count all the snapshots at all the locations in the snapshot collections
439 """
440 return sum(
441 len(snapshot_collection) for snapshot_collection in snapshot_collections
442 )
443
444 def _is_matching_path(self, snapshot_location: str, provided_path: str) -> bool:
445 """
446 Check if a snapshot location matches the path provided by checking that the
447 provided path folder is in a parent position relative to the snapshot location
448 """
449 path = Path(provided_path)
450 return str(path if path.is_dir() else path.parent) in snapshot_location
451
452 def _get_matching_path_nodes(self, snapshot_location: str) -> list[list[str]]:
453 """
454 For the snapshot location provided, get the nodes of the test paths provided to
455 pytest on invocation. If there were no paths provided then this list should be
456 empty. If there are paths without nodes provided then this is a list of empties
457 """
458 return [
459 self._provided_test_paths[path]
460 for path in self._provided_test_paths
461 if self._is_matching_path(snapshot_location, path)
462 ]
463
464 def _provided_nodes_match_name(
465 self,
466 snapshot_location: str,
467 snapshot_name: str,
468 provided_nodes: list[list[str]],
469 ) -> bool:
470 """
471 Check that a snapshot name matches the node paths provided.
472 If no nodes are filtered, provided_nodes is empty, which means
473 all nodes should be matched.
474 """
475 if not provided_nodes:
476 return True
477 for node_path in provided_nodes:
478 if snapshot_name in ".".join(node_path):
479 return True
480 return False
481
482 def _provided_keywords_match_name(self, snapshot_name: str) -> bool:
483 """
484 Check that a snapshot name would have been included by the keyword
485 expression parsed from the invocation arguments
486 """
487 names = snapshot_name.split(".")
488 return any(
489 expr.evaluate(lambda subname: any(subname in name for name in names))
490 for expr in self._keyword_expressions
491 )
492
493 def _ran_items_match_name(self, snapshot_location: str, snapshot_name: str) -> bool:
494 """
495 Check that a snapshot name would match a test node using the Pytest location
496 """
497 for item in self.ran_items:
498 location = PyTestLocation(item)
499 if location.matches_snapshot_location(
500 snapshot_location
501 ) and location.matches_snapshot_name(snapshot_name):
502 return True
503 return False
504
505 def _skipped_items_match_name(
506 self, snapshot_location: str, snapshot_name: str
507 ) -> bool:
508 """
509 Check that a snapshot name should be treated as skipped by the current session
510 This being true means that it will not be deleted even if the it is unused
511 """
512 for item in self.skipped_items:
513 location = PyTestLocation(item)
514 if location.matches_snapshot_location(
515 snapshot_location
516 ) and location.matches_snapshot_name(snapshot_name):
517 return True
518 return False
519
520 def _selected_items_match_name(
521 self, snapshot_location: str, snapshot_name: str
522 ) -> bool:
523 """
524 Check that a snapshot name should be treated as selected by the current session
525 This being true means that if the snapshot was not used then it will be deleted
526 """
527 if self._keyword_expressions:
528 return self._provided_keywords_match_name(snapshot_name)
529 return self._ran_items_match_name(
530 snapshot_location=snapshot_location, snapshot_name=snapshot_name
531 )
532
533 def _ran_items_match_location(self, snapshot_location: str) -> bool:
534 """
535 Check if any test run in the current session should match the snapshot location
536 This being true means that if no snapshot in the collection was used then it
537 should be discarded as obsolete
538 """
539 return any(
540 PyTestLocation(item).matches_snapshot_location(snapshot_location)
541 for item in self.ran_items
542 )
543
544
545 @cache
546 def _compile_keyword_expression(keyword: str) -> "PytestExpression":
547 return PytestExpression.compile(keyword)
548
549
550 @dataclass(frozen=True)
551 class Expression:
552 """
553 Evaluate a pytest ``-k`` keyword expression against snapshot names.
554
555 Delegates parsing and evaluation to pytest's own expression implementation
556 so that the ``and``/``or``/``not``/parenthesis operators behave exactly like
557 ``-k`` selection. A previous hand rolled version ignored those operators and
558 only did substring matching, which wrongly marked deselected snapshots (for
559 example ``-k 'not foo'``) as unused.
560 """
561
562 keyword: str = ""
563
564 def evaluate(self, matcher: Callable[[str], bool]) -> bool:
565 # pytest's matcher protocol allows extra keyword arguments (for mark
566 # expressions); keyword matching only ever passes the positional name.
567 return _compile_keyword_expression(self.keyword).evaluate(matcher) # type: ignore[arg-type]
568
569 @staticmethod
570 def compose(value: str) -> "Expression":
571 return Expression(keyword=value)