gpt4 book ai didi

Python unittest 导入问题

转载 作者:行者123 更新时间:2023-12-03 15:36:24 27 4
gpt4 key购买 nike

这是我的项目设置:

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 .

有想法该怎么解决这个吗?

最佳答案

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

from my_project.foo import bar

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

理想情况下, test文件夹根本不是一个包,也不是您的应用程序包的一部分。在 good practices 上查看 pytests 的页面.这需要您添加 setup.py到您的软件包并以开发模式将其安装到您的virtualenv。
pip install -e .

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

或者对于内置的 unittest 模块:
python -m unittest discover -s tests

关于Python unittest 导入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28664632/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com