Skip to content

Commit

Permalink
Support formatter on request body
Browse files Browse the repository at this point in the history
This is already supported on response body, mock request and responses,
so it makes sense to support this when setting the request body
  • Loading branch information
Stein Fletcher committed Mar 22, 2021
1 parent d79f37b commit d206f62
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
6 changes: 6 additions & 0 deletions apitest.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
25 changes: 25 additions & 0 deletions apitest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down

0 comments on commit d206f62

Please sign in to comment.