2022-02-16 12:30:49 +00:00
|
|
|
package initialise
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql/driver"
|
|
|
|
"regexp"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/DATA-DOG/go-sqlmock"
|
2024-04-03 10:43:43 +00:00
|
|
|
|
2023-10-19 10:19:10 +00:00
|
|
|
"github.com/zitadel/zitadel/internal/database"
|
2024-03-27 13:48:22 +00:00
|
|
|
db_mock "github.com/zitadel/zitadel/internal/database/mock"
|
2022-02-16 12:30:49 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type db struct {
|
|
|
|
mock sqlmock.Sqlmock
|
2023-10-19 10:19:10 +00:00
|
|
|
db *database.DB
|
2022-02-16 12:30:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func prepareDB(t *testing.T, expectations ...expectation) db {
|
|
|
|
t.Helper()
|
2024-03-27 13:48:22 +00:00
|
|
|
client, mock, err := sqlmock.New(sqlmock.ValueConverterOption(new(db_mock.TypeConverter)))
|
2022-02-16 12:30:49 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatalf("unable to create sql mock: %v", err)
|
|
|
|
}
|
|
|
|
for _, expectation := range expectations {
|
|
|
|
expectation(mock)
|
|
|
|
}
|
|
|
|
return db{
|
|
|
|
mock: mock,
|
2023-10-19 10:19:10 +00:00
|
|
|
db: &database.DB{DB: client},
|
2022-02-16 12:30:49 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
type expectation func(m sqlmock.Sqlmock)
|
|
|
|
|
|
|
|
func expectExec(stmt string, err error, args ...driver.Value) expectation {
|
|
|
|
return func(m sqlmock.Sqlmock) {
|
|
|
|
query := m.ExpectExec(regexp.QuoteMeta(stmt)).WithArgs(args...)
|
|
|
|
if err != nil {
|
|
|
|
query.WillReturnError(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
query.WillReturnResult(sqlmock.NewResult(1, 1))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-10-19 10:19:10 +00:00
|
|
|
func expectQuery(stmt string, err error, columns []string, rows [][]driver.Value, args ...driver.Value) expectation {
|
|
|
|
return func(m sqlmock.Sqlmock) {
|
2024-03-27 13:48:22 +00:00
|
|
|
res := m.NewRows(columns)
|
2023-10-19 10:19:10 +00:00
|
|
|
for _, row := range rows {
|
|
|
|
res.AddRow(row...)
|
|
|
|
}
|
|
|
|
query := m.ExpectQuery(regexp.QuoteMeta(stmt)).WithArgs(args...).WillReturnRows(res)
|
|
|
|
if err != nil {
|
|
|
|
query.WillReturnError(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-16 12:30:49 +00:00
|
|
|
func expectBegin(err error) expectation {
|
|
|
|
return func(m sqlmock.Sqlmock) {
|
|
|
|
query := m.ExpectBegin()
|
|
|
|
if err != nil {
|
|
|
|
query.WillReturnError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func expectCommit(err error) expectation {
|
|
|
|
return func(m sqlmock.Sqlmock) {
|
|
|
|
query := m.ExpectCommit()
|
|
|
|
if err != nil {
|
|
|
|
query.WillReturnError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func expectRollback(err error) expectation {
|
|
|
|
return func(m sqlmock.Sqlmock) {
|
|
|
|
query := m.ExpectRollback()
|
|
|
|
if err != nil {
|
|
|
|
query.WillReturnError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|