-
Notifications
You must be signed in to change notification settings - Fork 3
/
main_test.go
539 lines (505 loc) · 13.7 KB
/
main_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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
package ivory
import (
"context"
"database/sql"
"fmt"
"reflect"
"strconv"
"testing"
"time"
)
const createDatabaseInSqlTextTest = "createDatabaseInSqlText"
const sqlTextDbName = "example_created_in_sqlText"
func Test_mightHaveTransaction(t *testing.T) {
type args struct {
sqlText string
}
tests := []struct {
name string
args args
want bool
}{
{
name: "obvious",
args: args{
sqlText: "begin statement",
},
want: true,
},
{
name: "noteSpace",
args: args{
sqlText: "begin ",
},
want: true,
},
{
name: "dontBeGreedy",
args: args{
sqlText: "create table beginnings",
},
want: false,
},
{
name: "nothingMatching",
args: args{
sqlText: "insert into table pub (table_number, party_size, time) values (3, 7, '2021-10-13 03:38:57.914877')",
},
want: false,
},
{
name: "empty",
args: args{
sqlText: "",
},
want: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := mightHaveTransaction(tt.args.sqlText); got != tt.want {
t.Errorf("mightHaveTransaction() = %v, want %v", got, tt.want)
}
})
}
}
func TestDatabaseOptions_DSN(t *testing.T) {
type fields struct {
Host string
Port int
Database string
Schema string
User string
Password string
SslMode string
SslCert string
SslKey string
SslRootcert string
SslCertMode string
ConnectTimeoutSeconds int
MaxOpenConns int
MaxIdleConns int
reflectType reflect.Type
}
tests := []struct {
name string
fields fields
want string
wantErr bool
}{
{
name: "simpleString",
fields: fields{
Host: "localhost",
},
want: "host='localhost'",
},
{
name: "digit",
fields: fields{
Port: 1024,
},
want: "port=1024",
},
{
name: "hostPortIsSpaced",
fields: fields{
Host: "localhost",
Port: 1024,
},
want: "host='localhost' port=1024",
},
{
name: "emptyStringSkipped",
fields: fields{
Host: "",
},
want: "",
},
{
name: "zeroIntSkipped",
fields: fields{
Port: 0,
},
want: "",
},
{
name: "invalidSslError",
fields: fields{
SslMode: "post rock",
},
want: "",
wantErr: true,
},
{
name: "allFields",
fields: fields{
Host: "localhost",
Port: 1024,
Database: "exampleDB",
Schema: "exampleSchema",
User: "user",
Password: "password",
SslMode: "verify-full",
SslCert: "./cert.pem",
SslKey: "./key.pem",
SslRootcert: "./rootcert.pem",
SslCertMode: "require",
ConnectTimeoutSeconds: 10,
},
want: "host='localhost' port=1024 dbname='exampleDB' search_path='exampleSchema' user='user' password='password' sslmode=verify-full sslcert='./cert.pem' sslkey='./key.pem' sslrootcert='./rootcert.pem' sslcertmode=require connect_timeout=10",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
do := &DatabaseOptions{
Host: tt.fields.Host,
Port: tt.fields.Port,
Database: tt.fields.Database,
Schema: tt.fields.Schema,
User: tt.fields.User,
Password: tt.fields.Password,
SslMode: tt.fields.SslMode,
SslCert: tt.fields.SslCert,
SslKey: tt.fields.SslKey,
SslRootCert: tt.fields.SslRootcert,
SslCertMode: tt.fields.SslCertMode,
ConnectTimeoutSeconds: tt.fields.ConnectTimeoutSeconds,
MaxOpenConns: tt.fields.MaxOpenConns,
MaxIdleConns: tt.fields.MaxIdleConns,
reflectType: tt.fields.reflectType,
}
got, err := do.DSN()
if (err != nil) != tt.wantErr {
t.Errorf("DSN() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("DSN() = %v, want %v", got, tt.want)
}
})
}
}
// this convenience func creates a string with a temporal and random portion
// as such, we only test len does not exceed our expectation and that repeated runs don't collide on names
func Test_generateDbName(t *testing.T) {
// e.g. 1634246356
lenTimeNow := len(strconv.FormatInt(time.Now().Unix(), 10))
type args struct {
userProvidedId string
}
tests := []struct {
name string
args args
wantLen int
}{
{
name: "noIdProvided",
args: args{
userProvidedId: "",
},
wantLen: PgMaxIdentifierLen - (remainingNameBudget - lenTimeNow),
},
{
name: "IDVeryLong",
args: args{
userProvidedId: "aSBhbSByZWFsbHkgc2ljayBvZiBkb2luZyB3ZWIgZGV2ZWxvcG1lbnQhICBpcyBhbnlvbmUgaW50ZXJlc3RpbmcgaGlyaW5nPz8K",
},
wantLen: PgMaxIdentifierLen,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := generateDbName(tt.args.userProvidedId)
gotLen := len(got)
if gotLen != tt.wantLen {
t.Errorf("generateDbName() got len = %v, want len %v, value: %s", gotLen, tt.wantLen, got)
}
})
}
}
// Corresponds to values in docker-compose.yml
func TestNew(t *testing.T) {
type args struct {
ctx context.Context
opts *DatabaseOptions
sqlText []string
createDatabase bool
customIdPortion string
}
tests := []struct {
name string
args args
wantDBName string
wantErr bool
}{
{
name: "failToConnect",
args: args{
ctx: context.TODO(),
opts: &DatabaseOptions{
Host: "test_failToConnect.example.org",
Port: 99999,
Database: "abc123",
},
sqlText: []string{},
},
wantDBName: "", // no db will be created if we can't connect
wantErr: true,
},
{
name: "createRandomDB",
args: args{
ctx: context.TODO(),
opts: &DatabaseOptions{
Host: "localhost",
Port: 5555,
SslMode: "disable",
User: "postgres",
Password: "rootUserSeriousPassword1",
},
createDatabase: true,
sqlText: []string{},
},
wantDBName: "", // we don't know what it will be
wantErr: false,
},
{
name: "honorDBNameCreateDB",
args: args{
ctx: context.TODO(),
opts: &DatabaseOptions{
Host: "localhost",
Port: 5555,
Database: "flannel",
SslMode: "disable",
User: "postgres",
Password: "rootUserSeriousPassword1",
},
createDatabase: true,
sqlText: []string{"CREATE TABLE foo ( hello CHAR(5));"},
},
wantDBName: "flannel",
wantErr: false,
},
// if the user creates the database in sql text, they must clean up their own database(s)
{
name: "createDatabaseInSqlText",
args: args{
ctx: context.TODO(),
opts: &DatabaseOptions{
Host: "localhost",
Port: 5555,
SslMode: "disable",
User: "postgres",
Password: "rootUserSeriousPassword1",
},
createDatabase: false,
sqlText: []string{fmt.Sprintf("CREATE DATABASE %s;", sqlTextDbName)},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dbHandleNoBoundDB, dbHandleBound, dbName, tearDown, err := New(tt.args.ctx, tt.args.opts, tt.args.sqlText, tt.args.createDatabase, tt.args.customIdPortion)
// success of the tear down function should be tested separately
defer func() {
// a bit of a hack, but the "create db in the provided text" is a special, advanced case
// where the caller is responsible. come up with more elegant behavior if time permits.
// one naive approach would be allowing the user to include a snippet to run on tearDown
// that executes before closing connections.
if tt.name == createDatabaseInSqlTextTest {
return
}
err = tearDown()
// if we got an err on connection, we could not have created the database
if (err != nil) != tt.wantErr {
// stopping before creating more mess
t.Errorf("Failed to clean up created database: %s. error = %v", dbName, err)
t.FailNow()
}
}()
// if we received an error, it can be a failure to connect to the db or a failure running sql
if (err != nil) != tt.wantErr {
t.Errorf("New() did not expect error. error = %v", err)
return
}
if tt.wantErr {
return
}
if len(tt.wantDBName) > 0 {
if tt.wantDBName != dbName {
t.Errorf("New() did not honor the provided DB name. got name = %v, want name = %v", dbName, tt.wantDBName)
return
}
}
if tt.name == createDatabaseInSqlTextTest {
// make our own teardown func for this specific test
err = tearDownFunc(tt.args.ctx, dbHandleNoBoundDB, dbHandleBound, sqlTextDbName)()
if (err != nil) != tt.wantErr {
// stopping before creating more mess
t.Errorf("Failed to clean up created database: %s. error = %v", sqlTextDbName, err)
t.FailNow()
}
}
})
}
}
func TestFindLikelyAbandonedDBs(t *testing.T) {
ctx := context.Background()
expectedToFind := make([]string, 0)
testLocalTimeString := strconv.FormatInt(time.Now().Unix(), 10)
prefix := fmt.Sprintf("TestFLAD_%s", testLocalTimeString)
// create databases that we want to find later
// discarding teardown
dbHandleNoBoundDB1, dbHandleBound1, dbName1, _, err := New(
ctx,
&DatabaseOptions{
Host: "localhost",
Port: 5555,
Database: fmt.Sprintf(prefix + "_1"),
SslMode: "disable",
User: "postgres",
Password: "rootUserSeriousPassword1",
},
[]string{},
true,
"",
)
if err != nil {
t.Errorf("Test setup failed while creating DBs to abandon. error = %v ", err)
t.FailNow()
}
expectedToFind = append(expectedToFind, dbName1)
dbHandleNoBoundDB2, dbHandleBound2, dbName2, _, err := New(
ctx,
&DatabaseOptions{
Host: "localhost",
Port: 5555,
Database: fmt.Sprintf(prefix + "_2"),
SslMode: "disable",
User: "postgres",
Password: "rootUserSeriousPassword1",
},
[]string{},
true,
"",
)
if err != nil {
t.Errorf("Test setup failed while creating fixture DBs. error = %v ", err)
t.FailNow()
}
expectedToFind = append(expectedToFind, dbName2)
// close without using our a cleanup function to simulate left work behind
for _, closeFunc := range []func() error{
dbHandleNoBoundDB1.Close, dbHandleBound1.Close, dbHandleNoBoundDB2.Close, dbHandleBound2.Close} {
err = closeFunc()
if err != nil {
t.Errorf("Test setup failed closing handle for fixture DB. error = %v ", err)
t.FailNow()
}
}
// bind a new connection not specific to a database
noDBOpts := &DatabaseOptions{
Host: "localhost",
Port: 5555,
ConnectTimeoutSeconds: 10,
SslMode: "disable",
User: "postgres",
Password: "rootUserSeriousPassword1",
}
dbHandle, err := Connect(ctx, noDBOpts)
if err != nil {
t.Errorf("Test setup failed while creating a new DB handle. error = %v", err)
t.FailNow()
}
defer func(dbHandle *sql.DB) {
err := dbHandle.Close()
if err != nil {
// not really an error in the test, but good to know
// there is no t.Warn or t.Info
t.Errorf("Failed to clean up database handle for test.")
}
}(dbHandle)
dbsFound, err := FindLikelyAbandonedDBs(ctx, dbHandle, prefix)
if err != nil {
t.Errorf("FindLikelyAbandonedDBs() failed to run. error = %v", err)
t.FailNow()
return
}
// we could have some databases left over between tests, but it's really unlikely
if len(dbsFound) != len(expectedToFind) {
t.Errorf(
"FindLikelyAbandonedDBs() unexpected number of databases found. got len() = %v, want len = %v ", len(dbsFound), len(expectedToFind))
if len(dbsFound) == 0 {
// no point continuing with no work to do
t.FailNow()
}
}
dbsFoundTable := make(map[string]struct{}, len(dbsFound))
for _, v := range dbsFound {
dbsFoundTable[v] = struct{}{}
}
for _, expectedDB := range expectedToFind {
_, ok := dbsFoundTable[expectedDB]
if !ok {
t.Errorf("FindLikelyAbandonedDBs() did not find a fixture db. found: %s, missing db: %s", dbsFound, expectedDB)
}
// we don't want to use a teardown func in a loop as we'll close the database handle on the first iteration
}
_, errSlice := DropDB(ctx, dbHandle, expectedToFind)
for i, e := range errSlice {
if e != nil {
t.Errorf("FindLikelyAbandonedDBs() failed to clean up a test-created database: %s. error = %v", expectedToFind[i], e)
}
}
}
// TestNew_UserProvidedSQL specifically tests the functionality of running user-provided SQL
func TestNew_UserProvidedSQL(t *testing.T) {
ctx := context.Background()
_, dbHandleBound, dbName, tearDownFunc, err := New(
ctx,
&DatabaseOptions{
Host: "localhost",
Port: 5555,
SslMode: "disable",
User: "postgres",
Password: "rootUserSeriousPassword1",
},
[]string{
"create schema ivory;",
"create table ivory.disposable_table ( hello char(5));",
"insert into ivory.disposable_table (hello) values ('world');",
},
true,
"_test_ups",
)
defer func() {
err := tearDownFunc()
if err != nil {
t.Errorf("Failed to clean up created database: %s. error = %v", dbName, err)
}
}()
// test database creation without error
if err != nil {
t.Errorf("New() failed to create database for test. error = %v", err)
t.FailNow()
}
// confirm our table exists
rows, err := dbHandleBound.QueryContext(ctx, "SELECT hello FROM ivory.disposable_table LIMIT 1;")
if err != nil {
t.Errorf("Failed to ")
t.FailNow()
}
var r string
for rows.Next() {
err = rows.Scan(&r)
if err != nil {
t.Errorf("Failed to scan results. error = %v", err)
t.FailNow()
}
}
if r != "world" {
t.Errorf("New() failed to run sql expressions during setup. got = %v, want value: %v", r, "world")
}
}