Debian Codegraph @

test/util.go

raw symbols SCIP
1 package test
2
3 import (
4 "errors"
5 "fmt"
6 "os"
7 "runtime"
8 "runtime/pprof"
9 "strings"
10 "testing"
11 "time"
12 )
13
14 var errFlattenErrs = errors.New("")
15
16 // TimeOut is used to panic if a test takes to long.
17 // It will print the current goroutines and panic.
18 // It is meant as an aid in debugging deadlocks.
19 func TimeOut(t time.Duration) *time.Timer {
20 return time.AfterFunc(t, func() {
21 if err := pprof.Lookup("goroutine").WriteTo(os.Stdout, 1); err != nil {
22 fmt.Printf("failed to print goroutines: %v \n", err) // nolint
23 }
24 panic("timeout") // nolint
25 })
26 }
27
28 // CheckRoutines is used to check for leaked go-routines
29 func CheckRoutines(t *testing.T) func() {
30 tryLoop := func(failMessage string) {
31 try := 0
32 ticker := time.NewTicker(200 * time.Millisecond)
33 defer ticker.Stop()
34 for range ticker.C {
35 runtime.GC()
36 routines := getRoutines()
37 if len(routines) == 0 {
38 return
39 }
40 if try >= 50 {
41 t.Fatalf("%s: \n%s", failMessage, strings.Join(routines, "\n\n")) // nolint
42 }
43 try++
44 }
45 }
46
47 tryLoop("Unexpected routines on test startup")
48 return func() {
49 tryLoop("Unexpected routines on test end")
50 }
51 }
52
53 func getRoutines() []string {
54 buf := make([]byte, 2<<20)
55 buf = buf[:runtime.Stack(buf, true)]
56 return filterRoutines(strings.Split(string(buf), "\n\n"))
57 }
58
59 func filterRoutines(routines []string) []string {
60 result := []string{}
61 for _, stack := range routines {
62 if stack == "" || // Empty
63 filterRoutineWASM(stack) || // WASM specific exception
64 strings.Contains(stack, "testing.Main(") || // Tests
65 strings.Contains(stack, "testing.(*T).Run(") || // Test run
66 strings.Contains(stack, "test.getRoutines(") { // This routine
67 continue
68 }
69 result = append(result, stack)
70 }
71 return result
72 }
73
74 // GatherErrs gathers all errors returned by a channel.
75 // It blocks until the channel is closed.
76 func GatherErrs(c chan error) []error {
77 errs := make([]error, 0)
78
79 for err := range c {
80 errs = append(errs, err)
81 }
82
83 return errs
84 }
85
86 // FlattenErrs flattens a slice of errors into a single error
87 func FlattenErrs(errs []error) error {
88 var errStrings []string
89
90 for _, err := range errs {
91 if err != nil {
92 errStrings = append(errStrings, err.Error())
93 }
94 }
95
96 if len(errStrings) == 0 {
97 return nil
98 }
99
100 return fmt.Errorf("%w %s", errFlattenErrs, strings.Join(errStrings, "\n"))
101 }