Skip to content

Commit 46185f2

Browse files
committed
Fix flaky test TestSubscribeWithContextDone
Instead of comparing the number of goroutines which is inherently unreliable, we count the number of goroutines that exited using a defer statement, and an atomic counter. By the way, the timer are reduced to 100ms as it is more than enough time to let the goroutines exit. Closes: #186
1 parent c6d5381 commit 46185f2

File tree

1 file changed

+12
-9
lines changed

1 file changed

+12
-9
lines changed

client_test.go

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
"encoding/hex"
1111
"net/http"
1212
"net/http/httptest"
13-
"runtime"
13+
"sync/atomic"
1414
"testing"
1515
"time"
1616

@@ -400,25 +400,28 @@ func TestTrimHeader(t *testing.T) {
400400
}
401401
}
402402

403+
// Verify that cancelling the context really terminates the execution.
403404
func TestSubscribeWithContextDone(t *testing.T) {
404405
setup(false)
405406
defer cleanup()
406407

407408
ctx, cancel := context.WithCancel(context.Background())
408409

409-
var n1 = runtime.NumGoroutine()
410+
var launched int32 = 10
411+
var exited int32
410412

411413
c := NewClient(urlPath)
412414

413-
for i := 0; i < 10; i++ {
414-
go c.SubscribeWithContext(ctx, "test", func(msg *Event) {})
415+
for i := 0; i < int(launched); i++ {
416+
go func() {
417+
defer atomic.AddInt32(&exited, 1)
418+
c.SubscribeWithContext(ctx, "test", func(msg *Event) {})
419+
}()
415420
}
416421

417-
time.Sleep(1 * time.Second)
422+
time.Sleep(100 * time.Millisecond)
418423
cancel()
419424

420-
time.Sleep(1 * time.Second)
421-
var n2 = runtime.NumGoroutine()
422-
423-
assert.Equal(t, n1, n2)
425+
time.Sleep(100 * time.Millisecond)
426+
assert.Equal(t, launched, exited)
424427
}

0 commit comments

Comments
 (0)