0bc9160d97
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
73 lines
1.6 KiB
Go
73 lines
1.6 KiB
Go
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)
|
|
}
|