/
test_server.go
56 lines (49 loc) · 1.27 KB
/
test_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
54
55
56
package server
import (
"context"
"net"
"net/http/httptest"
"google.golang.org/api/option"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/test/bufconn"
)
type TestServer struct {
*httptest.Server
DialerOption grpc.DialOption
}
func (s *TestServer) GRPCDial(ctx context.Context) (*grpc.ClientConn, error) {
return grpc.DialContext(
ctx,
s.URL,
s.DialerOption,
grpc.WithTransportCredentials(insecure.NewCredentials()),
)
}
func (s *TestServer) GRPCClientOptions(ctx context.Context) ([]option.ClientOption, error) {
conn, err := s.GRPCDial(ctx)
if err != nil {
return nil, err
}
return []option.ClientOption{
option.WithGRPCConn(conn),
option.WithEndpoint(s.URL),
option.WithoutAuthentication(),
}, nil
}
func (s *Server) TestServer() *TestServer {
server := httptest.NewServer(s.Handler)
s.httpServer = server.Config
grpcListener := bufconn.Listen(1024 * 1024)
grpcServer := grpc.NewServer()
registerStorageServer(grpcServer, s)
s.grpcServer = grpcServer
go func() {
_ = grpcServer.Serve(grpcListener)
}()
testServer := &TestServer{Server: server}
testServer.DialerOption = grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) {
return grpcListener.Dial()
})
return testServer
}