github.com/cloudwego/kitex@v0.9.0/pkg/remote/trans/nphttp2/grpc/testutils/leakcheck/leakcheck_test.go (about)

     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   * This file may have been modified by CloudWeGo authors. All CloudWeGo
    18   * Modifications are Copyright 2021 CloudWeGo Authors.
    19   */
    20  
    21  package leakcheck
    22  
    23  import (
    24  	"fmt"
    25  	"strings"
    26  	"testing"
    27  	"time"
    28  )
    29  
    30  type testErrorfer struct {
    31  	errorCount int
    32  	errors     []string
    33  }
    34  
    35  func (e *testErrorfer) Errorf(format string, args ...interface{}) {
    36  	e.errors = append(e.errors, fmt.Sprintf(format, args...))
    37  	e.errorCount++
    38  }
    39  
    40  func TestCheck(t *testing.T) {
    41  	const leakCount = 3
    42  	for i := 0; i < leakCount; i++ {
    43  		go func() { time.Sleep(2 * time.Second) }()
    44  	}
    45  	if ig := interestingGoroutines(); len(ig) == 0 {
    46  		t.Error("blah")
    47  	}
    48  	e := &testErrorfer{}
    49  	check(e, time.Second)
    50  	if e.errorCount != leakCount {
    51  		t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
    52  		t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
    53  	}
    54  	check(t, 3*time.Second)
    55  }
    56  
    57  func ignoredTestingLeak(d time.Duration) {
    58  	time.Sleep(d)
    59  }
    60  
    61  func TestCheckRegisterIgnore(t *testing.T) {
    62  	RegisterIgnoreGoroutine("ignoredTestingLeak")
    63  	const leakCount = 3
    64  	for i := 0; i < leakCount; i++ {
    65  		go func() { time.Sleep(2 * time.Second) }()
    66  	}
    67  	go func() { ignoredTestingLeak(3 * time.Second) }()
    68  	if ig := interestingGoroutines(); len(ig) == 0 {
    69  		t.Error("blah")
    70  	}
    71  	e := &testErrorfer{}
    72  	check(e, time.Second)
    73  	if e.errorCount != leakCount {
    74  		t.Errorf("check found %v leaks, want %v leaks", e.errorCount, leakCount)
    75  		t.Logf("leaked goroutines:\n%v", strings.Join(e.errors, "\n"))
    76  	}
    77  	check(t, 3*time.Second)
    78  }