I've some code where a call to the method update() changes the values of some instance variables. I use the changed value to leave a loop. Here is simplified example of my code:
def do_stuff(self):
# get a new instance of A
a = get_a()
while True:
a.update()
if a.state == 'state':
break
This a simple version of the class (I can't change the class, because it's 3rd party library):
class A(object):
def __init__(self):
self.state = ''
def update(self):
# call to external system
self.state = extern_func()
Now I want to test my function do_stuff() by mocking class A. To test every aspect of the function I want to have all the different values of state and it should changing after each call of a.update() (iterate over the different states).
I started with this set up for my unit test:
from mock import Mock, patch
import unittest
class TestClass(unittest.TestClass):
@patch('get_a')
def test_do_stuff(self, mock_get_a):
mock_a = Mock(spec=A)
mock_get_a.return_value = mock_a
# do some assertions
Can I achieve that kind behaviour with Mock?
I know that Mock has side_effect to return different value for consecutive function calls. But I can't figure out a way to change a value of an instance variable after a function call?
side_effectto have it return each of the states.external_funcis imported (but we can't see that in your example). If it would beimport mymoduleandmymodule.external_func()then you'd need to change the patching to includemymodule.