Debian Codegraph @

tests/test_serialization.py

raw
1 #!/usr/bin/env python
2 from ipaddress import IPv4Address
3 import os
4 import json
5 import sys
6 import pytest
7 import datetime
8 import numpy as np
9 import hashlib
10 import base64
11 from typing import NamedTuple, Optional, Union, List, Dict
12 from pickle import UnpicklingError
13 from decimal import Decimal
14 from collections import Counter
15 from pydantic import BaseModel, IPvAnyAddress
16 from deepdiff import DeepDiff
17 from deepdiff.helper import pypy3, py_current_version, np_ndarray, Opcode, SetOrdered
18 from deepdiff.serialization import (
19 pickle_load, pickle_dump, ForbiddenModule, ModuleNotFoundError,
20 MODULE_NOT_FOUND_MSG, FORBIDDEN_MODULE_MSG, pretty_print_diff,
21 load_path_content, UnsupportedFormatErr, json_dumps, json_loads)
22 from conftest import FIXTURES_DIR
23 from tests import PicklableClass
24
25 import logging
26 logging.disable(logging.CRITICAL)
27
28 t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, 3]}}
29 t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": "world\n\n\nEnd"}}
30
31
32 class SampleSchema(BaseModel):
33 works: bool = False
34 ips: List[IPvAnyAddress]
35
36
37 class SomeStats(NamedTuple):
38 counter: Optional[Counter]
39 context_aware_counter: Optional[Counter] = None
40 min_int: Optional[int] = 0
41 max_int: Optional[int] = 0
42
43
44 field_stats1 = SomeStats(
45 counter=Counter(["a", "a", "b"]),
46 max_int=10
47 )
48
49
50 class TestSerialization:
51 """Tests for Serializations."""
52
53 def test_serialization_text(self):
54 ddiff = DeepDiff(t1, t2)
55 assert "builtins.list" in ddiff.to_json_pickle()
56 jsoned = ddiff.to_json()
57 assert "world" in jsoned
58
59 def test_serialization_text_force_builtin_json(self):
60 ddiff = DeepDiff(t1, t2)
61 with pytest.raises(TypeError) as excinfo:
62 jsoned = ddiff.to_json(sort_keys=True)
63 assert str(excinfo.value).startswith("orjson does not accept the sort_keys parameter.")
64 jsoned = ddiff.to_json(sort_keys=True, force_use_builtin_json=True)
65 assert "world" in jsoned
66
67 def test_deserialization(self):
68 ddiff = DeepDiff(t1, t2)
69 jsoned = ddiff.to_json_pickle()
70 ddiff2 = DeepDiff.from_json_pickle(jsoned)
71 assert ddiff == ddiff2
72
73 def test_serialization_tree(self):
74 ddiff = DeepDiff(t1, t2, view='tree')
75 pickle_jsoned = ddiff.to_json_pickle()
76 assert "world" in pickle_jsoned
77 jsoned = ddiff.to_json()
78 assert "world" in jsoned
79
80 def test_deserialization_tree(self):
81 ddiff = DeepDiff(t1, t2, view='tree')
82 jsoned = ddiff.to_json_pickle()
83 ddiff2 = DeepDiff.from_json_pickle(jsoned)
84 assert 'type_changes' in ddiff2
85
86 def test_serialize_custom_objects_throws_error(self):
87 class A:
88 pass
89
90 class B:
91 pass
92
93 t1 = A()
94 t2 = B()
95 ddiff = DeepDiff(t1, t2)
96 assert r'{"type_changes":{"root":{"old_type":"A","new_type":"B","old_value":{},"new_value":{}}}}' == ddiff.to_json()
97
98 def test_serialize_custom_objects_with_default_mapping(self):
99 class A:
100 pass
101
102 class B:
103 pass
104
105 t1 = A()
106 t2 = B()
107 ddiff = DeepDiff(t1, t2)
108 default_mapping = {A: lambda x: 'obj A', B: lambda x: 'obj B'}
109 result = ddiff.to_json(default_mapping=default_mapping)
110 expected_result = {"type_changes": {"root": {"old_type": "A", "new_type": "B", "old_value": "obj A", "new_value": "obj B"}}}
111 assert expected_result == json.loads(result)
112
113 # These lines are long but make it easier to notice the difference:
114 @pytest.mark.parametrize('verbose_level, expected', [
115 (0, {"type_changes": {"root[0]": {"old_type": str, "new_type": int}}, "dictionary_item_added": ["root[1][5]"], "dictionary_item_removed": ["root[1][3]"], "iterable_item_added": {"root[2]": "d"}}),
116 (1, {"type_changes": {"root[0]": {"old_type": str, "new_type": int, "old_value": "a", "new_value": 10}}, "dictionary_item_added": ["root[1][5]"], "dictionary_item_removed": ["root[1][3]"], "values_changed": {"root[1][1]": {"new_value": 2, "old_value": 1}}, "iterable_item_added": {"root[2]": "d"}}),
117 (2, {"type_changes": {"root[0]": {"old_type": str, "new_type": int, "old_value": "a", "new_value": 10}}, "dictionary_item_added": {"root[1][5]": 6}, "dictionary_item_removed": {"root[1][3]": 4}, "values_changed": {"root[1][1]": {"new_value": 2, "old_value": 1}}, "iterable_item_added": {"root[2]": "d"}}),
118 ])
119 def test_to_dict_at_different_verbose_level(self, verbose_level, expected):
120 t1 = ['a', {1: 1, 3: 4}, ]
121 t2 = [10, {1: 2, 5: 6}, 'd']
122
123 ddiff = DeepDiff(t1, t2, verbose_level=verbose_level)
124 assert expected == ddiff.to_dict()
125
126 def test_to_dict_tree_view_defaults_to_verbose_level_2(self):
127 t1 = ['a', {1: 1, 3: 4}]
128 t2 = [10, {1: 2, 5: 6}, 'd']
129 ddiff = DeepDiff(t1, t2, view='tree')
130 result = ddiff.to_dict()
131 # tree view defaults to verbose_level=2: added/removed are dicts, not sets
132 expected = {
133 "type_changes": {"root[0]": {"old_type": str, "new_type": int, "old_value": "a", "new_value": 10}},
134 "dictionary_item_added": {"root[1][5]": 6},
135 "dictionary_item_removed": {"root[1][3]": 4},
136 "values_changed": {"root[1][1]": {"new_value": 2, "old_value": 1}},
137 "iterable_item_added": {"root[2]": "d"},
138 }
139 assert expected == result
140
141 @pytest.mark.parametrize('verbose_level, expected', [
142 (0, {"type_changes": {"root[0]": {"old_type": str, "new_type": int}}, "dictionary_item_added": ["root[1][5]"], "dictionary_item_removed": ["root[1][3]"], "iterable_item_added": {"root[2]": "d"}}),
143 (1, {"type_changes": {"root[0]": {"old_type": str, "new_type": int, "old_value": "a", "new_value": 10}}, "dictionary_item_added": ["root[1][5]"], "dictionary_item_removed": ["root[1][3]"], "values_changed": {"root[1][1]": {"new_value": 2, "old_value": 1}}, "iterable_item_added": {"root[2]": "d"}}),
144 ])
145 def test_to_dict_tree_view_with_verbose_level_override(self, verbose_level, expected):
146 t1 = ['a', {1: 1, 3: 4}]
147 t2 = [10, {1: 2, 5: 6}, 'd']
148 ddiff = DeepDiff(t1, t2, view='tree')
149 result = ddiff.to_dict(verbose_level=verbose_level)
150 assert expected == result
151
152 def test_to_dict_text_view_preserves_original_verbose_level(self):
153 t1 = ['a', {1: 1, 3: 4}]
154 t2 = [10, {1: 2, 5: 6}, 'd']
155 # verbose_level=2 at init, text view
156 ddiff = DeepDiff(t1, t2, verbose_level=2)
157 result = ddiff.to_dict()
158 # Should preserve verbose_level=2 from init
159 assert isinstance(result.get("dictionary_item_added"), dict)
160 assert result["dictionary_item_added"] == {"root[1][5]": 6}
161
162 def test_to_dict_text_view_with_verbose_level_override(self):
163 t1 = ['a', {1: 1, 3: 4}]
164 t2 = [10, {1: 2, 5: 6}, 'd']
165 # verbose_level=2 at init, but override to 1 in to_dict
166 ddiff = DeepDiff(t1, t2, verbose_level=2)
167 result = ddiff.to_dict(verbose_level=1)
168 # verbose_level=1: dictionary_item_added is not a dict (it's a SetOrdered)
169 assert not isinstance(result.get("dictionary_item_added"), dict)
170
171 def test_to_dict_invalid_verbose_level(self):
172 t1 = [1]
173 t2 = [2]
174 ddiff = DeepDiff(t1, t2)
175 with pytest.raises(ValueError):
176 ddiff.to_dict(verbose_level=3)
177
178 def test_to_json_with_verbose_level(self):
179 t1 = ['a', {1: 1, 3: 4}]
180 t2 = [10, {1: 2, 5: 6}, 'd']
181 ddiff = DeepDiff(t1, t2, view='tree')
182 result = json.loads(ddiff.to_json())
183 # tree view defaults to verbose_level=2 in to_json too
184 assert "root[1][5]" in result.get("dictionary_item_added", {})
185
186 def test_to_json_with_verbose_level_override(self):
187 t1 = ['a', {1: 1, 3: 4}]
188 t2 = [10, {1: 2, 5: 6}, 'd']
189 ddiff = DeepDiff(t1, t2, view='tree')
190 result = json.loads(ddiff.to_json(verbose_level=1))
191 # verbose_level=1: dictionary_item_added is a list
192 assert isinstance(result.get("dictionary_item_added"), list)
193
194 def test_serialize_pydantic_model(self):
195 obj = SampleSchema(
196 works=True,
197 ips=["128.0.0.1"]
198 )
199 serialized = json_dumps(obj)
200 obj_again = json_loads(serialized)
201 assert {'works': True, 'ips': ['128.0.0.1']} == obj_again
202 assert {'works': True, 'ips': [IPv4Address('128.0.0.1')]} == obj.model_dump()
203
204
205 @pytest.mark.skipif(pypy3, reason='clevercsv is not supported in pypy3')
206 class TestLoadContet:
207
208 @pytest.mark.parametrize('path1, validate', [
209 ('t1.json', lambda x: x[0]['key1'] == 'value1'),
210 ('t1.yaml', lambda x: x[0][0] == 'name'),
211 ('t1.toml', lambda x: x['servers']['alpha']['ip'] == '10.0.0.1'),
212 ('t1.csv', lambda x: x[0]['last_name'] == 'Nobody'),
213 ('t1.pickle', lambda x: x[1] == 1),
214 ])
215 def test_load_path_content(self, path1, validate):
216 path = os.path.join(FIXTURES_DIR, path1)
217 result = load_path_content(path)
218 assert validate(result)
219
220 def test_load_path_content_when_unsupported_format(self):
221 path = os.path.join(FIXTURES_DIR, 't1.unsupported')
222 with pytest.raises(UnsupportedFormatErr):
223 load_path_content(path)
224
225
226 class TestPicklingSecurity:
227
228 @pytest.mark.skipif(sys.platform == "win32", reason="Resource module is Unix-only")
229 def test_restricted_unpickler_memory_exhaustion_cve(self):
230 """CVE-2026-33155: Prevent DoS via massive allocation through REDUCE opcode.
231
232 The payload calls bytes(10_000_000_000) which is allowed by find_class
233 but would allocate ~9.3GB of memory. The fix should reject this before
234 the allocation happens.
235 """
236 import resource
237
238 # 1. Cap memory to 500MB to prevent system freezes during the test
239 soft, hard = resource.getrlimit(resource.RLIMIT_AS)
240 maxsize_bytes = 500 * 1024 * 1024
241 resource.setrlimit(resource.RLIMIT_AS, (maxsize_bytes, hard))
242
243 try:
244 # 2. Malicious payload: attempts to allocate ~9.3GB via bytes(10000000000)
245 # This uses allowed builtins but passes a massive integer via REDUCE
246 payload = (
247 b"(dp0\n"
248 b"S'_'\n"
249 b"cbuiltins\nbytes\n"
250 b"(I10000000000\n"
251 b"tR"
252 b"s."
253 )
254
255 # 3. After the patch, deepdiff should catch the size violation
256 # and raise UnpicklingError before attempting allocation.
257 with pytest.raises((ValueError, UnpicklingError)):
258 pickle_load(payload)
259 finally:
260 # Restore original memory limit so other tests are not affected
261 resource.setrlimit(resource.RLIMIT_AS, (soft, hard))
262
263 def test_restricted_unpickler_allows_small_bytes(self):
264 """Ensure legitimate small bytes objects can still be deserialized."""
265 # Payload: {'_': bytes(100)} — well within the 128MB limit
266 payload = (
267 b"(dp0\n"
268 b"S'_'\n"
269 b"cbuiltins\nbytes\n"
270 b"(I100\n"
271 b"tR"
272 b"s."
273 )
274 result = pickle_load(payload)
275 assert result == {'_': bytes(100)}
276
277
278 class TestPickling:
279
280 def test_serialize(self):
281 obj = [1, 2, 3, None, {10: 11E2}, frozenset(['a', 'c']), SetOrdered([2, 1]),
282 datetime.datetime(2022, 4, 10, 0, 40, 41, 357857), datetime.time(11), Decimal('11.2'), 123.11]
283 serialized = pickle_dump(obj)
284 loaded = pickle_load(serialized)
285 assert obj == loaded
286
287 @pytest.mark.skipif(pypy3, reason='short pickle not supported in pypy3')
288 def test_pickle_that_is_string(self):
289 serialized_str = 'DeepDiff Delta Payload v0-0-1\nBlah'
290 with pytest.raises(UnpicklingError):
291 pickle_load(serialized_str)
292
293 def test_custom_object_deserialization_fails_without_explicit_permission(self):
294 obj = PicklableClass(10)
295 module_dot_name = 'tests.{}'.format(PicklableClass.__name__)
296
297 serialized = pickle_dump(obj)
298
299 expected_msg = FORBIDDEN_MODULE_MSG.format(module_dot_name)
300 with pytest.raises(ForbiddenModule) as excinfo:
301 pickle_load(serialized)
302 assert expected_msg == str(excinfo.value)
303
304 # Explicitly allowing the module to be loaded
305 loaded = pickle_load(serialized, safe_to_import={module_dot_name})
306 assert obj == loaded
307
308 # Explicitly allowing the module to be loaded. It can take a list instead of a set.
309 loaded2 = pickle_load(serialized, safe_to_import=[module_dot_name])
310 assert obj == loaded2
311
312 def test_unpickling_object_that_is_not_imported_raises_error(self):
313
314 def get_the_pickle():
315 import wave
316 obj = wave.Error
317 return pickle_dump(obj)
318
319 serialized = get_the_pickle()
320 # Making sure that the module is unloaded.
321 del sys.modules['wave']
322 module_dot_name = 'wave.Error'
323
324 expected_msg = MODULE_NOT_FOUND_MSG.format(module_dot_name)
325 with pytest.raises(ModuleNotFoundError) as excinfo:
326 pickle_load(serialized, safe_to_import=module_dot_name)
327 assert expected_msg == str(excinfo.value)
328
329
330 def test_seriaize_property(self):
331
332 class Sample:
333 @property
334 def something(self):
335 return 10
336
337 sample = Sample()
338 serialized = json_dumps(sample)
339 assert '{"something":10}' == serialized
340
341
342 class TestDeepDiffPretty:
343 """Tests for pretty() method of DeepDiff"""
344
345 class TestingClass:
346 one = 1
347
348 testing_class = TestingClass
349
350 @pytest.mark.parametrize('t1, t2, item_path, old_type, new_type, old_val_displayed, new_val_displayed',
351 [
352 [{2: 2, 4: 4}, {2: 'b', 4: 4}, 'root[2]', 'int', 'str', '2', '"b"'],
353 [[1, 2, 3], [1, '2', 3], 'root[1]', 'int', 'str', '2', '"2"'],
354 [[1, 2, 3], {1, 2, 3}, 'root', 'list', 'set', '[1, 2, 3]', '{1, 2, 3}']
355 ])
356 def test_pretty_print_diff_type_changes(self, t1, t2, item_path, old_type, new_type, old_val_displayed,
357 new_val_displayed):
358 ddiff = DeepDiff(t1, t2, view='tree')
359 result = pretty_print_diff(ddiff.tree['type_changes'][0])
360 assert result == 'Type of {} changed from {} to {} and value changed from {} to {}.'.format(item_path, old_type, new_type, old_val_displayed, new_val_displayed)
361
362 @pytest.mark.parametrize('t1, t2, item_path, verbose_level',
363 [
364 [{2: 2, 4: 4}, {2: 2, 4: 4, 5: 5}, 'root[5]', 1],
365 [{2: 2, 4: 4}, {2: 2, 4: 4, 5: 5}, 'root[5] (5)', 2],
366 [{"foo": "bar", "foo1": "bar1"}, {"foo": "bar", "foo1": "bar1", "foo2": "bar2"},
367 'root[\'foo2\']', 0],
368 [{"foo": "bar", "foo1": "bar1"}, {"foo": "bar", "foo1": "bar1", "foo2": "bar2"},
369 'root[\'foo2\'] ("bar2")', 2]
370 ])
371 def test_pretty_print_diff_dictionary_item_added(self, t1, t2, item_path, verbose_level):
372 ddiff = DeepDiff(t1, t2, view='tree', verbose_level=verbose_level)
373 result = pretty_print_diff(ddiff.tree['dictionary_item_added'][0])
374 assert result == 'Item {} added to dictionary.'.format(item_path)
375
376 @pytest.mark.parametrize('t1, t2, item_path, verbose_level',
377 [
378 [{2: 2, 4: 4}, {2: 2}, 'root[4]', 0],
379 [{2: 2, 4: 4}, {2: 2}, 'root[4] (4)', 2],
380 [{"foo": "bar", "foo1": "bar1"}, {"foo": "bar"},
381 'root[\'foo1\']', 1],
382 [{"foo": "bar", "foo1": "bar1"}, {"foo": "bar"},
383 'root[\'foo1\'] ("bar1")', 2],
384 ])
385 def test_pretty_print_diff_dictionary_item_removed(self, t1, t2, item_path, verbose_level):
386 ddiff = DeepDiff(t1, t2, view='tree', verbose_level=verbose_level)
387 result = pretty_print_diff(ddiff.tree['dictionary_item_removed'][0])
388 assert result == 'Item {} removed from dictionary.'.format(item_path)
389
390 @pytest.mark.parametrize('t1, t2, item_path, old_val_displayed, new_val_displayed',
391 [
392 [{2: 2, 4: 4}, {2: 3, 4: 4}, 'root[2]', '2', '3'],
393 [['a', 'b', 'c'], ['a', 'b', 'd'], 'root[2]', '"c"', '"d"']
394 ])
395 def test_pretty_print_diff_values_changed(self, t1, t2, item_path, old_val_displayed, new_val_displayed):
396 ddiff = DeepDiff(t1, t2, view='tree')
397 result = pretty_print_diff(ddiff.tree['values_changed'][0])
398 assert result == 'Value of {} changed from {} to {}.'.format(item_path, old_val_displayed, new_val_displayed)
399
400 @pytest.mark.parametrize('t1, t2, item_path, verbose_level',
401 [
402 [[1, 2, 3], [1, 2, 3, 4], 'root[3]', 1],
403 [[1, 2, 3], [1, 2, 3, 4], 'root[3] (4)', 2],
404 [["foo", "bar"], ["foo", "bar", "barbar"], 'root[2]', 0],
405 [["foo", "bar"], ["foo", "bar", "barbar"], 'root[2] ("barbar")', 2]
406 ])
407 def test_pretty_print_diff_iterable_item_added(self, t1, t2, item_path, verbose_level):
408 ddiff = DeepDiff(t1, t2, view='tree', verbose_level=verbose_level)
409 result = pretty_print_diff(ddiff.tree['iterable_item_added'][0])
410 assert result == 'Item {} added to iterable.'.format(item_path)
411
412 @pytest.mark.parametrize('t1, t2, item_path, verbose_level',
413 [
414 [[1, 2, 3], [1, 2], 'root[2]', 0],
415 [[1, 2, 3], [1, 2], 'root[2] (3)', 2],
416 [["foo", "bar", "barbar"], ["foo", "bar"], 'root[2]', 1],
417 [["foo", "bar", "barbar"], ["foo", "bar"], 'root[2] ("barbar")', 2]
418 ])
419 def test_pretty_print_diff_iterable_item_removed(self, t1, t2, item_path, verbose_level):
420 ddiff = DeepDiff(t1, t2, view='tree', verbose_level=verbose_level)
421 result = pretty_print_diff(ddiff.tree['iterable_item_removed'][0])
422 assert result == 'Item {} removed from iterable.'.format(item_path)
423
424 @pytest.mark.parametrize("verbose_level", range(3))
425 def test_pretty_print_diff_attribute_added(self, verbose_level):
426 t1 = self.testing_class()
427 t2 = self.testing_class()
428 t2.two = 2
429
430 ddiff = DeepDiff(t1, t2, view='tree', verbose_level=verbose_level)
431 result = pretty_print_diff(ddiff.tree['attribute_added'][0])
432 assert result == 'Attribute root.two (2) added.' if verbose_level == 2 else 'Attribute root.two added.'
433
434 @pytest.mark.parametrize("verbose_level", range(3))
435 def test_pretty_print_diff_attribute_removed(self, verbose_level):
436 t1 = self.testing_class()
437 t1.two = 2
438 t2 = self.testing_class()
439
440 ddiff = DeepDiff(t1, t2, view='tree', verbose_level=verbose_level)
441 result = pretty_print_diff(ddiff.tree['attribute_removed'][0])
442
443 assert result == 'Attribute root.two (2) removed.' if verbose_level == 2 else 'Attribute root.two removed.'
444
445 @pytest.mark.parametrize('t1, t2, item_path',
446 [
447 [{1, 2}, {1, 2, 3}, 'root[3]'],
448 ])
449 def test_pretty_print_diff_set_item_added(self, t1, t2, item_path):
450 ddiff = DeepDiff(t1, t2, view='tree')
451 result = pretty_print_diff(ddiff.tree['set_item_added'][0])
452 assert result == 'Item {} added to set.'.format(item_path)
453
454 @pytest.mark.parametrize('t1, t2, item_path',
455 [
456 [{1, 2, 3}, {1, 2}, 'root[3]'],
457 ])
458 def test_pretty_print_diff_set_item_removed(self, t1, t2, item_path):
459 ddiff = DeepDiff(t1, t2, view='tree')
460 result = pretty_print_diff(ddiff.tree['set_item_removed'][0])
461 assert result == 'Item {} removed from set.'.format(item_path)
462
463 @pytest.mark.parametrize('t1, t2, item_path',
464 [
465 [[1, 2, 3, 2], [1, 2, 3], 'root[1]'],
466 ])
467 def test_pretty_print_diff_repetition_change(self, t1, t2, item_path):
468 ddiff = DeepDiff(t1, t2, view='tree', ignore_order=True, report_repetition=True)
469 result = pretty_print_diff(ddiff.tree['repetition_change'][0])
470 assert result == 'Repetition change for item {}.'.format(item_path)
471
472 @pytest.mark.parametrize("expected, verbose_level",
473 (
474 ('Item root[5] added to dictionary.'
475 '\nItem root[3] removed from dictionary.'
476 '\nType of root[2] changed from int to str and value changed from 2 to "b".'
477 '\nValue of root[4] changed from 4 to 5.', 0),
478 ('Item root[5] (5) added to dictionary.'
479 '\nItem root[3] (3) removed from dictionary.'
480 '\nType of root[2] changed from int to str and value changed from 2 to "b".'
481 '\nValue of root[4] changed from 4 to 5.', 2),
482 ), ids=("verbose=0", "verbose=2")
483 )
484 def test_pretty_form_method(self, expected, verbose_level):
485 t1 = {2: 2, 3: 3, 4: 4}
486 t2 = {2: 'b', 4: 5, 5: 5}
487 ddiff = DeepDiff(t1, t2, view='tree', verbose_level=verbose_level)
488 result = ddiff.pretty()
489 assert result == expected
490
491 @pytest.mark.parametrize("expected, verbose_level",
492 (
493 ('\t\tItem root[5] added to dictionary.'
494 '\n\t\tItem root[3] removed from dictionary.'
495 '\n\t\tType of root[2] changed from int to str and value changed from 2 to "b".'
496 '\n\t\tValue of root[4] changed from 4 to 5.', 0),
497 ('\t\tItem root[5] (5) added to dictionary.'
498 '\n\t\tItem root[3] (3) removed from dictionary.'
499 '\n\t\tType of root[2] changed from int to str and value changed from 2 to "b".'
500 '\n\t\tValue of root[4] changed from 4 to 5.', 2),
501 ), ids=("verbose=0", "verbose=2")
502 )
503 def test_pretty_form_method_prefixed_simple(self, expected, verbose_level):
504 t1 = {2: 2, 3: 3, 4: 4}
505 t2 = {2: 'b', 4: 5, 5: 5}
506 ddiff = DeepDiff(t1, t2, verbose_level=verbose_level)
507 result = ddiff.pretty(prefix="\t\t")
508 assert result == expected
509
510 @pytest.mark.parametrize("expected, verbose_level",
511 (
512 ('Diff #1: Item root[5] added to dictionary.'
513 '\nDiff #2: Item root[3] removed from dictionary.'
514 '\nDiff #3: Type of root[2] changed from int to str and value changed from 2 to "b".'
515 '\nDiff #4: Value of root[4] changed from 4 to 5.', 0),
516 ('Diff #1: Item root[5] (5) added to dictionary.'
517 '\nDiff #2: Item root[3] (3) removed from dictionary.'
518 '\nDiff #3: Type of root[2] changed from int to str and value changed from 2 to "b".'
519 '\nDiff #4: Value of root[4] changed from 4 to 5.', 2),
520 ), ids=("verbose=0", "verbose=2")
521 )
522 def test_pretty_form_method_prefixed_callback(self, expected, verbose_level):
523 def prefix_callback(**kwargs):
524 """Helper function using a hidden variable on the diff that tracks which count prints next"""
525 kwargs['diff']._diff_count = 1 + getattr(kwargs['diff'], '_diff_count', 0)
526 return f"Diff #{kwargs['diff']._diff_count}: "
527
528 t1 = {2: 2, 3: 3, 4: 4}
529 t2 = {2: 'b', 4: 5, 5: 5}
530 ddiff = DeepDiff(t1, t2, verbose_level=verbose_level)
531 result = ddiff.pretty(prefix=prefix_callback)
532 assert result == expected
533
534 def sig_to_bytes(inp: Dict[str, Union[str, bytes]]):
535 inp['signature'] = inp['signature'].encode('utf-8')
536 return inp
537
538 @pytest.mark.parametrize('test_num, value, func_to_convert_back', [
539 (1, {'10': None}, None),
540 (2, {"type_changes": {"root": {"old_type": None, "new_type": list, "new_value": ["你好", 2, 3, 5]}}}, None),
541 (3, {'10': Decimal(2017)}, None),
542 (4, Decimal(2017.1), None),
543 (5, {1, 2, 10}, set),
544 (6, datetime.datetime(2023, 10, 11), datetime.datetime.fromisoformat),
545 (7, datetime.datetime.utcnow(), datetime.datetime.fromisoformat),
546 (8, field_stats1, lambda x: SomeStats(**x)),
547 (9, np.array([[ 101, 3533, 1998, 4532, 2024, 3415, 1012, 102]]), np.array),
548 (10, memoryview(b"hello"), lambda x: memoryview(x.encode('utf-8'))),
549 (11, {'file_type': 'xlsx', 'signature': b'52bd9907785'}, sig_to_bytes)
550 ])
551 def test_json_dumps_and_loads(self, test_num, value, func_to_convert_back):
552 serialized = json_dumps(value)
553 back = json_loads(serialized)
554 if func_to_convert_back:
555 back = func_to_convert_back(back)
556 if isinstance(back, np_ndarray):
557 assert np.array_equal(value, back), f"test_json_dumps_and_loads test #{test_num} failed"
558 else:
559 assert value == back, f"test_json_dumps_and_loads test #{test_num} failed"
560
561 def test_namedtuple_seriazliation(self):
562 op_code = Opcode(tag="replace", t1_from_index=0, t1_to_index=1, t2_from_index=10, t2_to_index=20)
563 serialized = json_dumps(op_code)
564 expected = '{"tag":"replace","t1_from_index":0,"t1_to_index":1,"t2_from_index":10,"t2_to_index":20,"old_values":null,"new_values":null}'
565 assert serialized == expected
566
567 def test_reversed_list(self):
568 items = reversed([1, 2, 3])
569
570 serialized = json_dumps(items)
571 serialized2 = json_dumps(items)
572
573 assert '[3,2,1]' == serialized
574 assert '[3,2,1]' == serialized2, "We should have copied the original list. If this returns empty, it means we exhausted the original list."
575
576 def test_dict_keys(self):
577 dic = {"foo": "bar", "apple": "too sweet"}
578 serialized = json_dumps(dic.keys())
579 assert '["foo","apple"]' == serialized
580
581 def test_non_utf8_bytes_serialization(self):
582 """Test that non-UTF-8 bytes are properly base64 encoded"""
583 # Create binary data that cannot be decoded as UTF-8
584 binary_data = b'\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f'
585
586 # Verify it's not UTF-8 decodable
587 with pytest.raises(UnicodeDecodeError):
588 binary_data.decode('utf-8')
589
590 # Test serialization
591 test_data = {"binary": binary_data}
592 serialized = json_dumps(test_data)
593
594 # Should contain base64 encoded data
595 expected_b64 = base64.b64encode(binary_data).decode('ascii')
596 assert expected_b64 in serialized
597
598 # Should be deserializable
599 deserialized = json_loads(serialized)
600 assert deserialized == {"binary": expected_b64}
601
602 def test_hash_bytes_serialization(self):
603 """Test serialization of hash-like binary data (blake3, sha256, etc.)"""
604 # Generate various hash-like byte sequences
605 test_cases = [
606 hashlib.md5(b"test").digest(),
607 hashlib.sha1(b"test").digest(),
608 hashlib.sha256(b"test").digest(),
609 hashlib.sha512(b"test").digest()[:16], # Truncated
610 b'\xff\xfe\xfd\xfc' * 8, # Artificial binary pattern
611 ]
612
613 for i, hash_bytes in enumerate(test_cases):
614 test_data = {"hash": hash_bytes}
615
616 # Should not raise UnicodeDecodeError
617 serialized = json_dumps(test_data)
618 assert serialized # Should produce valid JSON
619
620 # Should contain base64 if not UTF-8 decodable, or string if UTF-8 decodable
621 try:
622 utf8_decoded = hash_bytes.decode('utf-8')
623 # If UTF-8 decodable, should be in JSON as string
624 assert utf8_decoded in serialized
625 except UnicodeDecodeError:
626 # If not UTF-8 decodable, should be base64 encoded
627 expected_b64 = base64.b64encode(hash_bytes).decode('ascii')
628 assert expected_b64 in serialized
629
630 def test_mixed_utf8_and_binary_bytes(self):
631 """Test data structure with both UTF-8 decodable and binary bytes"""
632 test_data = {
633 "utf8_text": b"hello world", # UTF-8 decodable
634 "binary_hash": hashlib.sha256(b"secret").digest(), # Binary
635 "empty_bytes": b"", # Edge case
636 "utf8_unicode": "café".encode('utf-8'), # UTF-8 with unicode
637 "non_utf8_byte": b"\xff\xfe\xfd", # Non-UTF-8 bytes
638 }
639
640 # Should serialize without errors
641 serialized = json_dumps(test_data)
642 deserialized = json_loads(serialized)
643
644 # UTF-8 decodable bytes should remain as strings
645 assert "hello world" in serialized
646 assert deserialized["utf8_text"] == "hello world"
647
648 # Unicode UTF-8 should work
649 assert deserialized["utf8_unicode"] == "café"
650
651 # Binary data should be base64 encoded
652 expected_hash_b64 = base64.b64encode(test_data["binary_hash"]).decode('ascii')
653 assert expected_hash_b64 in serialized
654 assert deserialized["binary_hash"] == expected_hash_b64
655
656 # Empty bytes should be empty string
657 assert deserialized["empty_bytes"] == ""
658
659 # Non-UTF-8 bytes should be base64 encoded
660 expected_non_utf8_b64 = base64.b64encode(test_data["non_utf8_byte"]).decode('ascii')
661 assert expected_non_utf8_b64 in serialized
662 assert deserialized["non_utf8_byte"] == expected_non_utf8_b64
663
664 def test_json_dumps_large_int_exceeding_64bit(self):
665 """Test that integers exceeding 64-bit range are serialized as strings.
666 orjson cannot handle integers larger than 64-bit (9223372036854775807),
667 so json_dumps should convert them to strings."""
668 large_int = 59579472846392086780
669 assert large_int > 9223372036854775807 # larger than max int64
670
671 data = {'max_int': large_int, 'min_int': 1336138}
672 serialized = json_dumps(data)
673 back = json_loads(serialized)
674 assert back['max_int'] == str(large_int)
675 assert back['min_int'] == 1336138
676
677 def test_json_dumps_large_int_in_nested_structure(self):
678 """Test large integers in nested data structures are converted to strings."""
679 large_int = 59579472846392086780
680 data = {
681 'stats': {
682 'counter': {'HasInt': 499},
683 'max_int': large_int,
684 'min_int': 1336138,
685 },
686 'name': 'policy_number',
687 }
688 serialized = json_dumps(data)
689 back = json_loads(serialized)
690 assert back['stats']['max_int'] == str(large_int)
691
692 def test_json_dumps_large_negative_int(self):
693 """Test that large negative integers are also converted to strings."""
694 large_neg_int = -59579472846392086780
695 data = {'value': large_neg_int}
696 serialized = json_dumps(data)
697 back = json_loads(serialized)
698 assert back['value'] == str(large_neg_int)
699
700 def test_json_dumps_namedtuple_with_large_int(self):
701 """Test that a NamedTuple containing an oversized int is properly serialized.
702 _convert_oversized_ints must reconstruct the NamedTuple via _fields, not
703 pass a flat list to its constructor (which fails for NamedTuples with
704 required keyword arguments)."""
705 large_int = 59579472846392086780
706 stats = SomeStats(
707 counter=Counter(["a", "b"]),
708 context_aware_counter=Counter(),
709 min_int=0,
710 max_int=large_int,
711 )
712 data = {'stats': stats}
713 serialized = json_dumps(data)
714 back = json_loads(serialized)
715 assert back['stats']['max_int'] == str(large_int)
716 assert back['stats']['min_int'] == 0
717
718 def test_json_dumps_dict_of_namedtuples_with_large_int(self):
719 """Test a dict of NamedTuples where one contains an oversized int.
720 This mirrors the real-world pattern of field stats keyed by column name."""
721 large_int = 59579472846392086780
722 stats_map = {
723 'normal_field': SomeStats(counter=Counter(["x"]), max_int=10),
724 'big_field': SomeStats(counter=Counter(["y"]), max_int=large_int),
725 }
726 serialized = json_dumps(stats_map)
727 back = json_loads(serialized)
728 assert back['normal_field']['max_int'] == 10
729 assert back['big_field']['max_int'] == str(large_int)
730
731 def test_json_dumps_namedtuple_with_large_int_in_list(self):
732 """Test a list of NamedTuples where one has an oversized int."""
733 large_int = 59579472846392086780
734 data = [
735 SomeStats(counter=Counter(), max_int=5),
736 SomeStats(counter=Counter(), max_int=large_int),
737 ]
738 serialized = json_dumps(data)
739 back = json_loads(serialized)
740 assert back[0]['max_int'] == 5
741 assert back[1]['max_int'] == str(large_int)
742
743 def test_bytes_in_deepdiff_serialization(self):
744 """Test that bytes work correctly in DeepDiff JSON serialization"""
745 t1 = {
746 "text": b"hello",
747 "hash": hashlib.sha256(b"data1").digest(),
748 }
749 t2 = {
750 "text": b"world",
751 "hash": hashlib.sha256(b"data2").digest(),
752 }
753
754 diff = DeepDiff(t1, t2)
755
756 # Should serialize without errors
757 json_output = diff.to_json()
758 assert json_output
759
760 # Should contain both UTF-8 decoded strings and base64 encoded hashes
761 assert "hello" in json_output
762 assert "world" in json_output
763
764 # Hash values should be base64 encoded
765 expected_hash1 = base64.b64encode(t1["hash"]).decode('ascii')
766 expected_hash2 = base64.b64encode(t2["hash"]).decode('ascii')
767 assert expected_hash1 in json_output
768 assert expected_hash2 in json_output