-
Notifications
You must be signed in to change notification settings - Fork 1
/
conn_test.go
116 lines (107 loc) · 2.57 KB
/
conn_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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package pgvertica
import (
"database/sql"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/assert"
)
func TestBuildConnectionString(t *testing.T) {
testCases := []struct {
desc string
scheme string
params map[string]string
host string
port int
want string
}{
{
desc: "standard connection",
scheme: "postgres",
params: map[string]string{
"user": "test",
"password": "test",
"database": "testdb",
},
host: "localhost",
port: 5432,
want: "postgres://test:test@localhost:5432/testdb",
},
}
for _, tC := range testCases {
t.Run(tC.desc, func(t *testing.T) {
got := buildConnectionString(tC.scheme, tC.params, tC.host, tC.port)
if got != tC.want {
t.Errorf("BuildConnectionString(%s, %v, %s, %d) = %s; want %s", tC.scheme, tC.params, tC.host, tC.port, got, tC.want)
}
})
}
}
type MockDBOpener struct {
db *sql.DB
err error
}
func (mo MockDBOpener) Open(driverName, dataSourceName string) (*sql.DB, error) {
return mo.db, mo.err
}
func TestConnectToDB(t *testing.T) {
db, mock, err := sqlmock.NewWithDSN("", sqlmock.MonitorPingsOption(true))
if err != nil {
t.Fatalf("An error '%s' was not expected when opening a stub database connection", err)
}
defer db.Close()
testCases := []struct {
opener DBOpener
desc string
driverName string
connectionString string
params map[string]string
mockFunc func()
expectedError error
}{
{
opener: MockDBOpener{
db: db,
err: nil,
},
desc: "successful connection",
driverName: "postgres",
connectionString: "postgres://test:test@localhost:5432/testdb",
params: map[string]string{
"user": "test",
"password": "test",
"database": "testdb",
},
mockFunc: func() {
mock.ExpectPing()
},
expectedError: nil,
},
{
opener: MockDBOpener{
db: db,
err: nil,
},
desc: "failed connection",
driverName: "postgres",
connectionString: "postgres://test:test@localhost:5432/testdb",
params: map[string]string{
"user": "test",
"password": "test",
"database": "testdb",
},
mockFunc: func() {
mock.ExpectPing().WillReturnError(sql.ErrConnDone)
},
expectedError: sql.ErrConnDone,
},
}
for _, tC := range testCases {
t.Run(tC.desc, func(t *testing.T) {
tC.mockFunc()
_, err := connectToDB(tC.opener, tC.driverName, tC.connectionString, tC.params)
assert.Equal(t, tC.expectedError, err)
err = mock.ExpectationsWereMet()
assert.NoError(t, err)
})
}
}