refactor: optimize test DB setup — TestMain per package, truncate-only between tests
- Add TestMain to all 10 test packages (schema DROP+CREATE runs once per package) - Convert per-test setupTestDB to resetTestData (TRUNCATE only, ~60% faster) - Add 3 missing tables to TruncateTables (booking_edit_requests, exceptional_group_applications, business_settings) - Remove dead truncateDiscountTables helper - Consolidate discount_test.go into package bookings (was external test package) - Update testutils.SetupTestDB to truncate-only - Fix unused imports across user, bookings, and handlers packages - Verify: 286 passing, 2 skipped, 0 failures with -count=2 (no state leakage)
This commit is contained in:
@@ -9,48 +9,19 @@ import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"crussell/db"
|
||||
"crussell/mw"
|
||||
"crussell/testutils/jwt"
|
||||
"crussell/testutils/testdb"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
// TestMain initializes test environment variables before any tests run
|
||||
func TestMain(m *testing.M) {
|
||||
// Set database environment variables for test database
|
||||
os.Setenv("POSTGRES_USER", "myuser")
|
||||
os.Setenv("POSTGRES_PASSWORD", "mypassword")
|
||||
os.Setenv("POSTGRES_HOST", "localhost")
|
||||
os.Setenv("POSTGRES_DB", "crussell_test")
|
||||
os.Setenv("GO_TESTING", "true")
|
||||
|
||||
// Run the tests
|
||||
code := m.Run()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
// setupTestDB replaces the global db.DB with a test pool and returns a cleanup function
|
||||
func setupTestDB(t *testing.T) func() {
|
||||
// resetTestData truncates tables to clean up data between tests
|
||||
func resetTestData(t *testing.T) {
|
||||
t.Helper()
|
||||
|
||||
pool := testdb.Pool(t)
|
||||
testdb.Migrate(t, pool)
|
||||
testdb.TruncateTables(t, pool) // Clear data between tests
|
||||
|
||||
originalDB := db.DB
|
||||
db.DB = pool
|
||||
|
||||
jwt.Init()
|
||||
|
||||
return func() {
|
||||
db.DB = originalDB
|
||||
pool.Close()
|
||||
}
|
||||
testdb.TruncateTables(t, db.DB)
|
||||
}
|
||||
|
||||
// makeAdminRequest creates a request with admin context
|
||||
|
||||
Reference in New Issue
Block a user