Python assert_dict_matches recursive test helper function
The Jest library for Node.js has a helpful expect.objectContaining function that makes it easy to assert only on the keys of interest in a particular test.
Python’s unittest
library does have a similar
assertDictEqual
method, but it asserts on all keys.
I wanted to do be able to easily assert on only the keys of interest in Python
tests, so I put together this quick test helper function to do so. It makes use
of assertDictEqual
, but only after extracting the keys of interest in a
recursive way.
from typing import Dict
from unittest import TestCase
def assert_dict_matches(expected: Dict, actual: Dict):
"""
Assert that `actual` matches `expected` for the keys and indexes that are
present in `expected`, recursively.
"""
tc = TestCase()
tc.maxDiff = None
matched = match_keys(expected, actual)
tc.assertDictEqual(expected, matched)
def match_keys(expected, actual):
if isinstance(expected, dict):
assert isinstance(actual, dict)
return {
k: match_keys(expected[k], v)
for k, v in actual.items()
if k in expected.keys()
}
if isinstance(expected, list):
assert isinstance(actual, list)
return [
match_keys(expected[i], v) for i, v
in enumerate(actual[:len(expected)])
]
return actual