78

I want a unit test to assert that a variable action within a function is getting set to its expected value, the only time this variable is used is when it is passed in a call to a library.

Class Monolith(object):
    def foo(self, raw_event):
        action =  # ... Parse Event
        # Middle of function
        lib.event.Event(METADATA, action)
        # Continue on to use the build event.

My thought was that I could mock lib.event.Event, and get its input arguments and assert they are of specific value.

>Is this not how mocks work? The mock documentation frustrates me with its inconsistency, half-examples, and plethora of examples that are not related to what I want to do.

2
  • 1
    where have u used mock? you can mock lib.event.Event and assert
    – vks
    Jun 30, 2015 at 4:29
  • in retrospect, this the patch and mock approach seems so much more natural/defacto now then it did then Dec 13, 2018 at 22:54

4 Answers 4

87

You can use call_args or call_args_list as well.

A quick example would look like:

import mock
import unittest

class TestExample(unittest.TestCase):

    @mock.patch('lib.event.Event')
    def test_example1(self, event_mocked):
        args, kwargs = event_mocked.call_args
        args = event_mocked.call_args.args  # alternatively 
        self.assertEqual(args, ['metadata_example', 'action_example'])

I just quickly written this example for somebody who might need it - I have not actually tested this so there might be minor bugs.
3
  • 3
    For me, I had to do self.assertEqual(event_mocked.call_args[0], <expected_args>). event_mocked.call_args.args didn't work for me. Maybe a version issue?
    – Josmoor98
    Mar 10, 2021 at 10:56
  • @Josmoor98 If it is a version issue, it might help someone if you could share your Python version.
    – akki
    Mar 19, 2021 at 11:26
  • Indeed, as pointed out in the comments, python version - Python 3.6.12 - [PyPy 7.3.3 with GCC 9.3.0]
    – Josmoor98
    Mar 19, 2021 at 12:10
21

You could use patch decorator and then call assert_called_with to that mocked object like this:

If you have this structure:

example.py
tests.py
lib/__init__.py
lib/event.py

And the content of example.py is:

import lib

METADATA = 'metadata_example'

class Monolith(object):

    def foo(self, raw_event):
        action =  'action_example' # ... Parse Event
        # Middle of function
        lib.event.Event(METADATA, action)
        # Continue on to use the build event.

And the content of lib/event.py is:

class Event(object):

    def __init__(self, metadata, action):
        pass

The code of tests.py should be like:

import mock
import unittest

from lib.event import Event
from example import Monolith


class TestExample(unittest.TestCase):

    @mock.patch('lib.event.Event')
    def test_example1(self, event_mocked):
        # Setup
        m = Monolith()

        # Exercise
        m.foo('raw_event')

        # Verify
        event_mocked.assert_called_with('metadata_example', 'action_example')
4
  • 6
    what if i want to get the arguments passed to the mock as a dictionary?
    – dopatraman
    Jun 6, 2017 at 22:32
  • 19
    @dopatraman You can either use call_args or call_args_list. Jul 7, 2017 at 13:51
  • @CraigAnderson Can you post that as an answer?
    – Stevoisiak
    May 9, 2018 at 20:21
  • @StevenVascellaro It's not really an answer to the original question, is it? I've proposed an edit to this answer to illustrate how they might be used. May 10, 2018 at 12:30
10

If you want to access arguments directly, how about this? A little redundant though... See https://docs.python.org/3.6/library/unittest.mock.html#unittest.mock.call.call_list

import mock
import unittest

from lib.event import Event
from example import Monolith


class TestExample(unittest.TestCase):

    @mock.patch('lib.event.Event')
    def test_example1(self, event_mocked):
        # Setup
        m = Monolith()

        # Exercise
        m.foo('raw_event')

        # Verify
        name, args, kwargs = m.mock_calls[0]
        self.assertEquals(name, "foo")
        self.assertEquals(args, ['metadata_example', 'action_example'])
        self.assertEquals(kwargs, {})
1

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.