//go:build test // +build test package admin import ( "bytes" "context" "encoding/json" "net/http" "net/http/httptest" "testing" "crussell/db" "crussell/mw" "crussell/testutils/jwt" "crussell/testutils/testdb" ) // setupTestDB replaces the global db.DB with a test pool and returns a cleanup function func setupTestDB(t *testing.T) func() { t.Helper() pool := testdb.Pool(t) testdb.Migrate(t, pool) originalDB := db.DB db.DB = pool jwt.Init() return func() { db.DB = originalDB pool.Close() } } // 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, "admin-test-001", "admin") } // 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, "user-test-001", "verified_email") } // makeRequestWithContext creates a request with specific user context func makeRequestWithContext(handler http.Handler, method, path string, body interface{}, userID, role string) *httptest.ResponseRecorder { var req *http.Request if body != nil { bodyBytes, _ := json.Marshal(body) req = httptest.NewRequest(method, path, bytes.NewReader(bodyBytes)) req.Header.Set("Content-Type", "application/json") } else { req = httptest.NewRequest(method, path, nil) } // Set up context with user ID and role (simulating middleware) ctx := context.WithValue(req.Context(), mw.UserIDKey, userID) ctx = context.WithValue(ctx, mw.UserRoleKey, role) req = req.WithContext(ctx) w := httptest.NewRecorder() handler.ServeHTTP(w, req) return w } func parseResponseBody(w *httptest.ResponseRecorder, dest interface{}) error { return json.Unmarshal(w.Body.Bytes(), dest) }