Files
bamort/template/backend/database/testhelper.go
T
2026-04-01 15:16:12 +02:00

75 lines
1.5 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package database
import (
"io"
"myapp/logger"
"os"
"path/filepath"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var isTestDb bool
// SetupTestDB opens a temporary copy of PreparedTestDB as the global DB.
// Pass false as the first argument to use the real database instead.
func SetupTestDB(opts ...bool) {
isTestDb = true
if len(opts) > 0 {
isTestDb = opts[0]
}
if DB != nil {
return
}
if !isTestDb {
connectProduction()
return
}
logger.Info("SetupTestDB: creating temporary SQLite test database")
tmpDir, err := os.MkdirTemp("", "myapp-test-")
if err != nil {
panic("failed to create temp dir: " + err.Error())
}
target := filepath.Join(tmpDir, "test.db")
// Copy the prepared snapshot so every test starts with clean data.
if err := copyFile(PreparedTestDB, target); err != nil {
// No snapshot exists yet start with an empty database.
logger.Warn("SetupTestDB: no snapshot found at %s, using empty DB", PreparedTestDB)
target = filepath.Join(tmpDir, "empty.db")
}
db, err := gorm.Open(sqlite.Open(target), &gorm.Config{})
if err != nil {
panic("failed to open test database: " + err.Error())
}
DB = db
if err := MigrateStructure(db); err != nil {
panic("test database migration failed: " + err.Error())
}
}
func copyFile(src, dst string) error {
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
return err
}