github.com/jxskiss/gopkg/v2@v2.14.9-0.20240514120614-899f3e7952b4/easy/ezhttp/response_test.go (about) 1 package ezhttp 2 3 import ( 4 "io" 5 "net/http/httptest" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 func TestJSON(t *testing.T) { 12 w := httptest.NewRecorder() 13 data := map[string]any{ 14 "a": 1234, 15 "b": "abcd", 16 } 17 JSON(w, 200, data) 18 19 result := w.Result() 20 defer result.Body.Close() 21 assert.Equal(t, 200, result.StatusCode) 22 assert.Equal(t, contentTypeJSON, result.Header.Get(hdrContentTypeKey)) 23 24 body, _ := io.ReadAll(result.Body) 25 assert.Contains(t, string(body), `"a":1234`) 26 assert.Contains(t, string(body), `"b":"abcd"`) 27 } 28 29 func TestJSONHumanFriendly(t *testing.T) { 30 w := httptest.NewRecorder() 31 data := map[any]any{ 32 1234: "a", 33 "abcd": "b", 34 } 35 JSONHumanFriendly(w, 500, data) 36 37 result := w.Result() 38 defer result.Body.Close() 39 assert.Equal(t, 500, result.StatusCode) 40 assert.Equal(t, contentTypeJSON, result.Header.Get(hdrContentTypeKey)) 41 42 body, _ := io.ReadAll(result.Body) 43 assert.Contains(t, string(body), "{\n \"") 44 assert.Contains(t, string(body), "\"\n}") 45 assert.Contains(t, string(body), `"1234": "a"`) 46 assert.Contains(t, string(body), `"abcd": "b"`) 47 }