如何在导入时忽略某些Python模块?

时间:2018-08-28 10:34:16

标签: python python-import pytest python-module

我正在尝试对某些代码使用Pytest进行单元测试。测试在Docker上的单独Conda环境中运行。我想测试我的代码的某些功能,但是由于其中一些模块的安装很复杂且运行时间很长,因此无法安装我的代码的所有模块。

如何从文件中仅导入某些模块,而无需安装其他模块?

如果我在从文件导入模块的同时尝试运行测试,则我的测试失败,因为它无法导入其他模块。

下面是我的文件系统的模型:

test_file.py

from other_file import afunction

def this_test():
    assert afunction(2, 2) == 4

other_file.py

import math
import large_program

def afunction(x,y):
    return math.pow(x, y)

def anotherfunc():
    return large_program()

如果我运行Pytest,我将得到:

 E   ImportError: No module named 'large_program'

2 个答案:

答案 0 :(得分:2)

非常简单:将不依赖large_program的函数提取到另一个模块中,仅测试该模块。请注意,您可以通过在other_file中导入相关名称来做到这一点而不会破坏客户端代码(取决于other_file模块的代码):

# utils.py
import math

def afunction(x,y):
    return math.pow(x, y)

然后

# other_file.py
import large_program

# this will allow client code to access `afunction` from `other_file`
from utils import afunction

def anotherfunc():
    return large_program()

最后:

# 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

答案 1 :(得分:0)

我喜欢嘲笑的概念,并将其与dano的post here结合在一起。我创建了一个名为“ 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

other_file.py仍然像这样

import math
import large_program

def afunction(x,y):
    return math.pow(x, y)

def anotherfunc():
    return large_program()

您还可以在多个模块上应用with语句:

other_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), mock.patch.dict('sys.modules', even_larger_program=nothing):
    from other_file import afunction


def this_test():
    assert afunction(2, 2) == 4