-
Notifications
You must be signed in to change notification settings - Fork 115
/
moduletest.go
64 lines (52 loc) · 1.62 KB
/
moduletest.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
57
58
59
60
61
62
63
64
package moduletest
import (
"context"
"fmt"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/grpc"
"github.com/lyft/clutch/backend/module"
)
// Similar to httptest, this is a helper package to allow module authors to verify modules register correctly.
// Note: this is only for testing module behavior. The actual RPC implementation should be tested directly against the API server.
type TestRegistrar struct {
jsonCount int
grpcServer *grpc.Server
mux *runtime.ServeMux
}
func NewRegisterChecker() *TestRegistrar {
return &TestRegistrar{
grpcServer: grpc.NewServer(),
mux: runtime.NewServeMux(),
}
}
func (r *TestRegistrar) JSONRegistered() bool {
return r.jsonCount >= 1
}
func (r *TestRegistrar) GRPCRegistered() bool {
return len(r.grpcServer.GetServiceInfo()) >= 1
}
func (r *TestRegistrar) GRPCServer() *grpc.Server {
return r.grpcServer
}
func (r *TestRegistrar) RegisterJSONGateway(handlerFunc module.GatewayRegisterAPIHandlerFunc) error {
r.jsonCount++
if r.jsonCount != len(r.grpcServer.GetServiceInfo()) {
panic("RegisterJSONGateway called more than gRPC or no gRPC registration found")
}
if err := handlerFunc(context.TODO(), r.mux, nil); err != nil {
// Panic in case error was ignored by caller.
panic(err)
}
return nil
}
func (r *TestRegistrar) HasAPI(name string) error {
services := r.grpcServer.GetServiceInfo()
if _, ok := services[name]; !ok {
keys := make([]string, 0, len(services))
for key := range services {
keys = append(keys, key)
}
return fmt.Errorf("service '%s' not found in %d service(s): %+v", name, len(keys), keys)
}
return nil
}