Skip to content
Permalink
Browse files
feat(pubsub/pstest): add ability to create a pstest server listening …
…on (#4459)

a specified port

Signed-off-by: Danny Cao <caoxiaohua@gmail.com>
  • Loading branch information
caod123 committed Jul 19, 2021
1 parent 691e923 commit f1b7c8b33bc135c6cb8f21cdec586b25d81ea214
Showing with 53 additions and 2 deletions.
  1. +20 −0 pubsub/pstest/examples_test.go
  2. +7 −2 pubsub/pstest/fake.go
  3. +26 −0 pubsub/pstest/fake_test.go
@@ -42,3 +42,23 @@ func ExampleNewServer() {
defer client.Close()
_ = client // TODO: Use the client.
}

func ExampleNewServerWithPort() {
ctx := context.Background()
// Start a fake server running locally at 9001.
srv := pstest.NewServerWithPort(9001)
defer srv.Close()
// Connect to the server without using TLS.
conn, err := grpc.Dial(srv.Addr, grpc.WithInsecure())
if err != nil {
// TODO: Handle error.
}
defer conn.Close()
// Use the connection when creating a pubsub client.
client, err := pubsub.NewClient(ctx, "project", option.WithGRPCConn(conn))
if err != nil {
// TODO: Handle error.
}
defer client.Close()
_ = client // TODO: Use the client.
}
@@ -114,9 +114,14 @@ type GServer struct {

// NewServer creates a new fake server running in the current process.
func NewServer(opts ...ServerReactorOption) *Server {
srv, err := testutil.NewServer()
return NewServerWithPort(0, opts...)
}

// NewServerWithPort creates a new fake server running in the current process at the specified port.
func NewServerWithPort(port int, opts ...ServerReactorOption) *Server {
srv, err := testutil.NewServerWithPort(port)
if err != nil {
panic(fmt.Sprintf("pstest.NewServer: %v", err))
panic(fmt.Sprintf("pstest.NewServerWithPort: %v", err))
}
reactorOptions := ReactorOptions{}
for _, opt := range opts {
@@ -18,6 +18,7 @@ import (
"context"
"fmt"
"io"
"net"
"reflect"
"strings"
"sync"
@@ -34,6 +35,31 @@ import (
"google.golang.org/protobuf/types/known/timestamppb"
)

func TestNewServerWithPort(t *testing.T) {
// Allocate an available port to use with NewServerWithPort and then close it so it's available.
// Note: There is no guarantee that the port does not become used between closing
// the listener and creating the new server with NewServerWithPort, but the chances are
// very small.
l, err := net.Listen("tcp", ":0")
if err != nil {
t.Fatal(err)
}
port := l.Addr().(*net.TCPAddr).Port
l.Close()

// Pass a non 0 port to demonstrate we can pass a hardcoded port for the server to listen on
srv := NewServerWithPort(port)
if err != nil {
t.Fatal(err)
}
defer srv.Close()
conn, err := grpc.Dial(srv.Addr, grpc.WithInsecure())
if err != nil {
t.Fatal(err)
}
defer conn.Close()
}

func TestTopics(t *testing.T) {
pclient, _, server, cleanup := newFake(context.TODO(), t)
defer cleanup()

0 comments on commit f1b7c8b

Please sign in to comment.