-
Notifications
You must be signed in to change notification settings - Fork 0
/
grpc.go
108 lines (87 loc) · 2.26 KB
/
grpc.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package testutil
import (
"context"
"fmt"
"testing"
"github.com/alextanhongpin/core/grpc/grpcdump"
"github.com/alextanhongpin/core/internal"
"github.com/alextanhongpin/core/test/testdump"
"github.com/google/go-cmp/cmp"
)
type GRPCDump = testdump.GRPCDump
type GRPCHook = testdump.Hook[*GRPCDump]
type GRPCOption interface {
isGRPC()
}
func DumpGRPC(t *testing.T, ctx context.Context, opts ...GRPCOption) context.Context {
t.Helper()
ctx, flush := grpcdump.NewRecorder(ctx)
var fileName string
var hooks []testdump.Hook[*GRPCDump]
grpcOpt := new(testdump.GRPCOption)
for _, opt := range opts {
switch o := opt.(type) {
case FileName:
fileName = string(o)
case *grpcHookOption:
hooks = append(hooks, o.hook)
case *grpcCmpOption:
grpcOpt.Message = append(grpcOpt.Message, o.message...)
grpcOpt.Metadata = append(grpcOpt.Message, o.metadata...)
default:
panic(fmt.Errorf("testutil: unhandled gRPC option: %#v", opt))
}
}
p := Path{
Dir: "testdata",
FilePath: t.Name(),
FileName: fileName,
FileExt: ".http",
}
t.Cleanup(func() {
dump := flush()
if err := testdump.GRPC(testdump.NewFile(p.String()), dump, grpcOpt, hooks...); err != nil {
t.Fatal(err)
}
})
return ctx
}
type grpcHookOption struct {
hook testdump.Hook[*GRPCDump]
}
func (grpcHookOption) isGRPC() {}
type grpcCmpOption struct {
metadata []cmp.Option
message []cmp.Option
}
func (grpcCmpOption) isGRPC() {}
func IgnoreMetadata(headers ...string) *grpcCmpOption {
return &grpcCmpOption{
metadata: []cmp.Option{internal.IgnoreMapEntries(headers...)},
}
}
func IgnoreMessageFields(fields ...string) *grpcCmpOption {
return &grpcCmpOption{
message: []cmp.Option{internal.IgnoreMapEntries(fields...)},
}
}
func MaskMetadata(headers ...string) *grpcHookOption {
return &grpcHookOption{
hook: testdump.MaskMetadata(headers...),
}
}
func MaskMessage(fields ...string) *grpcHookOption {
return &grpcHookOption{
hook: testdump.MaskMessage(fields...),
}
}
func InspectGRPC(hook func(snapshot, received *GRPCDump) error) *grpcHookOption {
return &grpcHookOption{
hook: testdump.CompareHook(hook),
}
}
func InterceptGRPC(hook func(dump *GRPCDump) (*GRPCDump, error)) *grpcHookOption {
return &grpcHookOption{
hook: testdump.MarshalHook(hook),
}
}