Skip to content

Commit 2b51d5d

Browse files
committed
feat: add ResetForTesting function to enable isolated testing of shutdown hooks
1 parent 41278d6 commit 2b51d5d

2 files changed

Lines changed: 26 additions & 12 deletions

File tree

shutdown/shutdown.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,3 +105,20 @@ func finalize(title string) {
105105
log.Println("##########")
106106
}
107107
}
108+
109+
// ResetForTesting resets the singleton observer instance so that tests can run in isolation.
110+
//
111+
// WARNING: This function is ONLY intended for use in tests! Calling this in production code
112+
// will remove all registered shutdown hooks and break graceful shutdown behavior.
113+
// There is NO recovery from this – all previously registered hooks are lost.
114+
//
115+
// Usage:
116+
//
117+
// func TestSomething(t *testing.T) {
118+
// defer shutdown.ResetForTesting()
119+
// // ... test code ...
120+
// }
121+
func ResetForTesting() {
122+
observerSingleton = nil
123+
once = sync.Once{}
124+
}

shutdown/shutdown_test.go

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,18 @@ package shutdown
33
import (
44
"errors"
55
"testing"
6+
7+
"github.com/stretchr/testify/assert"
68
)
79

810
func TestNilShutdown(t *testing.T) {
11+
defer ResetForTesting()
912
finalize("Should not fail")
1013
}
1114

1215
func TestSimpleShutdown(t *testing.T) {
16+
defer ResetForTesting()
17+
1318
count := 0
1419

1520
func1 := func() error {
@@ -31,17 +36,9 @@ func TestSimpleShutdown(t *testing.T) {
3136
GetObserver().AddCommand(func2)
3237
GetObserver().AddCommand(func3)
3338

34-
success, err := observerSingleton.executeCommands()
35-
36-
if count != 6 {
37-
t.Fatal("Wrong count after execution of commands: ", count, " should be ", 6)
38-
}
39+
success, failed := observerSingleton.executeCommands()
3940

40-
if success != 2 {
41-
t.Fatal("Success execution should be: 2 not ", success)
42-
}
43-
44-
if err != 1 {
45-
t.Fatal("Failed execution should be: 1 not ", err)
46-
}
41+
assert.Equal(t, 6, count, "count after execution of all commands")
42+
assert.Equal(t, 2, success, "successful executions")
43+
assert.Equal(t, 1, failed, "failed executions")
4744
}

0 commit comments

Comments
 (0)