Debian Codegraph @

tests/test_hash.py

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2 import re
3 import pytest
4 import pytz
5 import uuid6
6 import logging
7 import datetime
8 import ipaddress
9 from typing import Union
10 from pathlib import Path
11 from collections import namedtuple
12 from functools import partial
13 from enum import Enum
14 from deepdiff import DeepDiff, DeepHash
15 from deepdiff.deephash import (
16 prepare_string_for_hashing, unprocessed,
17 UNPROCESSED_KEY, BoolObj, HASH_LOOKUP_ERR_MSG, combine_hashes_lists)
18 from deepdiff.helper import pypy3, get_id, number_to_string, np, py_major_version, py_minor_version
19 from tests import CustomClass2
20
21 logging.disable(logging.CRITICAL)
22
23
24 class ClassC:
25 class_attr = 0
26
27 def __init__(self, a, b=None):
28 self.a = a
29 self.b = b
30
31 def __str__(self):
32 return "({}, {})".format(self.a, self.b)
33
34 __repr__ = __str__
35
36
37 # Only the prep part of DeepHash. We don't need to test the actual hash function.
38 DeepHashPrep = partial(DeepHash, apply_hash=False)
39
40
41 def prep_str(obj, ignore_string_type_changes=True):
42 return obj if ignore_string_type_changes else 'str:{}'.format(obj)
43
44
45 class TestDeepHash:
46
47 def test_dictionary(self):
48
49 obj = {1: 1}
50 result = DeepHash(obj)
51 assert set(result.keys()) == {1, get_id(obj)}
52
53 def test_get_hash_by_obj_is_the_same_as_by_obj_get_id(self):
54 a = "a"
55 obj = {1: a}
56 result = DeepHash(obj)
57 assert result[a]
58
59 def test_deephash_repr(self):
60 obj = "a"
61 result = DeepHash(obj)
62 assert '{"a":"980410da9522db17c3ab8743541f192a5ab27772a6154dbc7795ee909e653a5c"}' == repr(result)
63
64 def test_deephash_values(self):
65 obj = "a"
66 result = list(DeepHash(obj).values())
67 assert ['980410da9522db17c3ab8743541f192a5ab27772a6154dbc7795ee909e653a5c'] == result
68
69 def test_deephash_keys(self):
70 obj = "a"
71 result = list(DeepHash(obj).keys())
72 assert ["a"] == result
73
74 def test_deephash_items(self):
75 obj = "a"
76 result = list(DeepHash(obj).items())
77 assert [('a', '980410da9522db17c3ab8743541f192a5ab27772a6154dbc7795ee909e653a5c')] == result
78
79 def test_get_hash_by_obj_when_does_not_exist(self):
80 a = "a"
81 obj = {1: a}
82 result = DeepHash(obj)
83 with pytest.raises(KeyError):
84 result[2]
85
86 def test_datetime(self):
87 now = datetime.datetime.now()
88 a = b = now
89 a_hash = DeepHash(a)
90 b_hash = DeepHash(b)
91 assert a_hash[a] == b_hash[b]
92
93 def test_date1(self):
94 date = datetime.date(2024, 2, 1)
95 date_hash = DeepHash(date)
96 assert 'd90e95901f85ca09b2536d3cb81a49747c3a4fb14906d6fa0d492713ebb4309c' == date_hash[date]
97
98 def test_date2(self):
99 item = {'due_date': datetime.date(2024, 2, 1)}
100
101 result = DeepHash(
102 item,
103 significant_digits=12,
104 number_format_notation='f',
105 ignore_numeric_type_changes=True,
106 ignore_type_in_groups=[{int, float, complex, datetime.datetime, datetime.date, datetime.timedelta, datetime.time}],
107 ignore_type_subclasses=False,
108 ignore_encoding_errors=False,
109 ignore_repetition=True,
110 number_to_string_func=number_to_string,
111 )
112 assert 'e0d7ec984a0eda44ceb1e3c595f9b805530d715c779483e63a72c67cbce68615' == result[item]
113
114 def test_datetime_truncate(self):
115 a = datetime.datetime(2020, 5, 17, 22, 15, 34, 913070)
116 b = datetime.datetime(2020, 5, 17, 22, 15, 39, 296583)
117 c = datetime.datetime(2020, 5, 17, 22, 15, 34, 500000)
118
119 a_hash = DeepHash(a, truncate_datetime='minute')
120 b_hash = DeepHash(b, truncate_datetime='minute')
121 assert a_hash[a] == b_hash[b]
122
123 a_hash = DeepHash(a, truncate_datetime='second')
124 c_hash = DeepHash(c, truncate_datetime='second')
125 assert a_hash[a] == c_hash[c]
126
127 def test_get_reserved_keyword(self):
128 hashes = {UNPROCESSED_KEY: 'full item', 'key1': ('item', 'count')}
129 result = DeepHash._getitem(hashes, obj='key1')
130 assert 'item' == result
131 # For reserved keys, it should just grab the object instead of grabbing an item in the tuple object.
132 result = DeepHash._getitem(hashes, obj=UNPROCESSED_KEY)
133 assert 'full item' == result
134
135 def test_get_key(self):
136 hashes = {'key1': ('item', 'count')}
137 result = DeepHash.get_key(hashes, key='key2', default='banana')
138 assert 'banana' == result
139
140 def test_list_of_sets(self):
141 a = {1}
142 b = {2}
143 obj = [a, b]
144 result = DeepHash(obj)
145 expected_result = {1, 2, get_id(a), get_id(b), get_id(obj)}
146 assert set(result.keys()) == expected_result
147
148 def test_bad_attribute(self):
149 class Bad:
150 __slots__ = ['x', 'y']
151
152 def __getattr__(self, key):
153 raise AttributeError("Bad item")
154
155 def __str__(self):
156 return "Bad Object"
157
158 def __repr__(self):
159 return "<Bad obj id {}>".format(id(self))
160
161 t1 = Bad()
162
163 result = DeepHash(t1)
164 expected_result = {t1: unprocessed, UNPROCESSED_KEY: [t1]}
165 assert expected_result == result
166
167 def test_built_in_hash_not_sensitive_to_bytecode_vs_unicode(self):
168 a = 'hello'
169 b = b'hello'
170 a_hash = DeepHash(a, ignore_string_type_changes=True)[a]
171 b_hash = DeepHash(b, ignore_string_type_changes=True)[b]
172 assert a_hash == b_hash
173
174 def test_sha1_hash_not_sensitive_to_bytecode_vs_unicode(self):
175 a = 'hello'
176 b = b'hello'
177 a_hash = DeepHash(a, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)[a]
178 b_hash = DeepHash(b, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)[b]
179 assert a_hash == b_hash
180
181 def test_path(self):
182 a = Path('testdir')
183 b = Path('testdir2')
184 a_hash = DeepHash(a)[a]
185 b_hash = DeepHash(b)[b]
186 assert a_hash != b_hash
187
188 def test_re(self):
189 import re
190 a = re.compile("asdf.?")
191 a_hash = DeepHash(a)[a]
192 assert not( a_hash is unprocessed)
193
194 # https://github.com/seperman/deepdiff/issues/494
195 def test_numpy_bool(self):
196 a = {'b': np.array([True], dtype='bool')}
197 a_hash = DeepHash(a)[a]
198 assert not( a_hash is unprocessed)
199
200 def test_numpy_datetime64(self):
201 now_dt = datetime.datetime.now()
202 now = np.datetime64(now_dt)
203 later = np.datetime64(now_dt + datetime.timedelta(seconds=10))
204 a = b = now
205 a_hash = DeepHash(a)
206 b_hash = DeepHash(b)
207 assert a_hash[a] == b_hash[b]
208
209 later_hash = DeepHash(later)
210 assert a_hash[a] != later_hash[later]
211
212 def test_uuid6_hash_positive(self):
213 """Positive test case: Same UUID objects should produce the same hash."""
214 uuid_obj = uuid6.uuid7()
215 hash1 = DeepHash(uuid_obj)
216 hash2 = DeepHash(uuid_obj)
217 assert hash1[uuid_obj] == hash2[uuid_obj]
218
219 import uuid
220 regular_uuid = uuid.uuid4()
221 hash_regular = DeepHash(regular_uuid)
222 assert hash_regular[regular_uuid] is not unprocessed
223
224 def test_uuid6_deepdiff_negative(self):
225 """Negative test case: DeepDiff should detect differences between sets containing different UUID objects."""
226 dummy_id_1 = uuid6.uuid7()
227 dummy_id_2 = uuid6.uuid7()
228 set1 = {dummy_id_1}
229 set2 = {dummy_id_1, dummy_id_2}
230 diff = DeepDiff(set1, set2)
231 assert diff != {}
232 assert 'set_item_added' in diff
233 assert str(dummy_id_2) in str(diff)
234
235 def test_slots_with_uninitialized_attributes(self):
236 """Test that DeepHash handles classes with __slots__ where not all slots are initialized."""
237 class PartiallyInitialized:
238 __slots__ = ['x', 'y', 'z']
239
240 def __init__(self, x):
241 self.x = x
242
243 obj = PartiallyInitialized(10)
244 result = DeepHash(obj)
245 # Should not raise AttributeError iternally, and should successfully hash the object
246 assert result[obj] is not unprocessed
247
248 def test_slots_fully_initialized(self):
249 """Test that DeepHash correctly hashes classes with __slots__ where all slots are initialized."""
250 class FullyInitialized:
251 __slots__ = ['x', 'y']
252
253 def __init__(self, x, y):
254 self.x = x
255 self.y = y
256
257 obj1 = FullyInitialized(1, 2)
258 obj2 = FullyInitialized(1, 2)
259 obj3 = FullyInitialized(3, 4)
260
261 hash1 = DeepHash(obj1)
262 hash2 = DeepHash(obj2)
263 hash3 = DeepHash(obj3)
264
265 # Same values should produce same hash
266 assert hash1[obj1] == hash2[obj2]
267 # Different values should produce different hash
268 assert hash1[obj1] != hash3[obj3]
269
270 def test_slots_with_no_initialized_attributes(self):
271 """Test that DeepHash handles classes with __slots__ where no slots are initialized."""
272 class EmptySlots:
273 __slots__ = ['a', 'b', 'c']
274
275 def __init__(self):
276 pass
277
278 obj = EmptySlots()
279 result = DeepHash(obj)
280 assert result[obj] is not unprocessed
281
282 def test_slots_inheritance(self):
283 """Test that DeepHash handles inherited __slots__ correctly."""
284 class Base:
285 __slots__ = ['x']
286
287 def __init__(self, x):
288 self.x = x
289
290 class Derived(Base):
291 __slots__ = ['y', 'z']
292
293 def __init__(self, x, y):
294 super().__init__(x)
295 self.y = y
296
297 obj = Derived(1, 2)
298 result = DeepHash(obj)
299 # Should still not raise AttributeError internally for uninitialized 'z'
300 assert result[obj] is not unprocessed
301
302 def test_slots_deepdiff_comparison(self):
303 """Test that DeepDiff also works correctly with __slots__ classes (incl inherited and uninitialized attributes)."""
304 class Base:
305 __slots__ = ['x']
306
307 def __init__(self, x):
308 self.x = x
309
310 class Derived(Base):
311 __slots__ = ['y', 'z']
312
313 def __init__(self, x, y):
314 super().__init__(x)
315 self.y = y
316
317 obj1 = Derived(1, 2)
318 obj2 = Derived(1, 2)
319 obj3 = Derived(3, 4)
320
321 # Same initialized values should show no difference
322 diff1 = DeepDiff(obj1, obj2)
323 assert diff1 == {}
324
325 # Different values should show difference
326 diff2 = DeepDiff(obj1, obj3)
327 assert diff2 == {
328 'values_changed': {
329 'root.x': {'new_value': 3, 'old_value': 1},
330 'root.y': {'new_value': 4, 'old_value': 2},
331 }
332 }
333
334 class TestDeepHashPrep:
335 """DeepHashPrep Tests covering object serialization."""
336
337 def test_prep_bool_vs_num1(self):
338 assert {BoolObj.TRUE: 'bool:true'} == DeepHashPrep(True)
339 assert {1: 'int:1'} == DeepHashPrep(1)
340
341 def test_prep_bool_vs_num2(self):
342 item1 = {
343 "Value One": True,
344 "Value Two": 1,
345 }
346 item2 = {
347 "Value Two": 1,
348 "Value One": True,
349 }
350 assert DeepHashPrep(item1)[item1] == DeepHashPrep(item2)[item2]
351
352 def test_prep_str1(self):
353 obj = "a"
354 obj2 = b"a"
355 expected_result = {obj: prep_str(obj)}
356 result = DeepHashPrep(obj, ignore_string_type_changes=True)
357 assert expected_result == result
358 assert result[obj] == 'a'
359 expected_result2 = {obj: prep_str(obj, ignore_string_type_changes=False)}
360 result = DeepHashPrep(obj, ignore_string_type_changes=False)
361 assert expected_result2 == result
362 assert result[obj] == 'str:a'
363
364 expected_result3 = {obj2: prep_str(obj2, ignore_string_type_changes=True)}
365 result = DeepHashPrep(obj2, ignore_string_type_changes=True)
366 assert expected_result3 != result
367 assert result[obj2] == 'a'
368 result = DeepHashPrep(obj2, ignore_string_type_changes=False)
369 assert {b'a': 'bytes:a'} == result
370 assert result[obj2] == 'bytes:a'
371
372 def test_prep_number1(self):
373 obj_int = 1
374 obj_float = 1.0
375 # By default, type is included in the prep
376 result_int = DeepHashPrep(obj_int)
377 result_float = DeepHashPrep(obj_float)
378 assert result_int[obj_int] == 'int:1'
379 assert result_float[obj_float] == 'float:1.0'
380 # When ignoring numeric type changes, both get the same "number:" prefix
381 result_int2 = DeepHashPrep(obj_int, ignore_numeric_type_changes=True)
382 result_float2 = DeepHashPrep(obj_float, ignore_numeric_type_changes=True)
383 assert result_int2[obj_int] == result_float2[obj_float]
384 assert result_int2[obj_int] == 'number:1.000000000000'
385
386 def test_dictionary_key_type_change(self):
387 obj1 = {"b": 10}
388 obj2 = {b"b": 10}
389
390 result1 = DeepHashPrep(obj1, ignore_string_type_changes=True)
391 result2 = DeepHashPrep(obj2, ignore_string_type_changes=True)
392 assert result1[obj1] == result2[obj2]
393 assert result1["b"] == result2[b"b"]
394
395 def test_number_type_change(self):
396 obj1 = 10
397 obj2 = 10.0
398
399 result1 = DeepHashPrep(obj1)
400 result2 = DeepHashPrep(obj2)
401 assert result1[obj1] != result2[obj2]
402
403 result1 = DeepHashPrep(obj1, ignore_numeric_type_changes=True)
404 result2 = DeepHashPrep(obj2, ignore_numeric_type_changes=True)
405 assert result1[obj1] == result2[obj2]
406
407 def test_prep_str_fail_if_deephash_leaks_results(self):
408 """
409 This test fails if DeepHash is getting a mutable copy of hashes
410 which means each init of the DeepHash will have hashes from
411 the previous init.
412 """
413 obj1 = "a"
414 expected_result = {obj1: prep_str(obj1)}
415 result = DeepHashPrep(obj1, ignore_string_type_changes=True)
416 assert expected_result == result
417 obj2 = "b"
418 result = DeepHashPrep(obj2, ignore_string_type_changes=True)
419 assert obj1 not in result
420
421 def test_dict_in_dict(self):
422 obj2 = {2: 3}
423 obj = {'a': obj2}
424 result = DeepHashPrep(obj, ignore_string_type_changes=True)
425 assert 'a' in result
426 assert obj2 in result
427
428 def do_list_or_tuple(self, func, func_str):
429 string1 = "a"
430 obj = func([string1, 10, 20])
431 if func is list:
432 obj_id = get_id(obj)
433 else:
434 obj_id = obj
435 string1_prepped = prep_str(string1)
436 expected_result = {
437 10: 'int:10',
438 20: 'int:20',
439 string1: string1_prepped,
440 obj_id: '{}:{},int:10,int:20'.format(func_str, string1_prepped),
441 }
442 result = DeepHashPrep(obj, ignore_string_type_changes=True)
443 assert expected_result == result
444
445 def test_list_and_tuple(self):
446 for func, func_str in ((list, 'list'), (tuple, 'tuple')):
447 self.do_list_or_tuple(func, func_str)
448
449 def test_named_tuples(self):
450 # checking if pypy3 is running the test
451 # in that case due to a difference of string interning implementation
452 # the id of x inside the named tuple changes.
453 x = "x"
454 x_prep = prep_str(x)
455 Point = namedtuple('Point', [x])
456 obj = Point(x=11)
457 result = DeepHashPrep(obj, ignore_string_type_changes=True)
458 if pypy3:
459 assert result[obj] == "ntPoint:{%s:int:11}" % x
460 else:
461 expected_result = {
462 x: x_prep,
463 obj: "ntPoint:{%s:int:11}" % x,
464 11: 'int:11',
465 }
466 assert expected_result == result
467
468 def test_hash_enum(self):
469 class MyEnum(Enum):
470 A = 1
471 B = 2
472
473 if (py_major_version, py_minor_version) >= (3, 11):
474 assert DeepHashPrep(MyEnum.A)[MyEnum.A] == r'objMyEnum:{str:_name_:str:A;str:_sort_order_:int:0;str:_value_:int:1}'
475 else:
476 assert DeepHashPrep(MyEnum.A)[MyEnum.A] == r'objMyEnum:{str:_name_:str:A;str:_value_:int:1}'
477 assert DeepHashPrep(MyEnum.A) == DeepHashPrep(MyEnum(1))
478 assert DeepHashPrep(MyEnum.A) != DeepHashPrep(MyEnum.A.name)
479 assert DeepHashPrep(MyEnum.A) != DeepHashPrep(MyEnum.A.value)
480 assert DeepHashPrep(MyEnum.A) != DeepHashPrep(MyEnum.B)
481
482 assert DeepHashPrep(MyEnum.A, use_enum_value=True)[MyEnum.A] == 'int:1'
483
484 def test_dict_hash(self):
485 string1 = "a"
486 string1_prepped = prep_str(string1)
487 key1 = "key1"
488 key1_prepped = prep_str(key1)
489 obj = {key1: string1, 1: 10, 2: 20}
490 expected_result = {
491 1: 'int:1',
492 10: 'int:10',
493 2: 'int:2',
494 20: 'int:20',
495 key1: key1_prepped,
496 string1: string1_prepped,
497 get_id(obj): 'dict:{{int:1:int:10;int:2:int:20;{}:{}}}'.format(key1, string1)
498 }
499 result = DeepHashPrep(obj, ignore_string_type_changes=True)
500 assert expected_result == result
501
502 def test_dict_in_list(self):
503 string1 = "a"
504 key1 = "key1"
505 dict1 = {key1: string1, 1: 10, 2: 20}
506 obj = [0, dict1]
507 expected_result = {
508 0: 'int:0',
509 1: 'int:1',
510 10: 'int:10',
511 2: 'int:2',
512 20: 'int:20',
513 key1: key1,
514 string1: string1,
515 get_id(dict1): 'dict:{int:1:int:10;int:2:int:20;%s:%s}' %
516 (key1, string1),
517 get_id(obj):
518 'list:dict:{int:1:int:10;int:2:int:20;%s:%s},int:0' %
519 (key1, string1)
520 }
521 result = DeepHashPrep(obj, ignore_string_type_changes=True)
522 assert expected_result == result
523
524 def test_nested_lists_same_hash(self):
525 t1 = [1, 2, [3, 4]]
526 t2 = [[4, 3], 2, 1]
527 t1_hash = DeepHashPrep(t1)
528 t2_hash = DeepHashPrep(t2)
529
530 assert t1_hash[get_id(t1)] == t2_hash[get_id(t2)]
531
532 def test_nested_lists_same_hash2(self):
533 t1 = [1, 2, [3, [4, 5]]]
534 t2 = [[[5, 4], 3], 2, 1]
535 t1_hash = DeepHashPrep(t1)
536 t2_hash = DeepHashPrep(t2)
537
538 assert t1_hash[get_id(t1)] == t2_hash[get_id(t2)]
539
540 def test_nested_lists_same_hash3(self):
541 t1 = [{1: [2, 3], 4: [5, [6, 7]]}]
542 t2 = [{4: [[7, 6], 5], 1: [3, 2]}]
543 t1_hash = DeepHashPrep(t1)
544 t2_hash = DeepHashPrep(t2)
545
546 assert t1_hash[get_id(t1)] == t2_hash[get_id(t2)]
547
548 def test_nested_lists_in_dictionary_same_hash(self):
549 t1 = [{"c": 4}, {"c": 3}]
550 t2 = [{"c": 3}, {"c": 4}]
551 t1_hash = DeepHashPrep(t1)
552 t2_hash = DeepHashPrep(t2)
553
554 assert t1_hash[get_id(t1)] == t2_hash[get_id(t2)]
555
556 def test_same_sets_same_hash(self):
557 t1 = {1, 3, 2}
558 t2 = {2, 3, 1}
559 t1_hash = DeepHashPrep(t1)
560 t2_hash = DeepHashPrep(t2)
561
562 assert t1_hash[get_id(t1)] == t2_hash[get_id(t2)]
563
564 @pytest.mark.parametrize("list1, list2, ignore_iterable_order, is_equal", [
565 ([1, 2], [2, 1], False, False),
566 ([1, 2], [2, 1], True, True),
567 ([1, 2, 3], [1, 3, 2], False, False),
568 ([1, [1, 2, 3]], [1, [3, 2, 1]], False, False),
569 ([1, [1, 2, 3]], [1, [3, 2, 1]], True, True),
570 ((1, 2), (2, 1), False, False),
571 ((1, 2), (2, 1), True, True),
572 ])
573 def test_ignore_iterable_order(self, list1, list2, ignore_iterable_order, is_equal):
574 list1_hash = DeepHash(list1, ignore_iterable_order=ignore_iterable_order)
575 list2_hash = DeepHash(list2, ignore_iterable_order=ignore_iterable_order)
576
577 assert is_equal == (list1_hash[list1] == list2_hash[list2])
578
579 @pytest.mark.parametrize("t1, t2, significant_digits, number_format_notation, result", [
580 ({0.012, 0.98}, {0.013, 0.99}, 1, "f", 'set:float:0.0,float:1.0'),
581 (100000, 100021, 3, "e", 'int:1.000e+5'),
582 ])
583 def test_similar_significant_hash(self, t1, t2, significant_digits,
584 number_format_notation, result):
585 t1_hash = DeepHashPrep(t1, significant_digits=significant_digits,
586 number_format_notation=number_format_notation)
587 t2_hash = DeepHashPrep(t2, significant_digits=significant_digits,
588 number_format_notation=number_format_notation)
589
590 if result:
591 assert result == t1_hash[t1] == t2_hash[t2]
592 else:
593 assert t1_hash[t1] != t2_hash[t2]
594
595 def test_number_to_string_func(self):
596 def custom_number_to_string(number, *args, **kwargs):
597 number = 100 if number < 100 else number
598 return number_to_string(number, *args, **kwargs)
599
600 t1 = [10, 12, 100000]
601 t2 = [50, 63, 100021]
602 t1_hash = DeepHashPrep(t1, significant_digits=4, number_format_notation="e",
603 number_to_string_func=custom_number_to_string)
604 t2_hash = DeepHashPrep(t2, significant_digits=4, number_format_notation="e",
605 number_to_string_func=custom_number_to_string)
606
607 assert t1_hash[10] == t2_hash[50] == t1_hash[12] == t2_hash[63] != t1_hash[100000]
608
609 def test_same_sets_in_lists_same_hash(self):
610 t1 = ["a", {1, 3, 2}]
611 t2 = [{2, 3, 1}, "a"]
612 t1_hash = DeepHashPrep(t1)
613 t2_hash = DeepHashPrep(t2)
614
615 assert t1_hash[get_id(t1)] == t2_hash[get_id(t2)]
616
617 def test_unknown_parameters(self):
618 with pytest.raises(ValueError):
619 DeepHashPrep(1, wrong_param=2)
620
621 def test_bad_attribute_prep(self):
622 class Bad:
623 __slots__ = ['x', 'y']
624
625 def __getattr__(self, key):
626 raise AttributeError("Bad item")
627
628 def __str__(self):
629 return "Bad Object"
630
631 t1 = Bad()
632
633 result = DeepHashPrep(t1)
634 expected_result = {t1: unprocessed, UNPROCESSED_KEY: [t1]}
635 assert expected_result == result
636
637 class Burrito:
638 bread = 'flour'
639
640 def __init__(self):
641 self.spicy = True
642
643 class Taco:
644 bread = 'flour'
645
646 def __init__(self):
647 self.spicy = True
648
649 class ClassA:
650 def __init__(self, x, y):
651 self.x = x
652 self.y = y
653
654 class ClassB:
655 def __init__(self, x, y):
656 self.x = x
657 self.y = y
658
659 class ClassC(ClassB):
660 pass
661
662 obj_a = ClassA(1, 2)
663 obj_b = ClassB(1, 2)
664 obj_c = ClassC(1, 2)
665
666 burrito = Burrito()
667 taco = Taco()
668
669 @pytest.mark.parametrize("test_num, t1, t2, ignore_type_in_groups, ignore_type_subclasses, is_qual", [
670 (1, taco, burrito, [], False, False),
671 (2, taco, burrito, [(Taco, Burrito)], False, True),
672 (3, [taco], [burrito], [(Taco, Burrito)], False, True),
673 (4, [obj_a], [obj_c], [(ClassA, ClassB)], False, True),
674 (5, [obj_a], [obj_c], [(ClassA, ClassB)], True, False),
675 (6, [obj_b], [obj_c], [(ClassB, )], True, False),
676 ])
677 def test_objects_with_same_content(self, test_num, t1, t2, ignore_type_in_groups, ignore_type_subclasses, is_qual):
678 t1_result = DeepHashPrep(t1, ignore_type_in_groups=ignore_type_in_groups,
679 ignore_type_subclasses=ignore_type_subclasses)
680 t2_result = DeepHashPrep(t2, ignore_type_in_groups=ignore_type_in_groups,
681 ignore_type_subclasses=ignore_type_subclasses)
682 assert is_qual == (t1_result[t1] == t2_result[t2]), f"test_objects_with_same_content #{test_num} failed."
683
684 def test_custom_object(self):
685 cc_a = CustomClass2(prop1=["a"], prop2=["b"])
686 t1 = [cc_a, CustomClass2(prop1=["c"], prop2=["d"])]
687 t1_result = DeepHashPrep(t1)
688 expected = 'list:objCustomClass2:{str:prop1:list:str:a;str:prop2:list:str:b},objCustomClass2:{str:prop1:list:str:c;str:prop2:list:str:d}' # NOQA
689 assert expected == t1_result[t1]
690
691 def test_repetition_by_default_does_not_effect(self):
692 list1 = [3, 4]
693 list1_id = get_id(list1)
694 a = [1, 2, list1]
695 a_id = get_id(a)
696
697 list2 = [4, 3, 3]
698 list2_id = get_id(list2)
699 b = [list2, 2, 1]
700 b_id = get_id(b)
701
702 hash_a = DeepHashPrep(a)
703 hash_b = DeepHashPrep(b)
704
705 assert hash_a[list1_id] == hash_b[list2_id]
706 assert hash_a[a_id] == hash_b[b_id]
707
708 def test_setting_repetition_off_unequal_hash(self):
709 list1 = [3, 4]
710 list1_id = get_id(list1)
711 a = [1, 2, list1]
712 a_id = get_id(a)
713
714 list2 = [4, 3, 3]
715 list2_id = get_id(list2)
716 b = [list2, 2, 1]
717 b_id = get_id(b)
718
719 hash_a = DeepHashPrep(a, ignore_repetition=False)
720 hash_b = DeepHashPrep(b, ignore_repetition=False)
721
722 assert not hash_a[list1_id] == hash_b[list2_id]
723 assert not hash_a[a_id] == hash_b[b_id]
724
725 assert hash_a[list1_id].replace('3|1', '3|2') == hash_b[list2_id]
726
727 def test_already_calculated_hash_wont_be_recalculated(self):
728 hashes = (i for i in range(10))
729
730 def hasher(obj):
731 return str(next(hashes))
732 obj = "a"
733 expected_result = {obj: '0'}
734 result = DeepHash(obj, hasher=hasher)
735 assert expected_result == result
736
737 # we simply feed the last result to DeepHash
738 # So it can re-use the results.
739 result2 = DeepHash(obj, hasher=hasher, hashes=result)
740 # if hashes are not cached and re-used,
741 # then the next time hasher runs, it returns
742 # number 1 instead of 0.
743 assert expected_result == result2
744
745 result3 = DeepHash(obj, hasher=hasher)
746 expected_result = {obj: '1'}
747 assert expected_result == result3
748
749 def test_skip_type(self):
750 l1 = logging.getLogger("test")
751 obj = {"log": l1, 2: 1337}
752 result = DeepHashPrep(obj, exclude_types={logging.Logger})
753 assert get_id(l1) not in result
754
755 def test_skip_type2(self):
756 l1 = logging.getLogger("test")
757 result = DeepHashPrep(l1, exclude_types={logging.Logger})
758 assert not result
759
760 def test_prep_dic_with_loop(self):
761 obj = {2: 1337}
762 obj[1] = obj
763 result = DeepHashPrep(obj)
764 expected_result = {get_id(obj): 'dict:{int:2:int:1337}', 1: 'int:1', 2: 'int:2', 1337: 'int:1337'}
765 assert expected_result == result
766
767 def test_prep_iterable_with_loop(self):
768 obj = [1]
769 obj.append(obj)
770 result = DeepHashPrep(obj)
771 expected_result = {get_id(obj): 'list:int:1', 1: 'int:1'}
772 assert expected_result == result
773
774 def test_prep_iterable_with_excluded_type(self):
775 l1 = logging.getLogger("test")
776 obj = [1, l1]
777 result = DeepHashPrep(obj, exclude_types={logging.Logger})
778 assert get_id(l1) not in result
779
780 def test_skip_str_type_in_dict_on_list(self):
781 dic1 = {1: "a"}
782 t1 = [dic1]
783 dic2 = {}
784 t2 = [dic2]
785 t1_hash = DeepHashPrep(t1, exclude_types=[str])
786 t2_hash = DeepHashPrep(t2, exclude_types=[str])
787 assert 1 in t1_hash
788 assert t1_hash[dic1] == t2_hash[dic2]
789
790 def test_skip_path_in_hash(self):
791 dic1 = {1: "a"}
792 t1 = [dic1, 2]
793 dic2 = {}
794 t2 = [dic2, 2]
795 t1_hash = DeepHashPrep(t1, exclude_paths=['root[0]'])
796 t2_hash = DeepHashPrep(t2, exclude_paths='root[0]')
797 t2_hash_again = DeepHashPrep(t2, include_paths='1')
798 assert 1 not in t1_hash
799 assert 2 in t1_hash
800 assert t1_hash[2] == t2_hash[2]
801 assert t1_hash[2] == t2_hash_again[2]
802
803 def test_skip_path2(self):
804
805 obj10 = {'a': 1, 'b': 'f', 'e': "1111", 'foo': {'bar': 'baz'}}
806 obj11 = {'c': 1, 'd': 'f', 'e': 'Cool'}
807
808 obj20 = {'a': 1, 'b': 'f', 'e': 'Cool', 'foo': {'bar': 'baz2'}}
809 obj21 = {'c': 1, 'd': 'f', 'e': "2222"}
810
811 t1 = [obj10, obj11]
812 t2 = [obj20, obj21]
813
814 exclude_paths = ["root[0]['e']", "root[1]['e']", "root[0]['foo']['bar']"]
815
816 t1_hash = DeepHashPrep(t1, exclude_paths=exclude_paths)
817 t2_hash = DeepHashPrep(t2, exclude_paths=exclude_paths)
818 assert t1_hash[t1] == t2_hash[t2]
819
820 def test_hash_include_path_nested(self):
821
822 obj10 = {'a': 1, 'b': 'f', 'e': "1111", 'foo': {'bar': 'baz'}}
823 obj11 = {'c': 1, 'd': 'f', 'e': 'Cool'}
824
825 obj20 = {'a': 1, 'b': 'f', 'e': 'Cool', 'foo': {'bar': 'baz'}}
826 obj21 = {'c': 1, 'd': 'f', 'e': "2222"}
827
828 t1 = [obj10, obj11]
829 t2 = [obj20, obj21]
830
831 include_paths = ["root[0]['foo']['bar']"]
832
833 t1_hash = DeepHashPrep(t1, include_paths=include_paths)
834 t2_hash = DeepHashPrep(t2, include_paths=include_paths)
835 assert t1_hash[t1] == t2_hash[t2]
836
837 def test_skip_regex_path(self):
838 dic1 = {1: "a"}
839 t1 = [dic1, 2]
840 exclude_re = re.compile(r'\[0\]')
841 t1_hash = DeepHashPrep(t1, exclude_regex_paths=r'\[0\]')
842 t2_hash = DeepHashPrep(t1, exclude_regex_paths=[exclude_re])
843 assert 1 not in t1_hash
844 assert 2 in t1_hash
845 assert t1_hash[2] == t2_hash[2]
846
847 def test_skip_hash_exclude_obj_callback(self):
848 def exclude_obj_callback(obj, parent):
849 return True if parent == "root[0]['x']" or obj == 2 else False
850
851 dic1 = {"x": 1, "y": 2, "z": 3}
852 t1 = [dic1]
853 t1_hash = DeepHashPrep(t1, exclude_obj_callback=exclude_obj_callback)
854 assert t1_hash == {'y': 'str:y', 'z': 'str:z', 3: 'int:3',
855 get_id(dic1): 'dict:{str:z:int:3}', get_id(t1): 'list:dict:{str:z:int:3}'}
856 dic2 = {"z": 3}
857 t2 = [dic2]
858 t2_hash = DeepHashPrep(t2, exclude_obj_callback=exclude_obj_callback)
859 assert t1_hash[t1] == t2_hash[t2]
860
861 def test_string_case(self):
862 t1 = "Hello"
863
864 t1_hash = DeepHashPrep(t1)
865 assert t1_hash == {'Hello': 'str:Hello'}
866
867 t1_hash = DeepHashPrep(t1, ignore_string_case=True)
868 assert t1_hash == {'Hello': 'str:hello'}
869
870 def test_hash_class(self):
871 t1 = ClassC
872 t1_hash = DeepHashPrep(t1)
873 assert t1_hash['class_attr'] == 'str:class_attr'
874 assert t1_hash[0] == 'int:0'
875 # Note: we ignore private names in calculating hashes now. So you dont see __init__ here for example.
876 assert t1_hash[t1] == r'objClassC:{str:class_attr:int:0}'
877
878 def test_hash_set_in_list(self):
879 t1 = [{1, 2, 3}, {4, 5}]
880 t1_hash = DeepHashPrep(t1)
881 assert t1_hash[t1] == 'list:set:int:1,int:2,int:3,set:int:4,int:5'
882
883 def test_hash_numpy_array1(self):
884 t1 = np.array([[1, 2]], np.int8)
885 t2 = np.array([[2, 1]], np.int8)
886 t1_hash = DeepHashPrep(t1)
887 t2_hash = DeepHashPrep(t2)
888 assert t1_hash[t1] == 'ndarray:ndarray:int8:1,int8:2'
889 assert t2_hash[t2] == t1_hash[t1]
890
891 def test_hash_numpy_array_ignore_numeric_type_changes(self):
892 t1 = np.array([[1, 2]], np.int8)
893 t1_hash = DeepHashPrep(t1, ignore_numeric_type_changes=True)
894 assert t1_hash[t1] == 'ndarray:ndarray:number:1.000000000000,number:2.000000000000'
895
896 def test_hash_numpy_array2_multi_dimensional_can_not_retrieve_individual_array_item_hashes(self):
897 """
898 This is a very interesting case. When DeepHash extracts t1[0] to create a hash for it,
899 Numpy creates an array. But that array will only be technically available during the DeepHash run.
900 Once DeepHash is run, the array is marked to be deleted by the garbage collector.
901 However depending on the version of the python and the machine that runs it, by the time we get
902 to the line that is t1_hash[t1[0]], the t1[0] may or may not be still in memory.
903 If it is still in the memory, t1_hash[t1[0]] works without a problem.
904 If it is already garbage collected, t1_hash[t1[0]] will throw a key error since there will be
905 a new t1[0] by the time t1_hash[t1[0]] is called. Hence it will have a new ID and thus it
906 will not be available anymore in t1_hash. Remember that since Numpy arrays are not hashable,
907 the ID of the array is stored in t1_hash as a key and not the object itself.
908 """
909 t1 = np.array([[1, 2, 3, 4], [4, 2, 2, 1]], np.int8)
910 t1_hash = DeepHashPrep(t1)
911 try:
912 t1_hash[t1[0]]
913 except Exception as e:
914 assert str(e).strip("'") == HASH_LOOKUP_ERR_MSG.format(t1[0])
915
916 def test_pandas(self):
917 import pandas as pd
918 df = pd.DataFrame({"a": [1]})
919 equal_df = pd.DataFrame({"a": [1]})
920 df_same_column_names = pd.DataFrame({"a": [1, 2]})
921 other_df = pd.DataFrame({"b": [1]})
922 df_hash = DeepHashPrep(df)[df]
923 equal_df_hash = DeepHashPrep(equal_df)[equal_df]
924 df_same_column_names_hash = DeepHashPrep(df_same_column_names)[df_same_column_names]
925 other_df_hash = DeepHashPrep(other_df)[other_df]
926 assert df_hash == equal_df_hash
927 assert df_hash != df_same_column_names_hash
928 assert df_hash != other_df_hash
929
930 df_mixed = pd.DataFrame({'a': [1], 'b': ['two'], 'c': [(1, 2)]})
931 df_mixed_2 = pd.DataFrame({'a': [1], 'b': ['two'], 'c': [(1, 2)]})
932 df_mixed_3 = pd.DataFrame({'a': [1], 'b': ['one'], 'c': [(1, 2)]})
933 df_mixed_4 = pd.DataFrame({'a': [1], 'b': ['two'], 'c': [(1, 3)]})
934 df_mixed_hash = DeepHashPrep(df_mixed)[df_mixed]
935 df_mixed_2_hash = DeepHashPrep(df_mixed_2)[df_mixed_2]
936 df_mixed_3_hash = DeepHashPrep(df_mixed_3)[df_mixed_3]
937 df_mixed_4_hash = DeepHashPrep(df_mixed_4)[df_mixed_4]
938 assert df_mixed_hash == df_mixed_2_hash
939 assert df_mixed_hash != df_mixed_3_hash
940 assert df_mixed_hash != df_mixed_4_hash
941
942 df_u8 = pd.DataFrame({'a': np.array([1], dtype=np.uint8)})
943 df_u16 = pd.DataFrame({'a': np.array([1], dtype=np.uint16)})
944 df_float = pd.DataFrame({'a': np.array([1], dtype=np.float32)})
945 df_u8_hash = DeepHashPrep(df_u8)[df_u8]
946 df_u16_hash = DeepHashPrep(df_u16)[df_u16]
947 df_float_hash = DeepHashPrep(df_float)[df_float]
948 assert df_u8_hash != df_float_hash
949 assert df_u8_hash != df_u16_hash
950
951 df_index = pd.DataFrame({'a': [1, 2, 3]}, index=[1, 2, 3])
952 df_index_diff = pd.DataFrame({'a': [1, 2, 3]}, index=[1, 2, 4])
953 df_index_hash = DeepHashPrep(df_index)[df_index]
954 df_index_diff_hash = DeepHashPrep(df_index_diff)[df_index_diff]
955 assert df_index_hash != df_index_diff_hash
956
957 def test_polars(self):
958 import polars as pl
959 df = pl.DataFrame({"a": [1]})
960 equal_df = pl.DataFrame({"a": [1]})
961 df_same_column_names = pl.DataFrame({"a": [1, 2]})
962 other_df = pl.DataFrame({"b": [1]})
963 df_hash = DeepHashPrep(df)[df]
964 equal_df_hash = DeepHashPrep(equal_df)[equal_df]
965 df_same_column_names_hash = DeepHashPrep(df_same_column_names)[df_same_column_names]
966 other_df_hash = DeepHashPrep(other_df)[other_df]
967 assert df_hash == equal_df_hash
968 assert df_hash != df_same_column_names_hash
969 assert df_hash != other_df_hash
970
971 df_mixed = pl.DataFrame({'a': [1], 'b': ['two'], 'c': [(1, 2)]})
972 df_mixed_2 = pl.DataFrame({'a': [1], 'b': ['two'], 'c': [(1, 2)]})
973 df_mixed_3 = pl.DataFrame({'a': [1], 'b': ['one'], 'c': [(1, 2)]})
974 df_mixed_4 = pl.DataFrame({'a': [1], 'b': ['two'], 'c': [(1, 3)]})
975 df_mixed_hash = DeepHashPrep(df_mixed)[df_mixed]
976 df_mixed_2_hash = DeepHashPrep(df_mixed_2)[df_mixed_2]
977 df_mixed_3_hash = DeepHashPrep(df_mixed_3)[df_mixed_3]
978 df_mixed_4_hash = DeepHashPrep(df_mixed_4)[df_mixed_4]
979 assert df_mixed_hash == df_mixed_2_hash
980 assert df_mixed_hash != df_mixed_3_hash
981 assert df_mixed_hash != df_mixed_4_hash
982
983 df_u8 = pl.DataFrame({'a': np.array([1], dtype=np.uint8)})
984 df_u16 = pl.DataFrame({'a': np.array([1], dtype=np.uint16)})
985 df_float = pl.DataFrame({'a': np.array([1], dtype=np.float32)})
986 df_u8_hash = DeepHashPrep(df_u8)[df_u8]
987 df_u16_hash = DeepHashPrep(df_u16)[df_u16]
988 df_float_hash = DeepHashPrep(df_float)[df_float]
989 assert df_u8_hash != df_float_hash
990 assert df_u8_hash != df_u16_hash
991
992 lazy_1 = pl.DataFrame({"foo": ["a", "b", "c"], "bar": [0, 1, 2]}).lazy()
993 lazy_2 = pl.DataFrame({"foo": ["a", "b", "c"], "bar": [0, 1, 2]}).lazy()
994 lazy_3 = pl.DataFrame({"foo": ["a", "b", "c"], "bar": [0, 1, 2], "foobar": 5}).lazy()
995 with pytest.raises(TypeError):
996 DeepHashPrep(lazy_1)[lazy_1] # lazy dfs can not be compared
997 df_1 = lazy_1.collect()
998 df_2 = lazy_2.collect()
999 df_3 = lazy_3.collect()
1000 df_1_hash = DeepHashPrep(df_1)[df_1]
1001 df_2_hash = DeepHashPrep(df_2)[df_2]
1002 df_3_hash = DeepHashPrep(df_3)[df_3]
1003 assert df_1_hash == df_2_hash
1004 assert df_1_hash != df_3_hash
1005
1006
1007 class TestDeepHashSHA:
1008 """DeepHash with SHA Tests."""
1009
1010 def test_str_sha1(self):
1011 obj = "a"
1012 expected_result = {
1013 obj: '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8'
1014 }
1015 result = DeepHash(obj, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)
1016 assert expected_result == result
1017
1018 def test_str_sha256(self):
1019 obj = "a"
1020 expected_result = {
1021 obj: 'ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb'
1022 }
1023 result = DeepHash(obj, ignore_string_type_changes=True, hasher=DeepHash.sha256hex)
1024 assert expected_result == result
1025
1026 def test_prep_str_sha1_fail_if_mutable(self):
1027 """
1028 This test fails if DeepHash is getting a mutable copy of hashes
1029 which means each init of the DeepHash will have hashes from
1030 the previous init.
1031 """
1032 obj1 = "a"
1033 expected_result = {
1034 obj1: '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8'
1035 }
1036 result = DeepHash(obj1, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)
1037 assert expected_result == result
1038 obj2 = "b"
1039 result = DeepHash(obj2, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)
1040 assert obj1 not in result
1041
1042 def test_bytecode(self):
1043 obj = b"a"
1044 expected_result = {
1045 obj: '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8'
1046 }
1047 result = DeepHash(obj, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)
1048 assert expected_result == result
1049
1050 def test_list1(self):
1051 string1 = "a"
1052 obj = [string1, 10, 20]
1053 expected_result = {
1054 string1: '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8',
1055 get_id(obj): 'eac61cbd194e5e03c210a3dce67b9bfd6a7b7acb',
1056 10: DeepHash.sha1hex('int:10'),
1057 20: DeepHash.sha1hex('int:20'),
1058 }
1059 result = DeepHash(obj, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)
1060 assert expected_result == result
1061
1062 def test_datetime_hash(self):
1063 dt_utc = datetime.datetime(2025, 2, 3, 12, 0, 0, tzinfo=pytz.utc) # UTC timezone
1064 # Convert it to another timezone (e.g., New York)
1065 dt_ny = dt_utc.astimezone(pytz.timezone('America/New_York'))
1066 assert dt_utc == dt_ny
1067
1068 result_utc = DeepHash(dt_utc, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)
1069 result_ny = DeepHash(dt_ny, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)
1070 assert result_utc[dt_utc] == result_ny[dt_ny]
1071
1072 def test_dict1(self):
1073 string1 = "a"
1074 key1 = "key1"
1075 obj = {key1: string1, 1: 10, 2: 20}
1076 expected_result = {
1077 1: DeepHash.sha1hex('int:1'),
1078 10: DeepHash.sha1hex('int:10'),
1079 2: DeepHash.sha1hex('int:2'),
1080 20: DeepHash.sha1hex('int:20'),
1081 key1: '1073ab6cda4b991cd29f9e83a307f34004ae9327',
1082 string1: '86f7e437faa5a7fce15d1ddcb9eaeaea377667b8',
1083 get_id(obj): '11e23f096df81b1ccab0c309cdf8b4ba5a0a6895'
1084 }
1085 result = DeepHash(obj, ignore_string_type_changes=True, hasher=DeepHash.sha1hex)
1086 assert expected_result == result
1087
1088
1089 class TestCleaningString:
1090
1091 @pytest.mark.parametrize("text, ignore_string_type_changes, expected_result", [
1092 (b'hello', True, 'hello'),
1093 (b'hello', False, 'bytes:hello'),
1094 ('hello', True, 'hello'),
1095 ('hello', False, 'str:hello'),
1096 ])
1097 def test_clean_type(self, text, ignore_string_type_changes, expected_result):
1098 result = prepare_string_for_hashing(text, ignore_string_type_changes=ignore_string_type_changes)
1099 assert expected_result == result
1100
1101
1102 class TestCounts:
1103
1104 @pytest.mark.parametrize('obj, expected_count', [
1105 (
1106 {1: 1, 2: 3},
1107 5
1108 ),
1109 (
1110 {"key": {1: 1, 2: 4}, "key2": ["a", "b"]},
1111 11
1112 ),
1113 (
1114 [{1}],
1115 3
1116 ),
1117 (
1118 [ClassC(a=10, b=11)],
1119 6
1120 )
1121 ])
1122 def test_dict_count(self, obj, expected_count):
1123 """
1124 How many object went to build this dict?
1125 """
1126
1127 result = DeepHash(obj).get(obj, extract_index=1)
1128 assert expected_count == result
1129
1130
1131 class TestOtherHashFuncs:
1132
1133 @pytest.mark.parametrize('items, prefix, expected', [
1134 ([[1], [2]], 'pre', 'pre583852d84b3482edf53408b64724a37289d7af458c44bb989a8abbffe24d2d2b'),
1135 ([[1], [2]], b'pre', 'pre583852d84b3482edf53408b64724a37289d7af458c44bb989a8abbffe24d2d2b'),
1136 ])
1137 def test_combine_hashes_lists(self, items, prefix, expected):
1138 result = combine_hashes_lists(items, prefix)
1139 assert expected == result
1140
1141 EXPECTED_MESSAGE1 = (
1142 "'utf-8' codec can't decode byte 0xc3 in position 0: invalid continuation byte in '('. "
1143 "Please either pass ignore_encoding_errors=True or pass the encoding via encodings=['utf-8', '...'].")
1144
1145 EXPECTED_MESSAGE2 = (
1146 "'utf-8' codec can't decode byte 0xbc in position 0: invalid start byte in ' cup of flour'. "
1147 "Please either pass ignore_encoding_errors=True or pass the encoding via encodings=['utf-8', '...'].")
1148
1149 EXPECTED_MESSAGE3 = (
1150 "'utf-8' codec can't decode byte 0xc3 in position 34: invalid continuation byte in '...up of potatos. Then ( cup of flour'. Please either pass ignore_encoding_errors=True or "
1151 "pass the encoding via encodings=['utf-8', '...']."
1152 )
1153
1154 @pytest.mark.parametrize('test_num, item, encodings, ignore_encoding_errors, expected_result, expected_message', [
1155 (1, b'\xc3\x28', None, False, UnicodeDecodeError, EXPECTED_MESSAGE1),
1156 (2, b'\xc3\x28', ['utf-8'], False, UnicodeDecodeError, EXPECTED_MESSAGE1),
1157 (3, b'\xc3\x28', ['utf-8'], True, {b'\xc3(': '640da73f0d9b268a0a7ae884d77063d1193f43a651352f9032d99a8fe1705546'}, None),
1158 (4, b"\xbc cup of flour", ['utf-8'], False, UnicodeDecodeError, EXPECTED_MESSAGE2),
1159 (5, b"\xbc cup of flour", ['utf-8'], True, {b'\xbc cup of flour': '86ac12eb5e35db88cf93baca1d62098023b2d93d634e75fb4e37657e514f3d51'}, None),
1160 (6, b"\xbc cup of flour", ['utf-8', 'latin-1'], False, {b'\xbc cup of flour': 'cfc354ae2232a8983bf59b2004f44fcb4036f57df1d08b9cde9950adea3f8d3e'}, None),
1161 (7, b"First have a cup of potatos. Then \xc3\x28 cup of flour", None, False, UnicodeDecodeError, EXPECTED_MESSAGE3),
1162 ])
1163 def test_hash_encodings(self, test_num, item, encodings, ignore_encoding_errors, expected_result, expected_message):
1164 if UnicodeDecodeError == expected_result: # NOQA
1165 with pytest.raises(expected_result) as exc_info:
1166 DeepHash(item, encodings=encodings, ignore_encoding_errors=ignore_encoding_errors)
1167 assert expected_message == str(exc_info.value), f"test_encodings test #{test_num} failed."
1168 else:
1169 result = DeepHash(item, encodings=encodings, ignore_encoding_errors=ignore_encoding_errors)
1170 assert expected_result == result, f"test_encodings test #{test_num} failed."
1171
1172 def test_ip_addresses(self):
1173
1174 class ClassWithIp:
1175 """Class containing single data member to demonstrate deepdiff infinite iterate over IPv6Interface"""
1176
1177 def __init__(self, addr: str):
1178 self.field: Union[
1179 ipaddress.IPv4Network,
1180 ipaddress.IPv6Network,
1181 ipaddress.IPv4Interface,
1182 ipaddress.IPv6Interface,
1183 ] = ipaddress.IPv6Network(addr)
1184
1185
1186 obj1 = ClassWithIp("2002:db8::/30")
1187 obj1_hash = DeepHashPrep(obj1)
1188 repr(obj1_hash) # shouldn't raise error
1189 assert r"objClassWithIp:{str:field:iprange:2002:db8::/30}" == obj1_hash[obj1]
1190 obj2 = ClassWithIp("2001:db8::/32")
1191 diff = DeepDiff(obj1, obj2)
1192 assert {
1193 "values_changed": {
1194 "root.field": {
1195 "new_value": ipaddress.IPv6Network("2001:db8::/32"),
1196 "old_value": ipaddress.IPv6Network("2002:db8::/30"),
1197 }
1198 }
1199 } == diff