python - 使用pytest时无法导入子模块
问题描述
我有一个具有以下布局的项目:
/src
/mypckg
__init__.py
calibration.py
_const.py
/tests
test_calibration.py
conftest.py
在我的测试文件中,我正在导入我的calibration
模块:
from mypkg import calibration
同时,我的calibration
模块导入了我的_const
模块,其中包含我的所有常量:
import _const
我的__init__.py
文件包含以下导入:
## __init__ file
from . import calibration
from . import _const
现在,当我pytest
从测试文件夹运行时,它找到了我的calibration
模块,但它给了我这个错误
...\mypckg\calibration.py:7: in <module>
import _const
E ModuleNotFoundError: No module named '_const'
我的calibration
模块显然找不到该_const
模块,但如果我python calibration.py
从我的包目录运行,它运行完美。问题是当我尝试从calibration
我的测试文件中的模块运行一个函数时。
如果我通过以下方式将_const
模块导入到我 的模块中,我的测试将完美运行:calibration
from mypckg import _const
# or from . import _const
但是如果我以这种方式导入它,当我运行它时python calibration.py
它会给我这个错误:
Traceback (most recent call last):
File "calibration.py", line 8, in <module>
from . import _const
ImportError: cannot import name '_const'
我试图用谷歌搜索我的问题,但没有发现任何类似的问题,即无法从测试文件中加载子模块。知道为什么会出现这种行为以及如何解决吗?
解决方案
推荐阅读
- firebase-cloud-messaging - Angular 7 无法在前台接收 firebase 通知
- php - 在 PHP 中使用会话变量编写 PHP 代码
- c - 为什么输出末尾有随机字符?
- laravel - laravel 模型控制器检索数据
- java - 尝试将布局设置为 BoxLayout
- c++ - 如何解决“if”块中的“未声明的标识符错误”?
- android - 如何在 ViewModel 中获取字符串值,例如 R.string.value
- reactjs - 无法从“C:\repos\ondemandProject\ondemnd-web”中找到模块“@babel/preset-es2015”
- swift - 如何设置当前线程的语言环境?
- python - 在没有应用的情况下计算熊猫中多列的条纹