-
Notifications
You must be signed in to change notification settings - Fork 11
/
transaction_test.go
113 lines (100 loc) · 2.12 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
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
package echo
import (
"bytes"
"context"
"testing"
"github.com/stretchr/testify/assert"
)
type debugTransaction struct {
*bytes.Buffer
}
func (b *debugTransaction) Begin(ctx context.Context) error {
_, err := b.WriteString(`[Begin]`)
return err
}
func (b *debugTransaction) Rollback(ctx context.Context) error {
_, err := b.WriteString(`[Rollback]`)
return err
}
func (b *debugTransaction) Commit(ctx context.Context) error {
_, err := b.WriteString(`[Commit]`)
return err
}
func (b *debugTransaction) End(ctx context.Context, succeed bool) error {
if succeed {
return b.Commit(ctx)
}
return b.Rollback(ctx)
}
func TestTransaction(t *testing.T) {
b := bytes.NewBuffer(nil)
tx := &debugTransaction{b}
w := NewTransaction(tx)
f := func(rollback bool) error {
b.WriteString(`<f:Begin`)
w.Begin(nil)
b.WriteString(`>`)
var e error
if rollback {
b.WriteString(`<f:Rollback`)
w.Rollback(nil)
e = ErrNotFound
} else {
b.WriteString(`<f:Commit`)
w.Commit(nil)
}
b.WriteString(`>`)
return e
}
f2 := func(rollback bool, rollback2 bool) error {
b.WriteString(`<f2:Begin`)
w.Begin(nil)
b.WriteString(`>`)
e := f(rollback2)
if e != nil {
return e
}
if rollback {
b.WriteString(`<f2:Rollback`)
w.Rollback(nil)
e = ErrNotFound
} else {
b.WriteString(`<f2:Commit`)
w.Commit(nil)
}
b.WriteString(`>`)
return e
}
// -------------
// - Commit
// -------------
b.WriteString(`<Begin`)
w.Begin(nil)
b.WriteString(`>`)
err := f2(false, false)
if err == nil {
b.WriteString(`<Commit`)
} else {
b.WriteString(`<Rollback`)
}
w.End(nil, err == nil)
//w.Commit(nil) //panic
b.WriteString(`>`)
assert.Equal(t, `<Begin[Begin]><f2:Begin><f:Begin><f:Commit><f2:Commit><Commit[Commit]>`, b.String())
// -------------
// - Rollback
// -------------
b.Reset()
b.WriteString(`<Begin`)
w.Begin(nil)
b.WriteString(`>`)
err = f2(false, true)
if err == nil {
b.WriteString(`<Commit`)
} else {
b.WriteString(`<Rollback`)
}
w.End(nil, err == nil)
b.WriteString(`>`)
assert.Equal(t, `<Begin[Begin]><f2:Begin><f:Begin><f:Rollback[Rollback]><Rollback>`, b.String())
}