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