From 4b81d8f8f28b915996fb3310fb7fe6008e5fdb07 Mon Sep 17 00:00:00 2001 From: Dhruv Thakur Date: Tue, 3 Sep 2024 12:10:37 +0200 Subject: [PATCH] test: add migration tests --- internal/persistence/migrations_test.go | 55 ++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 2 deletions(-) diff --git a/internal/persistence/migrations_test.go b/internal/persistence/migrations_test.go index 6a75da2..f97ac67 100644 --- a/internal/persistence/migrations_test.go +++ b/internal/persistence/migrations_test.go @@ -1,18 +1,69 @@ package persistence import ( + "database/sql" "testing" + + "github.com/stretchr/testify/assert" + _ "modernc.org/sqlite" // sqlite driver ) func TestMigrationsAreSetupCorrectly(t *testing.T) { + // GIVEN + // WHEN migrations := getMigrations() + + // THEN for i := 2; i <= latestDBVersion; i++ { m, ok := migrations[i] if !ok { - t.Errorf("couldn't get migration %d", i) + assert.True(t, ok, "couldn't get migration %d", i) } if m == "" { - t.Errorf("migration %d is empty", i) + assert.NotEmpty(t, ok, "migration %d is empty", i) } } } + +func TestMigrationsWork(t *testing.T) { + // GIVEN + var testDB *sql.DB + var err error + testDB, err = sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatalf("Couldn't open database: %s", err.Error()) + } + + err = InitDB(testDB) + if err != nil { + t.Fatalf("Couldn't initialize database: %s", err.Error()) + } + + // WHEN + err = UpgradeDB(testDB, 1) + + // THEN + assert.NoError(t, err) +} + +func TestRunMigrationFailsWhenGivenBadMigration(t *testing.T) { + // GIVEN + var testDB *sql.DB + var err error + testDB, err = sql.Open("sqlite", ":memory:") + if err != nil { + t.Fatalf("Couldn't open database: %s", err.Error()) + } + + err = InitDB(testDB) + if err != nil { + t.Fatalf("Couldn't initialize database: %s", err.Error()) + } + + // WHEN + query := "BAD SQL CODE;" + migrateErr := runMigration(testDB, query, 1) + + // THEN + assert.Error(t, migrateErr) +}