forked from demo-apps/go-gin-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
common_test.go
71 lines (57 loc) · 1.62 KB
/
common_test.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
package main
import (
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/gin-gonic/gin"
)
var tmpUserList []user
var tmpArticleList []article
// This function is used to do setup before executing the test functions
func TestMain(m *testing.M) {
//Set Gin to Test Mode
gin.SetMode(gin.TestMode)
// Run the other tests
os.Exit(m.Run())
}
// Helper function to create a router during testing
func getRouter(withTemplates bool) *gin.Engine {
r := gin.Default()
if withTemplates {
r.LoadHTMLGlob("templates/*")
r.Use(setUserStatus())
}
return r
}
// Helper function to process a request and test its response
func testHTTPResponse(t *testing.T, r *gin.Engine, req *http.Request, f func(w *httptest.ResponseRecorder) bool) {
// Create a response recorder
w := httptest.NewRecorder()
// Create the service and process the above request.
r.ServeHTTP(w, req)
if !f(w) {
t.Fail()
}
}
// This is a helper function that allows us to reuse some code in the above
// test methods
func testMiddlewareRequest(t *testing.T, r *gin.Engine, expectedHTTPCode int) {
// Create a request to send to the above route
req, _ := http.NewRequest("GET", "/", nil)
// Process the request and test the response
testHTTPResponse(t, r, req, func(w *httptest.ResponseRecorder) bool {
return w.Code == expectedHTTPCode
})
}
// This function is used to store the main lists into the temporary one
// for testing
func saveLists() {
tmpUserList = userList
tmpArticleList = articleList
}
// This function is used to restore the main lists from the temporary one
func restoreLists() {
userList = tmpUserList
articleList = tmpArticleList
}