package contratest import ( "database/sql" "io" "log/slog" "path/filepath" "sort" "testing" "github.com/carlosframework/rastrillo/db" contra "github.com/carlosframework/contra/internal/contra" ) // newDB opens a database the way main.go does, and hands back the handle // so a test can look at what the connection is actually configured to do. func newDB(t *testing.T) *db.DB { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) return d } // The storage settings web/1 (discussion 7) requires. The framework sets // them and we do not hand-roll them, but "the framework does it" is a // claim, and this is what turns it into a fact — including the pragma // ORDER, which is the part with teeth: busy_timeout has to be set before // journal_mode or concurrent opens crash. Order cannot be observed after // the fact, so what is checked here is the outcome it exists to produce. func TestDatabasePragmas(t *testing.T) { d := newDB(t) for _, c := range []struct { pragma string want string }{ {"journal_mode", "wal"}, {"busy_timeout", "5000"}, {"foreign_keys", "1"}, } { var got string if err := d.G.Raw("PRAGMA " + c.pragma).Scan(&got).Error; err != nil { t.Fatalf("PRAGMA %s: %v", c.pragma, err) } if got != c.want { t.Errorf("PRAGMA %s = %q, want %q", c.pragma, got, c.want) } } } // One writer connection, because SQLite has one writer and a pool of them // is a queue of lock contention wearing a pool's clothes. func TestWriterPoolIsSingleConnection(t *testing.T) { d := newDB(t) writer, err := d.G.DB() if err != nil { t.Fatalf("writer handle: %v", err) } if n := writer.Stats().MaxOpenConnections; n != 1 { t.Errorf("writer MaxOpenConnections = %d, want 1", n) } } // Migrations apply once and are never re-run. Building the app twice over // one database is the cheap proof: the second boot must apply nothing. func TestMigrationsApplyOnce(t *testing.T) { d := newDB(t) logger := slog.New(slog.NewTextHandler(io.Discard, nil)) if _, err := contra.App(d, testConfig(), logger); err != nil { t.Fatalf("first boot: %v", err) } before := tableNames(t, d) if _, err := contra.App(d, testConfig(), logger); err != nil { t.Fatalf("second boot: %v", err) } after := tableNames(t, d) if len(before) != len(after) { t.Errorf("second boot changed the schema:\n before %v\n after %v", before, after) } } // The bootstrap tripwire is gone, replaced by the thing it was holding the // door for: the merciless greps in greps_test.go. What is left here is the // narrower question of WHICH tables exist, which the greps do not ask. // // A table appearing without anybody deciding to add it is how a storage // surface arrives unnoticed. So the set is written down, each with its // owner, and a new one fails until somebody adds it here — and, on the same // commit, to the greps' write list. func TestSchemaIsTheDeclaredSet(t *testing.T) { d := newDB(t) logger := slog.New(slog.NewTextHandler(io.Discard, nil)) if _, err := contra.App(d, testConfig(), logger); err != nil { t.Fatalf("App: %v", err) } owners := map[string]string{ "rastrillo_migrations": "rastrillo/migrate — the migration ledger", "sessions": "rastrillo/sessions", "sqlite_sequence": "sqlite, for AUTOINCREMENT", // CONTRA's own. Every one holds ciphertext, public keys, opaque // random ids, or the parameters needed to hand the right blob back. "accounts": "an identity: a blind index, never an address", "login_keys": "public keys to verify signed challenges against", "wraps": "the three peer wraps of RK", "vaults": "a vault's existence and its drop-box public key", "vault_members": "vault keysets sealed to members — the sharing graph", "items": "one opaque blob per item, quantised into buckets", "login_challenges": "live sign-in state: a random nonce, deleted when spent", "signup_sessions": "an address proved but no account yet: a blind index and a token hash", "device_links": "a live handoff: a code hash, an ephemeral point, and an envelope the server has no key for", } found := map[string]bool{} for _, name := range tableNames(t, d) { found[name] = true if _, ok := owners[name]; !ok { t.Errorf("undeclared table %q. If you meant to add it: name its owner "+ "here, and add its write path to writeEverything in greps_test.go "+ "on this same commit. A storage surface lands with its canary or "+ "it does not land.", name) } } for name := range owners { if name == "sqlite_sequence" { continue // only exists once something AUTOINCREMENTs } if !found[name] { t.Errorf("declared table %q is missing: a migration did not apply", name) } } if len(contra.Models) == 0 { t.Error("contra.Models is empty, so `rastrillo migration check` is " + "comparing nothing against nothing") } } func tableNames(t *testing.T, d *db.DB) []string { t.Helper() var names []string rows, err := d.G.Raw( "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name").Rows() if err != nil { t.Fatalf("list tables: %v", err) } defer rows.Close() for rows.Next() { var n string if err := rows.Scan(&n); err != nil { t.Fatalf("scan table name: %v", err) } names = append(names, n) } if err := rows.Err(); err != nil && err != sql.ErrNoRows { t.Fatalf("list tables: %v", err) } sort.Strings(names) return names }