github.com/msales/pkg/v3@v3.24.0/httpx/json_test.go (about) 1 package httpx 2 3 import ( 4 "errors" 5 "net/http" 6 "net/http/httptest" 7 "testing" 8 9 "github.com/stretchr/testify/assert" 10 ) 11 12 func TestWriteJSONResponse(t *testing.T) { 13 tests := []struct { 14 code int 15 data interface{} 16 expectedJSON string 17 expectedErr bool 18 }{ 19 { 20 200, 21 struct { 22 Foo string 23 Bar string 24 }{"foo", "bar"}, 25 `{"Foo":"foo","Bar":"bar"}`, 26 false, 27 }, 28 { 29 500, 30 make(chan int), 31 "", 32 true, 33 }, 34 } 35 36 for _, test := range tests { 37 w := httptest.NewRecorder() 38 err := WriteJSONResponse(w, test.code, test.data) 39 40 assert.Equal(t, test.code, w.Code) 41 assert.Equal(t, test.expectedJSON, string(w.Body.Bytes())) 42 if test.expectedErr { 43 assert.Error(t, err) 44 continue 45 46 } 47 assert.NoError(t, err) 48 assert.Equal(t, JSONContentType, w.Header().Get("Content-Type")) 49 } 50 } 51 52 func TestWriteJSONResponse_WriteError(t *testing.T) { 53 w := FakeResponseWriter{} 54 55 err := WriteJSONResponse(w, 200, "test") 56 57 assert.Error(t, err) 58 } 59 60 type FakeResponseWriter struct{} 61 62 func (rw FakeResponseWriter) Header() http.Header { 63 return http.Header{} 64 } 65 66 func (rw FakeResponseWriter) Write([]byte) (int, error) { 67 return 0, errors.New("test error") 68 } 69 70 func (rw FakeResponseWriter) WriteHeader(int) { 71 72 }