grpcmock

package module
Version: v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2022 License: MIT Imports: 31 Imported by: 1

README

gRPC Test Utilities for Golang

GitHub Releases Build Status codecov Go Report Card GoDevDoc Donate

Test gRPC service and client like a pro.

Table of Contents

Prerequisites

  • Go >= 1.17

[table of contents]

Install

go get github.com/nhatthm/grpcmock

[table of contents]

Usage

Mock a gRPC server

Read more about mocking a gRPC server

[table of contents]

Unary Method

Read more about mocking a Unary Method

package main

import (
	"context"
	"testing"
	"time"

	"github.com/nhatthm/grpcmock"
	grpcAssert "github.com/nhatthm/grpcmock/assert"
	"github.com/stretchr/testify/assert"
)

func TestGetItems(t *testing.T) {
	t.Parallel()

	expected := &Item{Id: 42, Name: "Item 42"}

	_, d := grpcmock.MockServerWithBufConn(
		grpcmock.RegisterService(RegisterItemServiceServer),
		func(s *grpcmock.Server) {
			s.ExpectUnary("myservice/GetItem").
				WithHeader("locale", "en-US").
				WithPayload(&GetItemRequest{Id: 42}).
				Return(expected)
		},
	)(t)

	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	out := &Item{}

	err := grpcmock.InvokeUnary(ctx,
		"myservice/GetItem",
		&GetItemRequest{Id: 42}, out,
		grpcmock.WithHeader("locale", "en-US"),
		grpcmock.WithContextDialer(d),
		grpcmock.WithInsecure(),
	)

	grpcAssert.EqualMessage(t, expected, out)
	assert.NoError(t, err)
}

[table of contents]

Client-Stream Method

Read more about mocking a Client-Stream Method

package main

import (
	"context"
	"testing"
	"time"

	"github.com/nhatthm/grpcmock"
	grpcAssert "github.com/nhatthm/grpcmock/assert"
	"github.com/stretchr/testify/assert"
)

func TestCreateItems(t *testing.T) {
	t.Parallel()

	expected := &CreateItemsResponse{NumItems: 1}

	_, d := grpcmock.MockServerWithBufConn(
		grpcmock.RegisterService(RegisterItemServiceServer),
		func(s *grpcmock.Server) {
			s.ExpectClientStream("myservice/CreateItems").
				WithPayload([]*Item{{Id: 42}}).
				Return(expected)
		},
	)(t)

	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	out := &CreateItemsResponse{}
	err := grpcmock.InvokeClientStream(ctx, "myservice/CreateItems",
		grpcmock.SendAll([]*Item{{Id: 42}}), out,
		grpcmock.WithContextDialer(d),
		grpcmock.WithInsecure(),
	)

	grpcAssert.EqualMessage(t, expected, out)
	assert.NoError(t, err)
}

[table of contents]

Server-Stream Method

Read more about mocking a Server-Stream Method

package main

import (
	"context"
	"testing"
	"time"

	"github.com/nhatthm/grpcmock"
	grpcAssert "github.com/nhatthm/grpcmock/assert"
	"github.com/stretchr/testify/assert"
)

func TestListItems(t *testing.T) {
	t.Parallel()

	expected := []*Item{
		{Id: 41, Name: "Item 41"},
		{Id: 42, Name: "Item 42"},
	}

	_, d := grpcmock.MockServerWithBufConn(
		grpcmock.RegisterService(RegisterItemServiceServer),
		func(s *grpcmock.Server) {
			s.ExpectServerStream("myservice/ListItems").
				WithPayload(&ListItemsRequest{}).
				Return(expected)
		},
	)(t)

	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	actual := make([]*Item, 0)

	err := grpcmock.InvokeServerStream(ctx,
		"myservice/ListItems",
		&ListItemsRequest{},
		grpcmock.RecvAll(&actual),
		grpcmock.WithContextDialer(d),
		grpcmock.WithInsecure(),
	)

	assert.NoError(t, err)
	assert.Len(t, actual, len(expected))

	for i := 0; i < len(expected); i++ {
		grpcAssert.EqualMessage(t, expected[i], actual[i])
	}
}

