-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlifecycle_test.go
More file actions
358 lines (304 loc) · 9.19 KB
/
lifecycle_test.go
File metadata and controls
358 lines (304 loc) · 9.19 KB
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
package lifecycle_test
import (
"bytes"
"context"
"testing"
"time"
"github.com/aretw0/lifecycle"
"github.com/aretw0/lifecycle/pkg/events"
"github.com/aretw0/procio/proc"
)
// Test facade methods in the root package.
//
// NOTE: These tests primarily verify that the facade functions allow data to pass through correctly
// to the underlying packages. They are NOT intended to be exhaustive behavioral tests;
// those reside in `pkg/core/*` and `pkg/events`.
//
// We use a clean/integration style here where possible.
func TestLifecycle_Go(t *testing.T) {
done := make(chan bool)
lifecycle.Go(context.Background(), func(ctx context.Context) error {
done <- true
return nil
})
select {
case <-done:
// OK
case <-time.After(100 * time.Millisecond):
t.Error("Go func not executed")
}
}
func TestLifecycle_Job(t *testing.T) {
job := lifecycle.Job(func(ctx context.Context) error { return nil })
if job == nil {
t.Error("Job returned nil")
}
}
func TestLifecycle_Run(t *testing.T) {
// Verify that Run() correctly delegates to the runtime and executes the job.
// Since we are not running in parallel (t.Parallel() is not called),
// this is safe regarding signal handling within this package's test suite.
executed := false
err := lifecycle.Run(lifecycle.Job(func(ctx context.Context) error {
executed = true
return nil
}))
if err != nil {
t.Fatalf("Run returned error: %v", err)
}
if !executed {
t.Error("Job was not executed")
}
}
func TestLifecycle_Do(t *testing.T) {
ctx := context.Background()
// Do
err := lifecycle.Do(ctx, func(ctx context.Context) error {
return nil
})
if err != nil {
t.Errorf("Do failed: %v", err)
}
// DoDetached
err = lifecycle.DoDetached(ctx, func(ctx context.Context) error {
return nil
})
if err != nil {
t.Errorf("DoDetached failed: %v", err)
}
}
func TestLifecycle_Receive(t *testing.T) {
ch := make(chan int, 2)
ch <- 1
ch <- 2
close(ch)
count := 0
for range lifecycle.Receive(context.Background(), ch) {
count++
}
if count != 2 {
t.Errorf("Receive yielded %d items, expected 2", count)
}
}
func TestLifecycle_Sleep(t *testing.T) {
start := time.Now()
lifecycle.Sleep(context.Background(), 10*time.Millisecond)
if time.Since(start) < 10*time.Millisecond {
t.Error("Sleep returned too early")
}
}
// Aliases
func TestLifecycle_WorkerAliases(t *testing.T) {
w := lifecycle.NewBaseWorker("test")
if w.String() == "" {
t.Error("BaseWorker String empty")
}
s := lifecycle.NewSupervisor("sup", lifecycle.SupervisorStrategyOneForOne)
if s == nil {
t.Error("NewSupervisor returned nil")
}
p := lifecycle.NewProcessWorker("proc", "echo")
if p == nil {
t.Error("NewProcessWorker returned nil")
}
f := lifecycle.NewWorkerFromFunc("func", func(ctx context.Context) error { return nil })
if f == nil {
t.Error("NewWorkerFromFunc returned nil")
}
c := lifecycle.NewContainerWorker("cont", lifecycle.NewMockContainer("id"))
if c == nil {
t.Error("NewContainerWorker returned nil")
}
sm := lifecycle.NewSuspendManager()
if sm == nil {
t.Error("NewSuspendManager returned nil")
}
// Diagrams
state := lifecycle.WorkerState{Name: "test", Status: lifecycle.WorkerStatusPending}
if d := lifecycle.WorkerTreeDiagram(state); d == "" {
t.Error("Tree diagram empty")
}
if d := lifecycle.WorkerStateDiagram(state); d == "" {
t.Error("State diagram empty")
}
}
func TestLifecycle_SignalAliases(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sc := lifecycle.NewSignalContext(ctx,
lifecycle.WithForceExit(2),
lifecycle.WithResetTimeout(time.Second),
lifecycle.WithHookTimeout(time.Second),
lifecycle.WithCancelOnInterrupt(true),
)
if sc == nil {
t.Error("NewSignalContext returned nil")
}
state, ok := lifecycle.GetSignalState(sc)
if !ok {
t.Error("GetSignalState failed")
}
if lifecycle.SignalStateDiagram(state) == "" {
t.Error("Signal diagram empty")
}
if lifecycle.IsUnsafe(sc) {
t.Error("IsUnsafe should be false")
}
if lifecycle.GetForceExitThreshold(sc) != 2 {
t.Error("Force exit threshold mismatch")
}
hookCalled := false
lifecycle.OnShutdown(sc, func() { hookCalled = true })
lifecycle.Shutdown(sc)
lifecycle.Wait(sc) // Should trigger hooks
if !hookCalled {
// Note: Signal context shutdown hooks may run asynchronously.
// Wait() guarantees completion, but the race detector might flag if we read too early.
// This check is a best-effort verification of the happy path.
}
// ShutdownAndWait
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
sc2 := lifecycle.NewSignalContext(ctx2)
lifecycle.ShutdownAndWait(sc2)
// Should return
}
func TestLifecycle_Context(t *testing.T) {
ctx := lifecycle.Context()
if ctx == nil {
t.Fatal("Context returned nil")
}
defer ctx.Stop()
if _, ok := lifecycle.GetSignalState(ctx); !ok {
t.Error("Context did not return a signal state")
}
}
func TestLifecycle_EventAliases(t *testing.T) {
// Source Aliases
if lifecycle.NewInputSource() == nil {
t.Error("NewInputSource returned nil")
}
if lifecycle.NewTickerSource(time.Second) == nil {
t.Error("NewTickerSource returned nil")
}
if lifecycle.NewHealthCheckSource("test", func(ctx context.Context) error { return nil }) == nil {
t.Error("NewHealthCheckSource returned nil")
}
if lifecycle.NewWebhookSource(":0") == nil {
t.Error("NewWebhookSource returned nil")
}
if lifecycle.NewChannelSource(make(chan lifecycle.Event)) == nil {
t.Error("NewChannelSource returned nil")
}
if lifecycle.NewOSSignalSource() == nil {
t.Error("NewOSSignalSource returned nil")
}
if lifecycle.NewFileWatchSource("test") == nil {
t.Error("NewFileWatchSource returned nil")
}
// Handler Aliases
if lifecycle.NewShutdownHandler(func() {}) == nil {
t.Error("NewShutdownHandler returned nil")
}
if lifecycle.NewShutdownFunc(func() {}) == nil {
t.Error("NewShutdownFunc returned nil")
}
if lifecycle.NewReloadHandler(func(ctx context.Context) error { return nil }) == nil {
t.Error("NewReloadHandler returned nil")
}
suspend := lifecycle.NewSuspendHandler()
if suspend == nil {
t.Error("NewSuspendHandler returned nil")
}
shutdown := lifecycle.NewShutdownHandler(func() {})
if lifecycle.NewTerminateHandler(suspend, shutdown) == nil {
t.Error("NewTerminateHandler returned nil")
}
// Options
_ = lifecycle.WithInputBackoff(time.Second)
_ = lifecycle.WithInputMapping("foo", lifecycle.SuspendEvent{})
_ = lifecycle.WithHealthInterval(time.Second)
// TriggerEdge is from events package
_ = lifecycle.WithHealthStrategy(events.TriggerEdge)
_ = lifecycle.WithContinueOnFailure(true)
// Router
router := lifecycle.NewRouter()
if router == nil {
t.Error("NewRouter returned nil")
}
lifecycle.DefaultRouter = router
lifecycle.Handle("test", shutdown)
lifecycle.HandleFunc("test2", func(ctx context.Context, e lifecycle.Event) error { return nil })
}
func TestLifecycle_Interactive(t *testing.T) {
// Verify creation of the Interactive Router helper.
sh := lifecycle.NewSuspendHandler()
cmdCalled := false
cmdHandler := events.HandlerFunc(func(ctx context.Context, e events.Event) error {
cmdCalled = true
return nil
})
ir := lifecycle.NewInteractiveRouter(
lifecycle.WithSuspendOnInterrupt(sh),
lifecycle.WithShutdown(func() {}),
lifecycle.WithInput(true),
lifecycle.WithSignal(false),
lifecycle.WithCommand("test-cmd", cmdHandler),
)
// Verify command registration via Dispatch
ir.Dispatch(context.Background(), events.InputEvent{Command: "test-cmd"})
if !cmdCalled {
t.Error("Custom command handler was not called")
}
}
func TestLifecycle_Introspection(t *testing.T) {
// SystemDiagram
sigState := lifecycle.SignalState{}
workState := lifecycle.WorkerState{Name: "root"}
diag := lifecycle.SystemDiagram(sigState, workState)
if diag == "" {
t.Error("SystemDiagram returned empty")
}
}
func TestLifecycle_RuntimeOptions(t *testing.T) {
_ = lifecycle.WithLogger(nil)
_ = lifecycle.WithMetrics(nil)
_ = lifecycle.WithShutdownTimeout(time.Second)
// SetLogger usually sets the global logger.
// We skip passing nil to avoid potential panics in the underlying logger implementation
// if it doesn't guard against it, focusing here on signature stability.
lifecycle.SetLogger(nil)
lifecycle.SetMetricsProvider(lifecycle.NewLogMetricsProvider())
}
func TestLifecycle_IO(t *testing.T) {
// OpenTerminal
_, _ = lifecycle.OpenTerminal()
// UpgradeTerminal
buf := bytes.NewBufferString("test")
_, _ = lifecycle.UpgradeTerminal(buf)
// IsInterrupted
if lifecycle.IsInterrupted(nil) {
t.Error("nil error should not be interrupted")
}
if !lifecycle.IsInterrupted(context.Canceled) {
t.Error("context.Canceled should be interrupted")
}
// NewInterruptibleReader
reader := lifecycle.NewInterruptibleReader(buf, nil)
if reader == nil {
t.Error("NewInterruptibleReader returned nil")
}
}
func TestLifecycle_Proc(t *testing.T) {
// Verify that the facade actually mutates the underlying state.
initial := proc.StrictMode
defer lifecycle.SetStrictMode(initial) // Restore after test
lifecycle.SetStrictMode(true)
if !proc.StrictMode {
t.Error("SetStrictMode(true) failed to update proc.StrictMode")
}
lifecycle.SetStrictMode(false)
if proc.StrictMode {
t.Error("SetStrictMode(false) failed to update proc.StrictMode")
}
}