| 1 |
import re |
| 2 |
import math |
| 3 |
import pytest |
| 4 |
from copy import deepcopy |
| 5 |
from typing import List, Any |
| 6 |
from deepdiff import DeepDiff |
| 7 |
from deepdiff.operator import BaseOperator, PrefixOrSuffixOperator, BaseOperatorPlus |
| 8 |
|
| 9 |
|
| 10 |
class TestOperators: |
| 11 |
def test_custom_operators_prevent_default(self): |
| 12 |
t1 = { |
| 13 |
"coordinates": [ |
| 14 |
{"x": 5, "y": 5}, |
| 15 |
{"x": 8, "y": 8} |
| 16 |
] |
| 17 |
} |
| 18 |
|
| 19 |
t2 = { |
| 20 |
"coordinates": [ |
| 21 |
{"x": 6, "y": 6}, |
| 22 |
{"x": 88, "y": 88} |
| 23 |
] |
| 24 |
} |
| 25 |
|
| 26 |
class L2DistanceDifferWithPreventDefault(BaseOperator): |
| 27 |
def __init__(self, regex_paths: List[str], distance_threshold: float): |
| 28 |
super().__init__(regex_paths) |
| 29 |
self.distance_threshold = distance_threshold |
| 30 |
|
| 31 |
def _l2_distance(self, c1, c2): |
| 32 |
return math.sqrt( |
| 33 |
(c1["x"] - c2["x"]) ** 2 + (c1["y"] - c2["y"]) ** 2 |
| 34 |
) |
| 35 |
|
| 36 |
def give_up_diffing(self, level, diff_instance) -> bool: |
| 37 |
l2_distance = self._l2_distance(level.t1, level.t2) |
| 38 |
if l2_distance > self.distance_threshold: |
| 39 |
diff_instance.custom_report_result('distance_too_far', level, { |
| 40 |
"l2_distance": l2_distance |
| 41 |
}) |
| 42 |
return True |
| 43 |
|
| 44 |
ddiff = DeepDiff(t1, t2, custom_operators=[L2DistanceDifferWithPreventDefault( |
| 45 |
["^root\\['coordinates'\\]\\[\\d+\\]$"], |
| 46 |
1 |
| 47 |
)]) |
| 48 |
|
| 49 |
expected = { |
| 50 |
'distance_too_far': { |
| 51 |
"root['coordinates'][0]": {'l2_distance': 1.4142135623730951}, |
| 52 |
"root['coordinates'][1]": {'l2_distance': 113.13708498984761} |
| 53 |
} |
| 54 |
} |
| 55 |
assert expected == ddiff |
| 56 |
|
| 57 |
def test_custom_operators_not_prevent_default(self): |
| 58 |
t1 = { |
| 59 |
"coordinates": [ |
| 60 |
{"x": 5, "y": 5}, |
| 61 |
{"x": 8, "y": 8} |
| 62 |
] |
| 63 |
} |
| 64 |
|
| 65 |
t2 = { |
| 66 |
"coordinates": [ |
| 67 |
{"x": 6, "y": 6}, |
| 68 |
{"x": 88, "y": 88} |
| 69 |
] |
| 70 |
} |
| 71 |
|
| 72 |
class L2DistanceDifferWithPreventDefault(BaseOperator): |
| 73 |
def __init__(self, regex_paths, distance_threshold): |
| 74 |
super().__init__(regex_paths) |
| 75 |
self.distance_threshold = distance_threshold |
| 76 |
|
| 77 |
def _l2_distance(self, c1, c2): |
| 78 |
return math.sqrt( |
| 79 |
(c1["x"] - c2["x"]) ** 2 + (c1["y"] - c2["y"]) ** 2 |
| 80 |
) |
| 81 |
|
| 82 |
def give_up_diffing(self, level, diff_instance) -> bool: |
| 83 |
l2_distance = self._l2_distance(level.t1, level.t2) |
| 84 |
if l2_distance > self.distance_threshold: |
| 85 |
diff_instance.custom_report_result('distance_too_far', level, { |
| 86 |
"l2_distance": l2_distance |
| 87 |
}) |
| 88 |
# |
| 89 |
return False |
| 90 |
|
| 91 |
ddiff = DeepDiff(t1, t2, custom_operators=[L2DistanceDifferWithPreventDefault( |
| 92 |
["^root\\['coordinates'\\]\\[\\d+\\]$"], |
| 93 |
1 |
| 94 |
) |
| 95 |
]) |
| 96 |
expected = { |
| 97 |
'values_changed': { |
| 98 |
"root['coordinates'][0]['x']": {'new_value': 6, 'old_value': 5}, |
| 99 |
"root['coordinates'][0]['y']": {'new_value': 6, 'old_value': 5}, |
| 100 |
"root['coordinates'][1]['x']": {'new_value': 88, 'old_value': 8}, |
| 101 |
"root['coordinates'][1]['y']": {'new_value': 88, 'old_value': 8} |
| 102 |
}, |
| 103 |
'distance_too_far': { |
| 104 |
"root['coordinates'][0]": {'l2_distance': 1.4142135623730951}, |
| 105 |
"root['coordinates'][1]": {'l2_distance': 113.13708498984761} |
| 106 |
} |
| 107 |
} |
| 108 |
assert expected == ddiff |
| 109 |
|
| 110 |
def test_custom_operators_should_not_equal(self): |
| 111 |
t1 = { |
| 112 |
"id": 5, |
| 113 |
"expect_change_pos": 10, |
| 114 |
"expect_change_neg": 10, |
| 115 |
} |
| 116 |
|
| 117 |
t2 = { |
| 118 |
"id": 5, |
| 119 |
"expect_change_pos": 100, |
| 120 |
"expect_change_neg": 10, |
| 121 |
} |
| 122 |
|
| 123 |
class ExpectChangeOperator(BaseOperator): |
| 124 |
def __init__(self, regex_paths): |
| 125 |
super().__init__(regex_paths) |
| 126 |
|
| 127 |
def give_up_diffing(self, level, diff_instance) -> bool: |
| 128 |
if level.t1 == level.t2: |
| 129 |
diff_instance.custom_report_result('unexpected:still', level, { |
| 130 |
"old": level.t1, |
| 131 |
"new": level.t2 |
| 132 |
}) |
| 133 |
|
| 134 |
return True |
| 135 |
|
| 136 |
ddiff = DeepDiff(t1, t2, custom_operators=[ |
| 137 |
ExpectChangeOperator(regex_paths=["root\\['expect_change.*'\\]"]) |
| 138 |
]) |
| 139 |
|
| 140 |
assert ddiff == {'unexpected:still': {"root['expect_change_neg']": {'old': 10, 'new': 10}}} |
| 141 |
|
| 142 |
def test_custom_operator2(self): |
| 143 |
|
| 144 |
class CustomClass: |
| 145 |
|
| 146 |
def __init__(self, d: dict, l: list): |
| 147 |
self.dict = d |
| 148 |
self.dict['list'] = l |
| 149 |
|
| 150 |
def __repr__(self): |
| 151 |
return "Class list is " + str(self.dict['list']) |
| 152 |
|
| 153 |
custom1 = CustomClass(d=dict(a=1, b=2), l=[1, 2, 3]) |
| 154 |
custom2 = CustomClass(d=dict(c=3, d=4), l=[1, 2, 3, 2]) |
| 155 |
custom3 = CustomClass(d=dict(a=1, b=2), l=[1, 2, 3, 4]) |
| 156 |
|
| 157 |
class ListMatchOperator(BaseOperator): |
| 158 |
|
| 159 |
def give_up_diffing(self, level, diff_instance) -> bool: |
| 160 |
if set(level.t1.dict['list']) == set(level.t2.dict['list']): |
| 161 |
return True |
| 162 |
return False |
| 163 |
|
| 164 |
ddiff = DeepDiff(custom1, custom2, custom_operators=[ |
| 165 |
ListMatchOperator(types=[CustomClass]) |
| 166 |
]) |
| 167 |
|
| 168 |
assert {} == ddiff |
| 169 |
|
| 170 |
ddiff2 = DeepDiff(custom2, custom3, threshold_to_diff_deeper=0, custom_operators=[ |
| 171 |
ListMatchOperator(types=[CustomClass]) |
| 172 |
]) |
| 173 |
|
| 174 |
expected = { |
| 175 |
'dictionary_item_added': ["root.dict['a']", "root.dict['b']"], |
| 176 |
'dictionary_item_removed': ["root.dict['c']", "root.dict['d']"], |
| 177 |
'values_changed': {"root.dict['list'][3]": {'new_value': 4, 'old_value': 2}}} |
| 178 |
|
| 179 |
assert expected == ddiff2 |
| 180 |
|
| 181 |
def test_include_only_certain_path(self): |
| 182 |
|
| 183 |
class MyOperator: |
| 184 |
|
| 185 |
def __init__(self, include_paths): |
| 186 |
self.include_paths = include_paths |
| 187 |
|
| 188 |
def match(self, level) -> bool: |
| 189 |
return True |
| 190 |
|
| 191 |
def give_up_diffing(self, level, diff_instance) -> bool: |
| 192 |
return level.path() not in self.include_paths |
| 193 |
|
| 194 |
t1 = {'a': [10, 11], 'b': [20, 21], 'c': [30, 31]} |
| 195 |
t2 = {'a': [10, 22], 'b': [20, 33], 'c': [30, 44]} |
| 196 |
|
| 197 |
ddiff = DeepDiff(t1, t2, custom_operators=[ |
| 198 |
MyOperator(include_paths="root['a'][1]") |
| 199 |
]) |
| 200 |
|
| 201 |
expected = {'values_changed': {"root['a'][1]": {'new_value': 22, 'old_value': 11}}} |
| 202 |
assert expected == ddiff |
| 203 |
|
| 204 |
def test_give_up_diffing_on_first_diff(self): |
| 205 |
|
| 206 |
class MyOperator: |
| 207 |
|
| 208 |
def match(self, level) -> bool: |
| 209 |
return True |
| 210 |
|
| 211 |
def give_up_diffing(self, level, diff_instance) -> bool: |
| 212 |
return any(diff_instance.tree.values()) |
| 213 |
|
| 214 |
t1 = [[1, 2], [3, 4], [5, 6]] |
| 215 |
t2 = [[1, 3], [3, 5], [5, 7]] |
| 216 |
|
| 217 |
ddiff = DeepDiff(t1, t2, custom_operators=[ |
| 218 |
MyOperator() |
| 219 |
]) |
| 220 |
|
| 221 |
expected = {'values_changed': {'root[0][1]': {'new_value': 3, 'old_value': 2}}} |
| 222 |
assert expected == ddiff |
| 223 |
|
| 224 |
def test_prefix_or_suffix_diff(self): |
| 225 |
|
| 226 |
t1 = { |
| 227 |
"key1": ["foo", "bar's food", "jack", "joe"] |
| 228 |
} |
| 229 |
t2 = { |
| 230 |
"key1": ["foo", "bar", "jill", "joe'car"] |
| 231 |
} |
| 232 |
|
| 233 |
ddiff = DeepDiff(t1, t2, custom_operators=[ |
| 234 |
PrefixOrSuffixOperator() |
| 235 |
]) |
| 236 |
|
| 237 |
expected = {'values_changed': {"root['key1'][2]": {'new_value': 'jill', 'old_value': 'jack'}}} |
| 238 |
assert expected == ddiff |
| 239 |
|
| 240 |
with pytest.raises(NotImplementedError) as exp: |
| 241 |
DeepDiff(t1, t2, ignore_order=True, custom_operators=[ |
| 242 |
PrefixOrSuffixOperator() |
| 243 |
]) |
| 244 |
expected2 = 'PrefixOrSuffixOperator needs to define a normalize_value_for_hashing method to be compatible with ignore_order=True or iterable_compare_func.' |
| 245 |
assert expected2 == str(exp.value) |
| 246 |
|
| 247 |
def test_custom_operator3_small_numbers(self): |
| 248 |
x = [2.0000000000000027, 2.500000000000005, 2.000000000000002, 3.000000000000001] |
| 249 |
y = [2.000000000000003, 2.500000000000005, 2.0000000000000027, 3.0000000000000027] |
| 250 |
result = DeepDiff(x, y) |
| 251 |
expected = { |
| 252 |
'values_changed': { |
| 253 |
'root[0]': {'new_value': 2.000000000000003, 'old_value': 2.0000000000000027}, |
| 254 |
'root[2]': {'new_value': 2.0000000000000027, 'old_value': 2.000000000000002}, |
| 255 |
'root[3]': {'new_value': 3.0000000000000027, 'old_value': 3.000000000000001}}} |
| 256 |
assert expected == result |
| 257 |
|
| 258 |
class CustomCompare(BaseOperatorPlus): |
| 259 |
def __init__(self, tolerance, types): |
| 260 |
self.tolerance = tolerance |
| 261 |
self.types = types |
| 262 |
|
| 263 |
def match(self, level) -> bool: |
| 264 |
if type(level.t1) in self.types: |
| 265 |
return True |
| 266 |
return False |
| 267 |
|
| 268 |
def give_up_diffing(self, level, diff_instance) -> bool: |
| 269 |
relative = abs(abs(level.t1 - level.t2) / level.t1) |
| 270 |
if not max(relative, self.tolerance) == self.tolerance: |
| 271 |
custom_report = f'relative diff: {relative:.8e}' |
| 272 |
diff_instance.custom_report_result('diff', level, custom_report) |
| 273 |
return True |
| 274 |
|
| 275 |
def normalize_value_for_hashing(self, parent: Any, obj: Any) -> Any: |
| 276 |
return obj |
| 277 |
|
| 278 |
|
| 279 |
def compare_func(x, y, level): |
| 280 |
return True |
| 281 |
|
| 282 |
operators = [CustomCompare(types=[float], tolerance=5.5e-5)] |
| 283 |
result2 = DeepDiff(x, y, custom_operators=operators, iterable_compare_func=compare_func) |
| 284 |
assert {} == result2 |
| 285 |
|
| 286 |
result3 = DeepDiff(x, y, custom_operators=operators, zip_ordered_iterables=True) |
| 287 |
assert {} == result3, "We should get the same result as result2 when zip_ordered_iterables is True." |
| 288 |
|
| 289 |
def test_custom_operator_and_ignore_order1_using_base_operator_plus(self): |
| 290 |
|
| 291 |
d1 = { |
| 292 |
"Name": "SUB_OBJECT_FILES", |
| 293 |
"Values": { |
| 294 |
"Value": [ |
| 295 |
"{f254498b-b752-4f35-bef5-6f1844b61eb7}", |
| 296 |
"{7fb2a550-1849-45c0-b273-9aa5e4eb9f2b}", |
| 297 |
"{3a614c62-4252-48eb-b279-1450ee8af182}", |
| 298 |
"{208f22c4-c256-4311-9a45-e6c37d343458}", |
| 299 |
"{1fcf5d37-ef19-43a7-a1ad-d17c7c1713c6}", |
| 300 |
] |
| 301 |
} |
| 302 |
} |
| 303 |
|
| 304 |
d2 = { |
| 305 |
"Name": "SUB_OBJECT_FILES", |
| 306 |
"Values": { |
| 307 |
"Value": [ |
| 308 |
"{e5d18917-1a2c-4abe-b601-8ec002629953}", |
| 309 |
"{ea71ba1f-1339-4fae-bc28-a9ce9b8a8c67}", |
| 310 |
"{66bb6192-9cd2-4074-8be1-f2ac52877c70}", |
| 311 |
"{0c88b900-3755-4d10-93ef-b6a96dbcba90}", |
| 312 |
"{e39fdfc5-be6c-4f97-9345-9a8286381fe7}" |
| 313 |
] |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
|
| 318 |
class RemoveGUIDsOperator(BaseOperatorPlus): |
| 319 |
_pattern = r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}" |
| 320 |
_substitute = "guid" |
| 321 |
|
| 322 |
def match(self, level) -> bool: |
| 323 |
return isinstance(level.t1, str) and isinstance(level.t2, str) |
| 324 |
|
| 325 |
@classmethod |
| 326 |
def _remove_pattern(cls, t: str): |
| 327 |
return re.sub(cls._pattern, cls._substitute, t) |
| 328 |
|
| 329 |
def give_up_diffing(self, level, diff_instance): |
| 330 |
t1 = self._remove_pattern(level.t1) |
| 331 |
t2 = self._remove_pattern(level.t2) |
| 332 |
return t1 == t2 |
| 333 |
|
| 334 |
def normalize_value_for_hashing(self, parent: Any, obj: Any) -> Any: |
| 335 |
""" |
| 336 |
Used for ignore_order=True |
| 337 |
""" |
| 338 |
if isinstance(obj, str): |
| 339 |
return self._remove_pattern(obj) |
| 340 |
return obj |
| 341 |
|
| 342 |
|
| 343 |
operator = RemoveGUIDsOperator() |
| 344 |
|
| 345 |
diff1 = DeepDiff(d1, d2, custom_operators=[operator], log_stacktrace=True) |
| 346 |
assert not diff1 |
| 347 |
|
| 348 |
|
| 349 |
diff2 = DeepDiff(d1, d2, ignore_order=True, custom_operators=[operator], log_stacktrace=True) |
| 350 |
assert not diff2 |
| 351 |
|
| 352 |
|
| 353 |
def test_custom_operator_and_ignore_order2(self): |
| 354 |
d1 = { |
| 355 |
"Entity": { |
| 356 |
"Property": { |
| 357 |
"Name": "SUB_OBJECT_FILES", |
| 358 |
"Values": { |
| 359 |
"Value": [ |
| 360 |
"{f254498b-b752-4f35-bef5-6f1844b61eb7}", |
| 361 |
"{7fb2a550-1849-45c0-b273-9aa5e4eb9f2b}", |
| 362 |
"{3a614c62-4252-48eb-b279-1450ee8af182}", |
| 363 |
"{208f22c4-c256-4311-9a45-e6c37d343458}", |
| 364 |
"{1fcf5d37-ef19-43a7-a1ad-d17c7c1713c6}", |
| 365 |
"{a9cbecc0-21dc-49ce-8b2c-d36352dae139}" |
| 366 |
] |
| 367 |
} |
| 368 |
} |
| 369 |
} |
| 370 |
} |
| 371 |
|
| 372 |
d2 = { |
| 373 |
"Entity": { |
| 374 |
"Property": { |
| 375 |
"Name": "SUB_OBJECT_FILES", |
| 376 |
"Values": { |
| 377 |
"Value": [ |
| 378 |
"{e5d18917-1a2c-4abe-b601-8ec002629953}", |
| 379 |
"{ea71ba1f-1339-4fae-bc28-a9ce9b8a8c67}", |
| 380 |
"{d7778018-a7b5-4246-8caa-f590138d99e5}", |
| 381 |
"{66bb6192-9cd2-4074-8be1-f2ac52877c70}", |
| 382 |
"{0c88b900-3755-4d10-93ef-b6a96dbcba90}", |
| 383 |
"{e39fdfc5-be6c-4f97-9345-9a8286381fe7}" |
| 384 |
] |
| 385 |
} |
| 386 |
} |
| 387 |
} |
| 388 |
} |
| 389 |
|
| 390 |
class RemovePatternOperator(BaseOperator): |
| 391 |
_pattern: str = "" |
| 392 |
_substitute: str = "" |
| 393 |
|
| 394 |
@classmethod |
| 395 |
def _remove_pattern(cls, t: str): |
| 396 |
return re.sub(cls._pattern, cls._substitute, t) |
| 397 |
|
| 398 |
def give_up_diffing(self, level, diff_instance): |
| 399 |
if isinstance(level.t1, str) and isinstance(level.t2, str): |
| 400 |
t1 = self._remove_pattern(level.t1) |
| 401 |
t2 = self._remove_pattern(level.t2) |
| 402 |
return t1 == t2 |
| 403 |
return False |
| 404 |
|
| 405 |
class RemoveGUIDsOperator(RemovePatternOperator): |
| 406 |
_pattern = r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}" |
| 407 |
_substitute = "guid" |
| 408 |
|
| 409 |
diff1 = DeepDiff(deepcopy(d1), deepcopy(d2), ignore_order=False, custom_operators=[RemoveGUIDsOperator(types=[str])]) |
| 410 |
assert not diff1 |
| 411 |
|
| 412 |
with pytest.raises(NotImplementedError) as exp: |
| 413 |
DeepDiff(deepcopy(d1), deepcopy(d2), ignore_order=True, custom_operators=[RemoveGUIDsOperator(types=[str])]) |
| 414 |
expected2 = 'RemoveGUIDsOperator needs to define a normalize_value_for_hashing method to be compatible with ignore_order=True or iterable_compare_func.' |
| 415 |
assert expected2 == str(exp.value) |
| 416 |
|
| 417 |
|
| 418 |
# --------- Let's implement the normalize_value_for_hashing to make it work with ignore_order=True --------- |
| 419 |
|
| 420 |
class RemoveGUIDsOperatorIgnoreOrderReady(RemoveGUIDsOperator): |
| 421 |
def normalize_value_for_hashing(self, parent: Any, obj: Any) -> Any: |
| 422 |
if isinstance(obj, str): |
| 423 |
return self._remove_pattern(obj) |
| 424 |
return obj |
| 425 |
|
| 426 |
diff3 = DeepDiff(deepcopy(d1), deepcopy(d2), ignore_order=True, custom_operators=[RemoveGUIDsOperatorIgnoreOrderReady(types=[str])]) |
| 427 |
assert not diff3, "We shouldn't have a diff because we have normalized the string values to be all the same vlues." |
| 428 |
|