67 lines
1.6 KiB
Go
67 lines
1.6 KiB
Go
package account_test
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"database/sql"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"net/url"
|
|
"os"
|
|
"testing"
|
|
|
|
hub "git.ipao.vip/rogee/creator-hub/internal/environment"
|
|
)
|
|
|
|
// Account tests truncate their fixtures. They must never run in the configured
|
|
// database schema; always initialize and destroy a separate schema first.
|
|
func TestMain(m *testing.M) { os.Exit(runAccountTests(m)) }
|
|
|
|
func runAccountTests(m *testing.M) (result int) {
|
|
databaseURL := os.Getenv("CREATORHUB_POSTGRES_TEST_URL")
|
|
if databaseURL == "" {
|
|
return m.Run()
|
|
}
|
|
fail := func(err error) int {
|
|
fmt.Fprintln(os.Stderr, "initialize isolated account test schema:", err)
|
|
return 1
|
|
}
|
|
parsed, err := url.Parse(databaseURL)
|
|
if err != nil {
|
|
return fail(err)
|
|
}
|
|
bytes := make([]byte, 8)
|
|
if _, err := rand.Read(bytes); err != nil {
|
|
return fail(err)
|
|
}
|
|
schema := "account_test_" + hex.EncodeToString(bytes)
|
|
db, err := sql.Open("pgx", databaseURL)
|
|
if err != nil {
|
|
return fail(err)
|
|
}
|
|
defer db.Close()
|
|
if _, err := db.Exec(`CREATE SCHEMA "` + schema + `"`); err != nil {
|
|
return fail(err)
|
|
}
|
|
defer func() {
|
|
if _, err := db.Exec(`DROP SCHEMA "` + schema + `" CASCADE`); err != nil {
|
|
fmt.Fprintln(os.Stderr, "cleanup isolated account test schema:", err)
|
|
result = 1
|
|
}
|
|
}()
|
|
query := parsed.Query()
|
|
query.Set("search_path", schema)
|
|
parsed.RawQuery = query.Encode()
|
|
store, err := hub.Open(context.Background(), parsed.String())
|
|
if err != nil {
|
|
return fail(err)
|
|
}
|
|
if err := store.Close(); err != nil {
|
|
return fail(err)
|
|
}
|
|
if err := os.Setenv("CREATORHUB_POSTGRES_TEST_URL", parsed.String()); err != nil {
|
|
return fail(err)
|
|
}
|
|
return m.Run()
|
|
}
|