繁体   English   中英

在 python 上模拟超类调用

[英]Mocking the super class calls on python

我正在做一些单元测试,在某些时候我需要模拟一个super调用来抛出错误,例如:

@classmethod
def myfunc(cls, *args, **kwargs)
    try:
        super(MyClass, cls).my_function(args, kwargs)
    except MyException as e:
        #...

我正在使用mocker库来模拟我的一般对象,但我还没有找到一种方法来模拟它。

使用标准库中的unittest.mock我会做这样的事情。

在您的类定义中:

from somelib import ASuperClass

class MyClass(ASuperClass):
    def my_cool_method(self):
        return super().my_cool_method()

在您调用MyClass的模块中:

from unittest.mock import patch
from mymodule import MyClass

@patch("mypackage.mymodule.ASuperClass.my_cool_method")
def call_with_mock(mocked_super):
    myinstance = MyClass()
    myinstance.my_cool_method()
    # do stuff with `mocked_super`

call_with_mock()

我找到了一种方法,有点 hacky 但它有效,我会用我的例子来解释,这是基于这个回复所以谢谢@kindall:

def my_test(self):
    import __builtin__
    from mocker import Mocker, KWARGS, ARGS

    mymocker = mocker.mock()
    mymocker.my_function(ARGS, KWARGS)
    mocker.throw(MyException)

    def mysuper(*args, **kwargs):
        if args and issubclass(MyClass, args[0]):
            return mymocker
        return original_super(*args, **kwargs)

    __builtin__.original_super = super
    __builtin__.super = mysuper

    with mocker:
        MyClass.myfunc()

所以基本上我要做的是检查super调用是否来自我想要模拟的类,否则就做一个普通的super

希望这对某人有所帮助:)

如果有人需要另一种方法来解决这个模拟:

# some_package/some_module.py

class MyClass(SuperClass):

    def some_function(self):
        result_super_call = super().function()

# test_file.py

@patch('some_package.some_module.super')
def test_something(self, mock_super):
    obj = MyClass()
    mock_super().some_function.return_value = None

使用 Python 3.6

@Markus 找对地方了。 只要您在进行单元测试(即只有一次调用super ),您就可以模拟__builtin__.super如下所示:

with mock.patch('__builtin__.super') as mock_super:
    mock_super.side_effect = TypeError
    with self.assertRaises(TypeError):
        obj.call_with_super()

Python 自己的 Mock 类提供了一个spec参数,可以帮助解决这个问题:

with mock.patch('...ParentClass.myfunc') as mocked_fn:
    mocked_fn.side_effect = MyException()  # Parent's method will raise
    instance = mock.Mock(spec=MyClass)  # Enables using super()
    MyClass.myfunc(instance)  # Will enter your `except` block

好吧,那你就需要mock一下MyClass的超类的my_function方法来炸了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM