Add database package
This commit is contained in:
@@ -0,0 +1,59 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// createDB sets up a real SQLite database in a temporary directory
|
||||
// and returns the connection. The temporary directory is cleaned up
|
||||
// when the test ends. The caller is responsible for applying the schema.
|
||||
func createDB(t *testing.T) *SQLite {
|
||||
t.Helper()
|
||||
|
||||
var (
|
||||
dir = t.TempDir()
|
||||
path = filepath.Join(dir, "test.db")
|
||||
)
|
||||
db, err := Connect(t.Context(), Config{Path: path})
|
||||
if err != nil {
|
||||
t.Fatalf("Connect: %v", err)
|
||||
}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
func TestDB(t *testing.T) {
|
||||
testConnect(t, t.Context())
|
||||
}
|
||||
|
||||
func testConnect(t *testing.T, ctx context.Context) {
|
||||
// Test bad path.
|
||||
_, err := Connect(ctx, Config{Path: "/nonexistent/directory/test.db"})
|
||||
if err == nil {
|
||||
t.Fatal("expected error connecting to bad path")
|
||||
}
|
||||
|
||||
// Test connect.
|
||||
path := filepath.Join(t.TempDir(), "test.db")
|
||||
db, err := Connect(ctx, Config{Path: path})
|
||||
if err != nil {
|
||||
t.Fatalf("Connect: %v", err)
|
||||
}
|
||||
if db.Writer == nil {
|
||||
t.Fatal("Writer is nil")
|
||||
}
|
||||
if db.Reader == nil {
|
||||
t.Fatal("Reader is nil")
|
||||
}
|
||||
|
||||
// Test close.
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatalf("Close: %v", err)
|
||||
}
|
||||
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||
t.Fatal("database file does not exist")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user