github.com/mailgun/holster/v4@v4.20.0/clock/README.md (about) 1 # Clock 2 3 A drop in (almost) replacement for the system `time` package. It provides a way 4 to make scheduled calls, timers and tickers deterministic in tests. By default 5 it forwards all calls to the system `time` package. In test, however, it is 6 possible to enable the frozen clock mode, and advance time manually to make 7 scheduled even trigger at certain moments. 8 9 # Usage 10 11 ```go 12 package foo 13 14 import ( 15 "testing" 16 17 "github.com/mailgun/holster/v4/clock" 18 "github.com/stretchr/testify/assert" 19 ) 20 21 func TestSleep(t *testing.T) { 22 // Freeze switches the clock package to the frozen clock mode. You need to 23 // advance time manually from now on. Note that all scheduled events, timers 24 // and ticker created before this call keep operating in real time. 25 // 26 // The initial time is set to now here, but you can set any datetime. 27 clock.Freeze(clock.Now()) 28 // Do not forget to revert the effect of Freeze at the end of the test. 29 defer clock.Unfreeze() 30 31 var fired bool 32 33 clock.AfterFunc(100*clock.Millisecond, func() { 34 fired = true 35 }) 36 clock.Advance(93*clock.Millisecond) 37 38 // Advance will make all fire all events, timers, tickers that are 39 // scheduled for the passed period of time. Note that scheduled functions 40 // are called from within Advanced unlike system time package that calls 41 // them in their own goroutine. 42 assert.Equal(t, 97*clock.Millisecond, clock.Advance(6*clock.Millisecond)) 43 assert.True(t, fired) 44 assert.Equal(t, 100*clock.Millisecond, clock.Advance(1*clock.Millisecond)) 45 assert.True(t, fired) 46 } 47 ```