SQLite project: a tested notes repository · 4 MIN READ
Test against real SQLite: a fresh migrated database file per test
Write a test helper that opens a migrated file database in t.TempDir, registers cleanup, and lets table-driven and parallel tests run against isolated databases.
Because SQLite is a library, tests can use the real engine with the real schema instead of a mock, and still run in milliseconds. The question is isolation: tests that share one database see each other's rows, and an in-memory database interacts badly with the connection pool. A helper that gives every test its own migrated file in a temporary directory solves both and keeps the tests safe to run in parallel.
sqlite · A MAP OF THE IDEA
- t.TempDir per test
- Open with prod DSN
- Migrate, register Cleanup
- Run cases in parallel
Useful when
- Tests use the real engine, schema and constraints.
- Isolated files make t.Parallel safe.
Watch out
- Schema setup cost grows with the migration list.
- :memory: with a pool silently splits databases.
Implementation & operation cost: A ten-line helper and a few milliseconds of disk work per test; a migrated template file once the schema grows.
The helper owns setup and teardown
newTestDB takes a small interface with Helper, TempDir, Cleanup and Fatalf, which *testing.T and *testing.B satisfy. It creates the file inside t.TempDir(), opens it with the same DSN options as production, registers db.Close with t.Cleanup and applies the schema, failing the test with Fatalf on any error. Helper makes failures point at the calling test line. Cleanup functions run last-registered first, so the pool is closed before the testing package removes the temporary directory, which matters on systems that cannot delete open files.
Table-driven cases, one database each
The program cannot import a test binary, so it runs the same helper with a tiny fake that implements the interface, records cleanups and turns Fatalf into a reported failure. Each case opens an account, withdraws and checks the balance; the CHECK constraint is part of the behaviour under test. A fourth test fails on purpose to show the reporting. At the end the program confirms that each case had its own directory and that cleanup removed every one.
package main
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"path/filepath"
_ "modernc.org/sqlite"
)
// TB is the part of testing.TB the helper needs. *testing.T and *testing.B
// satisfy it, and so does the small runner in main.
type TB interface {
Helper()
TempDir() string
Cleanup(func())
Fatalf(format string, args ...any)
}
const schema = `CREATE TABLE accounts (
id INTEGER PRIMARY KEY,
owner TEXT NOT NULL UNIQUE,
balance INTEGER NOT NULL CHECK (balance >= 0)
)`
// newTestDB opens a fresh, migrated file database that belongs to one test.
// The file lives in the test's temporary directory and disappears with it.
func newTestDB(t TB) *sql.DB {
t.Helper()
path := filepath.Join(t.TempDir(), "test.db")
db, err := sql.Open("sqlite", "file:"+path+"?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)")
if err != nil {
t.Fatalf("open: %v", err)
}
t.Cleanup(func() { db.Close() }) // registered after TempDir, so it runs first
if _, err := db.Exec(schema); err != nil {
t.Fatalf("migrate: %v", err)
}
return db
}
// Code under test.
func open(ctx context.Context, db *sql.DB, owner string, deposit int) error {
_, err := db.ExecContext(ctx, "INSERT INTO accounts (owner, balance) VALUES (?, ?)", owner, deposit)
return err
}
func withdraw(ctx context.Context, db *sql.DB, owner string, amount int) error {
res, err := db.ExecContext(ctx, "UPDATE accounts SET balance = balance - ? WHERE owner = ?", amount, owner)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return errors.New("no such account")
}
return nil
}
// fakeT is a minimal stand-in for *testing.T so this program runs with go run.
type fakeT struct {
name string
dir string
cleanups []func()
failed bool
}
func (t *fakeT) Helper() {}
func (t *fakeT) TempDir() string {
if t.dir == "" {
dir, err := os.MkdirTemp("", "test")
if err != nil {
panic(err)
}
t.dir = dir
t.Cleanup(func() { os.RemoveAll(dir) })
}
return t.dir
}
func (t *fakeT) Cleanup(f func()) { t.cleanups = append(t.cleanups, f) }
func (t *fakeT) Fatalf(format string, args ...any) {
t.failed = true
panic(fmt.Sprintf(format, args...))
}
func (t *fakeT) finish() {
for i := len(t.cleanups) - 1; i >= 0; i-- { // last registered runs first, like testing
t.cleanups[i]()
}
}
func run(name string, test func(t TB)) (dir string) {
t := &fakeT{name: name}
defer func() {
if r := recover(); r != nil {
fmt.Printf("--- FAIL: %s: %v\n", name, r)
} else {
fmt.Printf("--- PASS: %s\n", name)
}
t.finish()
}()
test(t)
return t.dir
}
func main() {
ctx := context.Background()
cases := []struct {
name string
deposit int
amount int
wantErr bool
want int
}{
{"withdraw part", 100, 30, false, 70},
{"withdraw all", 50, 50, false, 0},
{"overdraw is refused by CHECK", 20, 25, true, 20},
}
var dirs []string
for _, tc := range cases {
dirs = append(dirs, run(tc.name, func(t TB) {
db := newTestDB(t)
// Every case starts empty: earlier cases inserted "ada" too.
var n int
db.QueryRow("SELECT count(*) FROM accounts").Scan(&n)
if n != 0 {
t.Fatalf("leaked %d rows from another test", n)
}
if err := open(ctx, db, "ada", tc.deposit); err != nil {
t.Fatalf("open: %v", err)
}
err := withdraw(ctx, db, "ada", tc.amount)
if (err != nil) != tc.wantErr {
t.Fatalf("withdraw error = %v, want error %v", err, tc.wantErr)
}
var balance int
db.QueryRow("SELECT balance FROM accounts WHERE owner = 'ada'").Scan(&balance)
if balance != tc.want {
t.Fatalf("balance = %d, want %d", balance, tc.want)
}
}))
}
run("a deliberately wrong expectation", func(t TB) {
db := newTestDB(t)
if err := withdraw(ctx, db, "nobody", 1); err == nil {
t.Fatalf("expected an error")
}
t.Fatalf("balance = %d, want %d", 0, 1)
})
distinct := map[string]bool{}
removed := 0
for _, d := range dirs {
distinct[d] = true
if _, err := os.Stat(d); errors.Is(err, os.ErrNotExist) {
removed++
}
}
fmt.Printf("%d cases used %d separate databases; %d removed after cleanup\n", len(dirs), len(distinct), removed)
}All three table cases pass, and none sees the account a previous case created, because each starts from an empty, freshly migrated file. The overdraw case passes because CHECK (balance >= 0) rejects the UPDATE and the balance stays 20. The deliberate failure prints its Fatalf message. The summary reports three cases, three distinct databases and three directories removed after cleanup.
The same helper in a _test.go file
In a real package the helper lives in a _test.go file or an internal testing package, and tests call it with *testing.T. Because each test owns its file, t.Parallel is safe at both levels: subtests run concurrently against separate databases, so there is no shared lock to wait on and no ordering dependency. t.Context, available since Go 1.24, is cancelled just before cleanup runs, which is a good default context for queries.
package store
import "testing"
func TestWithdraw(t *testing.T) {
t.Parallel()
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
db := newTestDB(t) // its own file in its own t.TempDir()
if err := open(t.Context(), db, "ada", tc.deposit); err != nil {
t.Fatal(err)
}
// ...
})
}
}The loop variable tc is per iteration since Go 1.22, so parallel subtests read their own case. Each subtest calls newTestDB(t) with its own t, which ties the database lifetime to that subtest rather than to the parent.
Why not :memory: or one shared database
A plain :memory: database exists per connection, so a pooled *sql.DB can run the migration on one connection and the query on another that sees an empty database. It works only with SetMaxOpenConns(1) and a pool that never closes its last connection, or with a named shared-memory URI that leaks state between tests using the same name. A temporary file avoids those traps, exercises WAL and locking like production, and is still fast because the operating system caches it. One database shared across parallel tests makes results depend on order and timing; give each test its own.
Keep tests fast
Most of a fresh database's cost is applying the schema. When the migration list grows, migrate one template file once per package in TestMain and copy it per test with VACUUM INTO or a plain file copy, since nothing else has it open. Test the migration runner itself separately, from an empty file and from saved old versions. Avoid sleeping to provoke SQLITE_BUSY; hold a transaction on one connection explicitly instead, so a concurrency test is deterministic.
TAKE THIS WITH YOU
Give every test its own migrated SQLite file in t.TempDir through a helper that uses Helper, Cleanup and Fatalf. Tests then use the real engine and schema, run in parallel without interference and leave nothing behind.
Check your understanding
Tests share one *sql.DB opened on ":memory:" and sometimes fail with "no such table". What is the cause?
Go to the source
Progress stays in this browser. No account needed.