-
Notifications
You must be signed in to change notification settings - Fork 211
/
mock_grpc_server.go
53 lines (44 loc) · 1 KB
/
mock_grpc_server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package util
import (
"fmt"
"net"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
)
// MockGrpcServer allows for simulating a GRPC server in tests.
// Typical usage:
// ```
// gtw := NewMockGrpcServer(t)
// <register required GRPC services>
// var eg errgroup.Group
// eg.Go(gtw.Serve)
// t.Cleanup(func() { require.NoError(t, eg.Wait()) })
// t.Cleanup(gtw.Stop)
// ```
// .
type MockGrpcServer struct {
listener net.Listener
*grpc.Server
Port uint16
}
func NewMockGrpcServer(t testing.TB) *MockGrpcServer {
lis, err := net.Listen("tcp", ":0")
require.NoError(t, err)
port, err := strconv.ParseUint(strings.TrimPrefix(lis.Addr().String(), "[::]:"), 10, 16)
require.NoError(t, err)
s := grpc.NewServer()
return &MockGrpcServer{
listener: lis,
Server: s,
Port: uint16(port),
}
}
func (s *MockGrpcServer) Serve() error {
return s.Server.Serve(s.listener)
}
func (s *MockGrpcServer) Target() string {
return fmt.Sprintf("localhost:%d", s.Port)
}