-
Notifications
You must be signed in to change notification settings - Fork 0
/
in_memory_client.go
74 lines (65 loc) · 2.32 KB
/
in_memory_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package clickhouse
import (
"context"
"fmt"
"sync"
"time"
"github.com/SimifiniiCTO/simfiny-core-lib/instrumentation"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// NewInMemoryTestDbClient creates a new in memory test db client
// This is useful only for unit tests
func NewInMemoryTestDbClient(models ...any) (*Client, error) {
var (
mockQueryTimeout = 10 * time.Minute
mockMaxAttempts = 3
mockMaxConnectionRetryTimeout = 10 * time.Minute
mockRetrySleep = 10 * time.Second
once sync.Once
testdb *gorm.DB
testDatabaseName = "gen_test.db"
)
// initialize db with sqlite
once.Do(func() {
var err error
testdb, err = gorm.Open(sqlite.Open(testDatabaseName), &gorm.Config{})
if err != nil {
panic(fmt.Errorf("open sqlite %q fail: %w", testDatabaseName, err))
}
})
if err := testdb.AutoMigrate(models...); err != nil {
return nil, err
}
return &Client{
Engine: testdb,
QueryTimeout: &mockQueryTimeout,
maxConnectionRetries: &mockMaxAttempts,
maxConnectionRetryTimeout: &mockMaxConnectionRetryTimeout,
retrySleep: &mockRetrySleep,
InstrumentationClient: &instrumentation.Client{},
}, nil
}
// TestTxCleanupHandlerForUnitTests is a handler that can be used to rollback a transaction to a save point.
// This is useful for unit tests that need to rollback a transaction to a save point.
type TestTxCleanupHandlerForUnitTests struct {
cancelFunc context.CancelFunc
Tx *gorm.DB
savePointRollbackHandler func(tx *gorm.DB)
}
// ConfigureNewTxCleanupHandlerForUnitTests creates a new transaction with a save point and returns a handler that can be used to rollback to the save point.
// This is useful for unit tests that need to rollback a transaction to a save point.
func (c *Client) ConfigureNewTxCleanupHandlerForUnitTests() *TestTxCleanupHandlerForUnitTests {
const SAVE_POINT = "test_save_point"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
tx := c.Engine.WithContext(ctx).Begin()
tx.SavePoint(SAVE_POINT)
return &TestTxCleanupHandlerForUnitTests{
cancelFunc: cancel,
Tx: tx,
savePointRollbackHandler: func(tx *gorm.DB) {
tx.RollbackTo(SAVE_POINT)
tx.Commit()
},
}
}