Assert_called_once_with need to check if the instances in the call are with the same info

Viewed 1547

I'm trying to use assert_called_once_with from unittest.mock https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.assert_called_once_with

But I want to check if 2 instances of objects have been passed with te correct attributes.

So inside the class I overrided the __eq__ func:

    def __eq__(self, other):
        return (
            self.id == other.id
            and self.users == other.users
        )

And in the code I used like this

        mock_add_user.assert_called_once_with(context_fix, expected_user_obj1, expected_user_obj2, users)

But I keep getting an error and the teste keeps comparing the repr of the instance, like this

<app.domain.model.load_md.Load object at 0x10cb7d7d0>
E           AssertionError: Expected call: add_user(<app.infrastructure.context.Context object at 0x10cb7da50>, <app.domain.model.load_md.Load object at 0x10cb7d7d0>, <app.domain.model.load_md.Load object at 0x10cb7d550>, [1, 2, 3, 2])
E           Actual call: add_user(<app.infrastructure.context.Context object at 0x10cb7da50>, <app.domain.model.load_md.Load object at 0x10ca7f5d0>, <app.domain.model.load_md.Load object at 0x10cd1e650>, [1, 2, 3, 2])

I really need a way to assert if an instance of a object has being passed as an parameter of the function with the correct attributes filled.

1 Answers

You want to use the call_args attribute of the mock object:

from unittest.mock import ANY, Mock

class Foo:
    pass

def call(add_user):
    f = Foo()
    add_user(f)

def test_is_instance():
    mock_add_user = Mock()

    call(mock_add_user)

    # expected = Foo()
    # mock_add_user.assert_called_once_with(expected) # This would fail
    mock_add_user.assert_called_once_with(ANY)
    assert isinstance(mock_add_user.call_args.args[0], Foo)

Here is a slightly more complex example with args and kwargs assertions:

from unittest.mock import ANY, Mock

class Foo:
    pass

class Bar:
    pass

def call(add_user):
    f = Foo()
    b = Bar()
    add_user(f, bar=b)

def test_is_instance():
    mock_add_user = Mock()

    call(mock_add_user)

    mock_add_user.assert_called_once_with(ANY, bar=ANY)
    assert isinstance(mock_add_user.call_args.args[0], Foo)
    assert isinstance(mock_add_user.call_args.kwargs["bar"], Bar)
Related