forked from pashagolub/pgxmock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rows_test.go
711 lines (591 loc) · 16.4 KB
/
rows_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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
package pgxmock
import (
"context"
"encoding/json"
"errors"
"fmt"
"testing"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/stretchr/testify/assert"
)
func TestPointerToInterfaceArgument(t *testing.T) {
mock, err := NewPool()
if err != nil {
panic(err)
}
mock.ExpectQuery(`SELECT 123`).
WillReturnRows(
mock.NewRows([]string{"id"}).
AddRow(int64(123))) // Value which should be scanned in *interface{}
var value interface{}
err = mock.QueryRow(context.Background(), `SELECT 123`).Scan(&value)
if err != nil || value.(int64) != 123 {
t.Error(err)
}
}
func TestExplicitTypeCasting(t *testing.T) {
mock, err := NewPool()
if err != nil {
panic(err)
}
mock.ExpectQuery("SELECT .+ FROM test WHERE .+").
WithArgs(uint64(1)).
WillReturnRows(NewRows(
[]string{"id"}).
AddRow(uint64(1)),
)
rows := mock.QueryRow(context.Background(), "SELECT id FROM test WHERE id = $1", uint64(1))
var id uint64
err = rows.Scan(&id)
if err != nil {
t.Error(err)
}
}
func TestAddRows(t *testing.T) {
t.Parallel()
mock, err := NewConn()
if err != nil {
t.Fatal("failed to open sqlmock database:", err)
}
defer mock.Close(context.Background())
values := [][]any{
{
1, "John",
},
{
2, "Jane",
},
{
3, "Peter",
},
{
4, "Emily",
},
}
rows := NewRows([]string{"id", "name"}).AddRows(values...)
mock.ExpectQuery("SELECT").WillReturnRows(rows).RowsWillBeClosed()
rs, _ := mock.Query(context.Background(), "SELECT")
defer rs.Close()
for rs.Next() {
var id int
var name string
_ = rs.Scan(&id, &name)
fmt.Println("scanned id:", id, "and name:", name)
}
if rs.Err() != nil {
fmt.Println("got rows error:", rs.Err())
}
// Output: scanned id: 1 and title: John
// scanned id: 2 and title: Jane
// scanned id: 3 and title: Peter
// scanned id: 4 and title: Emily
}
func ExampleRows_AddRows() {
mock, err := NewConn()
if err != nil {
fmt.Println("failed to open sqlmock database:", err)
return
}
defer mock.Close(context.Background())
values := [][]any{
{
1, "one",
},
{
2, "two",
},
}
rows := NewRows([]string{"id", "title"}).AddRows(values...)
mock.ExpectQuery("SELECT").WillReturnRows(rows)
rs, _ := mock.Query(context.Background(), "SELECT")
defer rs.Close()
for rs.Next() {
var id int
var title string
_ = rs.Scan(&id, &title)
fmt.Println("scanned id:", id, "and title:", title)
}
if rs.Err() != nil {
fmt.Println("got rows error:", rs.Err())
}
// Output: scanned id: 1 and title: one
// scanned id: 2 and title: two
}
func ExampleRows() {
mock, err := NewConn()
if err != nil {
fmt.Println("failed to open pgxmock database:", err)
return
}
defer mock.Close(context.Background())
rows := NewRows([]string{"id", "title"}).
AddRow(1, "one").
AddRow(2, "two").
AddCommandTag(pgconn.NewCommandTag("SELECT 2"))
mock.ExpectQuery("SELECT").WillReturnRows(rows)
rs, _ := mock.Query(context.Background(), "SELECT")
defer rs.Close()
fmt.Println("command tag:", rs.CommandTag())
if len(rs.FieldDescriptions()) != 2 {
fmt.Println("got wrong number of fields")
}
for rs.Next() {
var id int
var title string
_ = rs.Scan(&id, &title)
fmt.Println("scanned id:", id, "and title:", title)
}
if rs.Err() != nil {
fmt.Println("got rows error:", rs.Err())
}
// Output: command tag: SELECT 2
// scanned id: 1 and title: one
// scanned id: 2 and title: two
}
func ExampleRows_rowError() {
mock, err := NewConn()
if err != nil {
fmt.Println("failed to open pgxmock database:", err)
return
}
// defer mock.Close(context.Background())
rows := NewRows([]string{"id", "title"}).
AddRow(0, "one").
AddRow(1, "two").
RowError(1, fmt.Errorf("row error"))
mock.ExpectQuery("SELECT").WillReturnRows(rows)
rs, _ := mock.Query(context.Background(), "SELECT")
defer rs.Close()
for rs.Next() {
var id int
var title string
_ = rs.Scan(&id, &title)
fmt.Println("scanned id:", id, "and title:", title)
if rs.Err() != nil {
fmt.Println("got rows error:", rs.Err())
}
}
// Output: scanned id: 0 and title: one
// scanned id: 1 and title: two
// got rows error: row error
}
func ExampleRows_expectToBeClosed() {
mock, err := NewConn()
if err != nil {
fmt.Println("failed to open pgxmock database:", err)
return
}
defer mock.Close(context.Background())
row := NewRows([]string{"id", "title"}).AddRow(1, "john")
rows := NewRowsWithColumnDefinition(
pgconn.FieldDescription{Name: "id"},
pgconn.FieldDescription{Name: "title"}).
AddRow(1, "john").AddRow(2, "anna")
mock.ExpectQuery("SELECT").WillReturnRows(row, rows).RowsWillBeClosed()
_, _ = mock.Query(context.Background(), "SELECT")
_, _ = mock.Query(context.Background(), "SELECT")
if err := mock.ExpectationsWereMet(); err != nil {
fmt.Println("got error:", err)
}
/*Output: got error: expected query rows to be closed, but it was not: ExpectedQuery => expecting call to Query() or to QueryRow():
- matches sql: 'SELECT'
- is without arguments
- returns data:
result set: 0
row 0: [1 john]
result set: 1
row 0: [1 john]
row 1: [2 anna]
*/
}
func ExampleRows_customDriverValue() {
mock, err := NewConn()
if err != nil {
fmt.Println("failed to open pgxmock database:", err)
return
}
defer mock.Close(context.Background())
rows := NewRows([]string{"id", "null_int"}).
AddRow(5, pgtype.Int8{Int64: 5, Valid: true}).
AddRow(2, pgtype.Int8{Valid: false})
mock.ExpectQuery("SELECT").WillReturnRows(rows)
rs, _ := mock.Query(context.Background(), "SELECT")
defer rs.Close()
for rs.Next() {
var id int
var num pgtype.Int8
_ = rs.Scan(&id, &num)
fmt.Println("scanned id:", id, "and null int64:", num)
}
if rs.Err() != nil {
fmt.Println("got rows error:", rs.Err())
}
// Output: scanned id: 5 and null int64: {5 true}
// scanned id: 2 and null int64: {0 false}
}
func TestAllowsToSetRowsErrors(t *testing.T) {
t.Parallel()
mock, err := NewConn()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
rows := NewRows([]string{"id", "title"}).
AddRow(0, "one").
AddRow(1, "two").
RowError(1, fmt.Errorf("error"))
mock.ExpectQuery("SELECT").WillReturnRows(rows)
rs, err := mock.Query(context.Background(), "SELECT")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
defer rs.Close()
if !rs.Next() {
t.Fatal("expected the first row to be available")
}
if rs.Err() != nil {
t.Fatalf("unexpected error: %s", rs.Err())
}
if !rs.Next() {
t.Fatal("expected the second row to be available, even there should be an error")
}
if rs.Err() == nil {
t.Fatal("expected an error, but got none")
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatal(err)
}
}
func TestRowsCloseError(t *testing.T) {
t.Parallel()
mock, err := NewConn()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
rows := NewRows([]string{"id"}).CloseError(fmt.Errorf("close error"))
mock.ExpectQuery("SELECT").WillReturnRows(rows)
rs, err := mock.Query(context.Background(), "SELECT")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
rs.Close()
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatal(err)
}
}
func TestRowsClosed(t *testing.T) {
t.Parallel()
mock, err := NewConn()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
rows := NewRows([]string{"id"}).AddRow(1)
mock.ExpectQuery("SELECT").WillReturnRows(rows).RowsWillBeClosed()
rs, err := mock.Query(context.Background(), "SELECT")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
rs.Close()
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatal(err)
}
}
func TestQuerySingleRow(t *testing.T) {
t.Parallel()
mock, err := NewConn()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
rows := NewRows([]string{"id"}).
AddRow(1).
AddRow(2)
mock.ExpectQuery("SELECT").WillReturnRows(rows)
var id int
if err := mock.QueryRow(context.Background(), "SELECT").Scan(&id); err != nil {
t.Fatalf("unexpected error: %s", err)
}
mock.ExpectQuery("SELECT").WillReturnRows(NewRows([]string{"id"}))
if err := mock.QueryRow(context.Background(), "SELECT").Scan(&id); err != pgx.ErrNoRows {
t.Fatal("expected sql no rows error")
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatal(err)
}
}
func ExampleRows_values() {
mock, err := NewConn()
if err != nil {
fmt.Println("failed to open pgxmock database:", err)
return
}
defer mock.Close(context.Background())
rows := NewRows([]string{"raw"}).
AddRow(`one string value with some text!`).
AddRow(`two string value with even more text than the first one`).
AddRow([]byte{})
mock.ExpectQuery("SELECT").WillReturnRows(rows)
rs, err := mock.Query(context.Background(), "SELECT")
if err != nil {
fmt.Print(err)
return
}
defer rs.Close()
for rs.Next() {
v, e := rs.Values()
fmt.Println(v[0], e)
}
// Output: one string value with some text! <nil>
// two string value with even more text than the first one <nil>
// [] <nil>
}
func ExampleRows_rawValues() {
mock, err := NewConn()
if err != nil {
fmt.Println("failed to open pgxmock database:", err)
return
}
defer mock.Close(context.Background())
rows := NewRows([]string{"raw"}).
AddRow([]byte(`one binary value with some text!`)).
AddRow([]byte(`two binary value with even more text than the first one`)).
AddRow([]byte{})
mock.ExpectQuery("SELECT").WillReturnRows(rows)
rs, err := mock.Query(context.Background(), "SELECT")
if err != nil {
fmt.Print(err)
return
}
defer rs.Close()
for rs.Next() {
var rawValue []byte
if err := json.Unmarshal(rs.RawValues()[0], &rawValue); err != nil {
fmt.Print(err)
}
fmt.Println(string(rawValue))
}
// Output: one binary value with some text!
// two binary value with even more text than the first one
//
}
func TestRowsScanError(t *testing.T) {
t.Parallel()
mock, err := NewConn()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
r := NewRows([]string{"col1", "col2"}).AddRow("one", "two").AddRow("one", nil)
mock.ExpectQuery("SELECT").WillReturnRows(r)
rs, err := mock.Query(context.Background(), "SELECT")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
defer rs.Close()
var one, two string
if !rs.Next() || rs.Err() != nil || rs.Scan(&one, &two) != nil {
t.Fatal("unexpected error on first row scan")
}
if !rs.Next() || rs.Err() != nil {
t.Fatal("unexpected error on second row read")
}
err = rs.Scan(&one, two)
if err == nil {
t.Fatal("expected an error for scan, but got none")
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Fatal(err)
}
}
type testScanner struct {
Value int64
}
func (s *testScanner) Scan(src interface{}) error {
switch src := src.(type) {
case int64:
s.Value = src
return nil
default:
return errors.New("a dummy scan error")
}
}
func TestRowsScanWithScannerIface(t *testing.T) {
mock, err := NewConn()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
r := NewRows([]string{"col1"}).AddRow(int64(23))
mock.ExpectQuery("SELECT").WillReturnRows(r)
rs, err := mock.Query(context.Background(), "SELECT")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
var result testScanner
if !rs.Next() || rs.Err() != nil {
t.Fatal("unexpected error on first row read")
}
if rs.Scan(&result) != nil {
t.Fatal("unexpected error for scan")
}
if result.Value != int64(23) {
t.Fatalf("expected Value to be 23 but got: %d", result.Value)
}
}
func TestRowsScanErrorOnScannerIface(t *testing.T) {
mock, err := NewConn()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
r := NewRows([]string{"col1"}).AddRow("one").AddRow("two")
mock.ExpectQuery("SELECT").WillReturnRows(r)
rs, err := mock.Query(context.Background(), "SELECT")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
var one int64 // No scanner interface
var two testScanner // scanner error
if !rs.Next() || rs.Err() != nil {
t.Fatal("unexpected error on first row read")
}
if rs.Scan(&one) == nil {
t.Fatal("expected an error for first scan (no scanner interface), but got none")
}
if !rs.Next() || rs.Err() != nil {
t.Fatal("unexpected error on second row read")
}
err = rs.Scan(&two)
if err == nil {
t.Fatal("expected an error for second scan (scanner error), but got none")
}
}
func TestCSVRowParser(t *testing.T) {
t.Parallel()
rs := NewRows([]string{"col1", "col2"}).FromCSVString("a,NULL")
mock, err := NewConn()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
mock.ExpectQuery("SELECT").WillReturnRows(rs)
rw, err := mock.Query(context.Background(), "SELECT")
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
defer rw.Close()
var col1 string
var col2 []byte
rw.Next()
if err = rw.Scan(&col1, &col2); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if col1 != "a" {
t.Fatalf("expected col1 to be 'a', but got [%T]:%+v", col1, col1)
}
if col2 != nil {
t.Fatalf("expected col2 to be nil, but got [%T]:%+v", col2, col2)
}
}
func TestWrongNumberOfValues(t *testing.T) {
// Open new mock database
mock, err := NewConn()
if err != nil {
fmt.Println("error creating mock database")
return
}
defer mock.Close(context.Background())
defer func() {
_ = recover()
}()
mock.ExpectQuery("SELECT ID FROM TABLE").WithArgs(101).WillReturnRows(NewRows([]string{"ID"}).AddRow(101, "Hello"))
_, _ = mock.Query(context.Background(), "SELECT ID FROM TABLE", 101)
// shouldn't reach here
t.Error("expected panic from query")
}
func TestEmptyRowSets(t *testing.T) {
rs1 := NewRows([]string{"a"}).AddRow("a")
rs2 := NewRows([]string{"b"})
rs3 := NewRows([]string{"c"})
set1 := &rowSets{sets: []*Rows{rs1, rs2}}
set2 := &rowSets{sets: []*Rows{rs3, rs2}}
set3 := &rowSets{sets: []*Rows{rs2}}
if set1.empty() {
t.Fatalf("expected rowset 1, not to be empty, but it was")
}
if !set2.empty() {
t.Fatalf("expected rowset 2, to be empty, but it was not")
}
if !set3.empty() {
t.Fatalf("expected rowset 3, to be empty, but it was not")
}
}
func TestMockQueryWithCollect(t *testing.T) {
t.Parallel()
mock, err := NewConn()
if err != nil {
t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
}
defer mock.Close(context.Background())
type rowStructType struct {
ID int
Title string
}
rs := NewRows([]string{"id", "title"}).AddRow(5, "hello world")
mock.ExpectQuery("SELECT (.+) FROM articles WHERE id = ?").
WithArgs(5).
WillReturnRows(rs)
rows, err := mock.Query(context.Background(), "SELECT (.+) FROM articles WHERE id = ?", 5)
if err != nil {
t.Fatalf("error '%s' was not expected while retrieving mock rows", err)
}
defer rows.Close()
rawMap, err := pgx.CollectRows(rows, pgx.RowToAddrOfStructByPos[rowStructType])
if err != nil {
t.Fatalf("error '%s' was not expected while trying to collect rows", err)
}
var id = rawMap[0].ID
var title = rawMap[0].Title
if err != nil {
t.Fatalf("error '%s' was not expected while trying to scan row", err)
}
if id != 5 {
t.Errorf("expected mocked id to be 5, but got %d instead", id)
}
if title != "hello world" {
t.Errorf("expected mocked title to be 'hello world', but got '%s' instead", title)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}
func TestRowsConn(t *testing.T) {
assert.Nil(t, (&rowSets{}).Conn())
}
func TestRowsKind(t *testing.T) {
var alphabet = []string{"a", "b", "c", "d", "e", "f"}
rows := NewRows([]string{"id", "alphabet"})
for id, b := range alphabet {
rows.AddRow(id, b)
}
kindRows := rows.Kind()
for i := 0; kindRows.Next(); i++ {
var (
letter string
index int
)
if err := kindRows.Scan(&index, &letter); err != nil {
t.Fatalf("unexpected error: %s", err)
}
if index != i {
t.Fatalf("expected %d, but got %d", i, index)
}
if letter != alphabet[i] {
t.Fatalf("expected %s, but got %s", alphabet[i], letter)
}
}
}