Skip to content

Commit

Permalink
test: add migration tests
Browse files Browse the repository at this point in the history
  • Loading branch information
dhth committed Sep 3, 2024
1 parent d1137de commit 4b81d8f
Showing 1 changed file with 53 additions and 2 deletions.
55 changes: 53 additions & 2 deletions internal/persistence/migrations_test.go
Original file line number Diff line number Diff line change
@@ -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)
}

0 comments on commit 4b81d8f

Please sign in to comment.