Skip to content

Commit 3efa09f

Browse files
time: deflake TestTicker
Take the opportunity of deflaking to make it take less time to run. Updates #35537 Change-Id: I91ca8094fbe18fbfcd34dfda98da1592c9c82943 Reviewed-on: https://go-review.googlesource.com/c/go/+/207403 Run-TryBot: Ian Lance Taylor <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent c726361 commit 3efa09f

File tree

1 file changed

+50
-21
lines changed

1 file changed

+50
-21
lines changed

src/time/tick_test.go

Lines changed: 50 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -5,34 +5,63 @@
55
package time_test
66

77
import (
8+
"fmt"
89
"testing"
910
. "time"
1011
)
1112

1213
func TestTicker(t *testing.T) {
13-
const Count = 10
14-
Delta := 100 * Millisecond
15-
ticker := NewTicker(Delta)
16-
t0 := Now()
17-
for i := 0; i < Count; i++ {
18-
<-ticker.C
19-
}
20-
ticker.Stop()
21-
t1 := Now()
22-
dt := t1.Sub(t0)
23-
target := Delta * Count
24-
slop := target * 2 / 10
25-
if dt < target-slop || (!testing.Short() && dt > target+slop) {
26-
t.Fatalf("%d %s ticks took %s, expected [%s,%s]", Count, Delta, dt, target-slop, target+slop)
14+
// We want to test that a ticker takes as much time as expected.
15+
// Since we don't want the test to run for too long, we don't
16+
// want to use lengthy times. This makes the test inherently flaky.
17+
// So only report an error if it fails five times in a row.
18+
19+
const count = 10
20+
delta := 20 * Millisecond
21+
22+
var errs []string
23+
logErrs := func() {
24+
for _, e := range errs {
25+
t.Log(e)
26+
}
2727
}
28-
// Now test that the ticker stopped
29-
Sleep(2 * Delta)
30-
select {
31-
case <-ticker.C:
32-
t.Fatal("Ticker did not shut down")
33-
default:
34-
// ok
28+
29+
for i := 0; i < 5; i++ {
30+
ticker := NewTicker(delta)
31+
t0 := Now()
32+
for i := 0; i < count; i++ {
33+
<-ticker.C
34+
}
35+
ticker.Stop()
36+
t1 := Now()
37+
dt := t1.Sub(t0)
38+
target := delta * count
39+
slop := target * 2 / 10
40+
if dt < target-slop || dt > target+slop {
41+
errs = append(errs, fmt.Sprintf("%d %s ticks took %s, expected [%s,%s]", count, delta, dt, target-slop, target+slop))
42+
continue
43+
}
44+
// Now test that the ticker stopped.
45+
Sleep(2 * delta)
46+
select {
47+
case <-ticker.C:
48+
errs = append(errs, "Ticker did not shut down")
49+
continue
50+
default:
51+
// ok
52+
}
53+
54+
// Test passed, so all done.
55+
if len(errs) > 0 {
56+
t.Logf("saw %d errors, ignoring to avoid flakiness", len(errs))
57+
logErrs()
58+
}
59+
60+
return
3561
}
62+
63+
t.Errorf("saw %d errors", len(errs))
64+
logErrs()
3665
}
3766

3867
// Issue 21874

0 commit comments

Comments
 (0)