diff --git a/pkg/testttp/http.go b/pkg/testttp/http.go index 0164c933bc..05e4e408b6 100644 --- a/pkg/testttp/http.go +++ b/pkg/testttp/http.go @@ -7,6 +7,7 @@ import ( "io" "net/http" "net/http/httptest" + "net/url" "testing" ) @@ -79,6 +80,14 @@ func (r *Req) Do(handler http.Handler) *Resp { } } +func (r *Req) SetFormValue(k, v string) *Req { + if r.req.Form == nil { + r.req.Form = make(url.Values) + } + r.req.Form.Set(k, v) + return r +} + // Headers allows the user to set headers on the http request. func (r *Req) Headers(k, v string, rest ...string) *Req { headers := append(rest, k, v) diff --git a/pkg/testttp/http_test.go b/pkg/testttp/http_test.go index ebb57d9da8..5bed499486 100644 --- a/pkg/testttp/http_test.go +++ b/pkg/testttp/http_test.go @@ -45,11 +45,33 @@ func TestHTTP(t *testing.T) { }) t.Run("Post", func(t *testing.T) { - testttp. - Post(t, "/", nil). - Do(svr). - ExpectStatus(http.StatusCreated). - ExpectBody(assertBody(t, http.MethodPost)) + t.Run("basic", func(t *testing.T) { + testttp. + Post(t, "/", nil). + Do(svr). + ExpectStatus(http.StatusCreated). + ExpectBody(assertBody(t, http.MethodPost)) + }) + + t.Run("with form values", func(t *testing.T) { + svr := http.NewServeMux() + svr.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.ParseForm() + w.WriteHeader(http.StatusOK) + w.Write([]byte(r.FormValue("key"))) + })) + + testttp. + Post(t, "/", nil). + SetFormValue("key", "val"). + Do(svr). + ExpectStatus(http.StatusOK). + ExpectBody(func(body *bytes.Buffer) { + if expected, got := "val", body.String(); expected != got { + t.Fatalf("did not get form value; expected=%q got=%q", expected, got) + } + }) + }) }) t.Run("PostJSON", func(t *testing.T) {