Skip to content

Commit dab1a10

Browse files
time: only fail TestAfterStop if it fails five times in a row
The test is inherently slightly flaky, so repeat to reduce flakiness. Fixes #35537 Change-Id: Id918d48d33c7d5e19c4f24df104adc7fbf3720f2 Reviewed-on: https://go-review.googlesource.com/c/go/+/207457 Run-TryBot: Ian Lance Taylor <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]> Reviewed-by: Bryan C. Mills <[email protected]> TryBot-Result: Gobot Gobot <[email protected]>
1 parent acb9ac0 commit dab1a10

File tree

1 file changed

+51
-20
lines changed

1 file changed

+51
-20
lines changed

src/time/sleep_test.go

+51-20
Original file line numberDiff line numberDiff line change
@@ -235,28 +235,59 @@ func TestAfterTick(t *testing.T) {
235235
}
236236

237237
func TestAfterStop(t *testing.T) {
238-
AfterFunc(100*Millisecond, func() {})
239-
t0 := NewTimer(50 * Millisecond)
240-
c1 := make(chan bool, 1)
241-
t1 := AfterFunc(150*Millisecond, func() { c1 <- true })
242-
c2 := After(200 * Millisecond)
243-
if !t0.Stop() {
244-
t.Fatalf("failed to stop event 0")
245-
}
246-
if !t1.Stop() {
247-
t.Fatalf("failed to stop event 1")
248-
}
249-
<-c2
250-
select {
251-
case <-t0.C:
252-
t.Fatalf("event 0 was not stopped")
253-
case <-c1:
254-
t.Fatalf("event 1 was not stopped")
255-
default:
238+
// We want to test that we stop a timer before it runs.
239+
// We also want to test that it didn't run after a longer timer.
240+
// Since we don't want the test to run for too long, we don't
241+
// want to use lengthy times. That makes the test inherently flaky.
242+
// So only report an error if it fails five times in a row.
243+
244+
var errs []string
245+
logErrs := func() {
246+
for _, e := range errs {
247+
t.Log(e)
248+
}
256249
}
257-
if t1.Stop() {
258-
t.Fatalf("Stop returned true twice")
250+
251+
for i := 0; i < 5; i++ {
252+
AfterFunc(100*Millisecond, func() {})
253+
t0 := NewTimer(50 * Millisecond)
254+
c1 := make(chan bool, 1)
255+
t1 := AfterFunc(150*Millisecond, func() { c1 <- true })
256+
c2 := After(200 * Millisecond)
257+
if !t0.Stop() {
258+
errs = append(errs, "failed to stop event 0")
259+
continue
260+
}
261+
if !t1.Stop() {
262+
errs = append(errs, "failed to stop event 1")
263+
continue
264+
}
265+
<-c2
266+
select {
267+
case <-t0.C:
268+
errs = append(errs, "event 0 was not stopped")
269+
continue
270+
case <-c1:
271+
errs = append(errs, "event 1 was not stopped")
272+
continue
273+
default:
274+
}
275+
if t1.Stop() {
276+
errs = append(errs, "Stop returned true twice")
277+
continue
278+
}
279+
280+
// Test passed, so all done.
281+
if len(errs) > 0 {
282+
t.Logf("saw %d errors, ignoring to avoid flakiness", len(errs))
283+
logErrs()
284+
}
285+
286+
return
259287
}
288+
289+
t.Errorf("saw %d errors", len(errs))
290+
logErrs()
260291
}
261292

262293
func TestAfterQueuing(t *testing.T) {

0 commit comments

Comments
 (0)