package response import ( "encoding/json" "net/http" "net/http/httptest" "testing" errorspkg "github.com/company/ai-ops/pkg/errors" ) func TestJSONWritesStatusContentTypeAndBody(t *testing.T) { w := httptest.NewRecorder() JSON(w, http.StatusCreated, map[string]string{"ok": "true"}) if w.Code != http.StatusCreated { t.Fatalf("status = %d", w.Code) } if got := w.Header().Get("Content-Type"); got != "application/json" { t.Fatalf("content-type = %s", got) } if got := w.Body.String(); got != "{\"ok\":\"true\"}\n" { t.Fatalf("body = %s", got) } } func TestSuccessAndErrorResponses(t *testing.T) { t.Run("success", func(t *testing.T) { w := httptest.NewRecorder() Success(w, map[string]any{"id": "1"}) var out Response if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { t.Fatal(err) } data := out.Data.(map[string]any) if data["id"] != "1" { t.Fatalf("unexpected data: %+v", out.Data) } }) t.Run("error", func(t *testing.T) { w := httptest.NewRecorder() Error(w, errorspkg.ErrForbidden) if w.Code != http.StatusForbidden { t.Fatalf("status = %d", w.Code) } if got := w.Body.String(); got == "" || !json.Valid(w.Body.Bytes()) { t.Fatalf("invalid json body: %q", got) } }) } func TestPaginatedResponseComputesTotalPages(t *testing.T) { w := httptest.NewRecorder() PaginatedResponse(w, []string{"a", "b"}, 21, 2, 10) var out Response if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { t.Fatal(err) } payload := out.Data.(map[string]any) if payload["total_pages"].(float64) != 3 { t.Fatalf("total_pages = %+v", payload["total_pages"]) } }