需要能够子类化一个mockpatched python类

2024-09-29 23:28:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模拟类的沙盒框架。每当客户机试图调用该类时,都会提供一个替换。这很有效。但是,当客户机试图继承修补过的类时,我的框架就崩溃了

from unittest.mock import patch

class ProductionObject(object):

    def __init__(self, name):  # The number of args here are being treated as a black box.
        self.name = name

class FakeObject(ProductionObject):

    def __init__(self, **kwargs):
        kwargs['name'] = 'sandbox_' + kwargs['name']
        super(FakeObject, self).__init__(**kwargs)


@patch('__main__.ProductionObject')
def run(func, mock):
    mock.side_effect = FakeObject
    func()

获取客户端代码并在框架中运行:

def foo():
    a = ProductionObject(name='a')
    print(a.name)

run(foo)  # works great

def bar():

    class AnotherProductionObject(ProductionObject):
        def __init__(self, name, val):
            self.val = val
            super(AnotherProductionObject, self).__init__(name=name)

    a = AnotherProductionObject(name='a', val='b')
    print(a.name)

run(bar)  # doesn't work

输出

sandbox_a                                            <-- this is the correct output
<MagicMock name='ProductionObject.name' id='#####'>  <-- this is broken

Tags: runnameself框架客户机initdefval
1条回答
网友
1楼 · 发布于 2024-09-29 23:28:23

可以使用以下代码执行此操作:

@patch('__main__.ProductionObject', new_callable=lambda:FakeObject)
def run(func, mock):
    func()

您遇到的问题是因为side_effect只会更改调用mock时的行为。当您从mock继承时,您实际上从未调用它,因此您从未收到FakeObject

相关问题 更多 >

    热门问题