Fix test setup and middleware chain - Handler tests now passing

- Fix TestRequireRoleMiddleware by chaining RequireAuth before RequireRole (role context requirement)
- Remove unused 'strings' import from testdb.go
- Create crussell_test database in Docker setup
- Tests now properly initialize authentication context for role-based tests

Result: handlers test suite passes (13/13 tests)
Remaining failures in admin/auth/bookings/portfolio/scheduling/services/user packages need further investigation (environment setup, database constraints, endpoint initialization)
This commit is contained in:
2026-02-21 23:50:17 +00:00
parent e858c782a4
commit 44cac94f64
20 changed files with 6725 additions and 7 deletions
+362
View File
@@ -0,0 +1,362 @@
//go:build test
// +build test
package admin
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"crussell/db"
"crussell/handlers/notifications"
"crussell/handlers/today"
"crussell/mw"
)
func TestAdminToday_CurrentNext(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', 'hash', 'verified_email', 'standard')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create service
var serviceID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
RETURNING id
`).Scan(&serviceID)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
// Create booking for today (in_progress)
_, err = db.DB.Exec(context.Background(), `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, NOW(), 'in_progress', NOW())
`, userID)
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
// Get the booking ID
var bookingID string
err = db.DB.QueryRow(context.Background(), `
SELECT id FROM bookings WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1
`, userID).Scan(&bookingID)
if err != nil {
t.Fatalf("failed to get booking ID: %v", err)
}
// Add service to booking
_, err = db.DB.Exec(context.Background(), `
INSERT INTO booking_services (booking_id, service_id)
VALUES ($1, $2)
`, bookingID, serviceID)
if err != nil {
t.Fatalf("failed to add service to booking: %v", err)
}
handler := http.HandlerFunc(today.GetCurrentAndNextHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/current-next", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
var response today.CurrentNextResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if response.Current == nil {
t.Errorf("expected current appointment, got nil")
}
if response.Current != nil && response.Current.ID != bookingID {
t.Errorf("expected booking ID %s, got %s", bookingID, response.Current.ID)
}
}
func TestAdminToday_Appointments(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', 'hash', 'verified_email', 'standard')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create service
var serviceID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
RETURNING id
`).Scan(&serviceID)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
// Create booking for today
_, err = db.DB.Exec(context.Background(), `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, NOW(), 'confirmed', NOW())
`, userID)
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
// Get the booking ID
var bookingID string
err = db.DB.QueryRow(context.Background(), `
SELECT id FROM bookings WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1
`, userID).Scan(&bookingID)
if err != nil {
t.Fatalf("failed to get booking ID: %v", err)
}
// Add service to booking
_, err = db.DB.Exec(context.Background(), `
INSERT INTO booking_services (booking_id, service_id)
VALUES ($1, $2)
`, bookingID, serviceID)
if err != nil {
t.Fatalf("failed to add service to booking: %v", err)
}
handler := http.HandlerFunc(today.GetTodayAppointmentsHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/appointments", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
var response today.TodayAppointmentsResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if len(response.Appointments) != 1 {
t.Errorf("expected 1 appointment, got %d", len(response.Appointments))
}
if len(response.Appointments) > 0 && response.Appointments[0].ID != bookingID {
t.Errorf("expected booking ID %s, got %s", bookingID, response.Appointments[0].ID)
}
}
func TestAdminToday_PendingApprovals(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
INSERT INTO users (n_first_name, n_last_name, email, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'testuser@test.com', 'hash', 'verified_email', 'standard')
RETURNING id
`).Scan(&userID)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
// Create service
var serviceID string
err = db.DB.QueryRow(context.Background(), `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Basic manicure', 25.00, 30, true)
RETURNING id
`).Scan(&serviceID)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
// Create pending booking
_, err = db.DB.Exec(context.Background(), `
INSERT INTO bookings (user_id, start_time, status, created_at)
VALUES ($1, NOW() + INTERVAL '1 day', 'pending', NOW())
`, userID)
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
// Get the booking ID
var bookingID string
err = db.DB.QueryRow(context.Background(), `
SELECT id FROM bookings WHERE user_id = $1 ORDER BY created_at DESC LIMIT 1
`, userID).Scan(&bookingID)
if err != nil {
t.Fatalf("failed to get booking ID: %v", err)
}
// Add service to booking
_, err = db.DB.Exec(context.Background(), `
INSERT INTO booking_services (booking_id, service_id)
VALUES ($1, $2)
`, bookingID, serviceID)
if err != nil {
t.Fatalf("failed to add service to booking: %v", err)
}
handler := http.HandlerFunc(today.GetPendingApprovalsHandler)
w := makeAdminRequest(handler, "GET", "/api/admin/today/pending-approvals", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
var response today.PendingApprovalsResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if len(response.Approvals) != 1 {
t.Errorf("expected 1 pending approval, got %d", len(response.Approvals))
}
if len(response.Approvals) > 0 && response.Approvals[0].ID != bookingID {
t.Errorf("expected booking ID %s, got %s", bookingID, response.Approvals[0].ID)
}
}
func TestAdminNotifications_List(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create a notification
_, err := db.DB.Exec(context.Background(), `
INSERT INTO admin_notifications (reason, booking_id, user_id, created_at)
VALUES ('pending_booking', 1, 1, NOW())
`)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
handler := http.HandlerFunc(notifications.GetNotifications)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
var response notifications.AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &response); err != nil {
t.Fatalf("failed to unmarshal response: %v", err)
}
if response.Total != 1 {
t.Errorf("expected 1 notification, got %d", response.Total)
}
if len(response.Notifications) != 1 {
t.Errorf("expected 1 notification in list, got %d", len(response.Notifications))
}
if len(response.Notifications) > 0 && response.Notifications[0].Reason != "pending_booking" {
t.Errorf("expected reason 'pending_booking', got %s", response.Notifications[0].Reason)
}
}
func TestAdminNotifications_Acknowledge(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Create a notification
var notificationID int
err := db.DB.QueryRow(context.Background(), `
INSERT INTO admin_notifications (reason, booking_id, user_id, created_at)
VALUES ('pending_booking', 1, 1, NOW())
RETURNING id
`).Scan(&notificationID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
// Create request to acknowledge
req := httptest.NewRequest("POST", "/api/admin/notifications/"+strconv.Itoa(notificationID)+"/acknowledge", nil)
ctx := req.Context()
ctx = context.WithValue(ctx, mw.UserIDKey, "admin-test-001")
ctx = context.WithValue(ctx, mw.UserRoleKey, "admin")
req = req.WithContext(ctx)
w := httptest.NewRecorder()
handler := http.HandlerFunc(notifications.AcknowledgeNotification)
handler.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
}
// Verify it's acknowledged
var acknowledged bool
err = db.DB.QueryRow(context.Background(), `
SELECT acknowledged_at IS NOT NULL FROM admin_notifications WHERE id = $1
`, notificationID).Scan(&acknowledged)
if err != nil {
t.Fatalf("failed to check acknowledgment: %v", err)
}
if !acknowledged {
t.Errorf("expected notification to be acknowledged")
}
}
func TestAdminToday_NonAdmin(t *testing.T) {
cleanup := setupTestDB(t)
defer cleanup()
// Test current-next endpoint
currentNextHandler := mw.RequireAdmin(http.HandlerFunc(today.GetCurrentAndNextHandler))
w := makeUserRequest(currentNextHandler, "GET", "/api/admin/today/current-next", nil)
if w.Code != http.StatusForbidden {
t.Errorf("CurrentNext: expected status 403, got %d", w.Code)
}
// Test appointments endpoint
appointmentsHandler := mw.RequireAdmin(http.HandlerFunc(today.GetTodayAppointmentsHandler))
w = makeUserRequest(appointmentsHandler, "GET", "/api/admin/today/appointments", nil)
if w.Code != http.StatusForbidden {
t.Errorf("Appointments: expected status 403, got %d", w.Code)
}
// Test pending-approvals endpoint
pendingApprovalsHandler := mw.RequireAdmin(http.HandlerFunc(today.GetPendingApprovalsHandler))
w = makeUserRequest(pendingApprovalsHandler, "GET", "/api/admin/today/pending-approvals", nil)
if w.Code != http.StatusForbidden {
t.Errorf("PendingApprovals: expected status 403, got %d", w.Code)
}
// Test notifications list endpoint
notificationsHandler := mw.RequireAdmin(http.HandlerFunc(notifications.GetNotifications))
w = makeUserRequest(notificationsHandler, "GET", "/api/admin/notifications", nil)
if w.Code != http.StatusForbidden {
t.Errorf("Notifications List: expected status 403, got %d", w.Code)
}
// Test notifications acknowledge endpoint
ackHandler := mw.RequireAdmin(http.HandlerFunc(notifications.AcknowledgeNotification))
w = makeUserRequest(ackHandler, "POST", "/api/admin/notifications/1/acknowledge", nil)
if w.Code != http.StatusForbidden {
t.Errorf("Notifications Acknowledge: expected status 403, got %d", w.Code)
}
}