-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathsessions_test.go
273 lines (227 loc) · 8.43 KB
/
sessions_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
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
package sessions
import (
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"strings"
"testing"
// developers can use any library to add a custom cookie encoder/decoder.
// At this test code we use the gorilla's securecookie library:
"github.com/gavv/httpexpect"
"github.com/gorilla/securecookie"
)
var errReadBody = errors.New("While trying to read from the request body")
// ReadJSON reads JSON from request's body
func ReadJSON(jsonObject interface{}, req *http.Request) error {
b, err := ioutil.ReadAll(req.Body)
if err != nil && err != io.EOF {
return err
}
decoder := json.NewDecoder(strings.NewReader(string(b)))
err = decoder.Decode(jsonObject)
if err != nil && err != io.EOF {
return errReadBody
}
return nil
}
func getTester(mux *http.ServeMux, t *testing.T) *httpexpect.Expect {
testConfiguration := httpexpect.Config{
BaseURL: "http://localhost:8080",
Client: &http.Client{
Transport: httpexpect.NewBinder(mux),
Jar: httpexpect.NewJar(),
},
Reporter: httpexpect.NewAssertReporter(t),
}
return httpexpect.WithConfig(testConfiguration)
}
func writeValues(res http.ResponseWriter, values map[string]interface{}) error {
result, err := json.Marshal(values)
if err != nil {
return err
}
res.Header().Set("Content-Type", "application/json")
res.Write(result)
return nil
}
func TestSessionsNetHTTP(t *testing.T) {
testSessionsNetHTTP(t)
}
func TestSessionsEncodeDecodeNetHTTP(t *testing.T) {
// AES only supports key sizes of 16, 24 or 32 bytes.
// You either need to provide exactly that amount or you derive the key from what you type in.
hashKey := []byte("the-big-and-secret-fash-key-here")
blockKey := []byte("lot-secret-of-characters-big-too")
secureCookie := securecookie.New(hashKey, blockKey)
// set the encode/decode funcs and run the test
Default.config.Encode = secureCookie.Encode
Default.config.Decode = secureCookie.Decode
testSessionsNetHTTP(t)
}
func testSessionsNetHTTP(t *testing.T) {
// enable parallel with net/http session values vs fasthttp session values when fasthttp tests too
// t.Parallel()
mux := http.NewServeMux()
values := map[string]interface{}{
"Name": "go-sessions",
"Days": "1",
"Secret": "dsads£2132215£%%Ssdsa",
}
setHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
vals := make(map[string]interface{}, 0)
if err := ReadJSON(&vals, req); err != nil {
t.Fatalf("Cannot readjson. Trace %s", err.Error())
}
sess := Start(res, req)
for k, v := range vals {
sess.Set(k, v)
}
res.WriteHeader(http.StatusOK)
})
mux.Handle("/set/", setHandler)
writeSessValues := func(res http.ResponseWriter, req *http.Request) {
sess := Start(res, req)
sessValues := sess.GetAll()
if err := writeValues(res, sessValues); err != nil {
t.Fatalf("While serialize the session values: %s", err.Error())
}
}
getHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
writeSessValues(res, req)
})
mux.Handle("/get/", getHandler)
clearHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
sess := Start(res, req)
sess.Clear()
writeSessValues(res, req)
})
mux.Handle("/clear/", clearHandler)
destroyHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
Destroy(res, req)
writeSessValues(res, req)
res.WriteHeader(http.StatusOK)
// the cookie and all values should be empty
})
mux.Handle("/destroy/", destroyHandler)
destroyallHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
DestroyAll()
writeSessValues(res, req)
res.WriteHeader(http.StatusOK)
// the cookie and all values should be empty
})
mux.Handle("/destroyall/", destroyallHandler)
afterDestroyHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
})
// request cookie should be empty
mux.Handle("/after_destroy/", afterDestroyHandler)
e := getTester(mux, t)
e.POST("/set/").WithJSON(values).Expect().Status(http.StatusOK).Cookies().NotEmpty()
e.GET("/get/").Expect().Status(http.StatusOK).JSON().Object().Equal(values)
// test destroy which also clears first
d := e.GET("/destroy/").Expect().Status(http.StatusOK)
d.JSON().Object().Empty()
e.GET("/after_destroy/").Expect().Status(http.StatusOK).Cookies().Empty()
// set and clear again
e.POST("/set/").WithJSON(values).Expect().Status(http.StatusOK).Cookies().NotEmpty()
e.GET("/clear/").Expect().Status(http.StatusOK).JSON().Object().Empty()
// test destroy all (single)
// destroy in order to set the full object without noise
e.GET("/destroy/").Expect().Status(http.StatusOK).JSON().Object().Empty()
// set,get and destroy with (all function)
e.POST("/set/").WithJSON(values).Expect().Status(http.StatusOK)
e.GET("/get/").Expect().Status(http.StatusOK).JSON().Object().Equal(values)
// test destroy which also clears first
e.GET("/destroyall/").Expect().Status(http.StatusOK).JSON().Object().Empty()
e.GET("/after_destroy/").Expect().Status(http.StatusOK).Cookies().Empty()
}
func TestFlashMessages(t *testing.T) {
// enable parallel with net/http session values vs fasthttp session values when fasthttp tests too
// t.Parallel()
mux := http.NewServeMux()
valueSingleKey := "Name"
valueSingleValue := "go-sessions"
values := map[string]interface{}{
valueSingleKey: valueSingleValue,
"Days": "1",
"Secret": "dsads£2132215£%%Ssdsa",
}
setHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/set/" {
vals := make(map[string]interface{}, 0)
if err := ReadJSON(&vals, req); err != nil {
t.Fatalf("Cannot readjson. Trace %s", err.Error())
}
sess := Start(res, req)
for k, v := range vals {
sess.SetFlash(k, v)
}
res.WriteHeader(http.StatusOK)
}
})
mux.Handle("/set/", setHandler)
writeFlashValues := func(res http.ResponseWriter, req *http.Request) {
sess := Start(res, req)
flashes := sess.GetFlashes()
if err := writeValues(res, flashes); err != nil {
t.Fatalf("While serialize the flash values: %s", err.Error())
}
}
getSingleHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/get_single/" {
sess := Start(res, req)
flashMsgString := sess.GetFlashString(valueSingleKey)
res.Write([]byte(flashMsgString))
}
})
mux.Handle("/get_single/", getSingleHandler)
getHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/get/" {
writeFlashValues(res, req)
}
})
mux.Handle("/get/", getHandler)
clearHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/clear/" {
sess := Start(res, req)
sess.ClearFlashes()
writeFlashValues(res, req)
}
})
mux.Handle("/clear/", clearHandler)
destroyHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/destroy/" {
Destroy(res, req)
writeFlashValues(res, req)
res.WriteHeader(http.StatusOK)
}
// the cookie and all values should be empty
})
mux.Handle("/destroy/", destroyHandler)
afterDestroyHandler := http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.RequestURI == "/after_destroy/" {
res.WriteHeader(http.StatusOK)
}
})
// request cookie should be empty
mux.Handle("/after_destroy/", afterDestroyHandler)
e := getTester(mux, t)
e.POST("/set/").WithJSON(values).Expect().Status(http.StatusOK).Cookies().NotEmpty()
// get all
e.GET("/get/").Expect().Status(http.StatusOK).JSON().Object().Equal(values)
// get the same flash on other request should return nothing because the flash message is removed after fetch once
e.GET("/get/").Expect().Status(http.StatusOK).JSON().Object().Empty()
// test destroy which also clears first
d := e.GET("/destroy/").Expect().Status(http.StatusOK)
d.JSON().Object().Empty()
e.GET("/after_destroy/").Expect().Status(http.StatusOK).Cookies().Empty()
// set and clear again
e.POST("/set/").WithJSON(values).Expect().Status(http.StatusOK).Cookies().NotEmpty()
e.GET("/clear/").Expect().Status(http.StatusOK).JSON().Object().Empty()
// set again in order to take the single one ( we don't test Cookies.NotEmpty because httpexpect default conf reads that from the request-only)
e.POST("/set/").WithJSON(values).Expect().Status(http.StatusOK)
// e.GET("/get/").Expect().Status(http.StatusOK).JSON().Object().Equal(values)
e.GET("/get_single/").Expect().Status(http.StatusOK).Body().Equal(valueSingleValue)
}