简体   繁体   English

python unittest在源代码中相对导入失败

[英]python unittest failing with relative import in source code

I have my python source code and unittest code structure in the following hierarchy: 我有以下层次结构的python源代码和unittest代码结构:

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

The code in the modules are as follows: module1.py 模块中的代码如下:module1.py

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

module2.py module2.py

from module3 import testMethod4

module3.py module3.py

def testMethod4():

module1_test.py 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)

when I run python module1_test.py it fails with import error: 当我运行python module1_test.py时,它失败并出现导入错误:

ImportError: cannot import name testMethod4

Not sure what is wrong. 不知道出什么问题了。 If I run the source code then all the imports are working fine. 如果我运行源代码,那么所有导入都可以正常工作。 But with python unittest these relative imports are failing. 但是使用python unittest时,这些相对导入失败了。 Can anyone tell me what mistake i'm doing. 谁能告诉我我在做什么错误。

Create an __init__.py module in your tests folder and add the following to it: 在测试文件夹中创建一个__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)

I think your path append statement is incorrect. 我认为您的path附加语句不正确。 You are appending /bin which would look for bin in the disk root. 您正在附加/bin ,它将在磁盘根目录中查找bin

sys.path.append("/usr/lib/bin")

The issue was because of another module with the same name coming from python libs. 问题是由于另一个同名模块来自python libs。 I renamed it and that solved the issue. 我重命名它,就解决了这个问题。 Another approach that helped is setting the module to PYTHONPATH. 另一个有用的方法是将模块设置为PYTHONPATH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM