github.com/haraldrudell/parl@v0.4.176/ptime/on-ticker_test.go (about) 1 /* 2 © 2018–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/) 3 ISC License 4 */ 5 6 package ptime 7 8 import ( 9 "testing" 10 "time" 11 12 "github.com/haraldrudell/parl/internal/cyclebreaker" 13 ) 14 15 func TestNewOnTicker(t *testing.T) { 16 var period = time.Millisecond 17 18 // start a ticker that has a thread waiting for period alignment 19 var t0 = time.Now() 20 var ticker = NewOnTicker(period, nil) 21 22 // wait for first tick: thread will exit 23 var tx = <-ticker.C 24 var t1 = time.Now() 25 if !tx.After(t0) || !tx.Before(t1) { 26 t.Errorf("bad time received on channel\nt0: %s\nt: %s\nt1: %s", 27 t0.Format(cyclebreaker.Rfc3339ns), 28 tx.Format(cyclebreaker.Rfc3339ns), 29 t1.Format(cyclebreaker.Rfc3339ns), 30 ) 31 } 32 33 // second tick: thread should be exited 34 var ty = <-ticker.C 35 if !ticker.onTickp.isThreadExit.Load() { 36 t.Error("thread did not exit") 37 } 38 39 var duration = ty.Sub(tx) 40 if duration < period/2 { 41 t.Errorf("duration too short: %s exp %s", duration, period) 42 } else if duration >= 2*period { 43 t.Errorf("duration too long: %s exp %s", duration, period) 44 } 45 }