-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathsession_test.go
80 lines (68 loc) · 1.4 KB
/
session_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
72
73
74
75
76
77
78
79
80
package ginsession
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/go-session/session"
)
func TestSession(t *testing.T) {
cookieName := "test_gin_session"
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(New(
session.SetCookieName(cookieName),
session.SetSign([]byte("sign")),
))
r.Use(func(ctx *gin.Context) {
store := FromContext(ctx)
if ctx.Query("login") == "1" {
foo, ok := store.Get("foo")
fmt.Fprintf(ctx.Writer, "%s:%v", foo, ok)
return
}
store.Set("foo", "bar")
err := store.Save()
if err != nil {
t.Error(err)
return
}
fmt.Fprint(ctx.Writer, "ok")
})
w := httptest.NewRecorder()
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Error(err)
return
}
r.ServeHTTP(w, req)
res := w.Result()
cookie := res.Cookies()[0]
if cookie.Name != cookieName {
t.Error("Not expected value:", cookie.Name)
return
}
buf, _ := ioutil.ReadAll(res.Body)
res.Body.Close()
if string(buf) != "ok" {
t.Error("Not expected value:", string(buf))
return
}
req, err = http.NewRequest("GET", "/?login=1", nil)
if err != nil {
t.Error(err)
return
}
req.AddCookie(cookie)
w = httptest.NewRecorder()
r.ServeHTTP(w, req)
res = w.Result()
buf, _ = ioutil.ReadAll(res.Body)
res.Body.Close()
if string(buf) != "bar:true" {
t.Error("Not expected value:", string(buf))
return
}
}