add core lib

This commit is contained in:
2026-03-01 03:04:10 +01:00
parent 9a6818ea3c
commit baa764befd
22 changed files with 2353 additions and 0 deletions

View File

@@ -0,0 +1,77 @@
package migrate
import (
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
func TestResolveMigrationsPath(t *testing.T) {
if got := ResolveMigrationsPath(""); got != "file://migrations" && !strings.HasSuffix(got, "/migrations") {
t.Fatalf("expected default migrations path, got %q", got)
}
if got := ResolveMigrationsPath("file:///tmp/migs"); got != "file:///tmp/migs" {
t.Fatalf("expected passthrough file URI, got %q", got)
}
abs := filepath.Join(string(os.PathSeparator), "tmp", "migs")
if got := ResolveMigrationsPath(abs); got != "file://"+abs {
t.Fatalf("expected absolute path conversion, got %q", got)
}
rel := "migrations"
got := ResolveMigrationsPath(rel)
if !strings.HasPrefix(got, "file://") || !strings.HasSuffix(got, rel) {
t.Fatalf("expected file URI ending with %q, got %q", rel, got)
}
}
func TestRunWithTimeout(t *testing.T) {
if err := runWithTimeout(0, func() error { return nil }); err != nil {
t.Fatalf("expected no error for immediate execution, got %v", err)
}
if err := runWithTimeout(50*time.Millisecond, func() error {
time.Sleep(5 * time.Millisecond)
return nil
}); err != nil {
t.Fatalf("expected fn to finish before timeout, got %v", err)
}
err := runWithTimeout(10*time.Millisecond, func() error {
time.Sleep(50 * time.Millisecond)
return nil
})
if err == nil || !strings.Contains(err.Error(), "timed out") {
t.Fatalf("expected timeout error, got %v", err)
}
expected := errors.New("boom")
err = runWithTimeout(20*time.Millisecond, func() error { return expected })
if !errors.Is(err, expected) {
t.Fatalf("expected function error propagation, got %v", err)
}
}
func TestMigrationAPIs_InvalidSourcePath(t *testing.T) {
cfg := MigrationConfig{Path: "definitely-missing-migrations-dir"}
if err := RunMigrationsUp("postgres://ignored", cfg); err == nil {
t.Fatalf("expected RunMigrationsUp error for missing source path")
}
if err := RunMigrationsDown("postgres://ignored", cfg, 1); err == nil {
t.Fatalf("expected RunMigrationsDown error for missing source path")
}
if err := ForceMigrationVersion("postgres://ignored", cfg, 1); err == nil {
t.Fatalf("expected ForceMigrationVersion error for missing source path")
}
if _, err := GetMigrationStatus("postgres://ignored", cfg); err == nil {
t.Fatalf("expected GetMigrationStatus error for missing source path")
}
closeMigrator(nil)
}