[table of contents]

Bidirectional-Stream Method

Read more about mocking a Bidirectional-Stream Method

package main

import (
	"context"
	"errors"
	"fmt"
	"io"
	"testing"
	"time"

	"github.com/nhatthm/grpcmock"
	grpcAssert "github.com/nhatthm/grpcmock/assert"
	"github.com/stretchr/testify/assert"
	"google.golang.org/grpc"
)

func TestTransformItems(t *testing.T) {
	t.Parallel()

	expected := []*Item{
		{Id: 41, Name: "Item 41"},
		{Id: 42, Name: "Item 42"},
	}

	_, d := grpcmock.MockServerWithBufConn(
		grpcmock.RegisterService(RegisterItemServiceServer),
		func(s *grpcmock.Server) {
			s.ExpectBidirectionalStream("myservice/TransformItems").
				Run(func(ctx context.Context, s grpc.ServerStream) error {
					for {
						item := &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
						}
					}
				})
		},
	)(t)

	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	in := []*Item{
		{Id: 41, Name: "Item 41"},
		{Id: 42, Name: "Item 42"},
	}

	actual := make([]*Item, 0)

	err := grpcmock.InvokeBidirectionalStream(ctx,
		"myservice/TransformItems",
		grpcmock.SendAndRecvAll(in, &actual),
		grpcmock.WithContextDialer(d),
		grpcmock.WithInsecure(),
	)

	assert.NoError(t, err)
	assert.Len(t, actual, len(expected))

	for i := 0; i < len(expected); i++ {
		grpcAssert.EqualMessage(t, expected[i], actual[i])
	}
}

[table of contents]

Invoke a gRPC method
Unary Method
package main

import (
	"context"
	"time"

	"github.com/nhatthm/grpcmock"
	"google.golang.org/grpc/test/bufconn"
)

func getItem(l *bufconn.Listener, id int32) (*Item, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	out := &Item{}
	err := grpcmock.InvokeUnary(ctx, "myservice/GetItem",
		&GetItemRequest{Id: id}, out,
		grpcmock.WithHeader("Locale", "en-US"),
		grpcmock.WithBufConnDialer(l),
		grpcmock.WithInsecure(),
	)

	return out, err
}

[table of contents]

Client-Stream Method
package main

import (
	"context"
	"time"

	"github.com/nhatthm/grpcmock"
	"google.golang.org/grpc/test/bufconn"
)

func createItems(l *bufconn.Listener, items []*Item) (*CreateItemsResponse, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	out := &CreateItemsResponse{}
	err := grpcmock.InvokeClientStream(ctx, "myservice/CreateItems",
		grpcmock.SendAll(items), out,
		grpcmock.WithBufConnDialer(l),
		grpcmock.WithInsecure(),
	)

	return out, err
}

Or with a custom handler

package main

import (
	"context"
	"time"

	"github.com/nhatthm/grpcmock"
	"google.golang.org/grpc"
	"google.golang.org/grpc/test/bufconn"
)

func createItems(l *bufconn.Listener, items []*Item) (*CreateItemsResponse, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	out := &CreateItemsResponse{}
	err := grpcmock.InvokeClientStream(ctx, "myservice/CreateItems",
		func(s grpc.ClientStream) error {
			// Handle the stream here.
			return nil
		},
		out,
		grpcmock.WithBufConnDialer(l),
		grpcmock.WithInsecure(),
	)

	return out, err
}

[table of contents]

Server-Stream Method
package main

import (
	"context"
	"time"

	"github.com/nhatthm/grpcmock"
	"google.golang.org/grpc/test/bufconn"
)

