-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathinterceptor_test.go
435 lines (354 loc) · 11 KB
/
interceptor_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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package sqlcache
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"testing"
"time"
"github.com/prashanthpai/sqlcache/cache"
"github.com/prashanthpai/sqlcache/mocks"
sqlmock "github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
func TestNew(t *testing.T) {
assert := require.New(t)
// failure cases
inputs := []*Config{
nil,
{},
}
for _, input := range inputs {
i, err := NewInterceptor(input)
assert.Nil(i)
assert.NotNil(err)
}
// success
i, err := NewInterceptor(&Config{
Cache: new(mocks.Cacher),
})
assert.NotNil(i)
assert.Nil(err)
// stats
s := i.Stats()
assert.NotNil(s)
assert.Equal(s.Hits, uint64(0))
assert.Equal(s.Misses, uint64(0))
}
func runQuery(t *testing.T, assert *require.Assertions, qMock sqlmock.Sqlmock, db *sql.DB, query string, cacheMissExpected bool) {
if cacheMissExpected {
qMock.ExpectQuery(query).WithArgs(18).
WillReturnRows(sqlmock.NewRows([]string{"name"}).AddRow("John").AddRow("Lisa"))
}
rows, err := db.QueryContext(context.Background(), query, 18)
assert.Nil(err)
defer rows.Close()
var names []string
for rows.Next() {
var name string
assert.Nil(rows.Scan(&name))
names = append(names, name)
}
assert.Equal([]string{"John", "Lisa"}, names)
assert.Nil(qMock.ExpectationsWereMet())
}
func runQueryPrepared(t *testing.T, assert *require.Assertions, qMock sqlmock.Sqlmock, db *sql.DB, query string, cacheMissExpected bool) {
qMock.ExpectPrepare(query)
if cacheMissExpected {
qMock.ExpectQuery(query).WithArgs(18).
WillReturnRows(sqlmock.NewRows([]string{"name"}).AddRow("John").AddRow("Lisa"))
}
stmt, err := db.PrepareContext(context.Background(), query)
assert.Nil(err)
rows, err := stmt.QueryContext(context.Background(), 18)
assert.Nil(err)
defer rows.Close()
var names []string
for rows.Next() {
var name string
assert.Nil(rows.Scan(&name))
names = append(names, name)
}
assert.Equal([]string{"John", "Lisa"}, names)
assert.Nil(qMock.ExpectationsWereMet())
}
func TestAttrs(t *testing.T) {
assert := require.New(t)
tests := map[string]struct {
query string
}{
"ttl absent, max rows absent": {
query: `SELECT name FROM users WHERE age > ?`,
},
"ttl present, max rows absent": {
query: `-- @cache-ttl 30
SELECT name FROM users WHERE age > ?`,
},
"ttl absent, max rows present": {
query: `-- @cache-max-rows 10
SELECT name FROM users WHERE age > ?`,
},
"ttl invalid, max rows valid": {
query: `-- @cache-ttl -30
-- @cache-max-rows -10
SELECT name FROM users WHERE age > ?`,
},
"ttl valid, max rows invalid": {
query: `-- @cache-max-rows -10
-- @cache-ttl 30
SELECT name FROM users WHERE age > ?`,
},
}
dsn := fmt.Sprintf("fakeDSN:%s", t.Name())
mockDB, qMock, err := sqlmock.NewWithDSN(dsn)
assert.Nil(err)
defer mockDB.Close()
ic, _ := NewInterceptor(&Config{
Cache: new(mocks.Cacher),
})
driverName := fmt.Sprintf("mockdriver:%s", t.Name())
sql.Register(driverName, ic.Driver(mockDB.Driver()))
db, err := sql.Open(driverName, dsn)
assert.Nil(err)
defer db.Close()
cacheMissExpected := true
for testName, test := range tests {
t.Run(testName, func(t *testing.T) {
runQuery(t, assert, qMock, db, test.query, cacheMissExpected)
runQueryPrepared(t, assert, qMock, db, test.query, cacheMissExpected)
})
}
}
func TestCacheMiss(t *testing.T) {
assert := require.New(t)
dsn := fmt.Sprintf("fakeDSN:%s", t.Name())
mockDB, qMock, err := sqlmock.NewWithDSN(dsn)
assert.Nil(err)
defer mockDB.Close()
ic, _ := NewInterceptor(&Config{
Cache: new(mocks.Cacher),
})
driverName := fmt.Sprintf("mockdriver:%s", t.Name())
sql.Register(driverName, ic.Driver(mockDB.Driver()))
db, err := sql.Open(driverName, dsn)
assert.Nil(err)
defer db.Close()
query := `-- @cache-max-rows 10
-- @cache-ttl 30
SELECT name FROM users WHERE age > ?`
tests := map[string]struct {
err error
present bool
}{
"Get() failed; entry present": {errors.New("some error"), true},
"Get() failed; entry absent": {errors.New("some error"), false},
"Get() passed: entry absent": {nil, false},
}
cacheMissExpected := true
for tcName, td := range tests {
t.Run(tcName, func(t *testing.T) {
mCacher := new(mocks.Cacher)
for i := 0; i < 2; i++ { // once each for runQuery and runQueryPrepared
mCacher.On("Get", mock.Anything, mock.Anything).Return(nil, td.present, td.err)
mCacher.On("Set", mock.Anything, mock.Anything, mock.Anything, time.Duration(30*time.Second)).Return(nil)
}
ic.c = mCacher
onErrCalled := 0
ic.onErr = func(e error) {
onErrCalled++
}
runQuery(t, assert, qMock, db, query, cacheMissExpected)
runQueryPrepared(t, assert, qMock, db, query, cacheMissExpected)
if td.err != nil {
assert.Equal(2, onErrCalled)
} else {
assert.Equal(0, onErrCalled)
}
assert.True(mCacher.AssertExpectations(t))
})
}
}
func TestCacheHit(t *testing.T) {
assert := require.New(t)
dsn := fmt.Sprintf("fakeDSN:%s", t.Name())
mockDB, qMock, err := sqlmock.NewWithDSN(dsn)
assert.Nil(err)
defer mockDB.Close()
ic, _ := NewInterceptor(&Config{
Cache: new(mocks.Cacher),
})
driverName := fmt.Sprintf("mockdriver:%s", t.Name())
sql.Register(driverName, ic.Driver(mockDB.Driver()))
db, err := sql.Open(driverName, dsn)
assert.Nil(err)
defer db.Close()
query := `-- @cache-max-rows 10
-- @cache-ttl 30
SELECT name FROM users WHERE age > ?`
cacheItem := &cache.Item{
Cols: []string{"name"},
Rows: [][]driver.Value{
{"John"},
{"Lisa"},
},
}
mCacher := new(mocks.Cacher)
for i := 0; i < 2; i++ { // once each for runQuery and runQueryPrepared
mCacher.On("Get", mock.Anything, mock.Anything).Return(cacheItem, true, nil)
}
ic.c = mCacher
cacheMissExpected := false
runQuery(t, assert, qMock, db, query, cacheMissExpected)
runQueryPrepared(t, assert, qMock, db, query, cacheMissExpected)
assert.True(mCacher.AssertExpectations(t))
}
func TestDisabled(t *testing.T) {
assert := require.New(t)
dsn := fmt.Sprintf("fakeDSN:%s", t.Name())
mockDB, qMock, err := sqlmock.NewWithDSN(dsn)
assert.Nil(err)
defer mockDB.Close()
ic, _ := NewInterceptor(&Config{
Cache: new(mocks.Cacher),
})
driverName := fmt.Sprintf("mockdriver:%s", t.Name())
sql.Register(driverName, ic.Driver(mockDB.Driver()))
db, err := sql.Open(driverName, dsn)
assert.Nil(err)
defer db.Close()
query := `-- @cache-max-rows 10
-- @cache-ttl 30
SELECT name FROM users WHERE age > ?`
tests := map[string]bool{
"interceptor bypassed": false,
"interceptor enabled": true,
}
for tcName, enabled := range tests {
t.Run(tcName, func(t *testing.T) {
mCacher := new(mocks.Cacher)
if enabled == true {
ic.Enable()
for i := 0; i < 2; i++ { // once each for runQuery and runQueryPrepared
mCacher.On("Get", mock.Anything, mock.Anything).Return(nil, false, nil) // cache miss
mCacher.On("Set", mock.Anything, mock.Anything, mock.Anything, time.Duration(30*time.Second)).Return(nil)
}
} else {
ic.Disable()
}
ic.c = mCacher
cacheMissExpected := true
runQuery(t, assert, qMock, db, query, cacheMissExpected)
runQueryPrepared(t, assert, qMock, db, query, cacheMissExpected)
assert.True(mCacher.AssertExpectations(t))
})
}
}
func TestMaxRows(t *testing.T) {
assert := require.New(t)
dsn := fmt.Sprintf("fakeDSN:%s", t.Name())
mockDB, qMock, err := sqlmock.NewWithDSN(dsn)
assert.Nil(err)
defer mockDB.Close()
ic, _ := NewInterceptor(&Config{
Cache: new(mocks.Cacher),
})
driverName := fmt.Sprintf("mockdriver:%s", t.Name())
sql.Register(driverName, ic.Driver(mockDB.Driver()))
db, err := sql.Open(driverName, dsn)
assert.Nil(err)
defer db.Close()
// runQuery() and runQueryPrepared() returns 2 rows
// setting max rows limit to 1 here
query := `-- @cache-max-rows 1
-- @cache-ttl 30
SELECT name FROM users WHERE age > ?`
mCacher := new(mocks.Cacher)
for i := 0; i < 2; i++ { // once each for runQuery and runQueryPrepared
mCacher.On("Get", mock.Anything, mock.Anything).Return(nil, false, nil) // cache miss
// note that despite cache miss, no call must be made for cache.Set
// as max rows has been exceeded
}
ic.c = mCacher
cacheMissExpected := true
runQuery(t, assert, qMock, db, query, cacheMissExpected)
runQueryPrepared(t, assert, qMock, db, query, cacheMissExpected)
assert.True(mCacher.AssertExpectations(t))
}
func TestHashFuncErr(t *testing.T) {
assert := require.New(t)
dsn := fmt.Sprintf("fakeDSN:%s", t.Name())
mockDB, qMock, err := sqlmock.NewWithDSN(dsn)
assert.Nil(err)
defer mockDB.Close()
mCacher := new(mocks.Cacher)
hashFuncCalled := false
onErrCalled := false
ic, _ := NewInterceptor(&Config{
Cache: mCacher,
HashFunc: func(query string, args []driver.NamedValue) (string, error) {
hashFuncCalled = true
return "", errors.New("some error")
},
OnError: func(err error) {
onErrCalled = true
},
})
driverName := fmt.Sprintf("mockdriver:%s", t.Name())
sql.Register(driverName, ic.Driver(mockDB.Driver()))
db, err := sql.Open(driverName, dsn)
assert.Nil(err)
defer db.Close()
query := `-- @cache-max-rows 10
-- @cache-ttl 30
SELECT name FROM users WHERE age > ?`
cacheMissExpected := true
runQuery(t, assert, qMock, db, query, cacheMissExpected)
assert.True(hashFuncCalled)
assert.True(onErrCalled)
assert.Equal(ic.Stats().Errors, uint64(1))
hashFuncCalled = false // reset
onErrCalled = false // reset
runQueryPrepared(t, assert, qMock, db, query, cacheMissExpected)
assert.True(hashFuncCalled)
assert.True(onErrCalled)
assert.True(mCacher.AssertExpectations(t))
assert.Equal(ic.Stats().Errors, uint64(2))
}
func TestCacheSetErr(t *testing.T) {
assert := require.New(t)
dsn := fmt.Sprintf("fakeDSN:%s", t.Name())
mockDB, qMock, err := sqlmock.NewWithDSN(dsn)
assert.Nil(err)
defer mockDB.Close()
mCacher := new(mocks.Cacher)
for i := 0; i < 2; i++ { // once each for runQuery and runQueryPrepared
mCacher.On("Get", mock.Anything, mock.Anything).Return(nil, false, nil) // cache miss
mCacher.On("Set", mock.Anything, mock.Anything, mock.Anything, time.Duration(30*time.Second)).Return(errors.New("some error"))
}
onErrCalled := false
ic, _ := NewInterceptor(&Config{
Cache: mCacher,
OnError: func(err error) {
onErrCalled = true
},
})
driverName := fmt.Sprintf("mockdriver:%s", t.Name())
sql.Register(driverName, ic.Driver(mockDB.Driver()))
db, err := sql.Open(driverName, dsn)
assert.Nil(err)
defer db.Close()
query := `-- @cache-max-rows 10
-- @cache-ttl 30
SELECT name FROM users WHERE age > ?`
cacheMissExpected := true
runQuery(t, assert, qMock, db, query, cacheMissExpected)
assert.True(onErrCalled)
onErrCalled = false // reset
assert.Equal(ic.Stats().Errors, uint64(1))
runQueryPrepared(t, assert, qMock, db, query, cacheMissExpected)
assert.True(onErrCalled)
assert.True(mCacher.AssertExpectations(t))
assert.Equal(ic.Stats().Errors, uint64(2))
}