91 lines
1.9 KiB
Go
91 lines
1.9 KiB
Go
package litemigrate_test
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"github.com/stretchr/testify/assert"
|
|
"lmika.dev/pkg/litemigrate"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
"testing/fstest"
|
|
|
|
_ "modernc.org/sqlite"
|
|
)
|
|
|
|
func TestMigrator_MigrateUp(t *testing.T) {
|
|
ctx := context.Background()
|
|
|
|
db, closeFn := newDB(t)
|
|
defer closeFn()
|
|
|
|
fileMigrated := make([]string, 0)
|
|
migrator := litemigrate.New(testMigration, db, litemigrate.WithPreStepHook(func(filename string) {
|
|
fileMigrated = append(fileMigrated, filename)
|
|
}))
|
|
|
|
// Check initial version
|
|
ver, err := migrator.Version(ctx)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, 0, ver)
|
|
|
|
// Run migration
|
|
err = migrator.MigrateUp(ctx)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, []string{"01_base_schema.up.sql", "02_insert_things.up.sql"}, fileMigrated)
|
|
|
|
// Check new version
|
|
ver, err = migrator.Version(ctx)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, 2, ver)
|
|
|
|
// Verify that migration worked
|
|
var some string
|
|
row := db.QueryRow(`SELECT some FROM thing LIMIT 1`)
|
|
err = row.Scan(&some)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, "bla", some)
|
|
|
|
fileMigrated = make([]string, 0)
|
|
|
|
// Check that running migration nops
|
|
err = migrator.MigrateUp(ctx)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, []string{}, fileMigrated)
|
|
|
|
ver, err = migrator.Version(ctx)
|
|
assert.NoError(t, err)
|
|
assert.Equal(t, 2, ver)
|
|
}
|
|
|
|
func newDB(t *testing.T) (*sql.DB, func()) {
|
|
t.Helper()
|
|
|
|
tmpDir, err := os.MkdirTemp("", "")
|
|
if err != nil {
|
|
t.Errorf("cannot create mkdir: %v", err)
|
|
}
|
|
|
|
drvr, err := sql.Open("sqlite", filepath.Join(tmpDir, "test.db"))
|
|
if err != nil {
|
|
t.Errorf("cannot open driver: %v", err)
|
|
}
|
|
|
|
return drvr, func() {
|
|
drvr.Close()
|
|
}
|
|
}
|
|
|
|
var testMigration = fstest.MapFS{
|
|
"01_base_schema.up.sql": {
|
|
Data: []byte(`
|
|
CREATE TABLE thing (some text);
|
|
`),
|
|
},
|
|
"02_insert_things.up.sql": {
|
|
Data: []byte(`
|
|
INSERT INTO thing (some) VALUES ("bla");
|
|
`),
|
|
},
|
|
}
|