-
Notifications
You must be signed in to change notification settings - Fork 4
/
xormstore_test.go
375 lines (305 loc) · 8.57 KB
/
xormstore_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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// TODO: more expire/cleanup tests?
package xormstore
import (
"flag"
"fmt"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"
"github.com/lafriks/xormstore/util"
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"xorm.io/xorm"
"xorm.io/xorm/log"
)
// default test db
var dbURI = "sqlite3://file:dummy?mode=memory&cache=shared"
// TODO: this is ugly
func parseCookies(value string) map[string]*http.Cookie {
m := map[string]*http.Cookie{}
for _, c := range (&http.Request{Header: http.Header{"Cookie": {value}}}).Cookies() {
m[c.Name] = c
}
return m
}
func connectDbURI(uri string) (*xorm.Engine, error) {
parts := strings.SplitN(uri, "://", 2)
driver := parts[0]
dsn := parts[1]
var err error
// retry to give some time for db to be ready
for i := 0; i < 300; i++ {
e, err := xorm.NewEngine(driver, dsn)
e.SetLogLevel(log.LOG_WARNING)
if err == nil {
if err := e.Ping(); err == nil {
return e, nil
}
}
time.Sleep(time.Second)
}
return nil, err
}
// create new shared in memory db
func newEngine() *xorm.Engine {
var err error
var e *xorm.Engine
if e, err = connectDbURI(dbURI); err != nil {
panic(err)
}
//e.ShowSQL(true)
// cleanup db
if err := e.DropTables(
&xormSession{tableName: "abc"},
&xormSession{tableName: "sessions"},
); err != nil {
panic(err)
}
return e
}
func req(handler http.HandlerFunc, sessionCookie *http.Cookie) *httptest.ResponseRecorder {
req, _ := http.NewRequest("GET", "http://test", nil)
if sessionCookie != nil {
req.Header.Add("Cookie", fmt.Sprintf("%s=%s", sessionCookie.Name, sessionCookie.Value))
}
w := httptest.NewRecorder()
handler(w, req)
return w
}
func match(t *testing.T, resp *httptest.ResponseRecorder, code int, body string) {
if resp.Code != code {
t.Errorf("Expected %v, actual %v", code, resp.Code)
}
// http.Error in countHandler adds a \n
if strings.Trim(resp.Body.String(), "\n") != body {
t.Errorf("Expected %v, actual %v", body, resp.Body)
}
}
func findSession(e *xorm.Engine, store *Store, id string) *xormSession {
s := &xormSession{tableName: store.opts.TableName}
if has, err := e.ID(id).Get(s); !has || err != nil {
return nil
}
return s
}
func makeCountHandler(name string, store *Store) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, name)
if err != nil {
panic(err)
}
count, _ := session.Values["count"].(int)
count++
session.Values["count"] = count
if err := store.Save(r, w, session); err != nil {
panic(err)
}
// leak session ID so we can mess with it in the db
w.Header().Add("X-Session", session.ID)
http.Error(w, fmt.Sprintf("%d", count), http.StatusOK)
}
}
func TestBasic(t *testing.T) {
store, err := New(newEngine(), []byte("secret"))
if err != nil {
t.Errorf("New init failed: %d", err)
return
}
countFn := makeCountHandler("session", store)
r1 := req(countFn, nil)
match(t, r1, 200, "1")
r2 := req(countFn, parseCookies(r1.Header().Get("Set-Cookie"))["session"])
match(t, r2, 200, "2")
}
func TestExpire(t *testing.T) {
e := newEngine()
store, err := New(e, []byte("secret"))
if err != nil {
t.Errorf("New init failed: %d", err)
return
}
countFn := makeCountHandler("session", store)
r1 := req(countFn, nil)
match(t, r1, 200, "1")
// test still in db but expired
id := r1.Header().Get("X-Session")
s := findSession(e, store, id)
s.ExpiresUnix = util.TimeStampNow().AddDuration(-40 * 24 * time.Hour)
e.ID(s.ID).Cols("expires_unix").Update(s)
r2 := req(countFn, parseCookies(r1.Header().Get("Set-Cookie"))["session"])
match(t, r2, 200, "1")
store.Cleanup()
if findSession(e, store, id) != nil {
t.Error("Expected session to be deleted")
}
}
func TestBrokenCookie(t *testing.T) {
store, err := New(newEngine(), []byte("secret"))
if err != nil {
t.Errorf("New init failed: %d", err)
return
}
countFn := makeCountHandler("session", store)
r1 := req(countFn, nil)
match(t, r1, 200, "1")
cookie := parseCookies(r1.Header().Get("Set-Cookie"))["session"]
cookie.Value += "junk"
r2 := req(countFn, cookie)
match(t, r2, 200, "1")
}
func TestMaxAgeNegative(t *testing.T) {
e := newEngine()
store, err := New(e, []byte("secret"))
if err != nil {
t.Errorf("New init failed: %d", err)
return
}
countFn := makeCountHandler("session", store)
r1 := req(countFn, nil)
match(t, r1, 200, "1")
r2 := req(func(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "session")
if err != nil {
panic(err)
}
session.Options.MaxAge = -1
store.Save(r, w, session)
http.Error(w, "", http.StatusOK)
}, parseCookies(r1.Header().Get("Set-Cookie"))["session"])
match(t, r2, 200, "")
c := parseCookies(r2.Header().Get("Set-Cookie"))["session"]
if c != nil && c.Value != "" {
t.Error("Expected empty Set-Cookie session header", c)
}
id := r1.Header().Get("X-Session")
if s := findSession(e, store, id); s != nil {
t.Error("Expected session to be deleted")
}
}
func TestMaxLength(t *testing.T) {
store, err := New(newEngine(), []byte("secret"))
if err != nil {
t.Errorf("New init failed: %d", err)
return
}
store.MaxLength(10)
r1 := req(func(w http.ResponseWriter, r *http.Request) {
session, err := store.Get(r, "session")
if err != nil {
panic(err)
}
session.Values["a"] = "aaaaaaaaaaaaaaaaaaaaaaaa"
if err := store.Save(r, w, session); err == nil {
t.Error("Expected too large error")
}
http.Error(w, "", http.StatusOK)
}, nil)
match(t, r1, 200, "")
}
func TestTableName(t *testing.T) {
e := newEngine()
store, err := NewOptions(e, Options{TableName: "abc"}, []byte("secret"))
if err != nil {
t.Errorf("NewOptions init failed: %d", err)
return
}
countFn := makeCountHandler("session", store)
if has, err := e.IsTableExist(&xormSession{tableName: store.opts.TableName}); !has || err != nil {
t.Error("Expected abc table created")
}
r1 := req(countFn, nil)
match(t, r1, 200, "1")
r2 := req(countFn, parseCookies(r1.Header().Get("Set-Cookie"))["session"])
match(t, r2, 200, "2")
id := r2.Header().Get("X-Session")
s := findSession(e, store, id)
s.ExpiresUnix = util.TimeStampNow().AddDuration(-40 * 24 * time.Hour)
e.ID(s.ID).Cols("expires_unix").Update(s)
store.Cleanup()
if findSession(e, store, id) != nil {
t.Error("Expected session to be deleted")
}
}
func TestSkipCreateTable(t *testing.T) {
e := newEngine()
store, err := NewOptions(e, Options{SkipCreateTable: true}, []byte("secret"))
if err != nil {
t.Errorf("NewOptions init failed: %d", err)
return
}
if has, err := e.IsTableExist(&xormSession{tableName: store.opts.TableName}); has || err != nil {
t.Error("Expected no table created")
}
}
func TestMultiSessions(t *testing.T) {
store, err := New(newEngine(), []byte("secret"))
if err != nil {
t.Errorf("New init failed: %d", err)
return
}
countFn1 := makeCountHandler("session1", store)
countFn2 := makeCountHandler("session2", store)
r1 := req(countFn1, nil)
match(t, r1, 200, "1")
r2 := req(countFn2, nil)
match(t, r2, 200, "1")
r3 := req(countFn1, parseCookies(r1.Header().Get("Set-Cookie"))["session1"])
match(t, r3, 200, "2")
r4 := req(countFn2, parseCookies(r2.Header().Get("Set-Cookie"))["session2"])
match(t, r4, 200, "2")
}
func TestPeriodicCleanup(t *testing.T) {
e := newEngine()
store, err := New(e, []byte("secret"))
if err != nil {
t.Errorf("New init failed: %d", err)
return
}
store.SessionOpts.MaxAge = 1
countFn := makeCountHandler("session", store)
quit := make(chan struct{})
go store.PeriodicCleanup(200*time.Millisecond, quit)
// test that cleanup i done at least twice
r1 := req(countFn, nil)
id1 := r1.Header().Get("X-Session")
if findSession(e, store, id1) == nil {
t.Error("Expected r1 session to exist")
}
time.Sleep(2 * time.Second)
if findSession(e, store, id1) != nil {
t.Error("Expected r1 session to be deleted")
}
r2 := req(countFn, nil)
id2 := r2.Header().Get("X-Session")
if findSession(e, store, id2) == nil {
t.Error("Expected r2 session to exist")
}
time.Sleep(2 * time.Second)
if findSession(e, store, id2) != nil {
t.Error("Expected r2 session to be deleted")
}
close(quit)
// test that cleanup has stopped
r3 := req(countFn, nil)
id3 := r3.Header().Get("X-Session")
if findSession(e, store, id3) == nil {
t.Error("Expected r3 session to exist")
}
time.Sleep(2 * time.Second)
if findSession(e, store, id3) == nil {
t.Error("Expected r3 session to exist")
}
}
func TestMain(m *testing.M) {
flag.Parse()
if v := os.Getenv("DATABASE_URI"); v != "" {
dbURI = v
}
fmt.Printf("DATABASE_URI=%s\n", dbURI)
os.Exit(m.Run())
}