Skip to main content
 首页 » 编程设计

python unittest因源代码中的相对导入而失败

2025年05月04日42zhujiabin

我的 python 源代码和单元测试代码结构如下:

bin/ 
    module1.py 
    module2.py 
    module3.py 
test/ 
    module1_test.py 

模块中的代码如下: 模块1.py

from module2 import testMethod1, testMethod2 
def testMethodY(): 
    ... 
    ... 
    ... 

模块2.py

from module3 import testMethod4 

module3.py

def testMethod4(): 

module1_test.py

import unittest 
import sys, os 
path = os.path.dirname(__file__) 
path = os.path.join(path, 'bin') 
sys.path.append("/bin") 
from module1 import testMethodY 
 
...(Some code for unit test) 

当我运行 python module1_test.py 时 它因导入错误而失败:

ImportError: cannot import name testMethod4 

不知道哪里出了问题。如果我运行源代码,那么所有导入都可以正常工作。但是使用 python unittest 这些相对导入失败了。谁能告诉我我在做什么错误。

请您参考如下方法:

在您的测试文件夹中创建一个 __init__.py 模块并向其中添加以下内容:

import sys, os 
path = os.path.dirname(__file__) 
path = os.path.join(path, 'bin') 
if path not in sys.path: 
    sys.path.append(path)