blob: ac5d4b4c41d5c7d24dc73e7c097c0867702266cf (
plain)
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
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Paul Buetow
package repl
import (
"os"
"sync"
"sync/atomic"
"syscall"
"testing"
"time"
)
func TestNewSignalHandler(t *testing.T) {
h := NewSignalHandler()
if h == nil {
t.Fatal("NewSignalHandler returned nil")
}
}
func TestSignalHandlerStop(t *testing.T) {
h := NewSignalHandler()
// Stop should not panic on a handler that hasn't started
h.Stop()
}
func TestSignalHandlerStartExecutesCallback(t *testing.T) {
h := NewSignalHandler()
defer h.Stop()
var wg sync.WaitGroup
wg.Add(1)
h.Start(func() {
wg.Done()
})
// Send SIGINT to ourselves to trigger the handler
pid := os.Getpid()
if err := syscall.Kill(pid, syscall.SIGINT); err != nil {
t.Skipf("cannot send signal: %v", err)
}
// Wait for callback with timeout
done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()
select {
case <-done:
// Callback was executed
case <-time.After(2 * time.Second):
t.Error("callback was not executed within timeout")
}
}
func TestSignalHandlerStartCallbackRunsInGoroutine(t *testing.T) {
h := NewSignalHandler()
defer h.Stop()
started := make(chan struct{})
finished := make(chan struct{})
h.Start(func() {
close(started)
// Simulate some work
time.Sleep(100 * time.Millisecond)
close(finished)
})
// Send SIGINT to trigger
pid := os.Getpid()
if err := syscall.Kill(pid, syscall.SIGINT); err != nil {
t.Skipf("cannot send signal: %v", err)
}
// Start() should return immediately (goroutine)
select {
case <-started:
// Good, callback started
case <-time.After(2 * time.Second):
t.Error("callback goroutine did not start")
}
// Wait for it to finish
select {
case <-finished:
// Good
case <-time.After(2 * time.Second):
t.Error("callback goroutine did not finish")
}
}
func TestSignalHandlerSingleShot(t *testing.T) {
h := NewSignalHandler()
var callbackCount atomic.Int32
h.Start(func() {
callbackCount.Add(1)
})
// First signal should trigger callback
pid := os.Getpid()
if err := syscall.Kill(pid, syscall.SIGINT); err != nil {
t.Skipf("cannot send signal: %v", err)
}
time.Sleep(200 * time.Millisecond)
// The handler is single-shot: after consuming one signal the goroutine exits.
// Stop() unregisters the signal channel.
h.Stop()
if callbackCount.Load() != 1 {
t.Errorf("expected callback count 1, got %d", callbackCount.Load())
}
}
|