check / check (push) Waiting to run
SQLite deletes a shared in-memory database when its last connection closes. A query cancelled while it runs makes the pool close its connection, so a test could lose all its tables and rows at random. NewTestDatabaseURL in internal/db returns the URL of a new in-memory database with a random name. It holds one connection to it open until the test ends. The db, handlers, ircserver, server and service tests now take their database URL from it. A new test cancels a query on such a database, checks with a TEMP table that the connection was replaced, and checks that a row is still there. Model: opus-5-5
68 lines
1.3 KiB
Go
68 lines
1.3 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"fmt"
|
|
"log/slog"
|
|
"testing"
|
|
)
|
|
|
|
// NewTestDatabase creates an in-memory database for testing.
|
|
func NewTestDatabase(tb testing.TB) (*Database, error) {
|
|
tb.Helper()
|
|
|
|
dsn := NewTestDatabaseURL(tb) + "&_pragma=foreign_keys(1)"
|
|
|
|
conn, err := sql.Open("sqlite", dsn)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("open test db: %w", err)
|
|
}
|
|
|
|
database := &Database{ //nolint:exhaustruct // test helper, params not needed
|
|
conn: conn,
|
|
log: slog.Default(),
|
|
}
|
|
|
|
err = database.runMigrations(context.Background())
|
|
if err != nil {
|
|
closeErr := conn.Close()
|
|
if closeErr != nil {
|
|
return nil, fmt.Errorf(
|
|
"close after migration failure: %w",
|
|
closeErr,
|
|
)
|
|
}
|
|
|
|
return nil, fmt.Errorf(
|
|
"run test migrations: %w", err,
|
|
)
|
|
}
|
|
|
|
return database, nil
|
|
}
|
|
|
|
// Close closes the underlying database connection.
|
|
func (database *Database) Close() error {
|
|
err := database.conn.Close()
|
|
if err != nil {
|
|
return fmt.Errorf("close database: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// ExecForTest runs a raw statement, such as a trigger that
|
|
// makes a write fail.
|
|
func (database *Database) ExecForTest(
|
|
ctx context.Context,
|
|
query string,
|
|
) error {
|
|
_, err := database.conn.ExecContext(ctx, query)
|
|
if err != nil {
|
|
return fmt.Errorf("exec for test: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|