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

Python项目:无需修改sys.path访问pytest测试功能的优雅方案

优雅实现Python项目中src模块的无缝导入

项目结构

project_directory/
├── src/
│   └── my_functions.py   # 待测试的函数
├── tests/
│   └── test_my_functions.py   # pytest测试文件
└── other_files_and_folders/   # 项目其他文件/目录

你目前通过修改sys.path的方式虽能实现导入,但确实不够优雅,下面是几种遵循最佳实践的替代方案:

方案1:将src目录配置为可安装的Python包

这是最推荐的标准做法,既解决测试导入问题,也能适配项目分发、部署需求。

  1. 在项目根目录创建pyproject.toml文件,配置内容如下:
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "my_project"
version = "0.1.0"
packages = ["src"]
  1. 以可编辑模式安装包:
pip install -e .

完成后,测试文件里可直接导入:

from src.my_functions import your_function

方案2:通过pytest配置自动添加路径

若暂时无需将项目做成可分发包,可通过pytest配置文件自动把src目录加入Python路径,无需修改测试代码。

在项目根目录创建pytest.ini文件:

[pytest]
pythonpath = src

或者在pyproject.toml中添加pytest配置:

[tool.pytest.ini_options]
pythonpath = ["src"]

运行pytest时,src目录会被自动加入路径,测试文件可直接写:

from my_functions import your_function

方案3:使用相对导入(需调整包结构)

给src目录添加__init__.py文件(使其成为Python包),然后在测试文件中用相对导入:

from ..src.my_functions import your_function

注意:这种方式必须通过pytest运行测试,不能直接执行python tests/test_my_functions.py,否则会触发ValueError: attempted relative import beyond top-level package错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 07:18:19