golang生成功能测试的代码覆盖率
I have a go webservices (a REST Api) for which we have unit test, and for which go cover works fine.
Now we have a test suite written in python that launch a instance of the server, run the test , stop the server.
I would like to know if there's some tools that would permit me to run my server binary with a specific flag , so that at the end it prints coverage of the tests executed by my "blackbox" testing ?
Thanks.
我有一个go网络服务(REST Api),我们对其进行了单元测试,并且go cover可以正常工作 p>
现在,我们有了一个用python编写的测试套件,它可以启动服务器实例,运行测试,然后停止服务器。 p>
我会 想知道是否有一些工具可以让我使用特定的标志运行服务器二进制文件,以便最后显示“黑盒”测试执行的测试的覆盖范围? p>
谢谢。 p> div>
Based on this post here's what I did:
-
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() }
-
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 usego-restful
) in main.go the line- log.Fatal(http.ListenAndServe(":"+port, nil)) + graceful.Run(":"+port, 10*time.Second, nil)
-
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)"
You probably don't want to do that. Running code with coverage, race detection and/or other tools increases the binary size and makes it much slower. Running both the race detector and code coverage is 25 times slower on my computer.
Simply use go test -cover -race
for testing, and go build
when deploying. This will give you the output you want, albeit not in exactly the way you wanted it.