aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorEugene Triguba <eugenetriguba@gmail.com>2024-03-02 09:29:41 -0500
committerEugene Triguba <eugenetriguba@gmail.com>2024-03-02 09:29:41 -0500
commit6760ae82d62449f41c68950264c02c40be81bfb3 (patch)
treef071906933642e93e789b5def170985f366171ce
parentAdd proper tests to revert service methods (diff)
downloadcli-6760ae82d62449f41c68950264c02c40be81bfb3.zip
Improve coverage for separate Tx methods
-rw-r--r--internal/bolttest/mock_sql_db.go53
-rw-r--r--internal/repositories/migration_db_repo.go19
-rw-r--r--internal/repositories/migration_db_repo_test.go188
3 files changed, 216 insertions, 44 deletions
diff --git a/internal/bolttest/mock_sql_db.go b/internal/bolttest/mock_sql_db.go
new file mode 100644
index 0000000..0c12592
--- /dev/null
+++ b/internal/bolttest/mock_sql_db.go
@@ -0,0 +1,53 @@
+package bolttest
+
+import "database/sql"
+
+type MockSqlDb struct {
+ ExecReturnValue ExecReturnValue
+ ExecCallCount int
+ QueryReturnValue QueryReturnValue
+ QueryCallCount int
+ QueryRowReturnValue QueryRowReturnValue
+ QueryRowCallCount int
+ BeginReturnValue BeginReturnValue
+ BeginCallCount int
+}
+
+type ExecReturnValue struct {
+ Result sql.Result
+ Err error
+}
+
+type QueryReturnValue struct {
+ Rows *sql.Rows
+ Err error
+}
+
+type QueryRowReturnValue struct {
+ Row *sql.Row
+}
+
+type BeginReturnValue struct {
+ Tx *sql.Tx
+ Err error
+}
+
+func (db *MockSqlDb) Exec(query string, args ...any) (sql.Result, error) {
+ db.ExecCallCount += 1
+ return db.ExecReturnValue.Result, db.ExecReturnValue.Err
+}
+
+func (db *MockSqlDb) Query(query string, args ...any) (*sql.Rows, error) {
+ db.QueryCallCount += 1
+ return db.QueryReturnValue.Rows, db.QueryReturnValue.Err
+}
+
+func (db *MockSqlDb) QueryRow(query string, args ...any) *sql.Row {
+ db.QueryRowCallCount += 1
+ return db.QueryRowReturnValue.Row
+}
+
+func (db *MockSqlDb) Begin() (*sql.Tx, error) {
+ db.BeginCallCount += 1
+ return db.BeginReturnValue.Tx, db.BeginReturnValue.Err
+}
diff --git a/internal/repositories/migration_db_repo.go b/internal/repositories/migration_db_repo.go
index 500fea4..7a90a2a 100644
--- a/internal/repositories/migration_db_repo.go
+++ b/internal/repositories/migration_db_repo.go
@@ -9,10 +9,17 @@ import (
"github.com/eugenetriguba/bolt/internal/models"
)
-type SQLExecutor interface {
+type sqlExecutor interface {
Exec(query string, args ...interface{}) (sql.Result, error)
}
+type SqlDb interface {
+ Exec(query string, args ...any) (sql.Result, error)
+ Query(query string, args ...any) (*sql.Rows, error)
+ QueryRow(query string, args ...any) *sql.Row
+ Begin() (*sql.Tx, error)
+}
+
type MigrationDBRepo interface {
List() (map[string]*models.Migration, error)
IsApplied(version string) (bool, error)
@@ -23,14 +30,14 @@ type MigrationDBRepo interface {
}
type migrationDBRepo struct {
- db *sql.DB
+ db SqlDb
}
// NewMigrationDBRepo initializes the MigrationDBRepo with a
// database. Furthermore, it ensures the migration table it
// operates on exists. If it is unable to create or confirm
// the table exists, an error is returned.
-func NewMigrationDBRepo(db *sql.DB) (MigrationDBRepo, error) {
+func NewMigrationDBRepo(db SqlDb) (MigrationDBRepo, error) {
_, err := db.Exec(`
CREATE TABLE IF NOT EXISTS bolt_migrations(
version CHARACTER(14) PRIMARY KEY NOT NULL
@@ -38,7 +45,7 @@ func NewMigrationDBRepo(db *sql.DB) (MigrationDBRepo, error) {
`)
if err != nil {
return nil, fmt.Errorf(
- "unable to create bolt_migrations database table: %w",
+ "unable to confirm bolt_migrations database table exists: %w",
err,
)
}
@@ -157,7 +164,7 @@ func (mr migrationDBRepo) ApplyWithTx(
}
func applyMigration(
- executor SQLExecutor,
+ executor sqlExecutor,
upgradeScript string,
migration models.Migration,
) error {
@@ -229,7 +236,7 @@ func (mr migrationDBRepo) RevertWithTx(
}
func revertMigration(
- executor SQLExecutor,
+ executor sqlExecutor,
downgradeScript string,
migration models.Migration,
) error {
diff --git a/internal/repositories/migration_db_repo_test.go b/internal/repositories/migration_db_repo_test.go
index 9f4f9e8..2775faa 100644
--- a/internal/repositories/migration_db_repo_test.go
+++ b/internal/repositories/migration_db_repo_test.go
@@ -2,6 +2,7 @@ package repositories_test
import (
"database/sql"
+ "errors"
"testing"
"time"
@@ -11,7 +12,7 @@ import (
"github.com/eugenetriguba/checkmate/assert"
)
-func TestMigrationDBRepo_NewMigrationDBRepoCreatesTable(t *testing.T) {
+func TestNewMigrationDBRepo_CreatesTable(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
row := db.QueryRow(`
SELECT 1
@@ -36,7 +37,7 @@ func TestMigrationDBRepo_NewMigrationDBRepoCreatesTable(t *testing.T) {
assert.Nil(t, err)
}
-func TestMigrationDBRepo_NewMigrationDBRepoLeavesCurrentTable(t *testing.T) {
+func TestNewMigrationDBRepo_TableAlreadyExists(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
_, err := db.Exec(`CREATE TABLE bolt_migrations(id INT NOT NULL PRIMARY KEY)`)
assert.Nil(t, err)
@@ -53,7 +54,20 @@ func TestMigrationDBRepo_NewMigrationDBRepoLeavesCurrentTable(t *testing.T) {
assert.Equal(t, scanResult, 1)
}
-func TestMigrationDBRepo_ListWithEmptyTable(t *testing.T) {
+func TestNewMigrationDBRepo_TableCreationErr(t *testing.T) {
+ expectedErr := errors.New("error!")
+ db := bolttest.MockSqlDb{
+ ExecReturnValue: bolttest.ExecReturnValue{
+ Err: expectedErr,
+ },
+ }
+
+ _, err := repositories.NewMigrationDBRepo(&db)
+
+ assert.ErrorIs(t, err, expectedErr)
+}
+
+func TestList_EmptyTable(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
@@ -63,7 +77,22 @@ func TestMigrationDBRepo_ListWithEmptyTable(t *testing.T) {
assert.Equal(t, len(migrations), 0)
}
-func TestMigrationDBRepo_ListWithSingleResult(t *testing.T) {
+func TestList_QueryErr(t *testing.T) {
+ expectedErr := errors.New("error!")
+ db := bolttest.MockSqlDb{
+ QueryReturnValue: bolttest.QueryReturnValue{
+ Err: expectedErr,
+ },
+ }
+ repo, err := repositories.NewMigrationDBRepo(&db)
+ assert.Nil(t, err)
+
+ _, err = repo.List()
+
+ assert.ErrorIs(t, err, expectedErr)
+}
+
+func TestList_SingleResult(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
@@ -82,7 +111,7 @@ func TestMigrationDBRepo_ListWithSingleResult(t *testing.T) {
)
}
-func TestMigrationDBRepo_ListWithShortVersion(t *testing.T) {
+func TestList_ShortVersion(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
@@ -101,7 +130,7 @@ func TestMigrationDBRepo_ListWithShortVersion(t *testing.T) {
)
}
-func TestMigrationDBRepo_IsAppliedWithNotApplied(t *testing.T) {
+func TestIsApplied_WithNotApplied(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
@@ -112,7 +141,7 @@ func TestMigrationDBRepo_IsAppliedWithNotApplied(t *testing.T) {
assert.Equal(t, applied, false)
}
-func TestMigrationDBRepo_IsAppliedWithApplied(t *testing.T) {
+func TestIsApplied_WithApplied(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
@@ -126,7 +155,7 @@ func TestMigrationDBRepo_IsAppliedWithApplied(t *testing.T) {
assert.Equal(t, applied, true)
}
-func TestMigrationDBRepo_Apply(t *testing.T) {
+func TestApply(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
@@ -150,7 +179,69 @@ func TestMigrationDBRepo_Apply(t *testing.T) {
assert.Equal(t, applied, true)
}
-func TestMigrationDBRepo_Revert(t *testing.T) {
+func TestApply_MalformedSql(t *testing.T) {
+ db := bolttest.NewTestDB(t, "postgres")
+ repo, err := repositories.NewMigrationDBRepo(db)
+ assert.Nil(t, err)
+ migration := models.NewTimestampMigration(time.Now(), "test")
+
+ err = repo.Apply("this is not SQL", migration)
+ assert.ErrorContains(t, err, "syntax error")
+ assert.Equal(t, migration.Applied, false)
+}
+
+func TestApplyWithTx_BeginErr(t *testing.T) {
+ expectedErr := errors.New("error!")
+ db := bolttest.MockSqlDb{
+ BeginReturnValue: bolttest.BeginReturnValue{
+ Err: expectedErr,
+ },
+ }
+ repo, err := repositories.NewMigrationDBRepo(&db)
+ assert.Nil(t, err)
+ migration := models.NewTimestampMigration(time.Now(), "test")
+
+ err = repo.ApplyWithTx("SELECT 1 FROM bolt_migrations;", migration)
+
+ assert.ErrorIs(t, err, expectedErr)
+}
+
+func TestApplyWithTx_ExecErr(t *testing.T) {
+ db := bolttest.NewTestDB(t, "postgres")
+ repo, err := repositories.NewMigrationDBRepo(db)
+ assert.Nil(t, err)
+ migration := models.NewTimestampMigration(time.Now(), "test")
+
+ err = repo.ApplyWithTx("SELECT 1 FROM abc123donotexist;", migration)
+
+ assert.ErrorContains(t, err, `relation "abc123donotexist" does not exist`)
+}
+
+func TestApplyWithTx_SuccessfullyApplied(t *testing.T) {
+ db := bolttest.NewTestDB(t, "postgres")
+ repo, err := repositories.NewMigrationDBRepo(db)
+ assert.Nil(t, err)
+
+ migration := models.NewTimestampMigration(time.Now(), "test")
+ err = repo.ApplyWithTx(`CREATE TABLE tmp(id INT NOT NULL PRIMARY KEY)`, migration)
+ assert.Nil(t, err)
+ assert.Equal(t, migration.Applied, true)
+
+ row := db.QueryRow(`
+ SELECT 1
+ FROM INFORMATION_SCHEMA.TABLES
+ WHERE TABLE_SCHEMA = 'public'
+ AND TABLE_NAME = 'tmp'
+ `)
+ var scanResult int
+ err = row.Scan(&scanResult)
+ assert.Nil(t, err)
+ applied, err := repo.IsApplied(migration.Version)
+ assert.Nil(t, err)
+ assert.Equal(t, applied, true)
+}
+
+func TestRevert(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
@@ -187,57 +278,78 @@ func TestMigrationDBRepo_Revert(t *testing.T) {
assert.Equal(t, count, 0)
}
-func TestMigrationDBRepo_ApplyAndRevertWithoutTransaction(t *testing.T) {
+func TestRevert_MalformedSql(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
- _, err = db.Exec("CREATE TABLE tmp(id INT PRIMARY KEY, id2 INT, id3 INT)")
- assert.Nil(t, err)
-
migration := models.NewTimestampMigration(time.Now(), "test")
- // CREATE INDEX CONCURRENTLY cannot run inside a transaction.
- err = repo.Apply(
- `-- bolt: no-transaction\nCREATE INDEX CONCURRENTLY i1 ON tmp(id2);`,
- migration,
- )
- assert.Nil(t, err)
+ migration.Applied = true
+
+ err = repo.Revert("this is not SQL", migration)
+ assert.ErrorContains(t, err, "syntax error")
assert.Equal(t, migration.Applied, true)
+}
- err = repo.Revert(
- "-- bolt: no-transaction\nCREATE INDEX CONCURRENTLY i2 ON tmp(id3);",
- migration,
- )
+func TestRevertWithTx_BeginErr(t *testing.T) {
+ expectedErr := errors.New("error!")
+ db := bolttest.MockSqlDb{
+ BeginReturnValue: bolttest.BeginReturnValue{
+ Err: expectedErr,
+ },
+ }
+ repo, err := repositories.NewMigrationDBRepo(&db)
assert.Nil(t, err)
- assert.Equal(t, migration.Applied, false)
+ migration := models.NewTimestampMigration(time.Now(), "test")
+
+ err = repo.RevertWithTx("DROP TABLE bolt_migrations;", migration)
+
+ assert.ErrorIs(t, err, expectedErr)
}
-func TestMigrationDBRepo_ApplyMalformedSql(t *testing.T) {
+func TestRevertWithTx_ExecErr(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
migration := models.NewTimestampMigration(time.Now(), "test")
- err = repo.Apply("this is not SQL", migration)
- assert.ErrorContains(t, err, "syntax error")
- assert.Equal(t, migration.Applied, false)
+ err = repo.RevertWithTx("DROP TABLE abc123donotexist;", migration)
- err = repo.Apply("-- bolt: no-transaction\nthis is not SQL", migration)
- assert.ErrorContains(t, err, "syntax error")
- assert.Equal(t, migration.Applied, false)
+ assert.ErrorContains(t, err, `table "abc123donotexist" does not exist`)
}
-func TestMigrationDBRepo_RevertMalformedSql(t *testing.T) {
+func TestRevertWithTx_SuccessfullyReverted(t *testing.T) {
db := bolttest.NewTestDB(t, "postgres")
repo, err := repositories.NewMigrationDBRepo(db)
assert.Nil(t, err)
+
+ _, err = db.Exec(`CREATE TABLE tmp(id INT NOT NULL PRIMARY KEY)`)
+ assert.Nil(t, err)
+
migration := models.NewTimestampMigration(time.Now(), "test")
+ _, err = db.Exec(
+ `INSERT INTO bolt_migrations(version) VALUES ($1);`,
+ migration.Version,
+ )
+ assert.Nil(t, err)
migration.Applied = true
- err = repo.Revert("this is not SQL", migration)
- assert.ErrorContains(t, err, "syntax error")
- assert.Equal(t, migration.Applied, true)
+ err = repo.RevertWithTx(`DROP TABLE tmp;`, migration)
+ assert.Nil(t, err)
+ assert.Equal(t, migration.Applied, false)
- err = repo.Revert("-- bolt: no-transaction\nthis is not SQL", migration)
- assert.ErrorContains(t, err, "syntax error")
- assert.Equal(t, migration.Applied, true)
+ row := db.QueryRow(`
+ SELECT 1
+ FROM INFORMATION_SCHEMA.TABLES
+ WHERE TABLE_SCHEMA = 'public'
+ AND TABLE_NAME = 'tmp'
+ `)
+ var scanResult int
+ err = row.Scan(&scanResult)
+ assert.ErrorIs(t, err, sql.ErrNoRows)
+
+ row = db.QueryRow(`SELECT count(*) FROM bolt_migrations`)
+ var count int
+ err = row.Scan(&count)
+ assert.Nil(t, err)
+ assert.Equal(t, count, 0)
}