OSDN Git Service

new repo
[bytom/vapor.git] / vendor / google.golang.org / grpc / test / leakcheck / leakcheck_test.go
1 /*
2  *
3  * Copyright 2017 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18
19 package leakcheck
20
21 import (
22         "fmt"
23         "strings"
24         "testing"
25         "time"
26 )
27
28 type testErrorfer struct {
29         errorCount int
30         errors     []string
31 }
32
33 func (e *testErrorfer) Errorf(format string, args ...interface{}) {
34         e.errors = append(e.errors, fmt.Sprintf(format, args...))
35         e.errorCount++
36 }
37
38 func TestCheck(t *testing.T) {
39         const leakCount = 3
40         for i := 0; i < leakCount; i++ {
41                 go func() { time.Sleep(2 * time.Second) }()
42         }
43         if ig := interestingGoroutines(); len(ig) == 0 {
44                 t.Error("blah")
45         }
46         e := &testErrorfer{}
47         check(e, time.Second)
48         if e.errorCount != leakCount {
49                 t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
50                 t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
51         }
52         check(t, 3*time.Second)
53 }
54
55 func ignoredTestingLeak(d time.Duration) {
56         time.Sleep(d)
57 }
58
59 func TestCheckRegisterIgnore(t *testing.T) {
60         RegisterIgnoreGoroutine("ignoredTestingLeak")
61         const leakCount = 3
62         for i := 0; i < leakCount; i++ {
63                 go func() { time.Sleep(2 * time.Second) }()
64         }
65         go func() { ignoredTestingLeak(3 * time.Second) }()
66         if ig := interestingGoroutines(); len(ig) == 0 {
67                 t.Error("blah")
68         }
69         e := &testErrorfer{}
70         check(e, time.Second)
71         if e.errorCount != leakCount {
72                 t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
73                 t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
74         }
75         check(t, 3*time.Second)
76 }