Debian Codegraph @

src/syrupy/extensions/base.py

raw
1 import warnings
2 from abc import (
3 ABC,
4 abstractmethod,
5 )
6 from collections.abc import Callable, Iterator
7 from gettext import gettext
8 from itertools import zip_longest
9 from pathlib import Path
10 from typing import (
11 TYPE_CHECKING,
12 Optional,
13 )
14
15 from syrupy.constants import (
16 SYMBOL_CARRIAGE,
17 SYMBOL_ELLIPSIS,
18 SYMBOL_NEW_LINE,
19 )
20 from syrupy.data import (
21 DiffedLine,
22 Snapshot,
23 SnapshotCollection,
24 SnapshotCollections,
25 SnapshotEmptyCollection,
26 )
27 from syrupy.exceptions import SnapshotDoesNotExist
28 from syrupy.terminal import (
29 context_style,
30 disable_color,
31 received_diff_style,
32 received_style,
33 reset,
34 snapshot_diff_style,
35 snapshot_style,
36 )
37 from syrupy.utils import (
38 obj_attrs,
39 qdiff,
40 walk_snapshot_dir,
41 )
42
43 if TYPE_CHECKING:
44 from syrupy.location import PyTestLocation
45 from syrupy.types import (
46 PropertyFilter,
47 PropertyMatcher,
48 SerializableData,
49 SerializedData,
50 SnapshotIndex,
51 )
52
53
54 class SnapshotSerializer(ABC):
55 @abstractmethod
56 def serialize(
57 self,
58 data: "SerializableData",
59 *,
60 exclude: Optional["PropertyFilter"] = None,
61 include: Optional["PropertyFilter"] = None,
62 matcher: Optional["PropertyMatcher"] = None,
63 ) -> "SerializedData":
64 """
65 Serializes a python object / data structure into a string
66 to be used for comparison with snapshot data from disk.
67 """
68 raise NotImplementedError
69
70
71 class SnapshotCollectionStorage(ABC):
72 snapshot_dirname: str | Path = "__snapshots__"
73 file_extension = ""
74
75 @classmethod
76 def get_snapshot_name(
77 cls, *, test_location: "PyTestLocation", index: "SnapshotIndex" = 0
78 ) -> str:
79 """Get the snapshot name for the assertion index in a test location"""
80 index_suffix = ""
81 if isinstance(index, (str,)):
82 index_suffix = f"[{index}]"
83 elif index:
84 index_suffix = f".{index}"
85 return f"{test_location.snapshot_name}{index_suffix}"
86
87 @classmethod
88 def get_location(
89 cls, *, test_location: "PyTestLocation", index: "SnapshotIndex"
90 ) -> str:
91 """Returns full filepath where snapshot data is stored."""
92 basename = cls.get_file_basename(test_location=test_location, index=index)
93 fileext = f".{cls.file_extension}" if cls.file_extension else ""
94 return str(
95 Path(cls.dirname(test_location=test_location)).joinpath(
96 f"{basename}{fileext}"
97 )
98 )
99
100 def is_snapshot_location(self, *, location: str) -> bool:
101 """Checks if supplied location is valid for this snapshot extension"""
102 return location.endswith(self.file_extension)
103
104 def discover_snapshots(
105 self,
106 *,
107 test_location: "PyTestLocation",
108 ignore_extensions: list[str] | None = None,
109 ) -> "SnapshotCollections":
110 """
111 Returns all snapshot collections in test site
112 """
113 discovered = SnapshotCollections()
114 for filepath in walk_snapshot_dir(
115 self.dirname(test_location=test_location),
116 ignore_extensions=ignore_extensions,
117 ):
118 if self.is_snapshot_location(location=filepath):
119 snapshot_collection = self.read_snapshot_collection(
120 snapshot_location=filepath
121 )
122 if not snapshot_collection.has_snapshots:
123 snapshot_collection = SnapshotEmptyCollection(location=filepath)
124 else:
125 snapshot_collection = SnapshotCollection(location=filepath)
126
127 discovered.add(snapshot_collection)
128
129 return discovered
130
131 def read_snapshot(
132 self,
133 *,
134 test_location: "PyTestLocation",
135 index: "SnapshotIndex",
136 session_id: str,
137 ) -> "SerializedData":
138 """
139 This method is _final_, do not override. You can override
140 `read_snapshot_data_from_location` in a subclass to change behaviour.
141 """
142 snapshot_location = self.get_location(test_location=test_location, index=index)
143 snapshot_name = self.get_snapshot_name(test_location=test_location, index=index)
144 snapshot_data = self.read_snapshot_data_from_location(
145 snapshot_location=snapshot_location,
146 snapshot_name=snapshot_name,
147 session_id=session_id,
148 )
149 if snapshot_data is None:
150 raise SnapshotDoesNotExist()
151 return snapshot_data
152
153 @classmethod
154 def write_snapshot(
155 cls,
156 *,
157 snapshot_location: str,
158 snapshots: list[tuple["SerializedData", "PyTestLocation", "SnapshotIndex"]],
159 ) -> None:
160 """
161 This method is _final_, do not override. You can override
162 `write_snapshot_collection` in a subclass to change behaviour.
163 """
164 if not snapshots:
165 return
166
167 # First we group by location since it'll let us batch by file on disk.
168 # Not as useful for single file snapshots, but useful for the standard
169 # Amber extension.
170 snapshot_collection = SnapshotCollection(location=snapshot_location)
171 for data, test_location, index in snapshots:
172 snapshot_name = cls.get_snapshot_name(
173 test_location=test_location, index=index
174 )
175 snapshot = Snapshot(name=snapshot_name, data=data)
176 snapshot_collection.add(snapshot)
177
178 if not test_location.matches_snapshot_location(snapshot_location):
179 warning_msg = gettext(
180 "{line_end}Can not relate snapshot location '{}' "
181 "to the test location.{line_end}"
182 "Consider adding '{}' to the generated location."
183 ).format(
184 snapshot_location,
185 test_location.basename,
186 line_end="\n",
187 )
188 warnings.warn(warning_msg, stacklevel=1)
189
190 if not test_location.matches_snapshot_name(snapshot.name):
191 warning_msg = gettext(
192 "{line_end}Can not relate snapshot name '{}' "
193 "to the test location.{line_end}"
194 "Consider adding '{}' to the generated name."
195 ).format(
196 snapshot.name,
197 test_location.testname,
198 line_end="\n",
199 )
200 warnings.warn(warning_msg, stacklevel=1)
201
202 # Ensures the folder path for the snapshot file exists.
203 Path(snapshot_location).parent.mkdir(parents=True, exist_ok=True)
204
205 cls.write_snapshot_collection(snapshot_collection=snapshot_collection)
206
207 @abstractmethod
208 def delete_snapshots(
209 self, *, snapshot_location: str, snapshot_names: set[str]
210 ) -> None:
211 """
212 Remove snapshots from a snapshot file.
213 If the snapshot file will be empty remove the entire file.
214 """
215 raise NotImplementedError
216
217 @abstractmethod
218 def read_snapshot_collection(
219 self, *, snapshot_location: str
220 ) -> "SnapshotCollection":
221 """
222 Read the snapshot location and construct a snapshot collection object
223 """
224 raise NotImplementedError
225
226 @abstractmethod
227 def read_snapshot_data_from_location(
228 self, *, snapshot_location: str, snapshot_name: str, session_id: str
229 ) -> Optional["SerializedData"]:
230 """
231 Get only the snapshot data from location for assertion
232 """
233 raise NotImplementedError
234
235 @classmethod
236 @abstractmethod
237 def write_snapshot_collection(
238 cls, *, snapshot_collection: "SnapshotCollection"
239 ) -> None:
240 """
241 Adds the snapshot data to the snapshots in collection location
242 """
243 raise NotImplementedError
244
245 @classmethod
246 def dirname(cls, *, test_location: "PyTestLocation") -> str:
247 test_dir = Path(test_location.filepath).parent
248 return str(test_dir.joinpath(cls.snapshot_dirname))
249
250 @classmethod
251 def get_file_basename(
252 cls, *, test_location: "PyTestLocation", index: "SnapshotIndex"
253 ) -> str:
254 """Returns file basename without extension. Used to create full filepath."""
255 return test_location.basename
256
257
258 def _count_leading_whitespace(s: str) -> int:
259 return len(s) - len(s.lstrip())
260
261
262 class SnapshotReporter:
263 _context_line_count = 1
264
265 def diff_snapshots(
266 self, serialized_data: "SerializedData", snapshot_data: "SerializedData"
267 ) -> "SerializedData":
268 attrs = {"_context_line_count": 0}
269 with disable_color(), obj_attrs(self, attrs):
270 return "\n".join(self.diff_lines(serialized_data, snapshot_data))
271
272 def diff_lines(
273 self, serialized_data: "SerializedData", snapshot_data: "SerializedData"
274 ) -> Iterator[str]:
275 for line in self.__diff_lines(str(snapshot_data), str(serialized_data)):
276 yield reset(line)
277
278 @property
279 def _ends(self) -> dict[str, str]:
280 return {"\n": self._marker_new_line, "\r": self._marker_carriage}
281
282 @property
283 def _context_line_max(self) -> int:
284 return self._context_line_count * 2
285
286 @property
287 def _marker_context_max(self) -> str:
288 return SYMBOL_ELLIPSIS
289
290 @property
291 def _marker_new_line(self) -> str:
292 return SYMBOL_NEW_LINE
293
294 @property
295 def _marker_carriage(self) -> str:
296 return SYMBOL_CARRIAGE
297
298 def __diff_lines(self, a: str, b: str) -> Iterator[str]:
299 for line in self.__diffed_lines(a, b):
300 show_ends = (
301 self.__strip_ends(line.a[1:] if line.a is not None else "")
302 == self.__strip_ends(line.b[1:] if line.b is not None else "")
303 if line.is_complete
304 else False
305 )
306 if line.has_snapshot and line.a is not None:
307 yield self.__format_line(
308 line.a, line.diff_a, snapshot_style, snapshot_diff_style, show_ends
309 )
310 if line.has_received and line.b is not None:
311 yield self.__format_line(
312 line.b, line.diff_b, received_style, received_diff_style, show_ends
313 )
314 yield from map(context_style, self.__limit_context(line.c))
315
316 def __diffed_lines(self, a: str, b: str) -> Iterator["DiffedLine"]:
317 staged_diffed_line: DiffedLine | None = None
318 for line in qdiff(a.splitlines(keepends=True), b.splitlines(keepends=True)):
319 is_context_line = line[0] == " "
320 is_snapshot_line = line[0] == "-"
321 is_received_line = line[0] == "+"
322 is_diff_line = line[0] == "?"
323
324 if is_context_line or is_diff_line:
325 line = self.__strip_ends(line)
326
327 if staged_diffed_line:
328 if is_diff_line:
329 if staged_diffed_line.has_received:
330 staged_diffed_line.diff_b = line
331 elif staged_diffed_line.has_snapshot:
332 staged_diffed_line.diff_a = line
333 # else: should never happen because then it would have
334 # encounted a diff line without any previously staged line
335 else:
336 should_unstage = (
337 staged_diffed_line.is_complete
338 or (staged_diffed_line.has_snapshot and is_snapshot_line)
339 or (staged_diffed_line.has_received and is_received_line)
340 or (staged_diffed_line.is_context and not is_context_line)
341 )
342 if should_unstage:
343 yield staged_diffed_line
344 staged_diffed_line = None
345 elif is_snapshot_line:
346 staged_diffed_line.a = line
347 elif is_received_line:
348 staged_diffed_line.b = line
349 elif is_context_line:
350 staged_diffed_line.c.append(line)
351
352 if not staged_diffed_line:
353 if is_snapshot_line:
354 staged_diffed_line = DiffedLine(a=line)
355 elif is_received_line:
356 staged_diffed_line = DiffedLine(b=line)
357 elif is_context_line:
358 staged_diffed_line = DiffedLine(c=[line])
359 # else: should never happen because then it would have
360 # encounted a diff line without any previously staged line
361
362 if staged_diffed_line:
363 yield staged_diffed_line
364
365 def __format_line(
366 self,
367 line: str,
368 diff_markers: str,
369 line_style: Callable[[str], str],
370 diff_style: Callable[[str], str],
371 show_ends: bool,
372 ) -> str:
373 if show_ends:
374 for old, new in self._ends.items():
375 line = line.replace(old, new)
376 else:
377 line = self.__strip_ends(line)
378 return "".join(
379 diff_style(char) if str(marker) in "-+^" else line_style(char)
380 for marker, char in zip_longest(diff_markers.rstrip(), line)
381 if char is not None
382 )
383
384 def __limit_context(self, lines: list[str]) -> Iterator[str]:
385 yield from lines[: self._context_line_count]
386 num_lines = len(lines)
387 if num_lines:
388 if num_lines > self._context_line_max:
389 if self._context_line_count:
390 num_space = (
391 _count_leading_whitespace(lines[self._context_line_count - 1])
392 + _count_leading_whitespace(lines[-self._context_line_count])
393 ) // 2
394 else:
395 num_space = _count_leading_whitespace(lines[num_lines // 2])
396 yield " " * num_space + self._marker_context_max
397 if self._context_line_count and num_lines > 1:
398 yield from lines[-self._context_line_count :] # noqa: E203
399
400 def __strip_ends(self, line: str) -> str:
401 return line.rstrip("".join(self._ends.keys()))
402
403
404 class SnapshotComparator:
405 def matches(
406 self,
407 *,
408 serialized_data: "SerializableData",
409 snapshot_data: "SerializableData",
410 ) -> bool:
411 """
412 Compares serialized data and snapshot data and returns
413 whether they match.
414 """
415 return bool(serialized_data == snapshot_data)
416
417
418 class AbstractSyrupyExtension(
419 SnapshotSerializer, SnapshotCollectionStorage, SnapshotReporter, SnapshotComparator
420 ):
421 pass