Files
linearvoid/backend/chat/src/handlers/handlers_test.go
T
zwitschi 33b6296c5e
CI / test (push) Successful in 2m50s
CI / docker (push) Successful in 5m12s
Refactor load testing scripts to support Bash and PowerShell
- Updated README.md to reflect changes in load testing commands and added usage examples for Bash scripts.
- Converted PowerShell load testing scripts to Bash equivalents for better cross-platform compatibility.
- Added new Bash scripts: run-loadtests.sh, summarize-artillery.sh, and summarize-k6.sh to mirror existing PowerShell functionality.
- Updated admin-api.js and ws-chat.yml for consistency and improved performance metrics reporting.
- Enhanced error handling and output formatting in summary scripts for better readability.
2026-09-02 19:47:34 +02:00

1423 lines
40 KiB
Go

package handlers
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/glebarez/sqlite"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"chat/src/auth"
"chat/src/config"
"chat/src/db"
"chat/src/media"
"chat/src/ws"
)
// mockRedis implements db.RedisClient for handler tests.
type mockRedis struct {
mu sync.Mutex
store map[string]string
}
func newMockRedis() *mockRedis {
return &mockRedis{store: make(map[string]string)}
}
func (m *mockRedis) Ping(ctx context.Context) error { return nil }
func (m *mockRedis) Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error {
m.mu.Lock()
defer m.mu.Unlock()
m.store[key] = value.(string)
return nil
}
func (m *mockRedis) Get(ctx context.Context, key string) (string, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.store[key], nil
}
func (m *mockRedis) Del(ctx context.Context, keys ...string) error {
m.mu.Lock()
defer m.mu.Unlock()
for _, k := range keys {
delete(m.store, k)
}
return nil
}
func (m *mockRedis) Incr(ctx context.Context, key string) (int64, error) {
m.mu.Lock()
defer m.mu.Unlock()
m.store[key] = "1"
return 1, nil
}
func (m *mockRedis) Decr(ctx context.Context, key string) (int64, error) { return 0, nil }
func (m *mockRedis) Expire(ctx context.Context, key string, expiration time.Duration) error {
return nil
}
func (m *mockRedis) Exists(ctx context.Context, keys ...string) (int64, error) {
m.mu.Lock()
defer m.mu.Unlock()
for _, k := range keys {
if _, ok := m.store[k]; ok {
return 1, nil
}
}
return 0, nil
}
func (m *mockRedis) Publish(ctx context.Context, channel string, message interface{}) error {
return nil
}
func (m *mockRedis) PSubscribe(ctx context.Context, channels ...string) db.PubSub {
return nil
}
func (m *mockRedis) Scan(ctx context.Context, cursor uint64, match string, count int64) ([]string, uint64, error) {
m.mu.Lock()
defer m.mu.Unlock()
var keys []string
for k := range m.store {
if strings.Contains(k, strings.TrimSuffix(match, "*")) {
keys = append(keys, k)
}
}
return keys, 0, nil
}
func (m *mockRedis) Info(ctx context.Context, sections ...string) (string, error) {
return "connected_clients:1\nused_memory_human:1M\n", nil
}
func (m *mockRedis) Close() error { return nil }
func setupTestDeps(t *testing.T) (*Dependencies, *gorm.DB, *auth.SessionStore) {
t.Helper()
gormDB, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
if err != nil {
t.Fatalf("failed to open test DB: %v", err)
}
// A single connection keeps the in-memory SQLite database shared across
// goroutines (each :memory: connection would otherwise be a separate DB).
sqlDB, err := gormDB.DB()
if err != nil {
t.Fatalf("failed to get sql.DB: %v", err)
}
sqlDB.SetMaxOpenConns(1)
gormDB.AutoMigrate(&db.Message{}, &db.ModerationLog{}, &db.Media{}, &db.ScheduleOverride{}, &db.User{})
mr := newMockRedis()
sessionStore := auth.NewSessionStore()
hub := ws.NewHub(gormDB, mr, "test-instance", 10, 10*time.Second, config.AdminUsername())
deps := &Dependencies{
DB: gormDB,
Redis: mr,
Hub: hub,
SessionStore: sessionStore,
UserSessions: auth.NewUserSessionStore(),
DBDriver: "sqlite",
}
return deps, gormDB, sessionStore
}
// adminCookie creates a valid admin session and returns the cookie header.
func adminCookie(t *testing.T, store *auth.SessionStore) string {
t.Helper()
token, _ := auth.GenerateToken()
store.Add(token, time.Now().Add(1*time.Hour))
return config.AdminSessionCookieName + "=" + token
}
func TestHandleAdminLogin_Success(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminLogin(deps)
// Ensure env vars are set for credential check
os.Setenv("ADMIN_USERNAME", "admin")
os.Setenv("ADMIN_PASSWORD", "admin")
defer os.Unsetenv("ADMIN_USERNAME")
defer os.Unsetenv("ADMIN_PASSWORD")
body := `{"username":"admin","password":"admin"}`
req := httptest.NewRequest("POST", "/api/admin/login", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var resp AdminSessionResponse
json.NewDecoder(w.Body).Decode(&resp)
if !resp.Authenticated {
t.Error("Authenticated = false, want true")
}
// Check cookie set
cookies := w.Result().Cookies()
found := false
for _, c := range cookies {
if c.Name == config.AdminSessionCookieName {
found = true
break
}
}
if !found {
t.Error("session cookie not set")
}
}
func TestHandleAdminLogin_InvalidCreds(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminLogin(deps)
body := `{"username":"admin","password":"wrong"}`
req := httptest.NewRequest("POST", "/api/admin/login", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", w.Code)
}
}
func TestHandleAdminLogin_InvalidJSON(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminLogin(deps)
req := httptest.NewRequest("POST", "/api/admin/login", strings.NewReader("not json"))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400", w.Code)
}
}
func TestHandleAdminLogin_WrongMethod(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminLogin(deps)
req := httptest.NewRequest("GET", "/api/admin/login", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusMethodNotAllowed {
t.Errorf("status = %d, want 405", w.Code)
}
}
func TestHandleAdminLogout(t *testing.T) {
deps, _, store := setupTestDeps(t)
handler := HandleAdminLogout(deps)
cookie := adminCookie(t, store)
req := httptest.NewRequest("POST", "/api/admin/logout", nil)
req.Header.Set("Cookie", cookie)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
// Cookie should be cleared
cookies := w.Result().Cookies()
found := false
for _, c := range cookies {
if c.Name == config.AdminSessionCookieName && c.MaxAge == -1 {
found = true
break
}
}
if !found {
t.Error("session cookie not cleared")
}
}
func TestHandleAdminSession_Authenticated(t *testing.T) {
deps, _, store := setupTestDeps(t)
handler := HandleAdminSession(deps)
cookie := adminCookie(t, store)
req := httptest.NewRequest("GET", "/api/admin/session", nil)
req.Header.Set("Cookie", cookie)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var resp AdminSessionResponse
json.NewDecoder(w.Body).Decode(&resp)
if !resp.Authenticated {
t.Error("Authenticated = false, want true")
}
}
func TestHandleAdminSession_Unauthenticated(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminSession(deps)
req := httptest.NewRequest("GET", "/api/admin/session", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", w.Code)
}
}
func TestHandleAdminOverview(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
// Add some test data
gormDB.Create(&db.Message{Room: "main", Username: "u1", Text: "hi", Timestamp: time.Now(), Type: "public"})
gormDB.Create(&db.ModerationLog{Action: "mute", Target: "u2", Moderator: "admin", Reason: "spam", Timestamp: time.Now()})
handler := HandleAdminOverview(deps)
req := httptest.NewRequest("GET", "/api/admin/overview", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var overview AdminOverview
json.NewDecoder(w.Body).Decode(&overview)
if overview.StoredMessages != 1 {
t.Errorf("StoredMessages = %d, want 1", overview.StoredMessages)
}
if overview.ModerationActions != 1 {
t.Errorf("ModerationActions = %d, want 1", overview.ModerationActions)
}
}
func TestHandleAdminPlaylist_Get(t *testing.T) {
deps, _, _ := setupTestDeps(t)
// Create temp playlist
tmpDir := t.TempDir()
playlistPath := filepath.Join(tmpDir, "playlist.txt")
os.WriteFile(playlistPath, []byte("file /videos/test.mp4\n"), 0644)
os.Setenv("PLAYLIST_PATH", playlistPath)
defer os.Unsetenv("PLAYLIST_PATH")
handler := HandleAdminPlaylist(deps)
req := httptest.NewRequest("GET", "/api/admin/playlist", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var payload PlaylistPayload
json.NewDecoder(w.Body).Decode(&payload)
if !strings.Contains(payload.Content, "test.mp4") {
t.Errorf("Content = %q, want test.mp4", payload.Content)
}
}
func TestHandleAdminPlaylist_Put(t *testing.T) {
deps, _, _ := setupTestDeps(t)
tmpDir := t.TempDir()
playlistPath := filepath.Join(tmpDir, "playlist.txt")
os.Setenv("PLAYLIST_PATH", playlistPath)
defer os.Unsetenv("PLAYLIST_PATH")
handler := HandleAdminPlaylist(deps)
body := `{"content":"file /videos/new.mp4"}`
req := httptest.NewRequest("PUT", "/api/admin/playlist", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
// Verify file written
data, _ := os.ReadFile(playlistPath)
if !strings.Contains(string(data), "new.mp4") {
t.Errorf("file content = %q, want new.mp4", string(data))
}
}
func TestHandleAdminModerationLogs(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.ModerationLog{Action: "mute", Target: "u1", Moderator: "admin", Reason: "spam", Timestamp: time.Now()})
handler := HandleAdminModerationLogs(deps)
req := httptest.NewRequest("GET", "/api/admin/moderation/logs", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var resp ModerationLogsResponse
json.NewDecoder(w.Body).Decode(&resp)
if len(resp.Logs) != 1 {
t.Errorf("len(Logs) = %d, want 1", len(resp.Logs))
}
}
func TestHandleAdminModerationAction(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
handler := HandleAdminModerationAction(deps)
body := `{"action":"mute","target":"baduser","moderator":"admin","reason":"spam","room":"main"}`
req := httptest.NewRequest("POST", "/api/admin/moderation/actions", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var count int64
gormDB.Model(&db.ModerationLog{}).Count(&count)
if count != 1 {
t.Errorf("moderation log count = %d, want 1", count)
}
}
func TestHandleAdminModerationAction_MissingFields(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminModerationAction(deps)
body := `{"action":"mute"}`
req := httptest.NewRequest("POST", "/api/admin/moderation/actions", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400", w.Code)
}
}
func TestHandleAdminAnalytics(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.Message{Room: "main", Username: "u1", Text: "hi", Timestamp: time.Now(), Type: "public"})
gormDB.Create(&db.Message{Room: "main", Username: "u2", Text: "hey", Timestamp: time.Now(), Type: "public"})
handler := HandleAdminAnalytics(deps)
req := httptest.NewRequest("GET", "/api/admin/analytics", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var analytics AdminAnalytics
json.NewDecoder(w.Body).Decode(&analytics)
if analytics.TotalMessages != 2 {
t.Errorf("TotalMessages = %d, want 2", analytics.TotalMessages)
}
}
func TestHandleAdminSystemSummary(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminSystemSummary(deps)
req := httptest.NewRequest("GET", "/api/admin/system", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var summary AdminSystemSummary
json.NewDecoder(w.Body).Decode(&summary)
if summary.DatabaseDriver != "sqlite" {
t.Errorf("DatabaseDriver = %q, want sqlite", summary.DatabaseDriver)
}
}
func TestHandleAdminConfig_Get(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminConfig(deps)
req := httptest.NewRequest("GET", "/api/admin/config", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}
func TestHandleAdminConfig_Put(t *testing.T) {
deps, _, _ := setupTestDeps(t)
setupConfigTest(t)
handler := HandleAdminConfig(deps)
body := `{"rateLimitMax":20}`
req := httptest.NewRequest("PUT", "/api/admin/config", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}
// setupConfigTest points the runtime config at a fresh temp file and resets the store.
func setupConfigTest(t *testing.T) {
t.Helper()
os.Setenv("CONFIG_PATH", filepath.Join(t.TempDir(), "config.json"))
os.Unsetenv("MATOMO_URL")
os.Unsetenv("MATOMO_SITE_ID")
os.Unsetenv("HLS_SEGMENT_DURATION")
os.Unsetenv("HLS_WINDOW_SIZE")
if err := config.LoadRuntimeConfig(); err != nil {
t.Fatalf("LoadRuntimeConfig: %v", err)
}
t.Cleanup(func() { os.Unsetenv("CONFIG_PATH") })
}
func TestHandleAdminConfig_Get_NewFields(t *testing.T) {
deps, _, _ := setupTestDeps(t)
setupConfigTest(t)
handler := HandleAdminConfig(deps)
req := httptest.NewRequest("GET", "/api/admin/config", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
var cfg map[string]any
if err := json.NewDecoder(w.Body).Decode(&cfg); err != nil {
t.Fatalf("decode: %v", err)
}
for _, k := range []string{"matomoUrl", "matomoSiteId", "hlsSegmentDuration", "hlsWindowSize"} {
if _, ok := cfg[k]; !ok {
t.Errorf("response missing %q", k)
}
}
}
func TestHandleAdminConfig_Put_Persists(t *testing.T) {
deps, _, _ := setupTestDeps(t)
setupConfigTest(t)
handler := HandleAdminConfig(deps)
body := `{"hlsSegmentDuration":5,"hlsWindowSize":30,"matomoUrl":"https://stats.example.com","matomoSiteId":"42"}`
req := httptest.NewRequest("PUT", "/api/admin/config", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
var cfg map[string]any
if err := json.NewDecoder(w.Body).Decode(&cfg); err != nil {
t.Fatalf("decode: %v", err)
}
if cfg["hlsSegmentDuration"] != float64(5) {
t.Errorf("hlsSegmentDuration = %v, want 5", cfg["hlsSegmentDuration"])
}
if cfg["hlsWindowSize"] != float64(30) {
t.Errorf("hlsWindowSize = %v, want 30", cfg["hlsWindowSize"])
}
if cfg["matomoUrl"] != "https://stats.example.com" {
t.Errorf("matomoUrl = %v", cfg["matomoUrl"])
}
if cfg["matomoSiteId"] != "42" {
t.Errorf("matomoSiteId = %v", cfg["matomoSiteId"])
}
}
func TestHandleAdminConfig_Put_Invalid(t *testing.T) {
deps, _, _ := setupTestDeps(t)
setupConfigTest(t)
handler := HandleAdminConfig(deps)
body := `{"hlsSegmentDuration":99}`
req := httptest.NewRequest("PUT", "/api/admin/config", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400", w.Code)
}
}
func TestHandlePublicMatomo(t *testing.T) {
setupConfigTest(t)
handler := HandlePublicMatomo()
req := httptest.NewRequest("GET", "/api/matomo", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
var resp map[string]any
if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
t.Fatalf("decode: %v", err)
}
for _, k := range []string{"matomoUrl", "matomoSiteId"} {
if _, ok := resp[k]; !ok {
t.Errorf("response missing %q", k)
}
}
}
func TestHandleUserRegister_Success(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
handler := HandleUserRegister(deps)
body := `{"username":"alice","password":"secret123"}`
req := httptest.NewRequest("POST", "/api/auth/register", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (got %s)", w.Code, w.Body.String())
}
var count int64
gormDB.Model(&db.User{}).Where("username = ?", "alice").Count(&count)
if count != 1 {
t.Errorf("user count = %d, want 1", count)
}
if len(w.Result().Cookies()) == 0 {
t.Error("expected session cookie to be set")
}
}
func TestHandleUserRegister_Duplicate(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.User{Username: "alice", PasswordHash: "x"})
handler := HandleUserRegister(deps)
body := `{"username":"alice","password":"secret123"}`
req := httptest.NewRequest("POST", "/api/auth/register", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusConflict {
t.Errorf("status = %d, want 409", w.Code)
}
}
func TestHandleUserLogin_Success(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
hash, _ := bcrypt.GenerateFromPassword([]byte("secret123"), bcrypt.MinCost)
gormDB.Create(&db.User{Username: "bob", PasswordHash: string(hash)})
handler := HandleUserLogin(deps)
body := `{"username":"bob","password":"secret123"}`
req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (got %s)", w.Code, w.Body.String())
}
}
func TestHandleUserLogin_WrongPassword(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
hash, _ := bcrypt.GenerateFromPassword([]byte("secret123"), bcrypt.MinCost)
gormDB.Create(&db.User{Username: "bob", PasswordHash: string(hash)})
handler := HandleUserLogin(deps)
body := `{"username":"bob","password":"wrong"}`
req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", w.Code)
}
}
func TestHandleUserSession(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleUserSession(deps)
// Unauthenticated
req := httptest.NewRequest("GET", "/api/auth/session", nil)
w := httptest.NewRecorder()
handler(w, req)
var resp map[string]any
json.NewDecoder(w.Body).Decode(&resp)
if resp["authenticated"] != false {
t.Errorf("authenticated = %v, want false", resp["authenticated"])
}
// Authenticated
token, _ := auth.GenerateToken()
deps.UserSessions.Add(token, "carol", time.Now().Add(1*time.Hour))
req2 := httptest.NewRequest("GET", "/api/auth/session", nil)
req2.AddCookie(&http.Cookie{Name: "linearvoid_user_session", Value: token})
w2 := httptest.NewRecorder()
handler(w2, req2)
var resp2 map[string]any
json.NewDecoder(w2.Body).Decode(&resp2)
if resp2["username"] != "carol" {
t.Errorf("username = %v, want carol", resp2["username"])
}
}
func TestHandleUserDMHistory(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
token, _ := auth.GenerateToken()
deps.UserSessions.Add(token, "alice", time.Now().Add(1*time.Hour))
now := time.Now()
gormDB.Create(&db.Message{Room: "dm:alice-bob", Username: "alice", Text: "hi bob", Type: "private", Timestamp: now.Add(-2 * time.Hour)})
gormDB.Create(&db.Message{Room: "dm:alice-bob", Username: "bob", Text: "hi alice", Type: "private", Timestamp: now.Add(-1 * time.Hour)})
handler := HandleUserDMHistory(deps)
req := httptest.NewRequest("GET", "/api/dm/history?with=bob", nil)
req.AddCookie(&http.Cookie{Name: "linearvoid_user_session", Value: token})
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
var msgs []db.Message
json.NewDecoder(w.Body).Decode(&msgs)
if len(msgs) != 2 {
t.Fatalf("len = %d, want 2", len(msgs))
}
if msgs[0].Text != "hi bob" {
t.Errorf("first message = %q, want hi bob (chronological)", msgs[0].Text)
}
}
func TestHandleUserDMHistory_Unauthorized(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleUserDMHistory(deps)
req := httptest.NewRequest("GET", "/api/dm/history?with=bob", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusUnauthorized {
t.Errorf("status = %d, want 401", w.Code)
}
}
func TestHandleUserDMSearch(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
token, _ := auth.GenerateToken()
deps.UserSessions.Add(token, "alice", time.Now().Add(1*time.Hour))
gormDB.Create(&db.Message{Room: "dm:alice-bob", Username: "alice", Text: "meet at 8", Type: "private"})
gormDB.Create(&db.Message{Room: "dm:alice-bob", Username: "bob", Text: "see you", Type: "private"})
handler := HandleUserDMSearch(deps)
req := httptest.NewRequest("GET", "/api/dm/search?with=bob&q=meet", nil)
req.AddCookie(&http.Cookie{Name: "linearvoid_user_session", Value: token})
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", w.Code)
}
var msgs []db.Message
json.NewDecoder(w.Body).Decode(&msgs)
if len(msgs) != 1 || msgs[0].Text != "meet at 8" {
t.Fatalf("search results = %v, want [meet at 8]", msgs)
}
}
func TestHandleAdminRestart(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminRestart(deps)
req := httptest.NewRequest("POST", "/api/admin/restart?service=chat", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}
func TestHandleAdminUsers_Get(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminUsers(deps)
req := httptest.NewRequest("GET", "/api/admin/users", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}
func TestHandleAdminUsers_Post(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminUsers(deps)
body := `{"action":"mute","username":"baduser","duration":10}`
req := httptest.NewRequest("POST", "/api/admin/users", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}
func TestHandleAdminSchedule(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
tmpDir := t.TempDir()
playlistPath := filepath.Join(tmpDir, "playlist.txt")
os.WriteFile(playlistPath, []byte("file /videos/test.mp4\n"), 0644)
os.Setenv("PLAYLIST_PATH", playlistPath)
defer os.Unsetenv("PLAYLIST_PATH")
gormDB.Create(&db.Media{
Filename: "test.mp4",
OriginalName: "test.mp4",
Path: "/videos/test.mp4",
SizeBytes: 1024,
DurationSeconds: 60,
Status: "ready",
Title: "Test Video",
})
handler := HandleAdminSchedule(deps)
req := httptest.NewRequest("GET", "/api/admin/schedule", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var resp AdminScheduleResponse
json.NewDecoder(w.Body).Decode(&resp)
if resp.MatchedEntries != 1 {
t.Errorf("MatchedEntries = %d, want 1", resp.MatchedEntries)
}
}
func TestHandleAdminScheduleOverrides_CRUD(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
// Create
handler := HandleAdminScheduleOverrides(deps)
now := time.Now()
body, _ := json.Marshal(db.ScheduleOverride{
MediaID: 1,
StartTime: now,
EndTime: now.Add(1 * time.Hour),
Reason: "test",
})
req := httptest.NewRequest("POST", "/api/admin/schedule/overrides", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusCreated {
t.Errorf("POST status = %d, want 201", w.Code)
}
// List
req2 := httptest.NewRequest("GET", "/api/admin/schedule/overrides", nil)
w2 := httptest.NewRecorder()
handler(w2, req2)
if w2.Code != http.StatusOK {
t.Errorf("GET status = %d, want 200", w2.Code)
}
// Delete
var overrides []db.ScheduleOverride
gormDB.Find(&overrides)
if len(overrides) > 0 {
req3 := httptest.NewRequest("DELETE", "/api/admin/schedule/overrides?id=1", nil)
w3 := httptest.NewRecorder()
handler(w3, req3)
if w3.Code != http.StatusNoContent {
t.Errorf("DELETE status = %d, want 204", w3.Code)
}
}
}
func TestHandleAdminChatLog(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.Message{Room: "main", Username: "u1", Text: "hello", Timestamp: time.Now(), Type: "public"})
handler := HandleAdminChatLog(deps)
req := httptest.NewRequest("GET", "/api/admin/chat-log", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var resp ChatLogListResponse
json.NewDecoder(w.Body).Decode(&resp)
if resp.Total != 1 {
t.Errorf("Total = %d, want 1", resp.Total)
}
}
func TestHandleAdminChatLog_FilterByRoom(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.Message{Room: "main", Username: "u1", Text: "hello", Timestamp: time.Now(), Type: "public"})
gormDB.Create(&db.Message{Room: "lobby", Username: "u2", Text: "hey", Timestamp: time.Now(), Type: "public"})
handler := HandleAdminChatLog(deps)
req := httptest.NewRequest("GET", "/api/admin/chat-log?room=main", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var resp ChatLogListResponse
json.NewDecoder(w.Body).Decode(&resp)
if resp.Total != 1 {
t.Errorf("Total = %d, want 1", resp.Total)
}
}
func TestHandleAdminChatLog_ExcludesSystem(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.Message{Room: "main", Username: "system", Text: "bob joined main", Timestamp: time.Now(), Type: "system"})
gormDB.Create(&db.Message{Room: "main", Username: "u1", Text: "hello", Timestamp: time.Now(), Type: "public"})
handler := HandleAdminChatLog(deps)
req := httptest.NewRequest("GET", "/api/admin/chat-log", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var resp ChatLogListResponse
json.NewDecoder(w.Body).Decode(&resp)
if resp.Total != 1 {
t.Errorf("Total = %d, want 1 (system messages must be excluded)", resp.Total)
}
if len(resp.Entries) != 1 || resp.Entries[0].Text != "hello" {
t.Errorf("entries = %v, want only the public chat message", resp.Entries)
}
}
func TestHandleAdminChatLogByID_Get(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
msg := db.Message{Room: "main", Username: "u1", Text: "hello", Timestamp: time.Now(), Type: "public"}
gormDB.Create(&msg)
handler := HandleAdminChatLogByID(deps)
req := httptest.NewRequest("GET", "/api/admin/chat-log/1", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}
func TestHandleAdminChatLogByID_Delete(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
msg := db.Message{Room: "main", Username: "u1", Text: "hello", Timestamp: time.Now(), Type: "public"}
gormDB.Create(&msg)
handler := HandleAdminChatLogByID(deps)
req := httptest.NewRequest("DELETE", "/api/admin/chat-log/1", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusNoContent {
t.Errorf("status = %d, want 204", w.Code)
}
var count int64
gormDB.Model(&db.Message{}).Count(&count)
if count != 0 {
t.Errorf("message count after delete = %d, want 0", count)
}
}
func TestHandleAdminChatLogBulk(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.Message{Room: "main", Username: "u1", Text: "m1", Timestamp: time.Now(), Type: "public"})
gormDB.Create(&db.Message{Room: "main", Username: "u2", Text: "m2", Timestamp: time.Now(), Type: "public"})
handler := HandleAdminChatLogBulk(deps)
body := `{"ids":[1,2]}`
req := httptest.NewRequest("DELETE", "/api/admin/chat-log/bulk", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var count int64
gormDB.Model(&db.Message{}).Count(&count)
if count != 0 {
t.Errorf("message count after bulk delete = %d, want 0", count)
}
}
func TestHandleAdminChatLogExport(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.Message{Room: "main", Username: "u1", Text: "hello", Timestamp: time.Now(), Type: "public"})
handler := HandleAdminChatLogExport(deps)
req := httptest.NewRequest("GET", "/api/admin/chat-log/export", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
contentType := w.Header().Get("Content-Type")
if !strings.Contains(contentType, "text/csv") {
t.Errorf("Content-Type = %q, want text/csv", contentType)
}
body := w.Body.String()
if !strings.Contains(body, "hello") {
t.Errorf("CSV body missing 'hello': %s", body)
}
}
func TestHandlePublicSchedule(t *testing.T) {
deps, _, _ := setupTestDeps(t)
tmpDir := t.TempDir()
playlistPath := filepath.Join(tmpDir, "playlist.txt")
os.WriteFile(playlistPath, []byte("file /videos/test.mp4\n"), 0644)
os.Setenv("PLAYLIST_PATH", playlistPath)
defer os.Unsetenv("PLAYLIST_PATH")
handler := HandlePublicSchedule(deps)
req := httptest.NewRequest("GET", "/api/schedule", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}
func TestHandleAdminMedia_Get(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.Media{
Filename: "test.mp4",
OriginalName: "test.mp4",
Path: "/media/test.mp4",
SizeBytes: 1024,
DurationSeconds: 60,
Status: "ready",
Title: "Test",
})
handler := HandleAdminMedia(deps)
req := httptest.NewRequest("GET", "/api/admin/media", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var resp AdminMediaResponse
json.NewDecoder(w.Body).Decode(&resp)
if len(resp.Files) != 1 {
t.Errorf("len(Files) = %d, want 1", len(resp.Files))
}
}
func TestHandleAdminMediaByID_Get(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.Media{
Filename: "test.mp4",
OriginalName: "test.mp4",
Path: "/media/test.mp4",
SizeBytes: 1024,
DurationSeconds: 60,
Status: "ready",
Title: "Test",
})
handler := HandleAdminMediaByID(deps)
req := httptest.NewRequest("GET", "/api/admin/media/1", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
}
func TestHandleAdminMediaByID_NotFound(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminMediaByID(deps)
req := httptest.NewRequest("GET", "/api/admin/media/999", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusNotFound {
t.Errorf("status = %d, want 404", w.Code)
}
}
func TestHandleAdminMediaByID_Put(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
gormDB.Create(&db.Media{
Filename: "test.mp4",
OriginalName: "test.mp4",
Path: "/media/test.mp4",
SizeBytes: 1024,
DurationSeconds: 60,
Status: "ready",
Title: "Old Title",
})
handler := HandleAdminMediaByID(deps)
body := `{"title":"New Title","status":"needs_normalization","tags":"tag1"}`
req := httptest.NewRequest("PUT", "/api/admin/media/1", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var updated db.Media
gormDB.First(&updated, 1)
if updated.Title != "New Title" {
t.Errorf("Title = %q, want New Title", updated.Title)
}
}
func TestHandleAdminMediaByID_Delete(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
// Create a real temp file for the media record
tmpDir := t.TempDir()
os.Setenv("MEDIA_DIR", tmpDir)
defer os.Unsetenv("MEDIA_DIR")
mediaPath := filepath.Join(tmpDir, "test.mp4")
os.WriteFile(mediaPath, []byte("fake video"), 0644)
gormDB.Create(&db.Media{
Filename: "test.mp4",
OriginalName: "test.mp4",
Path: mediaPath,
SizeBytes: 10,
DurationSeconds: 1,
Status: "ready",
Title: "Test",
})
handler := HandleAdminMediaByID(deps)
req := httptest.NewRequest("DELETE", "/api/admin/media/1", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var count int64
gormDB.Model(&db.Media{}).Count(&count)
if count != 0 {
t.Errorf("media count after delete = %d, want 0", count)
}
}
func TestHandleAdminMediaUploads_Init(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminMediaUploads(deps)
body := `{"fileName":"video.mp4","fileSize":1024,"mimeType":"video/mp4","chunkSize":524288,"totalChunks":1}`
req := httptest.NewRequest("POST", "/api/admin/media/uploads", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("status = %d, want 200", w.Code)
}
var status AdminMediaUploadStatusResponse
json.NewDecoder(w.Body).Decode(&status)
if status.FileName != "video.mp4" {
t.Errorf("FileName = %q, want video.mp4", status.FileName)
}
if status.UploadID == "" {
t.Error("UploadID is empty")
}
}
func TestHandleAdminMediaUploads_InvalidFile(t *testing.T) {
deps, _, _ := setupTestDeps(t)
handler := HandleAdminMediaUploads(deps)
body := `{"fileName":"bad.exe","fileSize":1024,"mimeType":"application/x-msdownload","chunkSize":524288,"totalChunks":1}`
req := httptest.NewRequest("POST", "/api/admin/media/uploads", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusBadRequest {
t.Errorf("status = %d, want 400", w.Code)
}
}
func TestNormalizeMediaRecord_Success(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
tmpDir := t.TempDir()
os.Setenv("MEDIA_DIR", tmpDir)
defer os.Unsetenv("MEDIA_DIR")
srcPath := filepath.Join(tmpDir, "source.mov")
if err := os.WriteFile(srcPath, []byte("fake video"), 0o644); err != nil {
t.Fatal(err)
}
gormDB.Create(&db.Media{
Filename: "source.mov",
OriginalName: "source.mov",
Path: srcPath,
SizeBytes: 10,
DurationSeconds: 0,
Status: "needs_normalization",
Title: "source",
})
origNormalize := media.NormalizeVideo
t.Cleanup(func() { media.NormalizeVideo = origNormalize })
media.NormalizeVideo = func(src, dst string) (int, int64, error) {
if err := os.WriteFile(dst, []byte("normalized"), 0o644); err != nil {
return 0, 0, err
}
return 120, 10, nil
}
var record db.Media
gormDB.First(&record, 1)
normalizeMediaRecord(deps, record)
var updated db.Media
gormDB.First(&updated, 1)
if updated.Status != "ready" {
t.Errorf("Status = %q, want ready", updated.Status)
}
if updated.DurationSeconds != 120 {
t.Errorf("DurationSeconds = %d, want 120", updated.DurationSeconds)
}
if !strings.HasSuffix(updated.Path, ".normalized.mp4") {
t.Errorf("Path = %q, want .normalized.mp4 suffix", updated.Path)
}
}
func TestNormalizeMediaRecord_Failure(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
tmpDir := t.TempDir()
os.Setenv("MEDIA_DIR", tmpDir)
defer os.Unsetenv("MEDIA_DIR")
srcPath := filepath.Join(tmpDir, "source.mov")
if err := os.WriteFile(srcPath, []byte("fake video"), 0o644); err != nil {
t.Fatal(err)
}
gormDB.Create(&db.Media{
Filename: "source.mov",
OriginalName: "source.mov",
Path: srcPath,
SizeBytes: 10,
DurationSeconds: 0,
Status: "needs_normalization",
Title: "source",
})
origNormalize := media.NormalizeVideo
t.Cleanup(func() { media.NormalizeVideo = origNormalize })
media.NormalizeVideo = func(src, dst string) (int, int64, error) {
return 0, 0, fmt.Errorf("ffmpeg failed")
}
var record db.Media
gormDB.First(&record, 1)
normalizeMediaRecord(deps, record)
var updated db.Media
gormDB.First(&updated, 1)
if updated.Status != "normalization_failed" {
t.Errorf("Status = %q, want normalization_failed", updated.Status)
}
}
func TestHandleAdminMediaByID_Normalize(t *testing.T) {
deps, gormDB, _ := setupTestDeps(t)
tmpDir := t.TempDir()
os.Setenv("MEDIA_DIR", tmpDir)
defer os.Unsetenv("MEDIA_DIR")
srcPath := filepath.Join(tmpDir, "source.mov")
if err := os.WriteFile(srcPath, []byte("fake video"), 0o644); err != nil {
t.Fatal(err)
}
gormDB.Create(&db.Media{
Filename: "source.mov",
OriginalName: "source.mov",
Path: srcPath,
SizeBytes: 10,
DurationSeconds: 0,
Status: "needs_normalization",
Title: "source",
})
origNormalize := media.NormalizeVideo
t.Cleanup(func() { media.NormalizeVideo = origNormalize })
media.NormalizeVideo = func(src, dst string) (int, int64, error) {
if err := os.WriteFile(dst, []byte("normalized"), 0o644); err != nil {
return 0, 0, err
}
return 90, 9, nil
}
handler := HandleAdminMediaByID(deps)
req := httptest.NewRequest("POST", "/api/admin/media/1/normalize", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusAccepted {
t.Errorf("status = %d, want 202", w.Code)
}
// Wait for the asynchronous normalization goroutine to finish before
// t.Cleanup restores media.NormalizeVideo, avoiding a data race on the
// package-level mock variable.
var updated db.Media
deadline := time.Now().Add(5 * time.Second)
for {
gormDB.First(&updated, 1)
if updated.Status != media.StatusNormalizing {
break
}
if time.Now().After(deadline) {
t.Fatal("normalization did not complete within 5s")
}
time.Sleep(10 * time.Millisecond)
}
if updated.Status != media.StatusReady {
t.Errorf("Status = %q, want ready", updated.Status)
}
if updated.DurationSeconds != 90 {
t.Errorf("DurationSeconds = %d, want 90", updated.DurationSeconds)
}
if !strings.HasSuffix(updated.Path, ".normalized.mp4") {
t.Errorf("Path = %q, want .normalized.mp4 suffix", updated.Path)
}
}