mirror of
https://github.com/phishingclub/phishingclub.git
synced 2026-12-06 10:03:46 +01:00
373 lines
12 KiB
Go
373 lines
12 KiB
Go
// Package testdb opens the database a test runs against. Only tests import
|
|
// it, it is not part of the application binary.
|
|
//
|
|
// Without PC_TEST_DB the test gets the sqlite database of the DSN it passes,
|
|
// opened with gorm.Open and a silent logger. With PC_TEST_DB=postgres every Open creates a new
|
|
// postgres database through the admin DSN in PC_TEST_PG_DSN (a URL such as
|
|
// postgres://postgres:TEST@postgres:5432/postgres?sslmode=disable) and drops
|
|
// it when the test ends.
|
|
//
|
|
// Foreign keys follow the sqlite DSN: mattn sqlite leaves them off unless the
|
|
// DSN has _foreign_keys=ON (or 1, or _fk), so many tests insert rows without
|
|
// their parents. On postgres such a database is opened with
|
|
// session_replication_role=replica on every connection, which skips foreign
|
|
// key checks the same way. Unique and check constraints still apply.
|
|
package testdb
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"database/sql"
|
|
"encoding/hex"
|
|
"fmt"
|
|
"net/url"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
|
|
// registers the pgx database/sql driver used for the admin connection
|
|
_ "github.com/jackc/pgx/v5/stdlib"
|
|
"github.com/phishingclub/phishingclub/database/dbengine"
|
|
"gorm.io/driver/postgres"
|
|
"gorm.io/driver/sqlite"
|
|
"gorm.io/gorm"
|
|
"gorm.io/gorm/logger"
|
|
)
|
|
|
|
const (
|
|
// EnvEngine picks the engine, postgres or empty for sqlite
|
|
EnvEngine = "PC_TEST_DB"
|
|
// EnvPostgresDSN is the admin DSN used to create and drop test databases
|
|
EnvPostgresDSN = "PC_TEST_PG_DSN"
|
|
|
|
enginePostgres = "postgres"
|
|
|
|
// postgresMaxOpenConns bounds each test database pool, so packages
|
|
// running at the same time stay below the server connection limit
|
|
postgresMaxOpenConns = 8
|
|
)
|
|
|
|
var (
|
|
// databaseNamePattern is the only form of database name the tests create
|
|
// and drop
|
|
databaseNamePattern = regexp.MustCompile(`^pctest_[0-9a-f]{16}$`)
|
|
|
|
adminOnce sync.Once
|
|
adminDB *sql.DB
|
|
adminErr error
|
|
)
|
|
|
|
// IsPostgres is true when the tests run against postgres
|
|
func IsPostgres() bool {
|
|
return os.Getenv(EnvEngine) == enginePostgres
|
|
}
|
|
|
|
// SkipUnlessSQLite skips a test that checks sqlite internals when the tests
|
|
// run against another engine
|
|
func SkipUnlessSQLite(t testing.TB, reason string) {
|
|
t.Helper()
|
|
if IsPostgres() {
|
|
t.Skipf("sqlite only: %s", reason)
|
|
}
|
|
}
|
|
|
|
// SkipUnlessPostgres skips a test that only applies to postgres
|
|
func SkipUnlessPostgres(t testing.TB) {
|
|
t.Helper()
|
|
if !IsPostgres() {
|
|
t.Skip("postgres only, set " + EnvEngine + "=postgres")
|
|
}
|
|
}
|
|
|
|
// Open opens the test database. sqliteDSN is the sqlite DSN the test uses,
|
|
// on postgres only its foreign key flag is read. The gorm config matches what
|
|
// the tests used before (silent logger) and, on postgres, what the
|
|
// application uses (TranslateError).
|
|
func Open(t testing.TB, sqliteDSN string) (*gorm.DB, error) {
|
|
t.Helper()
|
|
return open(t, sqliteDSN, "")
|
|
}
|
|
|
|
// OpenWithExecMode is Open with the pgx default_query_exec_mode set on the
|
|
// postgres DSN, empty keeps the default. On sqlite it is Open.
|
|
func OpenWithExecMode(t testing.TB, sqliteDSN string, execMode string) (*gorm.DB, error) {
|
|
t.Helper()
|
|
return open(t, sqliteDSN, execMode)
|
|
}
|
|
|
|
func open(t testing.TB, sqliteDSN string, execMode string) (*gorm.DB, error) {
|
|
t.Helper()
|
|
if !IsPostgres() {
|
|
db, err := gorm.Open(sqlite.Open(sqliteDSN), &gorm.Config{
|
|
Logger: logger.Default.LogMode(logger.Silent),
|
|
})
|
|
if err == nil {
|
|
setActive(t, db)
|
|
logStatements(db)
|
|
}
|
|
return db, err
|
|
}
|
|
dsn := NewPostgresDatabase(t, sqliteForeignKeysOn(sqliteDSN))
|
|
return openPostgresTest(t, dsn, execMode, true)
|
|
}
|
|
|
|
// openPostgresTest opens the test database at dsn, see openPostgres, and
|
|
// closes it when the test ends
|
|
func openPostgresTest(t testing.TB, dsn string, execMode string, rowOrderTrigger bool) (*gorm.DB, error) {
|
|
t.Helper()
|
|
db, sqlDB, err := openPostgres(dsn, execMode, rowOrderTrigger)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
setActive(t, db)
|
|
logStatements(db)
|
|
// closed before the database is dropped, cleanups run last added first
|
|
t.Cleanup(func() { _ = sqlDB.Close() })
|
|
return db, nil
|
|
}
|
|
|
|
// openPostgres opens the postgres database at dsn the way the tests use it.
|
|
// execMode sets the pgx default_query_exec_mode, empty keeps the default.
|
|
// rowOrderTrigger installs the row order event trigger, which a new empty
|
|
// database needs and a copy of a template already has.
|
|
func openPostgres(dsn string, execMode string, rowOrderTrigger bool) (*gorm.DB, *sql.DB, error) {
|
|
if execMode != "" {
|
|
u, err := url.Parse(dsn)
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
q := u.Query()
|
|
q.Set("default_query_exec_mode", execMode)
|
|
// the DSN parser takes a + literally, so a space is sent as %20
|
|
u.RawQuery = strings.ReplaceAll(q.Encode(), "+", "%20")
|
|
dsn = u.String()
|
|
}
|
|
db, err := gorm.Open(dbengine.NewPostgres(postgres.Config{DSN: dsn}), &gorm.Config{
|
|
Logger: logger.Default.LogMode(logger.Silent),
|
|
TranslateError: true,
|
|
})
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
sqlDB, err := db.DB()
|
|
if err != nil {
|
|
return nil, nil, err
|
|
}
|
|
sqlDB.SetMaxOpenConns(postgresMaxOpenConns)
|
|
// as the application, see dbengine.RegisterEventInsertLock
|
|
if err := dbengine.RegisterEventInsertLock(db); err != nil {
|
|
_ = sqlDB.Close()
|
|
return nil, nil, err
|
|
}
|
|
dbengine.RegisterArrayIN(db)
|
|
if rowOrderTrigger {
|
|
if err := addRowOrderTrigger(db); err != nil {
|
|
_ = sqlDB.Close()
|
|
return nil, nil, err
|
|
}
|
|
}
|
|
return db, sqlDB, nil
|
|
}
|
|
|
|
// setActive records the engine of db for the quoting helpers and fails the
|
|
// test when the process already uses another engine
|
|
func setActive(t testing.TB, db *gorm.DB) {
|
|
t.Helper()
|
|
if err := dbengine.SetActive(db.Dialector); err != nil {
|
|
t.Fatalf("testdb: %s engine in a process that uses another engine: %v", db.Dialector.Name(), err)
|
|
}
|
|
}
|
|
|
|
// NewPostgresDatabase creates an empty postgres database that is dropped when
|
|
// the test ends and returns its DSN. foreignKeys false opens every connection
|
|
// with foreign key checks off. It fails the test when postgres is not set up.
|
|
func NewPostgresDatabase(t testing.TB, foreignKeys bool) string {
|
|
t.Helper()
|
|
return newPostgresDatabase(t, foreignKeys, "")
|
|
}
|
|
|
|
// OpenPostgresDSN opens the postgres database at dsn, made by
|
|
// NewPostgresDatabase, the way Open opens a test database, and closes the
|
|
// connections when the test ends. A test that builds the database with
|
|
// another handle first, such as an older schema, opens it again with this.
|
|
func OpenPostgresDSN(t testing.TB, dsn string) (*gorm.DB, error) {
|
|
t.Helper()
|
|
return openPostgresTest(t, dsn, "", false)
|
|
}
|
|
|
|
// newPostgresDatabase is NewPostgresDatabase, a copy of the database named
|
|
// template when it is not empty, see OpenMigrated
|
|
func newPostgresDatabase(t testing.TB, foreignKeys bool, template string) string {
|
|
t.Helper()
|
|
admin := adminConnection(t)
|
|
b := make([]byte, 8)
|
|
if _, err := rand.Read(b); err != nil {
|
|
t.Fatalf("testdb: random name: %v", err)
|
|
}
|
|
// Test only. CREATE and DROP DATABASE take no bind parameter, so the
|
|
// name is put into the statement, after a check that it is the random
|
|
// name made here and nothing else.
|
|
name := "pctest_" + hex.EncodeToString(b)
|
|
if !databaseNamePattern.MatchString(name) {
|
|
t.Fatalf("testdb: invalid database name %q", name)
|
|
}
|
|
create := "CREATE DATABASE " + name
|
|
if template != "" {
|
|
if !templateNamePattern.MatchString(template) {
|
|
t.Fatalf("testdb: invalid template name %q", template)
|
|
}
|
|
create += " TEMPLATE " + quoteIdentifier(template)
|
|
}
|
|
if _, err := admin.Exec(create); err != nil {
|
|
t.Fatalf("testdb: create database: %v", err)
|
|
}
|
|
t.Cleanup(func() {
|
|
if !databaseNamePattern.MatchString(name) {
|
|
t.Errorf("testdb: invalid database name %q", name)
|
|
return
|
|
}
|
|
if _, err := admin.Exec("DROP DATABASE IF EXISTS " + name + " WITH (FORCE)"); err != nil {
|
|
t.Logf("testdb: drop database %s: %v", name, err)
|
|
}
|
|
})
|
|
return databaseDSN(t, name, foreignKeys)
|
|
}
|
|
|
|
// databaseDSN is the admin DSN pointed at the database name. foreignKeys
|
|
// false opens every connection with foreign key checks off.
|
|
func databaseDSN(t testing.TB, name string, foreignKeys bool) string {
|
|
t.Helper()
|
|
u, err := url.Parse(os.Getenv(EnvPostgresDSN))
|
|
if err != nil {
|
|
t.Fatalf("testdb: %s is not a URL", EnvPostgresDSN)
|
|
}
|
|
u.Path = "/" + name
|
|
if !foreignKeys {
|
|
q := u.Query()
|
|
q.Set("options", "-c session_replication_role=replica")
|
|
// the DSN parser takes a + literally, so the space is sent as %20
|
|
u.RawQuery = strings.ReplaceAll(q.Encode(), "+", "%20")
|
|
}
|
|
return u.String()
|
|
}
|
|
|
|
// SetForeignKeys turns foreign key checks on or off for one connection of
|
|
// db, like the sqlite foreign_keys pragma, so tests that toggle it hold a
|
|
// single connection. On postgres it sets session_replication_role, which
|
|
// needs a superuser, as the test server user is.
|
|
func SetForeignKeys(db *gorm.DB, on bool) error {
|
|
if IsPostgres() {
|
|
if on {
|
|
return db.Exec("SET session_replication_role = origin").Error
|
|
}
|
|
return db.Exec("SET session_replication_role = replica").Error
|
|
}
|
|
if on {
|
|
return db.Exec("PRAGMA foreign_keys = ON").Error
|
|
}
|
|
return db.Exec("PRAGMA foreign_keys = OFF").Error
|
|
}
|
|
|
|
// ForeignKeysOn reports whether foreign keys are checked on a connection of db
|
|
func ForeignKeysOn(db *gorm.DB) (bool, error) {
|
|
if IsPostgres() {
|
|
var role string
|
|
if err := db.Raw("SHOW session_replication_role").Scan(&role).Error; err != nil {
|
|
return false, err
|
|
}
|
|
return role != "replica", nil
|
|
}
|
|
var on int
|
|
if err := db.Raw("PRAGMA foreign_keys").Scan(&on).Error; err != nil {
|
|
return false, err
|
|
}
|
|
return on == 1, nil
|
|
}
|
|
|
|
// adminConnection opens the shared admin connection once
|
|
func adminConnection(t testing.TB) *sql.DB {
|
|
t.Helper()
|
|
adminOnce.Do(func() {
|
|
dsn := os.Getenv(EnvPostgresDSN)
|
|
if dsn == "" {
|
|
adminErr = fmt.Errorf("%s=postgres needs %s", EnvEngine, EnvPostgresDSN)
|
|
return
|
|
}
|
|
adminDB, adminErr = sql.Open("pgx", dsn)
|
|
if adminErr == nil {
|
|
adminErr = adminDB.Ping()
|
|
}
|
|
})
|
|
if adminErr != nil {
|
|
// the error of the driver does not hold the password
|
|
t.Fatalf("testdb: admin connection: %v", adminErr)
|
|
}
|
|
return adminDB
|
|
}
|
|
|
|
// sqliteForeignKeysOn mirrors how mattn sqlite reads the foreign key flag
|
|
func sqliteForeignKeysOn(dsn string) bool {
|
|
i := strings.Index(dsn, "?")
|
|
if i == -1 {
|
|
return false
|
|
}
|
|
q, err := url.ParseQuery(dsn[i+1:])
|
|
if err != nil {
|
|
return false
|
|
}
|
|
for _, key := range []string{"_foreign_keys", "_fk"} {
|
|
switch strings.ToLower(q.Get(key)) {
|
|
case "1", "yes", "true", "on":
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// EnvSQLLog names a directory. When set, every statement a test database
|
|
// runs is appended to a file per test process there, the SQL text with its
|
|
// placeholders and no values. It is for comparing the SQL two versions of
|
|
// the code send.
|
|
const EnvSQLLog = "PC_TEST_SQL_LOG"
|
|
|
|
var (
|
|
sqlLogOnce sync.Once
|
|
sqlLogFile *os.File
|
|
sqlLogMu sync.Mutex
|
|
)
|
|
|
|
// logStatements registers the callbacks that write the SQL of db, see
|
|
// EnvSQLLog
|
|
func logStatements(db *gorm.DB) {
|
|
dir := os.Getenv(EnvSQLLog)
|
|
if dir == "" {
|
|
return
|
|
}
|
|
sqlLogOnce.Do(func() {
|
|
f, err := os.OpenFile(fmt.Sprintf("%s/sql-%d.log", dir, os.Getpid()), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
|
|
if err == nil {
|
|
sqlLogFile = f
|
|
}
|
|
})
|
|
if sqlLogFile == nil {
|
|
return
|
|
}
|
|
write := func(tx *gorm.DB) {
|
|
text := strings.Join(strings.Fields(tx.Statement.SQL.String()), " ")
|
|
if text == "" {
|
|
return
|
|
}
|
|
sqlLogMu.Lock()
|
|
defer sqlLogMu.Unlock()
|
|
_, _ = sqlLogFile.WriteString(text + "\n")
|
|
}
|
|
cb := db.Callback()
|
|
_ = cb.Query().After("gorm:query").Register("testdb:sqllog", write)
|
|
_ = cb.Create().After("gorm:create").Register("testdb:sqllog", write)
|
|
_ = cb.Update().After("gorm:update").Register("testdb:sqllog", write)
|
|
_ = cb.Delete().After("gorm:delete").Register("testdb:sqllog", write)
|
|
_ = cb.Row().After("gorm:row").Register("testdb:sqllog", write)
|
|
_ = cb.Raw().After("gorm:raw").Register("testdb:sqllog", write)
|
|
}
|