-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_utils.go
104 lines (84 loc) · 2.15 KB
/
test_utils.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
package testutils
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"github.com/gin-gonic/gin"
)
var contentType = "Content-Type"
var applicationJson = "application/json"
func GetTestGinContext(w *httptest.ResponseRecorder) *gin.Context {
gin.SetMode(gin.TestMode)
ctx, _ := gin.CreateTestContext(w)
ctx.Request = &http.Request{
Header: make(http.Header),
URL: &url.URL{},
}
return ctx
}
func MockJsonPost(c *gin.Context, content interface{}, params gin.Params, urlValues url.Values) {
c.Request.Method = "POST"
c.Request.Header.Set(contentType, applicationJson)
if content != nil {
jsonbytes, err := json.Marshal(content)
if err != nil {
panic(err)
}
// the request body must be an io.ReadCloser
// the bytes buffer though doesn't implement io.Closer,
// so you wrap it in a no-op closer
c.Request.Body = io.NopCloser(bytes.NewBuffer(jsonbytes))
}
// set path params
if params != nil {
c.Params = params
}
// set query params
if urlValues != nil {
c.Request.URL.RawQuery = urlValues.Encode()
}
}
func MockJsonGet(c *gin.Context, params gin.Params, urlValues url.Values) {
c.Request.Method = "GET"
c.Request.Header.Set(contentType, applicationJson)
c.Set("user_id", 1)
// set path params
if params != nil {
c.Params = params
}
// set query params
if urlValues != nil {
c.Request.URL.RawQuery = urlValues.Encode()
}
}
func MockJsonDelete(c *gin.Context, params gin.Params) {
c.Request.Method = "DELETE"
c.Request.Header.Set(contentType, applicationJson)
c.Set("user_id", 1)
// set path params
if params != nil {
c.Params = params
}
}
func MockJsonPut(c *gin.Context, content interface{}, params gin.Params) {
c.Request.Method = "PUT"
c.Request.Header.Set(contentType, applicationJson)
c.Set("user_id", 1)
// set path params
if params != nil {
c.Params = params
}
if content != nil {
jsonbytes, err := json.Marshal(content)
if err != nil {
panic(err)
}
// the request body must be an io.ReadCloser
// the bytes buffer though doesn't implement io.Closer,
// so you wrap it in a no-op closer
c.Request.Body = io.NopCloser(bytes.NewBuffer(jsonbytes))
}
}