问题描述
我想在 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中的包(或至少一个模块)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!