在python上模拟超类调用 [英] Mocking the super class calls on python

查看:81
本文介绍了在python上模拟超类调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一些单元测试,有时需要模拟super调用以引发错误,例如:

I am doing some unit testing and at some point I need to mock a super call to throw an error, for example:

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

我通常使用 mocker 库来模拟我的对象,但是我还没有找到模拟该对象的方法

I am using the mocker library to mock my objects in general but I haven't found a way to mock this.

推荐答案

我发现了一种方法,虽然有点hacky,但是可以用,我将以我的示例为例进行说明,这是基于

I found a way, sort of hacky but it works, I'll explain with my example, this is based on this response so thanks @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.

so essentially what I do is check if the super call is from the class I want to mock, else just do a normal super.

希望这对某人有帮助:)

Hope this helps someone :)

这篇关于在python上模拟超类调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