golang 生成功能测试的代码覆盖率

golang generate code coverage of functional test

我有一个 go 网络服务(REST Api),我们对其进行了单元测试,go cover 工作正常。

现在我们有一个用 python 编写的测试套件启动服务器实例,运行 测试,停止服务器。

我想知道是否有一些工具允许我 运行 我的带有特定标志的服务器二进制文件,以便最后它打印我的 [=18= 执行的测试的覆盖范围] 测试 ?

谢谢。

您可能不想这样做。 运行 具有覆盖率、竞争检测的代码 and/or 其他工具会增加二进制文件的大小并使其速度变慢。 运行 在我的计算机上,竞争检测器和代码覆盖率都慢了 25 倍。

只需使用 go test -cover -race 进行测试,并在部署时使用 go build。这将为您提供所需的输出,尽管并非完全按照您想要的方式。

基于 this post 这是我所做的:

  1. 创建了一个 main_test.go 内容如下:

    package main
    
    // code based on technique explained here:
    // https://www.elastic.co/blog/code-coverage-for-your-golang-system-tests
    // you can look there if you want to see how not to execute this test
    // when running unit test etc.
    
    // This file is mandatory as otherwise the packetbeat.test binary is not generated correctly.
    
    import (
        "testing"
    )
    
    // Test started when the test binary is started. Only calls main.
    func TestSystem(t *testing.T) {
        main()
    }
    
  2. 因为它是一个网络服务(因此处于无限循环中),我需要一种在 SIGTERM 上正常退出的方法(不会被视为失败),所以我使用了包 go get gopkg.in/tylerb/graceful.v1 并在 main.go 行

    中替换(我使用 go-restful
        -       log.Fatal(http.ListenAndServe(":"+port, nil))
        +       graceful.Run(":"+port, 10*time.Second, nil)
    
  3. 那我就运行这样的测试

    • go test -c -covermode=count -coverpkg ./... -o foo.test
    • ./foo.test -test.coverprofile coverage.cov & echo $! > /tmp/test.pid
    • 运行 我的测试套件
    • kill "$(cat /tmp/test.pid)"

go test -c -cover 解决方案有一些缺点,例如在生成代码覆盖率配置文件时必须停止被测服务。它还会向覆盖的二进制文件中注入一些不必要的标志,例如“-test.v”,这可能会破坏服务的原始启动方式。

我们使用goc代替,它帮助我们在运行时轻松收集系统测试(API测试或e2e测试)的代码覆盖率,我认为它更优雅。