简体   繁体   English

使用pytest时无法在同一目录中导入模块

[英]unable to import module in same directory when using pytest

I am having a problem running pytest in a situation when my app calls another script in the same directory. 在我的应用程序调用同一目录中的另一个脚本时,我遇到运行pytest的问题。 Here is my directory structure: 这是我的目录结构:

├── my_project/
│   ├── application/
│   |   ├──__init__.py
│   |   ├──app.py
│   |   ├──utils.py   
│   ├── application_test/
│   |   ├── __init__.py
│   │   ├── unit_test.py

The code in app.py has the statement: from utils import func1, func2, func3 and this works fine when I run $ python app.py . app.py中的代码具有以下语句: from utils import func1, func2, func3 ,当我运行$ python app.py时这很好$ python app.py However, when I run $ py.test from the my_project directory level, I get the error "ModuleNotFoundError: No module named 'utils'." 但是,当我从my_project目录级别运行$ py.test时,我收到错误“ModuleNotFoundError:No module named'utils'。” The errors comes from this line in unit_test.py : 错误来自unit_test.py这一行:

import application.app

Because that line triggers app.py which then tries to import from utils.py and somehow app.py does not see the utils.py file even though it is in the same directory. 由于该行触发app.py ,然后试图从导入utils.py并以某种方式app.py没有看到utils.py文件,即使它是在同一目录下。

I have tried using $ python -m pytest application_test , as well as having __init__.py in the root and without, but none of these or other answers on stackoverflow seem to work. 我已经尝试过使用$ python -m pytest application_test ,以及在root中使用__init__.py而没有,但stackoverflow上的这些或其他答案似乎都不起作用。

It appears that import statements are relative to the directory you are currently in. The solution to calling another script in the same directory is to use relative imports. 似乎import语句与您当前所在的目录相关。在同一目录中调用另一个脚本的解决方案是使用相对导入。 In this case, from .utils import func1, func2, func3 worked! 在这种情况下, from .utils import func1, func2, func3工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM