Debian Codegraph @

src/syrupy/patches/pycharm_diff.py

raw
1 import warnings
2 from collections.abc import Iterator
3 from contextlib import contextmanager
4 from functools import wraps
5 from inspect import signature
6 from typing import (
7 Any,
8 )
9
10 from syrupy.assertion import SnapshotAssertion
11
12
13 @contextmanager
14 def patch_pycharm_diff() -> Iterator[None]:
15 """
16 Applies PyCharm diff patch to add Syrupy snapshot support.
17 See: https://github.com/syrupy-project/syrupy/issues/675
18 """
19
20 try:
21 from teamcity.diff_tools import EqualsAssertionError # type: ignore
22 except ImportError:
23 warnings.warn(
24 "Failed to patch PyCharm's diff tools. Skipping patch.",
25 stacklevel=2,
26 )
27 yield
28 return
29
30 old_init = EqualsAssertionError.__init__
31 old_init_signature = signature(old_init)
32
33 @wraps(old_init)
34 def new_init(self: "EqualsAssertionError", *args: Any, **kwargs: Any) -> None:
35 # Extract the __init__ arguments as originally passed in order to
36 # process them later
37 parameters = old_init_signature.bind(self, *args, **kwargs)
38 parameters.apply_defaults()
39
40 expected = parameters.arguments["expected"]
41 actual = parameters.arguments["actual"]
42 real_exception = parameters.arguments["real_exception"]
43
44 if isinstance(expected, SnapshotAssertion):
45 snapshot = expected
46 elif isinstance(actual, SnapshotAssertion):
47 snapshot = actual
48 else:
49 snapshot = None
50
51 old_init(self, *args, **kwargs)
52
53 # No snapshot was involved in the assertion. Let the old logic do its
54 # thing.
55 if snapshot is None:
56 return
57
58 # Although a snapshot was involved in the assertion, it seems the error
59 # was a result of a non-assertion exception (Ex. `assert 1/0`).
60 # Therefore, We will not do anything here either.
61 if real_exception is not None:
62 return
63
64 assertion_result = snapshot.executions[snapshot.num_executions - 1]
65 if assertion_result.exception is not None:
66 return
67
68 self.expected = str(assertion_result.recalled_data)
69 self.actual = str(assertion_result.asserted_data)
70
71 try:
72 EqualsAssertionError.__init__ = new_init
73 yield
74 finally:
75 EqualsAssertionError.__init__ = old_init