(t *testing.T)
| 71 | } |
| 72 | |
| 73 | func 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 | |
| 123 | type testJSONError struct { |
| 124 | Err string `json:"error"` |
nothing calls this directly
no test coverage detected
searching dependent graphs…