turash/bugulma/backend/internal/handler/settings_admin_handler_test.go
2025-12-15 10:06:41 +01:00

81 lines
2.2 KiB
Go

package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"bugulma/backend/internal/service"
"github.com/gin-gonic/gin"
)
type inMemorySettingsRepo struct {
data map[string]map[string]any
}
func newInMemorySettingsRepo() *inMemorySettingsRepo {
return &inMemorySettingsRepo{data: map[string]map[string]any{}}
}
func (r *inMemorySettingsRepo) Get(_ context.Context, key string) (map[string]any, error) {
return r.data[key], nil
}
func (r *inMemorySettingsRepo) Set(_ context.Context, key string, value map[string]any) error {
r.data[key] = value
return nil
}
func TestSettingsAdmin_GetAndSetMaintenance(t *testing.T) {
gin.SetMode(gin.TestMode)
repo := newInMemorySettingsRepo()
svc := service.NewSettingsService(repo)
h := NewSettingsAdminHandler(svc)
r := gin.New()
r.GET("/api/v1/admin/settings/maintenance", h.GetMaintenance)
r.PUT("/api/v1/admin/settings/maintenance", h.SetMaintenance)
// GET initially should return disabled
w := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/v1/admin/settings/maintenance", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("GET expected 200, got %d", w.Code)
}
var resp service.MaintenanceSetting
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if resp.Enabled {
t.Fatalf("expected disabled initially")
}
// PUT update
payload := service.MaintenanceSetting{Enabled: true, Message: "planned maintenance"}
b, _ := json.Marshal(payload)
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPut, "/api/v1/admin/settings/maintenance", bytes.NewReader(b))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("PUT expected 200, got %d", w.Code)
}
// GET again should reflect
w = httptest.NewRecorder()
req = httptest.NewRequest(http.MethodGet, "/api/v1/admin/settings/maintenance", nil)
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("GET expected 200, got %d", w.Code)
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatalf("unmarshal: %v", err)
}
if !resp.Enabled || resp.Message != "planned maintenance" {
t.Fatalf("unexpected maintenance setting: %#v", resp)
}
}