forked from vadimi/grpc-ditto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock_validator.go
54 lines (45 loc) · 1.36 KB
/
mock_validator.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
package main
import (
"fmt"
"github.com/jhump/protoreflect/desc"
"github.com/jhump/protoreflect/dynamic"
"github.com/vadimi/grpc-ditto/internal/dittomock"
)
type mockValidator struct {
findMethodFunc func(methodName string) *desc.MethodDescriptor
}
// Validate that all methods in mocks have protos loaded in memory.
// also verifies that mock responses can be successfully marshalled into method response message
func (v *mockValidator) Validate(mocks map[string][]dittomock.DittoMock) error {
for methodName, mocks := range mocks {
method := v.findMethodFunc(methodName)
if method == nil {
return fmt.Errorf("method %s not found in registered proto files", methodName)
}
for i, m := range mocks {
err := v.ValidateMock(m)
if err != nil {
return fmt.Errorf("invalid mock [%d]: %w", i, err)
}
}
}
return nil
}
func (v *mockValidator) ValidateMock(mock dittomock.DittoMock) error {
methodName := mock.Request.Method
method := v.findMethodFunc(methodName)
if method == nil {
return fmt.Errorf("method %s not found in registered proto files", methodName)
}
for _, resp := range mock.Response {
if resp.Status != nil {
continue
}
output := dynamic.NewMessage(method.GetOutputType())
err := output.UnmarshalJSON(resp.Body)
if err != nil {
return fmt.Errorf("invalid response for method %s: %w", methodName, err)
}
}
return nil
}