| 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 |
|
| 17 |
|
| 18 |
|
| 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) |
| 23 |
} |
| 24 |
panic("timeout") |
| 25 |
}) |
| 26 |
} |
| 27 |
|
| 28 |
|
| 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")) |
| 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 == "" || |
| 63 |
filterRoutineWASM(stack) || |
| 64 |
strings.Contains(stack, "testing.Main(") || |
| 65 |
strings.Contains(stack, "testing.(*T).Run(") || |
| 66 |
strings.Contains(stack, "test.getRoutines(") { |
| 67 |
continue |
| 68 |
} |
| 69 |
result = append(result, stack) |
| 70 |
} |
| 71 |
return result |
| 72 |
} |
| 73 |
|
| 74 |
|
| 75 |
|
| 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 |
|
| 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 |
} |