package checker import ( "log/slog" "testing" "time" "github.com/google/uuid" ) func TestEvidencePolicy(t *testing.T) { r := New(nil, 1, slog.New(slog.DiscardHandler)) r.jitter = func(time.Duration) time.Duration { return 0 } m := uuid.New() now := time.Now() steps := []struct { after time.Duration ok bool send bool }{ {0, true, true}, // first result {time.Minute, true, false}, // healthy, sent recently {2 * time.Minute, false, true}, // failure {3 * time.Minute, false, true}, // failures always {4 * time.Minute, true, true}, // recovery {5 * time.Minute, true, false}, // healthy again {4*time.Minute + evidenceEvery, true, true}, // periodic sample } for i, s := range steps { if got := r.shouldSendEvidence(m, s.ok, now.Add(s.after)); got != s.send { t.Errorf("step %d (ok=%t after %v): send = %t, want %t", i, s.ok, s.after, got, s.send) } } } // TestEvidenceSpreadsAfterStart starts with many healthy monitors at once: // their periodic evidence must not all fall into the same minute again. func TestEvidenceSpreadsAfterStart(t *testing.T) { r := New(nil, 1, slog.New(slog.DiscardHandler)) start := time.Now() const monitors = 600 ids := make([]uuid.UUID, monitors) for i := range ids { ids[i] = uuid.New() if !r.shouldSendEvidence(ids[i], true, start) { t.Fatal("first result sent no evidence") } } // One result per monitor and minute over the next period. perMinute := map[int]int{} for minute := 1; minute <= int(evidenceEvery/time.Minute); minute++ { for _, id := range ids { if r.shouldSendEvidence(id, true, start.Add(time.Duration(minute)*time.Minute)) { perMinute[minute]++ } } } total, peak := 0, 0 for _, n := range perMinute { total += n peak = max(peak, n) } if total != monitors { t.Errorf("periodic evidence in the first period = %d, want one per monitor, %d", total, monitors) } // 60 a minute on average; all 600 in one minute without the jitter. if peak > 150 { t.Errorf("busiest minute sent %d evidence, want them spread at about %d a minute", peak, monitors/10) } }