简体   繁体   中英

Python Unit Testing - Mock Patch at Runtime?

I am writing unit tests in python.

My code uses redis frequently and I want to mock this. I'd like to do this globally and not worry about mocking it in each test, but I don't think this is possible using the @patch decorator.

Example of working test-

class ExamplesTests(AbstractTestCase, unittest.TestCase):

    @patch('main.redis')
    def test_the_thing(self, redis: MagicMock):
        redis.set = self._my_mock_set # method that sets a dict val
        redis.get = self._my_mock_get # method that gets a dict val

        result = main.do_the_thing()

        self.assertTrue(result)

I don't actually need what's in the mock cache, i'm just trying to prevent the need to cleanup the actual redis cache that's being used by other processes. I tried doing this in the setUp -

class AbstractTestCase(ABC):

    @patch('main.redis')
    def setUp(self, redis: MagicMock):
        redis.set = self._my_mock_set # method that sets a dict val
        redis.get = self._my_mock_get # method that gets a dict val

Error: setUp() takes 2 positional arguments but 3 were given

Instead of patching every test, is it possible to use setup without the decorator? Something like this?-

class AbstractTestCase(ABC):

    def setUp(self):
        redis = patch('main.redis')
        redis.set = self._my_mock_set # method that sets a dict val
        redis.get = self._my_mock_get # method that gets a dict val

You can indeed create the patch like that, but you then need to explicitly enable it as well. You'll want to stop the patch as well after the test completes.

def setUp(self):
    self.redis = redis = patch('main.redis')
    redis.set = ...
    redis.get = ...
    redis.start()
    self.addCleanup(redis.stop)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM