github.com/searKing/golang/go@v1.2.117/testing/leakcheck/leakcheck_test.go (about) 1 // Copyright 2020 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package leakcheck 6 7 // it's borrowed from https://github.com/grpc/grpc-go/blob/master/internal/leakcheck/leakcheck_test.go 8 9 import ( 10 "fmt" 11 "strings" 12 "testing" 13 "time" 14 ) 15 16 type testErrorfer struct { 17 errorCount int 18 errors []string 19 } 20 21 func (e *testErrorfer) Errorf(format string, args ...any) { 22 e.errors = append(e.errors, fmt.Sprintf(format, args...)) 23 e.errorCount++ 24 } 25 26 func TestCheck(t *testing.T) { 27 const leakCount = 3 28 for i := 0; i < leakCount; i++ { 29 go func() { time.Sleep(2 * time.Second) }() 30 } 31 if ig := interestingGoroutines(); len(ig) == 0 { 32 t.Error("blah") 33 } 34 e := &testErrorfer{} 35 check(e, time.Second) 36 if e.errorCount != leakCount { 37 t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount) 38 t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n")) 39 } 40 check(t, 3*time.Second) 41 } 42 43 func ignoredTestingLeak(d time.Duration) { 44 time.Sleep(d) 45 } 46 47 func TestCheckRegisterIgnore(t *testing.T) { 48 RegisterIgnoreGoroutine("ignoredTestingLeak") 49 const leakCount = 3 50 for i := 0; i < leakCount; i++ { 51 go func() { time.Sleep(2 * time.Second) }() 52 } 53 go func() { ignoredTestingLeak(3 * time.Second) }() 54 if ig := interestingGoroutines(); len(ig) == 0 { 55 t.Error("blah") 56 } 57 e := &testErrorfer{} 58 check(e, time.Second) 59 if e.errorCount != leakCount { 60 t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount) 61 t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n")) 62 } 63 check(t, 3*time.Second) 64 }