-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraceful_test.go
76 lines (63 loc) · 1.53 KB
/
graceful_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
package graceful
import (
"sync/atomic"
"testing"
"time"
)
func TestOnShutdownHandlersAreExecuted(t *testing.T) {
Initialize()
var counter int32 = 0
// Register three handlers that increment the counter
OnShutdown(func() {
atomic.AddInt32(&counter, 1)
})
OnShutdown(func() {
atomic.AddInt32(&counter, 1)
})
OnShutdown(func() {
atomic.AddInt32(&counter, 1)
})
// Trigger the shutdown process
triggerShutdown()
Wait()
// Verify that all handlers were executed
expected := int32(3)
if counter != expected {
t.Errorf("Expected %d handlers to be executed, got %d", expected, counter)
}
}
func TestJobCounterLogic(t *testing.T) {
Initialize()
var (
jobStarted int32
jobCompleted int32
)
// Define a job that increments jobStarted upon start,
// waits, then signals completion
job := func() {
if IncrementJobCounter() {
atomic.AddInt32(&jobStarted, 1)
// Simulate job work...
DecrementJobCounter()
atomic.AddInt32(&jobCompleted, 1)
}
}
// Start a few jobs
go job()
go job()
go job()
// Allow some time for jobs to start
time.Sleep(100 * time.Millisecond)
// Initiate shutdown process
triggerShutdown()
// Attempt to start another job which should fail as shutdown has started
if IncrementJobCounter() {
t.Fatal("Was able to start a job after shutdown process began")
}
// Wait for the shutdown to complete
Wait()
// Verify that all started jobs have completed
if jobStarted != jobCompleted {
t.Errorf("Not all jobs completed: started %d, completed %d", jobStarted, jobCompleted)
}
}