从项目的根部执行pytest时,modulenotfounderror:无模块名称' main'

发布于 2025-01-31 18:18:21 字数 562 浏览 3 评论 0原文

问题:当我从cmd py -m pytest py_src/中从项目的根中执行pytest。我会收到以下错误:modulenotfoundError:no模块名为“ main”。但是,如果我将cd cd到py_src/中,然后运行py -m pytest 一切都相应。我对Pytest仍然相对较新,将不胜感激的是将我指向正确的方向。

目标:我要实现的目标是从项目的根部创建一个.yml文件,该文件将在其他目录中运行Pytest和其他测试。

当前状态:这是我的文件结构的样子。

root
|
|---py_src
|    |
|    |---main.py
|    |
|    |---tests
|    |    |
|    |    |---test_x.py

在我的tests.py文件中,我有

from main import app

PROBLEM: When I execute pytest from the root of the project in the cmd py -m pytest py_src/. I get the following error: ModuleNotFoundError: No module named 'main'. However if I cd into py_src/ and then run py -m pytest everything behaves accordingly. I am still relatively new with pytest, anything would be appreciated to direct me in the right direction.

GOAL: What I am trying to achieve is to create a .yml file from the root of the project that will run the pytest and other tests in other directories.

CURRENT STATE: here is what my file structure looks like.

root
|
|---py_src
|    |
|    |---main.py
|    |
|    |---tests
|    |    |
|    |    |---test_x.py

in my tests.py file, I have

from main import app

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沉鱼一梦 2025-02-07 18:18:21

通过在每个目录中添加名称__ INIT __。py来制作目录模块。

root
|
|---py_src
|    |
|    |---__init__.py
|    |---main.py
|    |
|    |---tests
|    |    |
|    |    |---__init__.py
|    |    |---test_x.py

现在,将您在test_x.py中更改您的导入到从模块中导入,例如

从py_src.main导入app

这将允许您从root或source目录运行pytest

make the directories modules by adding a blank file by the name __init__.py in each directory.

root
|
|---py_src
|    |
|    |---__init__.py
|    |---main.py
|    |
|    |---tests
|    |    |
|    |    |---__init__.py
|    |    |---test_x.py

Now change your import in test_x.py to import from module like

from py_src.main import app

This will allow you to run the pytest from either root or from the source directory

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文