I need to use unittest.mock.patch.object
to mock an external method that may fail sometimes. In the test, the method shall raise some errors and then return to the original behaviour. Note that the behaviour I want to reproduce is by far more complicated than return 'bar'
so I cannot just copy the code in Bar.some_method_that_may_fail
:
import unittest
from unittest.mock import patch
class Bar(object):
def some_method_that_may_fail(self):
return "bar"
class Foo(object):
bar = None
def retry_method(self):
try:
self.__class__.bar = Bar().some_method_that_may_fail()
except KeyError:
self.retry_method()
class TestRetry(unittest.TestCase):
def setUp(self):
self.instance = Foo()
def test_retry(self):
# raise KeyError the first 5 calls to the function and then work normally
errors_list = [KeyError("")] * 5
def raise_errors(*_):
if errors_list:
errors_list.pop(0)
# TODO: return to original behaviour
with patch.object(Bar, 'some_method_that_may_fail', new=raise_errors) as mocked:
self.instance.retry_method()
self.assertEqual(self.instance.bar, 'bar')
if __name__ == '__main__':
unittest.main()