Skip to content

Commit

Permalink
store: update leaked goroutines check to TestMain
Browse files Browse the repository at this point in the history
Go 1.4 landed a new testing.M type [1][1] which allows for start-up and
shutdown hooks when running tests. The standard library now uses this
for checking for leaked goroutines in net/http [2][2].

This patch re-ports the updated code from the net/http test. For a
previous example, see etcd-io/etcd#4026

[1]: https://golang.org/pkg/testing/#M
[2]: https://github.com/golang/go/blob/release-branch.go1.4/src/net/http/main_test.go#L18
  • Loading branch information
jonboulle committed Dec 23, 2015
1 parent b88a60e commit cd2569b
Showing 1 changed file with 22 additions and 10 deletions.
32 changes: 22 additions & 10 deletions store/z_last_test.go → store/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
package store

import (
"fmt"
"os"
"runtime"
"sort"
"strings"
Expand All @@ -21,9 +23,10 @@ func interestingGoroutines() (gs []string) {
}
stack := strings.TrimSpace(sl[1])
if stack == "" ||
strings.Contains(stack, "testing.RunTests") ||
strings.Contains(stack, "created by testing.RunTests") ||
strings.Contains(stack, "testing.Main(") ||
strings.Contains(stack, "runtime.goexit") ||
strings.Contains(stack, "github.com/coreos/rkt/store.interestingGoroutines") ||
strings.Contains(stack, "created by runtime.gc") ||
strings.Contains(stack, "runtime.MHeap_Scavenger") {
continue
Expand All @@ -35,10 +38,18 @@ func interestingGoroutines() (gs []string) {
}

// Verify the other tests didn't leave any goroutines running.
// This is in a file named z_last_test.go so it sorts at the end.
func TestGoroutinesRunning(t *testing.T) {
func TestMain(m *testing.M) {
v := m.Run()
if v == 0 && goroutineLeaked() {
os.Exit(1)
}
os.Exit(v)
}

func goroutineLeaked() bool {
if testing.Short() {
t.Skip("not counting goroutines for leakage in -short mode")
// not counting goroutines for leakage in -short mode
return false
}
gs := interestingGoroutines()

Expand All @@ -49,11 +60,12 @@ func TestGoroutinesRunning(t *testing.T) {
n++
}

t.Logf("num goroutines = %d", n)
if n > 0 {
t.Error("Too many goroutines.")
for stack, count := range stackCount {
t.Logf("%d instances of:\n%s", count, stack)
}
if n == 0 {
return false
}
fmt.Fprintf(os.Stderr, "Too many goroutines running after integration test(s).\n")
for stack, count := range stackCount {
fmt.Fprintf(os.Stderr, "%d instances of:\n%s\n", count, stack)
}
return true
}

0 comments on commit cd2569b

Please sign in to comment.