grpctest

package module
v0.0.0-...-eb3e924 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 18, 2023 License: MIT Imports: 6 Imported by: 0

README

grpctest

A small testing library for gRPC-Go servers

Description

grpctest provides a test server and client connection. The server response from a given client request is obtained with trivial setup, reducing the overhead of testing a gRPC service.

Usage

This test server is intended to be used along side the protocol compiler plugins, protoc-gen-go and protoc-gen-go-grpc to generate the relevant code. Familiarity with this process is assumed in the instructions below to further simplify setup. The following uses the gRPC quickstart greeter server as an example.

Set up the test

example code

Install the necessary prerequistes and create a test file. Import grpctest.

import "github.com/vision-cli/grpctest"

Define a test function. A test server can be initialised with context.

func TestSayHello(t *testing.T) {
	ctx := context.Background()
	s := grpctest.NewServer().WithContext(ctx)
	defer s.Close()

}
Initialise the client

Import the relevant generated protobuf package.

import pb "google.golang.org/grpc/examples/helloworld/helloworld"

Register the greeter server using the generated function with s.RunServer().

s.RunServer(t, func(s *grpc.Server) {
		pb.RegisterGreeterServer(s, &server{})
	})

Initialise a new Greeter client with s.ClientConn()

client := pb.NewGreeterClient(s.ClientConn(t))
Test a request

With all the necesssary setup complete, the client can now make a request.

reply, err := client.SayHello(ctx, &pb.HelloRequest{Name: "Alice"})

The reply and any errors can be tested accordingly.

if err != nil {
	t.Fatalf("SayHello failed: %v", err)
}
expected := "Hello Alice"
if actual := reply.GetMessage(); actual != expected {
	t.Errorf(`got "%s", want "%s"`, actual, expected)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Server

type Server struct {
	// contains filtered or unexported fields
}

func NewServer

func NewServer() *Server

func (*Server) ClientConn

func (s *Server) ClientConn(t *testing.T) *grpc.ClientConn

func (*Server) Close

func (s *Server) Close()

func (*Server) RunServer

func (s *Server) RunServer(t *testing.T, fn func(*grpc.Server))

func (*Server) WithContext

func (s *Server) WithContext(ctx context.Context) *Server

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL