Debian Codegraph @

src/syrupy/__init__.py

raw
1 import argparse
2 import contextlib
3 import sys
4 from collections.abc import Iterator
5 from functools import lru_cache
6 from gettext import gettext
7 from typing import (
8 Any,
9 Optional,
10 )
11
12 import pytest
13
14 from syrupy.extensions.base import SnapshotCollectionStorage
15
16 from .assertion import DiffMode, SnapshotAssertion
17 from .exceptions import FailedToLoadModuleMember
18 from .extensions import DEFAULT_EXTENSION
19 from .location import PyTestLocation
20 from .patches.pycharm_diff import patch_pycharm_diff
21 from .session import SnapshotSession
22 from .terminal import (
23 disable_color,
24 received_style,
25 reset,
26 snapshot_style,
27 )
28 from .utils import (
29 import_module_member,
30 is_xdist_worker,
31 )
32
33 # Global to have access to the session in `pytest_runtest_logfinish` hook
34 _syrupy: Optional["SnapshotSession"] = None
35
36
37 @lru_cache(maxsize=1)
38 def __import_extension(value: str | None) -> Any:
39 if not value:
40 return DEFAULT_EXTENSION
41 try:
42 return import_module_member(value)
43 except FailedToLoadModuleMember as e:
44 raise argparse.ArgumentTypeError(e) from e
45
46
47 def pytest_addoption(parser: "pytest.Parser") -> None:
48 """
49 Exposes snapshot plugin configuration to pytest.
50 https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_addoption
51 """
52 group = parser.getgroup("syrupy")
53 group.addoption(
54 "--snapshot-update",
55 action="store_true",
56 default=False,
57 dest="update_snapshots",
58 help="Update snapshots",
59 )
60 group.addoption(
61 "--snapshot-update-new-only",
62 action="store_true",
63 default=False,
64 dest="update_new_snapshots_only",
65 help="Write snapshots that do not exist yet, but do not modify existing ones",
66 )
67 group.addoption(
68 "--snapshot-warn-unused",
69 action="store_true",
70 default=False,
71 dest="warn_unused_snapshots",
72 help="Do not fail on unused snapshots",
73 )
74 group.addoption(
75 "--snapshot-no-cleanup",
76 action="store_true",
77 default=False,
78 dest="no_cleanup",
79 help="Do not delete unused snapshots when updating with --snapshot-update",
80 )
81 group.addoption(
82 "--snapshot-details",
83 action="store_true",
84 default=False,
85 dest="include_snapshot_details",
86 help="Include details of unused snapshots in the final report",
87 )
88
89 # We lazy evaluate the default extension since pytest-xdist requires
90 # all pytest options to be serializable.
91 group.addoption(
92 "--snapshot-default-extension",
93 default=None,
94 dest="default_extension",
95 help="Specify the default snapshot extension",
96 )
97
98 group.addoption(
99 "--snapshot-no-colors",
100 action="store_true",
101 default=not sys.stdout.isatty(),
102 dest="no_colors",
103 help="Disable test results output highlighting",
104 )
105 group.addoption(
106 "--snapshot-patch-pycharm-diff",
107 action="store_true",
108 default=False,
109 dest="patch_pycharm_diff",
110 help="Patch PyCharm diff",
111 )
112 group.addoption(
113 "--snapshot-diff-mode",
114 default=DiffMode.DETAILED,
115 choices=list(DiffMode),
116 type=DiffMode,
117 dest="diff_mode",
118 help="Controls how diffs are represented on snapshot assertion failure",
119 )
120 group.addoption(
121 "--snapshot-ignore-file-extensions",
122 dest="ignore_file_extensions",
123 help="Comma separated list of file extensions to ignore when discovering snapshots",
124 type=lambda v: v.split(","),
125 )
126 group.addoption(
127 "--snapshot-dirname",
128 dest="snapshot_dirname",
129 default="__snapshots__",
130 help="Directory name to use to store snapshots",
131 )
132
133
134 def __terminal_color(
135 config: "pytest.Config",
136 ) -> "contextlib.AbstractContextManager[None]":
137 if config.option.no_colors:
138 return disable_color()
139 else:
140 # No-op to avoid unnecessary work
141 return contextlib.nullcontext()
142
143
144 @pytest.hookimpl(tryfirst=True)
145 def pytest_assertrepr_compare(
146 config: "pytest.Config", op: str, left: Any, right: Any
147 ) -> list[str] | None:
148 """
149 Return explanation for comparisons in failing assert expressions.
150 https://docs.pytest.org/en/latest/reference.html#pytest.hookspec.pytest_assertrepr_compare
151 """
152 if not isinstance(left, SnapshotAssertion) and not isinstance(
153 right, SnapshotAssertion
154 ):
155 # Shortcut to minimise overhead in the case of other unrelated assertions
156 return None
157
158 with __terminal_color(config):
159 received_name = received_style("[+ received]")
160
161 def snapshot_name(name: str) -> str:
162 return snapshot_style(f"[- {name}]")
163
164 if isinstance(left, SnapshotAssertion):
165 assert_msg = reset(f"{snapshot_name(left.name)} {op} {received_name}")
166 return [assert_msg] + left.get_assert_diff(
167 diff_mode=config.option.diff_mode
168 )
169 elif isinstance(right, SnapshotAssertion):
170 assert_msg = reset(f"{received_name} {op} {snapshot_name(right.name)}")
171 return [assert_msg] + right.get_assert_diff(
172 diff_mode=config.option.diff_mode
173 )
174 return None
175
176
177 def pytest_sessionstart(session: Any) -> None:
178 """
179 Initialize snapshot session before tests are collected and ran.
180 https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_sessionstart
181 """
182
183 # Override the snapshot dirname in the base SnapshotCollectionStorage class with the pytest config.
184 SnapshotCollectionStorage.snapshot_dirname = session.config.option.snapshot_dirname
185
186 session.config._syrupy = SnapshotSession(
187 pytest_session=session,
188 ignore_file_extensions=session.config.option.ignore_file_extensions,
189 )
190 global _syrupy
191 _syrupy = session.config._syrupy
192 session.config._syrupy.start()
193
194
195 def pytest_collection_modifyitems(
196 session: Any, config: Any, items: list["pytest.Item"]
197 ) -> None:
198 """
199 After tests are collected and before any modification is performed.
200 https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_collection_modifyitems
201 """
202 config._syrupy.collect_items(items)
203
204
205 def pytest_collection_finish(session: Any) -> None:
206 """
207 After collection has been performed and modified.
208 https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_collection_finish
209 """
210 session.config._syrupy.select_items(session.items)
211
212
213 class DeferXDist:
214 """Defer pytest-xdist hook functions."""
215
216 def pytest_testnodedown(self, node: Any, error: Any) -> None:
217 """
218 Collect a pytest-xdist worker's snapshot report as the worker shuts down.
219 Runs on the controller; the payload is published via ``config.workeroutput``.
220 https://pytest-xdist.readthedocs.io/en/stable/distribution.html
221 """
222 workeroutput = getattr(node, "workeroutput", None)
223 syrupy = getattr(node.config, "_syrupy", None)
224 if workeroutput and syrupy:
225 report = workeroutput.get("syrupy_report")
226 if report is not None:
227 syrupy.add_worker_report(report)
228
229
230 def pytest_configure(config: pytest.Config) -> None:
231 if config.pluginmanager.hasplugin("xdist") or config.pluginmanager.hasplugin(
232 "xdist.plugin"
233 ):
234 config.pluginmanager.register(DeferXDist())
235
236
237 def pytest_runtest_logreport(report: pytest.TestReport) -> None:
238 """
239 After each of the setup, call and teardown runtest phases of an item.
240 https://docs.pytest.org/en/8.0.x/reference/reference.html#pytest.hookspec.pytest_runtest_logreport
241 """
242 global _syrupy
243 # The outcome will be passed in the teardown phase even if skipped
244 if _syrupy and report.when != "teardown":
245 _syrupy.ran_item(report.nodeid, report.outcome)
246
247
248 @pytest.hookimpl(tryfirst=True)
249 def pytest_sessionfinish(session: "pytest.Session", exitstatus: int) -> None:
250 """
251 Finish session run and set exit status.
252 https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_sessionfinish
253 """
254 session.exitstatus |= exitstatus | session.config._syrupy.finish() # type: ignore[attr-defined] # noqa: E501
255
256
257 def pytest_terminal_summary(
258 terminalreporter: Any, exitstatus: int, config: Any
259 ) -> None:
260 """
261 Add syrupy report to pytest.
262 https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_terminal_summary
263 """
264 if is_xdist_worker():
265 # There is no need for pytest-xdist worker processes to generate a
266 # summary and doing so has been seen to cause CPU spin and delays to
267 # test run shutdown.
268 return
269
270 with __terminal_color(config):
271 is_printing_report = False
272 for line in terminalreporter.config._syrupy.report.lines:
273 has_report_line = bool(line.strip())
274 if has_report_line and not is_printing_report:
275 terminalreporter.write_sep("-", gettext("snapshot report summary"))
276 is_printing_report = True
277 if is_printing_report:
278 terminalreporter.write_line(line)
279
280
281 @pytest.fixture
282 def snapshot(request: "pytest.FixtureRequest") -> "SnapshotAssertion":
283 return SnapshotAssertion(
284 update_snapshots=request.config.option.update_snapshots,
285 update_new_snapshots_only=request.config.option.update_new_snapshots_only,
286 extension_class=__import_extension(request.config.option.default_extension),
287 test_location=PyTestLocation(request.node),
288 session=request.session.config._syrupy, # type: ignore
289 )
290
291
292 @pytest.fixture(scope="session", autouse=True)
293 def _syrupy_apply_ide_patches(request: "pytest.FixtureRequest") -> Iterator[None]:
294 if request.config.option.patch_pycharm_diff:
295 with patch_pycharm_diff():
296 yield
297 else:
298 yield