test_aide.functions.assert_function_call

test_aide.functions.assert_function_call(mocker, target, attribute, expected_calls_args, **kwargs)[source]

Assert a function has been called with given arguments. This should be used as a context manager, see example below.

This can be used to check multiple calls to the same function. Both the positional and keyword arguments must be specified for any calls to check.

Parameters
  • mocker (pytest_mock.plugin.MockerFixture) – The mocker fixture from the pytest_mock package.

  • target (object) – Object with function to test is called.

  • attribute (str) – Name of the method to mock on the target object

  • expected_calls_args (dict) – Expected positional and keyword arguments to specific calls to target.attribute. Keys of expected_calls_args must be ints (indexed from 0) indicating the call # of interest. The value for each key should be a dict with keys ‘args’ and ‘kwargs’. The values for the keys in these sub dicts should be a tuple of expected positional arguments and a dict of expected keyword arguments for the given call to target.attribute. For example if expected_calls_args = {0: {‘args’:(‘a’,’b’), ‘kwargs’:{‘c’: 1}}} this indicates that the first call to target.attribute is expected to be called with positional args (‘a’,’b’) and keyword args {‘c’: 1}. See the example section below for more examples.

  • **kwargs (any) – Arbitrary keyword arguments passed on to mocker.patch.object.

Examples

>>> import test_aide as ta
>>> import random
>>>
>>> def test_number_calls_to_function(mocker):
...     expected_call_arguments = {
...         0: {
...             'args': (
...                 [1, 2, 3],
...             ),
...             'kwargs': {
...                 'weights': None
...             }
...         },
...         2: {
...             'args': (
...                 [1, 2, 3],
...             ),
...             'kwargs': {}
...         },
...         3: {
...             'args': (),
...             'kwargs': {
...                 'populaton': [1, 2, 3],
...                 'k': 2
...              }
...         }
...     }
...     with h.assert_function_call(mocker, random, "choices", expected_call_arguments, return_value=None):
...         random.choices([1, 2, 3], weights=None)
...         random.choices([1, 2, 3])
...         random.choices([1, 2, 3])
...         random.choices(population=[1, 2, 3], k=2)
>>>