You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

77 lines
1.9 KiB

  1. /*
  2. *
  3. * Copyright 2017 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package leakcheck
  19. import (
  20. "fmt"
  21. "strings"
  22. "testing"
  23. "time"
  24. )
  25. type testErrorfer struct {
  26. errorCount int
  27. errors []string
  28. }
  29. func (e *testErrorfer) Errorf(format string, args ...interface{}) {
  30. e.errors = append(e.errors, fmt.Sprintf(format, args...))
  31. e.errorCount++
  32. }
  33. func TestCheck(t *testing.T) {
  34. const leakCount = 3
  35. for i := 0; i < leakCount; i++ {
  36. go func() { time.Sleep(2 * time.Second) }()
  37. }
  38. if ig := interestingGoroutines(); len(ig) == 0 {
  39. t.Error("blah")
  40. }
  41. e := &testErrorfer{}
  42. check(e, time.Second)
  43. if e.errorCount != leakCount {
  44. t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
  45. t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
  46. }
  47. check(t, 3*time.Second)
  48. }
  49. func ignoredTestingLeak(d time.Duration) {
  50. time.Sleep(d)
  51. }
  52. func TestCheckRegisterIgnore(t *testing.T) {
  53. RegisterIgnoreGoroutine("ignoredTestingLeak")
  54. const leakCount = 3
  55. for i := 0; i < leakCount; i++ {
  56. go func() { time.Sleep(2 * time.Second) }()
  57. }
  58. go func() { ignoredTestingLeak(3 * time.Second) }()
  59. if ig := interestingGoroutines(); len(ig) == 0 {
  60. t.Error("blah")
  61. }
  62. e := &testErrorfer{}
  63. check(e, time.Second)
  64. if e.errorCount != leakCount {
  65. t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
  66. t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
  67. }
  68. check(t, 3*time.Second)
  69. }