-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_test.go
More file actions
952 lines (779 loc) · 22.8 KB
/
app_test.go
File metadata and controls
952 lines (779 loc) · 22.8 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
941
942
943
944
945
946
947
948
949
950
951
952
package forge
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"syscall"
"testing"
"time"
"github.com/xraph/forge/internal/logger"
)
// TestNewApp tests app creation.
func TestNewApp(t *testing.T) {
tests := []struct {
name string
config AppConfig
want string
}{
{
name: "default config",
config: DefaultAppConfig(),
want: "forge-app",
},
{
name: "custom config",
config: AppConfig{
Name: "test-app",
Version: "2.0.0",
},
want: "test-app",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Use test logger to prevent terminal bloating
tt.config.Logger = logger.NewTestLogger()
app := NewApp(tt.config)
if app == nil {
t.Fatal("expected app, got nil")
}
if got := app.Name(); got != tt.want {
t.Errorf("app.Name() = %v, want %v", got, tt.want)
}
})
}
}
// TestAppComponents tests core component access.
func TestAppComponents(t *testing.T) {
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
app := NewApp(config)
t.Run("container", func(t *testing.T) {
if app.Container() == nil {
t.Error("expected container, got nil")
}
})
t.Run("router", func(t *testing.T) {
if app.Router() == nil {
t.Error("expected router, got nil")
}
})
t.Run("config", func(t *testing.T) {
if app.Config() == nil {
t.Error("expected config, got nil")
}
})
t.Run("logger", func(t *testing.T) {
if app.Logger() == nil {
t.Error("expected logger, got nil")
}
})
t.Run("metrics", func(t *testing.T) {
if app.Metrics() == nil {
t.Error("expected metrics, got nil")
}
})
t.Run("health manager", func(t *testing.T) {
if app.HealthManager() == nil {
t.Error("expected health manager, got nil")
}
})
}
// TestAppInfo tests app information methods.
func TestAppInfo(t *testing.T) {
config := AppConfig{
Name: "test-app",
Version: "1.2.3",
Environment: "test",
Logger: logger.NewTestLogger(),
}
app := NewApp(config)
t.Run("name", func(t *testing.T) {
if got := app.Name(); got != "test-app" {
t.Errorf("Name() = %v, want test-app", got)
}
})
t.Run("version", func(t *testing.T) {
if got := app.Version(); got != "1.2.3" {
t.Errorf("Version() = %v, want 1.2.3", got)
}
})
t.Run("environment", func(t *testing.T) {
if got := app.Environment(); got != "test" {
t.Errorf("Environment() = %v, want test", got)
}
})
t.Run("start time", func(t *testing.T) {
start := app.StartTime()
if start.IsZero() {
t.Error("expected non-zero start time")
}
})
t.Run("uptime", func(t *testing.T) {
time.Sleep(10 * time.Millisecond)
uptime := app.Uptime()
if uptime < 10*time.Millisecond {
t.Errorf("expected uptime >= 10ms, got %v", uptime)
}
})
}
// TestAppStart tests app startup.
func TestAppStart(t *testing.T) {
t.Run("successful start", func(t *testing.T) {
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
app := NewApp(config)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
// Cleanup
_ = app.Stop(ctx)
})
t.Run("double start fails", func(t *testing.T) {
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
app := NewApp(config)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
// Second start should fail
err = app.Start(ctx)
if err == nil {
t.Error("expected error on double start, got nil")
}
// Cleanup
_ = app.Stop(ctx)
})
}
// TestAppStop tests app shutdown.
func TestAppStop(t *testing.T) {
t.Run("stop after start", func(t *testing.T) {
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
app := NewApp(config)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
err = app.Stop(ctx)
if err != nil {
t.Errorf("Stop() error = %v", err)
}
})
t.Run("stop without start", func(t *testing.T) {
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
app := NewApp(config)
ctx := context.Background()
// Should not error
err := app.Stop(ctx)
if err != nil {
t.Errorf("Stop() error = %v", err)
}
})
t.Run("double stop", func(t *testing.T) {
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
app := NewApp(config)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
err = app.Stop(ctx)
if err != nil {
t.Errorf("Stop() error = %v", err)
}
// Second stop should not error
err = app.Stop(ctx)
if err != nil {
t.Errorf("Stop() error on double stop = %v", err)
}
})
}
// TestAppRegisterService tests service registration.
func TestAppRegisterService(t *testing.T) {
t.Run("register service", func(t *testing.T) {
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
app := NewApp(config)
// Register a test service
err := app.RegisterService("testService", func(c Container) (any, error) {
return "test", nil
})
if err != nil {
t.Errorf("RegisterService() error = %v", err)
}
// Verify service was registered
val, err := app.Container().Resolve("testService")
if err != nil {
t.Fatalf("Resolve() error = %v", err)
}
if val != "test" {
t.Errorf("expected 'test', got %v", val)
}
})
}
// TestAppRegisterController tests controller registration.
func TestAppRegisterController(t *testing.T) {
t.Run("register controller", func(t *testing.T) {
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
app := NewApp(config)
// Create a test controller
ctrl := &appTestController{}
err := app.RegisterController(ctrl)
if err != nil {
t.Errorf("RegisterController() error = %v", err)
}
// Verify route was registered
routes := app.Router().Routes()
found := false
for _, route := range routes {
if route.Path == "/test" {
found = true
break
}
}
if !found {
t.Error("expected controller route to be registered")
}
})
}
// appTestController is a simple test controller for app tests.
type appTestController struct{}
func (c *appTestController) Name() string { return "apptest" }
func (c *appTestController) Routes(r Router) error {
return r.GET("/test", func(ctx Context) error {
return ctx.JSON(200, map[string]string{"message": "test"})
})
}
// TestAppInfoEndpoint tests the /_/info endpoint.
func TestAppInfoEndpoint(t *testing.T) {
app := NewApp(AppConfig{
Name: "info-test",
Version: "1.0.0",
Description: "Test app",
Environment: "test",
Logger: logger.NewTestLogger(),
})
// Start app
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
defer app.Stop(ctx)
// Make request to /_/info
req := httptest.NewRequest(http.MethodGet, "/_/info", nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200, got %d", w.Code)
}
// Parse response
var info AppInfo
body, _ := io.ReadAll(w.Body)
if err := json.Unmarshal(body, &info); err != nil {
t.Fatalf("failed to parse response: %v", err)
}
// Verify info
if info.Name != "info-test" {
t.Errorf("info.Name = %v, want info-test", info.Name)
}
if info.Version != "1.0.0" {
t.Errorf("info.Version = %v, want 1.0.0", info.Version)
}
if info.Environment != "test" {
t.Errorf("info.Environment = %v, want test", info.Environment)
}
}
// TestAppWithMetrics tests metrics integration.
func TestAppWithMetrics(t *testing.T) {
config := DefaultAppConfig()
config.MetricsConfig.Enabled = true
config.MetricsConfig.Collection.Namespace = "test"
config.Logger = logger.NewTestLogger()
app := NewApp(config)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
defer app.Stop(ctx)
// Verify metrics endpoint is available
req := httptest.NewRequest(http.MethodGet, "/_/metrics", nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200 for metrics, got %d", w.Code)
}
}
// TestAppWithHealth tests health check integration.
func TestAppWithHealth(t *testing.T) {
config := DefaultAppConfig()
config.HealthConfig.Enabled = true
config.HealthGracePeriod = 0 // Disable grace period for testing
config.Logger = logger.NewTestLogger()
app := NewApp(config)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
defer app.Stop(ctx)
// Register a health check
app.HealthManager().RegisterFn("test", func(ctx context.Context) *HealthResult {
return &HealthResult{
Status: HealthStatusHealthy,
Message: "test is healthy",
}
})
// Verify health endpoint is available
req := httptest.NewRequest(http.MethodGet, "/_/health", nil)
w := httptest.NewRecorder()
app.Router().ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Errorf("expected status 200 for health, got %d", w.Code)
}
// Parse response
var report HealthReport
body, _ := io.ReadAll(w.Body)
if err := json.Unmarshal(body, &report); err != nil {
t.Fatalf("failed to parse health response: %v", err)
}
if report.Overall != HealthStatusHealthy {
t.Errorf("expected healthy status, got %v", report.Overall)
}
}
// TestDefaultAppConfig tests default configuration.
func TestDefaultAppConfig(t *testing.T) {
config := DefaultAppConfig()
if config.Name != "forge-app" {
t.Errorf("expected Name 'forge-app', got %v", config.Name)
}
if config.Version != "1.0.0" {
t.Errorf("expected Version '1.0.0', got %v", config.Version)
}
if config.Environment != "development" {
t.Errorf("expected Environment 'development', got %v", config.Environment)
}
if config.HTTPAddress != ":8080" {
t.Errorf("expected HTTPAddress ':8080', got %v", config.HTTPAddress)
}
if config.HTTPTimeout != 30*time.Second {
t.Errorf("expected HTTPTimeout 30s, got %v", config.HTTPTimeout)
}
if config.ShutdownTimeout != 30*time.Second {
t.Errorf("expected ShutdownTimeout 30s, got %v", config.ShutdownTimeout)
}
if !config.MetricsConfig.Enabled {
t.Error("expected MetricsConfig.Enabled = true")
}
if !config.HealthConfig.Enabled {
t.Error("expected HealthConfig.Enabled = true")
}
}
// TestAppConfigDefaults tests that defaults are applied.
func TestAppConfigDefaults(t *testing.T) {
tests := []struct {
name string
config AppConfig
check func(*testing.T, App)
}{
{
name: "empty name uses default",
config: AppConfig{},
check: func(t *testing.T, app App) {
if app.Name() != "forge-app" {
t.Errorf("expected default name, got %v", app.Name())
}
},
},
{
name: "empty version uses default",
config: AppConfig{},
check: func(t *testing.T, app App) {
if app.Version() != "1.0.0" {
t.Errorf("expected default version, got %v", app.Version())
}
},
},
{
name: "empty environment uses default",
config: AppConfig{},
check: func(t *testing.T, app App) {
if app.Environment() != "development" {
t.Errorf("expected default environment, got %v", app.Environment())
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.config.Logger = logger.NewTestLogger()
app := NewApp(tt.config)
tt.check(t, app)
})
}
}
// TestAppRun tests the Run method (without actual server).
func TestAppRun(t *testing.T) {
t.Skip("Run() blocks - requires integration test")
// This would require setting up signal handling and is better suited
// for integration tests
}
// TestAppGracefulShutdown tests graceful shutdown.
func TestAppGracefulShutdown(t *testing.T) {
t.Run("shutdown with timeout", func(t *testing.T) {
config := DefaultAppConfig()
config.ShutdownTimeout = 100 * time.Millisecond
config.Logger = logger.NewTestLogger()
app := NewApp(config)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
// Shutdown should complete within timeout
err = app.Stop(ctx)
if err != nil {
t.Errorf("Stop() error = %v", err)
}
})
}
// TestFieldHelper tests the F() helper function.
func TestFieldHelper(t *testing.T) {
field := F("key", "value")
if field.Key() != "key" {
t.Errorf("Field.Key() = %v, want key", field.Key())
}
if field.Value() != "value" {
t.Errorf("Field.Value() = %v, want value", field.Value())
}
}
// TestDefaultLogger tests the default logger implementation.
func TestDefaultLogger(t *testing.T) {
logger := NewNoopLogger()
// These should not panic
logger.Debug("test")
logger.Info("test")
logger.Warn("test")
logger.Error("test")
logger.Debugf("test %s", "formatted")
logger.Infof("test %s", "formatted")
logger.Warnf("test %s", "formatted")
logger.Errorf("test %s", "formatted")
// Test With methods
logger2 := logger.With(F("key", "value"))
if logger2 == nil {
t.Error("With() returned nil")
}
logger3 := logger.WithContext(context.Background())
if logger3 == nil {
t.Error("WithContext() returned nil")
}
logger4 := logger.Named("test")
if logger4 == nil {
t.Error("Named() returned nil")
}
// Test Sugar logger
sugar := logger.Sugar()
if sugar == nil {
t.Error("Sugar() returned nil")
}
sugar.Debugw("test", "key", "value")
sugar.Infow("test", "key", "value")
sugar.Warnw("test", "key", "value")
sugar.Errorw("test", "key", "value")
sugar2 := sugar.With("key", "value")
if sugar2 == nil {
t.Error("Sugar.With() returned nil")
}
// Test Sync
err := logger.Sync()
if err != nil {
t.Errorf("Sync() error = %v", err)
}
}
// TestDefaultLoggerFatal tests that Fatal doesn't panic for noop logger.
func TestDefaultLoggerFatal(t *testing.T) {
logger := NewNoopLogger()
// Noop logger doesn't panic, it does nothing
logger.Fatal("test")
logger.Fatalf("test %s", "formatted")
logger.Sugar().Fatalw("test", "key", "value")
// Test passed if we got here without panicking
}
// TestDefaultConfigManager tests the default config manager.
func TestDefaultConfigManager(t *testing.T) {
logger := logger.NewTestLogger()
metrics := NewNoOpMetrics()
errorHandler := NewDefaultErrorHandler(logger)
cm := NewDefaultConfigManager(logger, metrics, errorHandler)
t.Run("Get returns nil for missing key", func(t *testing.T) {
val := cm.Get("key")
if val != nil {
t.Errorf("expected nil, got %v", val)
}
})
t.Run("GetString returns default", func(t *testing.T) {
val := cm.GetString("key", "default")
if val != "default" {
t.Errorf("expected 'default', got %v", val)
}
})
t.Run("GetInt returns default", func(t *testing.T) {
val := cm.GetInt("key", 42)
if val != 42 {
t.Errorf("expected 42, got %v", val)
}
})
t.Run("GetBool returns default", func(t *testing.T) {
val := cm.GetBool("key", true)
if val != true {
t.Errorf("expected true, got %v", val)
}
})
t.Run("Set succeeds", func(t *testing.T) {
cm.Set("key", "value")
// Set doesn't return error in real ConfigManager
})
t.Run("Bind returns error", func(t *testing.T) {
var target string
err := cm.Bind("nonexistent-key", &target)
if err == nil {
t.Error("expected error, got nil")
}
})
}
// TestAppWithCustomLogger tests app with custom logger.
func TestAppWithCustomLogger(t *testing.T) {
customLogger := &testLogger{}
config := DefaultAppConfig()
config.Logger = customLogger
app := NewApp(config)
if app.Logger() != customLogger {
t.Error("expected custom logger to be used")
}
}
// testLogger is a test logger implementation.
type testLogger struct {
messages []string
}
func (l *testLogger) Debug(msg string, fields ...Field) {}
func (l *testLogger) Info(msg string, fields ...Field) { l.messages = append(l.messages, msg) }
func (l *testLogger) Warn(msg string, fields ...Field) {}
func (l *testLogger) Error(msg string, fields ...Field) {}
func (l *testLogger) Fatal(msg string, fields ...Field) { panic(msg) }
func (l *testLogger) Debugf(template string, args ...any) {}
func (l *testLogger) Infof(template string, args ...any) {}
func (l *testLogger) Warnf(template string, args ...any) {}
func (l *testLogger) Errorf(template string, args ...any) {}
func (l *testLogger) Fatalf(template string, args ...any) {
panic(fmt.Sprintf(template, args...))
}
func (l *testLogger) With(fields ...Field) Logger { return l }
func (l *testLogger) WithContext(ctx context.Context) Logger { return l }
func (l *testLogger) Named(name string) Logger { return l }
func (l *testLogger) Sugar() SugarLogger { return &testSugarLogger{} }
func (l *testLogger) Sync() error { return nil }
type testSugarLogger struct{}
func (l *testSugarLogger) Debugw(msg string, keysAndValues ...any) {}
func (l *testSugarLogger) Infow(msg string, keysAndValues ...any) {}
func (l *testSugarLogger) Warnw(msg string, keysAndValues ...any) {}
func (l *testSugarLogger) Errorw(msg string, keysAndValues ...any) {}
func (l *testSugarLogger) Fatalw(msg string, keysAndValues ...any) { panic(msg) }
func (l *testSugarLogger) With(args ...any) SugarLogger { return l }
// TestAppShutdownSignals tests shutdown signal configuration.
func TestAppShutdownSignals(t *testing.T) {
config := DefaultAppConfig()
config.ShutdownSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
config.Logger = logger.NewTestLogger()
app := NewApp(config)
if app == nil {
t.Fatal("expected app, got nil")
}
// Just verify app was created - actual signal handling tested in integration
}
// TestAppWithDisabledObservability tests app with observability disabled.
func TestAppWithDisabledObservability(t *testing.T) {
config := DefaultAppConfig()
config.MetricsConfig.Enabled = false
config.HealthConfig.Enabled = false
config.Logger = logger.NewTestLogger()
app := NewApp(config)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
defer app.Stop(ctx)
// Metrics should still be available (just empty)
if app.Metrics() == nil {
t.Error("expected metrics to be available even when disabled")
}
// Health manager should still be available
if app.HealthManager() == nil {
t.Error("expected health manager to be available even when disabled")
}
}
// =============================================================================
// EXTENSION LIFECYCLE ORDER TESTS
// =============================================================================
// testExtension is a mock extension for testing lifecycle order.
type testExtension struct {
*BaseExtension
name string
dependencies []string
events *[]string // Shared slice to track events
}
func newTestExtension(name string, dependencies []string, events *[]string) *testExtension {
return &testExtension{
BaseExtension: NewBaseExtension(name, "1.0.0", "Test extension"),
name: name,
dependencies: dependencies,
events: events,
}
}
func (e *testExtension) Name() string { return e.name }
func (e *testExtension) Dependencies() []string { return e.dependencies }
func (e *testExtension) Register(app App) error {
*e.events = append(*e.events, e.name+":register")
return nil
}
func (e *testExtension) Start(ctx context.Context) error {
*e.events = append(*e.events, e.name+":start")
return nil
}
func (e *testExtension) Stop(ctx context.Context) error {
*e.events = append(*e.events, e.name+":stop")
return nil
}
func (e *testExtension) Health(ctx context.Context) error {
return nil
}
// TestExtensionLifecycleOrder verifies that extensions complete their full lifecycle
// (Register + Start) before dependent extensions begin.
func TestExtensionLifecycleOrder(t *testing.T) {
events := []string{}
// Create extensions where B depends on A
extA := newTestExtension("extA", nil, &events)
extB := newTestExtension("extB", []string{"extA"}, &events)
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
// Register B first, then A (wrong order) - app should still process in dependency order
app := New(
WithAppName("test"),
WithAppLogger(logger.NewTestLogger()),
WithConfig(config),
WithExtensions(extB, extA), // B first, but A should run first due to dependency
)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
defer app.Stop(ctx)
// Expected order: A's full lifecycle, then B's full lifecycle
expectedOrder := []string{
"extA:register",
"extA:start",
"extB:register",
"extB:start",
}
if len(events) != len(expectedOrder) {
t.Errorf("Expected %d events, got %d: %v", len(expectedOrder), len(events), events)
return
}
for i, expected := range expectedOrder {
if events[i] != expected {
t.Errorf("Event %d: expected %q, got %q", i, expected, events[i])
}
}
}
// TestExtensionLifecycleOrderChain tests a chain of dependencies: C -> B -> A.
func TestExtensionLifecycleOrderChain(t *testing.T) {
events := []string{}
extA := newTestExtension("extA", nil, &events)
extB := newTestExtension("extB", []string{"extA"}, &events)
extC := newTestExtension("extC", []string{"extB"}, &events)
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
// Register in wrong order
app := New(
WithAppName("test"),
WithAppLogger(logger.NewTestLogger()),
WithConfig(config),
WithExtensions(extC, extA, extB),
)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
defer app.Stop(ctx)
// A's full lifecycle, then B's full lifecycle, then C's full lifecycle
expectedOrder := []string{
"extA:register", "extA:start",
"extB:register", "extB:start",
"extC:register", "extC:start",
}
if len(events) != len(expectedOrder) {
t.Errorf("Expected %d events, got %d: %v", len(expectedOrder), len(events), events)
return
}
for i, expected := range expectedOrder {
if events[i] != expected {
t.Errorf("Event %d: expected %q, got %q", i, expected, events[i])
}
}
}
// TestExtensionStopOrder verifies extensions stop in reverse dependency order.
func TestExtensionStopOrder(t *testing.T) {
events := []string{}
extA := newTestExtension("extA", nil, &events)
extB := newTestExtension("extB", []string{"extA"}, &events)
config := DefaultAppConfig()
config.Logger = logger.NewTestLogger()
app := New(
WithAppName("test"),
WithAppLogger(logger.NewTestLogger()),
WithConfig(config),
WithExtensions(extA, extB),
)
ctx := context.Background()
err := app.Start(ctx)
if err != nil {
t.Fatalf("Start() error = %v", err)
}
// Clear events to only track stop order
events = events[:0]
err = app.Stop(ctx)
if err != nil {
t.Fatalf("Stop() error = %v", err)
}
// B should stop before A (reverse dependency order)
expectedOrder := []string{
"extB:stop",
"extA:stop",
}
if len(events) != len(expectedOrder) {
t.Errorf("Expected %d events, got %d: %v", len(expectedOrder), len(events), events)
return
}
for i, expected := range expectedOrder {
if events[i] != expected {
t.Errorf("Event %d: expected %q, got %q", i, expected, events[i])
}
}
}