- 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)
72 lines
1.9 KiB
Go
72 lines
1.9 KiB
Go
//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)
|
|
}
|