From 6992d476b38a267b6e5390bd1c9f8ae8374d8bfe Mon Sep 17 00:00:00 2001 From: Stein Fletcher Date: Sun, 7 Apr 2019 10:38:19 +0100 Subject: [PATCH] support whitespace characters when asserting json --- apitest.go | 7 +------ apitest_test.go | 23 +++++++++++++++++++++++ diagram.go | 2 +- mocks.go | 2 +- 4 files changed, 26 insertions(+), 8 deletions(-) diff --git a/apitest.go b/apitest.go index 16ecfeb..1060586 100644 --- a/apitest.go +++ b/apitest.go @@ -656,7 +656,7 @@ func (a *APITest) assertResponse(res *httptest.ResponseRecorder) { } if a.response.body != "" { - if isJSON(a.response.body) { + if json.Valid([]byte(a.response.body)) { assert.JSONEq(a.t, a.response.body, res.Body.String()) } else { assert.Equal(a.t, a.response.body, res.Body.String()) @@ -728,11 +728,6 @@ func (a *APITest) assertHeaders(res *httptest.ResponseRecorder) { } } -func isJSON(s string) bool { - var js map[string]interface{} - return json.Unmarshal([]byte(s), &js) == nil -} - func debugLog(prefix, header, msg string) { fmt.Printf("\n%s %s\n%s\n", prefix, header, msg) } diff --git a/apitest_test.go b/apitest_test.go index e7d7d9e..0685bfd 100644 --- a/apitest_test.go +++ b/apitest_test.go @@ -254,6 +254,29 @@ func TestApiTest_MatchesJSONResponseBody(t *testing.T) { End() } +func TestApiTest_MatchesJSONResponseBodyWithWhitespace(t *testing.T) { + handler := http.NewServeMux() + handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusCreated) + w.Header().Set("Content-Type", "application/json") + _, err := w.Write([]byte(`{"a": 12345, "b": "hi"}`)) + if err != nil { + panic(err) + } + }) + + New(). + Handler(handler). + Get("/hello"). + Expect(t). + Body(`{ + "a": 12345, + "b": "hi" + }`). + Status(http.StatusCreated). + End() +} + func TestApiTest_MatchesTextResponseBody(t *testing.T) { handler := http.NewServeMux() handler.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { diff --git a/diagram.go b/diagram.go index b0454fc..57eaeb3 100644 --- a/diagram.go +++ b/diagram.go @@ -240,7 +240,7 @@ func formatBodyContent(bodyReadCloser io.ReadCloser) (string, error) { bodyReadCloser = ioutil.NopCloser(bytes.NewBuffer(body)) buf := new(bytes.Buffer) - if isJSON(string(body)) { + if json.Valid(body) { jsonEncodeErr := json.Indent(buf, body, "", " ") if jsonEncodeErr != nil { return "", jsonEncodeErr diff --git a/mocks.go b/mocks.go index 612653a..0f8bfc9 100644 --- a/mocks.go +++ b/mocks.go @@ -155,7 +155,7 @@ func buildResponseFromMock(mockResponse *MockResponse) *http.Response { // if the content type isn't set and the body contains json, set content type as json if len(mockResponse.body) > 0 { if len(contentTypeHeader) == 0 { - if isJSON(mockResponse.body) { + if json.Valid([]byte(mockResponse.body)) { contentType = "application/json" } else { contentType = "text/plain"