Commits

Anonymous committed bb708c5

Adding funcionality where the differing dictionaries are reported as context diffs.
The idea and code came from http://www.aminus.org/blogs/index.php/2009/01/09/assertnodiff

  • Participants
  • Parent commits b3cad54

Comments (0)

Files changed (2)

File dict_compare.py

 False
 >>> len(sr.get_errors())
 60
+
+Here we generate use failIfDiff and assertNoDiff to generate common diff (unified format) output from two dictionaries.
+
+>>> dc   = ['a', {'foo': 'bar'}]
+>>> failIfDiff(dc, dc, sr)
+True
+>>> assertNoDiff(dc, dc, sr)
+True
+>>> sr = SimpleReporter()
+>>> dc2  = ['a', {'foo': 'bar2'}]
+>>> failIfDiff(dc, dc2, sr)
+False
+>>> len(sr.get_errors())
+85
+>>> assertNoDiff(dc, dc2, sr)
+False
+>>> len(sr.get_errors())
+85
+
 """
 import sys
 import os
 
+import difflib
+from pprint import pformat
+
 def listToDict(l):
     d = {}
     for (k,v) in enumerate(l):
                  + repr(d_received)+ repr(type(d_received)) )
     return msg
 
+def diff_inspector(d_expected, d_received):
+    if isinstance(d_expected, (tuple, list, dict)):
+        d_expected = [pformat(d) for d in d_expected]
+    else:
+        d_expected = [pformat(d_expected)]
+
+    if isinstance(d_received, (tuple, list, dict)):
+        d_received = [pformat(d) for d in d_received]
+    else:
+        d_received = [pformat(d_received)]
+
+    diff = difflib.unified_diff(d_expected, d_received, fromfile="expected", tofile="received")
+    return ''.join([d + '\n' for d in diff])
+
 def dict_compare(d_expected, d_received, reporter=None, inspector=structure_inspector):
     if cmp(d_expected,d_received)==0:
         return True
                     
     return False
 
+def failIfDiff(d_expected, d_received, reporter=None):
+    return dict_compare(d_expected, d_received, reporter=reporter, inspector=diff_inspector)
+
+assertNoDiff = failIfDiff
+
 class SimpleReporter(object):
     def __init__(self):
         self._msg = None
                    "Topic :: Software Development :: Testing"],
       py_modules=['dict_compare'],
       )
+
+__ALL__ = ["dict_compare", "assertNoDiff", "failIfDiff"]