Python 一个 class 中的 Mock Patch 多个方法

Python Mock Patch multiple methods in a class

我正在尝试修补 class 中的多个方法。这是我的简化设置

Hook.py 定义为

class Hook():
    def get_key(self):
        return "Key"

    def get_value(self):
        return "Value"

HookTransfer.py 定义为

from Hook import Hook

class HookTransfer():
    def execute(self):
        self.hook = Hook()
        key = self.hook.get_key()
        value = self.hook.get_value()
        print(key)
        print(value)

我想在 Hook class 中模拟方法 get_key 和 get_value。以下作品即打印 New_Key 和 New_Value

from HookTransfer import HookTransfer
import unittest
from unittest import mock

class TestMock(unittest.TestCase):
    @mock.patch('HookTransfer.Hook.get_key', return_value="New_Key")
    @mock.patch('HookTransfer.Hook.get_value', return_value="New_Value")
    def test_execute1(self, mock_get_key, mock_get_value):
        HookTransfer().execute()

if __name__ == '__main__':
    unittest.main()

然而事实并非如此。它打印 <MagicMock name='Hook().get_key()' id='4317706896'><MagicMock name='Hook().get_value()' id='4317826128'>

from HookTransfer import HookTransfer
import unittest
from unittest import mock

class TestMock(unittest.TestCase):
    @mock.patch('HookTransfer.Hook', spec=True)
    def test_execute2(self, mock_hook):
        mock_hook.get_key = mock.Mock(return_value="New_Key")
        mock_hook.get_value = mock.Mock(return_value="New_Value")
        HookTransfer().execute()

if __name__ == '__main__':
    unittest.main()

从直觉上看,第二个似乎也应该有效,但事实并非如此。能不能帮忙解释下为什么不行。我怀疑它与 "where to patch" 有关,但我无法弄清楚。

经过一些测试,我找到了问题所在。

在第二个测试用例中,补丁装饰器创建了一个 Mock class 的新实例,并通过 mock_hook 参数将其传递给 test_execute2 函数。让我们将其称为 mock1。 mock1 替换了 HookTransfer.py 中的 Hook class。当self.hook = Hook()为运行时,转化为调用mock1的__init__。通过设计,这个 return 是另一个 Mock 实例 - 让我们将其称为 mock2。所以 self.hook 指向 mock2。但是mock_hook.get_key = mock.Mock(return_value="New_Key"),模拟了mock1中的方法。

为了正确模拟,mock2 需要修补。这可以通过两种方式完成

  1. 通过模拟 mock1 的 return_value(returns mock2)mock_hook.return_value.get_key = mock.Mock(return_value="New_Key")
  2. 模拟 mock1 构造函数的 return 值(returns mock2)mock_hook().get_key = mock.Mock(return_value="New_Key")

这两个选项实际上做同样的事情。

您需要的是:

模拟 class 钩子,

from HookTransfer import HookTransfer
from Hook import Hook

import unittest
try:
    import mock
except ImportError:
    from unittest import mock

class TestMock(unittest.TestCase):
    @mock.patch.object(Hook, 'get_key', return_value="New_Key")
    @mock.patch.object(Hook, 'get_value', return_value="New_Value")
    def test_execute1(self, mock_get_value, mock_get_key):
        HookTransfer().execute()

if __name__ == "__main__":
    unittest.main()

您可以使用 patch.multiple() 修补模块或 class 的多个方法。像这样的东西应该适合你的情况:

import unittest
from unittest.mock import MagicMock, patch

class TestMock(unittest.TestCase):
    @patch.multiple('HookTransfer.Hook',
                    get_key=MagicMock(return_value='New_Key'),
                    get_value=MagicMock(return_value='New_Value'))
    def test_execute1(self, **mocks):
        HookTransfer().execute()

patch.multiple()作为装饰器时,mock通过关键字传入装饰函数,作为上下文管理器时返回字典。