Debian Codegraph @

src/syrupy/extensions/json/__init__.py

raw
1 # noqa: A005
2 import datetime
3 import inspect
4 import json
5 from collections import OrderedDict
6 from collections.abc import Iterable
7 from types import (
8 FunctionType,
9 GeneratorType,
10 )
11 from typing import (
12 TYPE_CHECKING,
13 Any,
14 Optional,
15 )
16
17 from syrupy.constants import SYMBOL_ELLIPSIS
18 from syrupy.extensions.amber.serializer import Repr
19 from syrupy.extensions.single_file import (
20 SingleFileSnapshotExtension,
21 WriteMode,
22 )
23
24 if TYPE_CHECKING:
25 from syrupy.types import (
26 PropertyFilter,
27 PropertyMatcher,
28 PropertyPath,
29 SerializableData,
30 SerializedData,
31 )
32
33
34 class JSONSnapshotExtension(SingleFileSnapshotExtension):
35 _max_depth: int = 99
36 _write_mode = WriteMode.TEXT
37 file_extension = "json"
38
39 @classmethod
40 def sort(cls, iterable: Iterable[Any]) -> Iterable[Any]:
41 try:
42 return sorted(iterable)
43 except TypeError:
44 return sorted(iterable, key=str)
45
46 @classmethod
47 def __is_namedtuple(cls, obj: Any) -> bool:
48 return isinstance(obj, tuple) and all(
49 isinstance(n, (str,)) for n in getattr(obj, "_fields", [None])
50 )
51
52 @classmethod
53 def _filter(
54 cls,
55 data: "SerializableData",
56 *,
57 depth: int = 0,
58 path: "PropertyPath",
59 exclude: Optional["PropertyFilter"] = None,
60 include: Optional["PropertyFilter"] = None,
61 matcher: Optional["PropertyMatcher"] = None,
62 visited: set[Any] | None = None,
63 ) -> "SerializableData":
64 data_id = id(data)
65 visited = set() if visited is None else visited
66 if depth > cls._max_depth or data_id in visited:
67 data = Repr(SYMBOL_ELLIPSIS)
68 elif matcher:
69 data = matcher(data=data, path=path)
70
71 if isinstance(data, (int, float, str)) or data is None:
72 return data
73
74 filtered_dct: dict[Any, Any]
75 if isinstance(data, (dict,)):
76 filtered_dct = OrderedDict()
77 keys = (
78 cls.sort(data.keys())
79 if not isinstance(data, (OrderedDict,))
80 else data.keys()
81 )
82 for key in keys:
83 value = data[key]
84 if exclude and exclude(prop=key, path=path):
85 continue
86 if include and not include(prop=key, path=path):
87 continue
88 if not isinstance(key, (str,)):
89 continue
90 filtered_dct[key] = cls._filter(
91 data=value,
92 depth=depth + 1,
93 path=(*path, (key, type(value))),
94 exclude=exclude,
95 include=include,
96 matcher=matcher,
97 visited={*visited, data_id},
98 )
99 return filtered_dct
100
101 if cls.__is_namedtuple(data):
102 filtered_dct = OrderedDict()
103 for key in cls.sort(data._fields):
104 value = getattr(data, key)
105 filtered_dct[key] = cls._filter(
106 data=value,
107 depth=depth + 1,
108 path=(*path, (key, type(value))),
109 exclude=exclude,
110 include=include,
111 matcher=matcher,
112 visited={*visited, data_id},
113 )
114 return filtered_dct
115
116 if isinstance(data, (set, frozenset, list, tuple, GeneratorType)):
117 filtered_lst: list[Any] = []
118 iterable = (
119 cls.sort(data) if isinstance(data, (set, frozenset)) else list(data)
120 )
121 for key, value in enumerate(iterable):
122 filtered_lst.append(
123 cls._filter(
124 data=value,
125 depth=depth + 1,
126 path=(*path, (key, type(value))),
127 exclude=exclude,
128 include=include,
129 matcher=matcher,
130 visited={*visited, data_id},
131 )
132 )
133 return filtered_lst
134
135 if isinstance(data, (datetime.datetime,)):
136 return data.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
137
138 if isinstance(data, FunctionType):
139 return (
140 f"<{FunctionType.__name__} "
141 f"{data.__qualname__}{str(inspect.signature(data))}>"
142 )
143
144 if data.__class__.__repr__ != object.__repr__:
145 return repr(data)
146
147 return f"<class '{data.__class__.__name__}'>"
148
149 def serialize(
150 self,
151 data: "SerializableData",
152 *,
153 exclude: Optional["PropertyFilter"] = None,
154 include: Optional["PropertyFilter"] = None,
155 matcher: Optional["PropertyMatcher"] = None,
156 ) -> "SerializedData":
157 data = self._filter(
158 data=data,
159 depth=0,
160 path=(),
161 exclude=exclude,
162 include=include,
163 matcher=matcher,
164 )
165 return json.dumps(data, indent=2, ensure_ascii=False, sort_keys=False) + "\n"