我想在 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模板网!
在鼻子下测试 Python 代码时,我应该如何验证日志How should I verify a log message when testing Python code under nose?(在鼻子下测试 Python 代码时,我应该如何验证日志消息?)
修补函数的 __call__Patch __call__ of a function(修补函数的 __call__)
如何在 Python 中对象的模拟方法中调用 self?How to call self in a mock method of an object in Python?(如何在 Python 中对象的模拟方法中调用 self?)
仅模拟对象上的单个方法Mocking only a single method on an object(仅模拟对象上的单个方法)
在 Python 中模拟子进程调用Mocking a subprocess call in Python(在 Python 中模拟子进程调用)
检查多个模拟的调用顺序Checking call order across multiple mocks(检查多个模拟的调用顺序)