-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtq.go
245 lines (210 loc) · 6.17 KB
/
rtq.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
package rtq
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"github.com/samber/lo"
)
// Have a RoundTrip queue for each specific request, and if the request matches, retrieve the RoundTrip from the queue and execute it.
type MockTransport struct {
queues []*RoundTripQueue
requestLogs []requestLog
mu sync.Mutex
}
var _ http.RoundTripper = (*MockTransport)(nil)
func NewTransport(queues ...RoundTripQueue) *MockTransport {
return &MockTransport{
queues: lo.ToSlicePtr(queues),
}
}
func (m *MockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
roundTrip, err := m.dequeue(req)
if err != nil {
return nil, err
}
return roundTrip(req)
}
func (m *MockTransport) dequeue(req *http.Request) (func(*http.Request) (*http.Response, error), error) {
m.mu.Lock()
defer m.mu.Unlock()
// Find a queue matching the request
q, found, err := m.find(req)
if err != nil {
return nil, err
}
if !found {
m.requestLogs = append(m.requestLogs, requestLog{matched: false, request: req})
return nil, errors.New("mock is not registered")
}
m.requestLogs = append(m.requestLogs, requestLog{matched: true, request: req})
// Retrieve the roundTrip from the queue and execute it
// In the find method, queues with len(roundTripFuncs) of 0 are not matched, so it is guaranteed that len(roundTripFuncs) is 1 or more.
roundTrip := q.roundTripFuncs[0]
q.roundTripFuncs = q.roundTripFuncs[1:]
return roundTrip, nil
}
// Find a queue that matches the passed request
func (m *MockTransport) find(req *http.Request) (*RoundTripQueue, bool, error) {
for _, q := range m.queues {
// If roundTripFuncs is empty, it is treated as no match and the next matching queue is searched.
if len(q.roundTripFuncs) != 0 {
m, err := q.match(req)
if err != nil {
return nil, false, err
}
if m {
return q, true, nil
}
}
}
return nil, false, nil
}
func (m *MockTransport) unmatchRequests() []*http.Request {
return lo.FilterMap(m.requestLogs, func(l requestLog, _ int) (*http.Request, bool) {
return l.request, !l.matched
})
}
func (m *MockTransport) Completed() bool {
remaining := lo.SumBy(
m.queues,
func(q *RoundTripQueue) int { return len(q.roundTripFuncs) },
)
return remaining == 0 && len(m.unmatchRequests()) == 0
}
func (m *MockTransport) RequestLogString() string {
return strings.Join(
lo.Map(m.requestLogs, func(l requestLog, i int) string { return fmt.Sprintf("%d: %s", i+1, l.String()) }),
"\n",
)
}
type MatchFunc func(*http.Request) (bool, error)
// roundTrip queue
type RoundTripQueue struct {
matchFuncs []MatchFunc
roundTripFuncs []func(*http.Request) (*http.Response, error)
}
func New(origin string) RoundTripQueue {
matchFuncs := []MatchFunc{
func(req *http.Request) (bool, error) {
return req.URL.Scheme+"://"+req.URL.Host == origin, nil
},
}
return RoundTripQueue{
matchFuncs: matchFuncs,
roundTripFuncs: make([]func(*http.Request) (*http.Response, error), 0),
}
}
func (q RoundTripQueue) match(req *http.Request) (bool, error) {
for _, f := range q.matchFuncs {
m, err := f(req)
if err != nil {
return false, err
}
if !m {
return false, nil
}
}
return true, nil
}
func (q RoundTripQueue) Header(key, value string) RoundTripQueue {
q.matchFuncs = append(q.matchFuncs, func(req *http.Request) (bool, error) {
return req.Header.Get(key) == value, nil
})
return q
}
func (q RoundTripQueue) method(method string) RoundTripQueue {
q.matchFuncs = append(q.matchFuncs, func(req *http.Request) (bool, error) {
return req.Method == method, nil
})
return q
}
func (q RoundTripQueue) path(path string) RoundTripQueue {
q.matchFuncs = append(q.matchFuncs, func(req *http.Request) (bool, error) {
return req.URL.Path == path, nil
})
return q
}
func (q RoundTripQueue) Get(path string) RoundTripQueue {
return q.method(http.MethodGet).path(path)
}
func (q RoundTripQueue) Post(path string) RoundTripQueue {
return q.method(http.MethodPost).path(path)
}
func (q RoundTripQueue) Put(path string) RoundTripQueue {
return q.method(http.MethodPut).path(path)
}
func (q RoundTripQueue) Delete(path string) RoundTripQueue {
return q.method(http.MethodDelete).path(path)
}
func (q RoundTripQueue) Query(key, value string) RoundTripQueue {
q.matchFuncs = append(q.matchFuncs, func(req *http.Request) (bool, error) {
return req.URL.Query().Get(key) == value, nil
})
return q
}
func (q RoundTripQueue) BodyString(body string) RoundTripQueue {
q.matchFuncs = append(q.matchFuncs, func(req *http.Request) (bool, error) {
got, err := io.ReadAll(req.Body)
if err != nil {
return false, err
}
req.Body = io.NopCloser(bytes.NewReader(got))
return string(got) == body, nil
})
return q
}
func (q RoundTripQueue) Matcher(matchFunc MatchFunc) RoundTripQueue {
q.matchFuncs = append(q.matchFuncs, matchFunc)
return q
}
func (q RoundTripQueue) ResponseSimple(statusCode int, body string) RoundTripQueue {
q.roundTripFuncs = append(q.roundTripFuncs, func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: statusCode,
Body: io.NopCloser(strings.NewReader(body)),
Request: req,
}, nil
})
return q
}
func (q RoundTripQueue) ResponseJSON(statusCode int, body any) RoundTripQueue {
b, err := json.Marshal(body)
if err != nil {
panic(err)
}
q.roundTripFuncs = append(q.roundTripFuncs, func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: statusCode,
Body: io.NopCloser(bytes.NewBuffer(b)),
Header: http.Header{"Content-Type": []string{"application/json"}},
Request: req,
}, nil
})
return q
}
func (q RoundTripQueue) Response(res *http.Response) RoundTripQueue {
q.roundTripFuncs = append(q.roundTripFuncs, func(req *http.Request) (*http.Response, error) {
return res, nil
})
return q
}
func (q RoundTripQueue) ResponseFunc(roundTrip func(*http.Request) (*http.Response, error)) RoundTripQueue {
q.roundTripFuncs = append(q.roundTripFuncs, roundTrip)
return q
}
type requestLog struct {
matched bool
request *http.Request
}
func (l requestLog) String() string {
s := fmt.Sprintf("%s %s", l.request.Method, l.request.URL.String())
if !l.matched {
s += " (not matched)"
}
return s
}