【发布时间】:2020-03-25 14:43:59
【问题描述】:
我的项目的目录结构是这样的:
project/
│
├── __init__.py
├── my_only_script.py
│
│
└── tests/
|
└── unit/
| ├── __init__.py
| └── unit_test.py
|
└── integration/
|
├── fixtures/
| ├── correct_data.csv
| └── generated_data.csv
|
├── __init__.py
└── test_integration.py
我正在尝试通过在测试目录上以发现模式运行 unittest 来执行 my_only_script.py 的集成测试
# working directory is project root
python -m unittest discover -s tests
但是,当我运行这个命令时,我遇到了错误
ImportError: Failed to import test module: integration.test_integration
为什么unittest可以发现集成测试——毕竟它提到了模块名称为integration.test_integration,所以它一定找到了它——但是集成测试仍然无法导入?
编辑
我遇到的完整错误信息是
(base) [project]$ python -m unittest discover -s tests
E
======================================================================
ERROR: integration.test_integration (unittest.loader._FailedTest)
ImportError: Failed to import test module: integration.test_integration
Traceback (most recent call last):
File "/home/david/anaconda3/lib/python3.7/unittest/loader.py", line 436, in _find_test_path
module = self._get_module_from_name(name)
File "/home/david/anaconda3/lib/python3.7/unittest/loader.py", line 377, in _get_module_from_name
import(name)
File "/home/david/project/tests/integration/test_integration.py", line 13
class PROJECT_INTEGRATION_TEST(unittest.TestCase)
^
SyntaxError: invalid syntax
Ran 1 test in 0.000s
FAILED (errors=1)
在 test_integration.py 中,除了普通的 import my_only_script 之外,我还尝试了相对导入 from ... import my_only_script、绝对导入 from project import my_only_script。我也尝试过完全注释掉导入语句。所有似乎都导致上面显示的相同错误。
我知道test_integration.py 中的代码没有任何问题else,因为如果我将它移到项目目录的根目录,并使用 python test_integration.py 运行它,其中 test_integration.py 使用 @ 987654333@ 测试运行没有问题。
【问题讨论】:
-
我猜
test_integration中的某些导入失败(可能是由于绝对/相对导入问题)。 -
哦,我明白了。我认为这是目录结构的问题。那么从
test_integration.py中导入my_only_script.py的正确方法是什么? -
从您的项目根目录使用绝对导入 - 现在是如何完成的?
-
我在test_integration.py中的import语句就是
import my_only_script,我觉得是对的,因为它不在包里,就在根目录下。 -
如果
project是你的根,你可能需要from project import my_only_script
标签: python python-3.x integration-testing python-import python-unittest