背景
持续测试作为持续集成的一部分,对代码质量起到了把关作用。而测试覆盖率作为衡量测试代码质量的重要指标,在大型项目发布、维护过程中是必不可少的。
对于使用Git进行版本管理的项目,通过引入Codecov可以得到多个维度的测试统计报表,并加以自动化代码质量检查。
思路
使用Codecov的前提仅是拥有测试代码,但配置自动发布管道可让Codecov的集成更为方便。因此本篇博文以GitHub Actions为例,演示一个托管在GitHub上的项目引入Codecov的简单方式。
编码
- 假设仓库由一个JavaScript项目构成,并有对应的Jest测试代码,则需要创建的构建管道如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| //.github/workflows/test.yml name: Test
on: [push, pull_request]
jobs: test-js: runs-on: ubuntu-latest name: Test js code defaults: run: working-directory: ./js steps: - uses: actions/checkout@v1 - uses: actions/setup-node@v3.1.1 - name: Install dependencies run: npm ci - name: Run tests run: npm run test - name: Upload coverage reports to Codecov with GitHub Action uses: codecov/codecov-action@v3
|
该管道中的GitHub Action codecov/codecov-action
负责将Jest测试套件输出的测试统计结果转化成Codecov平台支持的XML报表格式,并上传至Codecov服务端。
若需要对Pull Request进行代码覆盖率检查,则需要在根目录创建的Codecov配置文件如下所示:
1 2 3 4 5 6 7 8 9 10 11
| // Codecov.yml coverage: status: project: default: target: 100% threshold: 10% patch: default: target: 100% threshold: 10%
|
若仓库有另一个.NET项目,且需要对两个项目分别配置不同的测试覆盖率检查,则构建管道及Codecov配置文件的改动如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| //.github/workflows/test.yml name: Test
on: [push, pull_request]
jobs: test-js: runs-on: ubuntu-latest name: Test js code defaults: run: working-directory: ./js steps: - uses: actions/checkout@v1 - uses: actions/setup-node@v3.1.1 - name: Install dependencies run: npm ci - name: Run tests run: npm run test - name: Upload coverage reports to Codecov with GitHub Action uses: codecov/codecov-action@v3 test-dotnet: runs-on: ubuntu-latest name: Test dotnet divide function defaults: run: working-directory: ./dotnet/Math.Test steps: - uses: actions/checkout@v1 - uses: actions/setup-dotnet@v1.9.0 with: dotnet-version: '6.0.x' - name: Install dependencies run: dotnet restore - name: Build run: dotnet build --no-restore - name: Test run: dotnet test --no-build --no-restore --collect:"XPlat Code Coverage" - name: Upload coverage reports to Codecov with GitHub Action uses: codecov/codecov-action@v3
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| // Codecov.yml coverage: status: project: default: false js: target: 100% threshold: 10% paths: - js/ dotnet: target: auto threshold: 10% paths: - dotnet/ patch: default: false
|
- 若需要给项目README添加测试覆盖率徽章,可在Codecov控制台中获取Markdown链接:
- 除了使用不同的Status配置,还可以使用Codecov的Flag特性来更定制化地生成独立的测试统计报表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| // Codecov.yml coverage: status: project: off patch: off
flag_management: individual_flags: - name: js paths: - js/ statuses: - type: project target: 100% threshold: 10% - name: dotnet paths: - dotnet/Math statuses: - type: project target: auto threshold: 10%
|
- 更多配置项及特性,可在Codecov官方文档中了解