-
Notifications
You must be signed in to change notification settings - Fork 124
/
api_mock.go
308 lines (288 loc) · 7.91 KB
/
api_mock.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package testutil
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/require"
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
)
var (
mux *http.ServeMux
server *httptest.Server
fakeUAAServer *httptest.Server
)
type MockRoute struct {
Method string
Endpoint string
Output []string
UserAgent string
Status int
Statuses []int
QueryString string
PostForm string
RedirectLocation string
}
func SetupFakeAPIServer() string {
if fakeUAAServer == nil {
SetupFakeUAAServer(3)
}
mux = http.NewServeMux()
server = httptest.NewServer(mux)
return server.URL
}
func SetupFakeUAAServer(expiresIn int) string {
uaaMux := http.NewServeMux()
fakeUAAServer = httptest.NewServer(uaaMux)
m := martini.New()
m.Use(render.Renderer())
r := martini.NewRouter()
count := 1
r.Post("/oauth/token", func(r render.Render) {
r.JSON(200, map[string]interface{}{
"token_type": "bearer",
"access_token": "foobar" + strconv.Itoa(count),
"refresh_token": "barfoo",
"expires_in": expiresIn,
})
count = count + 1
})
r.NotFound(func() string { return "" })
m.Action(r.Handle)
uaaMux.Handle("/", m)
return fakeUAAServer.URL
}
func Setup(mock MockRoute, t *testing.T) string {
return SetupMultiple([]MockRoute{mock}, t)
}
func SetupMultiple(mockEndpoints []MockRoute, t *testing.T) string {
if server == nil {
SetupFakeAPIServer()
}
m := martini.New()
m.Use(render.Renderer())
r := martini.NewRouter()
for _, mock := range mockEndpoints {
method := mock.Method
endpoint := mock.Endpoint
userAgent := mock.UserAgent
status := mock.Status
statuses := mock.Statuses
queryString := mock.QueryString
postFormBody := mock.PostForm
redirectLocation := mock.RedirectLocation
// TODO: add support for other HTTP verbs
// GET optionally supports returning multiple results for the same endpoint
output := mock.Output
if len(output) == 0 {
output = []string{""}
}
// if a separate status wasn't specified for each call, reuse the same status
if len(statuses) == 0 {
statuses = make([]int, len(output))
for i := range statuses {
statuses[i] = status
}
}
switch method {
case "GET":
count := 0
r.Get(endpoint, func(res http.ResponseWriter, req *http.Request) (int, string) {
testUserAgent(req.Header.Get("User-Agent"), userAgent, t)
testQueryString(req.URL.RawQuery, queryString, t)
if redirectLocation != "" {
res.Header().Add("Location", redirectLocation)
}
singleOutput := output[count]
status = statuses[count]
count++
return status, singleOutput
})
case "POST":
count := 0
r.Post(endpoint, func(res http.ResponseWriter, req *http.Request) (int, string) {
testUserAgent(req.Header.Get("User-Agent"), userAgent, t)
testQueryString(req.URL.RawQuery, queryString, t)
testReqBody(req, postFormBody, t)
if redirectLocation != "" {
res.Header().Add("Location", redirectLocation)
}
singleOutput := output[count]
status = statuses[count]
count++
return status, singleOutput
})
case "DELETE":
count := 0
r.Delete(endpoint, func(res http.ResponseWriter, req *http.Request) (int, string) {
testUserAgent(req.Header.Get("User-Agent"), userAgent, t)
testQueryString(req.URL.RawQuery, queryString, t)
if redirectLocation != "" {
res.Header().Add("Location", redirectLocation)
}
singleOutput := output[count]
status = statuses[count]
count++
return status, singleOutput
})
case "PUT":
count := 0
r.Put(endpoint, func(res http.ResponseWriter, req *http.Request) (int, string) {
testUserAgent(req.Header.Get("User-Agent"), userAgent, t)
testQueryString(req.URL.RawQuery, queryString, t)
testReqBody(req, postFormBody, t)
if redirectLocation != "" {
res.Header().Add("Location", redirectLocation)
}
singleOutput := output[count]
status = statuses[count]
count++
return status, singleOutput
})
case "PATCH":
count := 0
r.Patch(endpoint, func(res http.ResponseWriter, req *http.Request) (int, string) {
testUserAgent(req.Header.Get("User-Agent"), userAgent, t)
testQueryString(req.URL.RawQuery, queryString, t)
testReqBody(req, postFormBody, t)
if redirectLocation != "" {
res.Header().Add("Location", redirectLocation)
}
singleOutput := output[count]
status = statuses[count]
count++
return status, singleOutput
})
case "PUT-FILE":
count := 0
r.Put(endpoint, func(res http.ResponseWriter, req *http.Request) (int, string) {
testUserAgent(req.Header.Get("User-Agent"), userAgent, t)
testBodyContains(req, postFormBody, t)
if redirectLocation != "" {
res.Header().Add("Location", redirectLocation)
}
singleOutput := output[count]
status = statuses[count]
count++
return status, singleOutput
})
}
}
r.Get("/", func(r render.Render) {
r.JSON(200, map[string]any{
"links": map[string]any{
"cloud_controller_v2": map[string]any{
"href": server.URL + "/v2",
"meta": map[string]any{
"version": "2.155.0",
},
},
"cloud_controller_v3": map[string]any{
"href": server.URL + "/v3",
"meta": map[string]any{
"version": "3.90.0",
},
},
"network_policy_v0": map[string]any{
"href": "https://api.example.org/networking/v0/external",
},
"network_policy_v1": map[string]any{
"href": "https://api.example.org/networking/v1/external",
},
"uaa": map[string]any{
"href": fakeUAAServer.URL,
},
"login": map[string]any{
"href": fakeUAAServer.URL,
},
"credhub": map[string]any{
"href": "",
},
"routing": map[string]any{
"href": "https://api.example.org/routing",
},
"logging": map[string]any{
"href": "wss://doppler.example.org:443",
},
"log_cache": map[string]any{
"href": "https://log-cache.example.org",
},
"log_stream": map[string]any{
"href": "https://log-stream.example.org",
},
"app_ssh": map[string]any{
"href": "ssh.example.org:2222",
"meta": map[string]any{
"host_key_fingerprint": "Y411oivJwZCUQnXHq83mdM5SKCK4ftyoSXI31RRe4Zs",
"oauth_client": "ssh-proxy",
},
},
},
})
})
m.Action(r.Handle)
mux.Handle("/", m)
return server.URL
}
func Teardown() {
if server != nil {
server.Close()
server = nil
}
if fakeUAAServer != nil {
fakeUAAServer.Close()
fakeUAAServer = nil
}
}
func testQueryString(QueryString string, QueryStringExp string, t *testing.T) {
t.Helper()
if QueryStringExp == "" {
return
}
value, _ := url.QueryUnescape(QueryString)
if QueryStringExp != value {
t.Errorf("Error: Query string '%s' should be equal to '%s'", QueryStringExp, value)
}
}
func testUserAgent(UserAgent string, UserAgentExp string, t *testing.T) {
t.Helper()
if len(UserAgentExp) < 1 {
UserAgentExp = "Go-CF-Client/3.0"
}
if UserAgent != UserAgentExp {
t.Errorf("Error: Agent %s should be equal to %s", UserAgent, UserAgentExp)
}
}
func testReqBody(req *http.Request, postFormBody string, t *testing.T) {
t.Helper()
if postFormBody != "" {
if body, err := io.ReadAll(req.Body); err != nil {
t.Error("No request body but expected one")
} else {
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(req.Body)
require.JSONEq(t, postFormBody, string(body),
"Expected request body (%s) does not equal request body (%s)", postFormBody, body)
}
}
}
func testBodyContains(req *http.Request, expected string, t *testing.T) {
t.Helper()
if expected != "" {
if body, err := io.ReadAll(req.Body); err != nil {
t.Error("No request body but expected one")
} else {
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(req.Body)
if !strings.Contains(string(body), expected) {
t.Errorf("Expected request body (%s) was not found in actual request body (%s)", expected, body)
}
}
}
}