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