Skip to content

Commit b89909b

Browse files
leakcheck: Fix flaky test TestCheck (#8309)
1 parent 709023d commit b89909b

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

internal/leakcheck/leakcheck_test.go

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -44,20 +44,21 @@ func (e *testLogger) Errorf(format string, args ...any) {
4444

4545
func TestCheck(t *testing.T) {
4646
const leakCount = 3
47+
ch := make(chan struct{})
4748
for i := 0; i < leakCount; i++ {
48-
go func() { time.Sleep(2 * time.Second) }()
49+
go func() { <-ch }()
4950
}
50-
if ig := interestingGoroutines(); len(ig) == 0 {
51-
t.Error("blah")
51+
if leaked := interestingGoroutines(); len(leaked) != leakCount {
52+
t.Errorf("interestingGoroutines() = %d, want length %d", len(leaked), leakCount)
5253
}
5354
e := &testLogger{}
5455
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
5556
defer cancel()
56-
CheckGoroutines(ctx, e)
57-
if e.errorCount != leakCount {
58-
t.Errorf("CheckGoroutines found %v leaks, want %v leaks", e.errorCount, leakCount)
57+
if CheckGoroutines(ctx, e); e.errorCount < leakCount {
58+
t.Errorf("CheckGoroutines() = %d, want count %d", e.errorCount, leakCount)
5959
t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
6060
}
61+
close(ch)
6162
ctx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
6263
defer cancel()
6364
CheckGoroutines(ctx, t)
@@ -69,22 +70,23 @@ func ignoredTestingLeak(d time.Duration) {
6970

7071
func TestCheckRegisterIgnore(t *testing.T) {
7172
RegisterIgnoreGoroutine("ignoredTestingLeak")
73+
go ignoredTestingLeak(3 * time.Second)
7274
const leakCount = 3
75+
ch := make(chan struct{})
7376
for i := 0; i < leakCount; i++ {
74-
go func() { time.Sleep(2 * time.Second) }()
77+
go func() { <-ch }()
7578
}
76-
go func() { ignoredTestingLeak(3 * time.Second) }()
77-
if ig := interestingGoroutines(); len(ig) == 0 {
78-
t.Error("blah")
79+
if leaked := interestingGoroutines(); len(leaked) != leakCount {
80+
t.Errorf("interestingGoroutines() = %d, want length %d", len(leaked), leakCount)
7981
}
8082
e := &testLogger{}
8183
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
8284
defer cancel()
83-
CheckGoroutines(ctx, e)
84-
if e.errorCount != leakCount {
85-
t.Errorf("CheckGoroutines found %v leaks, want %v leaks", e.errorCount, leakCount)
85+
if CheckGoroutines(ctx, e); e.errorCount < leakCount {
86+
t.Errorf("CheckGoroutines() = %d, want count %d", e.errorCount, leakCount)
8687
t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
8788
}
89+
close(ch)
8890
ctx, cancel = context.WithTimeout(context.Background(), 3*time.Second)
8991
defer cancel()
9092
CheckGoroutines(ctx, t)

0 commit comments

Comments
 (0)