// JSON returns reponse body as JSON structure. // In case of error if fails test. func (r *Response) JSON(t TestingT) (j jsons.Struct) { defer func() { if p := recover(); p != nil { j = nil t.Fatalf("panic: %v", p) } }() j = jsons.ParseBytes(r.Body) return }
func TestRequestResponseBody(t *testing.T) { u, err := url.Parse("http://jsonplaceholder.typicode.com") require.Nil(t, err) client := NewClient(*u) j := jsons.Parse(`{"userId": 1, "id": 101, "title": "title", "body": "body"}`) req := client.NewRequest(t, "POST", "/posts", j) assert.Nil(t, req.Body) assert.NotNil(t, req.Request.Body) resp := client.Do(t, req, 201) assert.Equal(t, []byte(j.String()), req.Body) assert.IsType(t, errorReadCloser{}, req.Request.Body) assert.Equal(t, jsons.Parse(`{"id": 101}`), jsons.ParseBytes(resp.Body)) assert.IsType(t, errorReadCloser{}, resp.Response.Body) }
// bodyRepr returns representation of body depending on content type. // It may be indented, shortened or returned as is. // It returns nil for empty body. func bodyRepr(contentType string, body []byte) []byte { if len(body) == 0 { return nil } switch { case strings.Contains(contentType, "json"): return []byte(jsons.ParseBytes(body).Indent()) default: for _, r := range string(body) { switch { case r == '\n': continue case strconv.IsPrint(r): continue default: return []byte(fmt.Sprintf("[%d bytes data]", len(body))) } } return body } }