File: session_cookie_test.go

package info (click to toggle)
golang-github-revel-revel 1.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,240 kB
  • sloc: xml: 7; makefile: 7; javascript: 1
file content (76 lines) | stat: -rw-r--r-- 2,353 bytes parent folder | download | duplicates (2)
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
// Copyright (c) 2012-2016 The Revel Framework Authors, All rights reserved.
// Revel Framework source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.

package session_test

import (
	"testing"

	"github.com/revel/revel"
	"github.com/revel/revel/session"
	"github.com/stretchr/testify/assert"
	"net/http"
	"time"
)

func TestCookieRestore(t *testing.T) {
	a := assert.New(t)
	session.InitSession(revel.RevelLog)

	cse := revel.NewSessionCookieEngine()
	originSession := session.NewSession()
	setSharedDataTest(originSession)
	originSession["foo"] = "foo"
	originSession["bar"] = "bar"
	cookie := cse.GetCookie(originSession)
	if !cookie.Expires.IsZero() {
		t.Error("incorrect cookie expire", cookie.Expires)
	}

	restoredSession := session.NewSession()
	cse.DecodeCookie(revel.GoCookie(*cookie), restoredSession)
	a.Equal("foo",restoredSession["foo"])
	a.Equal("bar",restoredSession["bar"])
	testSharedData(originSession, restoredSession, t, a)
}

func TestCookieSessionExpire(t *testing.T) {
	session.InitSession(revel.RevelLog)
	cse := revel.NewSessionCookieEngine()
	cse.ExpireAfterDuration = time.Hour
	session := session.NewSession()
	session["user"] = "Tom"
	var cookie *http.Cookie
	for i := 0; i < 3; i++ {
		cookie = cse.GetCookie(session)
		time.Sleep(time.Second)

		cse.DecodeCookie(revel.GoCookie(*cookie), session)
	}
	expectExpire := time.Now().Add(cse.ExpireAfterDuration)
	if cookie.Expires.Unix() < expectExpire.Add(-time.Second).Unix() {
		t.Error("expect expires", cookie.Expires, "after", expectExpire.Add(-time.Second))
	}
	if cookie.Expires.Unix() > expectExpire.Unix() {
		t.Error("expect expires", cookie.Expires, "before", expectExpire)
	}

	// Test that the expiration time is zero for a "browser" session
	session.SetNoExpiration()
	cookie = cse.GetCookie(session)
	if !cookie.Expires.IsZero() {
		t.Error("expect cookie expires is zero")
	}

	// Check the default session is set
	session.SetDefaultExpiration()
	cookie = cse.GetCookie(session)
	expectExpire = time.Now().Add(cse.ExpireAfterDuration)
	if cookie.Expires.Unix() < expectExpire.Add(-time.Second).Unix() {
		t.Error("expect expires", cookie.Expires, "after", expectExpire.Add(-time.Second))
	}
	if cookie.Expires.Unix() > expectExpire.Unix() {
		t.Error("expect expires", cookie.Expires, "before", expectExpire)
	}
}