Debian Codegraph @

src/syrupy/extensions/single_file.py

raw
1 from enum import Enum
2 from gettext import gettext
3 from pathlib import Path
4 from typing import (
5 TYPE_CHECKING,
6 Optional,
7 )
8 from unicodedata import category
9
10 from syrupy.constants import TEXT_ENCODING
11 from syrupy.data import (
12 Snapshot,
13 SnapshotCollection,
14 )
15 from syrupy.exceptions import TaintedSnapshotError
16 from syrupy.extensions.amber.serializer import AmberDataSerializer
17 from syrupy.location import PyTestLocation
18 from syrupy.types import PropertyFilter, PropertyMatcher, SerializableData
19
20 from .base import AbstractSyrupyExtension
21
22 if TYPE_CHECKING:
23 from syrupy.types import (
24 PropertyFilter,
25 PropertyMatcher,
26 SerializableData,
27 SerializedData,
28 SnapshotIndex,
29 )
30
31
32 class WriteMode(Enum):
33 BINARY = "b"
34 TEXT = "t"
35
36 def __str__(self) -> str:
37 return self.value
38
39
40 class SingleFileSnapshotExtension(AbstractSyrupyExtension):
41 _text_encoding = TEXT_ENCODING
42 _write_mode = WriteMode.BINARY
43 file_extension = "raw"
44
45 def serialize(
46 self,
47 data: "SerializableData",
48 *,
49 exclude: Optional["PropertyFilter"] = None,
50 include: Optional["PropertyFilter"] = None,
51 matcher: Optional["PropertyMatcher"] = None,
52 ) -> "SerializedData":
53 supported_dataclass = self.get_supported_dataclass()
54 if supported_dataclass is bytes:
55 try:
56 memoryview(data)
57 except TypeError:
58 raise TypeError(
59 gettext(
60 "Can't serialize '{}' to '{}'. You must convert the data first."
61 ).format(type(data).__name__, supported_dataclass.__name__)
62 ) from None
63 return supported_dataclass(data)
64
65 @classmethod
66 def get_snapshot_name(
67 cls, *, test_location: "PyTestLocation", index: "SnapshotIndex" = 0
68 ) -> str:
69 return cls.__clean_filename(
70 AbstractSyrupyExtension.get_snapshot_name(
71 test_location=test_location, index=index
72 )
73 )
74
75 def delete_snapshots(
76 self, *, snapshot_location: str, snapshot_names: set[str]
77 ) -> None:
78 Path(snapshot_location).unlink()
79
80 @classmethod
81 def get_file_basename(
82 cls, *, test_location: "PyTestLocation", index: "SnapshotIndex"
83 ) -> str:
84 return cls.get_snapshot_name(test_location=test_location, index=index)
85
86 @classmethod
87 def dirname(cls, *, test_location: "PyTestLocation") -> str:
88 original_dirname = AbstractSyrupyExtension.dirname(test_location=test_location)
89 return str(Path(original_dirname).joinpath(test_location.basename))
90
91 def read_snapshot_collection(
92 self, *, snapshot_location: str
93 ) -> "SnapshotCollection":
94 file_ext_len = len(self.file_extension) + 1 if self.file_extension else 0
95 filename_wo_ext = snapshot_location[:-file_ext_len]
96 basename = Path(filename_wo_ext).parts[-1]
97
98 snapshot_collection = SnapshotCollection(location=snapshot_location)
99 snapshot_collection.add(Snapshot(name=basename))
100 return snapshot_collection
101
102 def read_snapshot_data_from_location(
103 self, *, snapshot_location: str, snapshot_name: str, session_id: str
104 ) -> Optional["SerializableData"]:
105 try:
106 with open(
107 snapshot_location,
108 f"r{self._write_mode}",
109 encoding=self.get_write_encoding(),
110 ) as f:
111 return f.read()
112 except FileNotFoundError:
113 return None
114
115 @classmethod
116 def get_supported_dataclass(cls) -> type[str] | type[bytes]:
117 if cls._write_mode == WriteMode.TEXT:
118 return str
119 return bytes
120
121 @classmethod
122 def get_write_encoding(cls) -> str | None:
123 if cls._write_mode == WriteMode.TEXT:
124 return TEXT_ENCODING
125 return None
126
127 @classmethod
128 def write_snapshot_collection(
129 cls, *, snapshot_collection: "SnapshotCollection"
130 ) -> None:
131 filepath, data = (
132 snapshot_collection.location,
133 next(iter(snapshot_collection)).data,
134 )
135 if not isinstance(data, cls.get_supported_dataclass()):
136 error_text = gettext(
137 "Can't write non supported data. Expected '{}', got '{}'"
138 )
139 raise TypeError(
140 error_text.format(
141 cls.get_supported_dataclass().__name__, type(data).__name__
142 )
143 )
144 with open(
145 filepath, f"w{cls._write_mode}", encoding=cls.get_write_encoding()
146 ) as f:
147 f.write(data)
148
149 @classmethod
150 def __clean_filename(cls, filename: str) -> str:
151 max_filename_length = 255 - len(cls.file_extension or "")
152 exclude_chars = '\\/?*:|"<>'
153 exclude_categ = ("C",)
154 cleaned_filename = "".join(
155 c
156 for c in filename
157 if c not in exclude_chars
158 and not any(categ in category(c) for categ in exclude_categ)
159 )
160 return cleaned_filename[:max_filename_length]
161
162
163 class SingleFileAmberSnapshotExtension(SingleFileSnapshotExtension):
164 file_extension = "ambr"
165 _write_mode = WriteMode.TEXT
166
167 def serialize(
168 self,
169 data: "SerializableData",
170 *,
171 exclude: Optional["PropertyFilter"] = None,
172 include: Optional["PropertyFilter"] = None,
173 matcher: Optional["PropertyMatcher"] = None,
174 ) -> "SerializedData":
175 return AmberDataSerializer.serialize(
176 data, exclude=exclude, include=include, matcher=matcher
177 )
178
179 def read_snapshot_data_from_location(
180 self, *, snapshot_location: str, snapshot_name: str, session_id: str
181 ) -> Optional["SerializableData"]:
182 snapshot_collection = AmberDataSerializer.read_file(snapshot_location)
183 if not snapshot_collection or not snapshot_collection.has_snapshots:
184 return None
185
186 snapshot = next(iter(snapshot_collection), None)
187 if not snapshot:
188 return None
189
190 if snapshot_collection.tainted or snapshot.tainted:
191 raise TaintedSnapshotError(snapshot_data=snapshot.data)
192
193 return snapshot.data
194
195 @classmethod
196 def write_snapshot_collection(
197 cls, *, snapshot_collection: "SnapshotCollection"
198 ) -> None:
199 AmberDataSerializer.write_file(snapshot_collection, merge=False)