Search code examples
gocode-coveragefunctional-testing

golang generate code coverage of functional test


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.


Solution

  • Based on this post here's what I did:

    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)"