-
Notifications
You must be signed in to change notification settings - Fork 0
/
context_test.go
92 lines (75 loc) · 2.38 KB
/
context_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
package dbtxn_test
import (
"context"
"errors"
"testing"
"github.com/DATA-DOG/go-sqlmock"
"github.com/imantung/dbtxn"
"github.com/stretchr/testify/require"
)
func TestContext_Commit(t *testing.T) {
t.Run("expect rollback when error", func(t *testing.T) {
db, mock, _ := sqlmock.New()
mock.ExpectBegin()
mock.ExpectRollback()
c := dbtxn.NewContext()
c.Begin(context.Background(), db)
c.AppendError(errors.New("some-error"))
require.NoError(t, c.Commit())
})
t.Run("expect error rollback ", func(t *testing.T) {
db, mock, _ := sqlmock.New()
mock.ExpectBegin()
mock.ExpectRollback().WillReturnError(errors.New("rollback-error"))
c := dbtxn.NewContext()
c.Begin(context.Background(), db)
c.AppendError(errors.New("some-error"))
require.EqualError(t, c.Commit(), "rollback-error")
})
t.Run("expect commit when no error", func(t *testing.T) {
db, mock, _ := sqlmock.New()
mock.ExpectBegin()
mock.ExpectCommit()
c := dbtxn.NewContext()
c.Begin(context.Background(), db)
require.NoError(t, c.Commit())
})
t.Run("expect commit when no error", func(t *testing.T) {
db, mock, _ := sqlmock.New()
mock.ExpectBegin()
mock.ExpectCommit().WillReturnError(errors.New("commit-error"))
c := dbtxn.NewContext()
c.Begin(context.Background(), db)
require.EqualError(t, c.Commit(), "commit-error")
})
}
func TestContext_CommitWithError(t *testing.T) {
t.Run("return rollback error when no function error", func(t *testing.T) {
fn := func(ctx context.Context) (err error) {
db, mock, _ := sqlmock.New()
mock.ExpectBegin()
mock.ExpectRollback().WillReturnError(errors.New("rollback-error"))
c := dbtxn.NewContext()
c.Begin(ctx, db)
c.AppendError(errors.New("error-to-trigger-rollback"))
defer c.CommitWithError(&err)
return nil
}
err := fn(context.Background())
require.EqualError(t, err, "rollback-error")
})
t.Run("return function error although rollback-error", func(t *testing.T) {
fn := func(ctx context.Context) (err error) {
db, mock, _ := sqlmock.New()
mock.ExpectBegin()
mock.ExpectRollback().WillReturnError(errors.New("rollback-error"))
c := dbtxn.NewContext()
c.Begin(ctx, db)
c.AppendError(errors.New("error-to-trigger-rollback"))
defer c.CommitWithError(&err)
return errors.New("function-error")
}
err := fn(context.Background())
require.EqualError(t, err, "function-error; rollback-error")
})
}