在模拟基类时如何为子类编写Unittest?

时间:2019-03-07 07:00:05

标签: python python-unittest python-unittest.mock

我想在模拟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

1 个答案:

答案 0 :(得分:0)

您不需要模拟整个类,就足以模拟其中的方法。顺便说一句,我不得不将sanity_check声明为static才能使您的示例代码字变。

只需看一下简单的基类:

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!

(模块是声明Base的模块的名称,我只是使用__main__进行测试...)