Skip to content

Commit 82d1b4b

Browse files
committed
add callable group_by tests
1 parent 0265184 commit 82d1b4b

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

tests/test_diff_group_by.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""Tests for the group_by parameter of Deepdiff"""
2+
3+
import pytest
4+
5+
from deepdiff import DeepDiff
6+
7+
8+
class TestGetKeyForGroupBy:
9+
def test_group_by_string(self):
10+
"""Test where group_by is a single key (string)."""
11+
row = {'first': 'John', 'middle': 'Joe', 'last': 'Smith'}
12+
group_by = 'first'
13+
item_name = 't1'
14+
actual = DeepDiff._get_key_for_group_by(row, group_by, item_name)
15+
expected = 'John'
16+
17+
assert actual == expected
18+
19+
def test_group_by_callable(self):
20+
"""Test where group_by is callable."""
21+
row = {'id': 123, 'demographics': {'names': {'first': 'John', 'middle': 'Joe', 'last': 'Smith'}}}
22+
group_by = lambda x: x['demographics']['names']['first']
23+
item_name = 't1'
24+
actual = DeepDiff._get_key_for_group_by(row, group_by, item_name)
25+
expected = 'John'
26+
assert actual == expected
27+
28+
def test_group_by_key_error(self):
29+
"""Test where group_by is a key that is not in the row."""
30+
row = {'id': 123, 'demographics': {'names': {'first': 'John', 'middle': 'Joe', 'last': 'Smith'}}}
31+
group_by = 'someotherkey'
32+
item_name = 't1'
33+
with pytest.raises(KeyError):
34+
DeepDiff._get_key_for_group_by(row, group_by, item_name)
35+
36+
37+
class TestGroupBy:
38+
def test_group_by_callable(self):
39+
"""Test where group_by is a callable."""
40+
t1 = [
41+
{'id': 'AA', 'demographics': {'names': {'first': 'Joe', 'middle': 'John', 'last': 'Nobody'}}},
42+
{'id': 'BB', 'demographics': {'names': {'first': 'James', 'middle': 'Joyce', 'last': 'Blue'}}},
43+
{'id': 'CC', 'demographics': {'names': {'first': 'Mike', 'middle': 'Mark', 'last': 'Apple'}}},
44+
]
45+
46+
t2 = [
47+
{'id': 'AA', 'demographics': {'names': {'first': 'Joe', 'middle': 'John', 'last': 'Nobody'}}},
48+
{'id': 'BB', 'demographics': {'names': {'first': 'James', 'middle': 'Joyce', 'last': 'Brown'}}},
49+
{'id': 'CC', 'demographics': {'names': {'first': 'Mike', 'middle': 'Charles', 'last': 'Apple'}}},
50+
]
51+
52+
actual = DeepDiff(t1, t2, group_by=lambda x: x['demographics']['names']['first'])
53+
expected = {
54+
'values_changed': {
55+
"root['James']['demographics']['names']['last']": {'new_value': 'Brown', 'old_value': 'Blue'},
56+
"root['Mike']['demographics']['names']['middle']": {'new_value': 'Charles', 'old_value': 'Mark'},
57+
},
58+
}
59+
assert actual == expected

0 commit comments

Comments
 (0)