-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathshutter_test.go
141 lines (122 loc) · 2.35 KB
/
shutter_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
139
140
141
package shutter
import (
"errors"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
func TestShutterTerminating(t *testing.T) {
a := 0
s := NewWithCallback(func(_ error) {
time.Sleep(10*time.Millisecond)
a++
})
go func() {
select {
case <-s.Terminating():
assert.Equal(t, 0, a)
case <-s.Terminated():
assert.Equal(t, 1, a)
case <-time.After(50 * time.Millisecond):
t.Errorf("terminating channel was not closed as expected")
}
}()
s.Shutdown(nil)
}
func TestShutterTerminated(t *testing.T) {
a := 0
s := NewWithCallback(func(_ error) {
time.Sleep(10*time.Millisecond)
a++
})
go func() {
select {
case <-s.Terminated():
assert.Equal(t, 1, a)
case <-time.After(50 * time.Millisecond):
t.Errorf("terminating channel was not closed as expected")
}
}()
s.Shutdown(nil)
}
func TestShutterDeadlock(t *testing.T) {
obj := struct {
*Shutter
}{}
s := NewWithCallback(func(_ error) {
obj.Shutdown(errors.New("ouch"))
})
obj.Shutter = s
obj.Shutdown(errors.New("first"))
assert.Equal(t, obj.Err(), errors.New("first"))
}
func TestMultiCallbacks(t *testing.T) {
s := New()
var a int
s.OnShutdown(func(_ error) {
a++
})
s.OnShutdown(func(_ error) {
a++
})
s.Shutdown(nil)
assert.Equal(t, 2, a)
}
func TestLockedInitAlreadyShutdown(t *testing.T) {
s := New()
a := 0
s.OnShutdown(func(_ error) {
a--
})
s.Shutdown(nil)
err := s.LockedInit(func() error {
a++
return nil
})
assert.Equal(t, -1, a)
assert.Equal(t, ErrShutterWasAlreadyDown, err)
}
func TestLockedInitNotShutdown(t *testing.T) {
s := New()
a := 0
s.OnShutdown(func(_ error) {
a--
})
err := s.LockedInit(func() error {
a++
return nil
})
assert.NoError(t, err)
s.Shutdown(nil)
assert.Equal(t, 0, a)
}
func TestShutdownDuringLockedInit(t *testing.T) {
s := New()
a := 0
s.OnShutdown(func(_ error) {
a--
})
var err error
inLockedInitCh := make(chan interface{})
shutdownCalled := make(chan interface{})
go func() {
err = s.LockedInit(func() error {
close(inLockedInitCh)
select {
case <-shutdownCalled:
t.Errorf("Shutdown was called and completed while in LockedInit")
case <-time.After(50 * time.Millisecond):
return nil
}
return nil
})
}()
<-inLockedInitCh
go func() {
s.Shutdown(nil)
close(shutdownCalled)
}()
assert.NoError(t, err)
<-shutdownCalled
assert.Equal(t, -1, a)
}