Mocking the super class calls on python(在 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 但它有效,我会用我的例子来解释,这是基于 这个响应非常感谢@kindall:
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 上模拟超类调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 python 上模拟超类调用
基础教程推荐
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
