1package test
2
3import (
4 "context"
5 "path/filepath"
6 "testing"
7
8 "github.com/charmbracelet/soft-serve/pkg/db"
9)
10
11// OpenSqlite opens a new temp SQLite database for testing.
12// It removes the database file when the test is done using tb.Cleanup.
13// If ctx is nil, context.TODO() is used.
14func OpenSqlite(ctx context.Context, tb testing.TB) (*db.DB, error) {
15 if ctx == nil {
16 ctx = context.TODO()
17 }
18 dbpath := filepath.Join(tb.TempDir(), "test.db")
19 dbx, err := db.Open(ctx, "sqlite", dbpath)
20 if err != nil {
21 return nil, err
22 }
23 tb.Cleanup(func() {
24 if err := dbx.Close(); err != nil {
25 tb.Error(err)
26 }
27 })
28 return dbx, nil
29}