mirror of
https://github.com/SamyRai/turash.git
synced 2025-12-26 23:01:33 +00:00
60 lines
1.7 KiB
Go
60 lines
1.7 KiB
Go
package service
|
|
|
|
import (
|
|
"context"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
type memRepo struct {
|
|
data map[string]map[string]any
|
|
}
|
|
|
|
func newMemRepo() *memRepo { return &memRepo{data: map[string]map[string]any{}} }
|
|
func (r *memRepo) Get(_ context.Context, key string) (map[string]any, error) { return r.data[key], nil }
|
|
func (r *memRepo) Set(_ context.Context, key string, value map[string]any) error {
|
|
r.data[key] = value
|
|
return nil
|
|
}
|
|
|
|
func TestSettingsService_Caching(t *testing.T) {
|
|
repo := newMemRepo()
|
|
svc := NewSettingsService(repo)
|
|
// shorten TTL for test
|
|
svc.cacheTTL = 10 * time.Millisecond
|
|
|
|
// initial - no maintenance set
|
|
m, err := svc.GetMaintenanceCached(context.Background())
|
|
if err != nil {
|
|
t.Fatalf("err: %v", err)
|
|
}
|
|
if m.Enabled {
|
|
t.Fatalf("expected disabled initially")
|
|
}
|
|
|
|
// update repo directly and ensure cached value doesn't change until TTL or invalidation
|
|
repo.Set(context.Background(), "maintenance", map[string]any{"enabled": true, "message": "now"})
|
|
|
|
// cached - should still be old value
|
|
m, _ = svc.GetMaintenanceCached(context.Background())
|
|
if m.Enabled {
|
|
t.Fatalf("expected cached value to still be disabled")
|
|
}
|
|
|
|
// wait for TTL expiry
|
|
time.Sleep(20 * time.Millisecond)
|
|
m, _ = svc.GetMaintenanceCached(context.Background())
|
|
if !m.Enabled || m.Message != "now" {
|
|
t.Fatalf("expected refreshed value, got %#v", m)
|
|
}
|
|
|
|
// set via service should invalidate cache immediately
|
|
if err := svc.SetMaintenance(context.Background(), &MaintenanceSetting{Enabled: false, Message: "off"}); err != nil {
|
|
t.Fatalf("set maintenance: %v", err)
|
|
}
|
|
m, _ = svc.GetMaintenanceCached(context.Background())
|
|
if m.Enabled {
|
|
t.Fatalf("expected disabled after set, got %#v", m)
|
|
}
|
|
}
|