-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmock.go
55 lines (42 loc) · 1.52 KB
/
mock.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
54
55
package grpcmock
import (
"context"
"net"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc/test/bufconn"
)
// ServerMocker is a constructor to create a new mocked server.
type ServerMocker func(t T) *Server
// ServerMockerWithContextDialer starts a new mocked server with a bufconn and returns it as a context dialer for the grpc.DialOption.
type ServerMockerWithContextDialer func(t T) (*Server, ContextDialer)
// MockUnstartedServer mocks the server and ensures all the expectations were met at the end of the test.
func MockUnstartedServer(opts ...ServerOption) ServerMocker {
return func(t T) *Server {
s := NewUnstartedServer(opts...).WithTest(t)
t.Cleanup(func() {
assert.NoError(t, s.ExpectationsWereMet())
})
return s
}
}
// MockServer starts a new mocked server and ensures all the expectations were met at the end of the test.
func MockServer(opts ...ServerOption) ServerMocker {
return func(t T) *Server {
s := NewServer(opts...)
t.Cleanup(func() {
assert.NoError(t, s.ExpectationsWereMet())
_ = s.Close() //nolint: errcheck
})
return s
}
}
// MockServerWithBufConn starts a new mocked server with bufconn and ensures all the expectations were met at the end of the test.
func MockServerWithBufConn(opts ...ServerOption) ServerMockerWithContextDialer {
return func(t T) (*Server, ContextDialer) {
buf := bufconn.Listen(1024 * 1024)
opts = append(opts, WithListener(buf))
return MockServer(opts...)(t), func(context.Context, string) (net.Conn, error) {
return buf.Dial()
}
}
}