test: Add ValidateSession tests for API package

Add comprehensive tests for the ValidateSession wrapper function covering:
- Non-existent token (returns false)
- Empty token (returns false)
- Valid token (returns true)
- Expired token (returns false)

The ValidateSession function is a simple wrapper around the SessionStore's
ValidateSession method, but having direct tests ensures the wrapper is
exercised and documents its expected behavior.

Coverage: ValidateSession 0% → 100%
This commit is contained in:
rcourtman 2025-12-02 13:22:45 +00:00
parent ef6a370144
commit d219d9965d

View file

@ -5,6 +5,7 @@ import (
"net/http"
"net/http/httptest"
"testing"
"time"
)
func TestDetectProxy(t *testing.T) {
@ -314,3 +315,62 @@ func TestGenerateSessionToken(t *testing.T) {
}
}
}
func TestValidateSession_NonExistentToken(t *testing.T) {
// Ensure session store is initialized
InitSessionStore(t.TempDir())
// A random token that doesn't exist should return false
result := ValidateSession("nonexistent-token-12345")
if result {
t.Error("ValidateSession should return false for non-existent token")
}
}
func TestValidateSession_EmptyToken(t *testing.T) {
InitSessionStore(t.TempDir())
result := ValidateSession("")
if result {
t.Error("ValidateSession should return false for empty token")
}
}
func TestValidateSession_ValidToken(t *testing.T) {
dir := t.TempDir()
InitSessionStore(dir)
// Create a valid session with a generated token
store := GetSessionStore()
token := generateSessionToken()
store.CreateSession(token, 24*time.Hour, "test-agent", "127.0.0.1")
result := ValidateSession(token)
if !result {
t.Error("ValidateSession should return true for valid token")
}
}
func TestValidateSession_ExpiredToken(t *testing.T) {
dir := t.TempDir()
InitSessionStore(dir)
// Create a session and manually expire it
store := GetSessionStore()
token := generateSessionToken()
store.CreateSession(token, 24*time.Hour, "test-agent", "127.0.0.1")
// Manually expire the session by modifying the store
store.mu.Lock()
hash := sessionHash(token)
if session, exists := store.sessions[hash]; exists {
session.ExpiresAt = time.Now().Add(-1 * time.Hour) // Set to past
store.sessions[hash] = session
}
store.mu.Unlock()
result := ValidateSession(token)
if result {
t.Error("ValidateSession should return false for expired token")
}
}