grpctest: add new package to manage tests and support per-test setup/teardown (#2523)

- Migrate `grpc` & `grpc/test` packages to use `Teardown` support to guarantee `leakcheck` is used
This commit is contained in:
Doug Fawley 2019-01-07 14:24:56 -08:00 коммит произвёл GitHub
Родитель e441557ee9
Коммит 0a391ff2b7
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
25 изменённых файлов: 429 добавлений и 505 удалений

Просмотреть файл

@ -30,7 +30,6 @@ import (
"google.golang.org/grpc/connectivity"
_ "google.golang.org/grpc/grpclog/glogger"
"google.golang.org/grpc/internal"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/resolver/manual"
)
@ -129,8 +128,7 @@ func checkRoundRobin(cc *ClientConn, servers []*server) error {
return nil
}
func TestSwitchBalancer(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestSwitchBalancer(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -161,8 +159,7 @@ func TestSwitchBalancer(t *testing.T) {
}
// Test that balancer specified by dial option will not be overridden.
func TestBalancerDialOption(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestBalancerDialOption(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -189,8 +186,7 @@ func TestBalancerDialOption(t *testing.T) {
}
// First addr update contains grpclb.
func TestSwitchBalancerGRPCLBFirst(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestSwitchBalancerGRPCLBFirst(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -251,8 +247,7 @@ func TestSwitchBalancerGRPCLBFirst(t *testing.T) {
}
// First addr update does not contain grpclb.
func TestSwitchBalancerGRPCLBSecond(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestSwitchBalancerGRPCLBSecond(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -329,8 +324,7 @@ func TestSwitchBalancerGRPCLBSecond(t *testing.T) {
// Test that if the current balancer is roundrobin, after switching to grpclb,
// when the resolved address doesn't contain grpclb addresses, balancer will be
// switched back to roundrobin.
func TestSwitchBalancerGRPCLBRoundRobin(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestSwitchBalancerGRPCLBRoundRobin(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -393,8 +387,7 @@ func TestSwitchBalancerGRPCLBRoundRobin(t *testing.T) {
// Test that if resolved address list contains grpclb, the balancer option in
// service config won't take effect. But when there's no grpclb address in a new
// resolved address list, balancer will be switched to the new one.
func TestSwitchBalancerGRPCLBServiceConfig(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestSwitchBalancerGRPCLBServiceConfig(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -476,11 +469,10 @@ func TestSwitchBalancerGRPCLBServiceConfig(t *testing.T) {
// The tests sends 3 server addresses (all backends) as resolved addresses, but
// claim the first one is grpclb server. The all RPCs should all be send to the
// other addresses, not the first one.
func TestSwitchBalancerGRPCLBWithGRPCLBNotRegistered(t *testing.T) {
func (s) TestSwitchBalancerGRPCLBWithGRPCLBNotRegistered(t *testing.T) {
internal.BalancerUnregister("grpclb")
defer balancer.Register(&magicalLB{})
defer leakcheck.Check(t)
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()

Просмотреть файл

@ -29,7 +29,6 @@ import (
"google.golang.org/grpc/codes"
_ "google.golang.org/grpc/grpclog/glogger"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/naming"
"google.golang.org/grpc/status"
@ -121,8 +120,7 @@ func startServers(t *testing.T, numServers int, maxStreams uint32) ([]*server, *
}
}
func TestNameDiscovery(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestNameDiscovery(t *testing.T) {
// Start 2 servers on 2 ports.
numServers := 2
servers, r, cleanup := startServers(t, numServers, math.MaxUint32)
@ -157,8 +155,7 @@ func TestNameDiscovery(t *testing.T) {
}
}
func TestEmptyAddrs(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestEmptyAddrs(t *testing.T) {
servers, r, cleanup := startServers(t, 1, math.MaxUint32)
defer cleanup()
cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{}))
@ -189,8 +186,7 @@ func TestEmptyAddrs(t *testing.T) {
}
}
func TestRoundRobin(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestRoundRobin(t *testing.T) {
// Start 3 servers on 3 ports.
numServers := 3
servers, r, cleanup := startServers(t, numServers, math.MaxUint32)
@ -236,8 +232,7 @@ func TestRoundRobin(t *testing.T) {
}
}
func TestCloseWithPendingRPC(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCloseWithPendingRPC(t *testing.T) {
servers, r, cleanup := startServers(t, 1, math.MaxUint32)
defer cleanup()
cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{}))
@ -288,8 +283,7 @@ func TestCloseWithPendingRPC(t *testing.T) {
wg.Wait()
}
func TestGetOnWaitChannel(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestGetOnWaitChannel(t *testing.T) {
servers, r, cleanup := startServers(t, 1, math.MaxUint32)
defer cleanup()
cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{}))
@ -332,8 +326,7 @@ func TestGetOnWaitChannel(t *testing.T) {
wg.Wait()
}
func TestOneServerDown(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestOneServerDown(t *testing.T) {
// Start 2 servers.
numServers := 2
servers, r, cleanup := startServers(t, numServers, math.MaxUint32)
@ -385,8 +378,7 @@ func TestOneServerDown(t *testing.T) {
wg.Wait()
}
func TestOneAddressRemoval(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestOneAddressRemoval(t *testing.T) {
// Start 2 servers.
numServers := 2
servers, r, cleanup := startServers(t, numServers, math.MaxUint32)
@ -463,8 +455,7 @@ func checkServerUp(t *testing.T, currentServer *server) {
}
}
func TestPickFirstEmptyAddrs(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestPickFirstEmptyAddrs(t *testing.T) {
servers, r, cleanup := startServers(t, 1, math.MaxUint32)
defer cleanup()
cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{}))
@ -495,8 +486,7 @@ func TestPickFirstEmptyAddrs(t *testing.T) {
}
}
func TestPickFirstCloseWithPendingRPC(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestPickFirstCloseWithPendingRPC(t *testing.T) {
servers, r, cleanup := startServers(t, 1, math.MaxUint32)
defer cleanup()
cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(pickFirstBalancerV1(r)), WithBlock(), WithInsecure(), WithCodec(testCodec{}))
@ -547,8 +537,7 @@ func TestPickFirstCloseWithPendingRPC(t *testing.T) {
wg.Wait()
}
func TestPickFirstOrderAllServerUp(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestPickFirstOrderAllServerUp(t *testing.T) {
// Start 3 servers on 3 ports.
numServers := 3
servers, r, cleanup := startServers(t, numServers, math.MaxUint32)
@ -660,8 +649,7 @@ func TestPickFirstOrderAllServerUp(t *testing.T) {
}
}
func TestPickFirstOrderOneServerDown(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestPickFirstOrderOneServerDown(t *testing.T) {
// Start 3 servers on 3 ports.
numServers := 3
servers, r, cleanup := startServers(t, numServers, math.MaxUint32)
@ -751,8 +739,7 @@ func TestPickFirstOrderOneServerDown(t *testing.T) {
}
}
func TestPickFirstOneAddressRemoval(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestPickFirstOneAddressRemoval(t *testing.T) {
// Start 2 servers.
numServers := 2
servers, r, cleanup := startServers(t, numServers, math.MaxUint32)

Просмотреть файл

@ -31,7 +31,6 @@ import (
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/internal/transport"
"google.golang.org/grpc/status"
)
@ -214,8 +213,7 @@ func setUp(t *testing.T, port int, maxStreams uint32) (*server, *ClientConn) {
return server, cc
}
func TestInvoke(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestInvoke(t *testing.T) {
server, cc := setUp(t, 0, math.MaxUint32)
var reply string
if err := cc.Invoke(context.Background(), "/foo/bar", &expectedRequest, &reply); err != nil || reply != expectedResponse {
@ -225,8 +223,7 @@ func TestInvoke(t *testing.T) {
server.stop()
}
func TestInvokeLargeErr(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestInvokeLargeErr(t *testing.T) {
server, cc := setUp(t, 0, math.MaxUint32)
var reply string
req := "hello"
@ -242,8 +239,7 @@ func TestInvokeLargeErr(t *testing.T) {
}
// TestInvokeErrorSpecialChars checks that error messages don't get mangled.
func TestInvokeErrorSpecialChars(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestInvokeErrorSpecialChars(t *testing.T) {
server, cc := setUp(t, 0, math.MaxUint32)
var reply string
req := "weird error"
@ -259,8 +255,7 @@ func TestInvokeErrorSpecialChars(t *testing.T) {
}
// TestInvokeCancel checks that an Invoke with a canceled context is not sent.
func TestInvokeCancel(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestInvokeCancel(t *testing.T) {
server, cc := setUp(t, 0, math.MaxUint32)
var reply string
req := "canceled"
@ -278,8 +273,7 @@ func TestInvokeCancel(t *testing.T) {
// TestInvokeCancelClosedNonFail checks that a canceled non-failfast RPC
// on a closed client will terminate.
func TestInvokeCancelClosedNonFailFast(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestInvokeCancelClosedNonFailFast(t *testing.T) {
server, cc := setUp(t, 0, math.MaxUint32)
var reply string
cc.Close()

Просмотреть файл

@ -29,7 +29,6 @@ import (
"golang.org/x/net/http2"
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/internal/testutils"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/resolver/manual"
@ -46,9 +45,7 @@ func init() {
// These tests use a pipeListener. This listener is similar to net.Listener
// except that it is unbuffered, so each read and write will wait for the other
// side's corresponding write or read.
func TestStateTransitions_SingleAddress(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestStateTransitions_SingleAddress(t *testing.T) {
mctBkp := getMinConnectTimeout()
defer func() {
atomic.StoreInt64((*int64)(&mutableMinConnectTimeout), int64(mctBkp))
@ -151,8 +148,6 @@ client enters TRANSIENT FAILURE.`,
}
func testStateTransitionSingleAddress(t *testing.T, want []connectivity.State, server func(net.Listener) net.Conn) {
defer leakcheck.Check(t)
stateNotifications := make(chan connectivity.State, len(want))
testBalancer.ResetNotifier(stateNotifications)
@ -202,9 +197,7 @@ func testStateTransitionSingleAddress(t *testing.T, want []connectivity.State, s
}
// When a READY connection is closed, the client enters TRANSIENT FAILURE before CONNECTING.
func TestStateTransitions_ReadyToTransientFailure(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestStateTransitions_ReadyToTransientFailure(t *testing.T) {
want := []connectivity.State{
connectivity.Connecting,
connectivity.Ready,
@ -273,9 +266,7 @@ func TestStateTransitions_ReadyToTransientFailure(t *testing.T) {
// When the first connection is closed, the client enters stays in CONNECTING
// until it tries the second address (which succeeds, and then it enters READY).
func TestStateTransitions_TriesAllAddrsBeforeTransientFailure(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestStateTransitions_TriesAllAddrsBeforeTransientFailure(t *testing.T) {
want := []connectivity.State{
connectivity.Connecting,
connectivity.Ready,
@ -370,9 +361,7 @@ func TestStateTransitions_TriesAllAddrsBeforeTransientFailure(t *testing.T) {
// When there are multiple addresses, and we enter READY on one of them, a
// later closure should cause the client to enter TRANSIENT FAILURE before it
// re-enters CONNECTING.
func TestStateTransitions_MultipleAddrsEntersReady(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestStateTransitions_MultipleAddrsEntersReady(t *testing.T) {
want := []connectivity.State{
connectivity.Connecting,
connectivity.Ready,

Просмотреть файл

@ -33,7 +33,6 @@ import (
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/internal/backoff"
"google.golang.org/grpc/internal/envconfig"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/internal/transport"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/naming"
@ -62,8 +61,7 @@ func assertState(wantState connectivity.State, cc *ClientConn) (connectivity.Sta
return state, state == wantState
}
func TestDialWithMultipleBackendsNotSendingServerPreface(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestDialWithMultipleBackendsNotSendingServerPreface(t *testing.T) {
numServers := 2
servers := make([]net.Listener, numServers)
var err error
@ -147,13 +145,11 @@ var reqHSBeforeSuccess = []envconfig.RequireHandshakeSetting{
envconfig.RequireHandshakeHybrid,
}
func TestDialWaitsForServerSettings(t *testing.T) {
func (s) TestDialWaitsForServerSettings(t *testing.T) {
// Restore current setting after test.
old := envconfig.RequireHandshake
defer func() { envconfig.RequireHandshake = old }()
defer leakcheck.Check(t)
// Test with all environment variable settings, which should not impact the
// test case since WithWaitForHandshake has higher priority.
for _, setting := range allReqHSSettings {
@ -204,14 +200,12 @@ func TestDialWaitsForServerSettings(t *testing.T) {
}
}
func TestDialWaitsForServerSettingsViaEnv(t *testing.T) {
func (s) TestDialWaitsForServerSettingsViaEnv(t *testing.T) {
// Set default behavior and restore current setting after test.
old := envconfig.RequireHandshake
envconfig.RequireHandshake = envconfig.RequireHandshakeOn
defer func() { envconfig.RequireHandshake = old }()
defer leakcheck.Check(t)
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Error while listening. Err: %v", err)
@ -257,13 +251,11 @@ func TestDialWaitsForServerSettingsViaEnv(t *testing.T) {
<-done
}
func TestDialWaitsForServerSettingsAndFails(t *testing.T) {
func (s) TestDialWaitsForServerSettingsAndFails(t *testing.T) {
// Restore current setting after test.
old := envconfig.RequireHandshake
defer func() { envconfig.RequireHandshake = old }()
defer leakcheck.Check(t)
for _, setting := range allReqHSSettings {
envconfig.RequireHandshake = setting
lis, err := net.Listen("tcp", "localhost:0")
@ -305,14 +297,12 @@ func TestDialWaitsForServerSettingsAndFails(t *testing.T) {
}
}
func TestDialWaitsForServerSettingsViaEnvAndFails(t *testing.T) {
func (s) TestDialWaitsForServerSettingsViaEnvAndFails(t *testing.T) {
// Set default behavior and restore current setting after test.
old := envconfig.RequireHandshake
envconfig.RequireHandshake = envconfig.RequireHandshakeOn
defer func() { envconfig.RequireHandshake = old }()
defer leakcheck.Check(t)
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Error while listening. Err: %v", err)
@ -351,13 +341,11 @@ func TestDialWaitsForServerSettingsViaEnvAndFails(t *testing.T) {
<-done
}
func TestDialDoesNotWaitForServerSettings(t *testing.T) {
func (s) TestDialDoesNotWaitForServerSettings(t *testing.T) {
// Restore current setting after test.
old := envconfig.RequireHandshake
defer func() { envconfig.RequireHandshake = old }()
defer leakcheck.Check(t)
// Test with "off" and "hybrid".
for _, setting := range reqNoHSSettings {
envconfig.RequireHandshake = setting
@ -397,7 +385,7 @@ func TestDialDoesNotWaitForServerSettings(t *testing.T) {
}
}
func TestCloseConnectionWhenServerPrefaceNotReceived(t *testing.T) {
func (s) TestCloseConnectionWhenServerPrefaceNotReceived(t *testing.T) {
// Restore current setting after test.
old := envconfig.RequireHandshake
defer func() { envconfig.RequireHandshake = old }()
@ -406,7 +394,6 @@ func TestCloseConnectionWhenServerPrefaceNotReceived(t *testing.T) {
// 2. After minConnectTimeout(500 ms here), client disconnects and retries.
// 3. The new server sends its preface.
// 4. Client doesn't kill the connection this time.
defer leakcheck.Check(t)
cleanup := setMinConnectTimeout(time.Millisecond * 500)
defer cleanup()
@ -486,8 +473,7 @@ func TestCloseConnectionWhenServerPrefaceNotReceived(t *testing.T) {
}
}
func TestBackoffWhenNoServerPrefaceReceived(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestBackoffWhenNoServerPrefaceReceived(t *testing.T) {
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Error while listening. Err: %v", err)
@ -533,8 +519,7 @@ func TestBackoffWhenNoServerPrefaceReceived(t *testing.T) {
}
func TestConnectivityStates(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestConnectivityStates(t *testing.T) {
servers, resolver, cleanup := startServers(t, 2, math.MaxUint32)
defer cleanup()
cc, err := Dial("passthrough:///foo.bar.com", WithBalancer(RoundRobin(resolver)), WithInsecure())
@ -570,8 +555,7 @@ func TestConnectivityStates(t *testing.T) {
}
func TestWithTimeout(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestWithTimeout(t *testing.T) {
conn, err := Dial("passthrough:///Non-Existent.Server:80", WithTimeout(time.Millisecond), WithBlock(), WithInsecure())
if err == nil {
conn.Close()
@ -581,10 +565,9 @@ func TestWithTimeout(t *testing.T) {
}
}
func TestWithTransportCredentialsTLS(t *testing.T) {
func (s) TestWithTransportCredentialsTLS(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
defer cancel()
defer leakcheck.Check(t)
creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com")
if err != nil {
t.Fatalf("Failed to create credentials %v", err)
@ -598,8 +581,7 @@ func TestWithTransportCredentialsTLS(t *testing.T) {
}
}
func TestDefaultAuthority(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestDefaultAuthority(t *testing.T) {
target := "Non-Existent.Server:8080"
conn, err := Dial(target, WithInsecure())
if err != nil {
@ -611,8 +593,7 @@ func TestDefaultAuthority(t *testing.T) {
}
}
func TestTLSServerNameOverwrite(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestTLSServerNameOverwrite(t *testing.T) {
overwriteServerName := "over.write.server.name"
creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), overwriteServerName)
if err != nil {
@ -628,8 +609,7 @@ func TestTLSServerNameOverwrite(t *testing.T) {
}
}
func TestWithAuthority(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestWithAuthority(t *testing.T) {
overwriteServerName := "over.write.server.name"
conn, err := Dial("passthrough:///Non-Existent.Server:80", WithInsecure(), WithAuthority(overwriteServerName))
if err != nil {
@ -641,8 +621,7 @@ func TestWithAuthority(t *testing.T) {
}
}
func TestWithAuthorityAndTLS(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestWithAuthorityAndTLS(t *testing.T) {
overwriteServerName := "over.write.server.name"
creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), overwriteServerName)
if err != nil {
@ -658,8 +637,7 @@ func TestWithAuthorityAndTLS(t *testing.T) {
}
}
func TestDialContextCancel(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestDialContextCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
if _, err := DialContext(ctx, "Non-Existent.Server:80", WithBlock(), WithInsecure()); err != context.Canceled {
@ -672,8 +650,7 @@ type failFastError struct{}
func (failFastError) Error() string { return "failfast" }
func (failFastError) Temporary() bool { return false }
func TestDialContextFailFast(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestDialContextFailFast(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
failErr := failFastError{}
@ -713,8 +690,7 @@ func (b *blockingBalancer) Close() error {
return nil
}
func TestDialWithBlockingBalancer(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestDialWithBlockingBalancer(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
dialDone := make(chan struct{})
go func() {
@ -736,8 +712,7 @@ func (c securePerRPCCredentials) RequireTransportSecurity() bool {
return true
}
func TestCredentialsMisuse(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCredentialsMisuse(t *testing.T) {
tlsCreds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com")
if err != nil {
t.Fatalf("Failed to create authenticator %v", err)
@ -752,20 +727,17 @@ func TestCredentialsMisuse(t *testing.T) {
}
}
func TestWithBackoffConfigDefault(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestWithBackoffConfigDefault(t *testing.T) {
testBackoffConfigSet(t, &DefaultBackoffConfig)
}
func TestWithBackoffConfig(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestWithBackoffConfig(t *testing.T) {
b := BackoffConfig{MaxDelay: DefaultBackoffConfig.MaxDelay / 2}
expected := b
testBackoffConfigSet(t, &expected, WithBackoffConfig(b))
}
func TestWithBackoffMaxDelay(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestWithBackoffMaxDelay(t *testing.T) {
md := DefaultBackoffConfig.MaxDelay / 2
expected := BackoffConfig{MaxDelay: md}
testBackoffConfigSet(t, &expected, WithBackoffMaxDelay(md))
@ -822,8 +794,7 @@ func (b *emptyBalancer) Close() error {
return nil
}
func TestNonblockingDialWithEmptyBalancer(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestNonblockingDialWithEmptyBalancer(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
dialDone := make(chan error)
@ -841,8 +812,7 @@ func TestNonblockingDialWithEmptyBalancer(t *testing.T) {
}
}
func TestResolverServiceConfigBeforeAddressNotPanic(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestResolverServiceConfigBeforeAddressNotPanic(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -859,8 +829,7 @@ func TestResolverServiceConfigBeforeAddressNotPanic(t *testing.T) {
time.Sleep(time.Second) // Sleep to make sure the service config is handled by ClientConn.
}
func TestResolverServiceConfigWhileClosingNotPanic(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestResolverServiceConfigWhileClosingNotPanic(t *testing.T) {
for i := 0; i < 10; i++ { // Run this multiple times to make sure it doesn't panic.
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -875,8 +844,7 @@ func TestResolverServiceConfigWhileClosingNotPanic(t *testing.T) {
}
}
func TestResolverEmptyUpdateNotPanic(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestResolverEmptyUpdateNotPanic(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -892,8 +860,7 @@ func TestResolverEmptyUpdateNotPanic(t *testing.T) {
time.Sleep(time.Second) // Sleep to make sure the service config is handled by ClientConn.
}
func TestClientUpdatesParamsAfterGoAway(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestClientUpdatesParamsAfterGoAway(t *testing.T) {
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("Failed to listen. Err: %v", err)
@ -921,7 +888,7 @@ func TestClientUpdatesParamsAfterGoAway(t *testing.T) {
}
}
func TestDisableServiceConfigOption(t *testing.T) {
func (s) TestDisableServiceConfigOption(t *testing.T) {
r, cleanup := manual.GenerateAndRegisterManualResolver()
defer cleanup()
addr := r.Scheme() + ":///non.existent"
@ -950,7 +917,7 @@ func TestDisableServiceConfigOption(t *testing.T) {
}
}
func TestGetClientConnTarget(t *testing.T) {
func (s) TestGetClientConnTarget(t *testing.T) {
addr := "nonexist:///non.existent"
cc, err := Dial(addr, WithInsecure())
if err != nil {
@ -966,8 +933,7 @@ type backoffForever struct{}
func (b backoffForever) Backoff(int) time.Duration { return time.Duration(math.MaxInt64) }
func TestResetConnectBackoff(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestResetConnectBackoff(t *testing.T) {
dials := make(chan struct{})
defer func() { // If we fail, let the http2client break out of dialing.
select {
@ -1005,8 +971,7 @@ func TestResetConnectBackoff(t *testing.T) {
}
}
func TestBackoffCancel(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestBackoffCancel(t *testing.T) {
dialStrCh := make(chan string)
cc, err := Dial("any", WithInsecure(), WithDialer(func(t string, _ time.Duration) (net.Conn, error) {
dialStrCh <- t
@ -1022,7 +987,7 @@ func TestBackoffCancel(t *testing.T) {
// UpdateAddresses should cause the next reconnect to begin from the top of the
// list if the connection is not READY.
func TestUpdateAddresses_RetryFromFirstAddr(t *testing.T) {
func (s) TestUpdateAddresses_RetryFromFirstAddr(t *testing.T) {
cleanup := setMinConnectTimeout(time.Hour)
defer cleanup()

Просмотреть файл

@ -25,7 +25,7 @@ import (
"google.golang.org/grpc/encoding/proto"
)
func TestGetCodecForProtoIsNotNil(t *testing.T) {
func (s) TestGetCodecForProtoIsNotNil(t *testing.T) {
if encoding.GetCodec(proto.Name) == nil {
t.Fatalf("encoding.GetCodec(%q) must not be nil by default", proto.Name)
}

36
grpc_test.go Normal file
Просмотреть файл

@ -0,0 +1,36 @@
/*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package grpc
import (
"testing"
"google.golang.org/grpc/internal/grpctest"
"google.golang.org/grpc/internal/leakcheck"
)
type s struct{}
func (s) Teardown(t *testing.T) {
leakcheck.Check(t)
}
func Test(t *testing.T) {
grpctest.RunSubTests(t, s{})
}

Просмотреть файл

@ -0,0 +1,61 @@
/*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// Package grpctest implements testing helpers.
package grpctest
import (
"reflect"
"strings"
"testing"
)
func getTestFunc(t *testing.T, xv reflect.Value, name string) func(*testing.T) {
if m := xv.MethodByName(name); m.IsValid() {
if f, ok := m.Interface().(func(*testing.T)); ok {
return f
}
// Method exists but has the wrong type signature.
t.Fatalf("grpctest: function %v has unexpected signature (%T)", name, m.Interface())
}
return func(*testing.T) {}
}
// RunSubTests runs all "Test___" functions that are methods of x as subtests
// of the current test. If x contains Setup/Teardown functions, those are run
// before/after each of the test functions, respectively.
func RunSubTests(t *testing.T, x interface{}) {
xt := reflect.TypeOf(x)
xv := reflect.ValueOf(x)
setup := getTestFunc(t, xv, "Setup")
teardown := getTestFunc(t, xv, "Teardown")
for i := 0; i < xt.NumMethod(); i++ {
methodName := xt.Method(i).Name
if !strings.HasPrefix(methodName, "Test") {
continue
}
tfunc := getTestFunc(t, xv, methodName)
t.Run(strings.TrimPrefix(methodName, "Test"), func(t *testing.T) {
setup(t)
tfunc(t)
teardown(t)
})
}
}

Просмотреть файл

@ -0,0 +1,63 @@
/*
*
* Copyright 2018 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package grpctest
import (
"reflect"
"testing"
)
type tRunST struct {
setup, test, teardown bool
}
func (t *tRunST) Setup(*testing.T) {
t.setup = true
}
func (t *tRunST) TestSubTest(*testing.T) {
t.test = true
}
func (t *tRunST) Teardown(*testing.T) {
t.teardown = true
}
func TestRunSubTests(t *testing.T) {
x := &tRunST{}
RunSubTests(t, x)
if want := (&tRunST{setup: true, test: true, teardown: true}); !reflect.DeepEqual(x, want) {
t.Fatalf("x = %v; want all fields true", x)
}
}
type tNoST struct {
test bool
}
func (t *tNoST) TestSubTest(*testing.T) {
t.test = true
}
func TestNoSetupOrTeardown(t *testing.T) {
// Ensures nothing panics or fails if Setup/Teardown are omitted.
x := &tNoST{}
RunSubTests(t, x)
if want := (&tNoST{test: true}); !reflect.DeepEqual(x, want) {
t.Fatalf("x = %v; want %v", x, want)
}
}

Просмотреть файл

@ -28,7 +28,6 @@ import (
"google.golang.org/grpc/balancer"
"google.golang.org/grpc/connectivity"
_ "google.golang.org/grpc/grpclog/glogger"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/internal/transport"
)
@ -65,8 +64,7 @@ func (p *testingPicker) Pick(ctx context.Context, opts balancer.PickOptions) (ba
return p.sc, nil, nil
}
func TestBlockingPickTimeout(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestBlockingPickTimeout(t *testing.T) {
bp := newPickerWrapper()
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond)
defer cancel()
@ -75,8 +73,7 @@ func TestBlockingPickTimeout(t *testing.T) {
}
}
func TestBlockingPick(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestBlockingPick(t *testing.T) {
bp := newPickerWrapper()
// All goroutines should block because picker is nil in bp.
var finishedCount uint64
@ -95,8 +92,7 @@ func TestBlockingPick(t *testing.T) {
bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount})
}
func TestBlockingPickNoSubAvailable(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestBlockingPickNoSubAvailable(t *testing.T) {
bp := newPickerWrapper()
var finishedCount uint64
bp.updatePicker(&testingPicker{err: balancer.ErrNoSubConnAvailable, maxCalled: goroutineCount})
@ -116,8 +112,7 @@ func TestBlockingPickNoSubAvailable(t *testing.T) {
bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount})
}
func TestBlockingPickTransientWaitforready(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestBlockingPickTransientWaitforready(t *testing.T) {
bp := newPickerWrapper()
bp.updatePicker(&testingPicker{err: balancer.ErrTransientFailure, maxCalled: goroutineCount})
var finishedCount uint64
@ -138,8 +133,7 @@ func TestBlockingPickTransientWaitforready(t *testing.T) {
bp.updatePicker(&testingPicker{sc: testSC, maxCalled: goroutineCount})
}
func TestBlockingPickSCNotReady(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestBlockingPickSCNotReady(t *testing.T) {
bp := newPickerWrapper()
bp.updatePicker(&testingPicker{sc: testSCNotReady, maxCalled: goroutineCount})
var finishedCount uint64

Просмотреть файл

@ -26,7 +26,6 @@ import (
"time"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/resolver/manual"
"google.golang.org/grpc/status"
@ -39,8 +38,7 @@ func errorDesc(err error) string {
return err.Error()
}
func TestOneBackendPickfirst(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestOneBackendPickfirst(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -73,8 +71,7 @@ func TestOneBackendPickfirst(t *testing.T) {
t.Fatalf("EmptyCall() = _, %v, want _, %v", err, servers[0].port)
}
func TestBackendsPickfirst(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestBackendsPickfirst(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -107,8 +104,7 @@ func TestBackendsPickfirst(t *testing.T) {
t.Fatalf("EmptyCall() = _, %v, want _, %v", err, servers[0].port)
}
func TestNewAddressWhileBlockingPickfirst(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestNewAddressWhileBlockingPickfirst(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -144,8 +140,7 @@ func TestNewAddressWhileBlockingPickfirst(t *testing.T) {
wg.Wait()
}
func TestCloseWithPendingRPCPickfirst(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCloseWithPendingRPCPickfirst(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -181,8 +176,7 @@ func TestCloseWithPendingRPCPickfirst(t *testing.T) {
wg.Wait()
}
func TestOneServerDownPickfirst(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestOneServerDownPickfirst(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -223,8 +217,7 @@ func TestOneServerDownPickfirst(t *testing.T) {
t.Fatalf("EmptyCall() = _, %v, want _, %v", err, servers[0].port)
}
func TestAllServersDownPickfirst(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestAllServersDownPickfirst(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()
@ -267,8 +260,7 @@ func TestAllServersDownPickfirst(t *testing.T) {
t.Fatalf("EmptyCall() = _, %v, want _, error with code unavailable", err)
}
func TestAddressesRemovedPickfirst(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestAddressesRemovedPickfirst(t *testing.T) {
r, rcleanup := manual.GenerateAndRegisterManualResolver()
defer rcleanup()

Просмотреть файл

@ -31,8 +31,6 @@ import (
"net/url"
"testing"
"time"
"google.golang.org/grpc/internal/leakcheck"
)
const (
@ -102,7 +100,6 @@ func (p *proxyServer) stop() {
}
func testHTTPConnect(t *testing.T, proxyURLModify func(*url.URL) *url.URL, proxyReqCheck func(*http.Request) error) {
defer leakcheck.Check(t)
plis, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("failed to listen: %v", err)
@ -165,7 +162,7 @@ func testHTTPConnect(t *testing.T, proxyURLModify func(*url.URL) *url.URL, proxy
}
}
func TestHTTPConnect(t *testing.T) {
func (s) TestHTTPConnect(t *testing.T) {
testHTTPConnect(t,
func(in *url.URL) *url.URL {
return in
@ -182,7 +179,7 @@ func TestHTTPConnect(t *testing.T) {
)
}
func TestHTTPConnectBasicAuth(t *testing.T) {
func (s) TestHTTPConnectBasicAuth(t *testing.T) {
const (
user = "notAUser"
password = "notAPassword"
@ -210,8 +207,7 @@ func TestHTTPConnectBasicAuth(t *testing.T) {
)
}
func TestMapAddressEnv(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestMapAddressEnv(t *testing.T) {
// Overwrite the function in the test and restore them in defer.
hpfe := func(req *http.Request) (*url.URL, error) {
if req.URL.Host == envTestAddr {

Просмотреть файл

@ -27,7 +27,7 @@ import (
"google.golang.org/grpc/resolver"
)
func TestParseTarget(t *testing.T) {
func (s) TestParseTarget(t *testing.T) {
for _, test := range []resolver.Target{
{Scheme: "dns", Authority: "", Endpoint: "google.com"},
{Scheme: "dns", Authority: "a.server.com", Endpoint: "google.com"},
@ -42,7 +42,7 @@ func TestParseTarget(t *testing.T) {
}
}
func TestParseTargetString(t *testing.T) {
func (s) TestParseTargetString(t *testing.T) {
for _, test := range []struct {
targetStr string
want resolver.Target
@ -83,7 +83,7 @@ func TestParseTargetString(t *testing.T) {
// The target string with unknown scheme should be kept unchanged and passed to
// the dialer.
func TestDialParseTargetUnknownScheme(t *testing.T) {
func (s) TestDialParseTargetUnknownScheme(t *testing.T) {
for _, test := range []struct {
targetStr string
want string

Просмотреть файл

@ -45,7 +45,7 @@ func (f fullReader) Read(p []byte) (int, error) {
var _ CallOption = EmptyCallOption{} // ensure EmptyCallOption implements the interface
func TestSimpleParsing(t *testing.T) {
func (s) TestSimpleParsing(t *testing.T) {
bigMsg := bytes.Repeat([]byte{'x'}, 1<<24)
for _, test := range []struct {
// input
@ -72,7 +72,7 @@ func TestSimpleParsing(t *testing.T) {
}
}
func TestMultipleParsing(t *testing.T) {
func (s) TestMultipleParsing(t *testing.T) {
// Set a byte stream consists of 3 messages with their headers.
p := []byte{0, 0, 0, 0, 1, 'a', 0, 0, 0, 0, 2, 'b', 'c', 0, 0, 0, 0, 1, 'd'}
b := fullReader{bytes.NewReader(p)}
@ -101,7 +101,7 @@ func TestMultipleParsing(t *testing.T) {
}
}
func TestEncode(t *testing.T) {
func (s) TestEncode(t *testing.T) {
for _, test := range []struct {
// input
msg proto.Message
@ -123,7 +123,7 @@ func TestEncode(t *testing.T) {
}
}
func TestCompress(t *testing.T) {
func (s) TestCompress(t *testing.T) {
bestCompressor, err := NewGZIPCompressorWithLevel(gzip.BestCompression)
if err != nil {
t.Fatalf("Could not initialize gzip compressor with best compression.")
@ -170,7 +170,7 @@ func TestCompress(t *testing.T) {
}
}
func TestToRPCErr(t *testing.T) {
func (s) TestToRPCErr(t *testing.T) {
for _, test := range []struct {
// input
errIn error
@ -190,7 +190,7 @@ func TestToRPCErr(t *testing.T) {
}
}
func TestParseDialTarget(t *testing.T) {
func (s) TestParseDialTarget(t *testing.T) {
for _, test := range []struct {
target, wantNet, wantAddr string
}{

Просмотреть файл

@ -26,7 +26,6 @@ import (
"testing"
"time"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/internal/transport"
)
@ -34,8 +33,7 @@ type emptyServiceServer interface{}
type testServer struct{}
func TestStopBeforeServe(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestStopBeforeServe(t *testing.T) {
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
t.Fatalf("failed to create listener: %v", err)
@ -56,8 +54,7 @@ func TestStopBeforeServe(t *testing.T) {
}
}
func TestGracefulStop(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestGracefulStop(t *testing.T) {
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
@ -77,8 +74,7 @@ func TestGracefulStop(t *testing.T) {
}
}
func TestGetServiceInfo(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestGetServiceInfo(t *testing.T) {
testSd := ServiceDesc{
ServiceName: "grpc.testing.EmptyService",
HandlerType: (*emptyServiceServer)(nil),
@ -125,7 +121,7 @@ func TestGetServiceInfo(t *testing.T) {
}
}
func TestStreamContext(t *testing.T) {
func (s) TestStreamContext(t *testing.T) {
expectedStream := &transport.Stream{}
ctx := NewContextWithServerTransportStream(context.Background(), expectedStream)
s := ServerTransportStreamFromContext(ctx)

Просмотреть файл

@ -26,7 +26,7 @@ import (
"time"
)
func TestParseLoadBalancer(t *testing.T) {
func (s) TestParseLoadBalancer(t *testing.T) {
testcases := []struct {
scjs string
wantSC ServiceConfig
@ -85,7 +85,7 @@ func TestParseLoadBalancer(t *testing.T) {
}
}
func TestParseWaitForReady(t *testing.T) {
func (s) TestParseWaitForReady(t *testing.T) {
testcases := []struct {
scjs string
wantSC ServiceConfig
@ -173,7 +173,7 @@ func TestParseWaitForReady(t *testing.T) {
}
}
func TestPraseTimeOut(t *testing.T) {
func (s) TestPraseTimeOut(t *testing.T) {
testcases := []struct {
scjs string
wantSC ServiceConfig
@ -255,7 +255,7 @@ func TestPraseTimeOut(t *testing.T) {
}
}
func TestPraseMsgSize(t *testing.T) {
func (s) TestPraseMsgSize(t *testing.T) {
testcases := []struct {
scjs string
wantSC ServiceConfig
@ -324,7 +324,7 @@ func TestPraseMsgSize(t *testing.T) {
}
}
func TestParseDuration(t *testing.T) {
func (s) TestParseDuration(t *testing.T) {
testCases := []struct {
s *string
want *time.Duration

Просмотреть файл

@ -29,7 +29,6 @@ import (
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/resolver"
testpb "google.golang.org/grpc/test/grpc_testing"
@ -111,13 +110,12 @@ func (p *picker) Pick(ctx context.Context, opts balancer.PickOptions) (balancer.
return p.sc, func(d balancer.DoneInfo) { p.bal.doneInfo = append(p.bal.doneInfo, d) }, nil
}
func TestCredsBundleFromBalancer(t *testing.T) {
func (s) TestCredsBundleFromBalancer(t *testing.T) {
balancer.Register(&testBalancer{
newSubConnOptions: balancer.NewSubConnOptions{
CredsBundle: &testCredsBundle{},
},
})
defer leakcheck.Check(t)
te := newTest(t, env{name: "creds-bundle", network: "tcp", balancer: ""})
te.tapHandle = authHandle
te.customDialOptions = []grpc.DialOption{
@ -140,8 +138,7 @@ func TestCredsBundleFromBalancer(t *testing.T) {
}
}
func TestPickAndDone(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestPickAndDone(t *testing.T) {
for _, e := range listTestEnv() {
testPickAndDone(t, e)
}

Просмотреть файл

@ -29,11 +29,10 @@ import (
"time"
"google.golang.org/grpc/internal/channelz"
"google.golang.org/grpc/internal/leakcheck"
testpb "google.golang.org/grpc/test/grpc_testing"
)
func TestCZSocketMetricsSocketOption(t *testing.T) {
func (s) TestCZSocketMetricsSocketOption(t *testing.T) {
envs := []env{tcpClearRREnv, tcpTLSRREnv}
for _, e := range envs {
testCZSocketMetricsSocketOption(t, e)
@ -41,7 +40,6 @@ func TestCZSocketMetricsSocketOption(t *testing.T) {
}
func testCZSocketMetricsSocketOption(t *testing.T, e env) {
defer leakcheck.Check(t)
channelz.NewChannelzStorage()
te := newTest(t, e)
te.startServer(&testServer{security: e.security})

Просмотреть файл

@ -36,7 +36,6 @@ import (
"google.golang.org/grpc/connectivity"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/internal/channelz"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/keepalive"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/resolver/manual"
@ -67,8 +66,7 @@ func verifyResultWithDelay(f func() (bool, error)) error {
return err
}
func TestCZServerRegistrationAndDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZServerRegistrationAndDeletion(t *testing.T) {
testcases := []struct {
total int
start int64
@ -102,8 +100,7 @@ func TestCZServerRegistrationAndDeletion(t *testing.T) {
}
}
func TestCZTopChannelRegistrationAndDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZTopChannelRegistrationAndDeletion(t *testing.T) {
testcases := []struct {
total int
start int64
@ -156,8 +153,7 @@ func TestCZTopChannelRegistrationAndDeletion(t *testing.T) {
}
}
func TestCZNestedChannelRegistrationAndDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZNestedChannelRegistrationAndDeletion(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
// avoid calling API to set balancer type, which will void service config's change of balancer.
@ -202,8 +198,7 @@ func TestCZNestedChannelRegistrationAndDeletion(t *testing.T) {
}
}
func TestCZClientSubChannelSocketRegistrationAndDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZClientSubChannelSocketRegistrationAndDeletion(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
num := 3 // number of backends
@ -274,8 +269,7 @@ func TestCZClientSubChannelSocketRegistrationAndDeletion(t *testing.T) {
}
}
func TestCZServerSocketRegistrationAndDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZServerSocketRegistrationAndDeletion(t *testing.T) {
testcases := []struct {
total int
start int64
@ -351,8 +345,7 @@ func TestCZServerSocketRegistrationAndDeletion(t *testing.T) {
}
}
func TestCZServerListenSocketDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZServerListenSocketDeletion(t *testing.T) {
channelz.NewChannelzStorage()
s := grpc.NewServer()
lis, err := net.Listen("tcp", "localhost:0")
@ -398,7 +391,7 @@ func (d *dummySocket) ChannelzMetric() *channelz.SocketInternalMetric {
return &channelz.SocketInternalMetric{}
}
func TestCZRecusivelyDeletionOfEntry(t *testing.T) {
func (s) TestCZRecusivelyDeletionOfEntry(t *testing.T) {
// +--+TopChan+---+
// | |
// v v
@ -449,8 +442,7 @@ func TestCZRecusivelyDeletionOfEntry(t *testing.T) {
}
}
func TestCZChannelMetrics(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZChannelMetrics(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
num := 3 // number of backends
@ -538,8 +530,7 @@ func TestCZChannelMetrics(t *testing.T) {
}
}
func TestCZServerMetrics(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZServerMetrics(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -823,8 +814,7 @@ func doIdleCallToInvokeKeepAlive(tc testpb.TestServiceClient, t *testing.T) {
cancel()
}
func TestCZClientSocketMetricsStreamsAndMessagesCount(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZClientSocketMetricsStreamsAndMessagesCount(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -923,8 +913,7 @@ func TestCZClientSocketMetricsStreamsAndMessagesCount(t *testing.T) {
// server sending RST_STREAM to client due to client side flow control violation.
// It is separated from other cases due to setup incompatibly, i.e. max receive
// size violation will mask flow control violation.
func TestCZClientAndServerSocketMetricsStreamsCountFlowControlRSTStream(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZClientAndServerSocketMetricsStreamsCountFlowControlRSTStream(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -984,8 +973,7 @@ func TestCZClientAndServerSocketMetricsStreamsCountFlowControlRSTStream(t *testi
}
}
func TestCZClientAndServerSocketMetricsFlowControl(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZClientAndServerSocketMetricsFlowControl(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -1097,8 +1085,7 @@ func TestCZClientAndServerSocketMetricsFlowControl(t *testing.T) {
}
}
func TestCZClientSocketMetricsKeepAlive(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZClientSocketMetricsKeepAlive(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -1141,8 +1128,7 @@ func TestCZClientSocketMetricsKeepAlive(t *testing.T) {
}
}
func TestCZServerSocketMetricsStreamsAndMessagesCount(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZServerSocketMetricsStreamsAndMessagesCount(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -1202,8 +1188,7 @@ func TestCZServerSocketMetricsStreamsAndMessagesCount(t *testing.T) {
}
}
func TestCZServerSocketMetricsKeepAlive(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZServerSocketMetricsKeepAlive(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -1258,8 +1243,7 @@ var cipherSuites = []string{
"TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305",
}
func TestCZSocketGetSecurityValueTLS(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZSocketGetSecurityValueTLS(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpTLSRREnv
te := newTest(t, e)
@ -1308,8 +1292,7 @@ func TestCZSocketGetSecurityValueTLS(t *testing.T) {
}
}
func TestCZChannelTraceCreationDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZChannelTraceCreationDeletion(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
// avoid calling API to set balancer type, which will void service config's change of balancer.
@ -1385,8 +1368,7 @@ func TestCZChannelTraceCreationDeletion(t *testing.T) {
}
}
func TestCZSubChannelTraceCreationDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZSubChannelTraceCreationDeletion(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -1464,8 +1446,7 @@ func TestCZSubChannelTraceCreationDeletion(t *testing.T) {
}
}
func TestCZChannelAddressResolutionChange(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZChannelAddressResolutionChange(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
e.balancer = ""
@ -1567,8 +1548,7 @@ func TestCZChannelAddressResolutionChange(t *testing.T) {
}
}
func TestCZSubChannelPickedNewAddress(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZSubChannelPickedNewAddress(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
e.balancer = ""
@ -1628,8 +1608,7 @@ func TestCZSubChannelPickedNewAddress(t *testing.T) {
}
}
func TestCZSubChannelConnectivityState(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZSubChannelConnectivityState(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -1724,8 +1703,7 @@ func TestCZSubChannelConnectivityState(t *testing.T) {
}
}
func TestCZChannelConnectivityState(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZChannelConnectivityState(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -1782,8 +1760,7 @@ func TestCZChannelConnectivityState(t *testing.T) {
}
}
func TestCZTraceOverwriteChannelDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZTraceOverwriteChannelDeletion(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
// avoid calling API to set balancer type, which will void service config's change of balancer.
@ -1844,8 +1821,7 @@ func TestCZTraceOverwriteChannelDeletion(t *testing.T) {
}
}
func TestCZTraceOverwriteSubChannelDeletion(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZTraceOverwriteSubChannelDeletion(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)
@ -1904,8 +1880,7 @@ func TestCZTraceOverwriteSubChannelDeletion(t *testing.T) {
}
}
func TestCZTraceTopChannelDeletionTraceClear(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCZTraceTopChannelDeletionTraceClear(t *testing.T) {
channelz.NewChannelzStorage()
e := tcpClearRREnv
te := newTest(t, e)

Просмотреть файл

@ -27,7 +27,6 @@ import (
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/internal/leakcheck"
testpb "google.golang.org/grpc/test/grpc_testing"
"google.golang.org/grpc/testdata"
)
@ -66,8 +65,7 @@ func (c *testCredsBundle) NewWithMode(mode string) (credentials.Bundle, error) {
return &testCredsBundle{mode: mode}, nil
}
func TestCredsBundleBoth(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCredsBundleBoth(t *testing.T) {
te := newTest(t, env{name: "creds-bundle", network: "tcp", balancer: "v1", security: "empty"})
te.tapHandle = authHandle
te.customDialOptions = []grpc.DialOption{
@ -90,8 +88,7 @@ func TestCredsBundleBoth(t *testing.T) {
}
}
func TestCredsBundleTransportCredentials(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCredsBundleTransportCredentials(t *testing.T) {
te := newTest(t, env{name: "creds-bundle", network: "tcp", balancer: "v1", security: "empty"})
te.customDialOptions = []grpc.DialOption{
grpc.WithCredentialsBundle(&testCredsBundle{t: t, mode: bundleTLSOnly}),
@ -113,8 +110,7 @@ func TestCredsBundleTransportCredentials(t *testing.T) {
}
}
func TestCredsBundlePerRPCCredentials(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestCredsBundlePerRPCCredentials(t *testing.T) {
te := newTest(t, env{name: "creds-bundle", network: "tcp", balancer: "v1", security: "empty"})
te.tapHandle = authHandle
te.customDialOptions = []grpc.DialOption{

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -28,7 +28,6 @@ import (
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/internal/leakcheck"
testpb "google.golang.org/grpc/test/grpc_testing"
)
@ -106,8 +105,7 @@ func (d *delayConn) Read(b []byte) (n int, err error) {
return d.Conn.Read(b)
}
func TestGracefulStop(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestGracefulStop(t *testing.T) {
// This test ensures GracefulStop cannot race and break RPCs on new
// connections created after GracefulStop was called but before
// listener.Accept() returns a "closing" error.

Просмотреть файл

@ -35,7 +35,6 @@ import (
healthpb "google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/internal"
"google.golang.org/grpc/internal/channelz"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/resolver"
"google.golang.org/grpc/resolver/manual"
"google.golang.org/grpc/status"
@ -168,8 +167,7 @@ func setupClient(c *clientConfig) (cc *grpc.ClientConn, r *manual.Resolver, defe
return cc, r, func() { cc.Close(); rcleanup() }, nil
}
func TestHealthCheckWatchStateChange(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckWatchStateChange(t *testing.T) {
_, lis, ts, deferFunc, err := setupServer(&svrConfig{})
defer deferFunc()
if err != nil {
@ -248,8 +246,7 @@ func TestHealthCheckWatchStateChange(t *testing.T) {
}
// If Watch returns Unimplemented, then the ClientConn should go into READY state.
func TestHealthCheckHealthServerNotRegistered(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckHealthServerNotRegistered(t *testing.T) {
s := grpc.NewServer()
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
@ -286,9 +283,7 @@ func TestHealthCheckHealthServerNotRegistered(t *testing.T) {
// In the case of a goaway received, the health check stream should be terminated and health check
// function should exit.
func TestHealthCheckWithGoAway(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckWithGoAway(t *testing.T) {
hcEnterChan, hcExitChan, testHealthCheckFuncWrapper := setupHealthCheckWrapper()
s, lis, ts, deferFunc, err := setupServer(&svrConfig{})
@ -378,9 +373,7 @@ func TestHealthCheckWithGoAway(t *testing.T) {
}
}
func TestHealthCheckWithConnClose(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckWithConnClose(t *testing.T) {
hcEnterChan, hcExitChan, testHealthCheckFuncWrapper := setupHealthCheckWrapper()
s, lis, ts, deferFunc, err := setupServer(&svrConfig{})
@ -442,9 +435,7 @@ func TestHealthCheckWithConnClose(t *testing.T) {
// addrConn drain happens when addrConn gets torn down due to its address being no longer in the
// address list returned by the resolver.
func TestHealthCheckWithAddrConnDrain(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckWithAddrConnDrain(t *testing.T) {
hcEnterChan, hcExitChan, testHealthCheckFuncWrapper := setupHealthCheckWrapper()
_, lis, ts, deferFunc, err := setupServer(&svrConfig{})
@ -534,9 +525,7 @@ func TestHealthCheckWithAddrConnDrain(t *testing.T) {
}
// ClientConn close will lead to its addrConns being torn down.
func TestHealthCheckWithClientConnClose(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckWithClientConnClose(t *testing.T) {
hcEnterChan, hcExitChan, testHealthCheckFuncWrapper := setupHealthCheckWrapper()
_, lis, ts, deferFunc, err := setupServer(&svrConfig{})
@ -598,9 +587,7 @@ func TestHealthCheckWithClientConnClose(t *testing.T) {
// This test is to test the logic in the createTransport after the health check function returns which
// closes the skipReset channel(since it has not been closed inside health check func) to unblock
// onGoAway/onClose goroutine.
func TestHealthCheckWithoutReportHealthCalledAddrConnShutDown(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckWithoutReportHealthCalledAddrConnShutDown(t *testing.T) {
hcEnterChan, hcExitChan, testHealthCheckFuncWrapper := setupHealthCheckWrapper()
_, lis, ts, deferFunc, err := setupServer(&svrConfig{
@ -673,9 +660,7 @@ func TestHealthCheckWithoutReportHealthCalledAddrConnShutDown(t *testing.T) {
// This test is to test the logic in the createTransport after the health check function returns which
// closes the allowedToReset channel(since it has not been closed inside health check func) to unblock
// onGoAway/onClose goroutine.
func TestHealthCheckWithoutReportHealthCalled(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckWithoutReportHealthCalled(t *testing.T) {
hcEnterChan, hcExitChan, testHealthCheckFuncWrapper := setupHealthCheckWrapper()
s, lis, ts, deferFunc, err := setupServer(&svrConfig{
@ -856,9 +841,7 @@ func testHealthCheckDisableWithServiceConfig(t *testing.T, addr string) {
}
}
func TestHealthCheckDisable(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckDisable(t *testing.T) {
_, lis, ts, deferFunc, err := setupServer(&svrConfig{})
defer deferFunc()
if err != nil {
@ -872,9 +855,7 @@ func TestHealthCheckDisable(t *testing.T) {
testHealthCheckDisableWithServiceConfig(t, lis.Addr().String())
}
func TestHealthCheckChannelzCountingCallSuccess(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckChannelzCountingCallSuccess(t *testing.T) {
_, lis, _, deferFunc, err := setupServer(&svrConfig{
specialWatchFunc: func(s *testHealthServer, in *healthpb.HealthCheckRequest, stream healthgrpc.Health_WatchServer) error {
if in.Service != "channelzSuccess" {
@ -929,9 +910,7 @@ func TestHealthCheckChannelzCountingCallSuccess(t *testing.T) {
}
}
func TestHealthCheckChannelzCountingCallFailure(t *testing.T) {
defer leakcheck.Check(t)
func (s) TestHealthCheckChannelzCountingCallFailure(t *testing.T) {
_, lis, _, deferFunc, err := setupServer(&svrConfig{
specialWatchFunc: func(s *testHealthServer, in *healthpb.HealthCheckRequest, stream healthgrpc.Health_WatchServer) error {
if in.Service != "channelzFailure" {

Просмотреть файл

@ -44,7 +44,7 @@ func enableRetry() func() {
return func() { envconfig.Retry = old }
}
func TestRetryUnary(t *testing.T) {
func (s) TestRetryUnary(t *testing.T) {
defer enableRetry()()
i := -1
ss := &stubServer{
@ -112,7 +112,7 @@ func TestRetryUnary(t *testing.T) {
}
}
func TestRetryDisabledByDefault(t *testing.T) {
func (s) TestRetryDisabledByDefault(t *testing.T) {
if strings.EqualFold(os.Getenv("GRPC_GO_RETRY"), "on") {
return
}
@ -174,7 +174,7 @@ func TestRetryDisabledByDefault(t *testing.T) {
}
}
func TestRetryThrottling(t *testing.T) {
func (s) TestRetryThrottling(t *testing.T) {
defer enableRetry()()
i := -1
ss := &stubServer{
@ -250,7 +250,7 @@ func TestRetryThrottling(t *testing.T) {
}
}
func TestRetryStreaming(t *testing.T) {
func (s) TestRetryStreaming(t *testing.T) {
defer enableRetry()()
req := func(b byte) *testpb.StreamingOutputCallRequest {
return &testpb.StreamingOutputCallRequest{Payload: &testpb.Payload{Body: []byte{b}}}

4
vet.sh
Просмотреть файл

@ -76,6 +76,10 @@ fi
# - Ensure all source files contain a copyright message.
git ls-files "*.go" | xargs grep -L "\(Copyright [0-9]\{4,\} gRPC authors\)\|DO NOT EDIT" 2>&1 | fail_on_output
# - Make sure all tests in grpc and grpc/test use leakcheck via Teardown.
(! grep 'func Test[^(]' *_test.go)
(! grep 'func Test[^(]' test/*.go)
# - Do not import math/rand for real library code. Use internal/grpcrand for
# thread safety.
git ls-files "*.go" | xargs grep -l '"math/rand"' 2>&1 | (! grep -v '^examples\|^stress\|grpcrand')