Debian Codegraph @

tests/test_diff_text.py

raw
1 #!/usr/bin/env python
2 import datetime
3 import pytest
4 import logging
5 import re
6 import uuid
7 from enum import Enum
8 from dataclasses import dataclass
9 from typing import List
10 from decimal import Decimal
11 from deepdiff import DeepDiff
12 from deepdiff.helper import pypy3, PydanticBaseModel, np_float64
13 from tests import CustomClass
14
15
16 logging.disable(logging.CRITICAL)
17
18
19 class MyEnum1(Enum):
20 book = "book"
21 cake = "cake"
22
23 class MyEnum2(str, Enum):
24 book = "book"
25 cake = "cake"
26
27
28 @dataclass(frozen=True)
29 class MyDataClass:
30 val: int
31 val2: int
32
33
34 class TestDeepDiffText:
35 """DeepDiff Tests."""
36
37 def test_same_objects(self):
38 t1 = {1: 1, 2: 2, 3: 3}
39 t2 = t1
40 assert {} == DeepDiff(t1, t2)
41
42 def test_item_type_change(self):
43 t1 = {1: 1, 2: 2, 3: 3}
44 t2 = {1: 1, 2: "2", 3: 3}
45 ddiff = DeepDiff(t1, t2)
46 assert {
47 'type_changes': {
48 "root[2]": {
49 "old_value": 2,
50 "old_type": int,
51 "new_value": "2",
52 "new_type": str
53 }
54 }
55 } == ddiff
56
57 def test_item_type_change_less_verbose(self):
58 t1 = {1: 1, 2: 2, 3: 3}
59 t2 = {1: 1, 2: "2", 3: 3}
60 assert {'type_changes': {
61 "root[2]": {
62 "old_type": int,
63 "new_type": str
64 }
65 }} == DeepDiff(t1, t2, verbose_level=0)
66
67 def test_item_type_change_for_strings_ignored_by_default(self):
68 """ ignore_string_type_changes = True by default """
69
70 t1 = 'hello'
71 t2 = b'hello'
72 ddiff = DeepDiff(t1, t2, ignore_string_type_changes=True)
73 assert not ddiff
74
75 def test_item_type_change_for_strings_override(self):
76 t1 = 'hello'
77 t2 = b'hello'
78 ddiff = DeepDiff(t1, t2, ignore_string_type_changes=False)
79 assert {
80 'type_changes': {
81 'root': {
82 'old_type': str,
83 'new_type': bytes,
84 'old_value': 'hello',
85 'new_value': b'hello'
86 }
87 }
88 } == ddiff
89
90 def test_value_change(self):
91 t1 = {1: 1, 2: 2, 3: 3}
92 t2 = {1: 1, 2: 4, 3: 3}
93 result = {
94 'values_changed': {
95 'root[2]': {
96 "old_value": 2,
97 "new_value": 4
98 }
99 }
100 }
101 assert result == DeepDiff(t1, t2)
102
103 def test_item_added_and_removed(self):
104 t1 = {1: 1, 2: 2, 3: [3], 4: 4}
105 t2 = {1: 1, 2: 4, 3: [3, 4], 5: 5, 6: 6}
106 ddiff = DeepDiff(t1, t2, threshold_to_diff_deeper=0)
107 result = {
108 'dictionary_item_added': ["root[5]", "root[6]"],
109 'dictionary_item_removed': ["root[4]"],
110 'values_changed': {
111 'root[2]': {
112 'new_value': 4,
113 'old_value': 2
114 }
115 },
116 'iterable_item_added': {
117 'root[3][1]': 4
118 }
119 }
120 assert result == ddiff
121 assert {'root[4]', 'root[5]', 'root[6]', 'root[3][1]', 'root[2]'} == ddiff.affected_paths
122 assert {4, 5, 6, 3, 2} == ddiff.affected_root_keys
123
124 def test_item_added_and_removed_verbose(self):
125 t1 = {1: 1, 3: 3, 4: 4}
126 t2 = {1: 1, 3: 3, 5: 5, 6: 6}
127 ddiff = DeepDiff(t1, t2, verbose_level=2)
128 result = {
129 'dictionary_item_removed': {
130 'root[4]': 4
131 },
132 'dictionary_item_added': {
133 'root[6]': 6,
134 'root[5]': 5
135 }
136 }
137 assert result == ddiff
138
139 def test_diffs_dates(self):
140 t1 = datetime.date(2016, 8, 8)
141 t2 = datetime.date(2016, 8, 7)
142 ddiff = DeepDiff(t1, t2)
143 result = {
144 'values_changed': {
145 'root': {
146 'new_value': t2,
147 'old_value': t1
148 }
149 }
150 }
151 assert result == ddiff
152
153 def test_diffs_timedeltas(self):
154 t1 = datetime.timedelta(days=1, seconds=12)
155 t2 = datetime.timedelta(days=1, seconds=10)
156 t3 = datetime.timedelta(seconds=(60*60*24) + 12)
157 ddiff = DeepDiff(t1, t2)
158 result = {
159 'values_changed': {
160 'root': {
161 'new_value': t2,
162 'old_value': t1
163 }
164 }
165 }
166 assert result == ddiff
167 ddiff = DeepDiff(t1, t3)
168 result = {}
169 assert result == ddiff
170
171 def test_diffs_times(self):
172 t1 = datetime.time(1, 1)
173 t2 = datetime.time(1, 2)
174 t3 = datetime.time(1, 1)
175 expected_result = {
176 'values_changed': {
177 'root': {
178 'new_value': t2,
179 'old_value': t1
180 }
181 }
182 }
183 assert DeepDiff(t1, t2) == expected_result
184 assert DeepDiff(t1, t3) == {}
185
186 def test_diffs_uuid1(self):
187 t1 = uuid.uuid1()
188 t2 = uuid.uuid1()
189 ddiff = DeepDiff(t1, t2)
190 result = {
191 'values_changed': {
192 'root': {
193 'new_value': t2,
194 'old_value': t1
195 }
196 }
197 }
198 assert result == ddiff
199 ddiff = DeepDiff(t1, t1)
200 result = {}
201 assert result == ddiff
202
203 def test_diffs_uuid3(self):
204 t1 = uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
205 t2 = uuid.uuid3(uuid.NAMESPACE_DNS, 'stackoverflow.com')
206 ddiff = DeepDiff(t1, t2)
207 result = {
208 'values_changed': {
209 'root': {
210 'new_value': t2,
211 'old_value': t1
212 }
213 }
214 }
215 assert result == ddiff
216 ddiff = DeepDiff(t1, t1)
217 result = {}
218 assert result == ddiff
219
220 def test_diffs_uuid4(self):
221 t1 = uuid.uuid4()
222 t2 = uuid.uuid4()
223 ddiff = DeepDiff(t1, t2)
224 result = {
225 'values_changed': {
226 'root': {
227 'new_value': t2,
228 'old_value': t1
229 }
230 }
231 }
232 assert result == ddiff
233 ddiff = DeepDiff(t1, t1)
234 result = {}
235 assert result == ddiff
236
237 def test_diffs_uuid5(self):
238 t1 = uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
239 t2 = uuid.uuid5(uuid.NAMESPACE_DNS, 'stackoverflow.com')
240 ddiff = DeepDiff(t1, t2)
241 result = {
242 'values_changed': {
243 'root': {
244 'new_value': t2,
245 'old_value': t1
246 }
247 }
248 }
249 assert result == ddiff
250 ddiff = DeepDiff(t1, t1)
251 result = {}
252 assert result == ddiff
253
254 def test_string_difference(self):
255 t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": "world"}}
256 t2 = {1: 1, 2: 4, 3: 3, 4: {"a": "hello", "b": "world!"}}
257 ddiff = DeepDiff(t1, t2)
258 result = {
259 'values_changed': {
260 'root[2]': {
261 'old_value': 2,
262 'new_value': 4
263 },
264 "root[4]['b']": {
265 'old_value': 'world',
266 'new_value': 'world!'
267 }
268 }
269 }
270 assert result == ddiff
271
272 def test_diffs_equal_strings_when_not_identical(self):
273 t1 = 'hello'
274 t2 = 'hel'
275 t2 += 'lo'
276 assert t1 is not t2
277 ddiff = DeepDiff(t1, t2)
278 assert {} == ddiff
279
280 def test_string_difference2(self):
281 t1 = {
282 1: 1,
283 2: 2,
284 3: 3,
285 4: {
286 "a": "hello",
287 "b": "world!\nGoodbye!\n1\n2\nEnd"
288 }
289 }
290 t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": "world\n1\n2\nEnd"}}
291 ddiff = DeepDiff(t1, t2)
292 result = {
293 'values_changed': {
294 "root[4]['b']": {
295 'diff':
296 '--- \n+++ \n@@ -1,5 +1,4 @@\n-world!\n-Goodbye!\n+world\n 1\n 2\n End',
297 'new_value': 'world\n1\n2\nEnd',
298 'old_value': 'world!\nGoodbye!\n1\n2\nEnd'
299 }
300 }
301 }
302 assert result == ddiff
303
304 def test_string_difference_ignore_case(self):
305 t1 = "Hello"
306 t2 = "hello"
307
308 ddiff = DeepDiff(t1, t2)
309 result = {'values_changed': {'root': {'new_value': 'hello', 'old_value': 'Hello'}}}
310 assert result == ddiff
311
312 ddiff = DeepDiff(t1, t2, ignore_string_case=True)
313 result = {}
314 assert result == ddiff
315
316 def test_string_dict_key_ignore_case(self):
317 t1 = {'User': {'AboutMe': 1, 'ALIAS': 1}}
318 t2 = {'User': {'Alias': 1, 'AboutMe': 1}}
319 ddiff = DeepDiff(t1, t2)
320 result = {'dictionary_item_added': ["root['User']['Alias']"], 'dictionary_item_removed': ["root['User']['ALIAS']"]}
321 assert result == ddiff
322
323 ddiff = DeepDiff(t1, t2, ignore_string_case=True)
324 result = {}
325 assert result == ddiff
326
327 def test_string_list_ignore_case(self):
328 t1 = ['AboutMe', 'ALIAS']
329 t2 = ['aboutme', 'alias']
330 ddiff = DeepDiff(t1, t2)
331 result = {'values_changed': {'root[0]': {'new_value': 'aboutme', 'old_value': 'AboutMe'}, 'root[1]': {'new_value': 'alias', 'old_value': 'ALIAS'}}}
332 assert result == ddiff
333
334 ddiff = DeepDiff(t1, t2, ignore_string_case=True)
335 result = {}
336 assert result == ddiff
337
338 def test_diff_quote_in_string(self):
339 t1 = {
340 "a']['b']['c": 1
341 }
342 t2 = {
343 "a']['b']['c": 2
344 }
345 diff = DeepDiff(t1, t2)
346 expected = {'values_changed': {'''root["a']['b']['c"]''': {'new_value': 2, 'old_value': 1}}}
347 assert expected == diff
348
349 def test_diff_quote_and_double_quote_in_string(self):
350 t1 = {'''a'"a''': 1}
351 t2 = {'''a'"a''': 2}
352 diff = DeepDiff(t1, t2)
353 expected = {'values_changed': {'root["a\'"a"]': {'new_value': 2, 'old_value': 1}}}
354 assert expected == diff
355
356 def test_bytes(self):
357 t1 = {
358 1: 1,
359 2: 2,
360 3: 3,
361 4: {
362 "a": b"hello",
363 "b": b"world!\nGoodbye!\n1\n2\nEnd",
364 "c": b"\x80",
365 }
366 }
367 t2 = {
368 1: 1,
369 2: 2,
370 3: 3,
371 4: {
372 "a": b"hello",
373 "b": b"world\n1\n2\nEnd",
374 "c": b'\x81',
375 }
376 }
377
378 ddiff = DeepDiff(t1, t2)
379 result = {
380 'values_changed': {
381 "root[4]['b']": {
382 'diff':
383 '--- \n+++ \n@@ -1,5 +1,4 @@\n-world!\n-Goodbye!\n+world\n 1\n 2\n End',
384 'new_value': b'world\n1\n2\nEnd',
385 'old_value': b'world!\nGoodbye!\n1\n2\nEnd'
386 },
387 "root[4]['c']": {
388 'new_value': b'\x81',
389 'old_value': b'\x80'
390 }
391 }
392 }
393 assert result == ddiff
394
395 def test_unicode(self):
396 t1 = {
397 1: 1,
398 2: 2,
399 3: 3,
400 4: {
401 "a": "hello",
402 "b": "world!\nGoodbye!\n1\n2\nEnd"
403 }
404 }
405 t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": "world\n1\n2\nEnd"}}
406 ddiff = DeepDiff(t1, t2)
407 result = {
408 'values_changed': {
409 "root[4]['b']": {
410 'diff':
411 '--- \n+++ \n@@ -1,5 +1,4 @@\n-world!\n-Goodbye!\n+world\n 1\n 2\n End',
412 'new_value': 'world\n1\n2\nEnd',
413 'old_value': 'world!\nGoodbye!\n1\n2\nEnd'
414 }
415 }
416 }
417 assert result == ddiff
418
419 def test_type_change(self):
420 t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, 3]}}
421 t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": "world\n\n\nEnd"}}
422 ddiff = DeepDiff(t1, t2)
423 result = {
424 'type_changes': {
425 "root[4]['b']": {
426 'old_type': list,
427 'new_value': 'world\n\n\nEnd',
428 'old_value': [1, 2, 3],
429 'new_type': str
430 }
431 }
432 }
433 assert result == ddiff
434
435 def test_list_difference(self):
436 t1 = {
437 1: 1,
438 2: 2,
439 3: 3,
440 4: {
441 "a": "hello",
442 "b": [1, 2, 'to_be_removed', 'to_be_removed2']
443 }
444 }
445 t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2]}}
446 ddiff = DeepDiff(t1, t2)
447 result = {
448 'iterable_item_removed': {
449 "root[4]['b'][2]": "to_be_removed",
450 "root[4]['b'][3]": 'to_be_removed2'
451 }
452 }
453 assert result == ddiff
454
455 def test_list_difference_add(self):
456 t1 = [1, 2]
457 t2 = [1, 2, 3, 5]
458 ddiff = DeepDiff(t1, t2)
459 result = {'iterable_item_added': {'root[2]': 3, 'root[3]': 5}}
460 assert result == ddiff
461
462 def test_list_difference2(self):
463 t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, 3, 10, 12]}}
464 t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 3, 2]}}
465 result = {
466 'values_changed': {
467 "root[4]['b'][2]": {
468 'new_value': 2,
469 'old_value': 3
470 },
471 "root[4]['b'][1]": {
472 'new_value': 3,
473 'old_value': 2
474 }
475 },
476 'iterable_item_removed': {
477 "root[4]['b'][3]": 10,
478 "root[4]['b'][4]": 12
479 }
480 }
481 ddiff = DeepDiff(t1, t2)
482 assert result == ddiff
483
484 def test_list_difference3(self):
485 t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, 5]}}
486 t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 3, 2, 5]}}
487 ddiff = DeepDiff(t1, t2)
488 expected = {'iterable_item_added': {"root[4]['b'][1]": 3}}
489 assert expected == ddiff
490
491 def test_list_difference4(self):
492 t1 = ["a", "b", "d", "e"]
493 t2 = ["a", "b", "c", "d", "e"]
494 ddiff = DeepDiff(t1, t2)
495 result = {'iterable_item_added': {'root[2]': 'c'}}
496 assert result == ddiff
497
498 def test_list_difference5(self):
499 t1 = ["a", "b", "d", "e", "f", "g"]
500 t2 = ["a", "b", "c", "d", "e", "f"]
501 ddiff = DeepDiff(t1, t2)
502 result = {'iterable_item_added': {'root[2]': 'c'}, 'iterable_item_removed': {'root[5]': 'g'}}
503 assert result == ddiff
504
505 def test_list_difference_with_tiny_variations(self):
506 t1 = ['a', 'b', 'c', 'd']
507 t2 = ['f', 'b', 'a', 'g']
508
509 values = {
510 'a': 2.0000000000000027,
511 'b': 2.500000000000005,
512 'c': 2.000000000000002,
513 'd': 3.000000000000001,
514 'f': 2.000000000000003,
515 'g': 3.0000000000000027,
516 }
517 ddiff = DeepDiff(t1, t2)
518 result = {
519 'values_changed': {
520 'root[0]': {
521 'new_value': 'f',
522 'old_value': 'a'
523 },
524 'root[2]': {
525 'new_value': 'a',
526 'old_value': 'c'
527 },
528 'root[3]': {
529 'new_value': 'g',
530 'old_value': 'd'
531 }
532 }
533 }
534 assert result == ddiff
535
536 ddiff2 = DeepDiff(t1, t2, zip_ordered_iterables=True)
537 assert result == ddiff2
538 # Now we change the characters with numbers with tiny variations
539
540 t3 = [2.0000000000000027, 2.500000000000005, 2.000000000000002, 3.000000000000001]
541 t4 = [2.000000000000003, 2.500000000000005, 2.0000000000000027, 3.0000000000000027]
542 ddiff3 = DeepDiff(t3, t4)
543
544 expected = {'values_changed': {}}
545 for path, report in result['values_changed'].items():
546 expected['values_changed'][path] = {
547 'new_value': values[report['new_value']],
548 'old_value': values[report['old_value']],
549 }
550 assert expected == ddiff3
551
552 def test_list_of_booleans(self):
553 t1 = [False, False, True, True]
554 t2 = [False, False, False, True]
555 ddiff = DeepDiff(t1, t2)
556 assert {'values_changed': {'root[2]': {'new_value': False, 'old_value': True}}} == ddiff
557
558 def test_set_of_none(self):
559 """
560 https://github.com/seperman/deepdiff/issues/64
561 """
562 ddiff = DeepDiff(set(), {None})
563 assert {'set_item_added': {'root[None]'}} == ddiff
564
565 def test_list_that_contains_dictionary(self):
566 t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, {1: 1, 2: 2}]}}
567 t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, {1: 3}]}}
568 ddiff = DeepDiff(t1, t2)
569 result = {
570 'dictionary_item_removed': {"root[4]['b'][2][2]"},
571 'values_changed': {
572 "root[4]['b'][2][1]": {
573 'old_value': 1,
574 'new_value': 3
575 }
576 }
577 }
578 assert result == ddiff
579
580 def test_set(self):
581 t1 = {1, 2, 8}
582 t2 = {1, 2, 3, 5}
583 ddiff = DeepDiff(t1, t2)
584 result = {
585 'set_item_added': {'root[3]', 'root[5]'},
586 'set_item_removed': {'root[8]'}
587 }
588 assert result == ddiff
589
590 def test_set_strings(self):
591 t1 = {"veggies", "tofu"}
592 t2 = {"veggies", "tofu", "seitan"}
593 ddiff = DeepDiff(t1, t2)
594 result = {'set_item_added': {"root['seitan']"}}
595 assert result == ddiff
596
597 def test_frozenset(self):
598 t1 = frozenset([1, 2, 'B'])
599 t2 = frozenset([1, 2, 3, 5])
600 ddiff = DeepDiff(t1, t2)
601 result = {
602 'set_item_added': {'root[3]', 'root[5]'},
603 'set_item_removed': {"root['B']"}
604 }
605 assert result == ddiff
606
607 def test_tuple(self):
608 t1 = (1, 2, 8)
609 t2 = (1, 2, 3, 5)
610 ddiff = DeepDiff(t1, t2)
611 result = {
612 'values_changed': {
613 'root[2]': {
614 'old_value': 8,
615 'new_value': 3
616 }
617 },
618 'iterable_item_added': {
619 'root[3]': 5
620 }
621 }
622 assert result == ddiff
623
624 def test_named_tuples(self):
625 from collections import namedtuple
626 Point = namedtuple('Point', ['x', 'y'])
627 t1 = Point(x=11, y=22)
628 t2 = Point(x=11, y=23)
629 ddiff = DeepDiff(t1, t2)
630 result = {
631 'values_changed': {
632 'root.y': {
633 'old_value': 22,
634 'new_value': 23
635 }
636 }
637 }
638 assert result == ddiff
639
640 def test_enums(self):
641
642 class MyEnum(Enum):
643 A = 1
644 B = 2
645
646 ddiff = DeepDiff(MyEnum.A, MyEnum(1))
647 result = {}
648 assert ddiff == result
649
650 ddiff = DeepDiff(MyEnum.A, MyEnum.B)
651 result = {
652 'values_changed': {
653 'root.name': {
654 'old_value': 'A',
655 'new_value': 'B'
656 },
657 'root.value': {
658 'old_value': 1,
659 'new_value': 2
660 },
661 }
662 }
663 assert ddiff == result
664
665 def test_enum_ignore_type_change(self):
666
667 diff = DeepDiff("book", MyEnum1.book)
668 expected = {
669 'type_changes': {'root': {'old_type': str, 'new_type': MyEnum1, 'old_value': 'book', 'new_value': MyEnum1.book}}}
670 assert expected == diff
671
672 diff2 = DeepDiff("book", MyEnum1.book, ignore_type_in_groups=[(Enum, str)])
673 assert not diff2
674
675 diff3 = DeepDiff("book", MyEnum2.book, ignore_type_in_groups=[(Enum, str)])
676 assert not diff3
677
678 def test_enum_use_enum_value1(self):
679 diff = DeepDiff("book", MyEnum2.book, use_enum_value=True)
680 assert not diff
681
682 def test_enum_use_enum_value_in_dict_key(self):
683 diff = DeepDiff({"book": 2}, {MyEnum2.book: 2}, use_enum_value=True)
684 assert not diff
685
686 def test_precompiled_regex(self):
687
688 pattern_1 = re.compile('foo')
689 pattern_2 = re.compile('foo')
690 pattern_3 = re.compile('foo', flags=re.I)
691 pattern_4 = re.compile('(foo)')
692 pattern_5 = re.compile('bar')
693
694 # same object
695 ddiff = DeepDiff(pattern_1, pattern_1)
696 result = {}
697 assert ddiff == result
698
699 # same pattern, different object
700 ddiff = DeepDiff(pattern_1, pattern_2)
701 result = {}
702 assert ddiff == result
703
704 # same pattern, different flags
705 ddiff = DeepDiff(pattern_1, pattern_3)
706 result = {
707 'values_changed': {
708 'root.flags': {
709 'new_value': 34,
710 'old_value': 32,
711 },
712 }
713 }
714 assert ddiff == result
715
716 # same pattern, different groups
717 ddiff = DeepDiff(pattern_1, pattern_4)
718 result = {
719 'values_changed': {
720 'root.pattern': {
721 'new_value': '(foo)',
722 'old_value': 'foo',
723 },
724 'root.groups': {
725 'new_value': 1,
726 'old_value': 0,
727 },
728 }
729 }
730 assert ddiff == result
731
732 # different pattern
733 ddiff = DeepDiff(pattern_1, pattern_5)
734 result = {
735 'values_changed': {
736 'root.pattern': {
737 'new_value': 'bar',
738 'old_value': 'foo',
739 },
740 }
741 }
742 assert ddiff == result
743
744 def test_custom_objects_change(self):
745 t1 = CustomClass(1)
746 t2 = CustomClass(2)
747 ddiff = DeepDiff(t1, t2)
748 result = {
749 'values_changed': {
750 'root.a': {
751 'old_value': 1,
752 'new_value': 2
753 }
754 }
755 }
756 assert result == ddiff
757
758 def test_custom_objects_slot_change(self):
759 class ClassA:
760 __slots__ = ('x', 'y')
761
762 def __init__(self, x, y):
763 self.x = x
764 self.y = y
765
766 t1 = ClassA(1, 1)
767 t2 = ClassA(1, 2)
768 ddiff = DeepDiff(t1, t2)
769 result = {
770 'values_changed': {
771 'root.y': {
772 'old_value': 1,
773 'new_value': 2
774 }
775 }
776 }
777 assert result == ddiff
778
779 def test_custom_class_changes_with_slot_changes(self):
780 class ClassA:
781 __slots__ = ['x', 'y']
782
783 def __init__(self, x, y):
784 self.x = x
785 self.y = y
786
787 class ClassB:
788 __slots__ = ['x']
789
790 ddiff = DeepDiff(ClassA, ClassB)
791 result = {'type_changes': {'root': {'old_type': ClassA, 'new_type': ClassB}}}
792 assert result == ddiff
793
794 def test_custom_class_changes_with_slot_change_when_ignore_type(self):
795 class ClassA:
796 __slots__ = ['x', 'y']
797
798 def __init__(self, x, y):
799 self.x = x
800 self.y = y
801
802 class ClassB:
803 __slots__ = ['x']
804
805 ddiff = DeepDiff(ClassA, ClassB, ignore_type_in_groups=[(ClassA, ClassB)])
806 result = {'attribute_removed': ['root.y']}
807 assert result == ddiff
808
809 def test_custom_objects_slot_in_group_change(self):
810 class ClassA:
811 __slots__ = ('x', 'y')
812
813 def __init__(self, x, y):
814 self.x = x
815 self.y = y
816
817 class ClassB(ClassA):
818 pass
819
820 t1 = ClassA(1, 1)
821 t2 = ClassB(1, 1)
822 ddiff = DeepDiff(t1, t2, ignore_type_in_groups=[(ClassA, ClassB)])
823 result = {}
824 assert result == ddiff
825
826
827 def test_custom_class_changes_none_when_ignore_type(self):
828 ddiff1 = DeepDiff({'a': None}, {'a': 1}, ignore_type_subclasses=True, ignore_type_in_groups=[(int, float)])
829 result = {
830 'type_changes': {
831 "root['a']": {
832 'old_type': type(None),
833 'new_type': int,
834 'old_value': None,
835 'new_value': 1
836 }
837 }
838 }
839 assert result == ddiff1
840
841 ddiff2 = DeepDiff({'a': None}, {'a': '1'}, ignore_type_subclasses=True, ignore_type_in_groups=[(str, int, float, None)])
842 assert {'values_changed': {"root['a']": {'new_value': '1', 'old_value': None}}} == ddiff2
843
844 ddiff3 = DeepDiff({'a': '1'}, {'a': None}, ignore_type_subclasses=True, ignore_type_in_groups=[(str, int, float, None)])
845 assert {'values_changed': {"root['a']": {'new_value': None, 'old_value': '1'}}} == ddiff3
846
847 ddiff4 = DeepDiff({'a': {'b': None}}, {'a': {'b': '1'}}, ignore_type_subclasses=True, ignore_type_in_groups=[(str, int, float, None)])
848 assert {'values_changed': {"root['a']['b']": {'new_value': '1', 'old_value': None}}} == ddiff4
849
850 ddiff5 = DeepDiff({'a': {'b': '1'}}, {'a': {'b': None}}, ignore_type_subclasses=True, ignore_type_in_groups=[(str, int, float, None)])
851 assert {'values_changed': {"root['a']['b']": {'new_value': None, 'old_value': '1'}}} == ddiff5
852
853 def test_custom_object_changes_when_ignore_type_in_groups(self):
854 class ClassA:
855 def __init__(self, x, y):
856 self.x = x
857 self.y = y
858
859 class ClassB:
860 def __init__(self, x):
861 self.x = x
862
863 class ClassC(ClassB):
864 def __repr__(self):
865 return "obj c"
866
867 obj_a = ClassA(1, 2)
868 obj_c = ClassC(3)
869 ddiff = DeepDiff(obj_a, obj_c, ignore_type_in_groups=[(ClassA, ClassB)], ignore_type_subclasses=True)
870 result = {'type_changes': {'root': {'old_type': ClassA, 'new_type': ClassC, 'old_value': obj_a, 'new_value': obj_c}}}
871 assert result == ddiff
872
873 ddiff = DeepDiff(obj_a, obj_c, ignore_type_in_groups=[(ClassA, ClassB)], ignore_type_subclasses=False)
874 result = {'values_changed': {'root.x': {'new_value': 3, 'old_value': 1}}, 'attribute_removed': ['root.y']}
875 assert result == ddiff
876
877 def test_custom_objects_slot_in_parent_class_change(self):
878 class ClassA:
879 __slots__ = ['x']
880
881 class ClassB(ClassA):
882 __slots__ = ['y']
883
884 def __init__(self, x, y):
885 self.x = x
886 self.y = y
887
888 t1 = ClassB(1, 1)
889 t2 = ClassB(2, 1)
890 ddiff = DeepDiff(t1, t2)
891 result = {
892 'values_changed': {
893 'root.x': {
894 'old_value': 1,
895 'new_value': 2
896 }
897 }
898 }
899 assert result == ddiff
900
901 def test_custom_objects_with_single_protected_slot(self):
902 class ClassA:
903 __slots__ = '__a'
904
905 def __init__(self):
906 self.__a = 1
907
908 def __str__(self):
909 return str(self.__a)
910
911 t1 = ClassA()
912 t2 = ClassA()
913 ddiff = DeepDiff(t1, t2)
914 assert {} == ddiff
915
916 def test_custom_objects_with_weakref_in_slots(self):
917 class ClassA:
918 __slots__ = ['a', '__weakref__']
919
920 def __init__(self, a):
921 self.a = a
922
923 t1 = ClassA(1)
924 t2 = ClassA(2)
925 diff = DeepDiff(t1, t2)
926 result = {
927 'values_changed': {
928 'root.a': {
929 'new_value': 2,
930 'old_value': 1
931 }
932 },
933 }
934 assert result == diff
935
936 def get_custom_objects_add_and_remove(self):
937 class ClassA:
938 a = 1
939
940 def __init__(self, b):
941 self.b = b
942 self.d = 10
943
944 t1 = ClassA(1)
945 t2 = ClassA(2)
946 t2.c = "new attribute"
947 del t2.d
948 return t1, t2
949
950 def test_custom_objects_add_and_remove(self):
951 t1, t2 = self.get_custom_objects_add_and_remove()
952 ddiff = DeepDiff(t1, t2)
953 result = {
954 'attribute_added': {'root.c'},
955 'values_changed': {
956 'root.b': {
957 'new_value': 2,
958 'old_value': 1
959 }
960 },
961 'attribute_removed': {'root.d'}
962 }
963 assert result == ddiff
964
965 def test_custom_objects_add_and_remove_verbose(self):
966 t1, t2 = self.get_custom_objects_add_and_remove()
967 ddiff = DeepDiff(t1, t2, verbose_level=2)
968 result = {
969 'attribute_added': {
970 'root.c': 'new attribute'
971 },
972 'attribute_removed': {
973 'root.d': 10
974 },
975 'values_changed': {
976 'root.b': {
977 'new_value': 2,
978 'old_value': 1
979 }
980 }
981 }
982 assert result == ddiff
983
984 def get_custom_object_with_added_removed_methods(self):
985 class ClassA:
986 VAL = 1
987 VAL2 = 2
988
989 def method_a(self):
990 pass
991
992 t1 = ClassA()
993 t2 = ClassA()
994
995 def method_b(self):
996 pass
997
998 def method_c(self):
999 return "hello"
1000
1001 t2.method_b = method_b
1002 t2.method_a = method_c
1003 # Note that we are comparing ClassA instances. method_a originally was in ClassA
1004 # But we also added another version of it to t2. So it comes up as
1005 # added attribute.
1006 return t1, t2
1007
1008 def test_custom_objects_add_and_remove_method(self):
1009 t1, t2 = self.get_custom_object_with_added_removed_methods()
1010 ddiff = DeepDiff(t1, t2)
1011
1012 result = {'attribute_added': {'root.method_a', 'root.method_b'}}
1013 assert result == ddiff
1014
1015 def test_custom_objects_add_and_remove_method_verbose(self):
1016 t1, t2 = self.get_custom_object_with_added_removed_methods()
1017 ddiff = DeepDiff(t1, t2, verbose_level=2)
1018 assert 'root.method_a' in ddiff['attribute_added']
1019 assert 'root.method_b' in ddiff['attribute_added']
1020
1021 def test_set_of_custom_objects(self):
1022 member1 = CustomClass(13, 37)
1023 member2 = CustomClass(13, 37)
1024 t1 = {member1}
1025 t2 = {member2}
1026 ddiff = DeepDiff(t1, t2)
1027 result = {}
1028 assert result == ddiff
1029
1030 def test_dictionary_of_custom_objects(self):
1031 member1 = CustomClass(13, 37)
1032 member2 = CustomClass(13, 37)
1033 t1 = {1: member1}
1034 t2 = {1: member2}
1035 ddiff = DeepDiff(t1, t2)
1036 result = {}
1037 assert result == ddiff
1038
1039 def test_dictionary_with_string_keys1(self):
1040 t1 = {"veggie": "carrots"}
1041 t2 = {"meat": "carrots"}
1042
1043 diff = DeepDiff(t1, t2, threshold_to_diff_deeper=0)
1044 assert {'dictionary_item_added': ["root['meat']"],
1045 'dictionary_item_removed': ["root['veggie']"]} == diff
1046
1047 def test_dictionary_with_string_keys_threshold_to_diff_deeper(self):
1048 t1 = {"veggie": "carrots"}
1049 t2 = {"meat": "carrots"}
1050
1051 diff = DeepDiff(t1, t2, threshold_to_diff_deeper=0.33)
1052 assert {'values_changed': {'root': {'new_value': {'meat': 'carrots'}, 'old_value': {'veggie': 'carrots'}}}} == diff
1053
1054 def test_dictionary_with_numeric_keys(self):
1055 t1 = {Decimal('10.01'): "carrots"}
1056 t2 = {10.01: "carrots"}
1057 diff = DeepDiff(t1, t2, threshold_to_diff_deeper=0)
1058 assert {'dictionary_item_added': ["root[10.01]"], 'dictionary_item_removed': ["root[Decimal('10.01')]"]} == diff
1059
1060 diff2 = DeepDiff(t1, t2)
1061 assert {'values_changed': {'root': {'new_value': {10.01: 'carrots'}, 'old_value': {Decimal('10.01'): 'carrots'}}}} == diff2
1062
1063 def test_loop(self):
1064 class LoopTest:
1065 def __init__(self, a):
1066 self.loop = self
1067 self.a = a
1068
1069 t1 = LoopTest(1)
1070 t2 = LoopTest(2)
1071
1072 ddiff = DeepDiff(t1, t2)
1073 result = {
1074 'values_changed': {
1075 'root.a': {
1076 'old_value': 1,
1077 'new_value': 2
1078 }
1079 }
1080 }
1081 assert result == ddiff
1082
1083 def test_loop2(self):
1084 class LoopTestA:
1085 def __init__(self, a):
1086 self.loop = LoopTestB
1087 self.a = a
1088
1089 class LoopTestB:
1090 def __init__(self, a):
1091 self.loop = LoopTestA
1092 self.a = a
1093
1094 t1 = LoopTestA(1)
1095 t2 = LoopTestA(2)
1096
1097 ddiff = DeepDiff(t1, t2)
1098 result = {
1099 'values_changed': {
1100 'root.a': {
1101 'old_value': 1,
1102 'new_value': 2
1103 }
1104 }
1105 }
1106 assert result == ddiff
1107
1108 def test_loop3(self):
1109 class LoopTest:
1110 def __init__(self, a):
1111 self.loop = LoopTest
1112 self.a = a
1113
1114 t1 = LoopTest(1)
1115 t2 = LoopTest(2)
1116
1117 ddiff = DeepDiff(t1, t2)
1118 result = {
1119 'values_changed': {
1120 'root.a': {
1121 'old_value': 1,
1122 'new_value': 2
1123 }
1124 }
1125 }
1126 assert result == ddiff
1127
1128 def test_loop_in_lists(self):
1129 t1 = [1, 2, 3]
1130 t1.append(t1)
1131
1132 t2 = [1, 2, 4]
1133 t2.append(t2)
1134
1135 ddiff = DeepDiff(t1, t2)
1136 result = {
1137 'values_changed': {
1138 'root[2]': {
1139 'new_value': 4,
1140 'old_value': 3
1141 }
1142 }
1143 }
1144 assert result == ddiff
1145
1146 def test_loop_in_lists2(self):
1147 t1 = [1, 2, [3]]
1148 t1[2].append(t1)
1149 t2 = [1, 2, [4]]
1150 t2[2].append(t2)
1151
1152 ddiff = DeepDiff(t1, t2)
1153 result = {
1154 'values_changed': {
1155 'root[2][0]': {
1156 'old_value': 3,
1157 'new_value': 4
1158 }
1159 }
1160 }
1161 assert result == ddiff
1162
1163 def test_decimal(self):
1164 t1 = {1: Decimal('10.1')}
1165 t2 = {1: Decimal('2.2')}
1166 ddiff = DeepDiff(t1, t2)
1167 result = {
1168 'values_changed': {
1169 'root[1]': {
1170 'new_value': Decimal('2.2'),
1171 'old_value': Decimal('10.1')
1172 }
1173 }
1174 }
1175 assert result == ddiff
1176
1177 def test_unicode_string_type_changes(self):
1178 """
1179 These tests were written when DeepDiff was in Python 2.
1180 Writing b"你好" throws an exception in Python 3 so can't be used for testing.
1181 These tests are currently useless till they are rewritten properly.
1182 """
1183 unicode_string = {"hello": "你好"}
1184 ascii_string = {"hello": "你好"}
1185 ddiff = DeepDiff(unicode_string, ascii_string)
1186 result = {}
1187 assert result == ddiff
1188
1189 def test_unicode_string_value_changes(self):
1190 unicode_string = {"hello": "你好"}
1191 ascii_string = {"hello": "你好hello"}
1192 ddiff = DeepDiff(unicode_string, ascii_string)
1193 result = {
1194 'values_changed': {
1195 "root['hello']": {
1196 'old_value': '你好',
1197 'new_value': '你好hello'
1198 }
1199 }
1200 }
1201 assert result == ddiff
1202
1203 def test_unicode_string_value_and_type_changes(self):
1204 unicode_string = {"hello": "你好"}
1205 ascii_string = {"hello": "你好hello"}
1206 ddiff = DeepDiff(unicode_string, ascii_string)
1207 # In python3, all string is unicode, so these 2 strings only diff
1208 # in values
1209 result = {
1210 'values_changed': {
1211 "root['hello']": {
1212 'new_value': '你好hello',
1213 'old_value': '你好'
1214 }
1215 }
1216 }
1217 assert result == ddiff
1218
1219 def test_int_to_unicode_string(self):
1220 t1 = 1
1221 ascii_string = "你好"
1222 ddiff = DeepDiff(t1, ascii_string)
1223 # In python3, all string is unicode, so these 2 strings only diff
1224 # in values
1225 result = {
1226 'type_changes': {
1227 'root': {
1228 'old_type': int,
1229 'new_type': str,
1230 'old_value': 1,
1231 'new_value': '你好'
1232 }
1233 }
1234 }
1235 assert result == ddiff
1236
1237 def test_int_to_unicode(self):
1238 t1 = 1
1239 unicode_string = "你好"
1240 ddiff = DeepDiff(t1, unicode_string)
1241 # In python3, all string is unicode, so these 2 strings only diff
1242 # in values
1243 result = {
1244 'type_changes': {
1245 'root': {
1246 'old_type': int,
1247 'new_type': str,
1248 'old_value': 1,
1249 'new_value': '你好'
1250 }
1251 }
1252 }
1253 assert result == ddiff
1254
1255 @pytest.mark.parametrize("test_num, t1, t2, ignore_numeric_type_changes, significant_digits, number_format_notation, result", [
1256 (1, 43.265798602382986, 43.71677762295505, False, 0, "f", {'values_changed': {'root': {'new_value': 43.71677762295505, 'old_value': 43.265798602382986}}}), # Note that it rounds the number so one becomes 43 and the other one is 44
1257 (2, Decimal('2.5'), Decimal('1.5'), False, 0, "f", {}),
1258 (3, Decimal('2.5'), Decimal('1.5'), False, 1, "f", {'values_changed': {'root': {'new_value': Decimal('1.5'), 'old_value': Decimal('2.5')}}}),
1259 (4, Decimal('2.5'), Decimal(2.5), False, 3, "f", {}),
1260 (5, 1024, 1022, False, 2, "e", {}),
1261 (6, {"key": [Decimal('2.0001'), Decimal('20000.0001')]}, {"key": [2.0002, 20000.0002]}, True, 4, "e", {'values_changed': {"root['key'][0]": {'new_value': 2.0002, 'old_value': Decimal('2.0001')}}}),
1262 (7, [Decimal("999.99999999")], [Decimal("999.9999999999")], False, 6, "f", {}),
1263 ])
1264 def test_significant_digits_and_notation(self, test_num, t1, t2, ignore_numeric_type_changes, significant_digits, number_format_notation, result):
1265 ddiff = DeepDiff(t1, t2, significant_digits=significant_digits, number_format_notation=number_format_notation,
1266 ignore_numeric_type_changes=ignore_numeric_type_changes)
1267 assert result == ddiff, f"test_significant_digits_and_notation #{test_num} failed."
1268
1269 def test_significant_digits_for_complex_imaginary_part(self):
1270 t1 = 1.23 + 1.222254j
1271 t2 = 1.23 + 1.222256j
1272 ddiff = DeepDiff(t1, t2, significant_digits=4)
1273 assert {} == ddiff
1274 result = {
1275 'values_changed': {
1276 'root': {
1277 'new_value': (1.23 + 1.222256j),
1278 'old_value': (1.23 + 1.222254j)
1279 }
1280 }
1281 }
1282 ddiff = DeepDiff(t1, t2, significant_digits=5)
1283 assert result == ddiff
1284
1285 def test_significant_digits_for_complex_real_part(self):
1286 t1 = 1.23446879 + 1.22225j
1287 t2 = 1.23446764 + 1.22225j
1288 ddiff = DeepDiff(t1, t2, significant_digits=5)
1289 assert {} == ddiff
1290
1291 def test_significant_digits_for_list_of_floats(self):
1292 t1 = [1.2344, 5.67881, 6.778879]
1293 t2 = [1.2343, 5.67882, 6.778878]
1294 ddiff = DeepDiff(t1, t2, significant_digits=3)
1295 assert {} == ddiff
1296 ddiff = DeepDiff(t1, t2, significant_digits=4)
1297 result = {
1298 'values_changed': {
1299 'root[0]': {
1300 'new_value': 1.2343,
1301 'old_value': 1.2344
1302 }
1303 }
1304 }
1305 assert result == ddiff
1306 ddiff = DeepDiff(t1, t2, significant_digits=5)
1307 result = {
1308 'values_changed': {
1309 'root[0]': {
1310 'new_value': 1.2343,
1311 'old_value': 1.2344
1312 },
1313 'root[1]': {
1314 'new_value': 5.67882,
1315 'old_value': 5.67881
1316 }
1317 }
1318 }
1319 assert result == ddiff
1320 ddiff = DeepDiff(t1, t2)
1321 ddiff2 = DeepDiff(t1, t2, significant_digits=6)
1322 assert ddiff2 == ddiff
1323
1324 def test_negative_significant_digits(self):
1325 with pytest.raises(ValueError):
1326 DeepDiff(1, 1, significant_digits=-1)
1327
1328 @pytest.mark.parametrize("t1, t2, significant_digits, expected_result",
1329 [
1330 (10, 10.0, 5, {}),
1331 (10, 10.2, 5, {'values_changed': {'root': {'new_value': 10.2, 'old_value': 10}}}),
1332 (10, 10.2, 0, {}),
1333 (Decimal(10), 10, 0, {}),
1334 (Decimal(10), 10, 10, {}),
1335 (Decimal(10), 10.0, 0, {}),
1336 (Decimal(10), 10.0, 10, {}),
1337 (Decimal('10.0'), 10.0, 5, {}),
1338 (Decimal('10.01'), 10.01, 1, {}),
1339 (Decimal('10.01'), 10.01, 2, {}),
1340 (Decimal('10.01'), 10.01, 5, {}),
1341 (Decimal('10.01'), 10.01, 8, {}),
1342 (Decimal('10.010'), 10.01, 3, {}),
1343 (Decimal('100000.1'), 100000.1, 0, {}),
1344 (Decimal('100000.1'), 100000.1, 1, {}),
1345 (Decimal('100000.1'), 100000.1, 5, {}),
1346 (Decimal('100000'), 100000.1, 0, {}),
1347 (Decimal('100000'), 100000.1, 1, {'values_changed': {'root': {'new_value': 100000.1, 'old_value': Decimal('100000')}}}),
1348 (np_float64(123.93420232), 123.93420232, 0, {}),
1349 ])
1350 def test_decimal_digits(self, t1, t2, significant_digits, expected_result):
1351 ddiff = DeepDiff(t1, t2, ignore_numeric_type_changes=True, ignore_string_type_changes=True, significant_digits=significant_digits)
1352 assert expected_result == ddiff
1353
1354 @pytest.mark.parametrize('test_num, t1, t2, log_scale_similarity_threshold, expected', [
1355 (
1356 1,
1357 {'foo': 110, 'bar': 306}, # t1
1358 {'foo': 140, 'bar': 298}, # t2
1359 0.01, # threshold
1360 {'values_changed': {"root['foo']": {'new_value': 140, 'old_value': 110}, "root['bar']": {'new_value': 298, 'old_value': 306}}}, # expected
1361 ),
1362 (
1363 2,
1364 {'foo': 110, 'bar': 306}, # t1
1365 {'foo': 140, 'bar': 298}, # t2
1366 0.1, # threshold
1367 {'values_changed': {"root['foo']": {'new_value': 140, 'old_value': 110}}}, # expected
1368 ),
1369 (
1370 2,
1371 {'foo': 110, 'bar': 306}, # t1
1372 {'foo': 140, 'bar': 298}, # t2
1373 0.3, # threshold
1374 {}, # expected
1375 ),
1376 ])
1377 def test_log_scale(self, test_num, t1, t2, log_scale_similarity_threshold, expected):
1378 diff = DeepDiff(t1, t2, use_log_scale=True, log_scale_similarity_threshold=log_scale_similarity_threshold)
1379 assert expected == diff, f"test_log_scale #{test_num} failed."
1380
1381 def test_ignore_type_in_groups(self):
1382 t1 = [1, 2, 3]
1383 t2 = [1.0, 2.0, 3.0]
1384 ddiff = DeepDiff(t1, t2, ignore_type_in_groups=DeepDiff.numbers)
1385 assert not ddiff
1386
1387 def test_ignore_type_in_groups2(self):
1388 t1 = [1, 2, 3]
1389 t2 = [1.0, 2.0, 3.3]
1390 ddiff = DeepDiff(t1, t2, ignore_type_in_groups=DeepDiff.numbers)
1391 result = {'values_changed': {'root[2]': {'new_value': 3.3, 'old_value': 3}}}
1392 assert result == ddiff
1393
1394 def test_ignore_type_in_groups3(self):
1395 t1 = {Decimal('10.01'): "carrots"}
1396 t2 = {10.01: "carrots"}
1397
1398 diff1 = DeepDiff(t1, t2, threshold_to_diff_deeper=0)
1399
1400 diff2 = DeepDiff(t1, t2, ignore_numeric_type_changes=True)
1401
1402 diff3 = DeepDiff(t1, t2, ignore_type_in_groups=DeepDiff.numbers)
1403 assert {'dictionary_item_added': ["root[10.01]"], 'dictionary_item_removed': ["root[Decimal('10.01')]"]} == diff1
1404 assert {} == diff2 == diff3
1405
1406 def test_ignore_type_in_groups_just_numbers(self):
1407 t1 = [1, 2, 3, 'a']
1408 t2 = [1.0, 2.0, 3.3, b'a']
1409 ddiff = DeepDiff(t1, t2, ignore_type_in_groups=[DeepDiff.numbers])
1410 result = {'values_changed': {'root[2]': {'new_value': 3.3, 'old_value': 3}},
1411 'type_changes': {'root[3]': {'new_type': bytes,
1412 'new_value': b'a',
1413 'old_type': str,
1414 'old_value': 'a'}}
1415 }
1416 assert result == ddiff
1417
1418 def test_ignore_type_in_groups_numbers_and_strings(self):
1419 t1 = [1, 2, 3, 'a']
1420 t2 = [1.0, 2.0, 3.3, b'a']
1421 ddiff = DeepDiff(t1, t2, ignore_type_in_groups=[DeepDiff.numbers, DeepDiff.strings])
1422 result = {'values_changed': {'root[2]': {'new_value': 3.3, 'old_value': 3}}}
1423 assert result == ddiff
1424
1425 def test_ignore_type_in_groups_none_and_objects(self):
1426 t1 = [1, 2, 3, 'a', None]
1427 t2 = [1.0, 2.0, 3.3, b'a', 'hello']
1428 ddiff = DeepDiff(t1, t2, ignore_type_in_groups=[(1, 1.0), (None, str, bytes)])
1429 result = {
1430 'values_changed': {
1431 'root[2]': {
1432 'new_value': 3.3,
1433 'old_value': 3
1434 },
1435 'root[4]': {
1436 'new_value': 'hello',
1437 'old_value': None
1438 }
1439 }
1440 }
1441 assert result == ddiff
1442
1443 def test_ignore_type_in_groups_str_and_datetime(self):
1444 now = datetime.datetime(2022, 4, 10, 0, 40, 41, 357857)
1445 t1 = [1, 2, 3, 'a', now]
1446 t2 = [1, 2, 3, 'a', 'now']
1447 ddiff = DeepDiff(t1, t2, ignore_type_in_groups=[(str, bytes, datetime.datetime)])
1448 now_utc = now.replace(tzinfo=datetime.timezone.utc)
1449 result = {'values_changed': {'root[4]': {'new_value': 'now', 'old_value': now_utc}}}
1450 assert result == ddiff
1451
1452 def test_ignore_type_in_groups_float_vs_decimal(self):
1453 diff = DeepDiff(float('0.1'), Decimal('0.1'), ignore_type_in_groups=[(float, Decimal)], significant_digits=2)
1454 assert not diff
1455
1456 @pytest.mark.parametrize("t1, t2, significant_digits, result", [
1457 ([0.1], [Decimal('0.10')], 55,
1458 {'values_changed': {'root[0]': {'new_value': Decimal('0.10'), 'old_value': 0.1}}}), # Due to floating point arithmetics with high significant digits.
1459 ([0.1], [Decimal('0.10')], 5, {}), # Same inputs as above but with significant digits that is low.
1460 ([-0.1], [-Decimal('0.10')], 5, {}),
1461 ([-Decimal('0.102')], [-Decimal('0.10')], 2, {}),
1462 ([1], [Decimal('1.00000002')], 3, {}),
1463 ])
1464 def test_ignore_numeric_type_changes_numbers_when_decimal(self, t1, t2, significant_digits, result):
1465 ddiff = DeepDiff(t1, t2, ignore_numeric_type_changes=True, significant_digits=significant_digits)
1466 assert result == ddiff
1467
1468 @pytest.mark.skip(reason="REMAPPING DISABLED UNTIL KEY NAMES CHANGE AGAIN IN FUTURE")
1469 def test_base_level_dictionary_remapping(self):
1470 """
1471 Since subclassed dictionaries that override __getitem__ treat newdict.get(key)
1472 differently than newdict['key'], we are unable to create a unittest with
1473 self.assertIn() and have to resort to fetching the values of two keys and making
1474 sure they are the same value.
1475 """
1476 t1 = {1: 1, 2: 2}
1477 t2 = {2: 2, 3: 3}
1478 ddiff = DeepDiff(t1, t2)
1479 assert ddiff['dic_item_added'] == ddiff['dictionary_item_added']
1480 assert ddiff['dic_item_removed'] == ddiff['dictionary_item_removed']
1481
1482 @pytest.mark.skip(reason="REMAPPING DISABLED UNTIL KEY NAMES CHANGE AGAIN IN FUTURE")
1483 def test_index_and_repeat_dictionary_remapping(self):
1484 t1 = [1, 3, 1, 4]
1485 t2 = [4, 4, 1]
1486 ddiff = DeepDiff(t1, t2, ignore_order=True, report_repetition=True)
1487 assert ddiff['repetition_change']['root[0]']['newindexes'] == ddiff['repetition_change']['root[0]']['new_indexes']
1488 assert ddiff['repetition_change']['root[0]']['newrepeat'] == ddiff['repetition_change']['root[0]']['new_repeat']
1489 assert ddiff['repetition_change']['root[0]']['oldindexes'] == ddiff['repetition_change']['root[0]']['old_indexes']
1490 assert ddiff['repetition_change']['root[0]']['oldrepeat'] == ddiff['repetition_change']['root[0]']['old_repeat']
1491
1492 @pytest.mark.skip(reason="REMAPPING DISABLED UNTIL KEY NAMES CHANGE AGAIN IN FUTURE")
1493 def test_value_and_type_dictionary_remapping(self):
1494 t1 = {1: 1, 2: 2}
1495 t2 = {1: 1, 2: '2'}
1496 ddiff = DeepDiff(t1, t2)
1497 assert ddiff['type_changes']['root[2]']['newtype'] == ddiff['type_changes']['root[2]']['new_type']
1498 assert ddiff['type_changes']['root[2]']['newvalue'] == ddiff['type_changes']['root[2]']['new_value']
1499 assert ddiff['type_changes']['root[2]']['oldtype'] == ddiff['type_changes']['root[2]']['old_type']
1500 assert ddiff['type_changes']['root[2]']['oldvalue'] == ddiff['type_changes']['root[2]']['old_value']
1501
1502 def test_skip_type(self):
1503 l1 = logging.getLogger("test")
1504 l2 = logging.getLogger("test2")
1505 t1 = {"log": l1, 2: 1337}
1506 t2 = {"log": l2, 2: 1337}
1507 ddiff = DeepDiff(t1, t2, exclude_types={logging.Logger})
1508 assert {} == ddiff
1509
1510 t1 = {"log": "book", 2: 1337}
1511 t2 = {"log": l2, 2: 1337}
1512 ddiff = DeepDiff(t1, t2, exclude_types={logging.Logger})
1513 assert {} == ddiff
1514
1515 def test_skip_path1(self):
1516 t1 = {
1517 "for life": "vegan",
1518 "ingredients": ["no meat", "no eggs", "no dairy"]
1519 }
1520 t2 = {
1521 "for life": "vegan",
1522 "ingredients": ["veggies", "tofu", "soy sauce"]
1523 }
1524 ddiff = DeepDiff(t1, t2, exclude_paths={"root['ingredients']"})
1525 assert {} == ddiff
1526
1527 def test_skip_path2(self):
1528 t1 = {
1529 "for life": "vegan",
1530 "ingredients": ["no meat", "no eggs", "no dairy"]
1531 }
1532 t2 = {"for life": "vegan"}
1533 ddiff = DeepDiff(t1, t2, exclude_paths={"root['ingredients']"})
1534 assert {} == ddiff
1535
1536 def test_skip_path2_key_names(self):
1537 t1 = {
1538 "for life": "vegan",
1539 "ingredients": ["no meat", "no eggs", "no dairy"]
1540 }
1541 t2 = {"for life": "vegan"}
1542 ddiff = DeepDiff(t1, t2, exclude_paths={"ingredients"})
1543 assert {} == ddiff
1544
1545 def test_skip_path2_reverse(self):
1546 t1 = {
1547 "for life": "vegan",
1548 "ingredients": ["no meat", "no eggs", "no dairy"]
1549 }
1550 t2 = {"for life": "vegan"}
1551 ddiff = DeepDiff(t2, t1, exclude_paths={"root['ingredients']"})
1552 assert {} == ddiff
1553
1554 def test_exclude_path_when_prefix_of_exclude_path_matches1(self):
1555 diff = DeepDiff({}, {'foo': '', 'bar': ''}, exclude_paths=['foo', 'bar'])
1556 assert not diff
1557
1558 def test_include_path3(self):
1559 t1 = {
1560 "for life": "vegan",
1561 "ingredients": ["no meat", "no eggs", "no dairy"]
1562 }
1563 t2 = {"for life": "vegan"}
1564 ddiff = DeepDiff(t2, t1, include_paths={"root['for_life']"})
1565 assert {} == ddiff
1566
1567 def test_include_path3_with_just_key_names(self):
1568 t1 = {
1569 "for life": "vegan",
1570 "ingredients": ["no meat", "no eggs", "no dairy"]
1571 }
1572 t2 = {"for life": "vegan"}
1573 ddiff = DeepDiff(t1, t2, include_paths={"for_life"})
1574 assert {} == ddiff
1575
1576 def test_include_path4_nested(self):
1577 t1 = {
1578 "foo": {"bar": "potato"},
1579 "ingredients": ["no meat", "no eggs", "no dairy"]
1580 }
1581 t2 = {
1582 "foo": {"bar": "banana"},
1583 "ingredients": ["bread", "cheese"]
1584 }
1585 ddiff = DeepDiff(t1, t2, include_paths="foo")
1586 assert {
1587 'values_changed': {
1588 "root['foo']['bar']": {
1589 'new_value': 'banana',
1590 'old_value': 'potato'
1591 }
1592 }
1593 } == ddiff
1594
1595 def test_include_path5(self):
1596 diff = DeepDiff(
1597 {
1598 'name': 'Testname',
1599 'code': 'bla',
1600 'noneCode': 'blu',
1601 }, {
1602 'uid': '12345',
1603 'name': 'Testname2',
1604 },
1605 )
1606
1607 diff2 = DeepDiff(
1608 {
1609 'name': 'Testname',
1610 'code': 'bla',
1611 'noneCode': 'blu',
1612 }, {
1613 'uid': '12345',
1614 'name': 'Testname2',
1615 },
1616 include_paths = "root['name']"
1617 )
1618 expected = {'values_changed': {'root': {'new_value': {'uid': '12345', 'name': 'Testname2'}, 'old_value': {'name': 'Testname', 'code': 'bla', 'noneCode': 'blu'}}}}
1619 expected2 = {'values_changed': {"root['name']": {'new_value': 'Testname2', 'old_value': 'Testname'}}}
1620
1621 assert expected == diff
1622 assert expected2 == diff2
1623
1624 def test_include_path6(self):
1625 t1 = [1, 2, 3, [4, 5, {6: 7}]]
1626 t2 = [1, 2, 3, [4, 5, {6: 1000}]]
1627 diff = DeepDiff(
1628 t1,
1629 t2,
1630 )
1631
1632 diff2 = DeepDiff(
1633 t1,
1634 t2,
1635 include_paths = "root[3]"
1636 )
1637
1638 diff3 = DeepDiff(
1639 t1,
1640 t2,
1641 include_paths = "root[4]"
1642 )
1643 expected = {'values_changed': {'root[3][2][6]': {'new_value': 1000, 'old_value': 7}}}
1644 assert expected == diff
1645 assert diff == diff2
1646 assert not diff3
1647
1648 def test_skip_path4(self):
1649 t1 = {
1650 "for life": "vegan",
1651 "ingredients": ["no meat", "no eggs", "no dairy"]
1652 }
1653 t2 = {"for life": "vegan", "zutaten": ["veggies", "tofu", "soy sauce"]}
1654 ddiff = DeepDiff(t1, t2, exclude_paths={"root['ingredients']"})
1655 assert 'dictionary_item_added' in ddiff, {}
1656 assert 'dictionary_item_removed' not in ddiff, {}
1657
1658 def test_skip_path5(self):
1659 t1 = [{'cn': 'tuser', 'first_name': 'Test', 'last_name': 'User', 'name': 'Test User', 'email': '[email protected]'}]
1660 t2 = [{'name': 'Test User', 'email': '[email protected]'}]
1661
1662 diff = DeepDiff(
1663 t1,
1664 t2,
1665 ignore_order=True,
1666 exclude_paths={
1667 "root[0]['cn']",
1668 "root[0]['first_name']",
1669 "root[0]['last_name']"
1670 })
1671
1672 assert not diff
1673
1674 def test_skip_custom_object_path(self):
1675 t1 = CustomClass(1)
1676 t2 = CustomClass(2)
1677 ddiff = DeepDiff(t1, t2, exclude_paths=['root.a'])
1678 result = {}
1679 assert result == ddiff
1680
1681 def test_skip_list_path(self):
1682 t1 = ['a', 'b']
1683 t2 = ['a']
1684 ddiff = DeepDiff(t1, t2, exclude_paths=['root[1]'])
1685 result = {}
1686 assert result == ddiff
1687
1688 def test_skip_dictionary_path(self):
1689 t1 = {1: {2: "a"}}
1690 t2 = {1: {}}
1691 ddiff = DeepDiff(t1, t2, exclude_paths=['root[1][2]'])
1692 result = {}
1693 assert result == ddiff
1694
1695 def test_skip_dictionary_path_with_custom_object(self):
1696 obj1 = CustomClass(1)
1697 obj2 = CustomClass(2)
1698
1699 t1 = {1: {2: obj1}}
1700 t2 = {1: {2: obj2}}
1701 ddiff = DeepDiff(t1, t2, exclude_paths=['root[1][2].a'])
1702 result = {}
1703 assert result == ddiff
1704
1705 # TODO: fix it for python 3.5, 3.6 and pypy3
1706 def test_skip_regexp(self):
1707 t1 = [{'a': 1, 'b': 2}, {'c': 4, 'b': 5}]
1708 t2 = [{'a': 1, 'b': 3}, {'c': 4, 'b': 5}]
1709 ddiff = DeepDiff(t1, t2, exclude_regex_paths=[r"root\[\d+\]\['b'\]"])
1710 result = {}
1711 assert result == ddiff
1712
1713 def test_include_obj_callback(self):
1714 def include_obj_callback(obj, path):
1715 return True if "include" in path or isinstance(obj, int) else False
1716
1717 t1 = {"x": 10, "y": "b", "z": "c", "include_me": "a"}
1718 t2 = {"x": 10, "y": "c", "z": "b", "include_me": "b"}
1719 ddiff = DeepDiff(t1, t2, include_obj_callback=include_obj_callback)
1720 result = {'values_changed': {"root['include_me']": {'new_value': "b", 'old_value': "a"}}}
1721 assert result == ddiff
1722 assert {"root['include_me']"} == ddiff.affected_paths
1723 assert {"include_me"} == ddiff.affected_root_keys
1724
1725 def test_include_obj_callback_strict(self):
1726 def include_obj_callback_strict(obj, path):
1727 return True if isinstance(obj, int) and obj > 10 else False
1728
1729 t1 = {"x": 11, "y": 10, "z": "c"}
1730 t2 = {"x": 12, "y": 12, "z": "c"}
1731 ddiff = DeepDiff(t1, t2, include_obj_callback_strict=include_obj_callback_strict)
1732 result = {'values_changed': {"root['x']": {'new_value': 12, 'old_value': 11}}}
1733 assert result == ddiff
1734 assert {"root['x']"} == ddiff.affected_paths
1735 assert {"x"} == ddiff.affected_root_keys
1736
1737 def test_skip_exclude_obj_callback(self):
1738 def exclude_obj_callback(obj, path):
1739 return True if "skip" in path or isinstance(obj, int) else False
1740
1741 t1 = {"x": 10, "y": "b", "z": "c", "skip_1": 0}
1742 t2 = {"x": 12, "y": "b", "z": "c", "skip_2": 0}
1743 ddiff = DeepDiff(t1, t2, exclude_obj_callback=exclude_obj_callback)
1744 result = {}
1745 assert result == ddiff
1746
1747 def test_skip_exclude_obj_callback_strict(self):
1748 def exclude_obj_callback_strict(obj, path):
1749 return True if isinstance(obj, int) and obj > 10 else False
1750
1751 t1 = {"x": 10, "y": "b", "z": "c"}
1752 t2 = {"x": 12, "y": "b", "z": "c"}
1753 ddiff = DeepDiff(t1, t2, exclude_obj_callback_strict=exclude_obj_callback_strict)
1754 result = {'values_changed': {"root['x']": {'new_value': 12, 'old_value': 10}}}
1755 assert result == ddiff
1756 assert {"root['x']"} == ddiff.affected_paths
1757 assert {"x"} == ddiff.affected_root_keys
1758
1759 def test_skip_str_type_in_dictionary(self):
1760 t1 = {1: {2: "a"}}
1761 t2 = {1: {}}
1762 ddiff = DeepDiff(t1, t2, exclude_types=[str])
1763 result = {}
1764 assert result == ddiff
1765
1766 def test_skip_str_type_in_dict_on_list(self):
1767 t1 = [{1: "a"}]
1768 t2 = [{}]
1769 ddiff = DeepDiff(t1, t2, exclude_types=[str])
1770 result = {}
1771 assert result == ddiff
1772
1773 def test_unknown_parameters(self):
1774 with pytest.raises(ValueError):
1775 DeepDiff(1, 1, wrong_param=2)
1776
1777 def test_bad_attribute(self):
1778 class Bad:
1779 __slots__ = ['x', 'y']
1780
1781 def __getattr__(self, key):
1782 raise AttributeError("Bad item")
1783
1784 def __str__(self):
1785 return "Bad Object"
1786
1787 t1 = Bad()
1788 t2 = Bad()
1789
1790 ddiff = DeepDiff(t1, t2)
1791 result = {}
1792 assert result == ddiff
1793
1794 def test_dict_none_item_removed(self):
1795 t1 = {1: None, 2: 2}
1796 t2 = {2: 2}
1797 ddiff = DeepDiff(t1, t2)
1798 result = {
1799 'dictionary_item_removed': {'root[1]'}
1800 }
1801 assert result == ddiff
1802
1803 def test_list_none_item_removed(self):
1804 t1 = [1, 2, None]
1805 t2 = [1, 2]
1806 ddiff = DeepDiff(t1, t2)
1807 result = {
1808 'iterable_item_removed': {'root[2]': None}
1809 }
1810 assert result == ddiff
1811 assert {"root[2]"} == ddiff.affected_paths
1812
1813 def test_list_item_removed_from_the_middle(self):
1814 t1 = [0, 1, 2, 3, 'bye', 5, 6, 7, 8, 'a', 'b', 'c']
1815 t2 = [0, 1, 2, 3, 5, 6, 7, 8, 'a', 'b', 'c']
1816 diff = DeepDiff(t1, t2)
1817 result = {'iterable_item_removed': {'root[4]': 'bye'}}
1818 assert result == diff
1819 assert {"root[4]"} == diff.affected_paths
1820 assert {4} == diff.affected_root_keys
1821
1822 # TODO: we need to support reporting that items have been swapped
1823 # def test_item_moved(self):
1824 # # currently all the items in the list need to be hashables
1825 # t1 = [1, 2, 3, 4]
1826 # t2 = [4, 2, 3, 1]
1827 # diff = DeepDiff(t1, t2)
1828 # result = {} # it should show that those items are swapped.
1829 # assert result == diff
1830
1831 def test_list_item_values_replace_in_the_middle(self):
1832 t1 = [0, 1, 2, 3, 'bye', 5, 6, 7, 8, 'a', 'b', 'c']
1833 t2 = [0, 1, 2, 3, 'see', 'you', 'later', 5, 6, 7, 8, 'a', 'b', 'c']
1834 diff = DeepDiff(t1, t2)
1835 result = {
1836 'values_changed': {
1837 'root[4]': {
1838 'old_value': 'bye',
1839 'new_value': 'see',
1840 }
1841 },
1842 'iterable_item_added': {
1843 'root[5]': 'you',
1844 'root[6]': 'later'
1845 }
1846 }
1847 assert result == diff
1848 assert {'root[5]', 'root[6]', 'root[4]'} == diff.affected_paths
1849 assert {4, 5, 6} == diff.affected_root_keys
1850
1851 def test_non_subscriptable_iterable(self):
1852 def gen1():
1853 yield 42
1854 yield 1337
1855 yield 31337
1856
1857 def gen2():
1858 yield 42
1859 yield 1337
1860
1861 t1 = gen1()
1862 t2 = gen2()
1863 ddiff = DeepDiff(t1, t2)
1864
1865 result = {'iterable_item_removed': {'root[2]': 31337}}
1866 # Note: In text-style results, we currently pretend this stuff is subscriptable for readability
1867
1868 assert result == ddiff
1869 assert {"root[2]"} == ddiff.affected_paths
1870
1871 @pytest.mark.parametrize('t1, t2, params, expected_result', [
1872 (float('nan'), float('nan'), {}, ['values_changed']),
1873 (float('nan'), float('nan'), {'ignore_nan_inequality': True}, []),
1874 ([1, float('nan')], [1, float('nan')], {'ignore_nan_inequality': True}, []),
1875 ])
1876 @pytest.mark.skipif(pypy3, reason="some versions of pypy3 have nan==nan")
1877 def test_ignore_nan_inequality(self, t1, t2, params, expected_result):
1878 assert expected_result == list(DeepDiff(t1, t2, **params).keys())
1879
1880 @pytest.mark.parametrize('ignore_order, ignore_private_variables, expected', [
1881 (True, True, {}),
1882 (False, True, {}),
1883 (True, False, {'values_changed': {"root[0]['schema']['items']['__ref']": {'new_value': 2, 'old_value': 1}}}),
1884 (False, False, {'values_changed': {"root[0]['schema']['items']['__ref']": {'new_value': 2, 'old_value': 1}}}),
1885 ])
1886 def test_private_variables(self, ignore_order, ignore_private_variables, expected):
1887 t1 = [{'in': 'body', 'name': 'params', 'description': 'params', 'required': True, 'schema': {'type': 'array', 'items': {'__ref': 1}}}]
1888 t2 = [{'in': 'body', 'name': 'params', 'description': 'params', 'required': True, 'schema': {'type': 'array', 'items': {'__ref': 2}}}]
1889 diff = DeepDiff(t1, t2, ignore_order=ignore_order, ignore_private_variables=ignore_private_variables)
1890 assert expected == diff
1891
1892 def test_group_by1(self):
1893 t1 = [
1894 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
1895 {'id': 'BB', 'name': 'James', 'last_name': 'Blue'},
1896 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
1897 ]
1898
1899 t2 = [
1900 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
1901 {'id': 'BB', 'name': 'James', 'last_name': 'Brown'},
1902 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
1903 ]
1904
1905 diff = DeepDiff(t1, t2)
1906 expected = {'values_changed': {"root[1]['last_name']": {
1907 'new_value': 'Brown',
1908 'old_value': 'Blue'}}}
1909 assert expected == diff
1910
1911 diff = DeepDiff(t1, t2, group_by='id')
1912 expected_grouped = {'values_changed': {"root['BB']['last_name']": {
1913 'new_value': 'Brown',
1914 'old_value': 'Blue'}}}
1915 assert expected_grouped == diff
1916
1917 def test_group_by2_when_repeats(self):
1918 t1 = [
1919 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
1920 {'id': 'BB', 'name': 'James', 'last_name': 'Blue', 'int_id': 20},
1921 {'id': 'BB', 'name': 'Jimmy', 'last_name': 'Red', 'int_id': 3},
1922 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
1923 ]
1924
1925 t2 = [
1926 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
1927 {'id': 'BB', 'name': 'James', 'last_name': 'Brown', 'int_id': 20},
1928 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
1929 ]
1930
1931 diff = DeepDiff(t1, t2, group_by='id', group_by_sort_key='name')
1932 expected_grouped = {
1933 'values_changed': {
1934 "root['BB'][0]['last_name']": {
1935 'new_value': 'Brown',
1936 'old_value': 'Blue'
1937 }
1938 },
1939 'iterable_item_removed': {
1940 "root['BB'][1]": {
1941 'name': 'Jimmy',
1942 'last_name': 'Red',
1943 'int_id': 3
1944 }
1945 }
1946 }
1947 assert expected_grouped == diff
1948
1949 diff2 = DeepDiff(t1, t2, group_by='id', group_by_sort_key=lambda x: x['name'])
1950 assert expected_grouped == diff2
1951
1952 def test_group_by3_when_repeats_and_group_by_list(self):
1953 t1 = [
1954 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
1955 {'id': 'BB', 'name': 'James', 'last_name': 'Blue', 'int_id': 20},
1956 {'id': 'BB', 'name': 'Jimmy', 'last_name': 'Red', 'int_id': 3},
1957 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
1958 ]
1959
1960 t2 = [
1961 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody', 'int_id': 2},
1962 {'id': 'BB', 'name': 'James', 'last_name': 'Brown', 'int_id': 20},
1963 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple', 'int_id': 4},
1964 ]
1965
1966 diff1 = DeepDiff(t1, t2, group_by=['id', 'name'])
1967 expected_grouped = {
1968 'dictionary_item_removed': ["root['BB']['Jimmy']"],
1969 'values_changed': {
1970 "root['BB']['James']['last_name']": {
1971 'new_value': 'Brown',
1972 'old_value': 'Blue'
1973 }
1974 }
1975 }
1976 assert expected_grouped == diff1
1977
1978 diff2 = DeepDiff(t1, t2, group_by=['id', 'name'], group_by_sort_key='int_id')
1979 expected_grouped = {
1980 'dictionary_item_removed': ["root['BB']['Jimmy']"],
1981 'values_changed': {
1982 "root['BB']['James'][0]['last_name']": {
1983 'new_value': 'Brown',
1984 'old_value': 'Blue'
1985 }
1986 }
1987 }
1988 assert expected_grouped == diff2
1989
1990 def test_group_by_key_missing(self):
1991 t1 = [
1992 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
1993 {'id': 'BB', 'name': 'James', 'last_name': 'Blue'},
1994 {'name': 'Mike', 'last_name': 'Apple'},
1995 ]
1996
1997 t2 = [
1998 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
1999 {'id': 'BB', 'name': 'James', 'last_name': 'Blue'},
2000 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
2001 ]
2002
2003 diff = DeepDiff(t1, t2, group_by='id')
2004 expected = {'dictionary_item_added': ["root[2]['id']"]}
2005 assert expected == diff
2006
2007 def test_group_by_not_dict1(self):
2008 t1 = [
2009 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
2010 None,
2011 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
2012 ]
2013
2014 t2 = [
2015 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
2016 {'id': 'BB'},
2017 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
2018 ]
2019
2020 diff = DeepDiff(t1, t2, group_by='id')
2021 expected = {
2022 'type_changes': {
2023 'root[1]': {
2024 'old_type': None.__class__,
2025 'new_type': dict,
2026 'old_value': None,
2027 'new_value': {
2028 'id': 'BB'
2029 }
2030 }
2031 },
2032 }
2033 assert expected == diff
2034
2035 def test_group_by_not_dict2(self):
2036 t1 = [
2037 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
2038 {'id': 'BB'},
2039 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
2040 ]
2041
2042 t2 = [
2043 {'id': 'AA', 'name': 'Joe', 'last_name': 'Nobody'},
2044 None,
2045 {'id': 'CC', 'name': 'Mike', 'last_name': 'Apple'},
2046 ]
2047
2048 diff = DeepDiff(t1, t2, group_by='id')
2049 expected = {
2050 'type_changes': {
2051 'root[1]': {
2052 'old_type': dict,
2053 'new_type': None.__class__,
2054 'new_value': None,
2055 'old_value': {
2056 'id': 'BB'
2057 }
2058 }
2059 },
2060 }
2061 assert expected == diff
2062
2063 def test_group_by_not_list_of_dicts(self):
2064 t1 = {1: 2}
2065
2066 t2 = {1: 3}
2067
2068 diff = DeepDiff(t1, t2, group_by='id')
2069 expected = {'values_changed': {'root[1]': {'new_value': 3, 'old_value': 2}}}
2070 assert expected == diff
2071 assert {"root[1]"} == diff.affected_paths
2072
2073 def test_datetime_in_key(self):
2074
2075 now = datetime.datetime(2022, 4, 10, 0, 40, 41, 357857)
2076 t1 = {now: 1, now + datetime.timedelta(1): 4}
2077 t2 = {now: 2, now + datetime.timedelta(1): 4}
2078 diff = DeepDiff(t1, t2)
2079 expected = {'values_changed': {f'root[{repr(now)}]': {'new_value': 2, 'old_value': 1}}}
2080
2081 assert expected == diff
2082
2083 def test_property_values(self):
2084
2085 class A:
2086 _thing = 0
2087
2088 def __init__(self, a):
2089 self.a = a
2090
2091 @property
2092 def thing(self):
2093 A._thing += 1
2094 return A._thing
2095
2096 @property
2097 def __thing2(self):
2098 A._thing += 1
2099 return A._thing
2100
2101 diff = DeepDiff(A(1), A(1))
2102 expected = {
2103 'values_changed': {
2104 'root._thing': {
2105 'new_value': 1,
2106 'old_value': 0
2107 },
2108 'root.thing': {
2109 'new_value': 2,
2110 'old_value': 1
2111 }
2112 }
2113 }
2114
2115 assert expected == diff
2116
2117 diff2 = DeepDiff(A(1), A(1), ignore_private_variables=False)
2118 expected2 = {
2119 'values_changed': {
2120 'root._A__thing2': {
2121 'new_value': 5,
2122 'old_value': 3
2123 },
2124 'root._thing': {
2125 'new_value': 5,
2126 'old_value': 3
2127 },
2128 'root.thing': {
2129 'new_value': 6,
2130 'old_value': 4
2131 }
2132 }
2133 }
2134
2135 assert expected2 == diff2
2136
2137 def test_diffs_rrules(self):
2138
2139 from dateutil.rrule import MONTHLY, rrule
2140
2141 d = DeepDiff(
2142 rrule(freq=MONTHLY, count=5, dtstart=datetime.datetime(2014, 12, 31)),
2143 rrule(freq=MONTHLY, count=4, dtstart=datetime.datetime(2011, 12, 31)),
2144 )
2145
2146 assert d == {
2147 "values_changed": {
2148 "root[0]": {
2149 "new_value": datetime.datetime(2011, 12, 31, 0, 0, tzinfo=datetime.timezone.utc),
2150 "old_value": datetime.datetime(2014, 12, 31, 0, 0, tzinfo=datetime.timezone.utc),
2151 },
2152 "root[1]": {
2153 "new_value": datetime.datetime(2012, 1, 31, 0, 0, tzinfo=datetime.timezone.utc),
2154 "old_value": datetime.datetime(2015, 1, 31, 0, 0, tzinfo=datetime.timezone.utc),
2155 },
2156 "root[2]": {
2157 "new_value": datetime.datetime(2012, 3, 31, 0, 0, tzinfo=datetime.timezone.utc),
2158 "old_value": datetime.datetime(2015, 3, 31, 0, 0, tzinfo=datetime.timezone.utc),
2159 },
2160 "root[3]": {
2161 "new_value": datetime.datetime(2012, 5, 31, 0, 0, tzinfo=datetime.timezone.utc),
2162 "old_value": datetime.datetime(2015, 5, 31, 0, 0, tzinfo=datetime.timezone.utc),
2163 },
2164 },
2165 "iterable_item_removed": {"root[4]": datetime.datetime(2015, 7, 31, 0, 0)},
2166 }
2167
2168 def test_pydantic1(self):
2169
2170 class Foo(PydanticBaseModel):
2171 thing: int = None
2172 that: str
2173
2174 t1 = Foo(thing=1, that='yes')
2175 t2 = Foo(thing=2, that='yes')
2176
2177 diff = DeepDiff(t1, t2)
2178 expected = {'values_changed': {'root.thing': {'new_value': 2, 'old_value': 1}}}
2179 assert expected == diff
2180
2181 def test_pydantic2(self):
2182
2183 class Foo(PydanticBaseModel):
2184 thing: int = None
2185 that: str
2186
2187 class Bar(PydanticBaseModel):
2188 stuff: List[Foo]
2189
2190 t1 = Bar(stuff=[Foo(thing=1, that='yes')])
2191 t2 = Bar(stuff=[Foo(thing=2, that='yes')])
2192
2193 diff = DeepDiff(t1, t2)
2194 expected = {'values_changed': {'root.stuff[0].thing': {'new_value': 2, 'old_value': 1}}}
2195 assert expected == diff
2196
2197 def test_dataclass1(self):
2198
2199
2200 t1 = MyDataClass(1, 4)
2201 t2 = MyDataClass(2, 4)
2202
2203 diff = DeepDiff(t1, t2, exclude_regex_paths=["any"])
2204 assert {'values_changed': {'root.val': {'new_value': 2, 'old_value': 1}}} == diff
2205
2206 def test_dataclass2(self):
2207
2208 @dataclass(frozen=True)
2209 class MyDataClass:
2210 val: int
2211 val2: int
2212
2213 t1 = {
2214 MyDataClass(1, 4): 10,
2215 MyDataClass(2, 4): 20,
2216 }
2217
2218 t2 = {
2219 MyDataClass(1, 4): 10,
2220 MyDataClass(2, 4): 10,
2221 }
2222
2223 diff = DeepDiff(t1, t2, exclude_regex_paths=["any"])
2224 assert {'values_changed': {'root[MyDataClass(val=2,val2=4)]': {'new_value': 10, 'old_value': 20}}} == diff
2225
2226
2227 def test_group_by_with_none_key_and_ignore_case(self):
2228 """Test that group_by works with None keys when ignore_string_case is True"""
2229 dict1 = [{'txt_field': 'FULL_NONE', 'group_id': None}, {'txt_field': 'FULL', 'group_id': 'a'}]
2230 dict2 = [{'txt_field': 'PARTIAL_NONE', 'group_id': None}, {'txt_field': 'PARTIAL', 'group_id': 'a'}]
2231
2232 diff = DeepDiff(
2233 dict1,
2234 dict2,
2235 ignore_order=True,
2236 group_by='group_id',
2237 ignore_string_case=True
2238 )
2239
2240 expected = {'values_changed': {"root[None]['txt_field']":
2241 {'new_value': 'partial_none', 'old_value': 'full_none'},
2242 "root['a']['txt_field']":
2243 {'new_value': 'partial', 'old_value': 'full'}
2244 }
2245 }
2246 assert expected == diff
2247
2248 def test_affected_root_keys_when_dict_empty(self):
2249 diff = DeepDiff({}, {1:1, 2:2}, threshold_to_diff_deeper=0)
2250 assert [1, 2] == diff.affected_root_keys
2251
2252 diff2 = DeepDiff({}, {1:1, 2:2})
2253 assert [] == diff2.affected_root_keys
2254
2255 def test_range1(self):
2256 range1 = range(0, 10)
2257 range2 = range(0, 8)
2258 diff = DeepDiff(range1, range2)
2259 assert {'iterable_item_removed': {'root[8]': 8, 'root[9]': 9}} == diff
2260
2261
2262 def test_group_by_that_has_integers(self):
2263 """Test that group_by with integer keys doesn't add type prefixes like 'int:33'"""
2264 t1 = [{'row_num_in_file': 33, 'value': 'old'}]
2265 t2 = [{'row_num_in_file': 33, 'value': 'new'}]
2266
2267 diff = DeepDiff(t1, t2, group_by='row_num_in_file', ignore_string_type_changes=True)
2268
2269 # Verify that the diff key contains the integer 33 without type prefix
2270 changes = diff.get('values_changed', {})
2271 assert len(changes) == 1
2272 key = list(changes.keys())[0]
2273 assert "int:" not in key
2274 assert "[33]" in key or "['33']" in key