Skip to content

Instantly share code, notes, and snippets.

@belyak
Created January 6, 2018 01:25
Show Gist options
  • Save belyak/54036ee3415c13ec6f18f3041f18ce64 to your computer and use it in GitHub Desktop.
Save belyak/54036ee3415c13ec6f18f3041f18ce64 to your computer and use it in GitHub Desktop.
Patching many functions for all test case methods
from unittest import TestCase
from unittest.mock import patch, call
from my_project.module import complex_function
class SomeTestCase(TestCase):
# in this test case every method will mock calls to func_1, func_2, func_3, func_4
def setUp(self):
super().setUp()
self.patchers = []
def get_mock(target, autospec=True):
patcher = patch(target, autospec=autospec)
self.patchers.append(patcher)
return patcher.start()
self.func_1_mock = get_mock("my_project.module.func_1")
self.func_2_mock = get_mock("my_project.module.func_1")
self.func_3_mock = get_mock("my_project.module.func_1")
self.func_4_mock = get_mock("my_project.module.func_1")
def tearDown(self):
super().tearDown()
for patcher in self.patchers:
patcher.stop()
def test_with_multiple_mocks(self):
self.func_1_mock.return_value = 1
self.func_2_mock.return_value = 2
self.func_3_mock.return_value = 3
self.func_4_mock.return_value = 4
result = complex_function()
#... asserts about result ...
self.func_1_mock.assert_called_once_with(arg1=1, arg2=2)
self.func_2_mock.assert_called_once_with()
self.assertFalse(self.func_3_mock.called)
self.func_3_mock.assert_has_calls(calls=[call(21), call(23)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment