golang测试覆盖率检测与阈值告警插件go-test-coverage的使用

Golang测试覆盖率检测与阈值告警插件go-test-coverage的使用

go-test-coverage简介

go-test-coverage是一个工具,用于在测试覆盖率低于指定阈值时报告问题,确保更高的代码质量并防止测试覆盖率随时间下降。

为什么使用go-test-coverage?

以下是主要功能和优势:

  • 快速设置:只需5分钟即可安装和配置
  • 无服务器操作:不需要外部服务器、注册或权限
    • 消除了连接或服务器相关的故障
  • 数据隐私:所有覆盖率检查都在本地完成,不会将敏感信息泄露给第三方
  • 高性能:执行速度极快(例如,在这个仓库上约1秒)
  • 多功能性:可以在本地和CI管道中使用
  • 可定制:广泛的配置选项以适应任何项目的需求
  • 漂亮的徽章:为您的仓库生成漂亮的覆盖率徽章
  • 覆盖率差异:相对于基础分支的代码覆盖率变化的详细比较
  • 开源:免费使用和贡献!

使用方法

您可以通过两种方式使用go-test-coverage

  • 作为开发过程的一部分在本地使用
  • 作为GitHub工作流中的一个步骤

对于Go项目,建议同时使用这两种方式。

本地使用

以下是一个包含check-coverage命令的Makefile示例,该命令在本地运行go-test-coverage

GOBIN ?= $$(go env GOPATH)/bin

.PHONY: install-go-test-coverage
install-go-test-coverage:
	go install github.com/vladopajic/go-test-coverage/v2@latest

.PHONY: check-coverage
check-coverage: install-go-test-coverage
	go test ./... -coverprofile=./cover.out -covermode=atomic -coverpkg=./...
	${GOBIN}/go-test-coverage --config=./.testcoverage.yml

GitHub工作流

以下是将go-test-coverage集成到GitHub Actions工作流中的示例:

name: Go test coverage check
runs-on: ubuntu-latest
steps:
  - uses: actions/checkout@v3
  - uses: actions/setup-go@v3
  
  - name: generate test coverage
    run: go test ./... -coverprofile=./cover.out -covermode=atomic -coverpkg=./...

  - name: check test coverage
    uses: vladopajic/go-test-coverage@v2
    with:
      config: ./.testcoverage.yml

配置

以下是一个.testcoverage.yml配置文件示例:

# (mandatory) 
# Path to coverage profile file (output of `go test -coverprofile` command).
#
# For cases where there are many coverage profiles, such as when running 
# unit tests and integration tests separately, you can combine all those
# profiles into one. In this case, the profile should have a comma-separated list 
# of profile files, e.g., 'cover_unit.out,cover_integration.out'.
profile: cover.out

# Holds coverage thresholds percentages, values should be in range [0-100].
threshold:
  # (optional; default 0) 
  # Minimum coverage percentage required for individual files.
  file: 70

  # (optional; default 0) 
  # Minimum coverage percentage required for each package.
  package: 80

  # (optional; default 0) 
  # Minimum overall project coverage percentage required.
  total: 95

# Holds regexp rules which will override thresholds for matched files or packages 
# using their paths.
#
# First rule from this list that matches file or package is going to apply 
# new threshold to it. If project has multiple rules that match same path, 
# override rules should be listed in order from specific to more general rules.
override:
  # Increase coverage threshold to 100% for `foo` package 
  # (default is 80, as configured above in this example).
  - path: ^pkg/lib/foo$
    threshold: 100

# Holds regexp rules which will exclude matched files or packages 
# from coverage statistics.
exclude:
  # Exclude files or packages matching their paths
  paths:
    - \.pb\.go$    # excludes all protobuf generated files
    - ^pkg/bar     # exclude package `pkg/bar`

# If specified, saves the current test coverage breakdown to this file.
#
# Typically, this breakdown is generated only for main (base) branches and 
# stored as an artifact. Later, this file can be used in feature branches 
# to compare test coverage against the base branch.
breakdown-file-name: ''

diff:
  # Path to the test coverage breakdown file from the base branch.
  #
  # This file is usually generated and stored in the main (base) branch,
  # controled via `breakdown-file-name` property.
  # When set in a feature branch, it allows the tool to compute and report 
  # the coverage difference between the current (feature) branch and the base.
  base-breakdown-file-name: ''

  # Allowed threshold for the test coverage difference (in percentage) 
  # between the feature branch and the base branch.
  #
  # By default, this is disabled (set to nil). Valid values range from 
  # -100.0 to +100.0.
  #
  # Example: 
  #   If set to 0.5, an error will be reported if the feature branch has 
  #   less than 0.5% more coverage than the base.
  #
  #   If set to -0.5, the check allows up to 0.5% less coverage than the base.
  threshold: nil

