65 lines
1.6 KiB
Go
65 lines
1.6 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
"5803025020/w04/internal/config"
|
|
"5803025020/w04/internal/database"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
// testConn is the single shared connection used by every integration test in
|
|
// this package. testMu serializes access to it the same way the production
|
|
// server serializes access across UserStore/SessionStore/SnippetStore.
|
|
var (
|
|
testConn *pgx.Conn
|
|
testMu = &sync.Mutex{}
|
|
)
|
|
|
|
func TestMain(m *testing.M) {
|
|
config.LoadEnv()
|
|
|
|
dbName := os.Getenv("DB_NAME")
|
|
if !strings.HasSuffix(dbName, "_test") {
|
|
fmt.Fprintf(os.Stderr,
|
|
"refusing to run internal/store integration tests: DB_NAME=%q must end in \"_test\" (safety guard against running against a non-test database)\n",
|
|
dbName)
|
|
os.Exit(1)
|
|
}
|
|
|
|
conn, err := database.Connect()
|
|
if err != nil {
|
|
fmt.Fprintf(os.Stderr, "failed to connect to test database: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
testConn = conn
|
|
|
|
// Create the schema through the exact same code path the server uses on
|
|
// startup — no second copy of the CREATE TABLE statements here.
|
|
if err := database.CreateTables(testConn); err != nil {
|
|
fmt.Fprintf(os.Stderr, "failed to create schema: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
code := m.Run()
|
|
|
|
testConn.Close(context.Background())
|
|
os.Exit(code)
|
|
}
|
|
|
|
// truncateAll wipes every application table so each test starts from a clean
|
|
// slate. Call this at the start of every test (not just once in TestMain).
|
|
func truncateAll(t *testing.T) {
|
|
t.Helper()
|
|
_, err := testConn.Exec(context.Background(),
|
|
"TRUNCATE TABLE sessions, snippets, users RESTART IDENTITY CASCADE")
|
|
if err != nil {
|
|
t.Fatalf("failed to truncate tables: %v", err)
|
|
}
|
|
}
|