Permalink
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
91 lines (78 sloc) 2.49 KB
//
// The application that does not use this middleware, Request.Session is alwasy nil.
//
// Copyright (C) 2014 Yohei Sasaki
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package wcg
import (
"net/http"
"testing"
"time"
)
func TestSessionEncodeAndDecode(t *testing.T) {
req, _ := http.NewRequest("GET", "http://example.com/", nil)
req.RemoteAddr = "1.2.3.4:12345"
rq := NewRequest(req)
s := NewSession(rq)
now := time.Now()
s.Set("string", "string")
s.SetInt("int", 1)
s.SetFloat("float", 1.2)
s.SetBool("bool", false)
s.SetTime("time", now)
str, err := s.Encode()
if err != nil {
t.Errorf("Session encode error: %v", err)
}
s1 := NewSession(rq)
err = s1.Decode(str)
if err != nil {
t.Errorf("Session decode error: %v", err)
}
if s.Id != s1.Id {
t.Errorf("Id is not same after Decode() (%s != %s)", s.Id, s1.Id)
}
if !s.Timestamp.Equal(s1.Timestamp) {
t.Errorf("Timestamp is not same after Decode() (%v != %v)", s.Timestamp, s1.Timestamp)
}
if val, _ := s1.Get("string"); val != "string" {
t.Errorf("s1.Get(\"string\") should return \"string\", but got \"%s\"", val)
}
if val, _ := s1.GetInt("int"); val != 1 {
t.Errorf("s1.GetInt(\"int\") should return 1, but got %d", val)
}
if val, _ := s1.GetFloat("float"); val != 1.2 {
t.Errorf("s1.GetFloat(\"float\") should return 1.2, but got %f", val)
}
if val, _ := s1.GetBool("bool"); val != false {
t.Errorf("s1.GetBool(\"bool\") should return false, but got %f", val)
}
if val, _ := s1.GetTime("time"); !val.Equal(now) {
t.Errorf("s1.GetTime(\"time\") should return %s, but got %s", now, val)
}
}
func TestMemorySessionStore(t *testing.T) {
store := NewMemorySessionStore()
SessionStoreTest(store, t)
}
func TestCSRFToken(t *testing.T) {
assert := NewAssert(t)
req, _ := http.NewRequest("GET", "http://example.com/", nil)
req.RemoteAddr = "1.2.3.4:12345"
rq := NewRequest(req)
s := NewSession(rq)
token, _ := s.CSRFToken()
assert.Nil(s.ValidateToken(token), "Should return a valid token")
}