Files

97 lines
2.2 KiB
Go

package handlers
import (
"net/http"
"net/http/httptest"
"testing"
"time"
"atcr.io/pkg/appview/db"
)
func TestLogoutHandler_NoSession(t *testing.T) {
database := setupTestDB(t)
defer database.Close()
sessionStore := db.NewSessionStore(database)
handler := &LogoutHandler{
BaseUIHandler: BaseUIHandler{SessionStore: sessionStore},
}
req := httptest.NewRequest("GET", "/auth/logout", nil)
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
// Should redirect even with no session
if rr.Code != http.StatusFound {
t.Errorf("Expected status %d, got %d", http.StatusFound, rr.Code)
}
location := rr.Header().Get("Location")
if location != "/" {
t.Errorf("Expected redirect to /, got %s", location)
}
}
func TestLogoutHandler_WithSession(t *testing.T) {
database := setupTestDB(t)
defer database.Close()
sessionStore := db.NewSessionStore(database)
// Create a user first (required for foreign key)
_, err := database.Exec(`
INSERT INTO users (did, handle, pds_endpoint, last_seen)
VALUES (?, ?, ?, ?)
`, "did:plc:test123", "test.bsky.social", "https://bsky.social", time.Now())
if err != nil {
t.Fatalf("Failed to create user: %v", err)
}
// Create a session
sessionID, err := sessionStore.Create("did:plc:test123", "test.bsky.social", "https://bsky.social", 24*time.Hour)
if err != nil {
t.Fatalf("Failed to create session: %v", err)
}
handler := &LogoutHandler{
BaseUIHandler: BaseUIHandler{SessionStore: sessionStore},
}
req := httptest.NewRequest("GET", "/auth/logout", nil)
req.AddCookie(&http.Cookie{
Name: "atcr_session",
Value: sessionID,
})
rr := httptest.NewRecorder()
handler.ServeHTTP(rr, req)
// Should redirect
if rr.Code != http.StatusFound {
t.Errorf("Expected status %d, got %d", http.StatusFound, rr.Code)
}
// Should clear cookie
cookies := rr.Result().Cookies()
found := false
for _, cookie := range cookies {
if cookie.Name == "atcr_session" {
found = true
if cookie.MaxAge != -1 {
t.Errorf("Expected cookie MaxAge=-1, got %d", cookie.MaxAge)
}
}
}
if !found {
t.Error("Expected atcr_session cookie to be cleared")
}
// Session should be deleted
_, exists := sessionStore.Get(sessionID)
if exists {
t.Error("Expected session to be deleted")
}
}