-
Notifications
You must be signed in to change notification settings - Fork 1
/
base.go
363 lines (329 loc) · 8.77 KB
/
base.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package httptest
import (
"fmt"
"io"
"log"
"net/http"
"strings"
"testing"
"text/template"
"github.com/gavv/httpexpect/v2"
"github.com/snowlyg/helper/str"
)
var (
httpTestClient *Client
// default page request params
GetRequestFunc = NewWithQueryObjectParamFunc(map[string]interface{}{"page": 1, "pageSize": 10})
// default page request params
PostRequestFunc = NewWithJsonParamFunc(map[string]interface{}{"page": 1, "pageSize": 10})
// default login request params
LoginFunc = NewWithJsonParamFunc(map[string]interface{}{"username": "admin", "password": "123456"})
// default login response params
LoginResponse = Responses{
{Key: "status", Value: http.StatusOK},
{Key: "message", Value: "OK"},
{Key: "data",
Value: Responses{
{Key: "accessToken", Value: "", Type: "notempty"},
},
},
}
//LogoutResponse default logout response params
LogoutResponse = Responses{
{Key: "status", Value: http.StatusOK},
{Key: "message", Value: "OK"},
}
// SuccessResponse default success response params
SuccessResponse = Responses{
{Key: "status", Value: http.StatusOK},
{Key: "message", Value: "OK"},
}
// ResponsePage default data response params
ResponsePage = Responses{
{Key: "status", Value: http.StatusOK},
{Key: "message", Value: "OK"},
{Key: "data", Value: Responses{
{Key: "pageSize", Value: 10},
{Key: "page", Value: 1},
}},
}
)
// paramFunc
type paramFunc func(req *httpexpect.Request) *httpexpect.Request
// NewWithJsonParamFunc return req.WithJSON
func NewWithJsonParamFunc(query map[string]interface{}) paramFunc {
return func(req *httpexpect.Request) *httpexpect.Request {
return req.WithJSON(query)
}
}
// NewWithQueryObjectParamFunc query for get method
func NewWithQueryObjectParamFunc(query map[string]interface{}) paramFunc {
return func(req *httpexpect.Request) *httpexpect.Request {
return req.WithQueryObject(query)
}
}
// NewWithFileParamFunc return req.WithFile
func NewWithFileParamFunc(fs []File) paramFunc {
return func(req *httpexpect.Request) *httpexpect.Request {
if len(fs) == 0 {
return req
}
req = req.WithMultipart()
for _, f := range fs {
req = req.WithFile(f.Key, f.Path, f.Reader)
}
return req
}
}
// NewResponsesWithLength return Responses with length value for data key
func NewResponsesWithLength(status int, message string, data []Responses, length int) Responses {
return Responses{
{Key: "status", Value: status},
{Key: "message", Value: message},
{Key: "data", Value: data, Length: length},
}
}
// NewResponses return Responses
func NewResponses(status int, message string, data ...Responses) Responses {
if status != http.StatusOK {
return Responses{
{Key: "status", Value: status},
{Key: "message", Value: message},
}
}
if len(data) == 0 {
return Responses{
{Key: "status", Value: status},
{Key: "message", Value: message},
}
}
if len(data) == 1 {
return Responses{
{Key: "status", Value: status},
{Key: "message", Value: message},
{Key: "data", Value: data[0]},
}
}
return Responses{
{Key: "status", Value: status},
{Key: "message", Value: message},
{Key: "data", Value: data},
}
}
type Client struct {
t *testing.T
expect *httpexpect.Expect
status int
headers map[string]string
}
var templateFuncs = template.FuncMap{
"underscore": func(s string) string {
var sb strings.Builder
elems := strings.Split(s, " ")
sb.WriteString(strings.Join(elems, "_"))
return sb.String()
},
}
type defulterAssertionHandler struct {
ctx *httpexpect.AssertionContext
failure *httpexpect.AssertionFailure
}
func (h *defulterAssertionHandler) Success(ctx *httpexpect.AssertionContext) {
h.ctx = ctx
}
func (h *defulterAssertionHandler) Failure(
ctx *httpexpect.AssertionContext, failure *httpexpect.AssertionFailure,
) {
h.ctx = ctx
h.failure = failure
}
// Instance return test client instance
func Instance(t *testing.T, handler http.Handler, url ...string) *Client {
config := httpexpect.Config{
Client: &http.Client{
Transport: httpexpect.NewBinder(handler),
Jar: httpexpect.NewCookieJar(),
},
Reporter: httpexpect.NewAssertReporter(t),
Printers: []httpexpect.Printer{
httpexpect.NewDebugPrinter(t, true),
},
AssertionHandler: &httpexpect.DefaultAssertionHandler{
Formatter: &httpexpect.DefaultFormatter{
TemplateFuncs: templateFuncs,
SuccessTemplate: "[OK]",
},
Reporter: t,
// to enable printing of success messages, we need to set `Logger`
Logger: nil,
},
}
if len(url) == 1 && url[0] != "" {
config.BaseURL = url[0]
}
httpTestClient = &Client{
t: t,
expect: httpexpect.WithConfig(config),
headers: map[string]string{},
}
return httpTestClient
}
// Login for http login
func (c *Client) Login(url, tokenIndex string, res Responses, paramFuncs ...paramFunc) error {
if len(paramFuncs) == 0 {
paramFuncs = append(paramFuncs, LoginFunc)
}
c.POST(url, res, paramFuncs...)
token := res.GetString("data.accessToken")
if tokenIndex != "" {
token = res.GetString(tokenIndex)
}
fmt.Printf("access_token is '%s'\n", token)
if token == "" {
return fmt.Errorf("access_token is empty")
}
c.headers["Authorization"] = str.Join("Bearer ", token)
c.expect = c.expect.Builder(func(req *httpexpect.Request) {
req.WithHeaders(c.headers)
})
return nil
}
// Logout for http logout
func (c *Client) Logout(url string, res Responses) {
if res == nil {
res = LogoutResponse
}
c.GET(url, res)
}
type File struct {
Key string
Path string
Reader io.Reader
}
// checkStatus check what's http response stauts want
func (c *Client) checkStatus() int {
if c.status == 0 {
return http.StatusOK
}
return c.status
}
// SetStatus set what's http response stauts want
func (c *Client) SetStatus(status int) *Client {
c.status = status
return c
}
// SetHeaders set http request headers
func (c *Client) SetHeaders(headers map[string]string) *Client {
c.headers = headers
return c
}
// POST
func (c *Client) POST(url string, res interface{}, paramFuncs ...paramFunc) {
req := c.expect.POST(url)
if len(paramFuncs) > 0 {
for _, f := range paramFuncs {
req = f(req)
}
}
if testRes, ok := res.(Responses); ok {
obj := req.Expect().Status(c.checkStatus()).JSON()
testRes.Test(obj)
} else if testRes, ok := res.([]Responses); ok {
array := req.Expect().Status(c.checkStatus()).JSON().Array()
for i, v := range testRes {
v.Test(array.Element(i))
}
} else {
log.Println("data type error")
}
}
// PUT
func (c *Client) PUT(url string, res interface{}, paramFuncs ...paramFunc) {
req := c.expect.PUT(url)
if len(paramFuncs) > 0 {
for _, f := range paramFuncs {
req = f(req)
}
}
if testRes, ok := res.(Responses); ok {
obj := req.Expect().Status(c.checkStatus()).JSON()
testRes.Test(obj)
} else if testRes, ok := res.([]Responses); ok {
array := req.Expect().Status(c.checkStatus()).JSON().Array()
for i, v := range testRes {
v.Test(array.Element(i))
}
} else {
log.Println("data type error")
}
}
// UPLOAD
func (c *Client) UPLOAD(url string, res interface{}, paramFuncs ...paramFunc) {
req := c.expect.POST(url)
if len(paramFuncs) > 0 {
for _, f := range paramFuncs {
req = f(req)
}
}
if testRes, ok := res.(Responses); ok {
obj := req.Expect().Status(c.checkStatus()).JSON()
testRes.Test(obj)
} else if testRes, ok := res.([]Responses); ok {
array := req.Expect().Status(c.checkStatus()).JSON().Array()
for i, v := range testRes {
v.Test(array.Element(i))
}
} else {
log.Println("data type error")
}
}
// GET
func (c *Client) GET(url string, res interface{}, paramFuncs ...paramFunc) {
req := c.expect.GET(url)
if len(paramFuncs) > 0 {
for _, f := range paramFuncs {
req = f(req)
}
}
if testRes, ok := res.(Responses); ok {
obj := req.Expect().Status(c.checkStatus()).JSON()
testRes.Test(obj)
} else if testRes, ok := res.([]Responses); ok {
array := req.Expect().Status(c.checkStatus()).JSON().Array()
for i, v := range testRes {
v.Test(array.Element(i))
}
} else {
log.Println("data type error")
}
}
// DOWNLOAD
func (c *Client) DOWNLOAD(url string, res interface{}, paramFuncs ...paramFunc) string {
req := c.expect.GET(url)
if len(paramFuncs) > 0 {
for _, f := range paramFuncs {
req = f(req)
}
}
return req.Expect().Status(c.checkStatus()).ContentType("application/octet-stream").Body().NotEmpty().Raw()
}
// DELETE
func (c *Client) DELETE(url string, res interface{}, paramFuncs ...paramFunc) {
req := c.expect.DELETE(url)
if len(paramFuncs) > 0 {
for _, f := range paramFuncs {
req = f(req)
}
}
if testRes, ok := res.(Responses); ok {
obj := req.Expect().Status(c.checkStatus()).JSON()
testRes.Test(obj)
} else if testRes, ok := res.([]Responses); ok {
array := req.Expect().Status(c.checkStatus()).JSON().Array()
for i, v := range testRes {
v.Test(array.Element(i))
}
} else {
log.Println("data type error")
}
}