我有一个go webservices(一个REST Api),我们有单元测试,并且封面工作正常。
现在我们有一个用python编写的测试套件,用于启动服务器实例,运行测试,停止服务器。
我想知道是否有一些工具允许我使用特定标志运行我的服务器二进制文件,这样最后它会打印我的" blackbox&#执行的测试的覆盖范围34;测试?
感谢。
答案 0 :(得分:3)
根据this post基于我所做的事情:
使用以下内容创建了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()
}
因为它是一个Web服务(因此是一个无限循环),我需要一种方法来优雅地退出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)
然后我会像这样运行测试
go test -c -covermode=count -coverpkg ./... -o foo.test
./foo.test -test.coverprofile coverage.cov & echo $! > /tmp/test.pid
kill "$(cat /tmp/test.pid)"
答案 1 :(得分:0)
你可能不想这样做。使用覆盖,竞争检测和/或其他工具运行代码会增加二进制文件的大小并使其更慢。在我的计算机上运行竞争检测器和代码覆盖率的速度要慢25倍。
只需使用go test -cover -race
进行测试,并在部署时使用go build
。这将为您提供所需的输出,尽管不是您想要的输出。
答案 2 :(得分:0)
go test -c -cover
解决方案具有一些缺点,例如在生成代码覆盖率配置文件时必须停止被测服务。并且还会向覆盖的二进制文件中插入一些不必要的标志,例如“ -test.v”,这可能会破坏服务的原始启动方式。
我们改用goc,它可以帮助我们在运行时轻松地收集系统测试(API测试或e2e测试)的代码覆盖率,我认为它更优雅。