如何在python中每次“import a real module”时加载我的伪模块?

2024-05-17 19:43:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在function.py上进行测试,并且函数.py有一个import语句:

from my.functions import cleaner
from my.functions import worker

我不想导入cleaner,因为它非常复杂。所以我尝试设置sys.path

^{pr2}$

fakes模块中,一个my.functions.cleaner也存在,但没有任何功能,这起作用,但也会影响worker,我真的希望worker能为我工作。在

所以我的问题是有没有办法“嘲笑”这个清洁剂对我的假清洁剂,我需要我的假清洁剂更换它每次进口清洁剂。在

我试过sys.modules,但失败了。在


Tags: path函数frompyimportmysysfunction
2条回答

您可以这样写unittests:

 from mock import MagicMock
 import function

 function.cleaner = MagicMock()

 # test function's methods

如果要动态替换函数,可以使用赋值语句进行替换,例如:

要了解这一点,请查看以下示例:

进口我的功能在

/my

functions.py

def cleaner():
    print("Cleaner from functions!")

def worker():
    print("Worker from functions!")

base.py

^{pr2}$

Python加载我的功能模块化系统模块,然后在后续的from imports中从已经加载的模块中获取对象,这样我们就可以在函数进行导入之前设置一个模拟函数。在

相关问题 更多 >