COVERAGE_GUIDE.md 6.3 KB

测试覆盖率工具使用指南

快速开始

1. 安装 coverage

pip install coverage

2. 运行覆盖率测试

最简单的方式:

# 运行测试并生成所有报告
python run_coverage.py

# 运行并自动在浏览器中打开 HTML 报告
python run_coverage.py --open

手动使用 coverage 命令

基本命令

# 1. 运行测试并收集覆盖率数据
python -m coverage run -m unittest discover -s tests -p "test_*.py"

# 2. 显示控制台报告
python -m coverage report

# 3. 生成 HTML 报告
python -m coverage html

# 4. 生成 XML 报告(用于 CI/CD)
python -m coverage xml

高级命令

# 显示缺失的行号
python -m coverage report -m

# 只显示特定文件的覆盖率
python -m coverage report services/gateway_session_store.py

# 设置覆盖率阈值(低于 80% 会失败)
python -m coverage report --fail-under=80

# 显示分支覆盖率详情
python -m coverage report --show-missing

查看报告

1. 控制台报告

运行 python -m coverage report 后直接在终端显示:

Name                                Stmts   Miss Branch BrPart   Cover
----------------------------------------------------------------------
services/token_store.py               158     63     50     10  52.40%
app.py                                129     25     48     16  74.58%
tools/bind_auth_code.py                18      3      6      3  75.00%
mcp_protocol.py                       147     20     66     18  80.28%
...
----------------------------------------------------------------------
TOTAL                                 909    132    294     63  80.80%

指标说明

  • Stmts: 可执行语句总数
  • Miss: 未执行的语句数
  • Branch: 分支总数(if/else)
  • BrPart: 部分覆盖的分支数
  • Cover: 覆盖率百分比

2. HTML 报告(推荐)

生成后打开 htmlcov/index.html

# 自动打开
python run_coverage.py --open

# 或手动打开
start htmlcov/index.html

HTML 报告特性

  • 📊 可视化的覆盖率统计
  • 📝 逐行查看哪些代码被执行
  • 🎨 颜色编码(绿色=覆盖,红色=未覆盖)
  • 🔍 点击文件查看详细信息
  • 📈 分支覆盖率可视化

3. XML 报告

用于 CI/CD 集成(如 GitHub Actions、Jenkins):

python -m coverage xml
# 生成 coverage.xml

配置文件

项目使用 .coveragerc 配置覆盖率工具:

[run]
source = .
omit = tests/*, */__pycache__/*, run_coverage.py
branch = True

[report]
precision = 2
exclude_lines = pragma: no cover

[html]
directory = htmlcov

关键配置

  • source: 要测量的源代码目录
  • omit: 排除的文件/目录
  • branch: 启用分支覆盖率
  • exclude_lines: 排除带有特定注释的行

提高覆盖率的技巧

1. 识别未覆盖的代码

查看 HTML 报告中的红色行:

python run_coverage.py --open

2. 编写针对性测试

对于未覆盖的代码,编写测试:

def test_error_handling(self):
    """测试错误处理分支"""
    with self.assertRaises(ValueError):
        function_that_raises_error()

3. 测试边界条件

def test_empty_input(self):
    result = process([])
    self.assertEqual(result, [])

def test_none_input(self):
    with self.assertRaises(ValueError):
        process(None)

4. 排除不可测试的代码

使用 # pragma: no cover 注释:

if __name__ == '__main__':  # pragma: no cover
    main()

CI/CD 集成

GitHub Actions

name: Tests with Coverage

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Set up Python
        uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      
      - name: Install dependencies
        run: |
          pip install -r requirements.txt
          pip install coverage
      
      - name: Run tests with coverage
        run: |
          python -m coverage run -m unittest discover -s tests -p "test_*.py"
          python -m coverage report --fail-under=80
          python -m coverage xml
      
      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v3
        with:
          file: ./coverage.xml

GitLab CI

test:
  script:
    - pip install coverage
    - python -m coverage run -m unittest discover -s tests -p "test_*.py"
    - python -m coverage report --fail-under=80
    - python -m coverage xml
  coverage: '/TOTAL.*\s+(\d+%)$/'
  artifacts:
    reports:
      coverage_report:
        coverage_format: cobertura
        path: coverage.xml

常见问题

Q: 为什么覆盖率突然下降?

A: 可能原因:

  1. 新增了未测试的代码
  2. 删除了部分测试
  3. 配置文件更改导致测量范围变化

解决:运行 python -m coverage report -m 查看缺失的行号。

Q: 如何只测试某个模块的覆盖率?

A: 使用 --source 参数:

python -m coverage run --source=services/gateway_session_store.py -m unittest tests.test_gateway_session_store_unit
python -m coverage report

Q: 覆盖率 100% 就够了吗?

A: 不一定。覆盖率只表示代码被执行了,不表示逻辑正确。还需要:

  • 测试边界条件
  • 测试错误处理
  • 测试并发场景
  • 集成测试和端到端测试

Q: 目标覆盖率应该设多少?

A: 建议:

  • 核心业务逻辑: 90%+
  • 工具类/辅助函数: 80%+
  • 整体项目: 70-80%
  • 新增代码: 要求 90%+

当前项目覆盖率

截至 2026-07-08:

类别 覆盖率 状态
新增核心模块 95-100% ✅ 优秀
整体项目 80.80% ✅ 良好
目标 80%+ ✅ 已达标

8 个新增核心模块达到 100% 覆盖率

  • constants.py
  • services/api_client.py
  • services/gateway_session_store.py
  • services/scoped_api_client.py
  • services/scoped_auth_client.py
  • tools/query_track.py
  • utils/rate_limiter.py
  • utils/security.py

参考资源