I tried run a sytemTest in this article: https://www.elastic.co/blog/code-coverage-for-your-golang-system-tests
so follow the tips first I create a system test file named main_test.go like this:
func TestSystem(t *testing.T) {
t.Logf("systemtest mod=%v", *SystemTest)
if *SystemTest {
t.Log("runing system test....")
main()
}
}
when this unit test is executed, whole main function will be executed
then I build a test birnary :
go test -c -covermode=count -coverpkg ./... -o main.test
and execute the test birnary file in my test environment
./main.test -systemTest -test.coverprofile ./coverage.cov
because the program will listen and waiting for client's request, so it will not exit unless I exit manunal, which means the coverprofile won't be genarated
so I start a timer to stop the program after 15 seconds... however when program exits , the coverprofile still not genarated
if test not call main, the coverprofile can be genarated normally
See the main function
var mkrtExitWait sync.WaitGroup
var mkrtExitCode int
var mkrtRunning bool = false
func MKrtRun() int {
mkrtExitWait.Add(1)
mkrtRunning = true
mkrtExitWait.Wait()
return mkrtExitCode
}
func MKrtExit(code int) {
if !mkrtRunning {
os.Exit(code)
} else {
mkrtRunning = false
mkrtExitCode = code
mkrtExitWait.Done()
}
}
func main() {
// listen and serve code
......
if *SystemTest { // a command flag
go func(){
time.Sleep(time.Second * 10)
MKrtExit(0)
}()
}
MKrtRun()
}
I tried some ways to genrate coverage file as followed, but it's not working:
send a client request to tell test server to execute os.Exit(0) when program is running
send a client request to tell test server to execute panic() when program is running
kill the process to force exit the program
What's the problem?
How can I generate coverage file?