-
Notifications
You must be signed in to change notification settings - Fork 2
/
eval.go
265 lines (242 loc) · 6.57 KB
/
eval.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
// Use and distribution licensed under the Apache license version 2.
//
// See the COPYING file in the root project directory for full text.
package http
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
nethttp "net/http"
"reflect"
"strings"
"testing"
gdtcontext "github.com/gdt-dev/gdt/context"
gdtdebug "github.com/gdt-dev/gdt/debug"
"github.com/gdt-dev/gdt/result"
"github.com/stretchr/testify/require"
)
// RunData is data stored in the context about the run. It is fetched from the
// gdtcontext.PriorRun() function and evaluated for things like the special
// `$LOCATION` URL value.
type RunData struct {
Response *nethttp.Response
}
// priorRunData returns any prior run cached data in the context.
func priorRunData(ctx context.Context) *RunData {
prData := gdtcontext.PriorRun(ctx)
httpData, ok := prData[pluginName]
if !ok {
return nil
}
if data, ok := httpData.(*RunData); ok {
return data
}
return nil
}
// getURL returns the URL to use for the test's HTTP request. The test's url
// field is first queried to see if it is the special $LOCATION string. If it
// is, then we return the previous HTTP response's Location header. Otherwise,
// we construct the URL from the httpFile's base URL and the test's url field.
func (s *Spec) getURL(ctx context.Context) (string, error) {
if strings.ToUpper(s.URL) == "$LOCATION" {
pr := priorRunData(ctx)
if pr == nil || pr.Response == nil {
panic("test unit referenced $LOCATION before executing an HTTP request")
}
url, err := pr.Response.Location()
if err != nil {
return "", ErrExpectedLocationHeader
}
return url.String(), nil
}
d := fromBaseDefaults(s.Defaults)
base := d.BaseURLFromContext(ctx)
return base + s.URL, nil
}
// processRequestData looks through the raw data interface{} that was
// unmarshaled during parse for any string values that look like JSONPath
// expressions. If we find any, we query the fixture registry to see if any
// fixtures have a value that matches the JSONPath expression. See
// gdt.fixtures:jsonFixture for more information on how this works
func (s *Spec) processRequestData(ctx context.Context) {
if s.Data == nil {
return
}
// Get a pointer to the unmarshaled interface{} so we can mutate the
// contents pointed to
p := reflect.ValueOf(&s.Data)
// We're interested in the value pointed to by the interface{}, which is
// why we do a double Elem() here.
v := p.Elem().Elem()
vt := v.Type()
switch vt.Kind() {
case reflect.Slice:
for i := 0; i < v.Len(); i++ {
item := v.Index(i).Elem()
it := item.Type()
s.preprocessMap(ctx, item, it.Key(), it.Elem())
}
// ht.f.preprocessSliceValue(v, vt.Key(), vt.Elem())
case reflect.Map:
s.preprocessMap(ctx, v, vt.Key(), vt.Elem())
}
}
// client returns the HTTP client to use when executing HTTP requests. If any
// fixture provides a state with key "http.client", the fixture is asked for
// the HTTP client. Otherwise, we use the net/http.DefaultClient
func (s *Spec) client(ctx context.Context) *nethttp.Client {
// query the fixture registry to determine if any of them contain an
// http.client state attribute.
fixtures := gdtcontext.Fixtures(ctx)
for _, f := range fixtures {
if f.HasState(StateKeyClient) {
c, ok := f.State(StateKeyClient).(*nethttp.Client)
if !ok {
panic("fixture failed to return a *net/http.Client")
}
return c
}
}
return nethttp.DefaultClient
}
// processRequestDataMap processes a map pointed to by v, transforming any
// string keys or values of the map into the results of calling the fixture
// set's State() method.
func (s *Spec) preprocessMap(
ctx context.Context,
m reflect.Value,
kt reflect.Type,
vt reflect.Type,
) error {
it := m.MapRange()
for it.Next() {
if kt.Kind() == reflect.String {
keyStr := it.Key().String()
fixtures := gdtcontext.Fixtures(ctx)
for _, f := range fixtures {
if !f.HasState(keyStr) {
continue
}
trKeyStr := f.State(keyStr)
keyStr = trKeyStr.(string)
}
val := it.Value()
err := s.preprocessMapValue(ctx, m, reflect.ValueOf(keyStr), val, val.Type())
if err != nil {
return err
}
}
}
return nil
}
func (s *Spec) preprocessMapValue(
ctx context.Context,
m reflect.Value,
k reflect.Value,
v reflect.Value,
vt reflect.Type,
) error {
if vt.Kind() == reflect.Interface {
v = v.Elem()
vt = v.Type()
}
switch vt.Kind() {
case reflect.Slice:
for i := 0; i < v.Len(); i++ {
item := v.Index(i)
fmt.Println(item)
}
fmt.Printf("map element is an array.\n")
case reflect.Map:
return s.preprocessMap(ctx, v, vt.Key(), vt.Elem())
case reflect.String:
valStr := v.String()
fixtures := gdtcontext.Fixtures(ctx)
for _, f := range fixtures {
if !f.HasState(valStr) {
continue
}
trValStr := f.State(valStr)
m.SetMapIndex(k, reflect.ValueOf(trValStr))
}
default:
return nil
}
return nil
}
// Run executes the test described by the HTTP test. A new HTTP request and
// response pair is created during this call.
func (s *Spec) Eval(ctx context.Context, t *testing.T) *result.Result {
runData := &RunData{}
var rerr error
fails := []error{}
t.Run(s.Title(), func(t *testing.T) {
url, err := s.getURL(ctx)
if err != nil {
rerr = err
return
}
gdtdebug.Println(ctx, t, "http: > %s %s", s.Method, url)
var body io.Reader
if s.Data != nil {
s.processRequestData(ctx)
jsonBody, err := json.Marshal(s.Data)
require.Nil(t, err)
b := bytes.NewReader(jsonBody)
if b.Size() > 0 {
sendData, _ := io.ReadAll(b)
gdtdebug.Println(ctx, t, "http: > %s", sendData)
b.Seek(0, 0)
}
body = b
}
req, err := nethttp.NewRequest(s.Method, url, body)
if err != nil {
rerr = err
return
}
// TODO(jaypipes): Allow customization of the HTTP client for proxying,
// TLS, etc
c := s.client(ctx)
resp, err := c.Do(req)
if err != nil {
rerr = err
return
}
gdtdebug.Println(ctx, t, "http: < %d", resp.StatusCode)
// Make sure we drain and close our response body...
defer func() {
io.Copy(ioutil.Discard, resp.Body)
resp.Body.Close()
}()
// Only read the response body contents once and pass the byte
// buffer to the assertion functions
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
rerr = err
return
}
if len(b) > 0 {
gdtdebug.Println(ctx, t, "http: < %s", b)
}
exp := s.Assert
if exp != nil {
a := newAssertions(exp, resp, b)
fails = a.Failures()
}
runData.Response = resp
})
if rerr != nil {
return result.New(
result.WithRuntimeError(rerr),
)
} else {
return result.New(
result.WithFailures(fails...),
result.WithData(pluginName, runData),
)
}
}