Something went wrong. Try again.
Simple homelab monitoring service
Something went wrong. Try again.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091package db
import ( "io" "os" "path" "strings" "testing"
"log/slog")
func TestNew(t *testing.T) { testCases := map[string]struct { path string err string cleanup bool }{ "can_create": { path: path.Join(os.TempDir(), "shouldwork.db"), cleanup: true, }, "cannot_create": { path: "/etc/shouldfail.db", err: "unable to open database file", }, }
logger := slog.New(slog.DiscardHandler) for name, tc := range testCases { t.Run(name, func(t *testing.T) { db, err := New(tc.path, logger) if tc.err != "" { if err == nil { t.Errorf("expected an error, got nil") return } if !strings.Contains(err.Error(), tc.err) { t.Errorf("got error '%s', want'%s'", err, tc.err) } return }
if tc.cleanup { db.Close() err := os.Remove(tc.path) if err != nil { t.Fatalf("could not delete test file: %q", err) } } }) }}
// newDB is a helper function that creates the new test database,// and provides teardown for it between tests. Given the amount// of data we deal with in tests, and the speed of SQLite, we just// use the in-memory database directly in tests.func newDB(dbpath string, testfile string, t *testing.T) *DB { logger := slog.New(slog.DiscardHandler) db, err := New(dbpath, logger) if err != nil { t.Error(err) }
// Mild hack for tests - using in-memory DB means we get two // separate databases for read/write, not one as for file-based // databases - so overwrite the default initialised readDB with // the write one. db.readDB = db.writeDB
if len(testfile) > 0 { f, err := os.Open(path.Join("./testdata", testfile)) if err != nil { t.Fatalf("could not open test file '%s': %v", testfile, err) } defer f.Close()
b, err := io.ReadAll(f) if err != nil { t.Fatalf("unable to read test file '%s': %v", testfile, err) }
if _, err := db.writeDB.Exec(string(b)); err != nil { t.Fatalf("unable to populate database with test data: %v", err) } }
return db}