-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathmain_test.go
More file actions
96 lines (84 loc) · 2.57 KB
/
main_test.go
File metadata and controls
96 lines (84 loc) · 2.57 KB
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
package main
import (
"net/http"
"testing"
"github.com/alecthomas/assert/v2"
"github.com/appleboy/gofight/v2"
"github.com/buger/jsonparser"
"github.com/gin-gonic/gin"
)
func init() {
gin.SetMode(gin.TestMode)
}
func Test_login(t *testing.T) {
tests := []struct {
name string
input gofight.H
code int
errorm string
message string
}{
{"invalid params", gofight.H{"username": "", "password": ""}, http.StatusBadRequest, "Parameters can't be empty", ""},
{"wrong username and password", gofight.H{"username": "test", "password": "test"}, http.StatusUnauthorized, "Authentication failed", ""},
{"correct username and password", gofight.H{"username": "hello", "password": "itsme"}, http.StatusOK, "", "Successfully authenticated user"},
}
g := gofight.New()
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g.POST("/login").
SetForm(tt.input).
Run(engine(), func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, tt.code, r.Code)
data := r.Body.Bytes()
if tt.errorm != "" {
e, _ := jsonparser.GetString(data, "error")
assert.Equal(t, tt.errorm, e)
}
if tt.message != "" {
e, _ := jsonparser.GetString(data, "message")
assert.Equal(t, tt.message, e)
}
})
})
}
}
func Test_status(t *testing.T) {
g := gofight.New()
e := engine()
g.GET("/private/me").Run(e, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusUnauthorized, r.Code)
})
var cookie string
g.POST("/login").
SetForm(gofight.H{"username": "hello", "password": "itsme"}).
Run(e, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusOK, r.Code)
cookie = r.Header().Get("Set-Cookie")
assert.NotZero(t, cookie)
})
g.GET("/private/me").
SetHeader(gofight.H{"Cookie": cookie}).
Run(e, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusOK, r.Code)
})
}
func Test_logout(t *testing.T) {
g := gofight.New()
e := engine()
g.GET("/logout").Run(e, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusBadRequest, r.Code)
})
var cookie string
g.POST("/login").
SetForm(gofight.H{"username": "hello", "password": "itsme"}).
Run(e, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusOK, r.Code)
cookie = r.Header().Get("Set-Cookie")
assert.NotZero(t, cookie)
})
g.GET("/logout").
SetHeader(gofight.H{"Cookie": cookie}).
Run(e, func(r gofight.HTTPResponse, rq gofight.HTTPRequest) {
assert.Equal(t, http.StatusOK, r.Code)
})
}