2015-07-11 03:11:09 +00:00
|
|
|
package pgstore
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"testing"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestCleanup(t *testing.T) {
|
2016-07-21 19:48:29 +00:00
|
|
|
dsn := os.Getenv("PGSTORE_TEST_CONN")
|
|
|
|
if dsn == "" {
|
|
|
|
t.Skip("This test requires a real database.")
|
|
|
|
}
|
2016-02-24 12:29:35 +00:00
|
|
|
|
2016-07-21 19:48:29 +00:00
|
|
|
ss, err := NewPGStore(dsn, []byte(secret))
|
2016-02-24 12:29:35 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal("Failed to get store", err)
|
|
|
|
}
|
|
|
|
|
2015-07-11 03:11:09 +00:00
|
|
|
defer ss.Close()
|
|
|
|
// Start the cleanup goroutine.
|
|
|
|
defer ss.StopCleanup(ss.Cleanup(time.Millisecond * 500))
|
|
|
|
|
|
|
|
req, err := http.NewRequest("GET", "http://www.example.com", nil)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal("Failed to create request", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
session, err := ss.Get(req, "newsess")
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal("Failed to create session", err)
|
|
|
|
}
|
|
|
|
|
2016-07-21 19:48:29 +00:00
|
|
|
// Expire the session.
|
2015-07-11 03:11:09 +00:00
|
|
|
session.Options.MaxAge = 1
|
|
|
|
|
|
|
|
m := make(http.Header)
|
|
|
|
if err = ss.Save(req, headerOnlyResponseWriter(m), session); err != nil {
|
|
|
|
t.Fatal("failed to save session:", err.Error())
|
|
|
|
}
|
|
|
|
|
2016-07-21 19:48:29 +00:00
|
|
|
// Give the ticker a moment to run.
|
|
|
|
time.Sleep(time.Millisecond * 1500)
|
2015-07-11 03:11:09 +00:00
|
|
|
|
2016-08-11 19:06:09 +00:00
|
|
|
// SELECT expired sessions. We should get a count of zero back.
|
|
|
|
var count int
|
|
|
|
err = ss.DbPool.QueryRow("SELECT count(*) FROM http_sessions WHERE expires_on < now()").Scan(&count)
|
2015-07-11 03:11:09 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("failed to select expired sessions from DB: %v", err)
|
|
|
|
}
|
|
|
|
|
2016-08-11 19:06:09 +00:00
|
|
|
if count > 0 {
|
|
|
|
t.Fatalf("ticker did not delete expired sessions: want 0 got %v", count)
|
2015-07-11 03:11:09 +00:00
|
|
|
}
|
|
|
|
}
|