package dregarnuhr import ( "context" "errors" "sync/atomic" "testing" "time" ) func TestLoopFakeClockWakeAndCoalescing(t *testing.T) { clock := newFakeClock() wake := make(chan struct{}, 1) steps := make(chan time.Time, 20) reports := make(chan string, 10) var once, periodic, awakened atomic.Int64 ctx, cancel := context.WithCancel(context.Background()) defer cancel() loop := Loop{Clock: clock, Every: time.Second, Wake: wake, OnWake: func(context.Context, time.Time) error { awakened.Add(1); return nil }, Triggers: []Trigger{ {Name: "once", After: 5 * time.Second, Run: func(context.Context, time.Time) error { once.Add(1); return nil }}, {Name: "periodic", Every: 10 * time.Second, Run: func(context.Context, time.Time) error { periodic.Add(1); return errors.New("synthetic") }}, }, Step: func(_ context.Context, at time.Time) error { steps <- at; return nil }, Report: func(stage string, _ error) { reports <- stage }, } done := make(chan error, 1) go func() { done <- loop.Run(ctx) }() receive(t, clock.created) wake <- struct{}{} receive(t, steps) receive(t, clock.created) if awakened.Load() != 1 || once.Load() != 0 { t.Fatal("wake changed timer deadlines") } clock.advance(5 * time.Second) receive(t, steps) receive(t, clock.created) if once.Load() != 1 || periodic.Load() != 0 { t.Fatal("initial cadence") } clock.advance(time.Hour) receive(t, steps) receive(t, clock.created) if once.Load() != 1 || periodic.Load() != 1 { t.Fatal("catch-up storm", once.Load(), periodic.Load()) } if receive(t, reports) != "periodic" { t.Fatal("hook failure missing") } close(wake) receive(t, clock.created) // closed wake channel must not spin clock.advance(10 * time.Second) receive(t, steps) receive(t, clock.created) if periodic.Load() != 2 { t.Fatal("periodic stopped after error") } cancel() if !errors.Is(receive(t, done), context.Canceled) { t.Fatal("loop did not stop") } clock.mu.Lock() defer clock.mu.Unlock() if len(clock.timers) != 0 { t.Fatal("timer leaked") } } func TestLoopRejectsInvalidHooks(t *testing.T) { for _, l := range []Loop{{}, {Every: time.Second, Step: func(context.Context, time.Time) error { return nil }, Triggers: []Trigger{{Name: "invalid"}}}} { if l.Run(context.Background()) == nil { t.Fatal("invalid loop accepted") } } }