MCPcopy
hub / github.com/nytimes/gizmo / TestJSONToHTTP

Function TestJSONToHTTP

server/middleware_test.go:73–121  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

71}
72
73func TestJSONToHTTP(t *testing.T) {
74 tests := []struct {
75 given JSONEndpoint
76 givenBody io.Reader
77
78 wantCode int
79 wantBody string
80 }{
81 {
82 JSONEndpoint(func(r *http.Request) (int, interface{}, error) {
83 bod, err := ioutil.ReadAll(r.Body)
84 if err != nil {
85 t.Error("unable to read given request body: ", err)
86 }
87 if string(bod) != "yup" {
88 t.Errorf("expected 'yup', got %+v", string(bod))
89 }
90 return http.StatusOK, struct{ Howdy string }{"Hi"}, nil
91 }),
92 bytes.NewBufferString("yup"),
93 http.StatusOK,
94 "{\"Howdy\":\"Hi\"}\n",
95 },
96 {
97 JSONEndpoint(func(r *http.Request) (int, interface{}, error) {
98 return http.StatusServiceUnavailable, nil, &testJSONError{"nope"}
99 }),
100 nil,
101 http.StatusServiceUnavailable,
102 "{\"error\":\"nope\"}\n",
103 },
104 }
105
106 for _, test := range tests {
107 r, _ := http.NewRequest("GET", "", test.givenBody)
108 w := httptest.NewRecorder()
109 JSONToHTTP(test.given).ServeHTTP(w, r)
110
111 if w.Code != test.wantCode {
112 t.Errorf("expected status code %d, got %d", test.wantCode, w.Code)
113 }
114 if gotHdr := w.Header().Get("Content-Type"); gotHdr != jsonContentType {
115 t.Errorf("expected Content-Type header of '%#v', got '%#v'", jsonContentType, gotHdr)
116 }
117 if got := w.Body.String(); got != test.wantBody {
118 t.Errorf("expected body of '%#v', got '%#v'", test.wantBody, got)
119 }
120 }
121}
122
123type testJSONError struct {
124 Err string `json:"error"`

Callers

nothing calls this directly

Calls 7

JSONEndpointFuncType · 0.85
JSONToHTTPFunction · 0.85
HeaderMethod · 0.80
ServeHTTPMethod · 0.65
GetMethod · 0.65
ErrorMethod · 0.45
StringMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…