Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 

73 rader
1.9 KiB

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