-
Notifications
You must be signed in to change notification settings - Fork 36
/
testing.go
259 lines (235 loc) · 7.63 KB
/
testing.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
// Copyright 2012-2016 Canonical Ltd.
// Licensed under the LGPLv3, see LICENCE file for details.
package gomaasapi
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"time"
)
type singleServingServer struct {
*httptest.Server
requestContent *string
requestHeader *http.Header
}
// newSingleServingServer creates a single-serving test http server which will
// return only one response as defined by the passed arguments.
func newSingleServingServer(uri string, response string, code int, delay time.Duration) *singleServingServer {
var requestContent string
var requestHeader http.Header
var requested bool
handler := func(writer http.ResponseWriter, request *http.Request) {
if requested {
http.Error(writer, "Already requested", http.StatusServiceUnavailable)
}
res, err := readAndClose(request.Body)
if err != nil {
panic(err)
}
requestContent = string(res)
requestHeader = request.Header
if request.URL.String() != uri {
errorMsg := fmt.Sprintf("Error 404: page not found (expected '%v', got '%v').", uri, request.URL.String())
http.Error(writer, errorMsg, http.StatusNotFound)
} else {
time.Sleep(delay)
writer.WriteHeader(code)
fmt.Fprint(writer, response)
}
requested = true
}
server := httptest.NewServer(http.HandlerFunc(handler))
return &singleServingServer{server, &requestContent, &requestHeader}
}
type flakyServer struct {
*httptest.Server
nbRequests *int
requests *[][]byte
headers *[]http.Header
}
// newFlakyServer creates a "flaky" test http server which will
// return `nbFlakyResponses` responses with the given code and then a 200 response.
func newFlakyServer(uri string, code int, nbFlakyResponses int) *flakyServer {
nbRequests := 0
requests := make([][]byte, nbFlakyResponses+1)
headers := make([]http.Header, nbFlakyResponses+1)
handler := func(writer http.ResponseWriter, request *http.Request) {
nbRequests += 1
body, err := readAndClose(request.Body)
if err != nil {
panic(err)
}
requests[nbRequests-1] = body
headers[nbRequests-1] = request.Header
if request.URL.String() != uri {
errorMsg := fmt.Sprintf("Error 404: page not found (expected '%v', got '%v').", uri, request.URL.String())
http.Error(writer, errorMsg, http.StatusNotFound)
} else if nbRequests <= nbFlakyResponses {
if code == http.StatusServiceUnavailable || code == http.StatusConflict {
writer.Header().Set("Retry-After", "0")
}
writer.WriteHeader(code)
fmt.Fprint(writer, "flaky")
} else {
writer.WriteHeader(http.StatusOK)
fmt.Fprint(writer, "ok")
}
}
server := httptest.NewServer(http.HandlerFunc(handler))
return &flakyServer{server, &nbRequests, &requests, &headers}
}
func newFlakyTLSServer(uri string, code int, nbFlakyResponses int) *flakyServer {
nbRequests := 0
requests := make([][]byte, nbFlakyResponses+1)
headers := make([]http.Header, nbFlakyResponses+1)
var server *httptest.Server
handler := func(writer http.ResponseWriter, request *http.Request) {
nbRequests += 1
body, err := readAndClose(request.Body)
if err != nil {
panic(err)
}
requests[nbRequests-1] = body
headers[nbRequests-1] = request.Header
if request.URL.String() != uri {
errorMsg := fmt.Sprintf("Error 404: page not found (expected '%v', got '%v').", uri, request.URL.String())
http.Error(writer, errorMsg, http.StatusNotFound)
} else if nbRequests <= nbFlakyResponses {
if code == http.StatusServiceUnavailable {
writer.Header().Set("Retry-After", "0")
}
writer.WriteHeader(code)
fmt.Fprint(writer, "flaky")
} else {
writer.WriteHeader(http.StatusOK)
fmt.Fprint(writer, "ok")
}
}
server = httptest.NewTLSServer(http.HandlerFunc(handler))
return &flakyServer{server, &nbRequests, &requests, &headers}
}
type simpleResponse struct {
status int
body string
}
type SimpleTestServer struct {
*httptest.Server
getResponses map[string][]simpleResponse
getResponseIndex map[string]int
putResponses map[string][]simpleResponse
putResponseIndex map[string]int
postResponses map[string][]simpleResponse
postResponseIndex map[string]int
deleteResponses map[string][]simpleResponse
deleteResponseIndex map[string]int
requests []*http.Request
}
func NewSimpleServer() *SimpleTestServer {
server := &SimpleTestServer{
getResponses: make(map[string][]simpleResponse),
getResponseIndex: make(map[string]int),
putResponses: make(map[string][]simpleResponse),
putResponseIndex: make(map[string]int),
postResponses: make(map[string][]simpleResponse),
postResponseIndex: make(map[string]int),
deleteResponses: make(map[string][]simpleResponse),
deleteResponseIndex: make(map[string]int),
}
server.Server = httptest.NewUnstartedServer(http.HandlerFunc(server.handler))
return server
}
func (s *SimpleTestServer) AddGetResponse(path string, status int, body string) {
logger.Debugf("add get response for: %s, %d", path, status)
s.getResponses[path] = append(s.getResponses[path], simpleResponse{status: status, body: body})
}
func (s *SimpleTestServer) AddPutResponse(path string, status int, body string) {
logger.Debugf("add put response for: %s, %d", path, status)
s.putResponses[path] = append(s.putResponses[path], simpleResponse{status: status, body: body})
}
func (s *SimpleTestServer) AddPostResponse(path string, status int, body string) {
logger.Debugf("add post response for: %s, %d", path, status)
s.postResponses[path] = append(s.postResponses[path], simpleResponse{status: status, body: body})
}
func (s *SimpleTestServer) AddDeleteResponse(path string, status int, body string) {
logger.Debugf("add delete response for: %s, %d", path, status)
s.deleteResponses[path] = append(s.deleteResponses[path], simpleResponse{status: status, body: body})
}
func (s *SimpleTestServer) LastRequest() *http.Request {
pos := len(s.requests) - 1
if pos < 0 {
return nil
}
return s.requests[pos]
}
func (s *SimpleTestServer) LastNRequests(n int) []*http.Request {
start := len(s.requests) - n
if start < 0 {
start = 0
}
return s.requests[start:]
}
func (s *SimpleTestServer) RequestCount() int {
return len(s.requests)
}
func (s *SimpleTestServer) ResetRequests() {
s.requests = nil
}
func (s *SimpleTestServer) handler(writer http.ResponseWriter, request *http.Request) {
method := request.Method
var (
err error
responses map[string][]simpleResponse
responseIndex map[string]int
)
switch method {
case "GET":
responses = s.getResponses
responseIndex = s.getResponseIndex
_, err = readAndClose(request.Body)
if err != nil {
panic(err) // it is a test, panic should be fine
}
case "PUT":
responses = s.putResponses
responseIndex = s.putResponseIndex
err = request.ParseForm()
if err != nil {
panic(err)
}
case "POST":
responses = s.postResponses
responseIndex = s.postResponseIndex
contentType := request.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "multipart/form-data;") {
err = request.ParseMultipartForm(2 << 20)
} else {
err = request.ParseForm()
}
if err != nil {
panic(err)
}
case "DELETE":
responses = s.deleteResponses
responseIndex = s.deleteResponseIndex
_, err := readAndClose(request.Body)
if err != nil {
panic(err)
}
default:
panic("unsupported method " + method)
}
s.requests = append(s.requests, request)
uri := request.URL.String()
testResponses, found := responses[uri]
if !found {
errorMsg := fmt.Sprintf("Error 404: page not found ('%v').", uri)
http.Error(writer, errorMsg, http.StatusNotFound)
} else {
index := responseIndex[uri]
response := testResponses[index]
responseIndex[uri] = index + 1
writer.WriteHeader(response.status)
fmt.Fprint(writer, response.body)
}
}