1
// Copyright (c) 2017 Uber Technologies, Inc.
2

3
// Permission is hereby granted, free of charge, to any person obtaining a copy
4
// of this software and associated documentation files (the "Software"), to deal
5
// in the Software without restriction, including without limitation the rights
6
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
// copies of the Software, and to permit persons to whom the Software is
8
// furnished to do so, subject to the following conditions:
9
//
10
// The above copyright notice and this permission notice shall be included in
11
// all copies or substantial portions of the Software.
12
//
13
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19
// THE SOFTWARE.
20

21
package goleak
22

23
import (
24
	"fmt"
25

26
	"go.uber.org/goleak/internal/stack"
27
)
28

29
// TestingT is the minimal subset of testing.TB that we use.
30
type TestingT interface {
31
	Error(...interface{})
32
}
33

34
// filterStacks will filter any stacks excluded by the given opts.
35
// filterStacks modifies the passed in stacks slice.
36
func filterStacks(stacks []stack.Stack, skipID int, opts *opts) []stack.Stack {
37 2
	filtered := stacks[:0]
38
	for _, stack := range stacks {
39
		// Always skip the running goroutine.
40 2
		if stack.ID() == skipID {
41 2
			continue
42
		}
43
		// Run any default or user-specified filters.
44 2
		if opts.filter(stack) {
45 2
			continue
46
		}
47 2
		filtered = append(filtered, stack)
48
	}
49 2
	return filtered
50
}
51

52
// Find looks for extra goroutines, and returns a descriptive error if
53
// any are found.
54
func Find(options ...Option) error {
55 2
	cur := stack.Current().ID()
56

57 2
	opts := buildOpts(options...)
58 2
	var stacks []stack.Stack
59

60
	for retry := opts.newRetry(); retry(); {
61 2
		stacks = filterStacks(stack.All(), cur, opts)
62

63 2
		if len(stacks) == 0 {
64 2
			return nil
65
		}
66
	}
67

68 2
	return fmt.Errorf("found unexpected goroutines:\n%s", stacks)
69
}
70

71
// VerifyNone marks the given TestingT as failed if any extra goroutines are
72
// found by Find. This is a helper method to make it easier to integrate in
73
// tests by doing:
74
// 	defer VerifyNone(t)
75
func VerifyNone(t TestingT, options ...Option) {
76 2
	if err := Find(options...); err != nil {
77 2
		t.Error(err)
78
	}
79
}

Read our documentation on viewing source code .

Loading