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

Python项目示例目录测试失败:如何测试示例文件?

解决示例脚本的测试问题

出现ModuleNotFoundError: No module named 'examples'的核心原因是**examples目录不在Python的模块搜索路径(sys.path)**中,pytest默认不会自动将项目根目录下的examples目录加入搜索路径。完全可以继续用pytest测试,不需要更换工具,以下是几种可行方案:

方法1:在测试脚本中手动添加路径

直接在test_examples.py中把项目根目录加入sys.path,同时优化测试逻辑确保示例代码被执行:

import sys
from pathlib import Path

# 获取项目根目录(myproject/)
project_root = Path(__file__).parent.parent
sys.path.append(str(project_root))

def test_ex1():
    # 执行整个示例脚本,验证是否能正常运行无报错
    exec(open(project_root / "examples/ex1.py").read())

def test_ex2():
    exec(open(project_root / "examples/ex2.py").read())

注意:原测试代码里仅写ex1不会执行脚本的顶层代码,使用exec可以完整运行示例脚本。

方法2:将examples转为可导入包+设置PYTHONPATH

  1. 在examples/目录下创建空的__init__.py,把它变成Python可识别的包
  2. 运行pytest时将项目根目录加入PYTHONPATH:
cd myproject
PYTHONPATH=. pytest

此时test_examples.py里的from examples import ex1就能正常导入,导入时示例的顶层代码会自动执行。

方法3:用pytest插件自动配置路径

安装pytest-pythonpath插件,让pytest自动识别项目根目录:

pip install pytest-pythonpath

在pyproject.toml中添加配置:

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

之后直接运行pytest即可,无需手动设置环境变量。

额外优化:提升示例的可测试性

如果想让测试更有意义(不仅验证运行不报错,还能验证逻辑正确性),建议把示例中的核心逻辑封装成函数:
修改ex1.py:

"""
Example 1
"""
from mypackage import adder

def run_example():
    x = 2.5
    y = 8
    a = adder(x, y)
    print('a is', a)
    return a

if __name__ == "__main__":
    run_example()

测试脚本可以改为:

from examples import ex1

def test_ex1():
    result = ex1.run_example()
    assert result == 10.5  # 验证计算结果是否符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:25:37