-
Notifications
You must be signed in to change notification settings - Fork 15
/
database_test.go
54 lines (43 loc) · 1.29 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
package sqldblogger
import (
"database/sql"
"database/sql/driver"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
)
func init() {
sql.Register("mock", &driverMock{})
}
func TestOpenDriver(t *testing.T) {
t.Run("Without Options", func(t *testing.T) {
mockDriver := &driverMock{}
mockDriver.On("Open", mock.Anything).Return(&driverConnMock{}, nil)
db := OpenDriver("test", mockDriver, bufLogger)
_, ok := interface{}(db).(*sql.DB)
assert.True(t, ok)
})
t.Run("With Options", func(t *testing.T) {
mockDriver := &driverMock{}
mockDriver.On("Open", mock.Anything).Return(&driverConnMock{}, driver.ErrBadConn)
db := OpenDriver("test", mockDriver, bufLogger, WithErrorFieldname("errtest"), WithMinimumLevel(LevelDebug))
_, ok := interface{}(db).(*sql.DB)
assert.True(t, ok)
err := db.Ping()
assert.Error(t, err)
var output bufLog
err = json.Unmarshal(bufLogger.Bytes(), &output)
assert.NoError(t, err)
assert.Equal(t, "Connect", output.Message)
assert.Equal(t, LevelError.String(), output.Level)
assert.Contains(t, output.Data, "errtest")
})
}
type driverMock struct {
mock.Mock
}
func (m *driverMock) Open(name string) (driver.Conn, error) {
arg := m.Called(name)
return arg.Get(0).(driver.Conn), arg.Error(1)
}