Pytest在其他文件夹中找不到模块



我的Python项目结构是

my_project
src
extensions
my_tool.py
tests
main_test.py
pytest.ini
.env

main_test.py中,我正在导入一个在my_tool.py中定义的类,如:

from extensions import main_tool as tool
hammer = tool.Hammer()

我正在使用Pipenv。我遵循了以下步骤:

  • 通过运行pipenv shell激活我的env
  • 已安装pytest。pipenv install -d pytest

我甚至添加了具有此内容的pytest.ini文件

[pytest]
pythonpath = src/extensions

文件.env具有

PYTHONPATH=${PYTHONPATH}:src/extensions

我无法让它发挥作用。每当我从项目的根运行pytest时,我总是得到

tests/main_test:1: in <module>
from extensions import main_tool as tool
E   ModuleNotFoundError: No module named 'extensions'

您只需要在使用from extensions import ...:时将pythonpath指向src

pytest.ini更改为:

[pytest]
pythonpath = src/

最新更新