RUD/internal/store/store_test.go
2026-11-01 13:11:54 +00:00

58 lines
1.8 KiB
Go

package store
import (
"path/filepath"
"testing"
"time"
"git.gsdistance.org/tyuXX/RUD/internal/config"
)
func TestStoreRingBufferAndPersistence(t *testing.T) {
tmpDir := t.TempDir()
persistPath := filepath.Join(tmpDir, "state.json")
cfg := config.DefaultConfig()
cfg.Storage.HistorySize = 3
cfg.Storage.PersistenceFile = persistPath
cfg.Monitors = []config.MonitorConfig{
{ID: "m1", Name: "Mon 1", Method: "http", URL: "http://localhost"},
{ID: "m2", Name: "Mon 2", Method: "tcp", Target: "localhost:80"},
}
st := New(&cfg)
t0 := time.Now().UTC().Add(-10 * time.Minute)
st.Record("m1", CheckResult{Timestamp: t0, State: StateUp, LatencyMs: 10})
st.Record("m1", CheckResult{Timestamp: t0.Add(time.Minute), State: StateUp, LatencyMs: 20})
st.Record("m1", CheckResult{Timestamp: t0.Add(2 * time.Minute), State: StateDegraded, LatencyMs: 800})
st.Record("m1", CheckResult{Timestamp: t0.Add(3 * time.Minute), State: StateDown, LatencyMs: 0, Message: "timeout"})
snap := st.Snapshot()
m1 := snap.MonitorsByID["m1"]
if len(m1.History) != 3 {
t.Fatalf("expected ring buffer length 3, got %d", len(m1.History))
}
if m1.State != StateDown {
t.Fatalf("expected m1 state down, got %s", m1.State)
}
if m1.UptimePct != 75.0 {
t.Fatalf("expected 75%% uptime (3 of 4 checks up/degraded), got %.2f%%", m1.UptimePct)
}
if snap.OverallState != StateDown {
t.Fatalf("expected overall state down, got %s", snap.OverallState)
}
if err := st.SaveToDisk(); err != nil {
t.Fatalf("SaveToDisk failed: %v", err)
}
st2 := New(&cfg)
if err := st2.LoadFromDisk(); err != nil {
t.Fatalf("LoadFromDisk failed: %v", err)
}
snap2 := st2.Snapshot()
if snap2.MonitorsByID["m1"].TotalChecks != 4 {
t.Fatalf("expected restored TotalChecks=4, got %d", snap2.MonitorsByID["m1"].TotalChecks)
}
}