-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlifecycle_test.go
More file actions
940 lines (776 loc) · 24.5 KB
/
Copy pathlifecycle_test.go
File metadata and controls
940 lines (776 loc) · 24.5 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
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
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
package goscade
import (
"context"
"errors"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"golang.org/x/sync/errgroup"
)
// mockComponentCyclic is used to create a cyclic dependency in tests.
// It implements the Component interface and calls readinessProbe immediately.
type mockComponentCyclic struct {
dep Component
}
func (m *mockComponentCyclic) Run(ctx context.Context, readinessProbe func(error)) error {
readinessProbe(nil)
<-ctx.Done()
return nil
}
func runLifecycle(ctx context.Context, lc Lifecycle, catch func()) error {
ready := make(chan error)
go func() {
defer catch()
_ = lc.Run(ctx, func(err error) {
ready <- err
})
}()
select {
case err := <-ready:
return err
case <-time.After(1 * time.Second):
return context.DeadlineExceeded
}
}
// Test: Circular dependency detection
func TestLifecycle_Run_CircularDependency(t *testing.T) {
tests := []struct {
name string
opts []Option
expectPanic bool
}{
{
name: "panic on circular dependency by default",
opts: nil,
expectPanic: true,
},
{
name: "ignore circular dependency when WithCircularDependency is set",
opts: []Option{WithCircularDependency()},
expectPanic: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
lc := NewLifecycle(&mockLogger{}, tt.opts...)
compA := &mockComponentCyclic{}
compB := &mockComponentCyclic{dep: compA}
compA.dep = compB // create cycle
lc.Register(compA)
lc.Register(compB)
catch := func() {
rec := recover()
if tt.expectPanic {
if rec == nil {
t.Fatal("expected panic due to circular dependency, but did not panic")
}
panicMsg, ok := rec.(string)
if !ok || !strings.Contains(panicMsg, "circular dependency detected") {
t.Fatalf("unexpected panic message: %v", rec)
}
} else {
if rec != nil {
t.Fatalf("did not expect panic, but got: %v", rec)
}
}
}
_ = runLifecycle(context.Background(), lc, catch)
})
}
}
// Test: Successful pointer registration
func TestLifecycle_Register_Pointer(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &mockComponentCyclic{}
defer func() {
if r := recover(); r != nil {
t.Fatalf("unexpected panic: %v", r)
}
}()
lc.Register(comp)
}
// Test: Register with implicit dependencies
func TestLifecycle_Register_WithImplicitDeps(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
dep1 := &mockComponentCyclic{}
dep2 := &mockComponentCyclic{}
comp := &mockComponentCyclic{}
defer func() {
if r := recover(); r != nil {
t.Fatalf("unexpected panic: %v", r)
}
}()
// Register component with implicit dependencies
lc.Register(comp, dep1, dep2)
// Check that all components are registered
deps := lc.Dependencies()
if len(deps) != 3 {
t.Errorf("expected 3 components, got %d", len(deps))
}
// Check that the component has the correct dependencies
compDeps := deps[comp]
if len(compDeps) != 2 {
t.Errorf("expected 2 dependencies for main component, got %d", len(compDeps))
}
// Check that both dependencies are present
hasDep1, hasDep2 := false, false
for _, dep := range compDeps {
if dep == dep1 {
hasDep1 = true
}
if dep == dep2 {
hasDep2 = true
}
}
if !hasDep1 {
t.Error("component should have dependency 1")
}
if !hasDep2 {
t.Error("component should have dependency 2")
}
}
// Test: Register with no implicit dependencies (backward compatibility)
func TestLifecycle_Register_NoImplicitDeps(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &mockComponentCyclic{}
defer func() {
if r := recover(); r != nil {
t.Fatalf("unexpected panic: %v", r)
}
}()
// Register component without implicit dependencies
lc.Register(comp)
// Check that component is registered
deps := lc.Dependencies()
if len(deps) != 1 {
t.Errorf("expected 1 component, got %d", len(deps))
}
// Check that component has no dependencies
compDeps := deps[comp]
if len(compDeps) != 0 {
t.Errorf("expected 0 dependencies, got %d", len(compDeps))
}
}
// Test: Register with duplicate implicit dependencies
func TestLifecycle_Register_DuplicateImplicitDeps(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
dep := &mockComponentCyclic{}
comp := &mockComponentCyclic{}
defer func() {
if r := recover(); r != nil {
t.Fatalf("unexpected panic: %v", r)
}
}()
// Register component with duplicate implicit dependencies
lc.Register(comp, dep, dep)
// Check dependencies
deps := lc.Dependencies()
if len(deps) != 2 {
t.Errorf("expected 2 components, got %d", len(deps))
}
// Check that the component has only one dependency (duplicates should be deduplicated)
compDeps := deps[comp]
if len(compDeps) != 1 {
t.Errorf("expected 1 dependency for main component (duplicates deduplicated), got %d", len(compDeps))
}
if compDeps[0] != dep {
t.Error("component should have the correct dependency")
}
}
// Test: Register component twice (should not duplicate)
func TestLifecycle_Register_DuplicateComponent(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &mockComponentCyclic{}
dep := &mockComponentCyclic{}
defer func() {
if r := recover(); r != nil {
t.Fatalf("unexpected panic: %v", r)
}
}()
// Register component first time
lc.Register(comp)
// Register same component again with implicit dependency
lc.Register(comp, dep)
// Check that only one instance of component exists
deps := lc.Dependencies()
if len(deps) != 2 {
t.Errorf("expected 2 components, got %d", len(deps))
}
// Check that component has the implicit dependency
compDeps := deps[comp]
if len(compDeps) != 1 {
t.Errorf("expected 1 dependency for main component, got %d", len(compDeps))
}
if compDeps[0] != dep {
t.Error("component should have the correct dependency")
}
}
// Test: Dependencies with a single component without dependencies
func TestLifecycle_Dependencies_Simple(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &mockComponentCyclic{}
lc.Register(comp)
deps := lc.Dependencies()
if len(deps) != 1 {
t.Errorf("expected 1 component, got %d", len(deps))
}
if len(deps[comp]) != 0 {
t.Errorf("expected 0 dependencies, got %d", len(deps[comp]))
}
}
// Test: Dependencies with dependencies
func TestLifecycle_Dependencies_WithDeps(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
compA := &mockComponentCyclic{}
compB := &mockComponentCyclic{dep: compA}
lc.Register(compA)
lc.Register(compB)
lcImpl := lc.(*lifecycle)
lcImpl.ptrToComp[reflect.ValueOf(compA).Pointer()] = compA
lcImpl.ptrToComp[reflect.ValueOf(compB).Pointer()] = compB
deps := lc.Dependencies()
if len(deps) != 2 {
t.Errorf("expected 2 components, got %d", len(deps))
}
if len(deps[compB]) != 1 {
t.Errorf("expected 1 dependency for compB, got %d", len(deps[compB]))
}
}
// Test: buildCompToParents and buildCompToChildren
func TestLifecycle_BuildCompToParents_And_Children(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
compA := &mockComponentCyclic{}
compB := &mockComponentCyclic{dep: compA}
lc.Register(compA)
lc.Register(compB)
lcImpl := lc.(*lifecycle)
parents := lcImpl.buildCompToParents()
children := lcImpl.buildCompToChildren(parents)
if len(parents) == 0 || len(children) == 0 {
t.Error("parents or children map is empty")
}
}
// Test: Run with no components
func TestLifecycle_NoComponents(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
assert.PanicsWithValue(t, "goscade: lifecycle has no components", func() {
_ = lc.Run(context.Background(), nil)
})
}
// Test: Correct status transitions
func TestLifecycle_Status_Transitions(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
lcImpl := lc.(*lifecycle)
if lc.Status() != LifecycleStatusIdle {
t.Errorf("expected status idle, got %s", lc.Status())
}
lcImpl.setStatus(LifecycleStatusRunning)
if lc.Status() != LifecycleStatusRunning {
t.Errorf("expected status running, got %s", lc.Status())
}
lcImpl.setStatus(LifecycleStatusReady)
if lc.Status() != LifecycleStatusReady {
t.Errorf("expected status ready, got %s", lc.Status())
}
lcImpl.setStatus(LifecycleStatusStopping)
if lc.Status() != LifecycleStatusStopping {
t.Errorf("expected status stopping, got %s", lc.Status())
}
lcImpl.setStatus(LifecycleStatusStopped)
if lc.Status() != LifecycleStatusStopped {
t.Errorf("expected status stopped, got %s", lc.Status())
}
}
// Test: Graceful shutdown
func TestLifecycle_Run_GracefulShutdown(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &mockComponentCyclic{}
lc.Register(comp)
lcImpl := lc.(*lifecycle)
lcImpl.ptrToComp[reflect.ValueOf(comp).Pointer()] = comp
cancelCtx, cancel := context.WithCancel(context.Background())
// Start components
go func() {
assert.NoError(t, runLifecycle(cancelCtx, lc, func() {}))
}()
// Wait until status becomes Ready
for lc.Status() != LifecycleStatusReady {
time.Sleep(10 * time.Millisecond)
}
// Cancel context
cancel()
// Wait until status becomes Stopped
for lc.Status() != LifecycleStatusStopped {
time.Sleep(10 * time.Millisecond)
}
}
// Test: Component error handling
type errorComponent struct{}
func (e *errorComponent) Run(_ context.Context, readinessProbe func(error)) error {
readinessProbe(errors.New("component error"))
return errors.New("component error")
}
// Test: Component error causes lifecycle to stop
func TestLifecycle_Run_ComponentError(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &errorComponent{}
lc.Register(comp)
// Start components
_ = runLifecycle(context.Background(), lc, func() {})
// Wait until status becomes Stopped
for {
if lc.Status() == LifecycleStatusStopped {
return
}
select {
case <-time.After(10 * time.Millisecond):
case <-time.After(1 * time.Second):
t.Fatal("lifecycle did not stop after component error")
}
}
}
// Test: NewAdapter creates an adapter with correct delegate and run function
func TestNewAdapter_Run(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
var probeCalled bool
adapter := NewAdapter(&mockComponentCyclic{}, func(ctx context.Context, delegate *mockComponentCyclic, probe func(error)) error {
probeCalled = true
probe(nil)
<-ctx.Done()
return nil
})
assert.NotNil(t, adapter)
assert.Implements(t, (*Component)(nil), adapter)
lc := NewLifecycle(&mockLogger{})
lc.Register(adapter)
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return lc.Run(ctx, func(err error) {
readinessProbe <- err
})
})
assert.NoError(t, <-readinessProbe)
assert.True(t, probeCalled, "Readiness probe should have been called")
cancel()
assert.EqualError(t, errGroup.Wait(), "context canceled")
}
// Test: adapter delegateName returns correct type string
func TestAdapter_DelegateName(t *testing.T) {
mockDelegate := &mockComponentCyclic{}
adapter := NewAdapter(mockDelegate, func(ctx context.Context, delegate *mockComponentCyclic, probe func(error)) error {
probe(nil)
<-ctx.Done()
return nil
})
// Cast to adapter to access delegateName method
adapterImpl := adapter.(interface{ delegateName() string })
name := adapterImpl.delegateName()
expectedName := reflect.TypeOf(mockDelegate).String()
assert.Equal(t, expectedName, name)
}
// Test: adapter Run method handles errors correctly
func TestAdapter_Run_Error(t *testing.T) {
mockDelegate := &mockComponentCyclic{}
expectedError := errors.New("test error")
adapter := NewAdapter(mockDelegate, func(ctx context.Context, delegate *mockComponentCyclic, probe func(error)) error {
probe(nil)
return expectedError
})
ctx := context.Background()
err := adapter.Run(ctx, func(err error) {})
assert.Equal(t, expectedError, err)
}
// customComponent implements delegateNameProvider for testing
type customComponent struct {
name string
}
func (c *customComponent) Run(ctx context.Context, readinessProbe func(error)) error {
readinessProbe(nil)
<-ctx.Done()
return nil
}
func (c *customComponent) delegateName() string {
return c.name
}
type failingNamedComponent struct {
name string
err error
}
func (c *failingNamedComponent) Run(_ context.Context, readinessProbe func(error)) error {
readinessProbe(nil)
return c.err
}
func (c *failingNamedComponent) delegateName() string {
return c.name
}
func TestRunComponent_ErrorIncludesDelegateName(t *testing.T) {
wantErr := errors.New("database failed")
lc := NewLifecycle(&mockLogger{})
lc.Register(&failingNamedComponent{name: "database", err: wantErr})
err := lc.Run(context.Background(), nil)
assert.ErrorIs(t, err, wantErr)
assert.EqualError(t, err, "component database: database failed")
}
// Test: runComponent with delegateNameProvider
func TestRunComponent_DelegateNameProvider(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &customComponent{name: "CustomComponent"}
lc.Register(comp)
// Run lifecycle to test delegateNameProvider functionality
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return lc.Run(ctx, func(err error) {
readinessProbe <- err
})
})
assert.NoError(t, <-readinessProbe)
// Wait for graceful shutdown
err := errGroup.Wait()
assert.ErrorIs(t, err, context.DeadlineExceeded)
}
// Test: runComponent with parent dependency failure
func TestRunComponent_ParentDependencyFailure(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
// Create parent component that will fail
parentComp := &errorComponent{}
childComp := &mockComponentCyclic{dep: parentComp}
lc.Register(parentComp)
lc.Register(childComp)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return lc.Run(ctx, func(err error) {
readinessProbe <- err
})
})
<-readinessProbe
// Wait for graceful shutdown
shutdownErr := errGroup.Wait()
assert.Contains(t, shutdownErr.Error(), "component *goscade.errorComponent")
assert.Contains(t, shutdownErr.Error(), "component error")
}
// cascadeComponent causes cascade shutdown for testing
type cascadeComponent struct{}
func (c *cascadeComponent) Run(_ context.Context, readinessProbe func(error)) error {
readinessProbe(nil)
// Return an error to trigger cascade shutdown
return errors.New("component error")
}
// Test: runComponent with cascade shutdown
func TestRunComponent_CascadeShutdown(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &cascadeComponent{}
lc.Register(comp)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return lc.Run(ctx, func(err error) {
readinessProbe <- err
})
})
// Should get a response from readiness probe
<-readinessProbe
// The readiness probe might succeed initially, but the component will fail later
// So we just check that we get a response (could be nil or error)
// Wait for graceful shutdown
shutdownErr := errGroup.Wait()
assert.Error(t, shutdownErr)
}
// probeErrorComponent fails readiness probe for testing
type probeErrorComponent struct{}
func (c *probeErrorComponent) Run(ctx context.Context, readinessProbe func(error)) error {
// Call readiness probe with error
readinessProbe(errors.New("probe error"))
<-ctx.Done()
return nil
}
// Test: runComponent with probe error
func TestRunComponent_ProbeError(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &probeErrorComponent{}
lc.Register(comp)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return lc.Run(ctx, func(err error) {
readinessProbe <- err
})
})
// Should get an error due to probe failure
err := <-readinessProbe
assert.Error(t, err)
assert.Contains(t, err.Error(), "component *goscade.probeErrorComponent readiness")
assert.Contains(t, err.Error(), "probe error")
// Wait for graceful shutdown
shutdownErr := errGroup.Wait()
assert.Error(t, shutdownErr)
}
// unexpectedCloseComponent closes without error for testing
type unexpectedCloseComponent struct{}
func (c *unexpectedCloseComponent) Run(_ context.Context, readinessProbe func(error)) error {
readinessProbe(nil)
// Return nil without waiting for context cancellation
return nil
}
// Test: runComponent with unexpected close
func TestRunComponent_UnexpectedClose(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
comp := &unexpectedCloseComponent{}
lc.Register(comp)
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return lc.Run(ctx, func(err error) {
readinessProbe <- err
})
})
// Should get a response from readiness probe
<-readinessProbe
// The readiness probe might succeed initially, but the component will fail later
// So we just check that we get a response (could be nil or error)
// Wait for graceful shutdown
shutdownErr := errGroup.Wait()
assert.ErrorIs(t, shutdownErr, UnexpectedCloseComponentError)
assert.Contains(t, shutdownErr.Error(), "component *goscade.unexpectedCloseComponent")
}
type stuckComponent struct {
release <-chan struct{}
}
func (c *stuckComponent) Run(_ context.Context, readinessProbe func(error)) error {
readinessProbe(nil)
<-c.release
return nil
}
func TestTimeout_ShutdownTimeout(t *testing.T) {
release := make(chan struct{})
defer close(release)
lc := NewLifecycle(&mockLogger{}, WithShutdownTimeout(50*time.Millisecond))
lc.Register(&stuckComponent{release: release})
ctx, cancel := context.WithCancel(context.Background())
ready := make(chan error)
done := make(chan error)
go func() {
done <- lc.Run(ctx, func(err error) { ready <- err })
}()
assert.NoError(t, <-ready)
cancel()
assert.ErrorIs(t, <-done, ShutdownTimeoutError)
}
func TestLifecycle_Run_WithShutdownHook(t *testing.T) {
lc := NewLifecycle(&mockLogger{}, WithShutdownHook())
lc.Register(&mockComponentCyclic{})
ctx, cancel := context.WithCancel(context.Background())
ready := make(chan error)
done := make(chan error)
go func() {
done <- lc.Run(ctx, func(err error) { ready <- err })
}()
assert.NoError(t, <-ready)
cancel()
assert.ErrorIs(t, <-done, context.Canceled)
}
// slowStartComponent takes time to start for timeout testing
type slowStartComponent struct {
delay time.Duration
}
func (c *slowStartComponent) Run(ctx context.Context, readinessProbe func(error)) error {
// Wait longer than the timeout before calling readiness probe
time.Sleep(c.delay)
readinessProbe(nil)
<-ctx.Done()
return ctx.Err()
}
// TestTimeout_StartTimeout tests that components timeout during startup
func TestTimeout_StartTimeout(t *testing.T) {
lc := NewLifecycle(&mockLogger{}, WithStartTimeout(100*time.Millisecond))
// Component that takes longer than timeout to start
comp := &slowStartComponent{delay: 200 * time.Millisecond}
lc.Register(comp)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return lc.Run(ctx, func(err error) {
readinessProbe <- err
})
})
// Should get timeout error
err := <-readinessProbe
assert.ErrorIs(t, err, context.DeadlineExceeded)
// Wait for graceful shutdown
shutdownErr := errGroup.Wait()
assert.ErrorIs(t, shutdownErr, context.DeadlineExceeded)
}
// TestTimeout_DefaultTimeouts tests that default timeouts work correctly
func TestTimeout_DefaultTimeouts(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
lc := NewLifecycle(&mockLogger{}) // No custom timeouts, should use defaults
// Component that starts quickly
comp := &mockComponentCyclic{}
lc.Register(comp)
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return lc.Run(ctx, func(err error) {
readinessProbe <- err
})
})
// Should succeed with default timeout (1 minute)
err := <-readinessProbe
assert.NoError(t, err)
cancel()
// Wait for graceful shutdown
shutdownErr := errGroup.Wait()
assert.ErrorIs(t, shutdownErr, context.Canceled)
}
// TestLifecycle_AsComponent tests that a lifecycle can be registered as a component in another lifecycle
func TestLifecycle_AsComponent(t *testing.T) {
// Create parent lifecycle
log := &mockLogger{}
parentLC := NewLifecycle(log)
// Create child lifecycle with a component
childLog := &mockLogger{}
childLC := NewLifecycle(childLog)
// Add a component to child lifecycle
childLC.Register(&mockComponentCyclic{})
// Wrap child lifecycle as a component
parentLC.Register(childLC)
// Add another component to parent lifecycle
parentComp := &mockComponentCyclic{}
parentLC.Register(parentComp)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return parentLC.Run(ctx, func(err error) {
readinessProbe <- err
})
})
// Wait for readiness probe - should succeed
err := <-readinessProbe
assert.NoError(t, err)
// Verify both lifecycles are running
assert.Equal(t, LifecycleStatusReady, parentLC.Status())
cancel()
// Wait for graceful shutdown
shutdownErr := errGroup.Wait()
assert.ErrorIs(t, shutdownErr, context.Canceled)
}
// TestLifecycle_NestedLifecycleWithDependencies tests nested lifecycles with dependencies
func TestLifecycle_NestedLifecycleWithDependencies(t *testing.T) {
// Create parent lifecycle
parentLog := &mockLogger{}
parentLC := NewLifecycle(parentLog)
// Create child lifecycle with dependencies
childLog := &mockLogger{}
childLC := NewLifecycle(childLog)
// Add components with dependencies to child lifecycle
childDB := &mockComponentCyclic{}
childCache := &mockComponentCyclic{dep: childDB}
childService := &mockComponentCyclic{dep: childCache}
childLC.Register(childDB)
childLC.Register(childCache)
childLC.Register(childService)
// Wrap child lifecycle as a component
parentLC.Register(childLC)
// Add parent-level component
parentService := &mockComponentCyclic{}
parentLC.Register(parentService)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return parentLC.Run(ctx, func(err error) {
readinessProbe <- err
})
})
// Wait for readiness probe - should succeed
err := <-readinessProbe
assert.NoError(t, err)
// Verify parent lifecycle is ready
assert.Equal(t, LifecycleStatusReady, parentLC.Status())
cancel()
// Wait for graceful shutdown
shutdownErr := errGroup.Wait()
assert.ErrorIs(t, shutdownErr, context.Canceled)
}
type startupOrder struct {
items []string
mu sync.Mutex
}
func (c *startupOrder) add(name string) {
c.mu.Lock()
c.items = append(c.items, name)
c.mu.Unlock()
}
// orderTrackingComponent tracks the order of component startup
type orderTrackingComponent struct {
order *startupOrder
name string
}
func (c *orderTrackingComponent) Run(ctx context.Context, readinessProbe func(error)) error {
c.order.add(c.name)
readinessProbe(nil)
<-ctx.Done()
return nil
}
// Test: Component startup order with implicit dependencies
func TestLifecycle_ImplicitDeps_StartupOrder(t *testing.T) {
lc := NewLifecycle(&mockLogger{})
order := &startupOrder{}
// Create components
dep1 := &orderTrackingComponent{name: "dep1", order: order}
dep2 := &orderTrackingComponent{name: "dep2", order: order}
comp := &orderTrackingComponent{name: "comp", order: order}
// Register component with implicit dependencies
lc.Register(comp, dep1, dep2)
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
readinessProbe := make(chan error)
errGroup := &errgroup.Group{}
errGroup.Go(func() error {
return lc.Run(ctx, func(err error) {
readinessProbe <- err
})
})
// Wait for readiness probe
err := <-readinessProbe
assert.NoError(t, err)
// Check that dependencies started before the main component
assert.Len(t, order.items, 3, "All components should have started")
// Find positions of components in startup order
dep1Pos, dep2Pos, compPos := -1, -1, -1
for i, name := range order.items {
switch name {
case "dep1":
dep1Pos = i
case "dep2":
dep2Pos = i
case "comp":
compPos = i
}
}
// Dependencies should start before the main component
assert.True(t, dep1Pos < compPos, "dep1 should start before comp")
assert.True(t, dep2Pos < compPos, "dep2 should start before comp")
cancel()
// Wait for graceful shutdown
shutdownErr := errGroup.Wait()
assert.ErrorIs(t, shutdownErr, context.Canceled)
}