...

Source file src/cloud.google.com/go/internal/leakcheck/leakcheck_test.go

Documentation: cloud.google.com/go/internal/leakcheck

     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  
    15  package leakcheck
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  	"testing"
    21  	"time"
    22  )
    23  
    24  type testErrorfer struct {
    25  	errorCount int
    26  	errors     []string
    27  }
    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  
    34  func TestCheck(t *testing.T) {
    35  	const leakCount = 3
    36  	for i := 0; i < leakCount; i++ {
    37  		go func() { time.Sleep(2 * time.Second) }()
    38  	}
    39  	if ig := interestingGoroutines(); len(ig) == 0 {
    40  		t.Error("blah")
    41  	}
    42  	e := &testErrorfer{}
    43  	check(e, time.Second)
    44  	if e.errorCount != leakCount {
    45  		t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
    46  		t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
    47  	}
    48  	check(t, 3*time.Second)
    49  }
    50  
    51  func ignoredTestingLeak(d time.Duration) {
    52  	time.Sleep(d)
    53  }
    54  
    55  func TestCheckRegisterIgnore(t *testing.T) {
    56  	RegisterIgnoreGoroutine("ignoredTestingLeak")
    57  	const leakCount = 3
    58  	for i := 0; i < leakCount; i++ {
    59  		go func() { time.Sleep(2 * time.Second) }()
    60  	}
    61  	go func() { ignoredTestingLeak(3 * time.Second) }()
    62  	if ig := interestingGoroutines(); len(ig) == 0 {
    63  		t.Error("blah")
    64  	}
    65  	e := &testErrorfer{}
    66  	check(e, time.Second)
    67  	if e.errorCount != leakCount {
    68  		t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
    69  		t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
    70  	}
    71  	check(t, 3*time.Second)
    72  }
    73  

View as plain text