z_last_test.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package etcdserver
  5. import (
  6. "net/http"
  7. "runtime"
  8. "sort"
  9. "strings"
  10. "testing"
  11. "time"
  12. )
  13. func interestingGoroutines() (gs []string) {
  14. buf := make([]byte, 2<<20)
  15. buf = buf[:runtime.Stack(buf, true)]
  16. for _, g := range strings.Split(string(buf), "\n\n") {
  17. sl := strings.SplitN(g, "\n", 2)
  18. if len(sl) != 2 {
  19. continue
  20. }
  21. stack := strings.TrimSpace(sl[1])
  22. if stack == "" ||
  23. strings.Contains(stack, "created by testing.RunTests") ||
  24. strings.Contains(stack, "testing.Main(") ||
  25. strings.Contains(stack, "runtime.goexit") ||
  26. strings.Contains(stack, "created by runtime.gc") ||
  27. strings.Contains(stack, "runtime.MHeap_Scavenger") {
  28. continue
  29. }
  30. gs = append(gs, stack)
  31. }
  32. sort.Strings(gs)
  33. return
  34. }
  35. // Verify the other tests didn't leave any goroutines running.
  36. // This is in a file named z_last_test.go so it sorts at the end.
  37. func TestGoroutinesRunning(t *testing.T) {
  38. if testing.Short() {
  39. t.Skip("not counting goroutines for leakage in -short mode")
  40. }
  41. gs := interestingGoroutines()
  42. n := 0
  43. stackCount := make(map[string]int)
  44. for _, g := range gs {
  45. stackCount[g]++
  46. n++
  47. }
  48. t.Logf("num goroutines = %d", n)
  49. if n > 0 {
  50. t.Error("Too many goroutines.")
  51. for stack, count := range stackCount {
  52. t.Logf("%d instances of:\n%s", count, stack)
  53. }
  54. }
  55. }
  56. func afterTest(t *testing.T) {
  57. http.DefaultTransport.(*http.Transport).CloseIdleConnections()
  58. if testing.Short() {
  59. return
  60. }
  61. var bad string
  62. badSubstring := map[string]string{
  63. ").readLoop(": "a Transport",
  64. ").writeLoop(": "a Transport",
  65. "created by net/http/httptest.(*Server).Start": "an httptest.Server",
  66. "timeoutHandler": "a TimeoutHandler",
  67. "net.(*netFD).connect(": "a timing out dial",
  68. ").noteClientGone(": "a closenotifier sender",
  69. }
  70. var stacks string
  71. for i := 0; i < 6; i++ {
  72. bad = ""
  73. stacks = strings.Join(interestingGoroutines(), "\n\n")
  74. for substr, what := range badSubstring {
  75. if strings.Contains(stacks, substr) {
  76. bad = what
  77. }
  78. }
  79. if bad == "" {
  80. return
  81. }
  82. // Bad stuff found, but goroutines might just still be
  83. // shutting down, so give it some time.
  84. time.Sleep(50 * time.Millisecond)
  85. }
  86. t.Errorf("Test appears to have leaked %s:\n%s", bad, stacks)
  87. }