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?