...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package leakcheck
16
17 import (
18 "fmt"
19 "strings"
20 "testing"
21 "time"
22 )
23
24 type testErrorfer struct {
25 errorCount int
26 errors []string
27 }
28
29 func (e *testErrorfer) Errorf(format string, args ...interface{}) {
30 e.errors = append(e.errors, fmt.Sprintf(format, args...))
31 e.errorCount++
32 }
33
34 func TestCheck(t *testing.T) {
35 const leakCount = 3
36 for i := 0; i < leakCount; i++ {
37 go func() { time.Sleep(2 * time.Second) }()
38 }
39 if ig := interestingGoroutines(); len(ig) == 0 {
40 t.Error("blah")
41 }
42 e := &testErrorfer{}
43 check(e, time.Second)
44 if e.errorCount != leakCount {
45 t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
46 t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
47 }
48 check(t, 3*time.Second)
49 }
50
51 func ignoredTestingLeak(d time.Duration) {
52 time.Sleep(d)
53 }
54
55 func TestCheckRegisterIgnore(t *testing.T) {
56 RegisterIgnoreGoroutine("ignoredTestingLeak")
57 const leakCount = 3
58 for i := 0; i < leakCount; i++ {
59 go func() { time.Sleep(2 * time.Second) }()
60 }
61 go func() { ignoredTestingLeak(3 * time.Second) }()
62 if ig := interestingGoroutines(); len(ig) == 0 {
63 t.Error("blah")
64 }
65 e := &testErrorfer{}
66 check(e, time.Second)
67 if e.errorCount != leakCount {
68 t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
69 t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
70 }
71 check(t, 3*time.Second)
72 }
73
View as plain text