You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pytest从相邻目录导入模块时的导入失败问题排查

命令行运行pytest异常但PyCharm正常的问题解析

问题背景

项目目录结构

/root
|- __init__.py
|
|- /src 
|  |
|  |- __init__.py
|  |- /x
|     |
|     |- __init__.py
|     |- xy.py
|
|- /tests
|  |- __init__.py
|  |- /test_x
|     |
|     |- __init__.py
|     |- test_xy.py

测试文件代码(tests/test_x/test_xy.py)

# tests/test_x/test_xy.py 

from src.x.xy import XY

class TestXY:
    # 测试逻辑省略

遇到的问题

  • 在/root目录执行pytest tests/*/*,报错找不到src模块;改为相对导入from ...src.x.xy import XY,又提示导入层级超出范围。
  • 执行python -m pytest tests/*/*时,出现__pycache__相关错误:
    ERROR: not found: /root/tests/__pycache__/conftest.cpython-310-pytest-7.1.2.pyc (no name '/root/tests/__pycache__/conftest.cpython-310-pytest-7.1.2.pyc' in any of [])
    
  • 但PyCharm中点击测试脚本的运行箭头,测试能正常执行。

原因分析与解决方法

1. pytest找不到src模块的核心原因

直接运行pytest tests/*/*时,Python的模块搜索路径(sys.path)只会加入测试文件所在的tests/test_x目录,而非项目根目录/root,所以src不在搜索范围内,自然无法导入。

PyCharm默认会把项目根目录(/root)添加到sys.path中,因此能正常识别src模块。

解决办法:

  • 临时设置PYTHONPATH
    在/root目录下执行:
PYTHONPATH=/root pytest tests/test_x/test_xy.py

通过环境变量把项目根目录加入模块搜索路径,即可正常导入src。

  • 正确使用python -m pytest
    之前的错误是因为tests/*/*通配符匹配到了tests/__pycache__下的缓存文件,pytest尝试加载这些文件导致报错。应直接指定测试文件或目录,避免匹配缓存:
# 运行单个测试文件
python -m pytest tests/test_x/test_xy.py
# 或运行整个测试目录
python -m pytest tests/

使用python -m pytest时,Python会自动把当前工作目录(/root)加入sys.path,无需额外配置就能找到src模块。

  • 安装为可编辑包
    在/root目录下创建pyproject.toml(或setup.py),内容示例:
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "your-project-name"
version = "0.1.0"
packages = ["src"]

然后执行:

pip install -e .

这样src模块会被安装到Python的site-packages中,无论在哪里运行测试都能直接导入。

2. 相对导入报错的原因

相对导入(如from ...src.x.xy import XY)只能在同一个包内部使用,tests和src是同级独立目录,不属于同一个包树,因此无法通过相对导入跨目录引用模块。

内容的提问来源于stack exchange,提问作者Jinx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 07:45:24