/
expect.go
249 lines (217 loc) · 6.81 KB
/
expect.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package grpc
import (
"fmt"
"reflect"
"strconv"
"strings"
"github.com/goccy/go-yaml"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
// Register proto messages to unmarshal com.google.protobuf.Any.
_ "google.golang.org/genproto/googleapis/rpc/errdetails"
"github.com/zoncoen/scenarigo/assert"
"github.com/zoncoen/scenarigo/context"
"github.com/zoncoen/scenarigo/errors"
"github.com/zoncoen/scenarigo/internal/assertutil"
)
// Expect represents expected response values.
type Expect struct {
Code string `yaml:"code"`
Message interface{} `yaml:"message"`
Status ExpectStatus `yaml:"status"`
Header yaml.MapSlice `yaml:"header"`
Trailer yaml.MapSlice `yaml:"trailer"`
// for backward compatibility
Body interface{} `yaml:"body,omitempty"`
}
// ExpectStatus represents expected gRPC status.
type ExpectStatus struct {
Code string `yaml:"code"`
Message string `yaml:"message"`
Details []map[string]yaml.MapSlice `yaml:"details"`
}
// Build implements protocol.AssertionBuilder interface.
func (e *Expect) Build(ctx *context.Context) (assert.Assertion, error) {
codePath := "code"
expectCode := "OK"
if e.Code != "" {
expectCode = e.Code
}
if e.Status.Code != "" {
codePath = "status.code"
expectCode = e.Status.Code
}
executedCode, err := ctx.ExecuteTemplate(expectCode)
if err != nil {
return nil, errors.WrapPathf(err, codePath, "invalid expect response: %s", err)
}
codeAssertion := assert.Build(executedCode)
var statusMsgAssertion assert.Assertion
if e.Status.Message != "" {
executedMsg, err := ctx.ExecuteTemplate(e.Status.Message)
if err != nil {
return nil, errors.WrapPathf(err, "message", "invalid expect response: %s", err)
}
statusMsgAssertion = assert.Build(executedMsg)
}
headerAssertion, err := assertutil.BuildHeaderAssertion(ctx, e.Header)
if err != nil {
return nil, errors.WrapPathf(err, "header", "invalid expect header")
}
trailerAssertion, err := assertutil.BuildHeaderAssertion(ctx, e.Trailer)
if err != nil {
return nil, errors.WrapPathf(err, "trailer", "invalid expect trailer")
}
expectMsg, err := ctx.ExecuteTemplate(e.Message)
if err != nil {
return nil, errors.WrapPathf(err, "message", "invalid expect response: %s", err)
}
msgAssertion := assert.Build(expectMsg)
return assert.AssertionFunc(func(v interface{}) error {
resp, ok := v.(response)
if !ok {
return errors.Errorf(`failed to convert to response type. type is %s`, reflect.TypeOf(v))
}
message, stErr, err := extract(resp)
if err != nil {
return err
}
if err := assertStatusCode(codeAssertion, stErr); err != nil {
return errors.WithPath(err, codePath)
}
if err := e.assertStatusMessage(statusMsgAssertion, stErr); err != nil {
return errors.WithPath(err, "status.message")
}
if err := e.assertStatusDetails(stErr); err != nil {
return errors.WithPath(err, "status.details")
}
if err := headerAssertion.Assert(resp.Header); err != nil {
return errors.WithPath(err, "header")
}
if err := trailerAssertion.Assert(resp.Trailer); err != nil {
return errors.WithPath(err, "trailer")
}
if err := msgAssertion.Assert(message); err != nil {
return errors.WithPath(err, "message")
}
return nil
}), nil
}
func assertStatusCode(assertion assert.Assertion, sts *status.Status) error {
err := assertion.Assert(sts.Code().String())
if err == nil {
return nil
}
err = assertion.Assert(strconv.Itoa(int(sts.Code())))
if err == nil {
return nil
}
return errors.Errorf(
`%s: message="%s"%s`,
err,
sts.Message(),
appendDetailsString(sts),
)
}
func (e *Expect) assertStatusMessage(assertion assert.Assertion, sts *status.Status) error {
if e.Status.Message == "" {
return nil
}
err := assertion.Assert(sts.Message())
if err == nil {
return nil
}
return errors.Errorf(
`%s%s`,
err,
appendDetailsString(sts),
)
}
func (e *Expect) assertStatusDetails(sts *status.Status) error {
if len(e.Status.Details) == 0 {
return nil
}
actualDetails := sts.Details()
for i, expecteDetailMap := range e.Status.Details {
if i >= len(actualDetails) {
return errors.Errorf(`expected status.details[%d] is not found%s`, i, appendDetailsString(sts))
}
if len(expecteDetailMap) != 1 {
return errors.Errorf("invalid yaml: expect status.details[%d]:"+
"An element of status.details list must be a map of size 1 with the detail message name as the key and the value as the detail message object.", i)
}
var expectName string
var expectDetail interface{}
for k, v := range expecteDetailMap {
expectName = k
expectDetail = v
break
}
actual, ok := actualDetails[i].(proto.Message)
if !ok {
return errors.Errorf(`expected status.details[%d] is "%s" but got detail is not a proto message: "%#v"`, i, expectName, actualDetails[i])
}
if name := string(actual.ProtoReflect().Descriptor().FullName()); name != expectName {
return errors.Errorf(`expected status.details[%d] is "%s" but got detail is "%s"%s`, i, expectName, name, appendDetailsString(sts))
}
if err := assert.Build(expectDetail).Assert(actual); err != nil {
return err
}
}
return nil
}
func appendDetailsString(sts *status.Status) string {
format := "%s: %s"
var details []string
for _, i := range sts.Details() {
if pb, ok := i.(proto.Message); ok {
b, err := protojson.Marshal(pb)
if err == nil {
details = append(details, fmt.Sprintf(format, pb.ProtoReflect().Descriptor().FullName(), string(b)))
continue
}
}
if e, ok := i.(interface{ Error() string }); ok {
details = append(details, fmt.Sprintf(format, "<non proto message>", e.Error()))
continue
}
details = append(details, fmt.Sprintf(format, "<non proto message>", fmt.Sprintf("%#v", i)))
}
if len(details) == 0 {
return ""
}
return fmt.Sprintf(": details=[ %s ]", strings.Join(details, ", "))
}
func extract(v response) (proto.Message, *status.Status, error) {
vs := v.rvalues
if len(vs) != 2 {
return nil, nil, errors.Errorf("expected return value length of method call is 2 but %d", len(vs))
}
if !vs[0].IsValid() {
return nil, nil, errors.New("first return value is invalid")
}
message, ok := vs[0].Interface().(proto.Message)
if !ok {
if !vs[0].IsNil() {
return nil, nil, errors.Errorf("expected first return value is proto.Message but %T", vs[0].Interface())
}
}
if !vs[1].IsValid() {
return nil, nil, errors.New("second return value is invalid")
}
callErr, ok := vs[1].Interface().(error)
if !ok {
if !vs[1].IsNil() {
return nil, nil, errors.Errorf("expected second return value is error but %T", vs[1].Interface())
}
}
var sts *status.Status
if ok {
sts, ok = status.FromError(callErr)
if !ok {
return nil, nil, errors.Errorf(`expected error is status but got %T: "%s"`, callErr, callErr.Error())
}
}
return message, sts, nil
}