该pytest.ini配置文件为“归藏层”项目定义了完整的测试框架行为,其核心配置与功能如下:
核心配置解析
| 配置类别 | 配置项 | 说明与作用 |
|---|---|---|
| 测试发现 | python_files,python_classes,python_functions,testpaths | 定义了测试文件、类、函数的命名模式以及搜索目录,确保pytest能正确发现并收集所有测试用例 。 |
| 自定义标记 | markers | 声明了项目专用的测试分类标记(如unit,integration,slow,traceback等),用于对测试用例进行逻辑分组和选择性执行 。 |
| 默认运行选项 | addopts | 设置了pytest的默认命令行参数。每次执行pytest时,这些选项会自动生效,无需在命令行重复输入 。 |
| 超时控制 | timeout,timeout_method | 为所有测试用例设置全局超时限制(300秒),防止个别用例长时间挂起 。 |
| 日志配置 | log_cli,log_cli_level,log_cli_format,log_cli_date_format | 配置测试运行时的实时日志输出格式和级别,便于调试 。 |
关键配置详解
1. 默认运行选项 (addopts)
此部分定义了项目的质量门禁和默认工作流:
addopts = -v # 详细输出 --strict-markers # 严格检查标记,防止未声明的标记被使用 --tb=short # 使用简短的错误回溯信息 --maxfail=2 # 遇到2个失败后停止测试 m "not slow" # 默认跳过标记为 `slow` 的测试用例 --cov-report=html:./coverage/html # 生成HTML覆盖率报告 --cov-report=term-missing # 在终端输出缺失覆盖的行 --cov=../guicang/core # 指定计算覆盖率的源码模块 --cov=../guicang/l2_explanation --cov-fail-under=75 # 设置覆盖率门槛,低于75%则测试失败m "not slow":实现了快速反馈循环。开发者日常运行pytest时,会自动跳过耗时较长的测试,提升效率 。--cov-fail-under=75:设定了覆盖率质量红线。如果整体行覆盖率低于75%,测试套件将返回失败状态,用于CI/CD流程中阻断低质量代码的合入 。--strict-markers:强制要求所有在测试中使用的@pytest.mark.xxx装饰器标记都必须在markers部分声明,避免了拼写错误和未定义的标记 。
2. 自定义标记 (markers)
标记系统是组织测试的核心,支持灵活的执行策略:
# 示例:在测试用例中使用标记 import pytest @pytest.mark.unit @pytest.mark.fast def test_addition(): assert 1 + 1 == 2 @pytest.mark.integration @pytest.mark.slow def test_database_connection(): # ... 耗时操作 pass @pytest.mark.traceback def test_traceback_algorithm(): # ... 任务A相关测试 pass通过命令行可以按需执行特定类型的测试:
# 仅运行单元测试 pytest -m unit # 运行除慢速测试外的所有测试(与默认配置一致) pytest -m "not slow" # 运行任务A相关的所有测试 pytest -m traceback # 同时满足多个标记的测试pytest -m "unit and fast"3. 与run_coverage.sh脚本的协同
该pytest.ini文件与之前提供的run_coverage.sh脚本共同构成了项目的测试基础设施:
pytest.ini定义了静态的、项目级的默认配置,是测试框架行为的基石 。run_coverage.sh是一个动态的、封装好的执行入口。它基于pytest.ini的配置,并通过脚本参数(如--full,--ci)在运行时覆盖或扩展某些默认行为(例如,在--full模式下覆盖-m "not slow"的过滤条件)。
配置验证与覆盖规则
- 配置文件位置:
pytest.ini应放置在项目根目录或tests/目录下,pytest会自动识别并加载 。 - 优先级:命令行参数具有最高优先级,会覆盖
pytest.ini中addopts的相同设置。例如,执行pytest -m slow会覆盖配置中的-m "not slow"。 - 标记严格性:由于配置了
--strict-markers,任何使用未在markers段落中声明的标记的测试,在运行时都会报错,这有助于维护标记列表的整洁和一致 。
参考来源
- pytest运行时参数说明,pytest详解,pytest.ini详解
- pytest运行时参数说明,pytest详解,pytest.ini详解
- pytest运行时参数说明,pytest详解,pytest.ini详解
- pytest运行时参数说明,pytest详解,pytest.ini详解
- pytest运行时参数说明,pytest详解,pytest.ini详解