Developer Friendly Test Fixutres in Python
Comparing Dictionaries
Starting with 2.7, Python's unittest includes a very nice way to compare dictionaries. Instead of printing the two unequal values, assertDictEqual print a human-readable diff
import unittest a = {'key1': 5, 'key2': 7} b = {'key1': 6, 'key2': 7, 'key3': 9} class Test1(unittest.TestCase): def test_1(self): self.assertDictEqual(a, b) unittest.main()
This makes comparing otherwise complex structures easy. This capability saves time, but more importantly it encourages concrete testing rather than sampling.
AssertionError: {'key2': 7, 'key1': 5} != {'key3': 9, 'key2': 7, 'key1': 6}
- {'key1': 5, 'key2': 7}
? ^
+ {'key1': 6, 'key2': 7, 'key3': 9}
? ^ +++++++++++
Comparing Blocks of Text
Sometimes subclassing unittest.TestCase is sensible, but if you inherit from more than one derived class this can become messy. In Python it may be better to create a new object to mix in that will use difflib to raise an exception with a messaged formatted as a unified diff
class CustomCompare(object): def assertTextEqual(self, s1, s2): diff = list(difflib.unified_diff(s1.splitlines(), s2.splitlines())) if diff != []: raise AssertionError("\n".join(diff))
Now add this to your test case
class Test1(unittest.TestCase, Comparison): def test_1(self): self.assertTextEqual(a, b)
AssertionError: @@ -1,4 +1,4 @@ one -two +Two three