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

如何在pytest测试文件中正确导入项目中的kernel模块?

解决pytest无法导入kernel模块的方案

方法1:动态添加项目根目录到Python路径(通用方案)

在test/test_ecommerce.py开头添加以下代码,自动识别并添加项目根目录到sys.path:

import sys
from pathlib import Path

# 从测试文件路径向上两级,定位到项目根目录
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))

# 现在可以正常导入
from kernel.ecommerce import Ecommerce

这种方式不依赖运行命令的工作目录,适配各种场景。

方法2:在项目根目录下运行pytest

直接切换到项目根目录执行测试命令:

cd /full/path/root_dir_project
pytest test/test_ecommerce.py -v

此时Python会自动将当前工作目录(项目根)加入模块搜索路径,from kernel.ecommerce import Ecommerce就能正常导入。

方法3:将项目转为可安装包(适合长期维护的项目)

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

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

安装后,无论在哪个路径运行测试,都能直接使用from kernel.ecommerce import Ecommerce导入模块。


原方法失效原因说明

  • 相对导入from ..kernel.ecommerce import Ecommerce:pytest执行测试文件时会将其作为独立脚本处理,而非包的一部分,因此相对导入会触发“no known parent package”错误。
  • 直接导入from kernel.ecommerce import Ecommerce:若运行pytest的工作目录不是项目根,Python的模块搜索路径(sys.path)中不包含项目根,无法找到kernel模块。
  • 手动路径写法:仅调用os.path.dirname但未将路径添加到sys.path,无法生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 23:02:29