本文介紹了在 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 上模擬超類調用的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!