使用诗歌运行 pytest 找不到子模块
我有一个这样结构的项目:
├───project
| ├───__init__.py
| ├───main.py
│ ├───collect_data
│ │ └───functions.py
│ └───other_folder
│ └───generate.py
├───tests
| ├───__init__.py
│ └───test_functions.py
├───pyproject.toml
└───poetry.lock
我做了poetry install
(它生成了poetry.lock)。 我在 Windows 机器上使用 vscode 和 python 3.7.11
、pytest 7.0.1
。和 conda 环境。
所以现在的问题是:如果我对functions.py进行测试,我会像这样导入:from project.collect_data.functions import my_function
并且这有效。
但是,如果我尝试测试“main.py”中的端点(from project.main import another_function
),问题是 main.py 依次导入一些函数,但没有调用“project”(就像 fromcollect_data.functions import my_function
) 因此,当测试运行时,我遇到 collect_data module not found
错误。
我读过大量文档,但显然我做错了。代码通常是从“项目”运行的,所以我不愿意改变 main 导入其他函数的方式(并且一些子文件夹也从其他地方调用其他函数,该项目实际上比示例大得多) .
我认为问题与 PATH 有关,但我不太确定如何解决它。
我试图在项目的根目录放置一个空的conftest.py(我在SO的某个地方看到它,现在找不到链接),但它也不起作用。
I have a project structured like this:
├───project
| ├───__init__.py
| ├───main.py
│ ├───collect_data
│ │ └───functions.py
│ └───other_folder
│ └───generate.py
├───tests
| ├───__init__.py
│ └───test_functions.py
├───pyproject.toml
└───poetry.lock
I did poetry install
(which generated the poetry.lock).
I am using vscode in a windows machine with python 3.7.11
, pytest 7.0.1
. and conda environnements.
So now the problem is: if I do a test for functions.py, I import like so : from project.collect_data.functions import my_function
and this works.
But if I try testing an endpoint that is in 'main.py' (from project.main import another_function
) the problem is that in turn main.py is importing some functions but without calling 'project' (like from collect_data.functions import my_function
) so when the test run I have an error with collect_data module not found
.
I've read tons of docs but obviously I'm doing something wrong. The code is usually ran from "project" so i'm not willing to change the way main is importing other functions (and some sub folders are calling others functions from somewhere else as well, the project is actually a lot bigger than the example).
I think the problem hs something to do with the PATH but I'm not really sure how to fix it.
I've tried to put an empty conftest.py
at the root of the project (I saw it somewhere in SO, can't find the link now)but it doesn't work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
应该起作用的一件事是将
project
添加到 $PYTHONPATH 环境变量,即运行export PYTHONPATH=project
。然后你可以使用poetry run pytest
运行 pytest (正如诗歌所暗示的)。或者将pyproject.toml
中的属性设置为One thing that should work is adding
project
to your $PYTHONPATH environment variable, ie runningexport PYTHONPATH=project
. Then you can run pytest withpoetry run pytest
(as suggested by poetry). Or setting the property in yourpyproject.toml
as