实例化模拟对象时,模拟属性返回值被覆盖

Tag*_*agc 6 python mocking python-3.x python-mock

背景

我正在尝试为我正在编写的应用程序设置一个测试装置,其中我的一个类被模拟替换。我很高兴将模拟类的大部分属性保留为默认MagicMock实例(我只对它们的用法做出断言感兴趣),但该类还有一个属性,我想为其提供特定的返回值.

作为参考,这是我试图修补的类的大纲:

class CommunicationService(object):
    def __init__(self):
        self.__received_response = Subject()

    @property
    def received_response(self):
        return self.__received_response

    def establish_communication(self, hostname: str, port: int) -> None:
        pass

    def send_request(self, request: str) -> None:
        pass
Run Code Online (Sandbox Code Playgroud)

问题

我遇到的困难是,当我修补时CommunicationService,我还尝试为将返回特定值PropertyMockreceived_response属性设置 a 。然而,当我在我的生产代码中实例化这个类时,我发现调用CommunicationService.received_response返回的是默认MagicMock实例而不是我希望它们返回的特定值。

在测试设置期间,我执行以下操作:

context.mock_comms_exit_stack = ExitStack()
context.mock_comms = context.mock_comms_exit_stack.enter_context(
    patch('testcube.comms.CommunicationService', spec=True))

# Make 'received_response' observers subscribe to a mock subject.
context.mock_received_response_subject = Subject()
type(context.mock_comms).received_response = PropertyMock(return_value=context.mock_received_response_subject)

# Reload TestCube module to make it import the mock communications class.
reload_testcube_module(context)
Run Code Online (Sandbox Code Playgroud)

在我的生产代码中(在执行此设置后调用):

# Establish communication with TestCube Web Service.
comms = CommunicationService()
comms.establish_communication(hostname, port)

# Wire plugins with communications service.
for plugin in context.command.plugins:
    plugin.on_response = comms.received_response
    plugin.request_generated.subscribe(comms.send_request)
Run Code Online (Sandbox Code Playgroud)

我希望comms.received_response成为Subject(属性模拟的返回值)的一个实例。但是,我得到以下信息:

<MagicMock name='CommunicationService().received_response' id='4580209944'>
Run Code Online (Sandbox Code Playgroud)

问题似乎是从 patch 方法返回的实例上的 mock 属性工作正常,但是在创建 patched class 的新实例时mock 属性会变得混乱

南昌

我相信下面的片段抓住了这个问题的本质。如果有办法修改下面的脚本以使其print(foo.bar)返回mock value,那么希望它会显示我如何在我的实际代码中解决问题。

from contextlib import ExitStack
from unittest.mock import patch, PropertyMock

class Foo:
    @property
    def bar(self):
        return 'real value'

exit_stack = ExitStack()
mock_foo = exit_stack.enter_context(patch('__main__.Foo', spec=True))
mock_bar = PropertyMock(return_value='mock value')
type(mock_foo).bar = mock_bar

print(mock_foo.bar) # 'mock value' (expected)

foo = Foo()
print(foo.bar) # <MagicMock name='Foo().bar' id='4372262080'> (unexpected - should be 'mock value')

exit_stack.close()
Run Code Online (Sandbox Code Playgroud)

Sim*_*ser 9

以下行:

type(mock_foo).bar = mock_bar
Run Code Online (Sandbox Code Playgroud)

mock_foo在这一点上,mocks是enter_context. 如果我理解的文档正确就意味着现在你实际处理结果__enter__的返回值patch('__main__.Foo', spec=True)

如果您将该行更改为:

type(Foo.return_value).bar = mock_bar
Run Code Online (Sandbox Code Playgroud)

然后你将模拟bar实例的属性Foo(因为调用类的返回值是一个实例)。然后第二个打印语句将按mock value预期打印。