0

I'd like to assert that say_name was called with each value in the list name.

from unittest.mock import patch


class MyClass:
    def __init__(self, name):
        self.name = name


def say_name(name):
    print('My name is ' + name)


def my_func():
    names = ['foo', 'bar', 'baz']
    objects = [MyClass(name) for name in names]
    [say_name(object.name) for object in objects]


@patch('my_test.say_name', spec_set=True)
@patch('my_test.MyClass', spec_set=True)
def test_my_func(mock_my_class, mock_say_name):
    names = ['foo', 'bar', 'baz']
    my_func()
    [mock_my_class.assert_any_call(name) for name in names]
    # [mock_say_name.assert_any_call(x.name) for x in xs]

If only one instance of MyClass was created, as is usually the case, I could set the attribute by setting mock_my_class.return_value = PropertyMock(name=name).

However, in this case, multiple different instances of MyClass are created.

Thus, this code will throw an error because my_func is executed by the tester, say_name is being passed a mock with no name attribute.

Therefore, how can I set different attributes for different MagicMock instances?

Jacob Beauchamp
  • 532
  • 5
  • 18

1 Answers1

2

It is possible to use side_effect to sequentially return values from a mock:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['spam', 123, 'potato']
>>> m()
'spam'
>>> m()
123
>>> m()
'potato'

Applying to your use-case:

from types import SimpleNamespace
from unittest.mock import call, patch

from my_lib import my_func


@patch('my_lib.say_name')
@patch('my_lib.MyClass')
def test_my_func(mock_my_class, mock_say_name):

    class FakeObj:
        pass

    obj1 = FakeObj()
    obj1.name = 'foo'
    obj2 = FakeObj()
    obj2.name = 'bar'
    obj3 = FakeObj()
    obj3.name = 'baz'

    mock_my_class.side_effect = [obj1, obj2, obj3]
    my_func()
    assert mock_my_class.call_args_list == [call('foo'), call('bar'), call('baz')]
    assert mock_say_name.call_args_list == [call('foo'), call('bar'), call('baz')]
wim
  • 338,267
  • 99
  • 616
  • 750