The answers above were helpful, but I wanted an easy way to write a unit test that wouldn't need refactoring when the tested code changed how the mocked function call was changed without any functional changes to go with it.
For instance, if I chose to call the function partially or completely by keywords (or build a kwargs dictionary and plug that in) without changing the values being passed in:
def function_being_mocked(x, y):
pass
# Initial code
def function_being_tested():
# other stuff
function_being_mocked(42, 150)
# After refactor
def function_being_tested():
# other stuff
function_being_mocked(x=42, y=150)
# or say kwargs = {'x': 42, 'y': 150} and function_being_mocked(**kwargs)
This might be overkill, but I wanted my unit test not to worry about changes to the function call format as long as the expected values made it to the function call (even including specifying or not-specifying default values).
Here's the solution I came up with. I hope this helps simplify your testing experience:
from inspect import Parameter, Signature, signature
class DefaultValue(object):
def __init__(self, value):
self.value = value
def __eq__(self, other_value) -> bool:
if isinstance(other_value, DefaultValue):
return self.value == other_value.value
return self.value == other_value
def __repr__(self) -> str:
return f'<DEFAULT_VALUE: {self.value}>'
def standardize_func_args(func_sig, args, kwargs, is_method):
kwargs = kwargs.copy()
# Remove self/cls from kwargs if is_method=True
parameters = list(func_sig.parameters.values())
if is_method:
parameters = list(parameters)[1:]
# Positional arguments passed in need to line up index-wise
# with the function signature.
for (i, arg_value) in enumerate(args):
kwargs[parameters[i].name] = arg_value
kwargs.update({
param.name: DefaultValue(param.default)
for param in parameters
if param.name not in kwargs
})
# Order the resulting kwargs by the function signature parameter order
# so that the stringification in assert error message is consistent on
# the objects being compared.
return {
param.name: kwargs[param.name]
for param in parameters
}
def _validate_func_signature(func_sig: Signature):
assert not any(
p.kind == Parameter.VAR_KEYWORD or p.kind == Parameter.VAR_POSITIONAL
for p in func_sig.parameters.values()
), 'Functions with *args or **kwargs not supported'
def __assert_called_with(mock, func, is_method, *args, **kwargs):
func_sig = signature(func)
_validate_func_signature(func_sig)
mock_args = standardize_func_args(
func_sig, mock.call_args.args, mock.call_args.kwargs, is_method)
func_args = standardize_func_args(func_sig, args, kwargs, is_method)
assert mock_args == func_args, f'Expected {func_args} but got {mock_args}'
def assert_called_with(mock, func, *args, **kwargs):
__assert_called_with(mock, func, False, *args, **kwargs)
def assert_method_called_with(mock, func, *args, **kwargs):
__assert_called_with(mock, func, True, *args, **kwargs)
Usage:
from unittest.mock import MagicMock
def bar(x, y=5, z=25):
pass
mock = MagicMock()
mock(42)
assert_called_with(mock, bar, 42) # passes
assert_called_with(mock, bar, 42, 5) # passes
assert_called_with(mock, bar, x=42) # passes
assert_called_with(mock, bar, 42, z=25) # passes
assert_called_with(mock, bar, z=25, x=42, y=5) # passes
# AssertionError: Expected {'x': 51, 'y': <DEFAULT_VALUE: 5>, 'z': <DEFAULT_VALUE: 25>} but got {'x': 42, 'y': <DEFAULT_VALUE: 5>, 'z': <DEFAULT_VALUE: 25>}
assert_called_with(mock, bar, 51)
# AssertionError: Expected {'x': 42, 'y': 51, 'z': <DEFAULT_VALUE: 25>} but got {'x': 42, 'y': <DEFAULT_VALUE: 5>, 'z': <DEFAULT_VALUE: 25>}
assert_called_with(mock, bar, 42, 51)
Please note a caveat before using this. assert_called_with()
requires reference to the original function. If you're using the decorator @unittest.mock.patch
on your unit test, it might backfire as your attempt to look up the function signature might pick up the mock object rather than the original function:
from unittest import mock
class Tester(unittest.TestCase):
@unittest.mock.patch('module.function_to_patch')
def test_function(self, mock):
function_to_be_tested()
# Here module.function_to_patch has already been replaced by mock,
# leading to error from _validate_func_signature. If this is your
# intended usage, don't use assert_called_with()
assert_called_with(mock, module.function_to_patch, *args, **kwargs)
I recommend using unittest.mock.patch.object
that requires you to import the function being patched as my code requires that for reference to the function anyway:
class Tester(unittest.TestCase):
def test_function(self):
orig_func_patched = module.function_to_patch
with unittest.mock.patch.object(module, 'function_to_patch') as mock:
function_to_be_tested()
assert_called_with(mock, orig_func_patched, *args, **kwargs)
lib.event.Event
and assert