Phase 1: database schema, migrations, repository, user seeding

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Jānis Kacēns
2026-05-11 11:38:31 +03:00
parent 34eb47b595
commit 0bc9160d97
8 changed files with 668 additions and 1 deletions
+72
View File
@@ -0,0 +1,72 @@
package db_test
import (
"os"
"path/filepath"
"testing"
"qbank/internal/config"
"qbank/internal/db"
)
func TestOpenAndSeed(t *testing.T) {
dir := t.TempDir()
dbPath := filepath.Join(dir, "test.db")
database, err := db.Open(dbPath)
if err != nil {
t.Fatalf("Open: %v", err)
}
defer database.Close()
// All tables must exist.
tables := []string{"users", "questions", "answers", "tests", "test_answers", "user_question_stats"}
for _, table := range tables {
var name string
err := database.QueryRow(
"SELECT name FROM sqlite_master WHERE type='table' AND name=?", table,
).Scan(&name)
if err != nil {
t.Errorf("table %q missing: %v", table, err)
}
}
// Seed two users.
users := []config.AdminUser{
{Name: "alice", Password: "pass1"},
{Name: "bob", Password: "pass2"},
}
if err := db.Seed(database, users); err != nil {
t.Fatalf("Seed: %v", err)
}
var count int
database.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
if count != 2 {
t.Errorf("want 2 users, got %d", count)
}
// Second Seed call must be a no-op (users table non-empty).
if err := db.Seed(database, users); err != nil {
t.Fatalf("second Seed: %v", err)
}
database.QueryRow("SELECT COUNT(*) FROM users").Scan(&count)
if count != 2 {
t.Errorf("after second seed: want 2 users, got %d", count)
}
// GetUserByName must find alice.
repo := db.New(database)
u, err := repo.GetUserByName("alice")
if err != nil {
t.Fatalf("GetUserByName: %v", err)
}
if u.Name != "alice" {
t.Errorf("want alice, got %q", u.Name)
}
if u.PasswordHash == "" {
t.Error("password hash is empty")
}
_ = os.Remove(dbPath)
}