简体   繁体   English

Python单元测试-运行时模拟补丁?

[英]Python Unit Testing - Mock Patch at Runtime?

I am writing unit tests in python. 我正在用python编写单元测试。

My code uses redis frequently and I want to mock this. 我的代码经常使用redis ,我想对此进行模拟。 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. 我想在全球范围内进行此操作,而不必担心在每个测试中都对其进行@patch ,但是我认为使用@patch装饰器是不可能的。

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. 我实际上并不需要模拟缓存中的内容,我只是想避免需要清除其他进程正在使用的实际Redis缓存。 I tried doing this in the setUp - 我想在这样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 错误:setUp()接受2个位置参数,但给出了3个

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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