[英]ImportError with unittest and multiples modules
I have a project with the following structure:我有一个具有以下结构的项目:
/
├── test
│ ├── __init__.py
│ └── test_do_stuff.py
└── my_package
├── do_stuff.py
├── helpers
│ ├── my_helper.py
│ └── __init__.py
├── __init__.py
└── main_do_stuff.py
When running the tests I get ImportError: No module named 'helpers'
运行测试时,我收到
ImportError: No module named 'helpers'
When the test imports my_package.do_stuff
, it tries to import helpers.my_helper
当测试导入
my_package.do_stuff
,它会尝试导入helpers.my_helper
The command to run the tests is python3 -m unittest
(Is this a correct way?)运行测试的命令是
python3 -m unittest
(这是正确的方法吗?)
All the __init__.py
are empty.所有
__init__.py
都是空的。
test_do_stuff.py: test_do_stuff.py:
import unittest
import my_package.do_stuff
# ...
do_stuff.py: do_stuff.py:
import helpers.my_helper
# ...
main_do_stuff.py: main_do_stuff.py:
import do_stuff
python3 my_package/main_do_stuff.py
works. python3 my_package/main_do_stuff.py
有效。 The main calls the same functions as the test. main 调用与测试相同的函数。
Does the problem comes from the way I launch the tests?问题是否来自我启动测试的方式?
Or my structure?还是我的结构?
I'm trying to find a solution that doesn't involve messing too much with the path or writing a lot of code just to run the tests.我试图找到一个解决方案,它不涉及过多地弄乱路径或编写大量代码来运行测试。 (There should be a simple way to have the tests separated from the code doesn't it?)
(应该有一种简单的方法可以将测试与代码分开,不是吗?)
The problem is the use of implicit relative imports:问题是使用隐式相对导入:
import helpers.my_helper
should be应该
import my_package.helpers.my_helper
Your problem is that python doesn't accept your directory hieracy.您的问题是 python 不接受您的目录层次结构。 Just put the test files under a root directory ( /everything for example ) and it will work fine.
只需将测试文件放在根目录下(例如 /everything ),它就可以正常工作。 Your directorys could look like this:
您的目录可能如下所示:
/
└── everything
├── __init__.py
├── test_do_stuff.py
└── my_package
├── do_stuff.py
├── helpers
│ ├── my_helper.py
│ └── __init__.py
├── __init__.py
└── main_do_stuff.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.