我有一个 go webservices(一个 REST Api),我们对其进行了单元测试,并且 go cover 工作正常。
现在我们有一个用 python 编写的测试套件,它启动服务器实例、运行测试、停止服务器。
我想知道是否有一些工具允许我使用特定标志运行我的服务器二进制文件,以便在最后打印由我的“黑盒”测试执行的测试的覆盖范围?
谢谢。
最佳答案
基于 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() }
因为它是一个网络服务(因此处于无限循环中),我需要一种在 SIGTERM 上正常退出的方法(不会被视为失败),所以我使用了包
go get gopkg .in/tylerb/graceful.v1
并替换(我使用go-restful
)在 main.go 行- 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)"
关于golang 生成功能测试的代码覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34837542/