Coming from a static programming language background, I am wondering how to best do mocking in Python. I am accustomed to dependency injection. Within tests, mocks are created and passed to the System Under Test (SUT). However, looking at Mock and other mock frameworks for Python, it appears that the types/functions/etc. in the module are replaced on a test-by-test basis.
Particularly, with Mock, atop each unit test you say @patch('some.type.in.the.module.under.test')
for each type/function/etc. you want to mock. For the lifetime of the test those things are mocked, then they are reverted. Unfortunately, across tests, the fixture is pretty close to the same and you end up repeating your @patch
es over and over again.
I want a way to share a collection of patches across unit tests. I also want carry through tweaks to the fixture in a composable way. I am okay using a context manager instead of a decorator.
You can patch the test class which flows down to each method in that class. And then you could inherit from a super class and work with the the setUp and tearDown methods.
import unittest
@patch('some.type.in.the.module.under.test')
class MySuperTestCase(unittest.TestCase):
pass
class MyActualTestCase(MySuperTestCase):
def test_method(self, mock_function)
mock_function.return_value = False
This is less general than you might think though. Because you need to patch the object in the exact location where it is being used. You don't patch 'sys.stdout', you patch 'my_dir.my_module.sys.stdout'. So it would really only be of use when testing a particular module. But to test that particular model you could certainly only need one single patch decorator.