86 lines
2.3 KiB
Go
86 lines
2.3 KiB
Go
package database_test
|
|
|
|
import (
|
|
"os"
|
|
"regexp"
|
|
"testing"
|
|
|
|
"github.com/DATA-DOG/go-sqlmock"
|
|
"github.com/rede5/gohorsejobs/backend/internal/database"
|
|
)
|
|
|
|
func TestBuildConnectionString(t *testing.T) {
|
|
// Backup env vars
|
|
oldURL := os.Getenv("DATABASE_URL")
|
|
|
|
defer func() {
|
|
os.Setenv("DATABASE_URL", oldURL)
|
|
}()
|
|
|
|
// Case 1: DATABASE_URL
|
|
os.Setenv("DATABASE_URL", "postgres://foo:bar@localhost:5432/db?sslmode=disable")
|
|
s, err := database.BuildConnectionString()
|
|
if err != nil {
|
|
t.Errorf("Unexpected error: %v", err)
|
|
}
|
|
if s != "postgres://foo:bar@localhost:5432/db?sslmode=disable" {
|
|
t.Errorf("Mismatch URL")
|
|
}
|
|
|
|
// Case 2: Missing DATABASE_URL
|
|
os.Unsetenv("DATABASE_URL")
|
|
_, err = database.BuildConnectionString()
|
|
if err == nil {
|
|
t.Error("Expected error for missing DATABASE_URL")
|
|
}
|
|
}
|
|
|
|
func TestRunMigrations(t *testing.T) {
|
|
// Setup Mock DB
|
|
db, mock, err := sqlmock.New()
|
|
if err != nil {
|
|
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
|
|
}
|
|
defer db.Close()
|
|
|
|
// Inject DB
|
|
database.DB = db
|
|
|
|
// Create temp migrations dir
|
|
err = os.Mkdir("migrations", 0755)
|
|
if err != nil && !os.IsExist(err) {
|
|
t.Fatalf("Failed to create migrations dir: %v", err)
|
|
}
|
|
defer os.RemoveAll("migrations")
|
|
|
|
// Create dummy migration file
|
|
content := "CREATE TABLE test (id int);"
|
|
err = os.WriteFile("migrations/001_test.sql", []byte(content), 0644)
|
|
if err != nil {
|
|
t.Fatalf("Failed to write migration file: %v", err)
|
|
}
|
|
|
|
// Mock Expectations
|
|
mock.ExpectExec(regexp.QuoteMeta(`
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
filename TEXT PRIMARY KEY,
|
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
)
|
|
`)).WillReturnResult(sqlmock.NewResult(0, 0))
|
|
mock.ExpectQuery(regexp.QuoteMeta("SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE filename = $1)")).
|
|
WithArgs("001_test.sql").
|
|
WillReturnRows(sqlmock.NewRows([]string{"exists"}).AddRow(false))
|
|
mock.ExpectBegin()
|
|
mock.ExpectExec(regexp.QuoteMeta(content)).WillReturnResult(sqlmock.NewResult(0, 0))
|
|
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO schema_migrations (filename) VALUES ($1)")).
|
|
WithArgs("001_test.sql").
|
|
WillReturnResult(sqlmock.NewResult(1, 1))
|
|
mock.ExpectCommit()
|
|
|
|
// Run
|
|
database.RunMigrations()
|
|
|
|
if err := mock.ExpectationsWereMet(); err != nil {
|
|
t.Errorf("there were unfulfilled expectations: %s", err)
|
|
}
|
|
}
|