forked from ivpusic/httpcheck
/
httpcheck.go
228 lines (179 loc) · 5.46 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
package httpcheck
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/ivpusic/golog"
"github.com/stretchr/testify/assert"
)
type (
Checker struct {
t *testing.T
handler http.Handler
request *http.Request
response *http.Response
cookies map[string]string
}
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
instance := &Checker{
t: t,
handler: handler,
cookies: map[string]string{},
}
return instance
}
// 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, path, nil)
assert.Nil(c.t, err, "Failed to make new request")
c.request = request
return c
}
// headers ///////////////////////////////////////////////////////
// Will put header on request
func (c *Checker) WithHeader(key, value string) *Checker {
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
}
// cookies ///////////////////////////////////////////////////////
// Will put cookie on request
func (c *Checker) HasCookie(key, expectedValue string) *Checker {
value, exists := c.cookies[key]
assert.True(c.t, exists && expectedValue == value)
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)
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)
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))
}
func (c *Checker) handleCookies(r *http.Response) {
if header, exist := r.Header["Set-Cookie"]; exist {
for _, str := range header {
if ind := strings.Index(str, "="); ind > 0 {
c.cookies[str[0:ind]] = str[ind+1 : len(str)]
} else {
panic("did not find = in cookie string")
}
}
}
}
func (c *Checker) generateCookieString() string {
str := ""
for name, val := range c.cookies {
str += fmt.Sprintf("%s=%s;", name, val)
}
return str
}
// 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 {
// set cookies
c.request.Header.Set("Cookie", c.generateCookieString())
recorder := httptest.NewRecorder()
c.handler.ServeHTTP(recorder, c.request)
resp := &http.Response{
StatusCode: recorder.Code,
Body: NewReadCloser(recorder.Body),
Header: recorder.Header(),
}
c.handleCookies(resp)
c.response = resp
return c
}
// Will call provided callback function with current response
func (c *Checker) Cb(cb Callback) {
cb(c.response)
}