45 lines
1.1 KiB
Go
45 lines
1.1 KiB
Go
package webutils_test
|
|
|
|
import (
|
|
"io"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
webutils "git.mstar.dev/mstar/goutils/http"
|
|
)
|
|
|
|
func TestSendJsonOk(t *testing.T) {
|
|
recorder := httptest.NewRecorder()
|
|
err := webutils.SendJson(recorder, map[string]any{
|
|
"a": 1,
|
|
"b": "b",
|
|
"c": nil,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("error while sending json: %v", err)
|
|
}
|
|
res := recorder.Result()
|
|
if ctype := res.Header.Get("Content-Type"); ctype != "application/json" {
|
|
t.Fatalf("expected content type \"application/json\", got %v", ctype)
|
|
}
|
|
// httptest guarantees body to be functional and only returned error will be EOL
|
|
// so no need to watch for error
|
|
bodyBytes, _ := io.ReadAll(res.Body)
|
|
body := string(bodyBytes)
|
|
expected := `{"a":1,"b":"b","c":null}`
|
|
if body != expected {
|
|
t.Fatalf("Expected %v as body, got %v", expected, body)
|
|
}
|
|
}
|
|
|
|
func TestSendJsonNotMarshallable(t *testing.T) {
|
|
recorder := httptest.NewRecorder()
|
|
err := webutils.SendJson(recorder, map[string]any{
|
|
"a": 1,
|
|
"b": "b",
|
|
"c": make(chan any),
|
|
})
|
|
if err == nil {
|
|
t.Fatal("expected json marshalling error")
|
|
}
|
|
}
|