-
Notifications
You must be signed in to change notification settings - Fork 10
/
httpcheck.go
297 lines (235 loc) · 6.94 KB
/
httpcheck.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
package httpcheck
import (
"encoding/json"
"encoding/xml"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"strings"
"testing"
"time"
"github.com/ivpusic/golog"
"github.com/stretchr/testify/assert"
"net/http/httptest"
)
type (
Checker struct {
t *testing.T
client *http.Client
request *http.Request
response *http.Response
pcookies map[string]bool
server *httptest.Server
handler http.Handler
}
Callback func(*http.Response)
)
var (
logger = golog.GetLogger("github.com/ivpusic/httpcheck")
)
func New(t *testing.T, handler http.Handler) *Checker {
logger.Level = golog.INFO
jar, _ := cookiejar.New(nil)
instance := &Checker{
t: t,
client: &http.Client{
Timeout: time.Duration(5 * time.Second),
Jar: jar,
},
pcookies: map[string]bool{},
server: createServer(handler),
handler: handler,
}
return instance
}
func createServer(handler http.Handler) *httptest.Server {
return httptest.NewUnstartedServer(handler)
}
// enables a cookie to be preserved between requests
func (c *Checker) PersistCookie(cookie string) {
c.pcookies[cookie] = true
}
// the specified cookie will not be preserved during requests anymore
func (c *Checker) UnpersistCookie(cookie string) {
delete(c.pcookies, cookie)
}
// Will run HTTP server
func (c *Checker) run() {
logger.Debug("running server")
c.server.Start()
}
// Will stop HTTP server
func (c *Checker) stop() {
logger.Debug("stopping server")
c.server.Close()
c.server = createServer(c.handler)
}
func (c *Checker) SetTesting(t *testing.T) *Checker {
if t == nil {
panic("testing.T is nil")
}
c.t = t
return c
}
// make request /////////////////////////////////////////////////
// If you want to provide you custom http.Request instance, you can do it using this method
// In this case internal http.Request instance won't be created, and passed instane will be used
// for making request
func (c *Checker) TestRequest(request *http.Request) *Checker {
assert.NotNil(c.t, request, "Request nil")
c.request = request
return c
}
// Prepare for testing some part of code which lives on provided path and method.
func (c *Checker) Test(method, path string) *Checker {
method = strings.ToUpper(method)
request, err := http.NewRequest(method, c.GetUrl()+path, nil)
assert.Nil(c.t, err, "Failed to make new request")
c.request = request
return c
}
func (c *Checker) GetUrl() string {
return "http://" + c.server.Listener.Addr().String()
}
// headers ///////////////////////////////////////////////////////
// Will put header on request
func (c *Checker) WithHeader(key, value string) *Checker {
c.request.Header.Set(key, value)
return c
}
// Will put a map of headers on request
func (c *Checker) WithHeaders(headers map[string]string) *Checker {
for key, value := range headers {
c.request.Header.Set(key, value)
}
return c
}
// Will check if response contains header on provided key with provided value
func (c *Checker) HasHeader(key, expectedValue string) *Checker {
value := c.response.Header.Get(key)
assert.Exactly(c.t, expectedValue, value)
return c
}
// Will check if response contains a provided headers map
func (c *Checker) HasHeaders(headers map[string]string) *Checker {
for key, expectedValue := range headers {
value := c.response.Header.Get(key)
assert.Exactly(c.t, expectedValue, value)
}
return c
}
// cookies ///////////////////////////////////////////////////////
// Will put cookie on request
func (c *Checker) HasCookie(key, expectedValue string) *Checker {
found := false
for _, cookie := range c.client.Jar.Cookies(c.request.URL) {
if cookie.Name == key && cookie.Value == expectedValue {
found = true
break
}
}
assert.True(c.t, found)
return c
}
// Will ckeck if response contains cookie with provided key and value
func (c *Checker) WithCookie(key, value string) *Checker {
c.request.AddCookie(&http.Cookie{
Name: key,
Value: value,
})
return c
}
// status ////////////////////////////////////////////////////////
// Will ckeck if response status is equal to provided
func (c *Checker) HasStatus(status int) *Checker {
assert.Exactly(c.t, status, c.response.StatusCode)
return c
}
// json body /////////////////////////////////////////////////////
// Will add the json-encoded struct to the body
func (c *Checker) WithJson(value interface{}) *Checker {
encoded, err := json.Marshal(value)
assert.Nil(c.t, err)
return c.WithBody(encoded)
}
// Will ckeck if body contains json with provided value
func (c *Checker) HasJson(value interface{}) *Checker {
body, err := ioutil.ReadAll(c.response.Body)
assert.Nil(c.t, err)
valueBytes, err := json.Marshal(value)
assert.Nil(c.t, err)
assert.Equal(c.t, string(valueBytes), string(body))
return c
}
// xml //////////////////////////////////////////////////////////
// Adds a XML encoded body to the request
func (c *Checker) WithXml(value interface{}) *Checker {
encoded, err := xml.Marshal(value)
assert.Nil(c.t, err)
return c.WithBody(encoded)
}
// Will ckeck if body contains xml with provided value
func (c *Checker) HasXml(value interface{}) *Checker {
body, err := ioutil.ReadAll(c.response.Body)
assert.Nil(c.t, err)
valueBytes, err := xml.Marshal(value)
assert.Nil(c.t, err)
assert.Equal(c.t, string(valueBytes), string(body))
return c
}
// body //////////////////////////////////////////////////////////
// Adds the []byte data to the body
func (c *Checker) WithBody(body []byte) *Checker {
c.request.Body = newClosingBuffer(body)
c.request.ContentLength = int64(len(body))
return c
}
// Will check if body contains provided []byte data
func (c *Checker) HasBody(body []byte) *Checker {
responseBody, err := ioutil.ReadAll(c.response.Body)
assert.Nil(c.t, err)
assert.Equal(c.t, body, responseBody)
return c
}
// Adds the string to the body
func (c *Checker) WithString(body string) *Checker {
c.request.Body = newClosingBufferString(body)
c.request.ContentLength = int64(len(body))
return c
}
// Convenience wrapper for HasBody
// Checks if body is equal to the given string
func (c *Checker) HasString(body string) *Checker {
return c.HasBody([]byte(body))
}
// Will make reqeust to built request object.
// After request is made, it will save response object for future assertions
// Responsibility of this method is also to start and stop HTTP server
func (c *Checker) Check() *Checker {
// start server in new goroutine
c.run()
defer c.stop()
newJar, _ := cookiejar.New(nil)
for name, _ := range c.pcookies {
for _, oldCookie := range c.client.Jar.Cookies(c.request.URL) {
if name == oldCookie.Name {
newJar.SetCookies(c.request.URL, []*http.Cookie{oldCookie})
break
}
}
}
c.client.Jar = newJar
response, err := c.client.Do(c.request)
if err != nil {
println(err.Error())
c.t.FailNow()
}
// assert.Nil(c.t, err, "Failed while making new request.", err)
// save response for assertion checks
c.response = response
return c
}
// Will call provided callback function with current response
func (c *Checker) Cb(cb Callback) {
cb(c.response)
}