Debian Codegraph @

src/syrupy/extensions/amber/serializer.py

raw
1 import collections
2 import inspect
3 from abc import ABC, abstractmethod
4 from collections import OrderedDict
5 from collections.abc import Callable, Generator, Iterable
6 from types import (
7 FunctionType,
8 GeneratorType,
9 MappingProxyType,
10 )
11 from typing import (
12 TYPE_CHECKING,
13 Any,
14 NamedTuple,
15 Optional,
16 )
17
18 from syrupy.constants import (
19 SYMBOL_ELLIPSIS,
20 TEXT_ENCODING,
21 )
22 from syrupy.data import (
23 Snapshot,
24 SnapshotCollection,
25 )
26
27 if TYPE_CHECKING:
28 from syrupy.types import (
29 PropertyFilter,
30 PropertyMatcher,
31 PropertyName,
32 PropertyPath,
33 SerializableData,
34 )
35
36 PropertyValueFilter = Callable[["PropertyName"], bool]
37 PropertyValueGetter = Callable[
38 ["SerializableData", "PropertyName"], "SerializableData"
39 ]
40 IterableEntries = tuple[
41 Iterable["PropertyName"],
42 "PropertyValueGetter",
43 "PropertyValueFilter | None",
44 ]
45
46
47 class Repr:
48 def __init__(self, _repr: str):
49 self._repr = _repr
50
51 def __repr__(self) -> str:
52 return self._repr
53
54
55 def attr_getter(o: "SerializableData", p: "PropertyName") -> "SerializableData":
56 return getattr(o, str(p))
57
58
59 def item_getter(o: "SerializableData", p: "PropertyName") -> "SerializableData":
60 return o[p]
61
62
63 class MalformedAmberFile(Exception):
64 """
65 The Amber file is malformed. It should be deleted and regenerated.
66 """
67
68
69 class MissingVersionError(Exception):
70 """
71 Missing Amber version marker.
72 """
73
74
75 def removesuffix(string: str, suffix: str) -> str:
76 """
77 Can be replaced with str.removesuffix once Py3.8 support is dropped.
78 """
79
80 if string.endswith(suffix):
81 return string[: -len(suffix)]
82 return string
83
84
85 class AmberDataSerializerPlugin(ABC):
86 """
87 A Syrupy plugin for extending Amber serialization.
88 """
89
90 @classmethod
91 @abstractmethod
92 def is_data_serializable(cls, data: "SerializableData") -> bool:
93 """
94 Determine if this plugin can serialize the given data.
95 """
96 pass
97
98 @classmethod
99 @abstractmethod
100 def serialize(cls, data: "SerializableData", **kwargs: Any) -> str:
101 """
102 Return the serialization method for the given data.
103 """
104 pass
105
106
107 class AmberDataSerializer:
108 """
109 If extending the serializer, change the VERSION property to some unique value
110 for your iteration of the serializer so as to force invalidation of existing
111 snapshots.
112 """
113
114 VERSION = "1"
115
116 serializer_plugins: Iterable[type["AmberDataSerializerPlugin"]] | None = None
117
118 _indent: str = " "
119 _max_depth: int = 99
120 _marker_prefix = "# "
121
122 class Marker:
123 Version = "serializer version"
124 Name = "name"
125 Divider = "---"
126
127 @classmethod
128 def snapshot_sort_key(cls, snapshot: "Snapshot") -> Any:
129 return snapshot.name
130
131 @classmethod
132 def write_file(
133 cls, snapshot_collection: "SnapshotCollection", merge: bool = False
134 ) -> None:
135 """
136 Writes the snapshot data into the snapshot file that can be read later.
137 """
138 filepath = snapshot_collection.location
139 if merge:
140 base_snapshot = cls.read_file(filepath)
141 base_snapshot.merge(snapshot_collection)
142 snapshot_collection = base_snapshot
143
144 with open(filepath, "w", encoding=TEXT_ENCODING, newline=None) as f:
145 f.write(f"{cls._marker_prefix}{cls.Marker.Version}: {cls.VERSION}\n")
146 for snapshot in sorted(
147 snapshot_collection,
148 key=cls.snapshot_sort_key, # noqa: E501
149 ):
150 snapshot_data = str(snapshot.data)
151 if snapshot_data is not None:
152 f.write(f"{cls._marker_prefix}{cls.Marker.Name}: {snapshot.name}\n")
153 # Split on \n only. We avoid str.splitlines() because it
154 # also splits on \x0b, \x0c, \x1c-\x1e, \x85, \u2028,
155 # and \u2029, but the file reader (which iterates lines
156 # from the file object) only splits on \n, \r, and \r\n.
157 parts = snapshot_data.split("\n")
158 for i, part in enumerate(parts):
159 is_last = i == len(parts) - 1
160 if not is_last:
161 f.write(cls.with_indent(part + "\n", 1))
162 elif part:
163 f.write(cls.with_indent(part, 1))
164 if snapshot_data.endswith("\n"):
165 f.write(cls.with_indent("", 1))
166 f.write(f"\n{cls._marker_prefix}{cls.Marker.Divider}\n")
167
168 @classmethod
169 def __read_file_with_markers(
170 cls, filepath: str
171 ) -> Generator["Snapshot", None, None]:
172 marker_offset = len(cls._marker_prefix)
173 indent_len = len(cls._indent)
174
175 test_name = None
176 snapshot_data = ""
177 tainted = False
178 missing_version = True
179
180 try:
181 with open(filepath, encoding=TEXT_ENCODING, newline=None) as f:
182 for line_no, line in enumerate(f):
183 if line.startswith(cls._marker_prefix):
184 marker_key, *marker_rest = line[marker_offset:].split(
185 ":", maxsplit=1
186 )
187 marker_key = marker_key.rstrip(" \r\n")
188 marker_value = marker_rest[0].strip() if marker_rest else None
189
190 if marker_key == cls.Marker.Version:
191 if line_no:
192 raise MalformedAmberFile(
193 "Version must be specified at the top of the file."
194 )
195 if not marker_value or marker_value != cls.VERSION:
196 tainted = True
197 continue
198 missing_version = False
199
200 if marker_key == cls.Marker.Name:
201 if not marker_value:
202 raise MalformedAmberFile("Missing snapshot name.")
203
204 test_name = marker_value.strip(" \r\n")
205 continue
206 if marker_key == cls.Marker.Divider:
207 if test_name and snapshot_data:
208 yield Snapshot(
209 name=test_name,
210 data=removesuffix(snapshot_data, "\r\n")
211 if snapshot_data.endswith("\r\n")
212 else removesuffix(snapshot_data, "\n"),
213 tainted=tainted,
214 )
215 test_name = None
216 snapshot_data = ""
217 elif test_name is not None and line.startswith(cls._indent):
218 snapshot_data += line[indent_len:]
219 except FileNotFoundError:
220 pass
221 else:
222 if missing_version:
223 raise MissingVersionError
224
225 @classmethod
226 def read_file(cls, filepath: str) -> "SnapshotCollection":
227 """
228 Read the raw snapshot data (str) from the snapshot file into a dict
229 of snapshot name to raw data. This does not attempt any deserialization
230 of the snapshot data.
231 """
232 snapshot_collection = SnapshotCollection(location=filepath)
233 try:
234 for snapshot in cls.__read_file_with_markers(filepath):
235 if snapshot.tainted:
236 snapshot_collection.tainted = True
237 snapshot_collection.add(snapshot)
238 except MissingVersionError:
239 snapshot_collection.tainted = True
240
241 return snapshot_collection
242
243 @classmethod
244 def serialize(
245 cls,
246 data: "SerializableData",
247 *,
248 exclude: Optional["PropertyFilter"] = None,
249 include: Optional["PropertyFilter"] = None,
250 matcher: Optional["PropertyMatcher"] = None,
251 ) -> str:
252 """
253 After serializing, new line control characters are normalised. This is needed
254 for interoperablity of snapshot matching between systems that do not use the
255 same new line control characters. Example snapshots generated on windows os
256 should not break when running the tests on a unix based system and vice versa.
257 """
258 serialized = cls._serialize(
259 data, exclude=exclude, include=include, matcher=matcher
260 )
261 return serialized.replace("\r\n", "\n").replace("\r", "\n")
262
263 @classmethod
264 def _serialize(
265 cls,
266 data: "SerializableData",
267 *,
268 depth: int = 0,
269 exclude: Optional["PropertyFilter"] = None,
270 include: Optional["PropertyFilter"] = None,
271 matcher: Optional["PropertyMatcher"] = None,
272 path: "PropertyPath" = (),
273 visited: set[Any] | None = None,
274 ) -> str:
275 visited = set() if visited is None else visited
276 data_id = id(data)
277 # Track ancestors in one shared set and unwind after recursing, instead
278 # of copying the set at every node.
279 already_visited = data_id in visited
280 if depth > cls._max_depth or already_visited:
281 data = Repr(SYMBOL_ELLIPSIS)
282 elif matcher:
283 data = matcher(data=data, path=path)
284 if not already_visited:
285 visited.add(data_id)
286 try:
287 serialize_method = cls._assign_serialize_method(data)
288 return serialize_method(
289 data=data,
290 depth=depth,
291 exclude=exclude,
292 include=include,
293 matcher=matcher,
294 path=path,
295 visited=visited,
296 )
297 finally:
298 if not already_visited:
299 visited.discard(data_id)
300
301 @classmethod
302 def _assign_serialize_method(cls, data: "SerializableData") -> Callable[..., str]:
303 if cls.serializer_plugins:
304 for plugin in cls.serializer_plugins:
305 if plugin.is_data_serializable(data):
306 return plugin.serialize
307
308 if isinstance(data, str):
309 return cls.serialize_string
310 elif isinstance(data, (int, float)):
311 return cls.serialize_number
312 elif isinstance(data, (set, frozenset)):
313 return cls.serialize_set
314 elif isinstance(data, (dict, MappingProxyType)):
315 return cls.serialize_dict
316 elif cls.__is_namedtuple(data):
317 return cls.serialize_namedtuple
318 elif isinstance(data, (list, tuple, GeneratorType)):
319 return cls.serialize_iterable
320 elif isinstance(data, FunctionType):
321 return cls.serialize_function
322 return cls.serialize_unknown
323
324 @classmethod
325 def serialize_number(
326 cls,
327 data: int | float,
328 *,
329 depth: int = 0,
330 exclude: Optional["PropertyFilter"] = None,
331 include: Optional["PropertyFilter"] = None,
332 matcher: Optional["PropertyMatcher"] = None,
333 path: "PropertyPath" = (),
334 visited: set[Any] | None = None,
335 ) -> str:
336 return cls.__serialize_plain(data=data, depth=depth)
337
338 @classmethod
339 def serialize_string(
340 cls,
341 data: str,
342 *,
343 depth: int = 0,
344 exclude: Optional["PropertyFilter"] = None,
345 include: Optional["PropertyFilter"] = None,
346 matcher: Optional["PropertyMatcher"] = None,
347 path: "PropertyPath" = (),
348 visited: set[Any] | None = None,
349 ) -> str:
350 if "\n" not in data and "\r" not in data:
351 return cls.__serialize_plain(data=data, depth=depth)
352
353 return cls.__serialize_lines(
354 data=data,
355 lines=(
356 cls.with_indent(line, depth + 1 if depth else depth)
357 for line in data.splitlines(keepends=True)
358 ),
359 depth=depth,
360 open_tag="'''",
361 close_tag="'''",
362 include_type=False,
363 ends="",
364 )
365
366 @classmethod
367 def serialize_iterable(
368 cls,
369 data: Iterable["SerializableData"],
370 *,
371 depth: int = 0,
372 exclude: Optional["PropertyFilter"] = None,
373 include: Optional["PropertyFilter"] = None,
374 matcher: Optional["PropertyMatcher"] = None,
375 path: "PropertyPath" = (),
376 visited: set[Any] | None = None,
377 ) -> str:
378 open_paren, close_paren = (None, None)
379 if isinstance(data, list):
380 open_paren, close_paren = ("[", "]")
381
382 values = list(data)
383 return cls.serialize_custom_iterable(
384 data=data,
385 resolve_entries=(range(len(values)), item_getter, None),
386 open_paren=open_paren,
387 close_paren=close_paren,
388 depth=depth,
389 exclude=exclude,
390 include=include,
391 matcher=matcher,
392 path=path,
393 visited=visited,
394 )
395
396 @classmethod
397 def serialize_set(
398 cls,
399 data: set["SerializableData"],
400 *,
401 depth: int = 0,
402 exclude: Optional["PropertyFilter"] = None,
403 include: Optional["PropertyFilter"] = None,
404 matcher: Optional["PropertyMatcher"] = None,
405 path: "PropertyPath" = (),
406 visited: set[Any] | None = None,
407 ) -> str:
408 return cls.serialize_custom_iterable(
409 data=data,
410 resolve_entries=(cls.sort(data), lambda _, p: p, None),
411 open_paren="{",
412 close_paren="}",
413 depth=depth,
414 exclude=exclude,
415 include=include,
416 matcher=matcher,
417 path=path,
418 visited=visited,
419 )
420
421 @classmethod
422 def serialize_namedtuple(
423 cls,
424 data: NamedTuple,
425 *,
426 depth: int = 0,
427 exclude: Optional["PropertyFilter"] = None,
428 include: Optional["PropertyFilter"] = None,
429 matcher: Optional["PropertyMatcher"] = None,
430 path: "PropertyPath" = (),
431 visited: set[Any] | None = None,
432 ) -> str:
433 return cls.serialize_custom_iterable(
434 data=data,
435 resolve_entries=(cls.sort(data._fields), attr_getter, None),
436 separator="=",
437 depth=depth,
438 exclude=exclude,
439 include=include,
440 matcher=matcher,
441 path=path,
442 visited=visited,
443 )
444
445 @classmethod
446 def serialize_dict(
447 cls,
448 data: dict["PropertyName", "SerializableData"],
449 *,
450 depth: int = 0,
451 exclude: Optional["PropertyFilter"] = None,
452 include: Optional["PropertyFilter"] = None,
453 matcher: Optional["PropertyMatcher"] = None,
454 path: "PropertyPath" = (),
455 visited: set[Any] | None = None,
456 ) -> str:
457 keys = (
458 data.keys() if isinstance(data, (OrderedDict,)) else cls.sort(data.keys())
459 )
460
461 return cls.serialize_custom_iterable(
462 data=data,
463 resolve_entries=(keys, item_getter, None),
464 open_paren="{",
465 close_paren="}",
466 separator=": ",
467 serialize_key=True,
468 depth=depth,
469 exclude=exclude,
470 include=include,
471 matcher=matcher,
472 path=path,
473 visited=visited,
474 )
475
476 @classmethod
477 def serialize_function(
478 cls,
479 data: FunctionType,
480 *,
481 depth: int = 0,
482 exclude: Optional["PropertyFilter"] = None,
483 include: Optional["PropertyFilter"] = None,
484 matcher: Optional["PropertyMatcher"] = None,
485 path: "PropertyPath" = (),
486 visited: set[Any] | None = None,
487 ) -> str:
488 return cls.__serialize_plain(
489 data=f"{data.__qualname__}{str(inspect.signature(data))}", depth=depth
490 )
491
492 @classmethod
493 def serialize_unknown(
494 cls,
495 data: Any,
496 *,
497 depth: int = 0,
498 exclude: Optional["PropertyFilter"] = None,
499 include: Optional["PropertyFilter"] = None,
500 matcher: Optional["PropertyMatcher"] = None,
501 path: "PropertyPath" = (),
502 visited: set[Any] | None = None,
503 ) -> str:
504 if data.__class__.__repr__ != object.__repr__:
505 return cls.__serialize_plain(data=data, depth=depth)
506
507 return cls.serialize_custom_iterable(
508 data=data,
509 resolve_entries=(
510 cls.sort(cls.object_attrs(data)),
511 attr_getter,
512 lambda v: not callable(v),
513 ),
514 depth=depth,
515 separator="=",
516 exclude=exclude,
517 include=include,
518 matcher=matcher,
519 path=path,
520 visited=visited,
521 )
522
523 @classmethod
524 def object_attrs(cls, data: Any) -> "Iterable[str]":
525 return (name for name in dir(data) if not name.startswith("_"))
526
527 @classmethod
528 def object_as_named_tuple(cls, data: Any) -> "tuple[Any, ...]":
529 attr_names = list(cls.object_attrs(data))
530 return collections.namedtuple(data.__class__.__name__, attr_names)(
531 **{prop: getattr(data, prop) for prop in attr_names}
532 )
533
534 @classmethod
535 def with_indent(cls, string: str, depth: int) -> str:
536 return f"{cls._indent * depth}{string}"
537
538 @classmethod
539 def sort(cls, iterable: Iterable[Any]) -> Iterable[Any]:
540 try:
541 return sorted(iterable)
542 except TypeError:
543 return sorted(iterable, key=cls._serialize)
544
545 @classmethod
546 def object_type(cls, data: "SerializableData") -> str:
547 return f"{data.__class__.__name__}"
548
549 @classmethod
550 def __is_namedtuple(cls, obj: Any) -> bool:
551 return isinstance(obj, tuple) and all(
552 isinstance(n, (str,)) for n in getattr(obj, "_fields", [None])
553 )
554
555 @classmethod
556 def __serialize_plain(
557 cls,
558 *,
559 data: "SerializableData",
560 depth: int = 0,
561 ) -> str:
562 return cls.with_indent(repr(data), depth)
563
564 @classmethod
565 def serialize_custom_iterable(
566 cls,
567 *,
568 data: "SerializableData",
569 resolve_entries: "IterableEntries",
570 open_paren: str | None = None,
571 close_paren: str | None = None,
572 depth: int = 0,
573 exclude: Optional["PropertyFilter"] = None,
574 include: Optional["PropertyFilter"] = None,
575 matcher: Optional["PropertyMatcher"] = None,
576 path: "PropertyPath" = (),
577 separator: str | None = None,
578 serialize_key: bool = False,
579 visited: set[Any] | None = None,
580 # Kept for backwards compatibility with serializer plugins that forward
581 # extra keyword arguments. All known arguments are bound explicitly above
582 # so the hot path no longer relies on this dict.
583 **kwargs: Any,
584 ) -> str:
585 """
586 Utility to serialize a custom iterable.
587 """
588 child_depth = depth + 1
589
590 keys, get_value, include_value = resolve_entries
591 key_values = (
592 (key, get_value(data, key))
593 for key in keys
594 if (not exclude or not exclude(prop=key, path=path))
595 and (not include or include(prop=key, path=path))
596 )
597 entries = (
598 entry
599 for entry in key_values
600 if not include_value or include_value(entry[1])
601 )
602
603 def key_str(key: "PropertyName") -> str:
604 if separator is None:
605 return ""
606 return (
607 cls._serialize(
608 data=key, depth=child_depth, matcher=matcher, visited=visited
609 )
610 if serialize_key
611 else cls.with_indent(str(key), depth=depth + 1)
612 ) + separator
613
614 def value_str(key: "PropertyName", value: "SerializableData") -> str:
615 serialized = cls._serialize(
616 data=value,
617 depth=child_depth,
618 exclude=exclude,
619 include=include,
620 matcher=matcher,
621 path=(*path, (key, type(value))),
622 visited=visited,
623 )
624 return serialized if separator is None else serialized.lstrip(cls._indent)
625
626 return cls.__serialize_lines(
627 data=data,
628 lines=(f"{key_str(key)}{value_str(key, value)}," for key, value in entries),
629 depth=depth,
630 open_tag=f"({open_paren or ''}",
631 close_tag=f"{close_paren or ''})",
632 )
633
634 @classmethod
635 def __serialize_lines(
636 cls,
637 *,
638 data: "SerializableData",
639 lines: Iterable[str],
640 open_tag: str,
641 close_tag: str,
642 depth: int = 0,
643 include_type: bool = True,
644 ends: str = "\n",
645 ) -> str:
646 lines = ends.join(lines)
647 lines_end = "\n" if lines else ""
648 maybe_obj_type = f"{cls.object_type(data)}" if include_type else ""
649 formatted_open_tag = cls.with_indent(f"{maybe_obj_type}{open_tag}", depth)
650 formatted_close_tag = cls.with_indent(close_tag, depth)
651 return f"{formatted_open_tag}\n{lines}{lines_end}{formatted_close_tag}"
652
653
654 class AmberDataSerializerSorted(AmberDataSerializer):
655 """
656 This is an experimental serializer with known performance issues.
657 """
658
659 VERSION = f"{AmberDataSerializer.VERSION}-sorted"
660
661 @classmethod
662 def __maybe_int(cls, part: str) -> tuple[int, str | int]:
663 try:
664 # cast to int only if the string is the exact representation of the int
665 # for example, '012' != str(int('012'))
666 i = int(part)
667 if str(i) == part:
668 return (1, i)
669 return (0, part)
670 except ValueError:
671 # the nested tuple is to prevent comparing a str to an int
672 return (0, part)
673
674 @classmethod
675 def snapshot_sort_key(cls, snapshot: "Snapshot") -> Any:
676 return [cls.__maybe_int(part) for part in snapshot.name.split(".")]