In my unit-tests there are some (nested) unittest.mock.Mock
objects.
At some point, these Mock
objects need to be serialized using json.dumps
.
As expected, this raises a
TypeError: Object of type Mock is not JSON serializable
There are many questions and answers on SO about making classes serializable. For example, there's 1, but this does not provide an answer specific to Mock
objects. The titles for 2 and 3 look promising, but these do not provide an answer either.
The obvious thing to do is use the default
argument, as in
json.dumps(my_mock_object, default=mock_to_dict)
The question is, what is the easiest way to implement mock_to_dict()
?
The serialized result should only include custom attributes, so Mock
internals should be disregarded.
The following implementation appears to do the job for simple cases
def mock_to_dict(obj):
if isinstance(obj, Mock):
# recursive case
return {
key: mock_to_dict(value)
for key, value in vars(obj).items()
if not key.startswith('_') and key != 'method_calls'
}
# base case
return obj
Is there a simpler way to do this?