How Do You Set Different Attributes For Different MagicMock Instances In Python?
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 = nam
Solution 1:
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')]
Post a Comment for "How Do You Set Different Attributes For Different MagicMock Instances In Python?"