2021-01-05 19:50:39 +00:00
|
|
|
package sqlite
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/go-testfixtures/testfixtures/v3"
|
2021-01-17 16:37:16 +00:00
|
|
|
"github.com/mickael-menu/zk/util/opt"
|
2021-01-10 15:39:10 +00:00
|
|
|
"github.com/mickael-menu/zk/util/test/assert"
|
2021-01-05 19:50:39 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// testTransaction is an utility function used to test a SQLite transaction to
|
2021-01-17 16:37:16 +00:00
|
|
|
// the DB, which loads the default set of DB fixtures.
|
2021-01-05 19:50:39 +00:00
|
|
|
func testTransaction(t *testing.T, test func(tx Transaction)) {
|
2021-01-17 16:37:16 +00:00
|
|
|
testTransactionWithFixtures(t, opt.NewString("default"), test)
|
|
|
|
}
|
|
|
|
|
|
|
|
// testTransactionWithFixtures is an utility function used to test a SQLite transaction to
|
|
|
|
// the DB, which loads the given set of DB fixtures.
|
|
|
|
func testTransactionWithFixtures(t *testing.T, fixturesDir opt.String, test func(tx Transaction)) {
|
2021-01-05 19:50:39 +00:00
|
|
|
db, err := OpenInMemory()
|
|
|
|
assert.Nil(t, err)
|
2021-03-08 20:38:32 +00:00
|
|
|
_, err = db.Migrate()
|
2021-01-05 19:50:39 +00:00
|
|
|
assert.Nil(t, err)
|
|
|
|
|
2021-01-17 16:37:16 +00:00
|
|
|
if !fixturesDir.IsNull() {
|
|
|
|
fixtures, err := testfixtures.New(
|
|
|
|
testfixtures.Database(db.db),
|
|
|
|
testfixtures.Dialect("sqlite"),
|
|
|
|
testfixtures.Directory("fixtures/"+fixturesDir.String()),
|
|
|
|
// Necessary to work with an in-memory database.
|
|
|
|
testfixtures.DangerousSkipTestDatabaseCheck(),
|
|
|
|
)
|
|
|
|
assert.Nil(t, err)
|
|
|
|
err = fixtures.Load()
|
|
|
|
assert.Nil(t, err)
|
|
|
|
}
|
2021-01-05 19:50:39 +00:00
|
|
|
|
|
|
|
err = db.WithTransaction(func(tx Transaction) error {
|
|
|
|
test(tx)
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
assert.Nil(t, err)
|
|
|
|
}
|
2021-03-06 18:38:52 +00:00
|
|
|
|
|
|
|
func assertExistOrNot(t *testing.T, tx Transaction, shouldExist bool, sql string, args ...interface{}) {
|
|
|
|
if shouldExist {
|
|
|
|
assertExist(t, tx, sql, args...)
|
|
|
|
} else {
|
|
|
|
assertNotExist(t, tx, sql, args...)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func assertExist(t *testing.T, tx Transaction, sql string, args ...interface{}) {
|
|
|
|
if !exists(t, tx, sql, args...) {
|
|
|
|
t.Errorf("SQL query did not return any result: %s, with arguments %v", sql, args)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func assertNotExist(t *testing.T, tx Transaction, sql string, args ...interface{}) {
|
|
|
|
if exists(t, tx, sql, args...) {
|
|
|
|
t.Errorf("SQL query returned a result: %s, with arguments %v", sql, args)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func exists(t *testing.T, tx Transaction, sql string, args ...interface{}) bool {
|
|
|
|
var exists int
|
|
|
|
err := tx.QueryRow("SELECT EXISTS ("+sql+")", args...).Scan(&exists)
|
|
|
|
assert.Nil(t, err)
|
|
|
|
return exists == 1
|
|
|
|
}
|