grpcstub

package module
v0.17.4 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2024 License: MIT Imports: 35 Imported by: 2

README

grpcstub Go Reference Coverage Code to Test Ratio Test Execution Time

grpcstub provides gRPC server and client conn ( *grpc.ClientConn ) for stubbing, for testing in Go.

There is an HTTP version stubbing tool with the same design concept, httpstub.

Usage

package myapp

import (
	"io"
	"net/http"
	"testing"

	"github.com/k1LoW/grpcstub"
	"github.com/k1LoW/myapp/protobuf/gen/go/routeguide"
)

func TestClient(t *testing.T) {
	ctx := context.Background()
	ts := grpcstub.NewServer(t, "protobuf/proto/*.proto")
	t.Cleanup(func() {
		ts.Close()
	})
	ts.Method("GetFeature").Response(&routeguite.Feature{
		Name: "hello",
		Location: &routeguide.Point{
			Latitude:  10,
			Longitude: 13,
		},
	})
	// OR
	// ts.Method("GetFeature").Response(map[string]any{"name": "hello", "location": map[string]any{"latitude": 10, "longitude": 13}})

	client := routeguide.NewRouteGuideClient(ts.Conn())
	if _, err := client.GetFeature(ctx, &routeguide.Point{
		Latitude:  10,
		Longitude: 13,
	}); err != nil {
		t.Fatal(err)
	}
	{
		got := len(ts.Requests())
		if want := 1; got != want {
			t.Errorf("got %v\nwant %v", got, want)
		}
	}
	req := ts.Requests()[0]
	{
		got := int32(req.Message["longitude"].(float64))
		if want := int32(13); got != want {
			t.Errorf("got %v\nwant %v", got, want)
		}
	}
}

Dynamic Response

grpcstub can return responses dynamically using the protocol buffer schema.

Dynamic response to all requests
ts := grpcstub.NewServer(t, "path/to/*.proto")
t.Cleanup(func() {
	ts.Close()
})
ts.ResponseDynamic()
Dynamic response to a request to a specific method (rpc)
ts := grpcstub.NewServer(t, "path/to/*.proto")
t.Cleanup(func() {
	ts.Close()
})
ts.Service("routeguide.RouteGuide").Method("GetFeature").ResponseDynamic()
Dynamic response with your own generators
ts := grpcstub.NewServer(t, "path/to/*.proto")
t.Cleanup(func() {
	ts.Close()
})
fk := faker.New()
want := time.Now()
opts := []GeneratorOption{
	Generator("*_id", func(r *grpcstub.Request) any {
		return fk.UUID().V4()
	}),
	Generator("*_time", func(r *grpcstub.Request) any {
		return want
	}),
}
ts.ResponseDynamic(opts...)

Test data

References

Documentation

Index

Constants

View Source
const (
	HealthCheckService_DEFAULT  = "default"
	HealthCheckService_FLAPPING = "flapping"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type GenerateFunc added in v0.8.0

type GenerateFunc func(r *Request) any

type GeneratorOption added in v0.8.0

type GeneratorOption func(generators) generators

func Generator added in v0.8.0

func Generator(pattern string, fn GenerateFunc) GeneratorOption

type Message

type Message map[string]any

type Option added in v0.6.0

type Option func(*config) error

func DisableReflection added in v0.11.1

func DisableReflection() Option

DisableReflection disable Server Reflection Protocol

func EnableHealthCheck added in v0.9.0

func EnableHealthCheck() Option

EnableHealthCheck enable grpc.health.v1

func ImportPath added in v0.8.0

func ImportPath(path string) Option

ImportPath set import path

func ImportPaths added in v0.6.0

func ImportPaths(paths []string) Option

ImportPaths set import paths

func Proto added in v0.6.0

func Proto(proto string) Option

Proto append proto

func Protos added in v0.6.0

func Protos(protos []string) Option

Protos append protos

func UseTLS added in v0.6.0

func UseTLS(cacert, cert, key []byte) Option

UseTLS enable TLS

type Request

type Request struct {
	Service string
	Method  string
	Headers metadata.MD
	Message Message
}

func (Request) String added in v0.14.0

func (r Request) String() string

type Response

type Response struct {
	Headers  metadata.MD
	Messages []Message
	Trailers metadata.MD
	Status   *status.Status
}

func NewResponse

func NewResponse() *Response

NewResponse returns a new empty response

type Server

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

func NewServer

func NewServer(t TB, protopath string, opts ...Option) *Server

NewServer returns a new server with registered *grpc.Server

func NewTLSServer added in v0.5.0

func NewTLSServer(t TB, proto string, cacert, cert, key []byte, opts ...Option) *Server

NewTLSServer returns a new server with registered secure *grpc.Server

func (*Server) Addr added in v0.2.0

func (s *Server) Addr() string

Addr returns server listener address

func (*Server) ClearMatchers added in v0.15.3

func (s *Server) ClearMatchers()

ClearMatchers clear matchers.

func (*Server) ClearRequests added in v0.15.3

func (s *Server) ClearRequests()

ClearRequests clear requests.

func (*Server) ClientConn added in v0.5.0

func (s *Server) ClientConn() *grpc.ClientConn

ClientConn is alias of Conn

func (*Server) Close

func (s *Server) Close()

Close shuts down *grpc.Server

func (*Server) Conn

func (s *Server) Conn() *grpc.ClientConn

Conn returns *grpc.ClientConn which connects *grpc.Server.

func (*Server) Match

func (s *Server) Match(fn func(r *Request) bool) *matcher

Match create request matcher with matchFunc (func(r *grpcstub.Request) bool).

func (*Server) Method

func (s *Server) Method(method string) *matcher

Method create request matcher using method.

func (*Server) Methodf added in v0.8.0

func (s *Server) Methodf(format string, a ...any) *matcher

Methodf create request matcher using sprintf-ed method.

func (*Server) Requests

func (s *Server) Requests() []*Request

Requests returns []*grpcstub.Request received by router.

func (*Server) ResponseDynamic added in v0.8.1

func (s *Server) ResponseDynamic(opts ...GeneratorOption) *matcher

ResponseDynamic set handler which return dynamic response.

func (*Server) Service

func (s *Server) Service(service string) *matcher

Service create request matcher using service.

func (*Server) Servicef added in v0.8.0

func (s *Server) Servicef(format string, a ...any) *matcher

Servicef create request matcher using sprintf-ed service.

func (*Server) UnmatchedRequests added in v0.14.0

func (s *Server) UnmatchedRequests() []*Request

UnmatchedRequests returns []*grpcstub.Request received but not matched by router.

type TB added in v0.16.0

type TB interface {
	Error(args ...any)
	Errorf(format string, args ...any)
	Fatal(args ...any)
	Fatalf(format string, args ...any)
	Helper()
}

Jump to

Keyboard shortcuts

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