master
go 49 lines 998 Bytes
Raw
1 // SPDX-License-Identifier: GPL-3.0-or-later
2
3 package ticker
4
5 import (
6 "testing"
7 "time"
8 )
9
10 // TODO: often fails Circle CI (~200-240)
11 var allowedDelta = 500 * time.Millisecond
12
13 func TestTickerParallel(t *testing.T) {
14 for i := range 100 {
15 go func() {
16 time.Sleep(time.Second / 100 * time.Duration(i))
17 TestTicker(t)
18 }()
19 }
20 time.Sleep(4 * time.Second)
21 }
22
23 func TestTicker(t *testing.T) {
24 tk := New(time.Second)
25 defer tk.Stop()
26 prev := time.Now()
27 for i := range 3 {
28 <-tk.C
29 now := time.Now()
30 diff := abs(now.Round(time.Second).Sub(now))
31 if diff >= allowedDelta {
32 t.Errorf("Ticker is not aligned: expect delta < %v but was: %v (%s)", allowedDelta, diff, now.Format(time.RFC3339Nano))
33 }
34 if i > 0 {
35 dt := now.Sub(prev)
36 if abs(dt-time.Second) >= allowedDelta {
37 t.Errorf("Ticker interval: expect delta < %v ns but was: %v", allowedDelta, abs(dt-time.Second))
38 }
39 }
40 prev = now
41 }
42 }
43
44 func abs(a time.Duration) time.Duration {
45 if a < 0 {
46 return -a
47 }
48 return a
49 }