从覆盖率中排除代码

对于不需要测试的代码块,可以通过在语句体开始行(在{之后)添加注释// coverage-ignore来从覆盖率统计中忽略它。

...
result, err := foo()
if err != nil { // coverage-ignore
	return err
}
...

类似地,当在函数体开始行(在{之后)找到注释时,可以从覆盖率统计中排除整个函数。

func bar() { // coverage-ignore
...
}

生成覆盖率徽章

您可以轻松地为您的仓库生成一个漂亮的覆盖率徽章,并将其嵌入到您的markdown文件中。

可视化覆盖率

Go包含一个内置工具用于可视化覆盖率配置文件,允许您查看代码的哪些部分未被测试覆盖。 以下命令将生成带有可视化覆盖率配置文件的cover.html页面:

go tool cover -html=cover.out -o=cover.html

支持项目

go-test-coverage对所有用户免费可用。如果您的组织从该工具中受益,特别是如果您已经从付费的覆盖率服务过渡过来,请考虑赞助该项目。 您的赞助将有助于持续开发,引入新功能并保持高质量的支持。每笔捐款都直接影响该项目的未来增长和稳定性。

贡献

我们欢迎所有贡献 - 无论是修复拼写错误、添加新功能还是指出问题。随时可以打开拉取请求或问题来贡献!

快乐编码 🌞


更多关于golang测试覆盖率检测与阈值告警插件go-test-coverage的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang测试覆盖率检测与阈值告警插件go-test-coverage的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Go测试覆盖率检测与阈值告警插件go-test-coverage使用指南

什么是go-test-coverage

go-test-coverage是一个用于检测Go项目测试覆盖率并设置阈值告警的工具。它可以帮助开发团队确保代码测试覆盖率维持在可接受的水平,当覆盖率低于设定阈值时会发出警告或失败。

安装

go install github.com/vladopajic/go-test-coverage@latest

基本使用

1. 查看当前覆盖率

go-test-coverage

这会运行go test -cover并显示覆盖率百分比。

2. 设置覆盖率阈值

go-test-coverage --min 80

如果覆盖率低于80%,命令将返回非零退出码。

3. 在CI/CD中使用

在GitHub Actions中示例:

name: Test with coverage check
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Set up Go
      uses: actions/setup-go@v2
      with:
        go-version: '1.21'
    - name: Install go-test-coverage
      run: go install github.com/vladopajic/go-test-coverage@latest
    - name: Run tests with coverage check
      run: go-test-coverage --min 80

高级功能

1. 排除特定文件

go-test-coverage --min 80 --exclude-file "**/mock_*.go"

2. 生成HTML覆盖率报告

go-test-coverage --min 80 --profile cover.out
go tool cover -html=cover.out -o coverage.html

3. 使用配置文件

创建.testcoverage.yml文件:

min: 80
exclude:
  - "**/mock_*.go"
  - "**/testdata/**"
  - "**/vendor/**"

然后运行:

go-test-coverage --config .testcoverage.yml

实际项目集成示例

// main.go
package main

import "fmt"

func Add(a, b int) int {
    return a + b
}

func Subtract(a, b int) int {
    return a - b
}

func main() {
    fmt.Println("Calculator app")
}
// main_test.go
package main

import "testing"

func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Errorf("Expected 5, got %d", result)
    }
}

func TestSubtract(t *testing.T) {
    result := Subtract(5, 3)
    if result != 2 {
        t.Errorf("Expected 2, got %d", result)
    }
}

运行测试并检查覆盖率:

go-test-coverage --min 100

如果覆盖率不足100%,工具会报错。

最佳实践

  1. 在CI/CD流水线中设置合理的覆盖率阈值(如80%)
  2. 对新代码设置更高的阈值(如90%)
  3. 排除生成的代码和第三方代码
  4. 定期审查覆盖率报告
  5. 将覆盖率检查作为代码审查的一部分

替代方案

  • go test -cover + 自定义脚本
  • gocov + gocov-html
  • go-acc + goveralls
  • SonarQube等专业工具

go-test-coverage的优势在于简单易用,特别适合中小型Go项目快速集成覆盖率检查。

回到顶部