-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafedown_test.go
847 lines (708 loc) · 25.8 KB
/
safedown_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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
// Package safedown_test contains all tests and examples for the
// safedown package.
//
// Due to the interaction of different methods, there will be
// duplications of tests cases. For example, testing that an
// action added via AddAction is performed when calling
// Shutdown occurs in the test for AddAction and Shutdown,
// although the description might differ slight.
package safedown_test
import (
"context"
"fmt"
"os"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/PeterEFinch/safedown"
)
// region Examples
// Example demonstrates how setting up the safedown's shutdown actions works
// when a signal is received.
func Example() {
// This will send an interrupt signal after a second to simulate a signal
// being sent from the outside.
go func(pid int) {
time.Sleep(time.Second)
process := os.Process{Pid: pid}
if err := process.Signal(os.Interrupt); err != nil {
panic("unable to continue test: could not send signal to process")
}
}(os.Getpid())
sa := safedown.NewShutdownActions(
safedown.ShutdownOnSignals(os.Interrupt),
safedown.UseOnSignalFunc(func(signal os.Signal) {
fmt.Printf("Signal received: %s\n", signal.String())
}),
)
defer sa.Shutdown()
ctx, cancel := context.WithCancel(context.Background())
sa.AddActions(cancel)
fmt.Println("Processing starting")
t := time.After(2 * time.Second)
select {
case <-ctx.Done():
fmt.Println("Context cancelled")
case <-t:
fmt.Println("Ticker ticked")
}
fmt.Println("Finished")
// Output:
// Processing starting
// Signal received: interrupt
// Context cancelled
// Finished
}
// Example_signalNotReceived demonstrates how setting up the safedown's
// shutdown actions works when no signal is received (and the program can
// terminate of its own accord).
func Example_noSignal() {
sa := safedown.NewShutdownActions(
safedown.ShutdownOnSignals(os.Interrupt),
safedown.UseOnSignalFunc(func(signal os.Signal) {
fmt.Printf("Signal received: %s\n", signal.String())
}),
)
defer sa.Shutdown()
ctx, cancel := context.WithCancel(context.Background())
sa.AddActions(cancel)
fmt.Println("Processing starting")
t := time.After(2 * time.Second)
select {
case <-ctx.Done():
fmt.Println("Context cancelled")
case <-t:
fmt.Println("Ticker ticked")
}
fmt.Println("Finished")
// Output:
// Processing starting
// Ticker ticked
// Finished
}
// ExampleShutdownActions_Shutdown demonstrates the default
// shutdown behaviour.
func ExampleShutdownActions_Shutdown() {
sa := safedown.NewShutdownActions()
sa.AddActions(func() {
fmt.Println("The action is performed after shutdown is called.")
})
fmt.Println("Code runs before shutdown is called.")
sa.Shutdown()
// Output:
// Code runs before shutdown is called.
// The action is performed after shutdown is called.
}
// ExampleUseOrder_firstInFirstDone demonstrates the "first in, first done"
// order.
func ExampleUseOrder_firstInFirstDone() {
sa := safedown.NewShutdownActions(
safedown.UseOrder(safedown.FirstInFirstDone),
)
sa.AddActions(func() {
fmt.Println("The first action added will be done first ...")
})
sa.AddActions(func() {
fmt.Println("... and the last action added will be done last.")
})
sa.Shutdown()
// Output:
// The first action added will be done first ...
// ... and the last action added will be done last.
}
// ExampleUseOrder_firstInFirstDone demonstrates the "first in, last done"
// order.
func ExampleUseOrder_firstInLastDone() {
sa := safedown.NewShutdownActions(
safedown.UseOrder(safedown.FirstInLastDone),
)
sa.AddActions(func() {
fmt.Println("... and the first action added will be done last.")
})
sa.AddActions(func() {
fmt.Println("The last action added will be done first ...")
})
sa.Shutdown()
// Output:
// The last action added will be done first ...
// ... and the first action added will be done last.
}
// ExampleUsePostShutdownStrategy demonstrates how to set a post shutdown strategy
// and its consequences.
func ExampleUsePostShutdownStrategy() {
sa := safedown.NewShutdownActions(
safedown.UsePostShutdownStrategy(safedown.PerformCoordinatelyInBackground),
)
sa.AddActions(func() {
fmt.Println("... and the first action added will be done after that.")
})
sa.AddActions(func() {
fmt.Println("The last action added will be done first ...")
})
sa.Shutdown()
wg := sync.WaitGroup{}
wg.Add(1)
sa.AddActions(func() {
fmt.Println("The action added after shutdown is also done (provided we wait a little).")
wg.Done()
})
wg.Wait()
// Output:
// The last action added will be done first ...
// ... and the first action added will be done after that.
// The action added after shutdown is also done (provided we wait a little).
}
// endregion
// region Tests
// TestNewShutdownActions tests the NewShutdownActions constructor.
func TestNewShutdownActions(t *testing.T) {
// Test that the constructor can be called without panicking.
t.Run("no_panic", func(t *testing.T) {
safedown.NewShutdownActions()
})
}
// TestShutdownActions_AddActions tests the behaviour of the AddActions.
func TestShutdownActions_AddActions(t *testing.T) {
// Testing that a single added action is performed on shutdown
t.Run("single", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions()
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
})
// Testing that multiple actions added in one call are performed
// on shutdown.
t.Run("multiple_inputs", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions()
sa.AddActions(
createTestableShutdownAction(t, wg, counter, 3),
createTestableShutdownAction(t, wg, counter, 2),
createTestableShutdownAction(t, wg, counter, 1),
)
sa.Shutdown()
})
// Testing that actions added in multiple call are performed
// on shutdown.
t.Run("multiple calls", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions()
sa.AddActions(createTestableShutdownAction(t, wg, counter, 3))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 2))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
})
}
// TestShutdownActions_Shutdown tests the behaviour of the shutdown method.
func TestShutdownActions_Shutdown(t *testing.T) {
// Testing that all shutdown actions are performed.
t.Run("completeness", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions()
sa.AddActions(createTestableShutdownAction(t, wg, counter, 3))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 2))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
})
// Testing that the shutdown method is idempotent.
t.Run("idempotency", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions()
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
sa.Shutdown()
})
}
// TestShutdownActions_Wait tests the behaviour of the wait method.
func TestShutdownActions_Wait(t *testing.T) {
// The test cases are not
const minimumWaitDuration = 10 * time.Millisecond
// Tests that the Wait method waits before a shutdown and not after one.
t.Run("shutdown", func(t *testing.T) {
sa := safedown.NewShutdownActions()
assertMethodIsTemporarilyBlocking(t, sa.Wait, minimumWaitDuration, "wait function before shutdown")
// The inclusion of the wait means that if wait still blocks after shutdown
// then this test will run into a timeout.
sa.Shutdown()
sa.Wait()
})
// TestShutdownActions_Wait_withSignal tests that the wait method waits before
// a signal and not after one.
t.Run("shutdown_on_signal", func(t *testing.T) {
sa := safedown.NewShutdownActions(safedown.ShutdownOnSignals(os.Interrupt))
assertMethodIsTemporarilyBlocking(t, sa.Wait, minimumWaitDuration, "wait function before signal received")
// The inclusion of the wait means that if wait still blocks after shutdown
// then this test will run into a timeout.
sendOSSignalToSelf(os.Interrupt)
sa.Wait()
})
}
// TestUseOrder tests the use of the safedown.ShutdownOnAnySignal option.
func TestShutdownOnAnySignal(t *testing.T) {
// Tests that the shutdown actions can still be shut down manually.
t.Run("shutdown", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(safedown.ShutdownOnAnySignal())
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
})
// Tests that shutdown will be called when a signal is received.
t.Run("signal", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(safedown.ShutdownOnAnySignal())
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sendOSSignalToSelf(os.Interrupt)
})
// Tests that multiple shutdown actions can be initialised listing for the same
// signal and both of them shutdown.
t.Run("multiple_actions", func(t *testing.T) {
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
counter1 := new(int32)
sa1 := safedown.NewShutdownActions(safedown.ShutdownOnAnySignal())
sa1.AddActions(createTestableShutdownAction(t, wg, counter1, 1))
counter2 := new(int32)
sa2 := safedown.NewShutdownActions(safedown.ShutdownOnAnySignal())
sa2.AddActions(createTestableShutdownAction(t, wg, counter2, 1))
sendOSSignalToSelf(os.Interrupt)
})
}
// TestUseOrder tests the use of the safedown.ShutdownOnSignals option.
func TestShutdownOnSignals(t *testing.T) {
// Tests that the shutdown actions can still be shut down manually.
t.Run("shutdown", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(safedown.ShutdownOnSignals(os.Interrupt))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
})
// Tests that shutdown will be called when a signal is received.
t.Run("signal", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(safedown.ShutdownOnSignals(os.Interrupt))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sendOSSignalToSelf(os.Interrupt)
})
// Tests that multiple shutdown actions can be initialised listing for different
// signals and only one of them shutdown.
t.Run("multiple_shutdown_actions_listening_for_different_signals", func(t *testing.T) {
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
counter1 := new(int32)
sa1 := safedown.NewShutdownActions(safedown.ShutdownOnSignals(os.Interrupt))
sa1.AddActions(createTestableShutdownAction(t, wg, counter1, 1))
counter2 := new(int32)
sa2 := safedown.NewShutdownActions(safedown.ShutdownOnSignals(os.Kill))
sa2.AddActions(createTestableShutdownAction(t, wg, counter2, -1)) // This action must never be called
sendOSSignalToSelf(os.Interrupt)
// The extra call to Done are required because `sa2` will never be triggered.
wg.Done()
})
// Tests that multiple shutdown actions can be initialised listing for the same
// signal and both of them shutdown.
t.Run("multiple_shutdown_actions_listening_for_same_signal", func(t *testing.T) {
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
counter1 := new(int32)
sa1 := safedown.NewShutdownActions(safedown.ShutdownOnSignals(os.Interrupt))
sa1.AddActions(createTestableShutdownAction(t, wg, counter1, 1))
counter2 := new(int32)
sa2 := safedown.NewShutdownActions(safedown.ShutdownOnSignals(os.Interrupt))
sa2.AddActions(createTestableShutdownAction(t, wg, counter2, 1))
sendOSSignalToSelf(os.Interrupt)
})
}
// TestUseOrder tests the use of the safedown.UseOnSignalFunc option.
func TestUseOnSignalFunc(t *testing.T) {
// Tests that the function passed in the UseOnSignalFunc does nothing
// if shutdown is called.
t.Run("shutdown", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(
safedown.ShutdownOnAnySignal(),
safedown.UseOnSignalFunc(func(signal os.Signal) {
t.Logf("unexpected signal received: %v", signal)
t.FailNow()
}),
)
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
})
// Tests that the function passed in the UseOnSignalFunc is called if a
// signal is sent.
t.Run("signal", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(
safedown.ShutdownOnAnySignal(),
safedown.UseOnSignalFunc(createTestableOnSignalFunction(t, wg, os.Interrupt)),
)
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sendOSSignalToSelf(os.Interrupt)
})
}
// TestUseOrder tests the use of the safedown.UseOrder option.
func TestUseOrder(t *testing.T) {
// Tests that all shutdown actions are performed in order when
// safedown.UseOrder() is not used.
t.Run("unused", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions()
sa.AddActions(createTestableShutdownAction(t, wg, counter, 3))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 2))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
})
// Tests that all shutdown actions are performed in order when using:
// safedown.UseOrder(safedown.FirstInLastDone).
t.Run("first_in_last_done", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(
safedown.UseOrder(safedown.FirstInLastDone),
)
sa.AddActions(createTestableShutdownAction(t, wg, counter, 3))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 2))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
})
// Tests that all shutdown actions are performed in order when using:
// safedown.UseOrder(safedown.FirstInFirstDone).
t.Run("first_in_first_down", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(
safedown.UseOrder(safedown.FirstInFirstDone),
)
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 2))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 3))
sa.Shutdown()
})
// Tests that if an invalid order is used the option will panic.
t.Run("invalid_order", func(t *testing.T) {
defer func() {
var panicked bool
if r := recover(); r != nil {
panicked = true
}
if !panicked {
t.Log("safedown.UseOrder was expected to panic")
t.Fail()
}
}()
safedown.UseOrder(42)
})
}
// TestUseOrder tests the use of the safedown.UsePostShutdownStrategy option.
func TestUsePostShutdownStrategy(t *testing.T) {
// Tests that no actions will be performed after shutdown has been called
// when UsePostShutdownStrategy is not used.
t.Run("unused", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions()
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
sa.AddActions(createTestableShutdownAction(t, wg, counter, -1))
wg.Done()
})
// Tests that no actions will be performed after shutdown has been called
// when using safedown.UsePostShutdownStrategy(safedown.DoNothing).
t.Run("do_nothing", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(safedown.UsePostShutdownStrategy(safedown.DoNothing))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
sa.AddActions(createTestableShutdownAction(t, wg, counter, -1))
wg.Done()
})
// Tests that actions can be performed after shutdown has been called in a way that
// matches the PerformCoordinatelyInBackground description.
t.Run("perform_coordinately_in_background", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(safedown.UsePostShutdownStrategy(safedown.PerformCoordinatelyInBackground))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 2))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
// The first action added will start the processing actions and will be the
// first to be started. However, due to the delay the other two actions
// will be added to a wait list. Due to the order the last will of the two
// will be done first.
sa.AddActions(createTestableShutdownActionWithDelay(t, wg, counter, 3, 5*time.Millisecond))
time.Sleep(time.Millisecond)
sa.AddActions(createTestableShutdownAction(t, wg, counter, 5))
time.Sleep(time.Millisecond)
sa.AddActions(createTestableShutdownAction(t, wg, counter, 4))
time.Sleep(time.Millisecond)
})
// Tests that actions can be performed after shutdown has been called in a way that
// matches the PerformImmediately description.
t.Run("perform_immediately", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(safedown.UsePostShutdownStrategy(safedown.PerformImmediately))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 2))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
sa.AddActions(createTestableShutdownActionWithDelay(t, wg, counter, 3, 5*time.Millisecond))
sa.AddActions(
createTestableShutdownAction(t, wg, counter, 5),
createTestableShutdownAction(t, wg, counter, 4),
)
})
// Tests that actions can be performed after shutdown has been called in a way that
// matches the PerformImmediatelyInBackground description.
t.Run("perform_immediately_in_background", func(t *testing.T) {
counter := new(int32)
wg := new(sync.WaitGroup)
defer assertWaitGroupDoneBeforeDeadline(t, wg, time.Now().Add(time.Second))
sa := safedown.NewShutdownActions(safedown.UsePostShutdownStrategy(safedown.PerformImmediatelyInBackground))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 2))
sa.AddActions(createTestableShutdownAction(t, wg, counter, 1))
sa.Shutdown()
// All actions will start immediately in a go routine. It is a race
// condition to determine which will increment the counter first. Due to the
// delays/sleeps we obtain the expected values.
sa.AddActions(createTestableShutdownActionWithDelay(t, wg, counter, 6, 5*time.Millisecond))
time.Sleep(time.Millisecond)
sa.AddActions(createTestableShutdownAction(t, wg, counter, 3))
time.Sleep(time.Millisecond)
sa.AddActions(
createTestableShutdownAction(t, wg, counter, 5),
createTestableShutdownAction(t, wg, counter, 4),
)
time.Sleep(time.Millisecond)
})
// Tests that if an invalid strategy is used the option will panic.
t.Run("invalid_strategy", func(t *testing.T) {
defer func() {
var panicked bool
if r := recover(); r != nil {
panicked = true
}
if !panicked {
t.Log("safedown.UsePostShutdownStrategy was expected to panic")
t.Fail()
}
}()
safedown.UsePostShutdownStrategy(42)
})
}
// assertCounterValue fails the test if the value stored in the counter does
// not match the expected value.
func assertCounterValue(t *testing.T, counter *int32, expectedValue int32, scenario string) {
actualValue := atomic.LoadInt32(counter)
if actualValue == expectedValue {
return
}
t.Logf("%s: mismatch between expected value (%d) and actual value (%d)", scenario, expectedValue, actualValue)
t.FailNow()
}
// assertMethodIsTemporarilyBlocking checks that the method provided blocks for
// the duration provided.
//
// This is useful for checking methods that are expected to temporarily block.
// The assertion utilises concurrency and may give false results on occasion.
// The duration should be sufficient to take into account the starting of a
// goroutine. It is only intended for very simple blocking methods e.g. ones
// that are solely waiting on a chan to be closed.
func assertMethodIsTemporarilyBlocking(t *testing.T, method func(), duration time.Duration, scenario string) {
var state int32
go func() {
method()
atomic.StoreInt32(&state, 1)
}()
time.Sleep(duration)
if !atomic.CompareAndSwapInt32(&state, 0, 1) {
t.Logf("%s: method failed to block for duration", scenario)
t.FailNow()
}
}
func assertSignalEquality(t *testing.T, actual, expected os.Signal) {
if actual == expected {
return
}
t.Logf("mismatch between expected signal (%d) and actual signal (%d) received", expected, actual)
t.FailNow()
}
// assertWaitGroupDoneBeforeDeadline is a way to quickly check that a test
// does not wait for a long time.
func assertWaitGroupDoneBeforeDeadline(t *testing.T, wg *sync.WaitGroup, deadline time.Time) {
/*
There is an accepted proposal in which each test can have its own
individual timeout (https://github.com/golang/go/issues/48157). Once
this has been implemented then this function can be removed.
*/
success := make(chan struct{})
go func() {
wg.Wait()
close(success)
}()
// A context was chosen over a ticker in case the deadline was in the past.
ctx, cancel := context.WithDeadline(context.Background(), deadline)
defer cancel()
select {
case <-success:
case <-ctx.Done():
t.Logf("wait group was not done before deadline")
t.FailNow()
}
}
// createTestableShutdownAction creates an action to be used in tests. The
// counter is included to ensure that the actions occur the in the correct
// order.
func createTestableShutdownAction(t *testing.T, wg *sync.WaitGroup, counter *int32, expectedValue int32) func() {
wg.Add(1)
return func() {
atomic.AddInt32(counter, 1)
assertCounterValue(t, counter, expectedValue, "the counter in testable action encountered an issue")
wg.Done()
}
}
// createTestableShutdownActionWithDelay creates a testable action
// using createTestableShutdownAction but adds a delay before the action is
// performed.
//
// This is useful when for testing behaviour that happens asynchronously.
// Consequently, it is unreliable and is expected to sometimes fail.
func createTestableShutdownActionWithDelay(t *testing.T, wg *sync.WaitGroup, counter *int32, expectedValue int32, delay time.Duration) func() {
action := createTestableShutdownAction(t, wg, counter, expectedValue)
return func() {
time.Sleep(delay)
action()
}
}
func createTestableOnSignalFunction(t *testing.T, wg *sync.WaitGroup, expectedSignal os.Signal) func(os.Signal) {
wg.Add(1)
return func(signal os.Signal) {
assertSignalEquality(t, signal, expectedSignal)
wg.Done()
}
}
func sendOSSignalToSelf(signal os.Signal) {
process := os.Process{Pid: os.Getpid()}
if err := process.Signal(signal); err != nil {
panic(fmt.Sprintf("test failed: unable to send signal (%v) to self", signal))
}
}
// endregion
// region Benchmarks
func BenchmarkNewShutdownActions(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = safedown.NewShutdownActions()
}
}
func BenchmarkShutdownActions_AddActions(b *testing.B) {
b.Run("single_action", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
sa := safedown.NewShutdownActions()
sa.AddActions(func() {})
}
})
b.Run("multiple_actions_in_one_call", func(b *testing.B) {
actions := make([]func(), 100)
for i := range actions {
actions[i] = func() {}
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
sa := safedown.NewShutdownActions()
sa.AddActions(actions...)
}
})
b.Run("multiple_actions_in_multiple_calls", func(b *testing.B) {
actions := make([]func(), 100)
for i := range actions {
actions[i] = func() {}
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
sa := safedown.NewShutdownActions()
for _, action := range actions {
sa.AddActions(action)
}
}
})
}
func BenchmarkShutdownActions_Shutdown(b *testing.B) {
b.Run("no_actions", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
sa := safedown.NewShutdownActions()
sa.Shutdown()
}
})
b.Run("single_action", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
sa := safedown.NewShutdownActions()
sa.AddActions(func() {})
sa.Shutdown()
}
})
b.Run("many_actions", func(b *testing.B) {
actions := make([]func(), 100)
for i := range actions {
actions[i] = func() {}
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
sa := safedown.NewShutdownActions()
sa.AddActions(actions...)
sa.Shutdown()
}
})
b.Run("idempotency", func(b *testing.B) {
sa := safedown.NewShutdownActions()
sa.AddActions(func() {})
sa.Shutdown()
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
sa.Shutdown()
}
})
}
// endregion