grpctest

package
v0.0.26 Latest Latest
Warning

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

Go to latest
Published: Sep 30, 2022 License: BSD-3-Clause Imports: 3 Imported by: 0

Documentation

Overview

Package grpctest provides a test server for unit tests that use gRPC.

Example
package main

import (
	"context"
	"fmt"
	"os"

	"google.golang.org/grpc"

	gomapb "go.chromium.org/goma/server/proto/api"
	pb "go.chromium.org/goma/server/proto/execlog"
	"go.chromium.org/goma/server/rpc/grpctest"
)

// MyServer is fake execlog server.
type MyServer struct {
	pb.UnimplementedLogServiceServer
	Req  *gomapb.SaveLogReq
	Resp *gomapb.SaveLogResp
	Err  error
}

func (s *MyServer) SaveLog(ctx context.Context, req *gomapb.SaveLogReq) (*gomapb.SaveLogResp, error) {
	s.Req = req
	return s.Resp, s.Err
}

func main() {
	srv := grpc.NewServer()
	s := &MyServer{
		Resp: &gomapb.SaveLogResp{},
	}
	pb.RegisterLogServiceServer(srv, s)
	addr, stop, err := grpctest.StartServer(srv)
	if err != nil {
		fmt.Printf("error creating test server: %v\n", err)
		os.Exit(1)
	}
	defer stop()

	conn, err := grpc.Dial(addr, grpc.WithInsecure())
	if err != nil {
		fmt.Printf("error connecting to %s: %v\n", addr, err)
		os.Exit(1)
	}
	defer conn.Close()
	client := pb.NewLogServiceClient(conn)
	ctx := context.Background()
	resp, err := client.SaveLog(ctx, &gomapb.SaveLogReq{})
	if err != nil {
		fmt.Printf("SaveLog()=%v, %v; want nil error\n", resp, err)
		os.Exit(1)
	}
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func StartServer

func StartServer(server *grpc.Server) (addr string, stop func(), err error)

StartServer instantiates a gRPC server suitable for unit tests, and returns the server address the client can use to connect and a stop function that must be called if err is nil to stop the server and cleanup resources.

Types

This section is empty.

Jump to

Keyboard shortcuts

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