0

我想在模拟 Base 时为 Subclass 编写测试,因为 Base 来自外部库。鉴于我们修改了基类中的所有可调用对象,我该如何模拟它。

class SubClass(Base):
    def __init__(self, *args, **argv):
        super().__init__(*args, **argv)

        for attr_name in Base.__dict__:
            attr = getattr(self, attr_name)
            if callable(attr):
                setattr(self, attr_name, functools.partial(__class__.sanity_check, attr))

    @classmethod
    def sanity_check(func):
        txt = func()
        if 'banned_word' in txt:
            raise Exception('Device has banned word on it!')
        return txt
4

1 回答 1

0

您不需要模拟整个类,从中模拟方法就足够了。顺便说一句,我必须声明sanity_check为静态才能使您的示例代码正常工作。

看看一个简单的基类:

class Base:
    def a(self):
        return "foo"
    def b(self):
        return "bar"

我们可以a在创建子类对象之前轻松地模拟方法:

with unittest.mock.patch('module.Base.a', return_value='banned_word') as p:
    x = SubClass()
    x.a()

按预期提高:

Traceback (most recent call last):
  File "###", line #, in <module>
    x.a()
  File "###", line ##, in sanity_check
    raise Exception('Device has banned word on it!')
Exception: Device has banned word on it!

module是声明的模块的名称Base,我只是用于__main__测试...)

于 2019-03-07T07:29:24.573 回答