-
Notifications
You must be signed in to change notification settings - Fork 0
/
database_test.go
98 lines (76 loc) · 1.74 KB
/
database_test.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package tyr
import (
"context"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/assert"
)
var sqlOpen = New
func TestDBConn(t *testing.T) {
conn, mock, err := sqlmock.New(sqlmock.MonitorPingsOption(true))
if err != nil {
assert.Failf(t, "failed to open stub db", "%v", err)
}
defer conn.Close()
sqlOpen = func(args SqlConnParams) (*Sql, error) {
return &Sql{DB: conn}, nil
}
mock.ExpectPing()
db, cleanup, err := DBConn()
ctx, cancel := context.WithCancel(context.Background())
// Asserts
assert.Nil(t, err)
assert.NotNil(t, db)
assert.NotNil(t, cleanup)
db.SetEvent(NewEventHandler())
db.Subscriber(ctx, UpdatedQuery, func(e Event) {
assert.Equal(t, UpdatedQuery, e.Type)
})
db.Subscriber(ctx, CreatedQuery, func(e Event) {
assert.Equal(t, CreatedQuery, e.Type)
})
db.Subscriber(ctx, DeletedQuery, func(e Event) {
assert.Equal(t, DeletedQuery, e.Type)
})
payload := map[string]interface{}{
"payload": "data",
}
db.Notify(ctx, Event{
Type: CreatedQuery,
Data: payload,
})
db.Notify(ctx, Event{
Type: DeletedQuery,
Data: payload,
})
db.Notify(ctx, Event{
Type: UpdatedQuery,
Data: payload,
})
mock.ExpectClose()
cleanup()
if err := mock.ExpectationsWereMet(); err != nil {
assert.Failf(t, "there were unfulfilled expectations", "%v", err)
}
cancel()
}
func DBConn() (*Sql, func(), error) {
conn, err := sqlOpen(SqlConnParams{
Driver: "",
Dsn: "",
})
if err != nil {
return nil, nil, err
}
cleanup := func() {
_ = conn.DB.Close()
}
conn.DB.SetConnMaxLifetime(time.Minute * time.Duration(5))
conn.DB.SetMaxOpenConns(2)
conn.DB.SetMaxIdleConns(2)
if err := conn.DB.Ping(); err != nil {
return nil, cleanup, err
}
return conn, cleanup, nil
}