Files
2026-06-08 15:03:41 -05:00

86 lines
2.3 KiB
Go

package httputil
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestDecodeJSONStrict(t *testing.T) {
t.Run("valid", func(t *testing.T) {
var got struct {
Name string `json:"name"`
}
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"demo"}`))
rr := httptest.NewRecorder()
if !DecodeJSON(rr, req, &got) {
t.Fatalf("DecodeJSON returned false: %s", rr.Body.String())
}
if got.Name != "demo" {
t.Fatalf("unexpected decoded value: %#v", got)
}
})
t.Run("unknown field", func(t *testing.T) {
var got struct {
Name string `json:"name"`
}
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"name":"demo","extra":true}`))
rr := httptest.NewRecorder()
if DecodeJSON(rr, req, &got) {
t.Fatal("DecodeJSON returned true for unknown field")
}
if rr.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", rr.Code, http.StatusBadRequest)
}
if !strings.Contains(rr.Body.String(), "unknown field") {
t.Fatalf("unexpected body: %s", rr.Body.String())
}
})
t.Run("invalid json", func(t *testing.T) {
var got map[string]string
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{`))
rr := httptest.NewRecorder()
if DecodeJSON(rr, req, &got) {
t.Fatal("DecodeJSON returned true for invalid JSON")
}
if rr.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want %d", rr.Code, http.StatusBadRequest)
}
})
}
func TestWriteJSONAndError(t *testing.T) {
rr := httptest.NewRecorder()
WriteJSON(rr, http.StatusCreated, map[string]string{"status": "ok"})
if rr.Code != http.StatusCreated {
t.Fatalf("status = %d", rr.Code)
}
if ct := rr.Header().Get("Content-Type"); ct != "application/json" {
t.Fatalf("content-type = %q", ct)
}
var body map[string]string
if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["status"] != "ok" {
t.Fatalf("unexpected body: %#v", body)
}
rr = httptest.NewRecorder()
WriteError(rr, http.StatusTeapot, "short and stout")
if rr.Code != http.StatusTeapot {
t.Fatalf("status = %d", rr.Code)
}
body = map[string]string{}
if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["error"] != "short and stout" {
t.Fatalf("unexpected error body: %#v", body)
}
}