Debian Codegraph @

packages/griffelib/tests/test_encoders.py

raw symbols SCIP
1 """Tests for the `encoders` module."""
2
3 from __future__ import annotations
4
5 import json
6 import sys
7 from pathlib import Path
8
9 import pytest
10 from jsonschema import ValidationError, validate
11
12 from griffe import (
13 Attribute,
14 Class,
15 Function,
16 GriffeLoader,
17 Kind,
18 Module,
19 Object,
20 temporary_inspected_package,
21 temporary_visited_module,
22 )
23
24
25 def test_minimal_data_is_enough() -> None:
26 """Test serialization and de-serialization.
27
28 This is an end-to-end test that asserts
29 we can load back a serialized tree and
30 infer as much data as within the original tree.
31 """
32 loader = GriffeLoader()
33 module = loader.load("griffe")
34 dump_options = {"indent": 2, "sort_keys": True}
35 minimal = module.as_json(full=False, **dump_options)
36 full = module.as_json(full=True, **dump_options)
37 reloaded = Module.from_json(minimal)
38 assert reloaded.as_json(full=False, **dump_options) == minimal
39 assert reloaded.as_json(full=True, **dump_options) == full
40
41 # Also works (but will result in a different type hint).
42 assert Object.from_json(minimal)
43
44 # Won't work if the JSON doesn't represent the type requested.
45 with pytest.raises(TypeError, match="provided JSON object is not of type"):
46 Function.from_json(minimal)
47
48
49 def test_namespace_packages() -> None:
50 """Test support for namespace packages.
51
52 Namespace packages are a bit special as they have no `__init__.py` file.
53 """
54 with temporary_inspected_package("namespace_package", init=False) as package:
55 dump_options = {"indent": 2, "sort_keys": True}
56 as_json = package.as_json(full=True, **dump_options)
57 from_json = Object.from_json(as_json)
58 assert from_json.as_json(full=True, **dump_options) == as_json
59
60
61 @pytest.mark.parametrize(
62 "symbol",
63 [
64 # Attribute.
65 "_internal.loader.GriffeLoader.finder",
66 # Function/method.
67 "_internal.loader.GriffeLoader.load",
68 # Class.
69 "_internal.mixins.GetMembersMixin",
70 # Module.
71 "_internal.debug",
72 ],
73 )
74 def test_minimal_light_data_is_enough(symbol: str) -> None:
75 """Test serialization and de-serialization."""
76 loader = GriffeLoader()
77 package = loader.load("griffe")
78 obj = package[symbol]
79 dump_options = {"indent": 2, "sort_keys": True}
80 minimal = obj.as_json(full=False, **dump_options)
81 full = obj.as_json(full=True, **dump_options)
82 reloaded = {
83 Kind.MODULE: Module,
84 Kind.CLASS: Class,
85 Kind.FUNCTION: Function,
86 Kind.ATTRIBUTE: Attribute,
87 }[obj.kind].from_json(minimal)
88 reloaded.parent = obj.parent
89 assert reloaded.as_json(full=False, **dump_options) == minimal
90 assert reloaded.as_json(full=True, **dump_options) == full
91
92
93 # YORE: EOL 3.12: Remove block.
94 # YORE: EOL 3.11: Remove line.
95 @pytest.mark.skipif(
96 sys.version_info < (3, 12),
97 reason="Python less than 3.12 does not have PEP 695 generics",
98 )
99 def test_encoding_pep695_generics_without_defaults() -> None:
100 """Test serialization and de-serialization of PEP 695 generics without defaults.
101
102 Defaults are only possible from Python 3.13 onwards.
103 """
104 with temporary_visited_module(
105 """
106 class Class[X: Exception]: pass
107 def func[**P, T, *R](arg: T, *args: P.args, **kwargs: P.kwargs) -> tuple[*R]: pass
108 type TA[T: (int, str)] = dict[str, T]
109 """,
110 ) as module:
111 minimal = module.as_json(full=False)
112 full = module.as_json(full=True)
113 reloaded = Module.from_json(minimal)
114 assert reloaded.as_json(full=False) == minimal
115 assert reloaded.as_json(full=True) == full
116
117 # Also works (but will result in a different type hint).
118 assert Object.from_json(minimal)
119
120 # Won't work if the JSON doesn't represent the type requested.
121 with pytest.raises(TypeError, match="provided JSON object is not of type"):
122 Function.from_json(minimal)
123
124
125 # YORE: EOL 3.12: Remove line.
126 @pytest.mark.skipif(sys.version_info < (3, 13), reason="Python less than 3.13 does not have defaults in PEP 695 generics") # fmt: skip
127 def test_encoding_pep695_generics() -> None:
128 """Test serialization and de-serialization of PEP 695 generics with defaults.
129
130 Defaults are only possible from Python 3.13 onwards.
131 """
132 with temporary_visited_module(
133 """
134 class Class[X: Exception = OSError]: pass
135 def func[**P, T, *R](arg: T, *args: P.args, **kwargs: P.kwargs) -> tuple[*R]: pass
136 type TA[T: (int, str) = str] = dict[str, T]
137 """,
138 ) as module:
139 minimal = module.as_json(full=False)
140 full = module.as_json(full=True)
141 reloaded = Module.from_json(minimal)
142 assert reloaded.as_json(full=False) == minimal
143 assert reloaded.as_json(full=True) == full
144
145 # Also works (but will result in a different type hint).
146 assert Object.from_json(minimal)
147
148 # Won't work if the JSON doesn't represent the type requested.
149 with pytest.raises(TypeError, match="provided JSON object is not of type"):
150 Function.from_json(minimal)
151
152
153 # use this function in test_json_schema to ease schema debugging
154 def _validate(obj: dict, schema: dict) -> None:
155 if "members" in obj:
156 for member in obj["members"]:
157 _validate(member, schema)
158
159 try:
160 validate(obj, schema)
161 except ValidationError:
162 print(obj["path"]) # noqa: T201
163 raise
164
165
166 @pytest.mark.skipif(
167 not Path("docs", "schema.json").exists(),
168 reason="schema.json not available",
169 )
170 def test_json_schema() -> None:
171 """Assert that our serialized data matches our JSON schema."""
172 loader = GriffeLoader()
173 module = loader.load("griffe")
174 loader.resolve_aliases()
175 data = json.loads(module.as_json(full=True))
176 with open("docs/schema.json", encoding="utf8") as f: # noqa: PTH123
177 schema = json.load(f)
178 validate(data, schema)
179
180
181 # YORE: EOL 3.12: Remove block.
182 # YORE: EOL 3.11: Remove line.
183 @pytest.mark.skipif(
184 sys.version_info < (3, 12),
185 reason="Python less than 3.12 does not have PEP 695 generics",
186 )
187 @pytest.mark.skipif(
188 not Path("docs", "schema.json").exists(),
189 reason="schema.json not available",
190 )
191 def test_json_schema_for_pep695_generics_without_defaults() -> None:
192 """Assert that serialized PEP 695 generics without defaults match our JSON schema.
193
194 Defaults are only possible from Python 3.13 onwards.
195 """
196 with temporary_visited_module(
197 """
198 class Class[X: Exception]: pass
199 def func[**P, T, *R](arg: T, *args: P.args, **kwargs: P.kwargs) -> tuple[*R]: pass
200 type TA[T: (int, str)] = dict[str, T]
201 """,
202 ) as module:
203 data = json.loads(module.as_json(full=True))
204 with open("docs/schema.json", encoding="utf8") as f: # noqa: PTH123
205 schema = json.load(f)
206 validate(data, schema)
207
208
209 # YORE: EOL 3.12: Remove line.
210 @pytest.mark.skipif(sys.version_info < (3, 13), reason="Python less than 3.13 does not have defaults in PEP 695 generics") # fmt: skip
211 @pytest.mark.skipif(
212 not Path("docs", "schema.json").exists(),
213 reason="schema.json not available",
214 )
215 def test_json_schema_for_pep695_generics() -> None:
216 """Assert that serialized PEP 695 generics with defaults match our JSON schema.
217
218 Defaults are only possible from Python 3.13 onwards.
219 """
220 with temporary_visited_module(
221 """
222 class Class[X: Exception = OSError]: pass
223 def func[**P, T, *R](arg: T, *args: P.args, **kwargs: P.kwargs) -> tuple[*R]: pass
224 type TA[T: (int, str) = str] = dict[str, T]
225 """,
226 ) as module:
227 data = json.loads(module.as_json(full=True))
228 with open("docs/schema.json", encoding="utf8") as f: # noqa: PTH123
229 schema = json.load(f)
230 validate(data, schema)