func listItems(l *bufconn.Listener) ([]*Item, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	out := make([]*Item, 0)
	err := grpcmock.InvokeServerStream(ctx, "myservice/ListItems",
		&ListItemsRequest{},
		grpcmock.RecvAll(&out),
		grpcmock.WithBufConnDialer(l),
		grpcmock.WithInsecure(),
	)

	return out, err
}

Or with a custom handler

package main

import (
	"context"
	"time"

	"github.com/nhatthm/grpcmock"
	"google.golang.org/grpc"
	"google.golang.org/grpc/test/bufconn"
)

func listItems(l *bufconn.Listener) ([]*Item, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	out := make([]*Item, 0)
	err := grpcmock.InvokeServerStream(ctx, "myservice/ListItems",
		&ListItemsRequest{},
		func(s grpc.ClientStream) error {
			// Handle the stream here.
			return nil
		},
		grpcmock.WithBufConnDialer(l),
		grpcmock.WithInsecure(),
	)

	return out, err
}

[table of contents]

Bidirectional-Stream Method
package main

import (
	"context"
	"time"

	"github.com/nhatthm/grpcmock"
	"google.golang.org/grpc/test/bufconn"
)

func transformItems(l *bufconn.Listener, in []*Item) ([]*Item, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	out := make([]*Item, 0)
	err := grpcmock.InvokeBidirectionalStream(ctx, "myservice/TransformItems",
		grpcmock.SendAndRecvAll(in, &out),
		grpcmock.WithBufConnDialer(l),
		grpcmock.WithInsecure(),
	)

	return out, err
}

Or with a custom handler

package main

import (
	"context"
	"time"

	"github.com/nhatthm/grpcmock"
	"google.golang.org/grpc"
	"google.golang.org/grpc/test/bufconn"
)

func transformItems(l *bufconn.Listener, in []*Item) ([]*Item, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*50)
	defer cancel()

	out := make([]*Item, 0)
	err := grpcmock.InvokeBidirectionalStream(ctx, "myservice/TransformItems",
		func(s grpc.ClientStream) error {
			// Handle the stream here.
			return nil
		},
		grpcmock.WithBufConnDialer(l),
		grpcmock.WithInsecure(),
	)

	return out, err
}

[table of contents]

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

[table of contents]

Paypal donation

paypal

       or scan this

[table of contents]

Documentation

Overview

Package grpcmock provides functionalities for testing grpc client and server.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func FindServerMethod added in v0.13.0

func FindServerMethod(srv *Server, method string) *service.Method

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.

func MatchClientStreamMsgCount added in v0.9.0

func MatchClientStreamMsgCount(expected int) func() (string, matcher.MatchFn)

MatchClientStreamMsgCount matches a number of messages.

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

Handle handles a client stream.

type ContextDialer

type ContextDialer = func(context.Context, string) (net.Conn, error)

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 WithHeader

func WithHeader(key, value string) InvokeOption

WithHeader sets request header.

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) Address added in v0.12.0

func (s *Server) Address() string

Address returns server address.

func (*Server) Close added in v0.9.0

func (s *Server) Close() error

Close stops and closes all open connections and listeners.

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

func (s *Server) ExpectationsWereMet() error

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) Serve added in v0.9.0

func (s *Server) Serve()

Serve runs the grpc server.

func (*Server) WithPlanner added in v0.9.0

func (s *Server) WithPlanner(p planner.Planner) *Server

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

func (*Server) WithTest added in v0.9.0

func (s *Server) WithTest(t T) *Server

WithTest sets the *testing.T of the server.

type ServerMocker added in v0.9.0

type ServerMocker func(t T) *Server

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

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().

type T added in v0.9.0

type T interface {
	Errorf(format string, args ...interface{})
	FailNow()
	Cleanup(func())
}

T is an interface wrapper around *testing.T.

func NoOpT added in v0.9.0

func NoOpT() T

NoOpT initiates a new T that does nothing.

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.

Jump to

Keyboard shortcuts

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