Reputation: 131
I am looking into the excellent pytest plugin called pytest-mock (https://github.com/pytest-dev/pytest-mock), and now I am trying some examples with assert_has_calls. In short I am testing an instance of class B, more specifically how that instance interact with an instance of class A (in which I have mocked the method 'time_consuming_task').
The example is working with alt. B (see comments in code). I would prefer alt. A, and instead mock the method in class A directly, instead of mocking the method in the instance of class A accessed through the instance (obj) of class B.
class A(object):
def do_time_consuming_task(self, timeout):
return True
class B(object):
def __init__(self):
self.a = A()
def do_work(self, timeout):
return self.a.do_time_consuming_task(timeout)
def test_calls(mocker):
# Prepare
obj = B()
#mock_a = mocker.patch.object(A, 'do_time_consuming_task', autospec=True) # Alt. A
mock_a = mocker.patch.object(obj.a, 'do_time_consuming_task', autospec=True) # Alt. B
mock_a.return_value = True
# Exercise
obj.do_work(timeout=100)
obj.do_work(timeout=50)
# Assert
mock_a.assert_has_calls([mocker.call(100), mocker.call(50)])
Upvotes: 6
Views: 10091
Reputation: 131
Managed to figure it out with the help of another answer provided by the author of pytest-mock.
The assert should be called as follows if using alt. A:
mock_a.assert_has_calls([mocker.call(mocker.ANY, 100), mocker.call(mocker.ANY, 50)])
Upvotes: 6