mardi 9 octobre 2018

How to create gin.Context from *http.Request and *httptest.ResponseRecorder?

I would like to create a test helper for gin similar to testify's HTTPBodyContain.

I am having a hard time creating gin.Context from *http.Request and *httptest.ResponseRecorder. I've already written something like this:

func HTTPBodyContains(t *testing.T, handler gin.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{}) bool {
    body := HTTPBody(handler, method, url, values)

    contains := strings.Contains(body, fmt.Sprint(str))
    if !contains {
        assert.Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body))
    }

    return contains
}

func HTTPBody(handler gin.HandlerFunc, method, url string, values url.Values) string {
    w := httptest.NewRecorder()
    req, err := http.NewRequest(method, url+"?"+values.Encode(), nil)
    if err != nil {
        return ""
    }
    handler(&gin.Context{
        Request: req,
        Writer:  gin.ResponseWriter(w),
    })
    return w.Body.String()
}

but this wouldn't work

Writer:  gin.ResponseWriter(w)

Aucun commentaire:

Enregistrer un commentaire