Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python unit-test assert called with partial

using python 3.5.3 I want to assert that mocked function received specific arguments, but I don't want to check all received arguments, only the ones which are important for the test.

for example, instead of doing that:

my_func_mock.assert_called_with('arg1','arg2','arg3')

I would like to do something like:

my_func_mock.assert_called_with_partial(arg2='arg2')

Is it possible?

like image 776
user2880391 Avatar asked Dec 11 '22 05:12

user2880391


2 Answers

You can use ANY from unittest.mock.

from unittest.mock import MagicMock, ANY
my_func_mock = MagicMock()
my_func_mock('argument', 1, foo='keyword argument', bar={'a thing': 2})
my_func_mock.assert_called_once_with(
    'argument',
    1,
    foo='keyword argument',
    bar=ANY
)

This requires knowing the argument names already but allows any value for that argument.

See: https://docs.python.org/3/library/unittest.mock.html#unittest.mock.ANY

like image 88
Jaakkonen Avatar answered Dec 12 '22 17:12

Jaakkonen


assert_called_with checks how the last call is made. In a MagicMock object, the last call's args can be found in its call_args.args attribute. The last call's kwargs can be found in its call_args.kwargs attribute. We can check these individually.

Say in a test we have called my_func_mock with

my_func_mock(arg0, arg1, kwarg1 = 'kw1', kwarg2 = 'kw2')

We can directly check individual args by

assert my_func_mock.call_args.args[0] == arg0
assert my_func_mock.call_args.args[1] == arg1

and for any kwargs, we can directly check them individually by

assert my_func_mock.call_args.kwargs['kwarg1'] == 'kw1'
assert my_func_mock.call_args.kwargs['kwarg2'] == 'kw2'
like image 28
l001d Avatar answered Dec 12 '22 17:12

l001d