-
Notifications
You must be signed in to change notification settings - Fork 1
/
service_test.go
387 lines (327 loc) · 8.44 KB
/
service_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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package service_test
import (
"context"
"fmt"
"github.com/niondir/go-service"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"log/slog"
"testing"
"time"
)
var _ service.Initer = &testService{}
var _ service.Runner = &testService{}
var _ fmt.Stringer = testService{}
// testService is a service that tracks it's state to be checked in tests
type testService struct {
Name string
// An error that will be returned in init
ErrorDuringInit error
// An error that will be returned during run
ErrorDuringRun error
// An error that will be returned when the service shut down
ErrorAfterRun error
// If set the service will not wait for <-ctx.Done()
SkipWaitForCtx bool
initialized bool
started bool
running bool
stopped bool
err error
startedCh chan struct{}
}
func (t testService) String() string {
return fmt.Sprintf("testService.%s", t.Name)
}
func (t *testService) Init(ctx context.Context) error {
if t.initialized {
return fmt.Errorf("service %s was already initialized", t.Name)
}
if t.ErrorDuringInit != nil {
return t.ErrorDuringInit
}
t.startedCh = make(chan struct{})
t.initialized = true
return nil
}
func (t *testService) Run(ctx context.Context) error {
if t.running {
return fmt.Errorf("service %s already running", t.Name)
}
t.running = true
if t.started {
return fmt.Errorf("service %s was already started", t.Name)
}
t.started = true
if t.startedCh != nil {
close(t.startedCh)
}
if t.ErrorDuringRun != nil {
t.running = false
t.stopped = true
return t.ErrorDuringRun
}
if !t.SkipWaitForCtx {
<-ctx.Done()
}
t.running = false
if t.stopped {
return fmt.Errorf("service %s was already stopped", t.Name)
}
t.stopped = true
return t.ErrorAfterRun
}
func assertServiceStartedAndStopped(t *testing.T, s *testService) {
t.Helper()
assert.True(t, s.initialized, "initialized")
assert.True(t, s.started, "started")
assert.True(t, s.stopped, "stopped")
assert.False(t, s.running, "running")
assert.NoError(t, s.err, "err")
}
func assertServiceStillRunning(t *testing.T, s *testService) {
t.Helper()
assert.True(t, s.initialized)
assert.True(t, s.started)
assert.False(t, s.stopped, "Stopped")
assert.True(t, s.running, "Still Running")
assert.NoError(t, s.err)
}
func assertServiceOnlyInitialized(t *testing.T, s *testService) {
t.Helper()
assert.True(t, s.initialized)
assert.False(t, s.started)
assert.False(t, s.stopped)
assert.False(t, s.running)
assert.NoError(t, s.err)
}
func assertServiceNeverStarted(t *testing.T, s *testService) {
t.Helper()
assert.False(t, s.initialized)
assert.False(t, s.started)
assert.False(t, s.stopped)
assert.False(t, s.running)
assert.NoError(t, s.err)
}
func TestStartAndStopWithContext(t *testing.T) {
c := service.NewContainer()
s1 := &testService{
Name: "s1",
}
c.Register(s1)
ctx, cancelCtx := context.WithCancel(context.Background())
err := c.StartAll(ctx)
require.NoError(t, err)
cancelCtx()
c.WaitAllStopped()
assert.Len(t, c.ServiceErrors(), 0)
assertServiceStartedAndStopped(t, s1)
}
func TestStartAndStopWithContext_timeout(t *testing.T) {
c := service.NewContainer()
s1 := &testService{
Name: "s1",
}
c.Register(s1)
err := c.StartAll(context.Background())
require.NoError(t, err)
c.WaitAllStoppedTimeout(100 * time.Millisecond)
assert.Len(t, c.ServiceErrors(), 0)
assertServiceStillRunning(t, s1)
}
// Start and Stop multiple services (happy path)
func TestStartAndStop(t *testing.T) {
c := service.NewContainer()
s1 := &testService{
Name: "s1",
}
c.Register(s1)
s2 := &testService{
Name: "s2",
}
c.Register(s2)
err := c.StartAll(context.Background())
require.NoError(t, err)
c.StopAll()
c.WaitAllStopped()
assert.Len(t, c.ServiceErrors(), 0)
assertServiceStartedAndStopped(t, s1)
assertServiceStartedAndStopped(t, s2)
}
// Start 3 services, the second will just return but the other two will keep running
func TestServiceCanReturnWithoutError(t *testing.T) {
c := service.NewContainer()
s1 := &testService{
Name: "s1",
}
c.Register(s1)
s2 := &testService{
Name: "s2",
SkipWaitForCtx: true,
}
c.Register(s2)
s3 := &testService{
Name: "s3",
}
c.Register(s3)
err := c.StartAll(context.Background())
require.NoError(t, err)
// wait all started
<-s1.startedCh
<-s2.startedCh
<-s3.startedCh
assertServiceStillRunning(t, s1)
assertServiceStartedAndStopped(t, s2)
assertServiceStillRunning(t, s3)
assert.Len(t, c.ServiceNames(), 3)
assert.Equal(t, 2, c.RunningCount())
c.StopAll()
c.WaitAllStopped()
assert.Len(t, c.ServiceErrors(), 0)
assertServiceStartedAndStopped(t, s1)
assertServiceStartedAndStopped(t, s2)
assertServiceStartedAndStopped(t, s2)
}
// Start 3 services, the second fails during init, none should run
func TestStopWhenInitFails(t *testing.T) {
c := service.NewContainer()
s1 := &testService{
Name: "s1",
}
c.Register(s1)
s2 := &testService{
Name: "s2",
ErrorDuringInit: fmt.Errorf("service failed during init"),
}
c.Register(s2)
s3 := &testService{
Name: "s3",
}
c.Register(s3)
runCtx, runCtxCancel := context.WithCancel(context.Background())
defer runCtxCancel()
err := c.StartAll(runCtx)
require.Error(t, err)
// Expect all services to stop, since there was an error
c.WaitAllStopped()
assert.Len(t, c.ServiceErrors(), 0)
assertServiceOnlyInitialized(t, s1)
assertServiceNeverStarted(t, s2)
assertServiceNeverStarted(t, s3)
}
// Start 3 services, the second fails during run
func TestStopWhenRunFails(t *testing.T) {
c := service.NewContainer()
s1 := &testService{
Name: "s1",
}
c.Register(s1)
s2 := &testService{
Name: "s2",
ErrorDuringRun: fmt.Errorf("service failed during run"),
}
c.Register(s2)
s3 := &testService{
Name: "s3",
}
c.Register(s3)
runCtx, runCtxCancel := context.WithCancel(context.Background())
defer runCtxCancel()
err := c.StartAll(runCtx)
require.NoError(t, err)
// Expect all services to stop, since there was an error
c.WaitAllStopped()
require.Len(t, c.ServiceErrors(), 1)
errs := c.ServiceErrors()
assert.NotNil(t, errs[s2.String()])
assertServiceStartedAndStopped(t, s1)
assertServiceStartedAndStopped(t, s2)
assertServiceStartedAndStopped(t, s3)
}
// Start 3 services, the second fails after run
func TestErrorOnShutdown(t *testing.T) {
c := service.NewContainer()
s1 := &testService{
Name: "s1",
}
c.Register(s1)
s2 := &testService{
Name: "s2",
ErrorAfterRun: fmt.Errorf("service failed after run"),
}
c.Register(s2)
s3 := &testService{
Name: "s3",
}
c.Register(s3)
runCtx, runCtxCancel := context.WithCancel(context.Background())
defer runCtxCancel()
err := c.StartAll(runCtx)
require.NoError(t, err)
// Stop all services, s2 will return an error
c.StopAll()
c.WaitAllStopped()
require.Len(t, c.ServiceErrors(), 1)
errs := c.ServiceErrors()
assert.NotNil(t, errs[s2.String()])
assertServiceStartedAndStopped(t, s1)
assertServiceStartedAndStopped(t, s2)
assertServiceStartedAndStopped(t, s3)
}
func TestStartAndFailWithError(t *testing.T) {
c := service.NewContainer()
c.SetLogger(slog.Default())
s1 := &testService{
Name: "s1",
ErrorDuringRun: fmt.Errorf("something failed"),
}
c.Register(s1)
ctx := context.Background()
err := c.StartAll(ctx)
require.NoError(t, err)
select {
case <-ctx.Done():
t.Fatal("parent context canceled, note that this does no happen!")
case <-time.After(1 * time.Second):
assert.Len(t, c.ServiceErrors(), 1)
//t.Fatal("timeout, expected context to be canceled")
}
}
// When the context starts to shutdown because of any service error the application want's to get notified
func TestNotifyOnShutdown(t *testing.T) {
c := service.NewContainer()
c.SetLogger(slog.Default())
s1 := &testService{
Name: "s1",
ErrorDuringRun: fmt.Errorf("something failed"),
}
c.Register(s1)
s2 := &testService{
Name: "s2",
ErrorDuringRun: fmt.Errorf("something failed"),
}
c.Register(s2)
s3 := &testService{
Name: "s3-no-error",
}
c.Register(s3)
ctx, cancelCtx := context.WithCancel(context.Background())
err := c.StartAll(ctx)
require.NoError(t, err)
shutdownCalls := 0
c.OnShutdown(func() {
shutdownCalls++
cancelCtx()
})
ctxIsDone := false
select {
case <-ctx.Done():
ctxIsDone = true
case <-time.After(1 * time.Second):
t.Fatal("timeout, expected context to be canceled")
}
c.WaitAllStoppedTimeout(100 * time.Millisecond)
assert.Equal(t, 1, shutdownCalls)
assert.True(t, ctxIsDone)
assert.Len(t, c.ServiceErrors(), 2)
}