refactor(backend): update test files for PoolProxy and per-test transactions

Migrate all test files from SetupTestDB/db.DB pattern to per-test transactions:

- Replace SetupTestDB(t) with SetupTestTx(t) for context + transaction
- Replace db.DB.Query/QueryRow/Exec with tx.Query/QueryRow/Exec
- Replace context.Background() with context from SetupTestTx
- Replace defer rows.Close() pattern with explicit rows.Close()
- Add testdb.SeedBaseline(pool) to all TestMain functions
- Wire db.Conn = db.NewPoolProxy(pool) in all TestMain functions

Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent)

Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
2026-06-21 19:29:24 +01:00
co-authored by Sisyphus
parent 3d0e2afc4c
commit 220a0ef6e8
57 changed files with 5911 additions and 6235 deletions
@@ -18,10 +18,9 @@ import (
"crussell/mw"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
func makeExtendedAdminRequest(handler http.Handler, method, path string, body interface{}) *httptest.ResponseRecorder {
func makeExtendedAdminRequest(handler http.Handler, method, path string, body interface{}, ctx context.Context) *httptest.ResponseRecorder {
var req *http.Request
if body != nil {
bodyBytes, _ := json.Marshal(body)
@@ -35,7 +34,7 @@ func makeExtendedAdminRequest(handler http.Handler, method, path string, body in
if id, _ := extractIDFromPath(path); id != "" {
rctx.URLParams.Add("id", id)
}
ctx := context.WithValue(req.Context(), chi.RouteCtxKey, rctx)
ctx = context.WithValue(ctx, chi.RouteCtxKey, rctx)
ctx = context.WithValue(ctx, mw.UserIDKey, "admin001")
ctx = context.WithValue(ctx, mw.UserRoleKey, "admin")
req = req.WithContext(ctx)
@@ -45,10 +44,10 @@ func makeExtendedAdminRequest(handler http.Handler, method, path string, body in
return w
}
func createTestUser(t *testing.T) string {
func createTestUser(t *testing.T, ctx context.Context, q db.Querier) string {
t.Helper()
var userID string
err := db.DB.QueryRow(context.Background(), `
err := q.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+447700900000', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
@@ -59,7 +58,7 @@ func createTestUser(t *testing.T) string {
return userID
}
func createNotification(t *testing.T, reason, userID string, acknowledged bool) string {
func createNotification(t *testing.T, ctx context.Context, q db.Querier, reason, userID string, acknowledged bool) string {
t.Helper()
var notificationID string
if userID == "" {
@@ -67,7 +66,7 @@ func createNotification(t *testing.T, reason, userID string, acknowledged bool)
if acknowledged {
query = `INSERT INTO admin_notifications (reason, acknowledged_at) VALUES ($1, NOW()) RETURNING id`
}
err := db.DB.QueryRow(context.Background(), query, reason).Scan(&notificationID)
err := q.QueryRow(ctx, query, reason).Scan(&notificationID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
@@ -76,7 +75,7 @@ func createNotification(t *testing.T, reason, userID string, acknowledged bool)
if acknowledged {
query = `INSERT INTO admin_notifications (reason, user_id, acknowledged_at) VALUES ($1, $2, NOW()) RETURNING id`
}
err := db.DB.QueryRow(context.Background(), query, reason, userID).Scan(&notificationID)
err := q.QueryRow(ctx, query, reason, userID).Scan(&notificationID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
@@ -89,14 +88,15 @@ func createNotification(t *testing.T, reason, userID string, acknowledged bool)
// =============================================================================
func TestNotifications_IncludeAcknowledged_Default(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "pending_booking", userID, false)
createNotification(t, "cancelled_booking", userID, true)
createNotification(t, ctx, tx, "pending_booking", userID, false)
createNotification(t, ctx, tx, "cancelled_booking", userID, true)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -109,14 +109,15 @@ func TestNotifications_IncludeAcknowledged_Default(t *testing.T) {
}
func TestNotifications_IncludeAcknowledged_True(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "pending_booking", userID, false)
createNotification(t, "cancelled_booking", userID, true)
createNotification(t, ctx, tx, "pending_booking", userID, false)
createNotification(t, ctx, tx, "cancelled_booking", userID, true)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications?include_acknowledged=true", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications?include_acknowledged=true", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -129,13 +130,14 @@ func TestNotifications_IncludeAcknowledged_True(t *testing.T) {
}
func TestNotifications_IncludeAcknowledged_ResponseHasAcknowledgedAt(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "pending_booking", userID, true)
createNotification(t, ctx, tx, "pending_booking", userID, true)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications?include_acknowledged=true", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications?include_acknowledged=true", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -156,8 +158,9 @@ func TestNotifications_IncludeAcknowledged_ResponseHasAcknowledgedAt(t *testing.
// =============================================================================
func TestNotifications_PriorityOrdering(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
// Create notifications in reverse priority order
reasons := []string{
@@ -167,11 +170,11 @@ func TestNotifications_PriorityOrdering(t *testing.T) {
"cancelled_booking",
}
for _, reason := range reasons {
createNotification(t, reason, userID, false)
createNotification(t, ctx, tx, reason, userID, false)
}
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -192,16 +195,17 @@ func TestNotifications_PriorityOrdering(t *testing.T) {
}
func TestNotifications_PriorityOrdering_OldestFirstWithinPriority(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
// Create two pending_booking notifications with a time gap
createNotification(t, "pending_booking", userID, false)
createNotification(t, ctx, tx, "pending_booking", userID, false)
time.Sleep(10 * time.Millisecond)
createNotification(t, "pending_booking", userID, false)
createNotification(t, ctx, tx, "pending_booking", userID, false)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -219,15 +223,16 @@ func TestNotifications_PriorityOrdering_OldestFirstWithinPriority(t *testing.T)
}
func TestNotifications_AllNotifications_NewestFirst(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "pending_booking", userID, false)
createNotification(t, ctx, tx, "pending_booking", userID, false)
time.Sleep(10 * time.Millisecond)
createNotification(t, "cancelled_booking", userID, true)
createNotification(t, ctx, tx, "cancelled_booking", userID, true)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications?include_acknowledged=true", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications?include_acknowledged=true", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -249,15 +254,16 @@ func TestNotifications_AllNotifications_NewestFirst(t *testing.T) {
// =============================================================================
func TestNotifications_UnreadCount(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "pending_booking", userID, false)
createNotification(t, "cancelled_booking", userID, false)
createNotification(t, "affiliate_claim", userID, true)
createNotification(t, ctx, tx, "pending_booking", userID, false)
createNotification(t, ctx, tx, "cancelled_booking", userID, false)
createNotification(t, ctx, tx, "affiliate_claim", userID, true)
handler := http.HandlerFunc(GetUnreadCount)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications/unread-count", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications/unread-count", nil, ctx)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
@@ -274,13 +280,14 @@ func TestNotifications_UnreadCount(t *testing.T) {
}
func TestNotifications_UnreadCount_Zero(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "pending_booking", userID, true)
createNotification(t, ctx, tx, "pending_booking", userID, true)
handler := http.HandlerFunc(GetUnreadCount)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications/unread-count", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications/unread-count", nil, ctx)
var resp map[string]int
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -293,10 +300,11 @@ func TestNotifications_UnreadCount_Zero(t *testing.T) {
}
func TestNotifications_UnreadCount_Empty(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, _ := testutils.SetupTestTx(t)
handler := http.HandlerFunc(GetUnreadCount)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications/unread-count", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications/unread-count", nil, ctx)
var resp map[string]int
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -313,13 +321,14 @@ func TestNotifications_UnreadCount_Empty(t *testing.T) {
// =============================================================================
func TestNotifications_NewBookingReason(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "new_booking", userID, false)
createNotification(t, ctx, tx, "new_booking", userID, false)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -336,13 +345,14 @@ func TestNotifications_NewBookingReason(t *testing.T) {
}
func TestNotifications_EditRequestedReason(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "edit_requested", userID, false)
createNotification(t, ctx, tx, "edit_requested", userID, false)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -359,14 +369,15 @@ func TestNotifications_EditRequestedReason(t *testing.T) {
}
func TestNotifications_Priority_NewBookingBelowPendingBooking(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "new_booking", userID, false)
createNotification(t, "pending_booking", userID, false)
createNotification(t, ctx, tx, "new_booking", userID, false)
createNotification(t, ctx, tx, "pending_booking", userID, false)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -387,15 +398,16 @@ func TestNotifications_Priority_NewBookingBelowPendingBooking(t *testing.T) {
// =============================================================================
func TestNotifications_IncludeAcknowledgedWithReasonFilter(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
createNotification(t, "pending_booking", userID, false)
createNotification(t, "pending_booking", userID, true)
createNotification(t, "cancelled_booking", userID, false)
createNotification(t, ctx, tx, "pending_booking", userID, false)
createNotification(t, ctx, tx, "pending_booking", userID, true)
createNotification(t, ctx, tx, "cancelled_booking", userID, false)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications?include_acknowledged=true&reason=pending_booking", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications?include_acknowledged=true&reason=pending_booking", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -412,11 +424,12 @@ func TestNotifications_IncludeAcknowledgedWithReasonFilter(t *testing.T) {
// =============================================================================
func TestNotifications_ResponseEnriched_WithUserAndBooking(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
// Create a service
var serviceID string
err := db.DB.QueryRow(context.Background(), `
err := tx.QueryRow(ctx, `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Test service', 25.00, 30, true)
RETURNING id
@@ -427,7 +440,7 @@ func TestNotifications_ResponseEnriched_WithUserAndBooking(t *testing.T) {
// Create a user
var userID string
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Alice', 'Smith', 'alice@test.com', '+447700900001', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
@@ -438,7 +451,7 @@ func TestNotifications_ResponseEnriched_WithUserAndBooking(t *testing.T) {
// Create a booking
var bookingID string
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
INSERT INTO bookings (user_id, start_time, status)
VALUES ($1, NOW() + INTERVAL '3 days', 'pending')
RETURNING id
@@ -448,10 +461,10 @@ func TestNotifications_ResponseEnriched_WithUserAndBooking(t *testing.T) {
}
// Create notification with both user_id and booking_id
createNotificationWithBooking(t, "pending_booking", userID, bookingID, false)
createNotificationWithBooking(t, ctx, tx, "pending_booking", userID, bookingID, false)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -472,13 +485,14 @@ func TestNotifications_ResponseEnriched_WithUserAndBooking(t *testing.T) {
}
func TestNotifications_ResponseEnriched_NoUserOrBooking(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
// Create notification without user_id or booking_id
createNotification(t, "1_week_no_pay", "", false)
createNotification(t, ctx, tx, "1_week_no_pay", "", false)
handler := http.HandlerFunc(GetNotifications)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeExtendedAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
var resp AdminNotificationListResponse
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
@@ -503,13 +517,14 @@ func TestNotifications_ResponseEnriched_NoUserOrBooking(t *testing.T) {
// =============================================================================
func TestNotifications_Acknowledge_ViaExtendedHandler(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
notifID := createNotification(t, "pending_booking", userID, false)
notifID := createNotification(t, ctx, tx, "pending_booking", userID, false)
handler := http.HandlerFunc(AcknowledgeNotification)
w := makeExtendedAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%s/acknowledge", notifID), nil)
w := makeExtendedAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%s/acknowledge", notifID), nil, ctx)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
@@ -517,7 +532,7 @@ func TestNotifications_Acknowledge_ViaExtendedHandler(t *testing.T) {
// Verify acknowledged
var ackTime *time.Time
err := db.DB.QueryRow(context.Background(),
err := tx.QueryRow(ctx,
"SELECT acknowledged_at FROM admin_notifications WHERE id = $1", notifID).Scan(&ackTime)
if err != nil {
t.Fatalf("failed to query notification: %v", err)
@@ -528,13 +543,14 @@ func TestNotifications_Acknowledge_ViaExtendedHandler(t *testing.T) {
}
func TestNotifications_Acknowledge_AlreadyAcknowledged_Extended(t *testing.T) {
testutils.SetupTestDB(t)
userID := createTestUser(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
userID := createTestUser(t, ctx, tx)
notifID := createNotification(t, "pending_booking", userID, true)
notifID := createNotification(t, ctx, tx, "pending_booking", userID, true)
handler := http.HandlerFunc(AcknowledgeNotification)
w := makeExtendedAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%s/acknowledge", notifID), nil)
w := makeExtendedAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%s/acknowledge", notifID), nil, ctx)
if w.Code != http.StatusNotFound {
t.Errorf("expected status 404 for already acknowledged, got %d", w.Code)
@@ -542,19 +558,18 @@ func TestNotifications_Acknowledge_AlreadyAcknowledged_Extended(t *testing.T) {
}
// createNotificationWithBooking creates a notification with both user_id and booking_id
func createNotificationWithBooking(t *testing.T, reason, userID, bookingID string, acknowledged bool) string {
func createNotificationWithBooking(t *testing.T, ctx context.Context, q db.Querier, reason, userID, bookingID string, acknowledged bool) string {
t.Helper()
var notificationID string
query := `INSERT INTO admin_notifications (reason, user_id, booking_id) VALUES ($1, $2, $3) RETURNING id`
if acknowledged {
query = `INSERT INTO admin_notifications (reason, user_id, booking_id, acknowledged_at) VALUES ($1, $2, $3, NOW()) RETURNING id`
}
err := db.DB.QueryRow(context.Background(), query, reason, userID, bookingID).Scan(&notificationID)
err := q.QueryRow(ctx, query, reason, userID, bookingID).Scan(&notificationID)
if err != nil {
t.Fatalf("failed to create notification: %v", err)
}
return notificationID
}
// Ensure test compilation
var _ = func() *pgxpool.Pool { return nil }
@@ -24,27 +24,25 @@ import (
"testing"
"time"
"crussell/db"
"crussell/testutils"
"crussell/mw"
"crussell/testutils/fixtures"
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
// makeAdminRequest creates a request with admin context
func makeAdminRequest(handler http.Handler, method, path string, body interface{}) *httptest.ResponseRecorder {
return makeRequestWithContext(handler, method, path, body, "admin001", "admin")
func makeAdminRequest(handler http.Handler, method, path string, body interface{}, ctx context.Context) *httptest.ResponseRecorder {
return makeRequestWithContext(handler, method, path, body, "admin001", "admin", ctx)
}
// makeUserRequest creates a request with regular user context
func makeUserRequest(handler http.Handler, method, path string, body interface{}) *httptest.ResponseRecorder {
return makeRequestWithContext(handler, method, path, body, "user001", "verified_email")
func makeUserRequest(handler http.Handler, method, path string, body interface{}, ctx context.Context) *httptest.ResponseRecorder {
return makeRequestWithContext(handler, method, path, body, "user001", "verified_email", ctx)
}
// makeRequestWithContext creates a request with specific user context
func makeRequestWithContext(handler http.Handler, method, path string, body interface{}, userID, role string) *httptest.ResponseRecorder {
func makeRequestWithContext(handler http.Handler, method, path string, body interface{}, userID, role string, ctx context.Context) *httptest.ResponseRecorder {
var req *http.Request
if body != nil {
bodyBytes, _ := json.Marshal(body)
@@ -59,7 +57,7 @@ func makeRequestWithContext(handler http.Handler, method, path string, body inte
if id, paramName := extractIDFromPath(path); id != "" {
rctx.URLParams.Add(paramName, id)
}
ctx := context.WithValue(req.Context(), chi.RouteCtxKey, rctx)
ctx = context.WithValue(ctx, chi.RouteCtxKey, rctx)
ctx = context.WithValue(ctx, mw.UserIDKey, userID)
ctx = context.WithValue(ctx, mw.UserRoleKey, role)
req = req.WithContext(ctx)
@@ -91,11 +89,12 @@ func extractIDFromPath(path string) (string, string) {
// TestNotifications_List tests that an admin can list all unacknowledged notifications
func TestNotifications_List(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
// Create test user for notification reference
var userID string
err := db.DB.QueryRow(context.Background(), `
err := tx.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
@@ -106,7 +105,7 @@ func TestNotifications_List(t *testing.T) {
// Create a notification
var notificationID string
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
INSERT INTO admin_notifications (reason, user_id)
VALUES ('pending_booking', $1)
RETURNING id
@@ -116,7 +115,7 @@ func TestNotifications_List(t *testing.T) {
}
handler := http.HandlerFunc(GetNotifications)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
@@ -143,10 +142,11 @@ func TestNotifications_List(t *testing.T) {
// TestNotifications_ListEmpty tests that an empty list is returned when no notifications exist
func TestNotifications_ListEmpty(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, _ := testutils.SetupTestTx(t)
handler := http.HandlerFunc(GetNotifications)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
@@ -169,11 +169,12 @@ func TestNotifications_ListEmpty(t *testing.T) {
// TestNotifications_ListFilterByReason tests that notifications can be filtered by reason
func TestNotifications_ListFilterByReason(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
err := tx.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
@@ -185,7 +186,7 @@ func TestNotifications_ListFilterByReason(t *testing.T) {
// Create notifications with different reasons
reasons := []string{"pending_booking", "cancelled_booking", "edit_requested"}
for _, reason := range reasons {
_, err := db.DB.Exec(context.Background(), `
_, err := tx.Exec(ctx, `
INSERT INTO admin_notifications (reason, user_id)
VALUES ($1, $2)
`, reason, userID)
@@ -197,7 +198,7 @@ func TestNotifications_ListFilterByReason(t *testing.T) {
handler := http.HandlerFunc(GetNotifications)
// Filter by pending_booking
w := makeAdminRequest(handler, "GET", "/api/admin/notifications?reason=pending_booking", nil)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications?reason=pending_booking", nil, ctx)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
@@ -219,11 +220,12 @@ func TestNotifications_ListFilterByReason(t *testing.T) {
// TestNotifications_ListPagination tests that pagination works correctly
func TestNotifications_ListPagination(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
err := tx.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
@@ -234,7 +236,7 @@ func TestNotifications_ListPagination(t *testing.T) {
// Create 25 notifications
for i := 0; i < 25; i++ {
_, err := db.DB.Exec(context.Background(), `
_, err := tx.Exec(ctx, `
INSERT INTO admin_notifications (reason, user_id)
VALUES ('pending_booking', $1)
`, userID)
@@ -246,7 +248,7 @@ func TestNotifications_ListPagination(t *testing.T) {
handler := http.HandlerFunc(GetNotifications)
// Get first page (default 20 items)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications?page=1&per_page=10", nil)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications?page=1&per_page=10", nil, ctx)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
@@ -268,11 +270,12 @@ func TestNotifications_ListPagination(t *testing.T) {
// TestNotifications_ListExcludesAcknowledged tests that acknowledged notifications are not returned
func TestNotifications_ListExcludesAcknowledged(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
err := tx.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
@@ -282,7 +285,7 @@ func TestNotifications_ListExcludesAcknowledged(t *testing.T) {
}
// Create acknowledged notification
_, err = db.DB.Exec(context.Background(), `
_, err = tx.Exec(ctx, `
INSERT INTO admin_notifications (reason, user_id, acknowledged_at)
VALUES ('pending_booking', $1, NOW())
`, userID)
@@ -292,7 +295,7 @@ func TestNotifications_ListExcludesAcknowledged(t *testing.T) {
// Create unacknowledged notification
var unackID string
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
INSERT INTO admin_notifications (reason, user_id)
VALUES ('cancelled_booking', $1)
RETURNING id
@@ -302,7 +305,7 @@ func TestNotifications_ListExcludesAcknowledged(t *testing.T) {
}
handler := http.HandlerFunc(GetNotifications)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
@@ -329,11 +332,12 @@ func TestNotifications_ListExcludesAcknowledged(t *testing.T) {
// TestNotifications_Acknowledge tests that an admin can acknowledge a notification
func TestNotifications_Acknowledge(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
err := tx.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
@@ -344,7 +348,7 @@ func TestNotifications_Acknowledge(t *testing.T) {
// Create notification
var notificationID string
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
INSERT INTO admin_notifications (reason, user_id)
VALUES ('pending_booking', $1)
RETURNING id
@@ -354,7 +358,7 @@ func TestNotifications_Acknowledge(t *testing.T) {
}
handler := http.HandlerFunc(AcknowledgeNotification)
w := makeAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%s/acknowledge", notificationID), nil)
w := makeAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%s/acknowledge", notificationID), nil, ctx)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d. body: %s", w.Code, w.Body.String())
@@ -362,7 +366,7 @@ func TestNotifications_Acknowledge(t *testing.T) {
// Verify the notification is acknowledged
var acknowledgedAt *time.Time
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
SELECT acknowledged_at FROM admin_notifications WHERE id = $1
`, notificationID).Scan(&acknowledgedAt)
if err != nil {
@@ -376,10 +380,11 @@ func TestNotifications_Acknowledge(t *testing.T) {
// TestNotifications_AcknowledgeNotFound tests that acknowledging a non-existent notification returns 404
func TestNotifications_AcknowledgeNotFound(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, _ := testutils.SetupTestTx(t)
handler := http.HandlerFunc(AcknowledgeNotification)
w := makeAdminRequest(handler, "POST", "/api/admin/notifications/ffffffffffff/acknowledge", nil)
w := makeAdminRequest(handler, "POST", "/api/admin/notifications/ffffffffffff/acknowledge", nil, ctx)
if w.Code != http.StatusNotFound {
t.Errorf("expected status 404 for non-existent notification, got %d", w.Code)
@@ -388,11 +393,12 @@ func TestNotifications_AcknowledgeNotFound(t *testing.T) {
// TestNotifications_AcknowledgeAlreadyAcknowledged tests that acknowledging an already-acknowledged notification returns 404
func TestNotifications_AcknowledgeAlreadyAcknowledged(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
err := tx.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
@@ -403,7 +409,7 @@ func TestNotifications_AcknowledgeAlreadyAcknowledged(t *testing.T) {
// Create already-acknowledged notification
var notificationID string
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
INSERT INTO admin_notifications (reason, user_id, acknowledged_at)
VALUES ('pending_booking', $1, NOW())
RETURNING id
@@ -413,7 +419,7 @@ func TestNotifications_AcknowledgeAlreadyAcknowledged(t *testing.T) {
}
handler := http.HandlerFunc(AcknowledgeNotification)
w := makeAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%s/acknowledge", notificationID), nil)
w := makeAdminRequest(handler, "POST", fmt.Sprintf("/api/admin/notifications/%s/acknowledge", notificationID), nil, ctx)
if w.Code != http.StatusNotFound {
t.Errorf("expected status 404 for already acknowledged notification, got %d", w.Code)
@@ -422,7 +428,8 @@ func TestNotifications_AcknowledgeAlreadyAcknowledged(t *testing.T) {
// TestNotifications_AcknowledgeInvalidID tests that invalid notification IDs are handled
func TestNotifications_AcknowledgeInvalidID(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
_, _ = testutils.SetupTestTx(t)
handler := http.HandlerFunc(AcknowledgeNotification)
@@ -461,7 +468,8 @@ func TestNotifications_AcknowledgeInvalidID(t *testing.T) {
// TestNotifications_AcknowledgeMissingID tests that missing ID returns 400
func TestNotifications_AcknowledgeMissingID(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
_, _ = testutils.SetupTestTx(t)
// Create a custom request with no ID in path
req := httptest.NewRequest("POST", "/api/admin/notifications//acknowledge", nil)
@@ -489,11 +497,12 @@ func TestNotifications_AcknowledgeMissingID(t *testing.T) {
// TestNotifications_WithBookingReference tests that notifications include booking_id when applicable
func TestNotifications_WithBookingReference(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
// Create test user
var userID string
err := db.DB.QueryRow(context.Background(), `
err := tx.QueryRow(ctx, `
INSERT INTO users (n_first_name, n_last_name, email, phone, date_of_birth, password_hash, account_role, account_type)
VALUES ('Test', 'User', 'test@test.com', '+1234567890', '1990-01-01', 'hash', 'verified_email', 'email')
RETURNING id
@@ -504,7 +513,7 @@ func TestNotifications_WithBookingReference(t *testing.T) {
// Create a service
var serviceID string
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
INSERT INTO services (name, description, price, duration_minutes, is_active)
VALUES ('Manicure', 'Test service', 25.00, 30, true)
RETURNING id
@@ -515,7 +524,7 @@ func TestNotifications_WithBookingReference(t *testing.T) {
// Create a booking
var bookingID string
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
INSERT INTO bookings (user_id, start_time, status)
VALUES ($1, NOW() + INTERVAL '1 day', 'pending')
RETURNING id
@@ -526,7 +535,7 @@ func TestNotifications_WithBookingReference(t *testing.T) {
// Create notification with booking reference
var notificationID string
err = db.DB.QueryRow(context.Background(), `
err = tx.QueryRow(ctx, `
INSERT INTO admin_notifications (reason, booking_id, user_id)
VALUES ('pending_booking', $1, $2)
RETURNING id
@@ -536,7 +545,7 @@ func TestNotifications_WithBookingReference(t *testing.T) {
}
handler := http.HandlerFunc(GetNotifications)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil)
w := makeAdminRequest(handler, "GET", "/api/admin/notifications", nil, ctx)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
@@ -558,37 +567,31 @@ func TestNotifications_WithBookingReference(t *testing.T) {
}
}
// Ensure test compilation - import pgxpool to avoid unused import
var _ = func() *pgxpool.Pool { return nil }
// =============================================================================
// AcknowledgePendingBookingNotification Tests
// =============================================================================
func TestAcknowledgePendingBookingNotification_Success(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
ctx := context.Background()
userID, err := fixtures.CreateTestUser(db.DB)
userID, err := fixtures.CreateTestUser(tx)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
t.Cleanup(func() { fixtures.DeleteUser(db.DB, userID) })
serviceID, err := fixtures.CreateTestService(db.DB)
serviceID, err := fixtures.CreateTestService(tx)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
t.Cleanup(func() { fixtures.DeleteService(db.DB, serviceID) })
bookingID, err := fixtures.CreateTestBookingAtTime(db.DB, userID, serviceID, time.Now().Add(24*time.Hour))
bookingID, err := fixtures.CreateTestBookingAtTime(tx, userID, serviceID, time.Now().Add(24*time.Hour))
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
t.Cleanup(func() { fixtures.DeleteBooking(db.DB, bookingID) })
// Create a pending notification for this booking
_, err = db.DB.Exec(ctx, `
_, err = tx.Exec(ctx, `
INSERT INTO admin_notifications (booking_id, reason, acknowledged_at)
VALUES ($1, 'pending_booking', NULL)
`, bookingID)
@@ -596,24 +599,14 @@ func TestAcknowledgePendingBookingNotification_Success(t *testing.T) {
t.Fatalf("failed to create notification: %v", err)
}
tx, err := db.DB.Begin(ctx)
if err != nil {
t.Fatalf("failed to begin tx: %v", err)
}
err = AcknowledgePendingBookingNotification(tx, ctx, bookingID)
if err != nil {
tx.Rollback(ctx)
t.Fatalf("AcknowledgePendingBookingNotification failed: %v", err)
}
if err := tx.Commit(ctx); err != nil {
t.Fatalf("failed to commit tx: %v", err)
}
// Verify notification was acknowledged
var acknowledgedAt *time.Time
err = db.DB.QueryRow(ctx,
err = tx.QueryRow(ctx,
"SELECT acknowledged_at FROM admin_notifications WHERE booking_id = $1 AND reason = 'pending_booking'",
bookingID).Scan(&acknowledgedAt)
if err != nil {
@@ -625,29 +618,26 @@ func TestAcknowledgePendingBookingNotification_Success(t *testing.T) {
}
func TestAcknowledgePendingBookingNotification_Idempotent(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
ctx := context.Background()
userID, err := fixtures.CreateTestUser(db.DB)
userID, err := fixtures.CreateTestUser(tx)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
t.Cleanup(func() { fixtures.DeleteUser(db.DB, userID) })
serviceID, err := fixtures.CreateTestService(db.DB)
serviceID, err := fixtures.CreateTestService(tx)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
t.Cleanup(func() { fixtures.DeleteService(db.DB, serviceID) })
bookingID, err := fixtures.CreateTestBookingAtTime(db.DB, userID, serviceID, time.Now().Add(24*time.Hour))
bookingID, err := fixtures.CreateTestBookingAtTime(tx, userID, serviceID, time.Now().Add(24*time.Hour))
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
t.Cleanup(func() { fixtures.DeleteBooking(db.DB, bookingID) })
// Notification already acknowledged
_, err = db.DB.Exec(ctx, `
_, err = tx.Exec(ctx, `
INSERT INTO admin_notifications (booking_id, reason, acknowledged_at)
VALUES ($1, 'pending_booking', NOW())
`, bookingID)
@@ -655,77 +645,57 @@ func TestAcknowledgePendingBookingNotification_Idempotent(t *testing.T) {
t.Fatalf("failed to create acknowledged notification: %v", err)
}
tx, err := db.DB.Begin(ctx)
if err != nil {
t.Fatalf("failed to begin tx: %v", err)
}
// Calling again on already acknowledged should not error
err = AcknowledgePendingBookingNotification(tx, ctx, bookingID)
if err != nil {
tx.Rollback(ctx)
t.Fatalf("AcknowledgePendingBookingNotification should not error when already acknowledged: %v", err)
}
tx.Commit(ctx)
}
func TestAcknowledgePendingBookingNotification_NoNotification(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
ctx := context.Background()
userID, err := fixtures.CreateTestUser(db.DB)
userID, err := fixtures.CreateTestUser(tx)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
t.Cleanup(func() { fixtures.DeleteUser(db.DB, userID) })
serviceID, err := fixtures.CreateTestService(db.DB)
serviceID, err := fixtures.CreateTestService(tx)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
t.Cleanup(func() { fixtures.DeleteService(db.DB, serviceID) })
bookingID, err := fixtures.CreateTestBookingAtTime(db.DB, userID, serviceID, time.Now().Add(24*time.Hour))
bookingID, err := fixtures.CreateTestBookingAtTime(tx, userID, serviceID, time.Now().Add(24*time.Hour))
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
t.Cleanup(func() { fixtures.DeleteBooking(db.DB, bookingID) })
tx, err := db.DB.Begin(ctx)
if err != nil {
t.Fatalf("failed to begin tx: %v", err)
}
// No notification exists - should not error
err = AcknowledgePendingBookingNotification(tx, ctx, bookingID)
if err != nil {
tx.Rollback(ctx)
t.Fatalf("AcknowledgePendingBookingNotification should not error when no notification exists: %v", err)
}
tx.Commit(ctx)
}
func TestAcknowledgePendingBookingNotification_NonTxCaller(t *testing.T) {
testutils.SetupTestDB(t)
t.Parallel()
ctx, tx := testutils.SetupTestTx(t)
ctx := context.Background()
userID, err := fixtures.CreateTestUser(db.DB)
userID, err := fixtures.CreateTestUser(tx)
if err != nil {
t.Fatalf("failed to create user: %v", err)
}
t.Cleanup(func() { fixtures.DeleteUser(db.DB, userID) })
serviceID, err := fixtures.CreateTestService(db.DB)
serviceID, err := fixtures.CreateTestService(tx)
if err != nil {
t.Fatalf("failed to create service: %v", err)
}
t.Cleanup(func() { fixtures.DeleteService(db.DB, serviceID) })
bookingID, err := fixtures.CreateTestBookingAtTime(db.DB, userID, serviceID, time.Now().Add(24*time.Hour))
bookingID, err := fixtures.CreateTestBookingAtTime(tx, userID, serviceID, time.Now().Add(24*time.Hour))
if err != nil {
t.Fatalf("failed to create booking: %v", err)
}
t.Cleanup(func() { fixtures.DeleteBooking(db.DB, bookingID) })
// Call with a plain struct (not a tx) - should log warning and not error
err = AcknowledgePendingBookingNotification("not-a-tx", ctx, bookingID)
@@ -14,8 +14,9 @@ import (
func TestMain(m *testing.M) {
pool := testdb.CreateTestDatabase("crussell_test_handlers_notifications")
db.DB = pool
db.Conn = db.NewPoolProxy(pool)
jwt.Init()
testdb.SeedBaseline(pool)
code := m.Run()
testdb.DestroyTestDatabase(pool, "crussell_test_handlers_notifications")
os.Exit(code)