-
Notifications
You must be signed in to change notification settings - Fork 72
/
events_test.go
138 lines (114 loc) · 2.46 KB
/
events_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
package kallax
import (
"errors"
"testing"
"github.com/stretchr/testify/require"
)
type (
evented struct {
events map[string]int
}
before struct {
model
evented
errorBeforeSave bool
errorBeforeInsert bool
errorBeforeUpdate bool
}
after struct {
model
evented
errorAfterSave bool
errorAfterInsert bool
errorAfterUpdate bool
}
)
func (e *evented) setup() {
if e.events == nil {
e.events = make(map[string]int)
}
}
func (b *before) BeforeInsert() error {
b.setup()
b.events["BeforeInsert"]++
if b.errorBeforeInsert {
return errors.New("foo")
}
return nil
}
func (b *before) BeforeUpdate() error {
b.setup()
b.events["BeforeUpdate"]++
if b.errorBeforeUpdate {
return errors.New("foo")
}
return nil
}
func (b *before) BeforeSave() error {
b.setup()
b.events["BeforeSave"]++
if b.errorBeforeSave {
return errors.New("foo")
}
return nil
}
func (b *after) AfterInsert() error {
b.setup()
b.events["AfterInsert"]++
if b.errorAfterInsert {
return errors.New("foo")
}
return nil
}
func (b *after) AfterUpdate() error {
b.setup()
b.events["AfterUpdate"]++
if b.errorAfterUpdate {
return errors.New("foo")
}
return nil
}
func (b *after) AfterSave() error {
b.setup()
b.events["AfterSave"]++
if b.errorAfterSave {
return errors.New("foo")
}
return nil
}
func TestApplyBeforeEvents(t *testing.T) {
r := require.New(t)
var before before
r.Nil(ApplyBeforeEvents(&before))
before.setPersisted()
r.Nil(ApplyBeforeEvents(&before))
r.Equal(1, before.events["BeforeInsert"])
r.Equal(1, before.events["BeforeUpdate"])
r.Equal(2, before.events["BeforeSave"])
before.errorBeforeUpdate = true
r.NotNil(ApplyBeforeEvents(&before))
before.errorBeforeInsert = true
before.errorBeforeUpdate = false
before.persisted = false
r.NotNil(ApplyBeforeEvents(&before))
before.errorBeforeSave = true
before.errorBeforeInsert = false
r.NotNil(ApplyBeforeEvents(&before))
}
func TestApplyAfterEvents(t *testing.T) {
r := require.New(t)
var after after
r.Nil(ApplyAfterEvents(&after, false))
r.Nil(ApplyAfterEvents(&after, true))
r.Equal(1, after.events["AfterInsert"])
r.Equal(1, after.events["AfterUpdate"])
r.Equal(2, after.events["AfterSave"])
after.errorAfterUpdate = true
r.NotNil(ApplyAfterEvents(&after, true))
after.errorAfterInsert = true
after.errorAfterUpdate = false
r.NotNil(ApplyAfterEvents(&after, false))
after.errorAfterSave = true
after.errorAfterInsert = false
r.NotNil(ApplyAfterEvents(&after, false))
}