問題描述
我想在 python 中偽造一個包.我想定義一些東西以便代碼可以做
I want to fake a package in python. I want to define something so that the code can do
from somefakepackage.morefakestuff import somethingfake
somefakepackage 是在代碼中定義的,它下面的所有內容也是如此.那可能嗎?這樣做的原因是為了欺騙我的單元測試,我在 python 路徑中得到了一個包(或者正如我在標題中所說,一個模塊),這實際上只是為這個單元測試模擬的東西.
And somefakepackage is defined in code and so is everything below it. Is that possible? The reason for doing this is to trick my unittest that I got a package ( or as I said in the title, a module ) in the python path which actually is just something mocked up for this unittest.
謝謝!
推薦答案
當然.定義一個類,把你需要的東西放進去,把這個類分配給 sys.modules["classname"]
.
Sure. Define a class, put the stuff you need inside that, assign the class to sys.modules["classname"]
.
class fakemodule(object):
@staticmethod
def method(a, b):
return a+b
import sys
sys.modules["package.module"] = fakemodule
您也可以使用單獨的模塊(稱為 fakemodule.py
):
You could also use a separate module (call it fakemodule.py
):
import fakemodule, sys
sys.modules["package.module"] = fakemodule
這篇關于我可以“假"嗎?用于測試目的的python中的包(或至少一個模塊)?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!