Python 单元测试导入问题

Python unittest import issues

这是我的项目设置:

my_project
    ./my_project
         ./__init__.py
         ./foo
              ./__init__.py
              ./bar.py
         ./tests
             ./__init__.py
             ./test_bar.py

test_bar.py 中,我有以下导入语句: from foo import bar

但是当我 运行 python /my_project/tests/test_bar.py 我得到这个错误:

ImportError: No module named foo.

关于如何解决这个问题有什么想法吗?

您可以使用相对导入:

from ..foo import bar

https://docs.python.org/2/whatsnew/2.5.html#pep-328-absolute-and-relative-imports

但我也认为 installing 你在 venv 中的项目使用绝对路径是更好的方法。

import sys
sys.path.append('/path/to/my_project/')

现在您可以导入

from foo import bar

想想你的 PYTHONPATH 上有什么。您的项目的顶级包是 my_project,因此它必须是您项目中某些内容的任何导入的开始。

from my_project.foo import bar

您也可以使用相对导入,尽管这不是很清楚,如果您更改了执行此导入的模块的相对位置,将会中断。

from ..foo import bar

理想情况下,test 文件夹根本不是一个包,也不属于您的应用程序包。请参阅 good practices 上的 pytests 页面。这需要你在你的包中添加一个 setup.py 并在开发模式下将它安装到你的 virtualenv 中。

pip install -e .

不要 运行 通过直接指向应用程序中的文件来进行测试。 structuring/installing 您的项目正确后,使用您正在使用的任何框架的发现机制来 运行 为您进行测试。例如,使用pytest,只需指向测试文件夹:

pytest tests

或者对于内置的单元测试模块:

python -m unittest discover -s tests