-
Notifications
You must be signed in to change notification settings - Fork 4
/
e2e_test.go
648 lines (582 loc) · 15.8 KB
/
e2e_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
package twowaysql
import (
"context"
"database/sql"
"errors"
"fmt"
"os"
"testing"
"time"
_ "github.com/jackc/pgx/v4/stdlib"
"github.com/jmoiron/sqlx"
"golang.org/x/sync/errgroup"
"gotest.tools/v3/assert"
"gotest.tools/v3/assert/cmp"
)
type Person struct {
FirstName string `db:"first_name"`
LastName string `db:"last_name"`
Email string `db:"email"`
NullString sql.NullString `db:"null_string"`
NullInt sql.NullInt64 `db:"null_int"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt sql.NullTime `db:"updated_at"`
}
func TestSelect(t *testing.T) {
//このテストはinit.sqlに依存しています。
//データベースは/testdata/postgres/init以下のsqlファイルを用いて初期化されている。
db := open(t)
t.Cleanup(func() {
db.Close()
})
tw := New(db)
ctx := context.Background()
// SELECT
var people []Person
var params = Info{
MaxEmpNo: 3,
DeptNo: 12,
}
expected := []Person{
{
FirstName: "Evan",
LastName: "MacMans",
Email: "evanmacmans@example.com",
},
{
FirstName: "Malvina",
LastName: "FitzSimons",
Email: "malvinafitzsimons@example.com",
},
}
sql := `-- comment
SELECT
first_name
, last_name
, email
FROM
persons
WHERE
employee_no < /*maxEmpNo*/1000 -- comment
/* IF deptNo */
AND dept_no < /*deptNo*/1
/* END */
-- comment`
err := tw.Select(ctx, &people, sql, ¶ms)
if err != nil {
t.Errorf("select: failed: %v", err)
}
assert.Check(t, cmp.DeepEqual(people, expected))
}
func TestSelectMap(t *testing.T) {
//このテストはinit.sqlに依存しています。
//データベースは/postgres/init以下のsqlファイルを用いて初期化されている。
db := open(t)
defer db.Close()
tw := New(db)
ctx := context.Background()
// SELECT
var people []map[string]interface{}
var params = Info{
MaxEmpNo: 3,
DeptNo: 12,
}
expected := []map[string]interface{}{
{
"first_name": "Evan",
"last_name": "MacMans",
"email": "evanmacmans@example.com",
},
{
"first_name": "Malvina",
"last_name": "FitzSimons",
"email": "malvinafitzsimons@example.com",
},
}
sql := `-- comment
SELECT
first_name
, last_name
, email
FROM
persons
WHERE
employee_no < /*maxEmpNo*/1000 -- comment
/* IF deptNo */
AND dept_no < /*deptNo*/1
/* END */
-- comment`
err := tw.Select(ctx, &people, sql, ¶ms)
if err != nil {
t.Errorf("select: failed: %v", err)
}
assert.Check(t, cmp.DeepEqual(people, expected))
}
func TestUpdate(t *testing.T) {
//このテストはinit.sqlに依存しています。
//データベースは/postgres/init以下のsqlファイルを用いて初期化されている。
db := open(t)
defer db.Close()
tw := New(db)
ctx := context.Background()
var params = Info{
MaxEmpNo: 3,
DeptNo: 12,
}
_, err := tw.Exec(ctx, `UPDATE persons SET dept_no = /*deptNo*/1 WHERE employee_no = /*EmpNo*/1`, ¶ms)
if err != nil {
t.Fatalf("exec: failed: %v", err)
}
var people []Person
err = tw.Select(ctx, &people, `SELECT first_name, last_name, email FROM persons WHERE dept_no = 11`, nil)
if err != nil {
t.Fatalf("select: failed: %v", err)
}
// 元に戻す。本当はトランザクションのラッパーを実装するべきかも
_, err = tw.Exec(ctx, `UPDATE persons SET dept_no = /*deptNo*/0 WHERE employee_no = /*EmpNo*/1`, ¶ms)
if err != nil {
t.Fatalf("exec: failed: %v", err)
}
var expected = []Person{
{
FirstName: "Malvina",
LastName: "FitzSimons",
Email: "malvinafitzsimons@example.com",
},
}
assert.Check(t, cmp.DeepEqual(people, expected))
}
func TestExec_Parallel(t *testing.T) {
//このテストはinit.sqlに依存しています。
//データベースは/postgres/init以下のsqlファイルを用いて初期化されている。
db := open(t)
defer db.Close()
tw := New(db)
ctx := context.Background()
var params = []Info{}
var expect []Person
for i := 0; i < 100; i++ {
empNo := i + 4
info :=
Info{
EmpNo: empNo,
DeptNo: 1,
FirstName: fmt.Sprintf("FirstName-%d", empNo),
LastName: fmt.Sprintf("LastName-%d", empNo),
Email: fmt.Sprintf("%d@test", empNo),
}
params = append(params, info)
person :=
Person{
FirstName: fmt.Sprintf("FirstName-%d", empNo),
LastName: fmt.Sprintf("LastName-%d", empNo),
Email: fmt.Sprintf("%d@test", empNo),
}
expect = append(expect, person)
}
sql :=
`
INSERT INTO persons(employee_no, dept_no, first_name, last_name, email, created_at) VALUES
(/*EmpNo*/1, /*deptNo*/1, /*firstName*/'firstName', /*lastName*/'lastName', /*email*/'temp', CURRENT_TIMESTAMP)
`
var eg errgroup.Group
for _, param := range params {
p := param
eg.Go(func() error {
_, err := tw.Exec(ctx, sql, &p)
return err
})
}
if err := eg.Wait(); err != nil {
t.Fatalf("exec: failed: %v", err)
}
var people []Person
err := tw.Select(ctx, &people, `SELECT first_name, last_name, email FROM persons WHERE dept_no = 1 order by employee_no`, nil)
if err != nil {
t.Fatalf("select: failed: %v", err)
}
// 元に戻す。
for _, param := range params {
p := param
_, err = tw.Exec(ctx, `DELETE from persons WHERE employee_no = /*EmpNo*/1`, &p)
if err != nil {
t.Fatalf("exec: failed: %v", err)
}
}
assert.Check(t, cmp.DeepEqual(people, expect))
}
func TestInsertAndDelete(t *testing.T) {
//このテストはinit.sqlに依存しています。
//データベースは/postgres/init以下のsqlファイルを用いて初期化されている。
db := open(t)
defer db.Close()
tw := New(db)
ctx := context.Background()
var params = Info{
EmpNo: 100,
FirstName: "Jeff",
LastName: "Dean",
DeptNo: 1011,
Email: "jeffdean@example.com",
NullString: sql.NullString{String: "value", Valid: true},
NullInt: sql.NullInt64{Int64: 11, Valid: false}, // NULL 登録
CreatedAt: time.Date(2022, 6, 10, 17, 0, 0, 0, time.UTC),
UpdatedAt: sql.NullTime{Time: time.Date(2022, 6, 10, 18, 0, 0, 0, time.UTC), Valid: true},
}
_, err := tw.Exec(ctx, `
INSERT INTO persons
(employee_no, dept_no, first_name, last_name, email, null_string, null_int, created_at, updated_at)
VALUES
(/*EmpNo*/1, /*deptNo*/1, /*firstName*/"Tim", /*lastName*/"Cook", /*email*/"timcook@example.com", /*null_string*/'null', /*null_int*/1, /*created_at*/'2022-06-01 10:00:00', /*updated_at*/'2022-06-02 10:00:00')`,
¶ms)
if err != nil {
t.Fatalf("exec: failed: %v", err)
}
var people []Person
err = tw.Select(ctx, &people, `SELECT first_name, last_name, email, null_string, null_int, created_at, updated_at FROM persons WHERE dept_no = /*deptNo*/0`, ¶ms)
if err != nil {
t.Fatalf("select: failed: %v", err)
}
var expected = []Person{
{
FirstName: "Jeff",
LastName: "Dean",
Email: "jeffdean@example.com",
NullString: sql.NullString{String: "value", Valid: true},
NullInt: sql.NullInt64{Int64: 0, Valid: false}, // NULL 確認
CreatedAt: time.Date(2022, 6, 10, 17, 0, 0, 0, time.UTC),
UpdatedAt: sql.NullTime{Time: time.Date(2022, 6, 10, 18, 0, 0, 0, time.UTC), Valid: true},
},
}
assert.Check(t, cmp.DeepEqual(people, expected))
_, err = tw.Exec(ctx, `DELETE FROM persons WHERE employee_no = /*EmpNo*/2`, ¶ms)
if err != nil {
t.Fatalf("exec: failed: %v", err)
}
people = []Person{}
err = tw.Select(ctx, &people, `SELECT first_name, last_name, email FROM persons WHERE dept_no = /*deptNo*/0`, ¶ms)
if err != nil {
t.Fatalf("select: failed: %v", err)
}
expected = []Person{}
assert.Check(t, cmp.DeepEqual(people, expected))
}
func TestTxCommit(t *testing.T) {
//このテストはinit.sqlに依存しています。
//データベースは/postgres/init以下のsqlファイルを用いて初期化されている。
db := open(t)
defer db.Close()
tw := New(db)
ctx := context.Background()
// insert test data
const insertSQL = `
INSERT INTO persons
(employee_no, dept_no, first_name, last_name, email, created_at) VALUES
(11, 111, 'Clegg', 'George', 'clegggeorge@example.com', CURRENT_TIMESTAMP)
;
`
if _, err := tw.Exec(ctx, insertSQL, nil); err != nil {
t.Fatal(err)
}
defer tw.Exec(ctx, `DELETE FROM persons WHERE employee_no = 11`, nil)
// begin
tx, err := tw.Begin(ctx)
if err != nil {
t.Fatal(err)
}
// update
type Param struct {
EmpNo int `twowaysql:"EmpNo"`
FirstName string `twowaysql:"FirstName"`
}
const sql = `
UPDATE
persons
SET first_name = /*FirstName*/Jon
WHERE employee_no = /*EmpNo*/10`
param := Param{EmpNo: 11, FirstName: "Rimmer"}
res, err := tx.Exec(ctx, sql, ¶m)
if err != nil {
t.Error(err)
}
rows, err := res.RowsAffected()
if err != nil {
t.Error(err)
}
if rows != 1 {
t.Errorf("update rows = %v", rows)
}
// commit
if err := tx.Commit(); err != nil {
t.Error(err)
}
// check
people := []Person{}
if err := tw.Select(ctx, &people, `SELECT first_name, last_name, email FROM persons WHERE employee_no = /*EmpNo*/10`, ¶m); err != nil {
t.Error(err)
}
expectedAfterCommit := []Person{
{
FirstName: "Rimmer",
LastName: "George",
Email: "clegggeorge@example.com",
},
}
if !match(expectedAfterCommit, people) {
t.Errorf("expected:\n%v\nbut got\n%v\n", expectedAfterCommit, people)
}
}
func TestTxRollback(t *testing.T) {
//このテストはinit.sqlに依存しています。
//データベースは/postgres/init以下のsqlファイルを用いて初期化されている。
db := open(t)
defer db.Close()
tw := New(db)
ctx := context.Background()
// insert test data
const insertSQL = `
INSERT INTO persons
(employee_no, dept_no, first_name, last_name, email, created_at) VALUES
(12, 121, 'Chmmg', 'Dudley', 'chmmgdudley@example.com', CURRENT_TIMESTAMP)
;
`
if _, err := tw.Exec(ctx, insertSQL, nil); err != nil {
t.Fatal(err)
}
defer tw.Exec(ctx, `DELETE FROM persons WHERE employee_no = 12`, nil)
// begin
tx, err := tw.Begin(ctx)
if err != nil {
t.Fatal(err)
}
// update
type Param struct {
EmpNo int `twowaysql:"EmpNo"`
FirstName string `twowaysql:"firstName"`
}
const sql = `
UPDATE
persons
SET first_name = /*firstName*/Jon
WHERE employee_no = /*EmpNo*/10`
param := Param{EmpNo: 12, FirstName: "Emerson"}
res, err := tx.Exec(ctx, sql, ¶m)
if err != nil {
t.Error(err)
}
rows, err := res.RowsAffected()
if err != nil {
t.Error(err)
}
if rows != 1 {
t.Errorf("update rows = %v", rows)
}
// rollback
if err := tx.Rollback(); err != nil {
t.Error(err)
}
// check
people := []Person{}
if err := tw.Select(ctx, &people, `SELECT first_name, last_name, email FROM persons WHERE employee_no = /*EmpNo*/10`, ¶m); err != nil {
t.Error(err)
}
expectedAfterCommit := []Person{
{
FirstName: "Chmmg",
LastName: "Dudley",
Email: "chmmgdudley@example.com",
},
}
if !match(expectedAfterCommit, people) {
t.Errorf("expected:\n%v\nbut got\n%v\n", expectedAfterCommit, people)
}
}
func TestTxBlock(t *testing.T) {
//このテストはinit.sqlに依存しています。
//データベースは/postgres/init以下のsqlファイルを用いて初期化されている。
db := open(t)
defer db.Close()
tw := New(db)
ctx := context.Background()
// insert test data
const insertSQL = `
INSERT INTO persons
(employee_no, dept_no, first_name, last_name, email, created_at) VALUES
(13, 131, 'Darling', 'Wat', 'darlingwat@example.com', CURRENT_TIMESTAMP),
(14, 141, 'Hallows', 'Jessie', 'hallowsjessie@example.com', CURRENT_TIMESTAMP)
;`
if _, err := tw.Exec(ctx, insertSQL, nil); err != nil {
t.Fatal(err)
}
defer tw.Exec(ctx, `DELETE FROM persons WHERE employee_no = 13`, nil)
defer tw.Exec(ctx, `DELETE FROM persons WHERE employee_no = 14`, nil)
type Param struct {
EmpNo int `twowaysql:"EmpNo"`
FirstName string `twowaysql:"firstName"`
}
// commit case
err := tw.Transaction(ctx, func(tx *TwowaysqlTx) error {
// update
const sql = `
UPDATE
persons
SET first_name = /*firstName*/Jon
WHERE employee_no = /*EmpNo*/10`
param := Param{EmpNo: 13, FirstName: "COMMITED"}
res, err := tx.Exec(ctx, sql, ¶m)
if err != nil {
return err
}
rows, err := res.RowsAffected()
if err != nil {
return err
}
if rows != 1 {
return fmt.Errorf("update rows = %v", rows)
}
return nil
})
if err != nil {
t.Error(err)
}
// rollcack case
err = tw.Transaction(ctx, func(tx *TwowaysqlTx) error {
// update
const sql = `
UPDATE
persons
SET first_name = /*firstName*/Jon
WHERE employee_no = /*EmpNo*/10`
param := Param{EmpNo: 14, FirstName: "ROLLBACKED"}
res, err := tx.Exec(ctx, sql, ¶m)
if err != nil {
return err
}
rows, err := res.RowsAffected()
if err != nil {
return err
}
if rows != 1 {
return fmt.Errorf("update rows = %v", rows)
}
// generate error
return errors.New("TEST ERROR")
})
if err == nil {
t.Error("unexpecte err == nil")
}
// check
people := []Person{}
const checkSQL = `SELECT first_name, last_name, email FROM persons WHERE employee_no IN (13, 14) order by employee_no`
if err := tw.Select(ctx, &people, checkSQL, nil); err != nil {
t.Error(err)
}
expectedAfterCommit := []Person{
// commit
{
FirstName: "COMMITED",
LastName: "Wat",
Email: "darlingwat@example.com",
},
// rollback
{
FirstName: "Hallows",
LastName: "Jessie",
Email: "hallowsjessie@example.com",
},
}
if !match(expectedAfterCommit, people) {
t.Errorf("expected:\n%v\nbut got\n%v\n", expectedAfterCommit, people)
}
}
func TestTxBlockPanic(t *testing.T) {
//このテストはinit.sqlに依存しています。
//データベースは/postgres/init以下のsqlファイルを用いて初期化されている。
db := open(t)
defer db.Close()
tw := New(db)
ctx := context.Background()
// insert test data
const insertSQL = `
INSERT INTO persons
(employee_no, dept_no, first_name, last_name, email, created_at) VALUES
(15, 151, 'Tom', 'Mike', 'tommike@example.com', CURRENT_TIMESTAMP)
;`
if _, err := tw.Exec(ctx, insertSQL, nil); err != nil {
t.Fatal(err)
}
defer tw.Exec(ctx, `DELETE FROM persons WHERE employee_no = 15`, nil)
type Param struct {
EmpNo int `twowaysql:"EmpNo"`
FirstName string `twowaysql:"firstName"`
}
defer func() {
p := recover()
assert.Equal(t, p != nil, true)
// check
people := []Person{}
const checkSQL = `SELECT first_name, last_name, email FROM persons WHERE employee_no = 15`
if err := tw.Select(ctx, &people, checkSQL, nil); err != nil {
t.Error(err)
}
expectedAfterCommit := []Person{
{
FirstName: "Tom",
LastName: "Mike",
Email: "tommike@example.com",
},
}
if !match(expectedAfterCommit, people) {
t.Errorf("expected:\n%v\nbut got\n%v\n", expectedAfterCommit, people)
}
}()
// rollcack case (panic recover)
err := tw.Transaction(ctx, func(tx *TwowaysqlTx) error {
// update
const sql = `
UPDATE
persons
SET first_name = /*firstName*/Jon
WHERE employee_no = /*EmpNo*/10`
param := Param{EmpNo: 15, FirstName: "ROLLBACKED(PANIC)"}
res, err := tx.Exec(ctx, sql, ¶m)
if err != nil {
return err
}
rows, err := res.RowsAffected()
if err != nil {
return err
}
if rows != 1 {
return fmt.Errorf("update rows = %v", rows)
}
// occure panic
panic("test panic")
})
assert.NilError(t, err)
}
func open(t *testing.T) *sqlx.DB {
t.Helper()
var db *sqlx.DB
var err error
if host := os.Getenv("POSTGRES_HOST"); host != "" {
db, err = sqlx.Open("pgx", fmt.Sprintf("host=%s user=postgres password=postgres dbname=postgres sslmode=disable", host))
} else {
db, err = sqlx.Open("pgx", "host=localhost user=postgres password=postgres dbname=postgres sslmode=disable")
}
if err != nil {
t.Fatal(err)
}
return db
}
func match(p1, p2 []Person) bool {
if len(p1) != len(p2) {
return false
}
for i := 0; i < len(p1); i++ {
if p1[i] != p2[i] {
return false
}
}
return true
}