Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Last active August 29, 2015 14:01
Show Gist options
  • Save carymrobbins/0214fe8964c5a3b62b14 to your computer and use it in GitHub Desktop.
Save carymrobbins/0214fe8964c5a3b62b14 to your computer and use it in GitHub Desktop.
from itertools import izip
class TestCaseBase(unittest.TestCase):
def assertDictEqualVerbose(self, d1, d2, message=None):
"""Compare two dictionaries for equality showing exact differences.
:param Mapping d1: First dict to compare.
:param Mapping d2: Second dict to compare.
:param basestring message: Optional error message.
:raises AssertionError: if the two dicts are not equal.
"""
if d1 == d2:
return
d1_keys = set(d1)
d2_keys = set(d2)
keys_in_d1_but_not_in_d2 = d1_keys.difference(d2_keys)
keys_in_d2_but_not_in_d1 = d2_keys.difference(d1_keys)
keys_in_both_d1_and_d2 = d1_keys.intersection(d2_keys)
keys_not_equal = {}
for k in keys_in_both_d1_and_d2:
v1, v2 = d1[k], d2[k]
if v1 != v2:
keys_not_equal[k] = (v1, v2)
messages = []
if message:
messages.append(message)
if keys_in_d1_but_not_in_d2:
messages.append('Keys in first dict but not in second: {0!r}'.format(
keys_in_d1_but_not_in_d2))
if keys_in_d2_but_not_in_d1:
messages.append('Keys in second dict but not in first: {0!r}'.format(
keys_in_d2_but_not_in_d1))
if keys_not_equal:
messages.append('Keys that are not equal:')
for k, (v1, v2) in keys_not_equal.iteritems():
messages.append(' {0!r}: {0!r} != {0!r}'.format(k, v1, v2))
raise AssertionError('\n'.join(messages))
def assertListOfDictEqualVerbose(self, xs, ys, message=None):
"""Compare two lists of dicts for equality failing on the first inequality.
:param Iterable[Mapping] xs: First list to compare.
:param Iterable[Mapping] ys: Second list to compare.
:param basestring message: Optional error message.
:raises AssertionError: if the two dicts are not equal.
"""
for i, (d1, d2) in enumerate(izip(xs, ys)):
sub_message = (message or 'Dicts not equal') + ' (index {0})'.format(i)
this.assertDictEqualVerbose(d1, d2, sub_message)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment