使用 Golang 生成功能测试的代码覆盖率。

3
我有一个go webservices(REST Api),我们已经进行了单元测试,并且go cover的结果很好。现在我们编写了一个用Python编写的测试套件,它会启动服务器实例,运行测试,停止服务器。我想知道是否有一些工具可以让我使用特定标志运行我的服务器二进制文件,以便最后打印由我的“黑盒”测试执行的覆盖率?谢谢。
3个回答

4

根据这篇文章,我做了以下事情:

  1. created a main_test.go with this content:

    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. as it was a web services (and hence in an infinite loop), I needed a way to gracefully exit on SIGTERM (without it being considered a failure), so I used the package go get gopkg.in/tylerb/graceful.v1 and replaced (I use go-restful) in main.go the line

        -       log.Fatal(http.ListenAndServe(":"+port, nil))
        +       graceful.Run(":"+port, 10*time.Second, nil)
    
  3. then I would run the test like this

    • go test -c -covermode=count -coverpkg ./... -o foo.test
    • ./foo.test -test.coverprofile coverage.cov & echo $! > /tmp/test.pid
    • run my test suite
    • kill "$(cat /tmp/test.pid)"

0

你可能不想这样做。使用覆盖率、竞争检测等工具运行代码会增加二进制文件的大小并且使其运行速度变慢。在我的电脑上,同时运行竞争检测器和代码覆盖率测试要慢25倍。

测试时只需简单地使用go test -cover -race命令,部署时使用go build命令。这样可以得到你想要的输出,虽然可能不完全符合你的期望方式。


1
事实上它很慢/占用空间大并非问题所在。这只是自动化功能测试运行的时间,集成测试/端到端测试则是在正常构建时运行。go test 只运行 Go 语言中的测试而不是二进制本身,对吧? - allan.simon

0

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接