Debian Codegraph @

test/units/utils/test_serialization_profiles.py

raw
1 # DTFIX-FUTURE: these tests need to be split so they can run under both module_utils and controller contexts
2
3 from __future__ import annotations
4
5 import contextlib
6 import dataclasses
7 import datetime
8 import hashlib
9 import itertools
10 import json
11 import pathlib
12 import pkgutil
13 import pprint
14 import typing as t
15
16 import pytest
17
18 from ansible.module_utils._internal._json import _profiles as target_serialization_profiles
19 from ansible.module_utils._internal import _json as _serialization
20 from ansible.module_utils._internal._datatag import AnsibleDatatagBase, NotTaggableError, AnsibleTagHelper
21 from ansible.module_utils._internal._datatag._tags import Deprecated
22 from ansible._internal._templating._lazy_containers import _AnsibleLazyTemplateMixin
23 from ansible._internal._templating._engine import TemplateEngine, TemplateOptions
24 from ansible._internal._templating._utils import TemplateContext
25 from ansible._internal._datatag._tags import TrustedAsTemplate, VaultedValue, Origin, SourceWasEncrypted
26 from ansible._internal._json import _profiles as controller_serialization_profiles
27 from ansible.module_utils.common.json import get_encoder, get_decoder
28 from ansible.module_utils._internal._json._profiles import _fallback_to_str
29 from ansible._internal._json._profiles import _cache_persistence
30 from ansible.errors import AnsibleRuntimeError
31
32 from ..mock.custom_types import CustomMapping, CustomSequence, CustomSet, CustomStr, CustomInt, CustomFloat
33
34
35 basic_values = (
36 None,
37 True,
38 1,
39 1.1,
40 'hi',
41 '汉语', # non-ASCII string
42 b'hi',
43 datetime.datetime(2024, 1, 2, 3, 4, 5, 6, datetime.timezone.utc, fold=1),
44 datetime.time(1, 2, 3, 4, datetime.timezone.utc, fold=1),
45 datetime.date(2024, 1, 2),
46 (1,),
47 [1],
48 CustomSequence([1]),
49 CustomStr('hello'),
50 CustomInt(42),
51 CustomFloat(42.0),
52 {1},
53 CustomSet([1]), # a collections.abc.Set that is not a concrete set/frozenset (e.g. like dict_keys)
54 dict(a=1),
55 CustomMapping(dict(a=1)),
56 {(1, 2): "three"}, # hashable non-scalar key
57 {frozenset((1, 2)): "three"}, # hashable non-scalar key
58 {1: "two"}, # int key
59 {1.1: "two"}, # float key
60 {True: "two"}, # bool key
61 {None: "two"}, # None key
62 )
63
64 # DTFIX5: we need tests for recursion, specifically things like custom sequences and mappings when:
65 # 1) using the legacy serializer
66 # 2) containing types in the type map, such as tagged values
67 # e.g. -- does trust inversion get applied to a value inside a custom sequence or mapping
68
69 tag_values = {
70 Deprecated: Deprecated(msg='x'), # DTFIX5: we need more exhaustive testing of the values supported by this tag to ensure schema ID is robust
71 TrustedAsTemplate: TrustedAsTemplate(),
72 Origin: Origin(path='/tmp/x', line_num=1, col_num=2, description='y'),
73 VaultedValue: VaultedValue(ciphertext='x'),
74 SourceWasEncrypted: SourceWasEncrypted(),
75 }
76
77
78 def test_cache_persistence_schema() -> None:
79 """
80 Check the schema ID for the cache_persistence schema to ensure it is updated when the schema changes.
81 Failure to update the schema ID will result in serialization/deserialiation failures for persisted data for things like cache plugins.
82 This test is only as comprehensive as these unit tests, so ensure profile data types are thoroughly covered.
83 If additional capabilities are added to the cache_persistence profile which are not tested, they will go undetected, leading to runtime failures.
84 """
85 # DTFIX5: update tests to ensure new fields on contracts will fail this test if they have defaults which are omitted from serialization
86 # one possibility: monkeypatch the default field value omission away so that any new field will invalidate the schema
87
88 # DTFIX5: ensure all types/attrs included in _profiles._common_module_response_types are represented here, since they can appear in cached responses
89
90 expected_schema_id = 1
91 expected_schema_hash = "c4b0a620372e25bccba064860f942239615796328caff3e6cc85d397535641a9"
92
93 test_hash = hashlib.sha256()
94 test_hash.update(pathlib.Path(DataSet.PROFILE_DIR / _cache_persistence._Profile.profile_name).with_suffix('.txt').read_bytes())
95
96 actual_schema_id = _cache_persistence._Profile.schema_id
97 actual_schema_hash = test_hash.hexdigest()
98
99 next_schema_id = actual_schema_id + 1
100
101 schema_check_failure_instructions = f"""The cache_persistence schema check hash has changed. The solution depends on the reason why:
102
103 1) The schema and tests have changed:
104
105 i. Increment `ansible._internal._json._profiles._cache_persistence._Profile.schema_id` to {next_schema_id}.
106 ii. Update `expected_schema_id` to {next_schema_id}.
107 iii. Update `expected_schema_hash` to {actual_schema_hash!r}.
108
109 2) The schema is unchanged, but the tests have changed:
110
111 i. Double-check that the schema really hasn't changed.
112 ii. Don't forget about added/changed/removed types as well as fields on those types.
113 iii. Update `expected_schema_hash` to {actual_schema_hash!r}.
114 """
115
116 if actual_schema_id != expected_schema_id:
117 raise Exception(f"The actual schema ID {actual_schema_id} does not match the expected schema ID {expected_schema_id}.")
118
119 if actual_schema_hash != expected_schema_hash:
120 raise Exception(schema_check_failure_instructions)
121
122
123 def get_profile_names() -> tuple[str, ...]:
124 packages = (target_serialization_profiles, controller_serialization_profiles)
125 names = []
126
127 for package in packages:
128 modules = list(pkgutil.iter_modules(package.__path__, f'{package.__name__}.'))
129
130 assert modules # ensure at least one serialization profile module was found
131
132 for module in modules:
133 names.append(_serialization.get_serialization_profile(module.name).profile_name)
134
135 return tuple(sorted(names))
136
137
138 @dataclasses.dataclass(frozen=True)
139 class _TestParameters:
140 profile_name: str
141 value: t.Any
142 tags: tuple[AnsibleDatatagBase, ...] = ()
143 lazy: bool = False
144
145 def __hash__(self):
146 return hash((self.profile_name, repr(self.value), self.tags))
147
148 def __repr__(self):
149 fields = ((field, getattr(self, field.name)) for field in dataclasses.fields(self))
150 args = (f'{f.name}={v!r}' for f, v in fields if v != f.default)
151 return f"{type(self).__name__}({', '.join(args)})"
152
153 def get_test_output(self) -> _TestOutput:
154 encoder = get_encoder(self.profile_name)
155 decoder = get_decoder(self.profile_name)
156
157 ctx = TemplateContext(
158 template_value=self.value,
159 templar=TemplateEngine(),
160 options=TemplateOptions.DEFAULT,
161 stop_on_template=False
162 ) if self.lazy else contextlib.nullcontext()
163
164 with ctx:
165 try:
166 value = AnsibleTagHelper.tag(self.value, self.tags)
167 except NotTaggableError:
168 value = self.value
169
170 if self.lazy:
171 value = _AnsibleLazyTemplateMixin._try_create(value)
172
173 payload: str | Exception
174
175 try:
176 payload = json.dumps(value, cls=encoder)
177 except Exception as ex:
178 payload = ex
179 round_trip = None
180 else:
181 try:
182 round_trip = json.loads(payload, cls=decoder)
183 except Exception as ex:
184 round_trip = ex
185
186 return _TestOutput(
187 payload=payload,
188 round_trip=AnsibleTagHelper.as_native_type(round_trip),
189 tags=tuple(sorted(AnsibleTagHelper.tags(round_trip), key=lambda item: type(item).__name__)),
190 )
191
192
193 @dataclasses.dataclass(frozen=True)
194 class _TestOutput:
195 payload: str | Exception
196 round_trip: t.Any
197 tags: tuple[AnsibleDatatagBase, ...]
198
199
200 @dataclasses.dataclass(frozen=True)
201 class _TestCase:
202 parameters: _TestParameters
203 expected: _TestOutput
204
205 def __str__(self) -> str:
206 parts = [f'profile={self.parameters.profile_name}', f'value={self.parameters.value}']
207
208 if self.parameters.tags:
209 parts.append(f"tags={','.join(sorted(type(obj).__name__ for obj in self.parameters.tags))}")
210
211 if self.parameters.lazy:
212 parts.append('lazy')
213
214 return '; '.join(parts)
215
216
217 class DataSet:
218 PROFILE_DIR = pathlib.Path(__file__).parent / 'expected_serialization_profiles'
219
220 def __init__(self, generate: bool) -> None:
221 self.data: dict[_TestParameters, _TestOutput] = {}
222 self.path = self.PROFILE_DIR
223 self.generate = generate
224
225 def load(self) -> None:
226 if self.generate:
227 return
228
229 for source in self.path.glob('*.txt'):
230 self.data.update(eval(source.read_text()))
231
232 def save(self) -> None:
233 if not self.generate:
234 return
235
236 sorted_items = sorted(self.data.items(), key=lambda o: o[0].profile_name) # additional items appended to the end means the data set is unsorted
237
238 grouped_data_set = {key: dict(gen) for key, gen in itertools.groupby(sorted_items, key=lambda o: o[0].profile_name)}
239
240 for group_name, profiles in grouped_data_set.items():
241 content = self.generate_content(profiles)
242 (self.path / f'{group_name}.txt').write_text(content)
243
244 @staticmethod
245 def generate_content(profiles: dict[_TestParameters, _TestOutput]) -> str:
246 content = ["{"]
247
248 # loop the dictionary entries manually to ensure one entry per line
249 for key, value in profiles.items():
250 key_pprint = pprint.pformat(key, width=10000, indent=0, sort_dicts=False)
251 value_pprint = pprint.pformat(value, width=10000, indent=0, sort_dicts=False)
252
253 content.append(f"{key_pprint}: {value_pprint},")
254
255 content.append("}")
256
257 return '\n'.join(content) + '\n'
258
259 def fetch_or_create_expected(self, test_params: _TestParameters) -> _TestOutput:
260 if self.generate:
261 output = self.data[test_params] = test_params.get_test_output()
262 else:
263 try:
264 output = self.data[test_params]
265 except KeyError:
266 raise Exception(f'Missing {test_params} in data set. Use `generate=True` to update the data set and then review the changes.') from None
267
268 return output
269
270
271 class ProfileHelper:
272 def __init__(self, profile_name: str) -> None:
273 self.profile_name = profile_name
274
275 profile = _serialization.get_serialization_profile(profile_name)
276
277 supported_tags = {obj: None for obj in profile.serialize_map if issubclass(obj, AnsibleDatatagBase)}
278
279 if supported_tags:
280 self.supported_tag_values = tuple(tag_value for tag_type, tag_value in tag_values.items() if tag_type in supported_tags)
281
282 if not self.supported_tag_values:
283 raise Exception(f'Profile {profile} supports tags {supported_tags}, but no supported tag value is available.')
284 else:
285 self.supported_tag_values = tuple()
286
287 self.unsupported_tag_value = next((tag_value for tag_type, tag_value in tag_values.items() if tag_type not in supported_tags), None)
288
289 if not self.unsupported_tag_value and profile.profile_name != _cache_persistence._Profile.profile_name:
290 raise Exception(f'Profile {profile} supports tags {supported_tags}, but no unsupported tag value is available.')
291
292 def create_parameters_from_values(self, *values: t.Any) -> list[_TestParameters]:
293 return list(itertools.chain.from_iterable(self.create_parameters_from_value(value) for value in values))
294
295 def create_parameters_from_value(self, value: t.Any) -> list[_TestParameters]:
296 test_parameters: list[_TestParameters] = [
297 _TestParameters(
298 profile_name=self.profile_name,
299 value=value,
300 )
301 ]
302
303 if self.supported_tag_values:
304 test_parameters.append(_TestParameters(
305 profile_name=self.profile_name,
306 value=value,
307 tags=self.supported_tag_values,
308 ))
309
310 if self.unsupported_tag_value:
311 test_parameters.append(_TestParameters(
312 profile_name=self.profile_name,
313 value=value,
314 tags=(self.unsupported_tag_value,),
315 ))
316
317 # test lazy containers on all non m2c profiles
318 if not self.profile_name.endswith("_m2c") and isinstance(value, (list, dict)):
319 test_parameters.extend([dataclasses.replace(p, lazy=True) for p in test_parameters])
320
321 return test_parameters
322
323
324 additional_test_parameters: list[_TestParameters] = []
325
326 # DTFIX5: need better testing for containers, especially for tagged values in containers
327
328 additional_test_parameters.extend(ProfileHelper(_fallback_to_str._Profile.profile_name).create_parameters_from_values(
329 b'\x00', # valid utf-8 strict, JSON escape sequence required
330 b'\x80', # utf-8 strict decoding fails, forcing the use of an error handler such as surrogateescape, JSON escape sequence required
331 '\udc80', # same as above, but already a string (verify that the string version is handled the same as the bytes version)
332 {1: "1"}, # integer key
333 {b'hi': "1"}, # bytes key
334 {TrustedAsTemplate().tag(b'hi'): "2"}, # tagged bytes key
335 {(b'hi',): 3}, # tuple[bytes] key
336 ))
337
338
339 _generate = False
340 """Set to True to regenerate all test data; a test failure will occur until it is set back to False."""
341
342
343 def get_test_cases() -> list[_TestCase]:
344 data_set = DataSet(generate=_generate)
345 data_set.load()
346
347 test_parameters: list[_TestParameters] = []
348
349 for profile_name in get_profile_names():
350 helper = ProfileHelper(profile_name)
351
352 for value in basic_values:
353 test_parameters.extend(helper.create_parameters_from_value(value))
354
355 test_parameters.extend(additional_test_parameters)
356
357 test_cases = [_TestCase(parameters=parameters, expected=data_set.fetch_or_create_expected(parameters)) for parameters in test_parameters]
358
359 data_set.save()
360
361 return test_cases
362
363
364 @pytest.mark.parametrize("test_case", get_test_cases(), ids=str)
365 def test_profile(test_case: _TestCase) -> None:
366 output = test_case.parameters.get_test_output()
367
368 if isinstance(output.payload, Exception):
369 if type(output.payload) is not type(test_case.expected.payload):
370 raise Exception('unexpected exception') from output.payload
371
372 assert str(output.payload) == str(test_case.expected.payload)
373 else:
374 assert output.payload == test_case.expected.payload
375 assert type(output.round_trip) is type(test_case.expected.round_trip)
376
377 if isinstance(output.round_trip, AnsibleRuntimeError):
378 assert str(output.round_trip._original_message) == str(test_case.expected.round_trip._original_message)
379 else:
380 assert output.round_trip == test_case.expected.round_trip
381
382 assert not set(output.tags).symmetric_difference(test_case.expected.tags)
383
384
385 def test_not_generate_mode():
386 assert not _generate, "set _generate=False to statically test expected behavior"