如何在导入时忽略某些Python模块?
我正在尝试对一些代码使用Pytest执行单元测试。测试在Docker上的单独Conda环境中运行。我想测试代码的某些功能,但无法安装代码中的所有模块,因为其中一些模块的安装非常复杂,并且需要运行时间 如何仅从文件导入某些模块,而不需要安装其他模块 如果在从文件导入模块时尝试运行测试,则测试将失败,因为它无法导入其他模块 下面是我的文件系统的模型: test_file.py如何在导入时忽略某些Python模块?,python,python-import,pytest,python-module,Python,Python Import,Pytest,Python Module,我正在尝试对一些代码使用Pytest执行单元测试。测试在Docker上的单独Conda环境中运行。我想测试代码的某些功能,但无法安装代码中的所有模块,因为其中一些模块的安装非常复杂,并且需要运行时间 如何仅从文件导入某些模块,而不需要安装其他模块 如果在从文件导入模块时尝试运行测试,则测试将失败,因为它无法导入其他模块 下面是我的文件系统的模型: test_file.py import unittest.mock as mock import nothing with mock.patch.d
import unittest.mock as mock
import nothing
with mock.patch.dict('sys.modules', large_program=nothing):
from other_file import afunction
def this_test():
assert afunction(2, 2) == 4
import unittest.mock as mock
import nothing
with mock.patch.dict('sys.modules', large_program=nothing), mock.patch.dict('sys.modules', even_larger_program=nothing):
from other_file import afunction
def this_test():
assert afunction(2, 2) == 4
其他_file.py
import math
import large_program
import even_larger_program
def afunction(x,y):
return math.pow(x, y)
def anotherfunc():
return large_program()
如果我运行Pytest,我将获得:
E ImportError: No module named 'large_program'
非常简单:将不依赖于
大型_程序的函数提取到另一个模块中,并仅测试该模块。请注意,通过导入其他_文件
中的相关名称,您可以在不中断客户端代码的情况下执行此操作(代码取决于您的其他_文件
模块):
# utils.py
import math
def afunction(x,y):
return math.pow(x, y)
然后
最后:
# test_file.py
# here we import from utils so we don't depend on `large_program`
from utils import afunction
def this_test():
assert afunction(2, 2) == 4
我喜欢克里斯蒂德的嘲弄,并把它与达诺的结合起来。我创建了一个名为“nothing.py”的空文件,该文件将用unittest模拟替换“large_program”:
test_file.py
import unittest.mock as mock
import nothing
with mock.patch.dict('sys.modules', large_program=nothing):
from other_file import afunction
def this_test():
assert afunction(2, 2) == 4
import unittest.mock as mock
import nothing
with mock.patch.dict('sys.modules', large_program=nothing), mock.patch.dict('sys.modules', even_larger_program=nothing):
from other_file import afunction
def this_test():
assert afunction(2, 2) == 4
另一个_file.py看起来仍然像这样
import math
import large_program
def afunction(x,y):
return math.pow(x, y)
def anotherfunc():
return large_program()
您还可以在多个模块上应用with语句:
其他_file.py
import math
import large_program
import even_larger_program
def afunction(x,y):
return math.pow(x, y)
def anotherfunc():
return large_program()
test_file.py
import unittest.mock as mock
import nothing
with mock.patch.dict('sys.modules', large_program=nothing):
from other_file import afunction
def this_test():
assert afunction(2, 2) == 4
import unittest.mock as mock
import nothing
with mock.patch.dict('sys.modules', large_program=nothing), mock.patch.dict('sys.modules', even_larger_program=nothing):
from other_file import afunction
def this_test():
assert afunction(2, 2) == 4
你不能对你需要的模块使用模拟吗?