-
Notifications
You must be signed in to change notification settings - Fork 0
/
json_test.go
61 lines (47 loc) · 1.65 KB
/
json_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"testing"
"encoding/json"
"net/http"
"net/http/httptest"
)
func TestJSONErrorToReturnJSONMessage(t *testing.T) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
JSONError(w, "test message", http.StatusInternalServerError)
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
h.ServeHTTP(res, req)
Expect(t, res.Code, http.StatusInternalServerError)
Expect(t, res.Header().Get("Content-Type"), "application/json; charset=utf-8")
Expect(t, res.Body.String(), `{"message":"test message"}`)
}
func TestJSONResponseToReturnJSONMessage(t *testing.T) {
type testData struct {
Name string `json:"name"`
Age int `json:"age"`
}
data := testData{Name: "Gandalf the Grey", Age: 2019}
expected, _ := json.MarshalIndent(data, "", " ")
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
JSONResponse(w, data, http.StatusOK)
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
h.ServeHTTP(res, req)
Expect(t, res.Code, http.StatusOK)
Expect(t, res.Header().Get("Content-Type"), "application/json; charset=utf-8")
Expect(t, res.Body.String(), string(expected))
}
func TestJSONResponseToReturnNilOnInvalidMarshal(t *testing.T) {
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := func() {}
JSONResponse(w, val, http.StatusInternalServerError)
})
res := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/foo", nil)
h.ServeHTTP(res, req)
Expect(t, res.Code, http.StatusInternalServerError)
Expect(t, res.Header().Get("Content-Type"), "application/json; charset=utf-8")
Expect(t, res.Body.String(), "")
}