Documentation ¶
Overview ¶
Package grpcmock provides functionalities for testing grpc client and server.
Index ¶
- func FindServerMethod(srv *Server, method string) *service.Method
- func InvokeBidirectionalStream(ctx context.Context, method string, handle ClientStreamHandler, ...) error
- func InvokeClientStream(ctx context.Context, method string, handle ClientStreamHandler, ...) error
- func InvokeServerStream(ctx context.Context, method string, in interface{}, handle ClientStreamHandler, ...) error
- func InvokeUnary(ctx context.Context, method string, in interface{}, out interface{}, ...) error
- func MatchClientStreamMsgCount(expected int) func() (string, matcher.MatchFn)
- type ClientStreamHandler
- type ContextDialer
- type InvokeOption
- func WithBufConnDialer(l *bufconn.Listener) InvokeOption
- func WithCallOptions(opts ...grpc.CallOption) InvokeOption
- func WithContextDialer(d ContextDialer) InvokeOption
- func WithDialOptions(opts ...grpc.DialOption) InvokeOption
- func WithHeader(key, value string) InvokeOption
- func WithHeaders(header map[string]string) InvokeOption
- func WithInsecure() InvokeOption
- type Server
- func (s *Server) Address() string
- func (s *Server) Close() error
- func (s *Server) ExpectBidirectionalStream(method string) *request.BidirectionalStreamRequest
- func (s *Server) ExpectClientStream(method string) *request.ClientStreamRequest
- func (s *Server) ExpectServerStream(method string) *request.ServerStreamRequest
- func (s *Server) ExpectUnary(method string) *request.UnaryRequest
- func (s *Server) ExpectationsWereMet() error
- func (s *Server) ResetExpectations()
- func (s *Server) Serve()
- func (s *Server) WithPlanner(p planner.Planner) *Server
- func (s *Server) WithTest(t T) *Server
- type ServerMocker
- type ServerMockerWithContextDialer
- type ServerOption
- func ChainStreamInterceptor(interceptors ...grpc.StreamServerInterceptor) ServerOption
- func ChainUnaryInterceptor(interceptors ...grpc.UnaryServerInterceptor) ServerOption
- func ConnectionTimeout(d time.Duration) ServerOption
- func Creds(c credentials.TransportCredentials) ServerOption
- func InTapHandle(h tap.ServerInHandle) ServerOption
- func InitialConnWindowSize(sz int32) ServerOption
- func InitialWindowSize(sz int32) ServerOption
- func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption
- func KeepaliveParams(kp keepalive.ServerParameters) ServerOption
- func MaxConcurrentStreams(n uint32) ServerOption
- func MaxHeaderListSize(sz uint32) ServerOption
- func MaxRecvMsgSize(m int) ServerOption
- func MaxSendMsgSize(m int) ServerOption
- func ReadBufferSize(sz int) ServerOption
- func RegisterService(registerFunc interface{}) ServerOption
- func RegisterServiceFromInstance(id string, svc interface{}) ServerOption
- func RegisterServiceFromMethods(serviceMethods ...service.Method) ServerOption
- func StatsHandler(h stats.Handler) ServerOption
- func StreamInterceptor(i grpc.StreamServerInterceptor) ServerOption
- func UnaryInterceptor(i grpc.UnaryServerInterceptor) ServerOption
- func UnknownServiceHandler(streamHandler grpc.StreamHandler) ServerOption
- func WithAddress(addr string) ServerOption
- func WithListener(l net.Listener) ServerOption
- func WithPlanner(p planner.Planner) ServerOption
- func WithPort(port int) ServerOption
- func WriteBufferSize(sz int) ServerOption
- type T
Examples ¶
- MockServer
- MockServerWithBufConn
- NewServer (BidirectionalStreamMethod)
- NewServer (ClientStreamMethod)
- NewServer (ClientStreamMethod_customHandler)
- NewServer (ServerStreamMethod)
- NewServer (ServerStreamMethod_customHandler)
- NewServer (ServerStreamMethod_customStreamBehaviors)
- NewServer (UnaryMethod)
- NewServer (UnaryMethod_customHandler)
- NewServer (WithPort)
- RegisterService
- RegisterServiceFromInstance
- RegisterServiceFromMethods
- Server (FirstMatch_planner)
- Server.WithPlanner
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FindServerMethod ¶ added in v0.13.0
FindServerMethod finds a method in the given server.
func InvokeBidirectionalStream ¶ added in v0.3.0
func InvokeBidirectionalStream( ctx context.Context, method string, handle ClientStreamHandler, opts ...InvokeOption, ) error
InvokeBidirectionalStream invokes a bidirectional-stream method.
func InvokeClientStream ¶ added in v0.2.0
func InvokeClientStream( ctx context.Context, method string, handle ClientStreamHandler, out interface{}, opts ...InvokeOption, ) error
InvokeClientStream invokes a client-stream method.
func InvokeServerStream ¶ added in v0.2.0
func InvokeServerStream( ctx context.Context, method string, in interface{}, handle ClientStreamHandler, opts ...InvokeOption, ) error
InvokeServerStream invokes a server-stream method.
func InvokeUnary ¶
func InvokeUnary( ctx context.Context, method string, in interface{}, out interface{}, opts ...InvokeOption, ) error
InvokeUnary invokes a unary method.
Types ¶
type ClientStreamHandler ¶ added in v0.2.0
type ClientStreamHandler func(s grpc.ClientStream) error
ClientStreamHandler handles a client stream.
func RecvAll ¶ added in v0.2.0
func RecvAll(out interface{}) ClientStreamHandler
RecvAll reads everything from the stream and put into the output.
func SendAll ¶ added in v0.2.0
func SendAll(in interface{}) ClientStreamHandler
SendAll sends everything to the stream.
func SendAndRecvAll ¶ added in v0.3.0
func SendAndRecvAll(in interface{}, out interface{}) ClientStreamHandler
SendAndRecvAll sends and receives messages to and from grpc server in turn until server sends the io.EOF.
func (ClientStreamHandler) Handle ¶ added in v0.2.0
func (h ClientStreamHandler) Handle(s grpc.ClientStream) error
Handle handles a client stream.
type ContextDialer ¶
ContextDialer is to set up the dialer.
type InvokeOption ¶
type InvokeOption func(c *invokeConfig)
InvokeOption sets invoker config.
func WithBufConnDialer ¶
func WithBufConnDialer(l *bufconn.Listener) InvokeOption
WithBufConnDialer sets a *bufconn.Listener as the context dialer.
See:
- grpcmock.WithContextDialer()
func WithCallOptions ¶ added in v0.4.0
func WithCallOptions(opts ...grpc.CallOption) InvokeOption
WithCallOptions sets call options.
func WithContextDialer ¶
func WithContextDialer(d ContextDialer) InvokeOption
WithContextDialer sets a context dialer to create connections.
See:
- grpcmock.WithBufConnDialer()
func WithDialOptions ¶
func WithDialOptions(opts ...grpc.DialOption) InvokeOption
WithDialOptions sets dial options.
func WithHeaders ¶
func WithHeaders(header map[string]string) InvokeOption
WithHeaders sets request header.
func WithInsecure ¶
func WithInsecure() InvokeOption
WithInsecure disables transport security for the connections.
type Server ¶ added in v0.9.0
type Server struct { // Holds the requested that were made to this server. Requests []request.Request // contains filtered or unexported fields }
Server wraps a grpc server and provides mocking functionalities.
Example (FirstMatch_planner) ¶
package main import ( "context" "encoding/json" "fmt" "math/rand" "sync" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/planner" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithPlanner(planner.FirstMatch()), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 1}). Return(&grpctest.Item{Id: 1, Name: "FoodUniversity"}) s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 2}). Return(&grpctest.Item{Id: 2, Name: "Metaverse"}) s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 3}). Return(&grpctest.Item{Id: 3, Name: "Crypto"}) }, ) defer srv.Close() // nolint: errcheck // Call the service. ids := []int32{1, 2, 3} result := make([]*grpctest.Item, len(ids)) rand.Shuffle(len(ids), func(i, j int) { ids[i], ids[j] = ids[j], ids[i] }) var wg sync.WaitGroup for _, id := range ids { wg.Add(1) go func(id int32) { defer wg.Done() out := &grpctest.Item{} err := grpcmock.InvokeUnary(context.Background(), "grpctest.ItemService/GetItem", &grpctest.GetItemRequest{Id: id}, out, grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) result[id-1] = out }(id) } wg.Wait() output, err := json.MarshalIndent(result, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: [ { "id": 1, "name": "FoodUniversity" }, { "id": 2, "name": "Metaverse" }, { "id": 3, "name": "Crypto" } ]
func NewServer ¶ added in v0.9.0
func NewServer(opts ...ServerOption) *Server
NewServer creates mocked server.
Example (BidirectionalStreamMethod) ¶
package main import ( "context" "encoding/json" "errors" "fmt" "io" "google.golang.org/grpc" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectBidirectionalStream("grpctest.ItemService/TransformItems"). Run(func(ctx context.Context, s grpc.ServerStream) error { for { item := &grpctest.Item{} err := s.RecvMsg(item) if errors.Is(err, io.EOF) { return nil } if err != nil { return err } item.Name = fmt.Sprintf("Modified #%d", item.Id) if err := s.SendMsg(item); err != nil { return err } } }) }, ) defer srv.Close() // nolint: errcheck // Call the service. in := []*grpctest.Item{ {Id: 40, Name: "Item #40"}, {Id: 41, Name: "Item #41"}, {Id: 42, Name: "Item #42"}, } out := make([]*grpctest.Item, 0) err := grpcmock.InvokeBidirectionalStream(context.Background(), "grpctest.ItemService/TransformItems", grpcmock.SendAndRecvAll(in, &out), grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: [ { "id": 40, "name": "Modified #40" }, { "id": 41, "name": "Modified #41" }, { "id": 42, "name": "Modified #42" } ]
Example (ClientStreamMethod) ¶
package main import ( "context" "encoding/json" "fmt" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectClientStream("grpctest.ItemService/CreateItems"). WithPayload([]*grpctest.Item{ {Id: 41, Name: "Item #41"}, {Id: 42, Name: "Item #42"}, }). Return(&grpctest.CreateItemsResponse{NumItems: 2}) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := &grpctest.CreateItemsResponse{} err := grpcmock.InvokeClientStream(context.Background(), "grpctest.ItemService/CreateItems", grpcmock.SendAll([]*grpctest.Item{ {Id: 41, Name: "Item #41"}, {Id: 42, Name: "Item #42"}, }), out, grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: { "num_items": 2 }
Example (ClientStreamMethod_customHandler) ¶
package main import ( "context" "encoding/json" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/stream" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectClientStream("grpctest.ItemService/CreateItems"). WithPayload(grpcmock.MatchClientStreamMsgCount(3)). Run(func(_ context.Context, s grpc.ServerStream) (interface{}, error) { out := make([]*grpctest.Item, 0) if err := stream.RecvAll(s, &out); err != nil { return nil, err } cnt := int64(0) for _, msg := range out { if msg.Id > 40 { cnt++ } } return &grpctest.CreateItemsResponse{NumItems: cnt}, nil }) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := &grpctest.CreateItemsResponse{} err := grpcmock.InvokeClientStream(context.Background(), "grpctest.ItemService/CreateItems", grpcmock.SendAll([]*grpctest.Item{ {Id: 40, Name: "Item #40"}, {Id: 41, Name: "Item #41"}, {Id: 42, Name: "Item #42"}, }), out, grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: { "num_items": 2 }
Example (ServerStreamMethod) ¶
package main import ( "context" "encoding/json" "fmt" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectServerStream("grpctest.ItemService/ListItems"). Return([]*grpctest.Item{ {Id: 41, Name: "Item #41"}, {Id: 42, Name: "Item #42"}, }) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := make([]*grpctest.Item, 0) err := grpcmock.InvokeServerStream(context.Background(), "grpctest.ItemService/ListItems", &grpctest.ListItemsRequest{}, grpcmock.RecvAll(&out), grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: [ { "id": 41, "name": "Item #41" }, { "id": 42, "name": "Item #42" } ]
Example (ServerStreamMethod_customHandler) ¶
package main import ( "context" "encoding/json" "fmt" "google.golang.org/grpc" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectServerStream("grpctest.ItemService/ListItems"). Run(func(_ context.Context, _ interface{}, s grpc.ServerStream) error { _ = s.SendMsg(&grpctest.Item{Id: 41, Name: "Item #41"}) // nolint: errcheck _ = s.SendMsg(&grpctest.Item{Id: 42, Name: "Item #42"}) // nolint: errcheck return nil }) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := make([]*grpctest.Item, 0) err := grpcmock.InvokeServerStream(context.Background(), "grpctest.ItemService/ListItems", &grpctest.ListItemsRequest{}, grpcmock.RecvAll(&out), grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: [ { "id": 41, "name": "Item #41" }, { "id": 42, "name": "Item #42" } ]
Example (ServerStreamMethod_customStreamBehaviors) ¶
package main import ( "context" "fmt" "google.golang.org/grpc/codes" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectServerStream("grpctest.ItemService/ListItems"). ReturnStream(). Send(&grpctest.Item{Id: 41, Name: "Item #41"}). ReturnError(codes.Aborted, "server aborted the transaction") }, ) defer srv.Close() // nolint: errcheck // Call the service. out := make([]*grpctest.Item, 0) err := grpcmock.InvokeServerStream(context.Background(), "grpctest.ItemService/ListItems", &grpctest.ListItemsRequest{}, grpcmock.RecvAll(&out), grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) fmt.Printf("received items: %d\n", len(out)) fmt.Printf("error: %s", err) }
Output: received items: 0 error: rpc error: code = Aborted desc = server aborted the transaction
Example (UnaryMethod) ¶
package main import ( "context" "encoding/json" "fmt" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 41}). Return(&grpctest.Item{ Id: 41, Locale: "en-US", Name: "Item #41", }) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := &grpctest.Item{} err := grpcmock.InvokeUnary(context.Background(), "grpctest.ItemService/GetItem", &grpctest.GetItemRequest{Id: 41}, out, grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: { "id": 41, "locale": "en-US", "name": "Item #41" }
Example (UnaryMethod_customHandler) ¶
package main import ( "context" "encoding/json" "fmt" "google.golang.org/grpc/metadata" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 42}). Run(func(ctx context.Context, in interface{}) (interface{}, error) { req := in.(*grpctest.GetItemRequest) // nolint: errcheck var locale string md, _ := metadata.FromIncomingContext(ctx) if md != nil { if values := md.Get("locale"); len(values) > 0 { locale = values[0] } } return &grpctest.Item{ Id: req.Id, Locale: locale, Name: fmt.Sprintf("Item #%d", req.Id), }, nil }) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := &grpctest.Item{} err := grpcmock.InvokeUnary(context.Background(), "grpctest.ItemService/GetItem", &grpctest.GetItemRequest{Id: 42}, out, grpcmock.WithHeader("locale", "en-US"), grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: { "id": 42, "locale": "en-US", "name": "Item #42" }
Example (WithPort) ¶
package main import ( "context" "encoding/json" "fmt" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithPort(8080), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 41}). Return(&grpctest.Item{ Id: 41, Locale: "en-US", Name: "Item #41", }) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := &grpctest.Item{} err := grpcmock.InvokeUnary(context.Background(), ":8080/grpctest.ItemService/GetItem", &grpctest.GetItemRequest{Id: 41}, out, grpcmock.WithInsecure(), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: { "id": 41, "locale": "en-US", "name": "Item #41" }
func NewUnstartedServer ¶ added in v0.12.0
func NewUnstartedServer(opts ...ServerOption) *Server
NewUnstartedServer returns a new Server but doesn't start it.
func (*Server) ExpectBidirectionalStream ¶ added in v0.10.0
func (s *Server) ExpectBidirectionalStream(method string) *request.BidirectionalStreamRequest
ExpectBidirectionalStream adds a new expected bidirectional-stream request.
Server.ExpectBidirectionalStream("grpctest.Service/TransformItems")
func (*Server) ExpectClientStream ¶ added in v0.9.0
func (s *Server) ExpectClientStream(method string) *request.ClientStreamRequest
ExpectClientStream adds a new expected client-stream request.
Server.ExpectClientStream("grpctest.Service/CreateItems")
func (*Server) ExpectServerStream ¶ added in v0.9.0
func (s *Server) ExpectServerStream(method string) *request.ServerStreamRequest
ExpectServerStream adds a new expected server-stream request.
Server.ExpectServerStream("grpctest.Service/ListItems")
func (*Server) ExpectUnary ¶ added in v0.9.0
func (s *Server) ExpectUnary(method string) *request.UnaryRequest
ExpectUnary adds a new expected unary request.
Server.ExpectUnary("grpctest.Service/GetItem")
func (*Server) ExpectationsWereMet ¶ added in v0.9.0
ExpectationsWereMet checks whether all queued expectations were met in order. If any of them was not met - an error is returned.
func (*Server) ResetExpectations ¶ added in v0.9.0
func (s *Server) ResetExpectations()
ResetExpectations resets all the expectations.
func (*Server) WithPlanner ¶ added in v0.9.0
WithPlanner sets the planner.
Example ¶
package main import ( "context" "errors" "fmt" "github.com/stretchr/testify/mock" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" plannerMock "github.com/nhatthm/grpcmock/mock/planner" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { p := &plannerMock.Planner{} p.On("IsEmpty").Return(false) p.On("Expect", mock.Anything) p.On("Plan", mock.Anything, mock.Anything, mock.Anything). Return(nil, errors.New("always fail")) s.WithPlanner(p) s.ExpectUnary("grpctest.ItemService/GetItem"). Run(func(context.Context, interface{}) (interface{}, error) { panic(`this never happens`) }) }, ) defer srv.Close() // nolint: errcheck // Call the service. err := grpcmock.InvokeUnary(context.Background(), "grpctest.ItemService/GetItem", &grpctest.GetItemRequest{Id: 41}, &grpctest.Item{}, grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) fmt.Println(err) }
Output: rpc error: code = Internal desc = always fail
type ServerMocker ¶ added in v0.9.0
ServerMocker is a constructor to create a new mocked server.
func MockServer ¶ added in v0.9.0
func MockServer(opts ...ServerOption) ServerMocker
MockServer starts a new mocked server and ensures all the expectations were met at the end of the test.
Example ¶
package main import ( "context" "encoding/json" "fmt" "github.com/stretchr/testify/require" "github.com/nhatthm/grpcmock" grpcAssert "github.com/nhatthm/grpcmock/assert" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { // Simulate a test function. // // In reality, it's just straightforward: // func TestMockAndStartServer(t *testing.T) { // t.Parallel() // // s, d := grpcmock.MockServer() // // Client call and assertions. // } TestMockServer := func(t grpcmock.T) { srv := grpcmock.MockServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 41}). Return(&grpctest.Item{ Id: 41, Locale: "en-US", Name: "Item #41", }) }, )(t) // Call the service. out := &grpctest.Item{} method := fmt.Sprintf("%s/grpctest.ItemService/GetItem", srv.Address()) err := grpcmock.InvokeUnary(context.Background(), method, &grpctest.GetItemRequest{Id: 41}, out, grpcmock.WithInsecure(), ) expected := &grpctest.Item{ Id: 41, Locale: "en-US", Name: "Item #41", } require.NoError(t, err) grpcAssert.EqualMessage(t, expected, out) output, err := json.MarshalIndent(out, "", " ") require.NoError(t, err) // Output for the example. fmt.Println(string(output)) } TestMockServer(grpcmock.NoOpT()) }
Output: { "id": 41, "locale": "en-US", "name": "Item #41" }
func MockUnstartedServer ¶ added in v0.12.0
func MockUnstartedServer(opts ...ServerOption) ServerMocker
MockUnstartedServer mocks the server and ensures all the expectations were met at the end of the test.
type ServerMockerWithContextDialer ¶ added in v0.9.0
type ServerMockerWithContextDialer func(t T) (*Server, ContextDialer)
ServerMockerWithContextDialer starts a new mocked server with a bufconn and returns it as a context dialer for the grpc.DialOption.
func MockServerWithBufConn ¶ added in v0.12.0
func MockServerWithBufConn(opts ...ServerOption) ServerMockerWithContextDialer
MockServerWithBufConn starts a new mocked server with bufconn and ensures all the expectations were met at the end of the test.
Example ¶
package main import ( "context" "encoding/json" "fmt" "github.com/stretchr/testify/require" "github.com/nhatthm/grpcmock" grpcAssert "github.com/nhatthm/grpcmock/assert" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { // Simulate a test function. // // In reality, it's just straightforward: // func TestMockAndStartServer(t *testing.T) { // t.Parallel() // // s, d := grpcmock.MockServerWithBufConn() // // Client call and assertions. // } TestMockServerWithBufConn := func(t grpcmock.T) { _, d := grpcmock.MockServerWithBufConn( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 41}). Return(&grpctest.Item{ Id: 41, Locale: "en-US", Name: "Item #41", }) }, )(t) // Call the service. out := &grpctest.Item{} err := grpcmock.InvokeUnary(context.Background(), "grpctest.ItemService/GetItem", &grpctest.GetItemRequest{Id: 41}, out, grpcmock.WithInsecure(), grpcmock.WithContextDialer(d), ) expected := &grpctest.Item{ Id: 41, Locale: "en-US", Name: "Item #41", } require.NoError(t, err) grpcAssert.EqualMessage(t, expected, out) output, err := json.MarshalIndent(out, "", " ") require.NoError(t, err) // Output for the example. fmt.Println(string(output)) } TestMockServerWithBufConn(grpcmock.NoOpT()) }
Output: { "id": 41, "locale": "en-US", "name": "Item #41" }
type ServerOption ¶ added in v0.9.0
type ServerOption func(s *Server)
ServerOption sets up the mocked server.
func ChainStreamInterceptor ¶ added in v0.9.0
func ChainStreamInterceptor(interceptors ...grpc.StreamServerInterceptor) ServerOption
ChainStreamInterceptor is a wrapper of google.golang.org/grpc.ChainStreamInterceptor().
func ChainUnaryInterceptor ¶ added in v0.9.0
func ChainUnaryInterceptor(interceptors ...grpc.UnaryServerInterceptor) ServerOption
ChainUnaryInterceptor is a wrapper of google.golang.org/grpc.ChainUnaryInterceptor().
func ConnectionTimeout ¶ added in v0.9.0
func ConnectionTimeout(d time.Duration) ServerOption
ConnectionTimeout is a wrapper of google.golang.org/grpc.ConnectionTimeout().
func Creds ¶ added in v0.9.0
func Creds(c credentials.TransportCredentials) ServerOption
Creds is a wrapper of google.golang.org/grpc.Creds().
func InTapHandle ¶ added in v0.9.0
func InTapHandle(h tap.ServerInHandle) ServerOption
InTapHandle is a wrapper of google.golang.org/grpc.InTapHandle().
func InitialConnWindowSize ¶ added in v0.9.0
func InitialConnWindowSize(sz int32) ServerOption
InitialConnWindowSize is a wrapper of google.golang.org/grpc.InitialConnWindowSize().
func InitialWindowSize ¶ added in v0.9.0
func InitialWindowSize(sz int32) ServerOption
InitialWindowSize is a wrapper of google.golang.org/grpc.InitialWindowSize().
func KeepaliveEnforcementPolicy ¶ added in v0.9.0
func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption
KeepaliveEnforcementPolicy is a wrapper of google.golang.org/grpc.KeepaliveEnforcementPolicy().
func KeepaliveParams ¶ added in v0.9.0
func KeepaliveParams(kp keepalive.ServerParameters) ServerOption
KeepaliveParams is a wrapper of google.golang.org/grpc.KeepaliveParams().
func MaxConcurrentStreams ¶ added in v0.9.0
func MaxConcurrentStreams(n uint32) ServerOption
MaxConcurrentStreams is a wrapper of google.golang.org/grpc.MaxConcurrentStreams().
func MaxHeaderListSize ¶ added in v0.9.0
func MaxHeaderListSize(sz uint32) ServerOption
MaxHeaderListSize is a wrapper of google.golang.org/grpc.MaxHeaderListSize().
func MaxRecvMsgSize ¶ added in v0.9.0
func MaxRecvMsgSize(m int) ServerOption
MaxRecvMsgSize is a wrapper of google.golang.org/grpc.MaxRecvMsgSize().
func MaxSendMsgSize ¶ added in v0.9.0
func MaxSendMsgSize(m int) ServerOption
MaxSendMsgSize is a wrapper of google.golang.org/grpc.MaxSendMsgSize().
func ReadBufferSize ¶ added in v0.9.0
func ReadBufferSize(sz int) ServerOption
ReadBufferSize is a wrapper of google.golang.org/grpc.ReadBufferSize().
func RegisterService ¶ added in v0.9.0
func RegisterService(registerFunc interface{}) ServerOption
RegisterService registers a new service using the generated register function.
grpcmock.MockUnstartedServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem").UnlimitedTimes(). Return(&grpctest.Item{}) }, )(t)
See: RegisterServiceFromInstance(), RegisterServiceFromMethods().
Example ¶
package main import ( "context" "encoding/json" "fmt" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 41}). Return(&grpctest.Item{ Id: 41, Locale: "en-US", Name: "Item #41", }) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := &grpctest.Item{} err := grpcmock.InvokeUnary(context.Background(), "grpctest.ItemService/GetItem", &grpctest.GetItemRequest{Id: 41}, out, grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: { "id": 41, "locale": "en-US", "name": "Item #41" }
func RegisterServiceFromInstance ¶ added in v0.9.0
func RegisterServiceFromInstance(id string, svc interface{}) ServerOption
RegisterServiceFromInstance registers a new service using the generated server interface.
grpcmock.MockUnstartedServer( grpcmock.RegisterServiceFromInstance("grpctest.ItemService", (*grpctest.ItemServiceServer)(nil)), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem").UnlimitedTimes(). Return(&grpctest.Item{}) }, )(t)
See: RegisterService(), RegisterServiceFromMethods().
Example ¶
package main import ( "context" "encoding/json" "fmt" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterServiceFromInstance("grpctest.ItemService", (*grpctest.ItemServiceServer)(nil)), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 41}). Return(&grpctest.Item{ Id: 41, Locale: "en-US", Name: "Item #41", }) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := &grpctest.Item{} err := grpcmock.InvokeUnary(context.Background(), "grpctest.ItemService/GetItem", &grpctest.GetItemRequest{Id: 41}, out, grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: { "id": 41, "locale": "en-US", "name": "Item #41" }
func RegisterServiceFromMethods ¶ added in v0.9.0
func RegisterServiceFromMethods(serviceMethods ...service.Method) ServerOption
RegisterServiceFromMethods registers a new service using service.Method definition.
grpcmock.MockUnstartedServer( grpcmock.RegisterServiceFromMethods(service.Method{ ServiceName: "grpctest.ItemService", MethodName: "GetItem", MethodType: service.TypeUnary, Input: &grpctest.GetItemRequest{}, Output: &grpctest.Item{}, }), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem").UnlimitedTimes(). Return(&grpctest.Item{}) }, )(t)
See: RegisterService(), RegisterServiceFromInstance().
Example ¶
package main import ( "context" "encoding/json" "fmt" "google.golang.org/grpc/test/bufconn" "github.com/nhatthm/grpcmock" "github.com/nhatthm/grpcmock/must" "github.com/nhatthm/grpcmock/service" "github.com/nhatthm/grpcmock/test/grpctest" ) func main() { buf := bufconn.Listen(1024 * 1024) defer buf.Close() // nolint: errcheck srv := grpcmock.NewServer( grpcmock.RegisterServiceFromMethods(service.Method{ ServiceName: "grpctest.ItemService", MethodName: "GetItem", MethodType: service.TypeUnary, Input: &grpctest.GetItemRequest{}, Output: &grpctest.Item{}, }), grpcmock.WithListener(buf), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem"). WithPayload(&grpctest.GetItemRequest{Id: 41}). Return(&grpctest.Item{ Id: 41, Locale: "en-US", Name: "Item #41", }) }, ) defer srv.Close() // nolint: errcheck // Call the service. out := &grpctest.Item{} err := grpcmock.InvokeUnary(context.Background(), "grpctest.ItemService/GetItem", &grpctest.GetItemRequest{Id: 41}, out, grpcmock.WithInsecure(), grpcmock.WithBufConnDialer(buf), ) must.NotFail(err) output, err := json.MarshalIndent(out, "", " ") must.NotFail(err) fmt.Println(string(output)) }
Output: { "id": 41, "locale": "en-US", "name": "Item #41" }
func StatsHandler ¶ added in v0.9.0
func StatsHandler(h stats.Handler) ServerOption
StatsHandler is a wrapper of google.golang.org/grpc.StatsHandler().
func StreamInterceptor ¶ added in v0.9.0
func StreamInterceptor(i grpc.StreamServerInterceptor) ServerOption
StreamInterceptor is a wrapper of google.golang.org/grpc.ChainStreamInterceptor().
func UnaryInterceptor ¶ added in v0.9.0
func UnaryInterceptor(i grpc.UnaryServerInterceptor) ServerOption
UnaryInterceptor is a wrapper of google.golang.org/grpc.ChainUnaryInterceptor().
func UnknownServiceHandler ¶ added in v0.9.0
func UnknownServiceHandler(streamHandler grpc.StreamHandler) ServerOption
UnknownServiceHandler is a wrapper of google.golang.org/grpc.UnknownServiceHandler().
func WithAddress ¶ added in v0.12.0
func WithAddress(addr string) ServerOption
WithAddress sets server address.
func WithListener ¶ added in v0.12.0
func WithListener(l net.Listener) ServerOption
WithListener sets the listener. Server does not need to start a new one.
func WithPlanner ¶ added in v0.11.0
func WithPlanner(p planner.Planner) ServerOption
WithPlanner sets the expectations' planner.
grpcmock.MockServer( grpcmock.RegisterService(grpctest.RegisterItemServiceServer), grpcmock.WithPlanner(planner.FirstMatch()), func(s *grpcmock.Server) { s.ExpectUnary("grpctest.ItemService/GetItem").UnlimitedTimes(). Return(&grpctest.Item{}) }, )(t)
func WithPort ¶ added in v0.12.0
func WithPort(port int) ServerOption
WithPort sets server address port.
func WriteBufferSize ¶ added in v0.9.0
func WriteBufferSize(sz int) ServerOption
WriteBufferSize is a wrapper of google.golang.org/grpc.WriteBufferSize().
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
Package assert provides assertions for grpc.
|
Package assert provides assertions for grpc. |
Package errors provides predefined errors.
|
Package errors provides predefined errors. |
Package format formats the requests.
|
Package format formats the requests. |
Package invoker constructs a grpc request and executes it.
|
Package invoker constructs a grpc request and executes it. |
Package matcher provides custom matchers for gRPC requests.
|
Package matcher provides custom matchers for gRPC requests. |
mock
|
|
grpc
Package grpc provides mock for grpc types.
|
Package grpc provides mock for grpc types. |
planner
Package planner provides mock for planner.
|
Package planner provides mock for planner. |
Package must panic on error.
|
Package must panic on error. |
Package planner provides functionalities for deciding what expectation matches the given request.
|
Package planner provides functionalities for deciding what expectation matches the given request. |
Package reflect provides a simple reflection on the grpc server.
|
Package reflect provides a simple reflection on the grpc server. |
Package request provides all the expectations for an RPC method.
|
Package request provides all the expectations for an RPC method. |
Package service provides service definition.
|
Package service provides service definition. |
Package stream provides functions to send or receive messages using a grpc stream.
|
Package stream provides functions to send or receive messages using a grpc stream. |
Package streamer provides functionalities to work with server-side RPC stream.
|
Package streamer provides functionalities to work with server-side RPC stream. |
Package test provides helpers for testing grpcmock.
|
Package test provides helpers for testing grpcmock. |
Package value provides functionalities to convert a generic value to string.
|
Package value provides functionalities to convert a generic value to string. |