-
Notifications
You must be signed in to change notification settings - Fork 12
/
datasource_test.go
270 lines (238 loc) · 6.73 KB
/
datasource_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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
package sqlds
import (
"context"
"database/sql"
"database/sql/driver"
"encoding/json"
"errors"
"fmt"
"io"
"testing"
"time"
"github.com/grafana/grafana-plugin-sdk-go/backend"
"github.com/grafana/grafana-plugin-sdk-go/data/sqlutil"
"github.com/grafana/sqlds/v2/mock"
"github.com/stretchr/testify/assert"
)
type fakeDriver struct {
openDBfn func() (*sql.DB, error)
Driver
}
func (d fakeDriver) Connect(backend.DataSourceInstanceSettings, json.RawMessage) (db *sql.DB, err error) {
return d.openDBfn()
}
func (d fakeDriver) Macros() Macros {
return Macros{}
}
func (d fakeDriver) Converters() []sqlutil.Converter {
return []sqlutil.Converter{}
}
// func (d fakeDriver) Settings(backend.DataSourceInstanceSettings) DriverSettings
func Test_getDBConnectionFromQuery(t *testing.T) {
db := &sql.DB{}
db2 := &sql.DB{}
db3 := &sql.DB{}
d := &fakeDriver{openDBfn: func() (*sql.DB, error) { return db3, nil }}
tests := []struct {
desc string
dsUID string
args string
existingDB *sql.DB
expectedKey string
expectedDB *sql.DB
}{
{
desc: "it should return the default db with no args",
dsUID: "uid1",
args: "",
expectedKey: "uid1-default",
expectedDB: db,
},
{
desc: "it should return the cached connection for the given args",
dsUID: "uid1",
args: "foo",
expectedKey: "uid1-foo",
existingDB: db2,
expectedDB: db2,
},
{
desc: "it should create a new connection with the given args",
dsUID: "uid1",
args: "foo",
expectedKey: "uid1-foo",
expectedDB: db3,
},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
ds := &SQLDatasource{c: d, EnableMultipleConnections: true}
settings := backend.DataSourceInstanceSettings{UID: tt.dsUID}
key := defaultKey(tt.dsUID)
// Add the mandatory default db
ds.storeDBConnection(key, dbConnection{db, settings})
if tt.existingDB != nil {
key = keyWithConnectionArgs(tt.dsUID, []byte(tt.args))
ds.storeDBConnection(key, dbConnection{tt.existingDB, settings})
}
key, dbConn, err := ds.getDBConnectionFromQuery(&Query{ConnectionArgs: json.RawMessage(tt.args)}, tt.dsUID)
if err != nil {
t.Fatalf("unexpected error %v", err)
}
if key != tt.expectedKey {
t.Fatalf("unexpected cache key %s", key)
}
if dbConn.db != tt.expectedDB {
t.Fatalf("unexpected result %v", dbConn.db)
}
})
}
t.Run("it should return an error if connection args are used without enabling multiple connections", func(t *testing.T) {
ds := &SQLDatasource{c: d, EnableMultipleConnections: false}
_, _, err := ds.getDBConnectionFromQuery(&Query{ConnectionArgs: json.RawMessage("foo")}, "dsUID")
if err == nil || !errors.Is(err, MissingMultipleConnectionsConfig) {
t.Errorf("expecting error: %v", MissingMultipleConnectionsConfig)
}
})
t.Run("it should return an error if the default connection is missing", func(t *testing.T) {
ds := &SQLDatasource{c: d}
_, _, err := ds.getDBConnectionFromQuery(&Query{}, "dsUID")
if err == nil || !errors.Is(err, MissingDBConnection) {
t.Errorf("expecting error: %v", MissingDBConnection)
}
})
}
func Test_Dispose(t *testing.T) {
t.Run("it should not delete connections", func(t *testing.T) {
ds := &SQLDatasource{}
ds.dbConnections.Store(defaultKey("uid1"), dbConnection{})
ds.dbConnections.Store("foo", dbConnection{})
ds.Dispose()
count := 0
ds.dbConnections.Range(func(key, value interface{}) bool {
count++
return true
})
if count != 2 {
t.Errorf("missing connections")
}
})
}
func Test_timeout_retries(t *testing.T) {
dsUID := "timeout"
settings := backend.DataSourceInstanceSettings{UID: dsUID}
handler := testSqlHandler{}
mockDriver := "sqlmock"
mock.RegisterDriver(mockDriver, handler)
db, err := sql.Open(mockDriver, "")
if err != nil {
t.Errorf("failed to connect to mock driver: %v", err)
}
timeoutDriver := fakeDriver{
openDBfn: func() (*sql.DB, error) { return db, nil },
}
retries := 5
max := time.Duration(testTimeout) * time.Second
driverSettings := DriverSettings{Retries: retries, Timeout: max}
ds := &SQLDatasource{c: timeoutDriver, driverSettings: driverSettings}
key := defaultKey(dsUID)
// Add the mandatory default db
ds.storeDBConnection(key, dbConnection{db, settings})
ctx := context.Background()
req := &backend.CheckHealthRequest{
PluginContext: backend.PluginContext{
DataSourceInstanceSettings: &settings,
},
}
result, err := ds.CheckHealth(ctx, req)
assert.Nil(t, err)
assert.Equal(t, retries, testCounter)
expected := context.DeadlineExceeded.Error()
assert.Equal(t, expected, result.Message)
}
func Test_error_retries(t *testing.T) {
testCounter = 0
dsUID := "error"
settings := backend.DataSourceInstanceSettings{UID: dsUID}
handler := testSqlHandler{
error: errors.New("foo"),
}
mockDriver := "sqlmock-error"
mock.RegisterDriver(mockDriver, handler)
timeoutDriver := fakeDriver{
openDBfn: func() (*sql.DB, error) {
db, err := sql.Open(mockDriver, "")
if err != nil {
t.Errorf("failed to connect to mock driver: %v", err)
}
return db, nil
},
}
retries := 5
max := time.Duration(10) * time.Second
driverSettings := DriverSettings{Retries: retries, Timeout: max, Pause: 1}
ds := &SQLDatasource{c: timeoutDriver, driverSettings: driverSettings}
key := defaultKey(dsUID)
// Add the mandatory default db
db, _ := timeoutDriver.Connect(settings, nil)
ds.storeDBConnection(key, dbConnection{db, settings})
ctx := context.Background()
qry := `{ "rawSql": "foo" }`
req := &backend.QueryDataRequest{
PluginContext: backend.PluginContext{
DataSourceInstanceSettings: &settings,
},
Queries: []backend.DataQuery{
{
RefID: "foo",
JSON: []byte(qry),
},
},
}
data, err := ds.QueryData(ctx, req)
assert.Nil(t, err)
assert.Equal(t, retries+1, testCounter)
assert.NotNil(t, data.Responses)
}
var testCounter = 0
var testTimeout = 1
var testRows = 0
type testSqlHandler struct {
mock.DBHandler
error
}
func (s testSqlHandler) Ping(ctx context.Context) error {
if s.error != nil {
return s.error
}
testCounter++ // track the retries for the test assertion
time.Sleep(time.Duration(testTimeout + 1)) // simulate a connection delay
select {
case <-ctx.Done():
fmt.Println(ctx.Err())
return ctx.Err()
}
}
func (s testSqlHandler) Query(args []driver.Value) (driver.Rows, error) {
fmt.Println("query")
if s.error != nil {
testCounter++
return s, s.error
}
return s, nil
}
func (s testSqlHandler) Columns() []string {
return []string{"foo", "bar"}
}
func (s testSqlHandler) Next(dest []driver.Value) error {
testRows++
if testRows > 5 {
return io.EOF
}
dest[0] = "foo"
dest[1] = "bar"
return nil
}
func (s testSqlHandler) Close() error {
return nil
}