Dict Diff and Test Driven Development

I recently wrote a short function called dict_diff() that would take two dicts, compare them, and return another two dicts that contain only the differences between the original dicts (the code is available as a gist). It works something like:

dict_diff(
    {'a': {'ab': 12}, 'b': {'ba': 21, 'bb': 22}, 'c': {'cc': 33}},
    {'a': {}, 'b': {'ba': 21, 'bc': 23}, 'c': {'cc': 33}},
)

# outputs: (
#    {'a': {'ab': 12}, 'b': {'bb': 22}},
#    {'b': {'bc': 23}}
# )

I wrote it to make the output of assertEqual() a lot easier to read when dealing with large dicts that are not equal. It is a recursive function, but other than that it is fairly simple and nothing very special. What is different is that I wrote the function using test-driven development (TDD).

Generally when writing recursive functions I tend to get a bit caught up trying to ensure that the recursive part of the function works correctly from the beginning and lose sight of what the function is actually supposed to be doing. By knowing what the expected output would be ahead of time I was able to take a test-driven development approach and write the test cases beforehand, then just work my way through making all of the tests pass. By starting with the simple tests first and working my way through to the more complex ones it meant everything just fell into place and I didn't have to worry if I broke anything when I introduced the recursive stuff.

In the past I have tended to just write the tests in tandem with the code (sometimes before, sometimes after) and not really put a lot of thought into planning it all out with test cases. Being a simple function I knew what most of the results should be ahead of time without having to put much thought into it, but it was valuable to see how well this approach worked. I think I'll try to spend more time planning out my test cases to drive my development in the future.