jet/internal/testutils/test_utils.go

300 lines
8.6 KiB
Go
Raw Normal View History

2019-07-29 18:08:53 +02:00
package testutils
import (
"bytes"
2022-05-05 13:01:42 +02:00
"context"
"database/sql"
2019-07-29 18:08:53 +02:00
"encoding/json"
"fmt"
2020-06-27 18:48:19 +02:00
"github.com/go-jet/jet/v2/internal/jet"
"github.com/go-jet/jet/v2/internal/utils/throw"
2020-06-27 18:48:19 +02:00
"github.com/go-jet/jet/v2/qrm"
"github.com/google/go-cmp/cmp"
2020-05-02 22:15:38 +02:00
"github.com/google/uuid"
2021-05-03 18:48:15 +02:00
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
2019-08-08 10:51:59 +02:00
"os"
"path/filepath"
2019-07-29 18:08:53 +02:00
"runtime"
"testing"
2020-05-02 22:15:38 +02:00
"time"
2019-07-29 18:08:53 +02:00
)
// UnixTimeComparer will compare time equality while ignoring time zone
var UnixTimeComparer = cmp.Comparer(func(t1, t2 time.Time) bool {
return t1.Unix() == t2.Unix()
})
2022-05-05 13:01:42 +02:00
// AssertExecAndRollback will execute and rollback statement in sql transaction
func AssertExecAndRollback(t *testing.T, stmt jet.Statement, db *sql.DB, rowsAffected ...int64) {
tx, err := db.Begin()
require.NoError(t, err)
defer func() {
err := tx.Rollback()
require.NoError(t, err)
}()
AssertExec(t, stmt, tx, rowsAffected...)
}
2019-08-17 18:32:01 +02:00
// AssertExec assert statement execution for successful execution and number of rows affected
func AssertExec(t *testing.T, stmt jet.Statement, db qrm.DB, rowsAffected ...int64) {
2019-08-02 11:08:24 +02:00
res, err := stmt.Exec(db)
require.NoError(t, err)
2019-08-02 11:08:24 +02:00
rows, err := res.RowsAffected()
require.NoError(t, err)
2019-08-02 11:08:24 +02:00
if len(rowsAffected) > 0 {
2020-06-01 20:30:09 +02:00
require.Equal(t, rowsAffected[0], rows)
2019-08-02 11:08:24 +02:00
}
}
2022-05-05 13:01:42 +02:00
// ExecuteInTxAndRollback will execute function in sql transaction and then rollback transaction
func ExecuteInTxAndRollback(t *testing.T, db *sql.DB, f func(tx *sql.Tx)) {
tx, err := db.Begin()
require.NoError(t, err)
defer func() {
err := tx.Rollback()
require.NoError(t, err)
}()
f(tx)
}
2019-08-17 18:32:01 +02:00
// AssertExecErr assert statement execution for failed execution with error string errorStr
func AssertExecErr(t *testing.T, stmt jet.Statement, db qrm.DB, errorStr string) {
2019-08-02 11:08:24 +02:00
_, err := stmt.Exec(db)
require.Error(t, err, errorStr)
2019-08-02 11:08:24 +02:00
}
2022-05-05 13:01:42 +02:00
// AssertExecContextErr assert statement execution for failed execution with error string errorStr
func AssertExecContextErr(ctx context.Context, t *testing.T, stmt jet.Statement, db qrm.DB, errorStr string) {
2022-05-05 13:01:42 +02:00
_, err := stmt.ExecContext(ctx, db)
require.Error(t, err, errorStr)
}
2019-08-08 10:51:59 +02:00
func getFullPath(relativePath string) string {
2020-06-27 18:48:19 +02:00
path, _ := os.Getwd()
return filepath.Join(path, "../", relativePath)
2019-08-08 10:51:59 +02:00
}
2019-08-17 18:32:01 +02:00
// PrintJson print v as json
2019-08-08 10:51:59 +02:00
func PrintJson(v interface{}) {
jsonText, _ := json.MarshalIndent(v, "", "\t")
fmt.Println(string(jsonText))
}
// ToJSON converts v into json string
func ToJSON(v interface{}) string {
jsonText, _ := json.MarshalIndent(v, "", "\t")
return string(jsonText)
}
2019-08-17 18:32:01 +02:00
// AssertJSON check if data json output is the same as expectedJSON
func AssertJSON(t *testing.T, data interface{}, expectedJSON string) {
2019-07-29 18:08:53 +02:00
jsonData, err := json.MarshalIndent(data, "", "\t")
require.NoError(t, err)
2019-07-29 18:08:53 +02:00
2022-02-09 12:41:58 +01:00
dataJson := "\n" + string(jsonData) + "\n"
require.Equal(t, dataJson, expectedJSON)
2019-07-29 18:08:53 +02:00
}
2019-08-17 18:32:01 +02:00
// SaveJSONFile saves v as json at testRelativePath
func SaveJSONFile(v interface{}, testRelativePath string) {
2019-08-08 10:51:59 +02:00
jsonText, _ := json.MarshalIndent(v, "", "\t")
filePath := getFullPath(testRelativePath)
err := os.WriteFile(filePath, jsonText, 0644)
2019-08-08 10:51:59 +02:00
throw.OnError(err)
2019-08-08 10:51:59 +02:00
}
2019-08-17 18:32:01 +02:00
// AssertJSONFile check if data json representation is the same as json at testRelativePath
2019-08-08 10:51:59 +02:00
func AssertJSONFile(t *testing.T, data interface{}, testRelativePath string) {
filePath := getFullPath(testRelativePath)
fileJSONData, err := os.ReadFile(filePath)
require.NoError(t, err)
2019-07-29 18:08:53 +02:00
if runtime.GOOS == "windows" {
fileJSONData = bytes.Replace(fileJSONData, []byte("\r\n"), []byte("\n"), -1)
}
jsonData, err := json.MarshalIndent(data, "", "\t")
require.NoError(t, err)
2019-07-29 18:08:53 +02:00
require.True(t, string(fileJSONData) == string(jsonData))
//AssertDeepEqual(t, string(fileJSONData), string(jsonData))
2019-07-29 18:08:53 +02:00
}
2019-08-17 18:32:01 +02:00
// AssertStatementSql check if statement Sql() is the same as expectedQuery and expectedArgs
2019-07-29 18:08:53 +02:00
func AssertStatementSql(t *testing.T, query jet.Statement, expectedQuery string, expectedArgs ...interface{}) {
queryStr, args := query.Sql()
assertQueryString(t, queryStr, expectedQuery)
2019-07-30 15:04:36 +02:00
2019-07-31 13:02:30 +02:00
if len(expectedArgs) == 0 {
return
}
AssertDeepEqual(t, args, expectedArgs)
2019-07-30 11:18:12 +02:00
}
2019-08-17 18:32:01 +02:00
// AssertStatementSqlErr checks if statement Sql() panics with errorStr
2019-08-12 12:11:16 +02:00
func AssertStatementSqlErr(t *testing.T, stmt jet.Statement, errorStr string) {
defer func() {
r := recover()
require.Equal(t, r, errorStr)
}()
2019-08-12 12:11:16 +02:00
stmt.Sql()
2019-08-12 12:11:16 +02:00
}
2019-08-17 18:32:01 +02:00
// AssertDebugStatementSql check if statement Sql() is the same as expectedQuery
2019-07-30 11:18:12 +02:00
func AssertDebugStatementSql(t *testing.T, query jet.Statement, expectedQuery string, expectedArgs ...interface{}) {
_, args := query.Sql()
if len(expectedArgs) > 0 {
AssertDeepEqual(t, args, expectedArgs)
}
2019-07-29 18:08:53 +02:00
debugSql := query.DebugSql()
assertQueryString(t, debugSql, expectedQuery)
2019-07-29 18:08:53 +02:00
}
// AssertSerialize checks if clause serialize produces expected query and args
func AssertSerialize(t *testing.T, dialect jet.Dialect, serializer jet.Serializer, query string, args ...interface{}) {
2019-08-17 18:32:01 +02:00
out := jet.SQLBuilder{Dialect: dialect}
jet.Serialize(serializer, jet.SelectStatementType, &out)
2019-07-31 18:43:54 +02:00
2019-08-12 12:11:16 +02:00
//fmt.Println(out.Buff.String())
2019-07-31 18:43:54 +02:00
AssertDeepEqual(t, out.Buff.String(), query)
2019-08-13 10:16:26 +02:00
if len(args) > 0 {
AssertDeepEqual(t, out.Args, args)
2019-08-13 10:16:26 +02:00
}
2019-07-31 18:43:54 +02:00
}
// AssertDebugSerialize checks if clause serialize produces expected debug query and args
func AssertDebugSerialize(t *testing.T, dialect jet.Dialect, clause jet.Serializer, query string, args ...interface{}) {
out := jet.SQLBuilder{Dialect: dialect, Debug: true}
jet.Serialize(clause, jet.SelectStatementType, &out)
AssertDeepEqual(t, out.Buff.String(), query)
if len(args) > 0 {
AssertDeepEqual(t, out.Args, args)
}
}
// AssertClauseSerialize checks if clause serialize produces expected query and args
func AssertClauseSerialize(t *testing.T, dialect jet.Dialect, clause jet.Clause, query string, args ...interface{}) {
out := jet.SQLBuilder{Dialect: dialect}
clause.Serialize(jet.SelectStatementType, &out)
require.Equal(t, out.Buff.String(), query)
if len(args) > 0 {
AssertDeepEqual(t, out.Args, args)
}
}
// AssertPanicErr checks if running a function fun produces a panic with errorStr string
func AssertPanicErr(t *testing.T, fun func(), errorStr string) {
defer func() {
r := recover()
require.Equal(t, r, errorStr)
}()
fun()
}
// AssertSerializeErr check if clause serialize panics with errString
func AssertSerializeErr(t *testing.T, dialect jet.Dialect, clause jet.Serializer, errString string) {
defer func() {
r := recover()
require.Equal(t, r, errString)
}()
2019-07-31 18:43:54 +02:00
2019-08-17 18:32:01 +02:00
out := jet.SQLBuilder{Dialect: dialect}
jet.Serialize(clause, jet.SelectStatementType, &out)
2019-07-31 18:43:54 +02:00
}
2019-08-17 18:32:01 +02:00
// AssertProjectionSerialize check if projection serialize produces expected query and args
2019-08-12 12:11:16 +02:00
func AssertProjectionSerialize(t *testing.T, dialect jet.Dialect, projection jet.Projection, query string, args ...interface{}) {
2019-08-17 18:32:01 +02:00
out := jet.SQLBuilder{Dialect: dialect}
jet.SerializeForProjection(projection, jet.SelectStatementType, &out)
2019-07-31 18:43:54 +02:00
AssertDeepEqual(t, out.Buff.String(), query)
AssertDeepEqual(t, out.Args, args)
2019-07-31 18:43:54 +02:00
}
2019-08-17 18:32:01 +02:00
// AssertQueryPanicErr check if statement Query execution panics with error errString
func AssertQueryPanicErr(t *testing.T, stmt jet.Statement, db qrm.DB, dest interface{}, errString string) {
defer func() {
r := recover()
require.Equal(t, r, errString)
}()
_ = stmt.Query(db, dest)
}
2019-09-20 13:55:07 +02:00
// AssertFileContent check if file content at filePath contains expectedContent text.
2020-04-13 10:18:14 +02:00
func AssertFileContent(t *testing.T, filePath string, expectedContent string) {
enumFileData, err := os.ReadFile(filePath)
2020-04-13 10:18:14 +02:00
require.NoError(t, err)
2020-04-13 10:18:14 +02:00
require.Equal(t, "\n"+string(enumFileData), expectedContent)
}
2019-09-20 13:55:07 +02:00
// AssertFileNamesEqual check if all filesInfos are contained in fileNames
func AssertFileNamesEqual(t *testing.T, dirPath string, fileNames ...string) {
files, err := os.ReadDir(dirPath)
require.NoError(t, err)
require.Equal(t, len(files), len(fileNames))
fileNamesMap := map[string]bool{}
for _, fileInfo := range files {
fileNamesMap[fileInfo.Name()] = true
}
for _, fileName := range fileNames {
require.True(t, fileNamesMap[fileName], fileName+" does not exist.")
}
}
// AssertDeepEqual checks if actual and expected objects are deeply equal.
func AssertDeepEqual(t *testing.T, actual, expected interface{}, option ...cmp.Option) {
if !assert.True(t, cmp.Equal(actual, expected, option...)) {
printDiff(actual, expected, option...)
t.FailNow()
}
}
func assertQueryString(t *testing.T, actual, expected string) {
if !assert.Equal(t, actual, expected) {
printDiff(actual, expected)
t.FailNow()
}
}
func printDiff(actual, expected interface{}, options ...cmp.Option) {
fmt.Println(cmp.Diff(actual, expected, options...))
fmt.Println("Actual: ")
fmt.Println(actual)
fmt.Println("Expected: ")
fmt.Println(expected)
}
2020-05-02 22:15:38 +02:00
// UUIDPtr returns address of uuid.UUID
func UUIDPtr(u string) *uuid.UUID {
newUUID := uuid.MustParse(u)
return &newUUID
}