Debian Codegraph @

src/syrupy/matchers.py

raw
1 import re
2 from collections.abc import Callable
3 from gettext import gettext
4 from typing import (
5 TYPE_CHECKING,
6 Any,
7 Optional,
8 )
9
10 from syrupy.extensions.amber.serializer import (
11 AmberDataSerializer,
12 Repr,
13 )
14
15 if TYPE_CHECKING:
16 from syrupy.types import (
17 PropertyMatcher,
18 PropertyPath,
19 PropertyValueType,
20 SerializableData,
21 )
22
23 try:
24 MatchResult = re.Match[str] | None
25 except TypeError:
26 globals()["MatchResult"] = re.Match | None
27 Replacer = Callable[[SerializableData, MatchResult], SerializableData]
28
29
30 class PathTypeError(TypeError):
31 pass
32
33
34 class StrictPathTypeError(PathTypeError):
35 pass
36
37
38 def path_type(
39 mapping: dict[str, tuple["PropertyValueType", ...]] | None = None,
40 *,
41 types: tuple["PropertyValueType", ...] = (),
42 strict: bool = True,
43 regex: bool = False,
44 replacer: "Replacer" = lambda data, _: Repr(AmberDataSerializer.object_type(data)),
45 ) -> "PropertyMatcher":
46 """
47 Factory to create a matcher using path and type mapping.
48 Usecase:
49 Replacing all values of certain types at specified paths.
50 with their class name instead. Allows for deterministic
51 snapshots on non-deterministic class e.g. datetime, random etc.
52 """
53 if not mapping and not types:
54 raise PathTypeError(gettext("Both mapping and types argument cannot be empty"))
55
56 def path_type_matcher(
57 *, data: "SerializableData", path: "PropertyPath"
58 ) -> Optional["SerializableData"]:
59 path_str = ".".join(str(p) for p, _ in path)
60 if mapping:
61 for pattern in mapping:
62 matches = _path_match(path_str, pattern, regex)
63 if matches:
64 for type_to_match in mapping[pattern]:
65 if isinstance(data, type_to_match):
66 return replacer(data, matches)
67 if strict:
68 raise StrictPathTypeError(
69 gettext(
70 "{} at '{}' of type {} does not "
71 "match any of the expected types: {}"
72 ).format(data, path_str, data.__class__, mapping[pattern])
73 )
74 for type_to_match in types:
75 if isinstance(data, type_to_match):
76 return replacer(data, None)
77 return data
78
79 return path_type_matcher
80
81
82 def path_value(
83 mapping: dict[str, str],
84 *,
85 types: tuple["PropertyValueType", ...],
86 replacer: "Replacer",
87 **kwargs: Any,
88 ) -> "PropertyMatcher":
89 """
90 Matches the path regex against the string repr of values for the types specified
91 """
92
93 kwargs["mapping"] = dict.fromkeys(mapping, types)
94 kwargs["replacer"] = lambda data, path_matches: (
95 replacer(
96 data,
97 _path_match(
98 str(data), mapping[path_matches.re.pattern], kwargs.get("regex", False)
99 ),
100 )
101 if path_matches.re.pattern in mapping
102 else data
103 )
104 return path_type(**kwargs)
105
106
107 def _path_match(path: str, pattern: str, is_regex: bool) -> "MatchResult":
108 """Match path against regular string or regex pattern"""
109 if not is_regex:
110 pattern = re.escape(pattern)
111 return re.fullmatch(pattern, path)
112
113
114 def compose_matchers(*matchers: "PropertyMatcher") -> "PropertyMatcher":
115 """
116 Composes 1 or more matchers into a single matcher.
117 """
118
119 def _matcher(
120 *, data: "SerializableData", path: "PropertyPath"
121 ) -> Optional["SerializableData"]:
122 for matcher in matchers:
123 try:
124 data = matcher(data=data, path=path)
125 except StrictPathTypeError:
126 # ignore strict mode when composing matchers
127 pass
128
129 return data
130
131 return _matcher