| 1 |
import traceback |
| 2 |
from collections import namedtuple |
| 3 |
from collections.abc import Callable |
| 4 |
from dataclasses import ( |
| 5 |
dataclass, |
| 6 |
field, |
| 7 |
) |
| 8 |
from enum import Enum |
| 9 |
from gettext import gettext |
| 10 |
from typing import ( |
| 11 |
TYPE_CHECKING, |
| 12 |
Any, |
| 13 |
Optional, |
| 14 |
) |
| 15 |
|
| 16 |
from .exceptions import ( |
| 17 |
SnapshotDoesNotExist, |
| 18 |
TaintedSnapshotError, |
| 19 |
) |
| 20 |
from .extensions.amber.serializer import Repr |
| 21 |
|
| 22 |
if TYPE_CHECKING: |
| 23 |
from .extensions.base import AbstractSyrupyExtension |
| 24 |
from .location import PyTestLocation |
| 25 |
from .session import SnapshotSession |
| 26 |
from .types import ( |
| 27 |
PropertyFilter, |
| 28 |
PropertyMatcher, |
| 29 |
PropertyPath, |
| 30 |
SerializableData, |
| 31 |
SerializedData, |
| 32 |
SnapshotIndex, |
| 33 |
) |
| 34 |
|
| 35 |
|
| 36 |
class DiffMode(Enum): |
| 37 |
DETAILED = "detailed" |
| 38 |
DISABLED = "disabled" |
| 39 |
|
| 40 |
def __str__(self) -> str: |
| 41 |
return self.value |
| 42 |
|
| 43 |
|
| 44 |
@dataclass |
| 45 |
class AssertionResult: |
| 46 |
snapshot_location: str |
| 47 |
snapshot_name: str |
| 48 |
asserted_data: Optional["SerializedData"] |
| 49 |
recalled_data: Optional["SerializedData"] |
| 50 |
created: bool |
| 51 |
updated: bool |
| 52 |
success: bool |
| 53 |
exception: Exception | None |
| 54 |
test_location: "PyTestLocation" |
| 55 |
|
| 56 |
@property |
| 57 |
def final_data(self) -> Optional["SerializedData"]: |
| 58 |
if self.created or self.updated: |
| 59 |
return self.asserted_data |
| 60 |
return self.recalled_data |
| 61 |
|
| 62 |
|
| 63 |
@dataclass(eq=False, order=False, repr=False) |
| 64 |
class SnapshotAssertion: |
| 65 |
session: "SnapshotSession" |
| 66 |
extension_class: type["AbstractSyrupyExtension"] |
| 67 |
test_location: "PyTestLocation" |
| 68 |
update_snapshots: bool |
| 69 |
update_new_snapshots_only: bool = False |
| 70 |
include: Optional["PropertyFilter"] = None |
| 71 |
exclude: Optional["PropertyFilter"] = None |
| 72 |
matcher: Optional["PropertyMatcher"] = None |
| 73 |
|
| 74 |
_exclude: Optional["PropertyFilter"] = field( |
| 75 |
init=False, |
| 76 |
default=None, |
| 77 |
) |
| 78 |
_include: Optional["PropertyFilter"] = field( |
| 79 |
init=False, |
| 80 |
default=None, |
| 81 |
) |
| 82 |
_custom_index: str | None = field( |
| 83 |
init=False, |
| 84 |
default=None, |
| 85 |
) |
| 86 |
_extension: Optional["AbstractSyrupyExtension"] = field( |
| 87 |
init=False, |
| 88 |
default=None, |
| 89 |
) |
| 90 |
_executions: int = field( |
| 91 |
init=False, |
| 92 |
default=0, |
| 93 |
) |
| 94 |
_execution_results: dict[int, "AssertionResult"] = field( |
| 95 |
init=False, |
| 96 |
default_factory=dict, |
| 97 |
) |
| 98 |
_execution_name_index: dict["SnapshotIndex", int] = field( |
| 99 |
init=False, default_factory=dict |
| 100 |
) |
| 101 |
_matcher: Optional["PropertyMatcher"] = field( |
| 102 |
init=False, |
| 103 |
default=None, |
| 104 |
) |
| 105 |
_post_assert_actions: list[Callable[..., None]] = field( |
| 106 |
init=False, |
| 107 |
default_factory=list, |
| 108 |
) |
| 109 |
|
| 110 |
def __post_init__(self) -> None: |
| 111 |
self.session.register_request(self) |
| 112 |
self._include = self.include |
| 113 |
self._exclude = self.exclude |
| 114 |
self._matcher = self.matcher |
| 115 |
|
| 116 |
def __init_extension( |
| 117 |
self, extension_class: type["AbstractSyrupyExtension"] |
| 118 |
) -> "AbstractSyrupyExtension": |
| 119 |
return extension_class() |
| 120 |
|
| 121 |
@property |
| 122 |
def extension(self) -> "AbstractSyrupyExtension": |
| 123 |
if not self._extension: |
| 124 |
self._extension = self.__init_extension(self.extension_class) |
| 125 |
return self._extension |
| 126 |
|
| 127 |
@property |
| 128 |
def num_executions(self) -> int: |
| 129 |
return int(self._executions) |
| 130 |
|
| 131 |
@property |
| 132 |
def executions(self) -> dict[int, "AssertionResult"]: |
| 133 |
return self._execution_results |
| 134 |
|
| 135 |
@property |
| 136 |
def index(self) -> "SnapshotIndex": |
| 137 |
if self._custom_index: |
| 138 |
return self._custom_index |
| 139 |
return self.num_executions |
| 140 |
|
| 141 |
@property |
| 142 |
def name(self) -> str: |
| 143 |
return self._custom_index or "snapshot" |
| 144 |
|
| 145 |
@property |
| 146 |
def __repr(self) -> "SerializableData": |
| 147 |
SnapshotAssertionRepr = namedtuple( # type: ignore |
| 148 |
"SnapshotAssertion", ["name", "num_executions"] |
| 149 |
) |
| 150 |
execution_index = ( |
| 151 |
self._custom_index and self._execution_name_index.get(self._custom_index) |
| 152 |
) or self.num_executions - 1 |
| 153 |
assertion_result = self.executions.get(execution_index) |
| 154 |
return ( |
| 155 |
Repr(str(assertion_result.final_data)) |
| 156 |
if execution_index in self.executions |
| 157 |
and assertion_result |
| 158 |
and assertion_result.final_data is not None |
| 159 |
else SnapshotAssertionRepr( |
| 160 |
name=self.name, |
| 161 |
num_executions=self.num_executions, |
| 162 |
) |
| 163 |
) |
| 164 |
|
| 165 |
@property |
| 166 |
def __matcher(self) -> "PropertyMatcher": |
| 167 |
""" |
| 168 |
Get matcher that replaces `SnapshotAssertion` with one that can be serialized |
| 169 |
""" |
| 170 |
|
| 171 |
def _matcher( |
| 172 |
*, data: "SerializableData", path: "PropertyPath" |
| 173 |
) -> Optional["SerializableData"]: |
| 174 |
if isinstance(data, SnapshotAssertion): |
| 175 |
return data.__repr |
| 176 |
if self._matcher: |
| 177 |
return self._matcher(data=data, path=path) |
| 178 |
return data |
| 179 |
|
| 180 |
return _matcher |
| 181 |
|
| 182 |
def with_defaults( |
| 183 |
self, |
| 184 |
*, |
| 185 |
exclude: Optional["PropertyFilter"] = None, |
| 186 |
include: Optional["PropertyFilter"] = None, |
| 187 |
matcher: Optional["PropertyMatcher"] = None, |
| 188 |
extension_class: type["AbstractSyrupyExtension"] | None = None, |
| 189 |
) -> "SnapshotAssertion": |
| 190 |
""" |
| 191 |
Create new snapshot assertion fixture with provided values. This preserves |
| 192 |
provided values between assertions. |
| 193 |
""" |
| 194 |
return self.__class__( |
| 195 |
matcher=matcher or self.matcher, |
| 196 |
include=include or self.include, |
| 197 |
exclude=exclude or self.exclude, |
| 198 |
update_snapshots=self.update_snapshots, |
| 199 |
update_new_snapshots_only=self.update_new_snapshots_only, |
| 200 |
test_location=self.test_location, |
| 201 |
extension_class=extension_class or self.extension_class, |
| 202 |
session=self.session, |
| 203 |
) |
| 204 |
|
| 205 |
def use_extension( |
| 206 |
self, extension_class: type["AbstractSyrupyExtension"] | None = None |
| 207 |
) -> "SnapshotAssertion": |
| 208 |
""" |
| 209 |
Create new snapshot assertion fixture with the same options but using |
| 210 |
specified extension class. This does not preserve assertion index or state. |
| 211 |
""" |
| 212 |
return self.with_defaults(extension_class=extension_class) |
| 213 |
|
| 214 |
def assert_match(self, data: "SerializableData") -> None: |
| 215 |
assert self == data |
| 216 |
|
| 217 |
def _serialize(self, data: "SerializableData") -> "SerializedData": |
| 218 |
return self.extension.serialize( |
| 219 |
data, exclude=self._exclude, include=self._include, matcher=self.__matcher |
| 220 |
) |
| 221 |
|
| 222 |
def get_assert_diff( |
| 223 |
self, *, diff_mode: "DiffMode" = DiffMode.DETAILED |
| 224 |
) -> list[str]: |
| 225 |
assertion_result = self._execution_results[self.num_executions - 1] |
| 226 |
if assertion_result.exception: |
| 227 |
if isinstance(assertion_result.exception, (TaintedSnapshotError,)): |
| 228 |
lines = [ |
| 229 |
gettext( |
| 230 |
"This snapshot needs to be regenerated. " |
| 231 |
"This is typically due to a major Syrupy update." |
| 232 |
) |
| 233 |
] |
| 234 |
else: |
| 235 |
lines = [ |
| 236 |
line |
| 237 |
for lines in traceback.format_exception( |
| 238 |
assertion_result.exception.__class__, |
| 239 |
assertion_result.exception, |
| 240 |
assertion_result.exception.__traceback__, |
| 241 |
) |
| 242 |
for line in lines.splitlines() |
| 243 |
] |
| 244 |
# Rotate to place exception with message at first line |
| 245 |
return lines[-1:] + lines[:-1] |
| 246 |
snapshot_data = assertion_result.recalled_data |
| 247 |
serialized_data = ( |
| 248 |
assertion_result.asserted_data |
| 249 |
if assertion_result.asserted_data is not None |
| 250 |
else "" |
| 251 |
) |
| 252 |
diff: list[str] = [] |
| 253 |
if snapshot_data is None: |
| 254 |
diff.append( |
| 255 |
gettext("Snapshot '{}' does not exist!").format( |
| 256 |
assertion_result.snapshot_name |
| 257 |
) |
| 258 |
) |
| 259 |
if not assertion_result.success: |
| 260 |
snapshot_data = snapshot_data if snapshot_data is not None else "" |
| 261 |
if diff_mode == DiffMode.DETAILED: |
| 262 |
diff.extend(self.extension.diff_lines(serialized_data, snapshot_data)) |
| 263 |
return diff |
| 264 |
|
| 265 |
def __with_prop(self, prop_name: str, prop_value: Any) -> None: |
| 266 |
_value = getattr(self, prop_name, None) |
| 267 |
setattr(self, prop_name, prop_value) |
| 268 |
self._post_assert_actions.append(lambda: setattr(self, prop_name, _value)) |
| 269 |
|
| 270 |
def __call__( |
| 271 |
self, |
| 272 |
*, |
| 273 |
diff: Optional["SnapshotIndex"] = None, |
| 274 |
exclude: Optional["PropertyFilter"] = None, |
| 275 |
include: Optional["PropertyFilter"] = None, |
| 276 |
extension_class: type["AbstractSyrupyExtension"] | None = None, |
| 277 |
matcher: Optional["PropertyMatcher"] = None, |
| 278 |
name: Optional["SnapshotIndex"] = None, |
| 279 |
) -> "SnapshotAssertion": |
| 280 |
""" |
| 281 |
Modifies assertion instance options |
| 282 |
""" |
| 283 |
if exclude: |
| 284 |
self.__with_prop("_exclude", exclude) |
| 285 |
if include: |
| 286 |
self.__with_prop("_include", include) |
| 287 |
if extension_class: |
| 288 |
self.__with_prop("_extension", self.__init_extension(extension_class)) |
| 289 |
if matcher: |
| 290 |
self.__with_prop("_matcher", matcher) |
| 291 |
if name: |
| 292 |
self.__with_prop("_custom_index", name) |
| 293 |
if diff is not None: |
| 294 |
self.__with_prop("_snapshot_diff", diff) |
| 295 |
return self |
| 296 |
|
| 297 |
def __repr__(self) -> str: |
| 298 |
return str(self.__repr) |
| 299 |
|
| 300 |
def __eq__(self, other: "SerializableData") -> bool: |
| 301 |
return self._assert(other) |
| 302 |
|
| 303 |
def _assert(self, data: "SerializableData") -> bool: |
| 304 |
snapshot_location = self.extension.get_location( |
| 305 |
test_location=self.test_location, index=self.index |
| 306 |
) |
| 307 |
snapshot_name = self.extension.get_snapshot_name( |
| 308 |
test_location=self.test_location, index=self.index |
| 309 |
) |
| 310 |
snapshot_data: SerializedData | None = None |
| 311 |
serialized_data: SerializedData | None = None |
| 312 |
matches = False |
| 313 |
assertion_success = False |
| 314 |
assertion_exception = None |
| 315 |
try: |
| 316 |
snapshot_data, tainted = self._recall_data(index=self.index) |
| 317 |
serialized_data = self._serialize(data) |
| 318 |
snapshot_diff = getattr(self, "_snapshot_diff", None) |
| 319 |
if snapshot_diff is not None: |
| 320 |
snapshot_data_diff, _ = self._recall_data(index=snapshot_diff) |
| 321 |
if snapshot_data_diff is None: |
| 322 |
raise SnapshotDoesNotExist() |
| 323 |
serialized_data = self.extension.diff_snapshots( |
| 324 |
serialized_data=serialized_data, |
| 325 |
snapshot_data=snapshot_data_diff, |
| 326 |
) |
| 327 |
matches = ( |
| 328 |
not tainted |
| 329 |
and snapshot_data is not None |
| 330 |
and self.extension.matches( |
| 331 |
serialized_data=serialized_data, snapshot_data=snapshot_data |
| 332 |
) |
| 333 |
) |
| 334 |
assertion_success = matches |
| 335 |
if not matches: |
| 336 |
should_write_new_only = ( |
| 337 |
self.update_new_snapshots_only and snapshot_data is None |
| 338 |
) |
| 339 |
if self.update_snapshots or should_write_new_only: |
| 340 |
self.session.queue_snapshot_write( |
| 341 |
extension=self.extension, |
| 342 |
test_location=self.test_location, |
| 343 |
data=serialized_data, |
| 344 |
index=self.index, |
| 345 |
) |
| 346 |
assertion_success = True |
| 347 |
elif tainted: |
| 348 |
raise TaintedSnapshotError |
| 349 |
return assertion_success |
| 350 |
except Exception as e: |
| 351 |
assertion_exception = e |
| 352 |
return False |
| 353 |
finally: |
| 354 |
snapshot_created = snapshot_data is None and assertion_success |
| 355 |
snapshot_updated = matches is False and assertion_success |
| 356 |
self._execution_name_index[self.index] = self._executions |
| 357 |
self._execution_results[self._executions] = AssertionResult( |
| 358 |
asserted_data=serialized_data, |
| 359 |
created=snapshot_created, |
| 360 |
exception=assertion_exception, |
| 361 |
recalled_data=snapshot_data, |
| 362 |
snapshot_location=snapshot_location, |
| 363 |
snapshot_name=snapshot_name, |
| 364 |
success=assertion_success, |
| 365 |
test_location=self.test_location, |
| 366 |
updated=snapshot_updated, |
| 367 |
) |
| 368 |
self._executions += 1 |
| 369 |
self._post_assert() |
| 370 |
|
| 371 |
def _post_assert(self) -> None: |
| 372 |
""" |
| 373 |
Restores assertion instance options |
| 374 |
""" |
| 375 |
while self._post_assert_actions: |
| 376 |
self._post_assert_actions.pop()() |
| 377 |
|
| 378 |
def _recall_data( |
| 379 |
self, index: "SnapshotIndex" |
| 380 |
) -> tuple[Optional["SerializableData"], bool]: |
| 381 |
try: |
| 382 |
return ( |
| 383 |
self.session.recall_snapshot(self.extension, self.test_location, index), |
| 384 |
False, |
| 385 |
) |
| 386 |
except SnapshotDoesNotExist: |
| 387 |
return None, False |
| 388 |
except TaintedSnapshotError as e: |
| 389 |
return e.snapshot_data, True |