71 lines
1.3 KiB
Go
71 lines
1.3 KiB
Go
package grabhttp
|
|
|
|
import (
|
|
"bytes"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
)
|
|
|
|
func TestWriteJSON(t *testing.T) {
|
|
testcases := []struct {
|
|
input interface{}
|
|
code int
|
|
outcode int
|
|
output []byte
|
|
}{
|
|
{
|
|
input: struct{}{},
|
|
code: http.StatusOK,
|
|
output: []byte("{}\n"),
|
|
},
|
|
{
|
|
input: struct{}{},
|
|
code: http.StatusNotFound,
|
|
output: []byte("{}\n"),
|
|
},
|
|
{
|
|
input: struct {
|
|
Foo string
|
|
}{
|
|
Foo: "foo",
|
|
},
|
|
code: http.StatusOK,
|
|
output: []byte(`{"Foo":"foo"}` + "\n"),
|
|
},
|
|
{
|
|
input: struct {
|
|
Foo struct {
|
|
Bar string `json:"quuz"`
|
|
}
|
|
}{
|
|
Foo: struct {
|
|
Bar string `json:"quuz"`
|
|
}{Bar: "foo"},
|
|
},
|
|
code: http.StatusOK,
|
|
output: []byte(`{"Foo":{"quuz":"foo"}}` + "\n"),
|
|
},
|
|
{
|
|
input: struct{ C func() }{C: func() {}},
|
|
code: http.StatusOK,
|
|
outcode: http.StatusInternalServerError,
|
|
output: []byte(`{"status":"error","error":"json: unsupported type: func()"}` + "\n"),
|
|
},
|
|
}
|
|
for i, c := range testcases {
|
|
w := httptest.NewRecorder()
|
|
WriteJSON(c.input, c.code, w, httptest.NewRequest("", "/", nil))
|
|
if w.Code != c.code && w.Code != c.outcode {
|
|
t.Logf("code mismatch on case %d", i)
|
|
t.Fail()
|
|
}
|
|
b, err := io.ReadAll(w.Body)
|
|
if err != nil || !bytes.Equal(b, c.output) {
|
|
t.Logf("failed: %s != %s", b, c.output)
|
|
t.Fail()
|
|
}
|
|
}
|
|
}
|