Skip to content

Commit

Permalink
Support receiving structs, slices and maps as arguments to request JS…
Browse files Browse the repository at this point in the history
…ON in api tests
  • Loading branch information
Stein Fletcher committed Mar 7, 2020
1 parent d76407e commit 6bcbc99
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 3 deletions.
19 changes: 16 additions & 3 deletions apitest.go
Original file line number Diff line number Diff line change
Expand Up @@ -288,9 +288,22 @@ func (r *Request) BodyFromFile(f string) *Request {
return r
}

// JSON is a convenience method for setting the request body and content type header as "application/json"
func (r *Request) JSON(b string) *Request {
r.body = b
// JSON is a convenience method for setting the request body and content type header as "application/json".
// If v is not a string or []byte it will marshall the provided variable as json
func (r *Request) JSON(v interface{}) *Request {
switch x := v.(type) {
case string:
r.body = x
case []byte:
r.body = string(x)
default:
asJSON, err := json.Marshal(x)
if err != nil {
r.apiTest.t.Fatal(err)
return nil
}
r.body = string(asJSON)
}
r.ContentType("application/json")
return r
}
Expand Down
45 changes: 45 additions & 0 deletions apitest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,51 @@ func TestApiTest_AddsJSONBodyToRequest(t *testing.T) {
End()
}

func TestApiTest_JSONBody(t *testing.T) {
type bodyStruct struct {
A int `json:"a"`
}

tests := map[string]struct {
body interface{}
}{
"string": {
body: `{"a": 12345}`,
},
"[]byte": {
body: []byte(`{"a": 12345}`),
},
"struct": {
body: bodyStruct{A: 12345},
},
"map": {
body: map[string]interface{}{"a": 12345},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
handler := http.NewServeMux()
handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
data, _ := ioutil.ReadAll(r.Body)
assert.JSONEq(t, `{"a": 12345}`, string(data))
if r.Header.Get("Content-Type") != "application/json" {
w.WriteHeader(http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
})

apitest.New().
Handler(handler).
Post("/hello").
JSON(test.body).
Expect(t).
Status(http.StatusOK).
End()
})
}
}

func TestApiTest_AddsJSONBodyToRequestUsingJSON(t *testing.T) {
handler := http.NewServeMux()
handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
Expand Down

0 comments on commit 6bcbc99

Please sign in to comment.