Skip to content

grpctest: new package #2186

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 15 additions & 50 deletions balancer/roundrobin/roundrobin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@
package roundrobin_test

import (
"fmt"
"net"
"sync"
"testing"
"time"
Expand All @@ -30,6 +28,7 @@ import (
"google.golang.org/grpc/balancer/roundrobin"
"google.golang.org/grpc/codes"
_ "google.golang.org/grpc/grpclog/glogger"
"google.golang.org/grpc/grpctest"
"google.golang.org/grpc/internal/leakcheck"
"google.golang.org/grpc/peer"
"google.golang.org/grpc/resolver"
Expand Down Expand Up @@ -61,44 +60,28 @@ func (t *test) cleanup() {
}
}

func startTestServers(count int) (_ *test, err error) {
func startTestServers(tt *testing.T, count int) *test {
t := &test{}

defer func() {
if err != nil {
for _, s := range t.servers {
s.Stop()
}
}
}()
for i := 0; i < count; i++ {
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
return nil, fmt.Errorf("Failed to listen %v", err)
}
srv := grpctest.NewServer(tt)

s := grpc.NewServer()
testpb.RegisterTestServiceServer(s, &testServer{})
t.servers = append(t.servers, s)
t.addresses = append(t.addresses, lis.Addr().String())
testpb.RegisterTestServiceServer(srv.GRPC, &testServer{})
t.servers = append(t.servers, srv.GRPC)
t.addresses = append(t.addresses, srv.Addr)

go func(s *grpc.Server, l net.Listener) {
s.Serve(l)
}(s, lis)
srv.Start()
}

return t, nil
return t
}

func TestOneBackend(t *testing.T) {
defer leakcheck.Check(t)
r, cleanup := manual.GenerateAndRegisterManualResolver()
defer cleanup()

test, err := startTestServers(1)
if err != nil {
t.Fatalf("failed to start servers: %v", err)
}
test := startTestServers(t, 1)
defer test.cleanup()

cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name))
Expand Down Expand Up @@ -127,10 +110,7 @@ func TestBackendsRoundRobin(t *testing.T) {
defer cleanup()

backendCount := 5
test, err := startTestServers(backendCount)
if err != nil {
t.Fatalf("failed to start servers: %v", err)
}
test := startTestServers(t, backendCount)
defer test.cleanup()

cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name))
Expand Down Expand Up @@ -186,10 +166,7 @@ func TestAddressesRemoved(t *testing.T) {
r, cleanup := manual.GenerateAndRegisterManualResolver()
defer cleanup()

test, err := startTestServers(1)
if err != nil {
t.Fatalf("failed to start servers: %v", err)
}
test := startTestServers(t, 1)
defer test.cleanup()

cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name))
Expand Down Expand Up @@ -228,10 +205,7 @@ func TestCloseWithPendingRPC(t *testing.T) {
r, cleanup := manual.GenerateAndRegisterManualResolver()
defer cleanup()

test, err := startTestServers(1)
if err != nil {
t.Fatalf("failed to start servers: %v", err)
}
test := startTestServers(t, 1)
defer test.cleanup()

cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name))
Expand Down Expand Up @@ -262,10 +236,7 @@ func TestNewAddressWhileBlocking(t *testing.T) {
r, cleanup := manual.GenerateAndRegisterManualResolver()
defer cleanup()

test, err := startTestServers(1)
if err != nil {
t.Fatalf("failed to start servers: %v", err)
}
test := startTestServers(t, 1)
defer test.cleanup()

cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name))
Expand Down Expand Up @@ -311,10 +282,7 @@ func TestOneServerDown(t *testing.T) {
defer cleanup()

backendCount := 3
test, err := startTestServers(backendCount)
if err != nil {
t.Fatalf("failed to start servers: %v", err)
}
test := startTestServers(t, backendCount)
defer test.cleanup()

cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name), grpc.WithWaitForHandshake())
Expand Down Expand Up @@ -409,10 +377,7 @@ func TestAllServersDown(t *testing.T) {
defer cleanup()

backendCount := 3
test, err := startTestServers(backendCount)
if err != nil {
t.Fatalf("failed to start servers: %v", err)
}
test := startTestServers(t, backendCount)
defer test.cleanup()

cc, err := grpc.Dial(r.Scheme()+":///test.server", grpc.WithInsecure(), grpc.WithBalancerName(roundrobin.Name), grpc.WithWaitForHandshake())
Expand Down
80 changes: 80 additions & 0 deletions grpctest/grpctest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
Package grpctest provides utilities for RPC testing.

Call grpctest.NewServer to create a Server for a test;
use its Addr field as the address to dial, or invoke its Dial method.
*/
package grpctest

import (
"net"
"testing"

"google.golang.org/grpc"
)

// A Server is an RPC server listening on a system-chosen port on the local loopback interface.
type Server struct {
GRPC *grpc.Server
Addr string // address of test server, suitable for passing to grpc.Dial

t *testing.T
l net.Listener
closing bool
closed chan struct{}
}

// NewServer returns a new unstarted Server.
// Attach RPC services to s.GRPC, then invoke s.Start to start the server.
// The caller should call the Server's Close method when finished.
func NewServer(t *testing.T) *Server {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This uses and encourages an anti-pattern for Go testing, which is passing testing.Ts around (which is particularly discouraged when crossing package boundaries and storing in structs AIUI).

Further, I'm not convinced this package is worth the extra API surface it introduces. It is easy to start and stop a server/client with grpc. The main complexity is the Listen-on-localhost problem (which really should be solved in the net package itself, but that's irrelevant here). In the not-too-distant future (~1Q or so), we should be introducing an in-process transport that will be even easier to serve/dial.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's fine to pass around testing.T in limited circumstances. That's why t.Helper exists, after all. It solves the problems that passing around a testing.T produces.

It may be easy to start and stop a server for people like us who know what's going on, but lots of people aren't so comfortable. I see a lot of people getting it wrong in various ways (e.g. binding to :0 instead of a loopback address, or starting the server before registering service handlers). It's not a lot of code, but it cuts down the error rate a lot.

t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
// IPv4 might be unavailable. Try IPv6.
t.Logf("net.Listen on 127.0.0.1:0: %v", err)
l, err = net.Listen("tcp", "[::1]:0")
if err != nil {
t.Fatalf("net.Listen on [::1]:0: %v", err)
}
}
s := &Server{
GRPC: grpc.NewServer(),
Addr: l.Addr().String(),
t: t,
l: l,
closed: make(chan struct{}),
}
return s
}

// Start starts the server. RPC services must be registered before this is called.
func (s *Server) Start() {
go func() {
err := s.GRPC.Serve(s.l)
if !s.closing && err != nil {
s.t.Errorf("gRPC serve: %v", err)
}
close(s.closed)
}()
}

// Close shuts down the server and refuses any new connections.
// Existing RPC connections will stay open.
func (s *Server) Close() {
s.closing = true
s.l.Close()
<-s.closed
}

// Dial is like grpc.Dial(s.Addr) but with error handling abstracted.
func (s *Server) Dial(opts ...grpc.DialOption) *grpc.ClientConn {
s.t.Helper()
opts = append([]grpc.DialOption{grpc.WithInsecure()}, opts...)

conn, err := grpc.Dial(s.Addr, opts...)
if err != nil {
s.t.Fatalf("grpc.Dial(%q): %v", s.Addr, err)
}
return conn
}