From d206f62a812e342114dfad9dc64186a97c221962 Mon Sep 17 00:00:00 2001 From: Stein Fletcher Date: Mon, 22 Mar 2021 14:30:28 +0000 Subject: [PATCH] Support formatter on request body This is already supported on response body, mock request and responses, so it makes sense to support this when setting the request body --- apitest.go | 6 ++++++ apitest_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/apitest.go b/apitest.go index c1c4287..198f8eb 100644 --- a/apitest.go +++ b/apitest.go @@ -322,6 +322,12 @@ func (r *Request) Body(b string) *Request { return r } +// Bodyf sets the request body and supports a formatter +func (r *Request) Bodyf(format string, args ...interface{}) *Request { + r.body = fmt.Sprintf(format, args...) + return r +} + // BodyFromFile is a builder method to set the request body func (r *Request) BodyFromFile(f string) *Request { b, err := ioutil.ReadFile(f) diff --git a/apitest_test.go b/apitest_test.go index 1fd2464..bc22746 100644 --- a/apitest_test.go +++ b/apitest_test.go @@ -55,6 +55,31 @@ func TestApiTest_AddsJSONBodyToRequest(t *testing.T) { End() } +func TestApiTest_AddsJSONBodyToRequest_SupportsFormatter(t *testing.T) { + handler := http.NewServeMux() + handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { + data, _ := ioutil.ReadAll(r.Body) + if string(data) != `{"a": 12345}` { + w.WriteHeader(http.StatusInternalServerError) + return + } + if r.Header.Get("Content-Type") != "application/json" { + w.WriteHeader(http.StatusBadRequest) + return + } + w.WriteHeader(http.StatusOK) + }) + + apitest.New(). + Handler(handler). + Post("/hello"). + Bodyf(`{"a": %d}`, 12345). + Header("Content-Type", "application/json"). + Expect(t). + Status(http.StatusOK). + End() +} + func TestApiTest_RequestURLFormat(t *testing.T) { apitest.New(). HandlerFunc(func(w http.ResponseWriter, r *http.Request) {