mercredi 26 février 2020

Go's httptest.NewRecorder() isnt registering hits in coverage report

Our goal is to have good integration tests on our api, so we use gin's router capabilities along with httptest.NewRecorder() to setup a dummy in process endpoint we can simulate http calls to. This ensures we test the actual path bindings, middleware, etc.

Our issue is in go's built in go coverage reports from say: go test -coverprofile=coverage.txt ./... It does not register hits against the apis. Full script we using to get coverage and upload to codecov.io is similar to this: https://github.com/codecov/example-go We loop per go package and aggregate a coverage.txt.

Has anyone experienced this? How do we fix? Is the indirect nature of invoking the code via simulated http requests expected to cause this gap?

How to reproduce:

http := gin.New()
api := http.Group("/api")
api.GET("/", apis.WelcomeHandler)

etc...

func PerformRequest(r http.Handler, method, path string, headers map[string]string, jsonPost string) *httptest.ResponseRecorder {
var payload io.Reader
if len(jsonPost) > 0 {
payload = bytes.NewBufferString(jsonPost)
}
req, err := http.NewRequest(method, path, payload)

if err != nil {
    fmt.Printf("Problem sending http request, %e", err)
    return nil
}
if headers != nil && len(headers) > 0 {
    for k, v := range headers {
        req.Header.Add(k, v)
    }
}
if len(jsonPost) > 0 {
    req.Header.Set("Content-Type", "application/json") // This makes it work
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w
}

Environment MacOS X go version go1.13.4 darwin/amd64

Aucun commentaire:

Enregistrer un commentaire