github.com/decred/dcrlnd@v0.7.6/clock/test_clock_test.go (about) 1 package clock 2 3 import ( 4 "fmt" 5 "testing" 6 "time" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 var ( 12 testTime = time.Date(2009, time.January, 3, 12, 0, 0, 0, time.UTC) 13 ) 14 15 func TestNow(t *testing.T) { 16 c := NewTestClock(testTime) 17 now := c.Now() 18 assert.Equal(t, testTime, now) 19 20 now = now.Add(time.Hour) 21 c.SetTime(now) 22 assert.Equal(t, now, c.Now()) 23 } 24 25 func TestTickAfter(t *testing.T) { 26 c := NewTestClock(testTime) 27 28 // Should be ticking immediately. 29 ticker0 := c.TickAfter(0) 30 31 // Both should be ticking after SetTime 32 ticker1 := c.TickAfter(time.Hour) 33 ticker2 := c.TickAfter(time.Hour) 34 35 // We don't expect this one to tick. 36 ticker3 := c.TickAfter(2 * time.Hour) 37 38 tickOrTimeOut := func(ticker <-chan time.Time, expectTick bool) { 39 tick := false 40 select { 41 case <-ticker: 42 tick = true 43 44 case <-time.After(time.Millisecond): 45 } 46 47 assert.Equal(t, expectTick, tick) 48 } 49 50 tickOrTimeOut(ticker0, true) 51 tickOrTimeOut(ticker1, false) 52 tickOrTimeOut(ticker2, false) 53 tickOrTimeOut(ticker3, false) 54 55 c.SetTime(c.Now().Add(time.Hour)) 56 57 tickOrTimeOut(ticker1, true) 58 tickOrTimeOut(ticker2, true) 59 tickOrTimeOut(ticker3, false) 60 } 61 62 // TestTickSignal tests that TickAfter signals registration allowing 63 // safe time advancement. 64 func TestTickSignal(t *testing.T) { 65 const interval = time.Second 66 67 ch := make(chan time.Duration) 68 c := NewTestClockWithTickSignal(testTime, ch) 69 err := make(chan error, 1) 70 71 go func() { 72 select { 73 // TickAfter will signal registration but will not 74 // tick, unless we read the signal and set the time. 75 case <-c.TickAfter(interval): 76 err <- nil 77 78 // Signal timeout if tick didn't happen. 79 case <-time.After(time.Second): 80 err <- fmt.Errorf("timeout") 81 } 82 }() 83 84 tick := <-ch 85 // Expect that the interval is correctly passed over the channel. 86 assert.Equal(t, interval, tick) 87 88 // Once the ticker is registered, set the time to make it fire. 89 c.SetTime(testTime.Add(time.Second)) 90 assert.NoError(t, <-err) 91 }