-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmock_test.go
More file actions
246 lines (205 loc) · 5.8 KB
/
mock_test.go
File metadata and controls
246 lines (205 loc) · 5.8 KB
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
package fhttpc
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"net"
"net/url"
"strings"
"time"
"github.com/valyala/fasthttp"
"github.com/valyala/fasthttp/fasthttputil"
)
type MockMatchFn func(ctx *fasthttp.RequestCtx) (bool, error)
type Mock struct {
method string
uri string
ln net.Listener
client *fasthttp.Client
handler fasthttp.RequestHandler
reply int
respHeaders Params
}
type MultiMock struct {
mocks map[string]*Mock
client *fasthttp.Client
}
func NewMultiMock(mocks ...*Mock) (*MultiMock, error) {
inMemListener := fasthttputil.NewInmemoryListener()
obj := &MultiMock{
mocks: make(map[string]*Mock),
client: &fasthttp.Client{
Dial: func(addr string) (net.Conn, error) {
return inMemListener.Dial()
},
},
}
for _, mock := range mocks {
mock.Close()
uri, err := url.Parse(mock.uri)
if err != nil {
return nil, fmt.Errorf("failed to parse mock URI `%s` for MultiMock routing: %w", mock.uri, err)
}
obj.mocks[strings.ToLower(mock.method+"_"+uri.Path)] = mock
}
go func() {
if err := fasthttp.Serve(inMemListener, func(ctx *fasthttp.RequestCtx) {
mock, ok := obj.mocks[strings.ToLower(string(ctx.Method())+"_"+string(ctx.Path()))]
if !ok {
ctx.Error("MOCK: no matching mock handler found", fasthttp.StatusNotFound)
return
}
mock.handler(ctx)
}); err != nil {
panic(err)
}
}()
return obj, nil
}
func (m *MultiMock) Client() *fasthttp.Client {
return m.client
}
func (m *MultiMock) Close() (err error) {
for _, mock := range m.mocks {
err = mock.Close()
}
return err
}
func NewMock(method, uri string, t testCase, matchFns ...MockMatchFn) *Mock {
inMemListener := fasthttputil.NewInmemoryListener()
m := &Mock{
method: method,
uri: uri,
ln: inMemListener,
reply: t.expectedStatusCode,
}
m.client = &fasthttp.Client{
Dial: func(addr string) (net.Conn, error) {
return inMemListener.Dial()
},
}
if strings.HasPrefix(uri, "https://") {
cert, err := tls.X509KeyPair([]byte(testServerCert), []byte(testServerKey))
if err != nil {
panic(err)
}
caCertPool, err := x509.SystemCertPool()
if err != nil {
panic(err)
}
if !caCertPool.AppendCertsFromPEM([]byte(testCACert)) {
panic("failed to append mock server CA certificate")
}
m.ln = tls.NewListener(m.ln, &tls.Config{
Certificates: []tls.Certificate{cert},
ClientAuth: tls.RequireAndVerifyClientCert,
ClientCAs: caCertPool,
MinVersion: tls.VersionTLS12,
})
m.client.TLSConfig = &tls.Config{
MinVersion: tls.VersionTLS12,
}
}
m.RespHeaders(t.responseHeaders)
m.handler = func(ctx *fasthttp.RequestCtx) {
// Handle hostnames
if t.hostName != "" {
if string(ctx.Request.Header.Peek("Host")) != t.hostName {
ctx.Error(fmt.Sprintf("MOCK: non-matching host name (want %s, have %s)", t.hostName, ctx.Request.Header.Peek("Host")), fasthttp.StatusInternalServerError)
return
}
}
// Check for method
if string(ctx.Method()) != m.method {
ctx.Error(fmt.Sprintf("MOCK: non-matching method (want %s, have %s)", m.method, ctx.Method()), fasthttp.StatusInternalServerError)
return
}
uri, err := url.Parse(m.uri)
if err != nil {
ctx.Error(fmt.Sprintf("MOCK: invalid expected URI (%s): %s", uri, err), fasthttp.StatusInternalServerError)
return
}
// Check for URI path
if string(ctx.Path()) != uri.Path {
ctx.Error(fmt.Sprintf("MOCK: non-matching URI path (want %s, have %s)", uri.Path, ctx.RequestURI()), fasthttp.StatusInternalServerError)
return
}
// Handle query parameters
if len(t.queryParams) > 0 {
q := ctx.URI().QueryArgs()
if q.Len() != len(t.queryParams) {
ctx.Error(fmt.Sprintf("MOCK: non-matching query args (want %v, have %v)", t.queryParams, ctx.URI().QueryArgs()), fasthttp.StatusInternalServerError)
return
}
for key, val := range t.queryParams {
if string(q.Peek(key)) != val {
ctx.Error(fmt.Sprintf("MOCK: non-matching query args (want %v, have %v)", t.queryParams, ctx.URI().QueryArgs()), fasthttp.StatusInternalServerError)
return
}
}
}
// Handle headers
if len(t.requestHeaders) > 0 {
for key, val := range t.requestHeaders {
if string(ctx.Request.Header.Peek(key)) != val {
ctx.Error(fmt.Sprintf("MOCK: non-matching header (want %v, have %v)", t.requestHeaders, string(ctx.Request.Header.Peek(key))), fasthttp.StatusInternalServerError)
return
}
}
}
// Handle request body
if t.requestBody != nil {
if !bytes.Equal(ctx.Request.Body(), t.requestBody) {
ctx.Error(fmt.Sprintf("MOCK: non-matching body (want len %d, have %d)", len(t.requestBody), len(ctx.Request.Body())), fasthttp.StatusInternalServerError)
return
}
}
for _, matchFn := range matchFns {
matches, err := matchFn(ctx)
if err != nil {
ctx.Error(fmt.Sprintf("MOCK: error executing match function: %s", err), fasthttp.StatusInternalServerError)
return
}
if !matches {
ctx.Error("MOCK: non-matching function call", fasthttp.StatusNotFound)
return
}
}
// Define the return code (and body, if provided)
if t.responseBody != nil {
ctx.Response.SetBody(t.responseBody)
}
// Set mock response headers
for k, v := range m.respHeaders {
ctx.Response.Header.Set(k, v)
}
// Set mock response status code (if requested, otherwise use the expected status code from the test)
if m.reply != 0 {
ctx.Response.SetStatusCode(m.reply)
}
// Delay response if requested
time.Sleep(t.respDelay)
}
go m.run()
return m
}
func (m *Mock) run() {
if err := fasthttp.Serve(m.ln, m.handler); err != nil {
panic(err)
}
}
func (m *Mock) RespHeaders(headers Params) *Mock {
m.respHeaders = headers
return m
}
func (m *Mock) Reply(reply int) *Mock {
m.reply = reply
return m
}
func (m *Mock) Client() *fasthttp.Client {
return m.client
}
func (m *Mock) Close() error {
return m.ln.Close()
}