-
Notifications
You must be signed in to change notification settings - Fork 0
/
tx_test.go
118 lines (105 loc) · 2.45 KB
/
tx_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
package gormmw_test
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"testing"
"time"
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/httptest"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
"github.com/pkg/errors"
"github.com/stretchr/testify/require"
"github.com/yanshiyason/gormmw"
)
type widget struct {
ID uint `gorm:"PRIMARY_KEY"`
CreatedAt *time.Time `gorm:"not null"`
UpdatedAt *time.Time `gorm:"not null"`
}
func tx(fn func(tx *gorm.DB)) error {
d, err := ioutil.TempDir("", "")
if err != nil {
return errors.WithStack(err)
}
path := filepath.Join(d, "pt_test.sqlite")
defer os.RemoveAll(path)
db, err := gorm.Open("sqlite3", path)
if err != nil {
return errors.WithStack(err)
}
defer db.Close()
db.Debug()
// db.LogMode(true)
db.SetLogger(log.New(os.Stdout, "\n", 0))
db.CreateTable(&widget{})
fn(db)
return nil
}
func app(db *gorm.DB) *buffalo.App {
app := buffalo.New(buffalo.Options{})
app.Use(gormmw.Transaction(db, log.New(os.Stdout, "\r\n", 0)))
app.GET("/success", func(c buffalo.Context) error {
w := &widget{}
tx := c.Value("tx").(*gorm.DB)
if db := tx.Create(w); db.Error != nil {
return db.Error
}
return c.Render(201, nil)
})
app.GET("/non-success", func(c buffalo.Context) error {
w := &widget{}
tx := c.Value("tx").(*gorm.DB)
if db := tx.Create(w); db.Error != nil {
return db.Error
}
return c.Render(301, nil)
})
app.GET("/error", func(c buffalo.Context) error {
w := &widget{}
tx := c.Value("tx").(*gorm.DB)
if db := tx.Create(w); db.Error != nil {
return db.Error
}
return errors.New("boom")
})
return app
}
func Test_PopTransaction(t *testing.T) {
r := require.New(t)
err := tx(func(db *gorm.DB) {
w := httptest.New(app(db))
res := w.HTML("/success").Get()
r.Equal(201, res.Code)
var count int
db.Table("widgets").Count(&count)
r.Equal(1, count)
})
r.NoError(err)
}
func Test_PopTransaction_Error(t *testing.T) {
r := require.New(t)
err := tx(func(db *gorm.DB) {
w := httptest.New(app(db))
res := w.HTML("/error").Get()
r.Equal(500, res.Code)
var count int
db.Table("widgets").Count(&count)
r.Equal(0, count)
})
r.NoError(err)
}
func Test_PopTransaction_NonSuccess(t *testing.T) {
r := require.New(t)
err := tx(func(db *gorm.DB) {
w := httptest.New(app(db))
res := w.HTML("/non-success").Get()
r.Equal(301, res.Code)
var count int
db.Table("widgets").Count(&count)
r.Equal(1, count)
})
r.NoError(err)
}