This repository has been archived by the owner on Dec 18, 2019. It is now read-only.
/
dict_differ.py
89 lines (72 loc) · 2.14 KB
/
dict_differ.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import json
def pinfo(*data):
"""
Prints all the params in separate lines.
"""
for d in data:
print d
def assert_same_jsons(expected, current):
"""
Checks if the dictionaries are the same.
It compares the keys and values.
Prints diff if they are not exact and throws exception.
"""
d = DictDiffer(expected, current)
if not d.same():
d.print_diff()
assert expected == current
class DictDiffer:
"""
Class for creating nicely looking dictionary diffs.
"""
def __init__(self, first, second):
if isinstance(first, basestring):
self.first = json.loads(first)
else:
self.first = first
if isinstance(second, basestring):
self.second = json.loads(second)
else:
self.second = second
self._diff = self._generate_diff()
def _generate_diff(self):
"""
Returns:
Dictionary difference as a dictionary.
"""
diff = {}
for k in self.first.keys():
if not k in self.second:
diff[k] = ('KEY NOT FOUND IN SECOND DICT', self.first[k])
elif self.first[k] != self.second[k]:
diff[k] = {"DIFFERENT VALUES":
{'EXPECTED DICT:': self.first[k],
'CURRENT DICT: ': self.second[k]}
}
for k in self.second.keys():
if not k in self.first:
diff[k] = ("KEY NOT FOUND IN FIRST DICT", self.second[k])
return diff
def same(self):
"""
Returns:
True if provided dictionaries are the same.
False otherwise.
"""
return self._diff == {}
def diff(self):
"""
Returns:
Dictionary difference between the dictionaries.
"""
return self._diff
def print_diff(self):
"""
Returns:
Nothing
Side effects:
Prints nicely the difference between dictionaries.
"""
import pprint
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(self._diff)