tss-rocks/backend/internal/testutil/db.go
CDN 05ddc1f783
Some checks failed
Build Backend / Build Docker Image (push) Successful in 3m33s
Test Backend / test (push) Failing after 31s
[feature] migrate to monorepo
2025-02-21 00:49:20 +08:00

57 lines
1.4 KiB
Go

package testutil
import (
"context"
"os"
"path/filepath"
"testing"
"entgo.io/ent/dialect"
"github.com/mattn/go-sqlite3"
"github.com/stretchr/testify/require"
"tss-rocks-be/ent"
)
// SetupTestDB creates a new test database and returns a client
func SetupTestDB(t *testing.T) *ent.Client {
// Create a temporary SQLite database for testing
dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db")
client, err := ent.Open(dialect.SQLite, "file:"+dbPath+"?mode=memory&cache=shared&_fk=1")
require.NoError(t, err)
// Run the auto migration tool
err = client.Schema.Create(context.Background())
require.NoError(t, err)
// Clean up the database after the test
t.Cleanup(func() {
client.Close()
os.Remove(dbPath)
})
return client
}
// CleanupTestDB removes all data from the test database
func CleanupTestDB(t *testing.T, client *ent.Client) {
ctx := context.Background()
// Delete all data in reverse order of dependencies
_, err := client.Permission.Delete().Exec(ctx)
require.NoError(t, err)
_, err = client.Role.Delete().Exec(ctx)
require.NoError(t, err)
_, err = client.User.Delete().Exec(ctx)
require.NoError(t, err)
}
// IsSQLiteConstraintError checks if the error is a SQLite constraint error
func IsSQLiteConstraintError(err error) bool {
sqliteErr, ok := err.(sqlite3.Error)
return ok && sqliteErr.Code == sqlite3.ErrConstraint
}