-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransaction_test.go
58 lines (52 loc) · 1.58 KB
/
transaction_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
package torm
import (
"context"
"errors"
"testing"
"time"
sqlmock "github.com/DATA-DOG/go-sqlmock"
"github.com/jmoiron/sqlx"
"github.com/pinnacles/torm/internal/test"
)
func TestTransactionCommit(t *testing.T) {
if err := test.WithSqlxMock(func(ctx context.Context, db *sqlx.DB, mock sqlmock.Sqlmock) {
tm := time.Now()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO `test`").WithArgs(1, tm, tm).WillReturnResult(sqlmock.NewResult(1, 1))
mock.ExpectCommit()
if err := Transaction(context.Background(), nil, db, func(tx *sqlx.Tx) error {
builder := NewBuilder(tx)
builder.SetTime(&tm)
_, err := builder.Insert().Exec(ctx, &test.TestSchema{Foo: 1, Bar: 2})
return err
}); err != nil {
t.Fatal(err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}); err != nil {
t.Fatal(err)
}
}
func TestTransactionRollback(t *testing.T) {
if err := test.WithSqlxMock(func(ctx context.Context, db *sqlx.DB, mock sqlmock.Sqlmock) {
tm := time.Now()
mock.ExpectBegin()
mock.ExpectExec("INSERT INTO `test`").WithArgs(1, tm, tm).WillReturnError(errors.New("insert error"))
mock.ExpectRollback()
if err := Transaction(context.Background(), nil, db, func(tx *sqlx.Tx) error {
builder := NewBuilder(tx)
builder.SetTime(&tm)
_, err := builder.Insert().Exec(ctx, &test.TestSchema{Foo: 1, Bar: 2})
return err
}); err == nil {
t.Fatal(err)
}
if err := mock.ExpectationsWereMet(); err != nil {
t.Errorf("there were unfulfilled expectations: %s", err)
}
}); err != nil {
t.Fatal(err)
}
}