Skip to content

Commit

Permalink
support whitespace characters when asserting json
Browse files Browse the repository at this point in the history
  • Loading branch information
Stein Fletcher committed Apr 7, 2019
1 parent 15cb78e commit 6992d47
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 8 deletions.
7 changes: 1 addition & 6 deletions apitest.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down Expand Up @@ -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)
}
Expand Down
23 changes: 23 additions & 0 deletions apitest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
2 changes: 1 addition & 1 deletion diagram.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion mocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down

0 comments on commit 6992d47

Please sign in to comment.