Files
lincodex/backend/internal/adapter/primary/http/router_test.go
T
2026-10-05 14:23:31 +03:00

83 lines
2.7 KiB
Go

package httpadapter
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"time"
v1 "lincodex/backend/internal/adapter/primary/http/v1"
metrics "lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/usecase/health"
)
type readinessFunc func(context.Context) error
func (check readinessFunc) Check(ctx context.Context) error {
return check(ctx)
}
func TestOperationalHealthRoutes(t *testing.T) {
for _, test := range []struct {
name string
check readinessFunc
path string
statusCode int
bodyStatus string
}{
{name: "live", check: func(context.Context) error { return nil }, path: "/healthz", statusCode: http.StatusOK, bodyStatus: "ok"},
{name: "ready", check: func(context.Context) error { return nil }, path: "/readyz", statusCode: http.StatusOK, bodyStatus: "ready"},
{name: "not ready", check: func(context.Context) error { return context.DeadlineExceeded }, path: "/readyz", statusCode: http.StatusServiceUnavailable, bodyStatus: "not_ready"},
} {
t.Run(test.name, func(t *testing.T) {
router := newTestRouter(t, test.check)
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, test.path, nil))
if response.Code != test.statusCode {
t.Fatalf("status code = %d, want %d", response.Code, test.statusCode)
}
var body struct {
Status string `json:"status"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
if body.Status != test.bodyStatus {
t.Fatalf("status = %q, want %q", body.Status, test.bodyStatus)
}
})
}
}
func TestPublicHealthRouteUsesGeneratedOgenHandler(t *testing.T) {
router := newTestRouter(t, func(context.Context) error { return context.DeadlineExceeded })
response := httptest.NewRecorder()
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/v1/healthz", nil))
if response.Code != http.StatusOK {
t.Fatalf("status code = %d, want %d: %s", response.Code, http.StatusOK, response.Body.String())
}
var body struct {
Status string `json:"status"`
}
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
t.Fatalf("decode response: %v", err)
}
if body.Status != "ok" {
t.Fatalf("status = %q, want %q", body.Status, "ok")
}
}
func newTestRouter(t *testing.T, checker readinessFunc) http.Handler {
t.Helper()
readiness := health.NewReadiness(checker)
healthHandler := v1.NewHealthHandler(readiness, time.Second)
router, err := NewRouter(healthHandler, metrics.New(), slog.New(slog.DiscardHandler))
if err != nil {
t.Fatalf("NewRouter() error = %v", err)
}
return router
}