package idleshut import ( "sync/atomic" "testing" "time" ) func TestFlow(t *testing.T) { p := New(Config{}) if p.Running() { t.Fatal("running when first started") } _ = p.Start() if !p.Running() { t.Fatal("should be running when started") } _ = p.Stop() if p.Running() { t.Fatal("running after stopped") } } func TestTicking(t *testing.T) { var idleTicksNonPtr uint32 var idleTicks = &idleTicksNonPtr p := New(Config{ TickDuration: 10 * time.Millisecond, MaxIdleTicks: 10, IdleTick: func() error { atomic.AddUint32(idleTicks, 1) return nil }, TickError: func(err error) { t.Fatal("got an idle process error:", err) }, }) // initial start _ = p.Start() if !p.Running() { t.Fatal("should be running when started") } // use up all the ticks right away time.Sleep(1 * time.Second) if atomic.LoadUint32(idleTicks) != 10 { t.Fatal("should have seen 10 idle ticks, which fits into MaxIdleTicks, saw", idleTicks) } if p.Running() { t.Fatal("should be expired from idle ticks") } // reset the ticks, but dont restart the process atomic.StoreUint32(idleTicks, 0) time.Sleep(130 * time.Millisecond) if atomic.LoadUint32(idleTicks) != 0 { t.Fatal("should have seen 0 idle ticks with no process running, saw", idleTicks) } _ = p.Start() if !p.Running() { t.Fatal("should be running when started again") } time.Sleep(31 * time.Millisecond) if saw := atomic.LoadUint32(idleTicks); saw != 3 { t.Fatal("should have seen 3 idle ticks, saw", saw) } p.Touch() time.Sleep(110 * time.Millisecond) if saw := atomic.LoadUint32(idleTicks); saw != 13 { t.Fatal("should have seen 13 idle ticks since we touched the process partway through, saw", saw) } // reset the ticks and restart the process atomic.StoreUint32(idleTicks, 0) _ = p.Start() if g := p.generation(); g != 3 { t.Fatal("we've started 3 times, but saw we counted to generation", g) } }