首页 > 解决方案 > 使用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'

我试图用谷歌搜索我的问题,但没有发现任何类似的问题,即无法从测试文件中加载子模块。知道为什么会出现这种行为以及如何解决吗?

标签: pythonimportmodulepackagepytest

解决方案


推荐阅读