cf-modkit 0.6.4

Core ModKit library
Documentation
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
#![allow(clippy::unwrap_used, clippy::expect_used)]

//! Comprehensive tests for the `ModKit` runner functionality
//!
//! Tests the core orchestration logic including lifecycle phases,
//! database strategies, shutdown options, and error handling.

use std::sync::{
    Arc, Mutex,
    atomic::{AtomicBool, Ordering},
};
use std::time::Duration;
use tokio::time::timeout;
use tokio_util::sync::CancellationToken;
use uuid::Uuid;

use modkit::{
    ModuleCtx,
    config::ConfigProvider,
    contracts::{
        DatabaseCapability, Module, OpenApiRegistry, RestApiCapability, RunnableCapability,
    },
    registry::{ModuleRegistry, RegistryBuilder},
    runtime::{DbOptions, RunOptions, ShutdownOptions, run},
};

// Test tracking infrastructure
#[allow(dead_code)]
type CallTracker = Arc<Mutex<Vec<String>>>;

#[derive(Default)]
#[allow(dead_code)]
struct TestOpenApiRegistry;

impl OpenApiRegistry for TestOpenApiRegistry {
    fn register_operation(&self, _spec: &modkit::api::OperationSpec) {}
    fn ensure_schema_raw(
        &self,
        root_name: &str,
        _schemas: Vec<(
            String,
            utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,
        )>,
    ) -> String {
        root_name.to_owned()
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// Mock config provider for testing
#[derive(Clone)]
struct MockConfigProvider {
    configs: std::collections::HashMap<String, serde_json::Value>,
}

impl MockConfigProvider {
    fn new() -> Self {
        Self {
            configs: std::collections::HashMap::new(),
        }
    }

    fn with_config(mut self, module_name: &str, config: serde_json::Value) -> Self {
        self.configs.insert(module_name.to_owned(), config);
        self
    }
}

impl ConfigProvider for MockConfigProvider {
    fn get_module_config(&self, module_name: &str) -> Option<&serde_json::Value> {
        self.configs.get(module_name)
    }
}

// Test trait to add pipe method for more readable code
#[allow(dead_code)]
trait Pipe<T> {
    fn pipe<U, F: FnOnce(T) -> U>(self, f: F) -> U;
}

impl<T> Pipe<T> for T {
    fn pipe<U, F: FnOnce(T) -> U>(self, f: F) -> U {
        f(self)
    }
}

// Test module implementations with lifecycle tracking
#[allow(dead_code)]
#[derive(Clone)]
struct TestModule {
    name: String,
    calls: CallTracker,
    should_fail_init: Arc<AtomicBool>,
    should_fail_db: Arc<AtomicBool>,
    should_fail_rest: Arc<AtomicBool>,
    should_fail_start: Arc<AtomicBool>,
    should_fail_stop: Arc<AtomicBool>,
}

#[allow(dead_code)]
impl TestModule {
    fn new(name: &str, calls: CallTracker) -> Self {
        Self {
            name: name.to_owned(),
            calls,
            should_fail_init: Arc::new(AtomicBool::new(false)),
            should_fail_db: Arc::new(AtomicBool::new(false)),
            should_fail_rest: Arc::new(AtomicBool::new(false)),
            should_fail_start: Arc::new(AtomicBool::new(false)),
            should_fail_stop: Arc::new(AtomicBool::new(false)),
        }
    }

    fn fail_init(self) -> Self {
        self.should_fail_init.store(true, Ordering::SeqCst);
        self
    }

    fn fail_db(self) -> Self {
        self.should_fail_db.store(true, Ordering::SeqCst);
        self
    }

    fn fail_rest(self) -> Self {
        self.should_fail_rest.store(true, Ordering::SeqCst);
        self
    }

    fn fail_start(self) -> Self {
        self.should_fail_start.store(true, Ordering::SeqCst);
        self
    }

    fn fail_stop(self) -> Self {
        self.should_fail_stop.store(true, Ordering::SeqCst);
        self
    }
}

#[async_trait::async_trait]
impl Module for TestModule {
    async fn init(&self, _ctx: &ModuleCtx) -> anyhow::Result<()> {
        self.calls
            .lock()
            .unwrap()
            .push(format!("{}.init", self.name));
        if self.should_fail_init.load(Ordering::SeqCst) {
            anyhow::bail!("Init failed for module {}", self.name);
        }
        Ok(())
    }
}

impl DatabaseCapability for TestModule {
    fn migrations(&self) -> Vec<Box<dyn sea_orm_migration::MigrationTrait>> {
        self.calls
            .lock()
            .unwrap()
            .push(format!("{}.migrations", self.name));
        if self.should_fail_db.load(Ordering::SeqCst) {
            vec![Box::new(FailingMigration)]
        } else {
            vec![]
        }
    }
}

struct FailingMigration;
impl sea_orm_migration::MigrationName for FailingMigration {
    #[allow(clippy::unnecessary_literal_bound)]
    fn name(&self) -> &str {
        "m000_fail"
    }
}
#[async_trait::async_trait]
impl sea_orm_migration::MigrationTrait for FailingMigration {
    async fn up(
        &self,
        _manager: &sea_orm_migration::SchemaManager,
    ) -> Result<(), sea_orm_migration::sea_orm::DbErr> {
        Err(sea_orm_migration::sea_orm::DbErr::Custom(
            "intentional migration failure".to_owned(),
        ))
    }
    async fn down(
        &self,
        _manager: &sea_orm_migration::SchemaManager,
    ) -> Result<(), sea_orm_migration::sea_orm::DbErr> {
        Ok(())
    }
}

impl RestApiCapability for TestModule {
    fn register_rest(
        &self,
        _ctx: &ModuleCtx,
        router: axum::Router,
        _openapi: &dyn OpenApiRegistry,
    ) -> anyhow::Result<axum::Router> {
        self.calls
            .lock()
            .unwrap()
            .push(format!("{}.register_rest", self.name));
        if self.should_fail_rest.load(Ordering::SeqCst) {
            anyhow::bail!("REST registration failed for module {}", self.name);
        }
        Ok(router)
    }
}

#[async_trait::async_trait]
impl RunnableCapability for TestModule {
    async fn start(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
        self.calls
            .lock()
            .unwrap()
            .push(format!("{}.start", self.name));
        if self.should_fail_start.load(Ordering::SeqCst) {
            anyhow::bail!("Start failed for module {}", self.name);
        }
        Ok(())
    }

    async fn stop(&self, _cancel: CancellationToken) -> anyhow::Result<()> {
        self.calls
            .lock()
            .unwrap()
            .push(format!("{}.stop", self.name));
        if self.should_fail_stop.load(Ordering::SeqCst) {
            anyhow::bail!("Stop failed for module {}", self.name);
        }
        Ok(())
    }
}

// Helper to create a registry with test modules
#[allow(dead_code)]
fn create_test_registry(modules: Vec<TestModule>) -> anyhow::Result<ModuleRegistry> {
    let mut builder = RegistryBuilder::default();

    for module in modules {
        let module_name = module.name.clone();
        let module_name_str: &'static str = Box::leak(module_name.into_boxed_str());
        let module = Arc::new(module);

        builder.register_core_with_meta(module_name_str, &[], module.clone() as Arc<dyn Module>);
        builder.register_db_with_meta(
            module_name_str,
            module.clone() as Arc<dyn DatabaseCapability>,
        );
        builder.register_rest_with_meta(
            module_name_str,
            module.clone() as Arc<dyn RestApiCapability>,
        );
        builder.register_stateful_with_meta(
            module_name_str,
            module.clone() as Arc<dyn RunnableCapability>,
        );
    }

    Ok(builder.build_topo_sorted()?)
}

// Helper function to create a mock DbManager for testing
fn create_mock_db_manager() -> Arc<modkit_db::DbManager> {
    use figment::{Figment, providers::Serialized};

    // Create a simple figment with mock database configuration
    let figment = Figment::new().merge(Serialized::defaults(serde_json::json!({
        "test_module": {
            "database": {
                "dsn": "sqlite::memory:",
                "params": {
                    "journal_mode": "WAL"
                }
            }
        }
    })));

    let home_dir = std::path::PathBuf::from("/tmp/test");

    Arc::new(modkit_db::DbManager::from_figment(figment, home_dir).unwrap())
}

#[tokio::test]
async fn test_db_phase_failure_stops_lifecycle() {
    use modkit::runtime::HostRuntime;

    let calls: CallTracker = Arc::new(Mutex::new(Vec::new()));
    let failing = TestModule::new("fail_db", calls.clone()).fail_db();

    let registry = create_test_registry(vec![failing]).expect("registry build");

    // Provide DB config for this module so DB handle exists.
    let db_manager = {
        use figment::{Figment, providers::Serialized};
        let figment = Figment::new().merge(Serialized::defaults(serde_json::json!({
            "modules": {
                "fail_db": {
                    "database": {
                        "dsn": "sqlite::memory:",
                        "pool": { "max_conns": 1 }
                    }
                }
            }
        })));
        let home_dir = std::path::PathBuf::from("/tmp/test");
        Arc::new(modkit_db::DbManager::from_figment(figment, home_dir).unwrap())
    };

    let cancel = CancellationToken::new();
    let hr = HostRuntime::new(
        registry,
        Arc::new(MockConfigProvider::new().with_config(
            "fail_db",
            serde_json::json!({
                "database": { "dsn": "sqlite::memory:", "pool": { "max_conns": 1 } },
                "config": {}
            }),
        )),
        DbOptions::Manager(db_manager),
        Arc::new(modkit::client_hub::ClientHub::default()),
        cancel,
        Uuid::new_v4(),
        None,
    );

    let err = hr.run_module_phases().await.unwrap_err();
    let chain = format!("{err:#}");
    assert!(
        chain.contains("intentional migration failure"),
        "expected migration failure in error chain, got: {chain}"
    );

    let events = calls.lock().unwrap().clone();
    assert!(events.contains(&"fail_db.migrations".to_owned()));
    assert!(
        !events.iter().any(|e| {
            std::path::Path::new(e)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("init"))
        }),
        "init must not run after db phase failure: {events:?}"
    );
    assert!(
        !events.iter().any(|e| e.ends_with(".register_rest")),
        "rest must not run after db phase failure: {events:?}"
    );
    assert!(
        !events.iter().any(|e| {
            std::path::Path::new(e)
                .extension()
                .is_some_and(|ext| ext.eq_ignore_ascii_case("start"))
        }),
        "start must not run after db phase failure: {events:?}"
    );
}

#[tokio::test]
async fn test_db_options_none() {
    // Mock the registry to avoid inventory dependency in tests
    let cancel = CancellationToken::new();
    cancel.cancel(); // Immediate shutdown for test

    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(MockConfigProvider::new()),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Token(cancel),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    // This test requires registry discovery to work, which won't work in isolation
    // For now, let's test the individual components we can test
    let result = timeout(Duration::from_millis(100), run(opts)).await;

    // Should complete quickly due to immediate cancellation
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_db_options_manager() {
    let cancel = CancellationToken::new();

    // Cancel after a brief delay
    let cancel_clone = cancel.clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(50)).await;
        cancel_clone.cancel();
    });

    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(MockConfigProvider::new().with_config(
            "test_module",
            serde_json::json!({
                "database": {
                    "dsn": "sqlite::memory:"
                },
                "config": {}
            }),
        )),
        db: DbOptions::Manager(create_mock_db_manager()),
        shutdown: ShutdownOptions::Token(cancel),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    let result = timeout(Duration::from_secs(1), run(opts)).await;
    assert!(result.is_ok());
    let run_result = result.unwrap();
    // Should succeed with DbManager approach
    assert!(run_result.is_ok());
}

#[tokio::test]
async fn test_shutdown_options_token() {
    let cancel = CancellationToken::new();

    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(MockConfigProvider::new()),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Token(cancel.clone()),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    // Start the runner in a background task
    let runner_handle = tokio::spawn(run(opts));

    // Give it a moment to start
    tokio::time::sleep(Duration::from_millis(10)).await;

    // Cancel it
    cancel.cancel();

    // Should complete quickly
    let result = timeout(Duration::from_millis(100), runner_handle).await;
    assert!(result.is_ok());
    let run_result = result.unwrap().unwrap();
    assert!(run_result.is_ok());
}

#[tokio::test]
async fn test_shutdown_options_future() {
    let (tx, rx) = tokio::sync::oneshot::channel();

    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(MockConfigProvider::new()),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Future(Box::pin(async move {
            _ = rx.await;
        })),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    // Start the runner in a background task
    let runner_handle = tokio::spawn(run(opts));

    // Give it a moment to start
    tokio::time::sleep(Duration::from_millis(10)).await;

    // Trigger shutdown via the future
    _ = tx.send(());

    // Should complete quickly
    let result = timeout(Duration::from_millis(100), runner_handle).await;
    assert!(result.is_ok());
    let run_result = result.unwrap().unwrap();
    assert!(run_result.is_ok());
}

#[tokio::test]
async fn test_runner_with_config_provider() {
    let cancel = CancellationToken::new();
    cancel.cancel(); // Immediate shutdown

    let config_provider = MockConfigProvider::new().with_config(
        "test_module",
        serde_json::json!({
            "setting1": "value1",
            "setting2": 42
        }),
    );

    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(config_provider),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Token(cancel),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    let result = timeout(Duration::from_millis(100), run(opts)).await;
    assert!(result.is_ok());
}

// Integration test for complete lifecycle (will work once we have proper module discovery mock)
#[tokio::test]
async fn test_complete_lifecycle_success() {
    // This test is a placeholder for when we can properly mock the module discovery
    // For now, we test that the runner doesn't panic with minimal setup
    let cancel = CancellationToken::new();
    cancel.cancel(); // Immediate shutdown

    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(MockConfigProvider::new()),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Token(cancel),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    let result = run(opts).await;
    assert!(result.is_ok());
}

#[test]
fn test_run_options_construction() {
    let cancel = CancellationToken::new();

    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(MockConfigProvider::new()),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Token(cancel),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    // Test that we can construct RunOptions with all variants
    match opts.db {
        DbOptions::None => {}
        DbOptions::Manager(_) => panic!("Expected DbOptions::None"),
    }

    match opts.shutdown {
        ShutdownOptions::Token(_) => {}
        _ => panic!("Expected ShutdownOptions::Token"),
    }
}

#[tokio::test]
async fn test_cancellation_during_startup() {
    let cancel = CancellationToken::new();

    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(MockConfigProvider::new()),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Token(cancel.clone()),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    // Start the runner in a background task
    let runner_handle = tokio::spawn(run(opts));

    // Cancel immediately to test cancellation handling
    cancel.cancel();

    // Should complete quickly due to cancellation
    let result = timeout(Duration::from_millis(100), runner_handle).await;
    assert!(
        result.is_ok(),
        "Runner should complete quickly when cancelled"
    );

    let run_result = result.unwrap().unwrap();
    assert!(
        run_result.is_ok(),
        "Runner should handle cancellation gracefully"
    );
}

#[tokio::test]
async fn test_multiple_config_provider_scenarios() {
    let cancel = CancellationToken::new();
    cancel.cancel(); // Immediate shutdown

    // Test with empty config
    let empty_config = MockConfigProvider::new();
    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(empty_config),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Token(cancel.clone()),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    let result = run(opts).await;
    assert!(result.is_ok(), "Should handle empty config");

    // Test with complex config
    let complex_config = MockConfigProvider::new()
        .with_config(
            "module1",
            serde_json::json!({
                "setting1": "value1",
                "nested": {
                    "setting2": 42,
                    "setting3": true
                }
            }),
        )
        .with_config(
            "module2",
            serde_json::json!({
                "array_setting": [1, 2, 3],
                "string_setting": "test"
            }),
        );

    let cancel2 = CancellationToken::new();
    cancel2.cancel();

    let opts2 = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(complex_config),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Token(cancel2),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    let result2 = run(opts2).await;
    assert!(result2.is_ok(), "Should handle complex config");
}

#[tokio::test]
async fn test_runner_timeout_scenarios() {
    // Test that runner doesn't hang indefinitely
    let cancel = CancellationToken::new();

    let opts = RunOptions {
        instance_id: Uuid::new_v4(),
        modules_cfg: Arc::new(MockConfigProvider::new()),
        db: DbOptions::None,
        shutdown: ShutdownOptions::Token(cancel.clone()),
        clients: vec![],
        oop: None,
        shutdown_deadline: None,
    };

    let runner_handle = tokio::spawn(run(opts));

    // Give it some time to start up
    tokio::time::sleep(Duration::from_millis(10)).await;

    // Cancel after a short delay
    cancel.cancel();

    // Should complete within a reasonable time
    let result = timeout(Duration::from_millis(200), runner_handle).await;
    assert!(result.is_ok(), "Runner should complete within timeout");

    let run_result = result.unwrap().unwrap();
    assert!(run_result.is_ok(), "Runner should complete successfully");
}

// Test configuration scenarios
#[test]
fn test_config_provider_edge_cases() {
    let provider = MockConfigProvider::new()
        .with_config("test", serde_json::json!(null))
        .with_config("empty", serde_json::json!({}))
        .with_config(
            "complex",
            serde_json::json!({
                "a": {
                    "b": {
                        "c": "deep_value"
                    }
                }
            }),
        );

    // Test null config
    let null_config = provider.get_module_config("test");
    assert!(null_config.is_some());
    assert!(null_config.unwrap().is_null());

    // Test empty config
    let empty_config = provider.get_module_config("empty");
    assert!(empty_config.is_some());
    assert!(empty_config.unwrap().is_object());

    // Test complex config
    let complex_config = provider.get_module_config("complex");
    assert!(complex_config.is_some());
    assert!(complex_config.unwrap()["a"]["b"]["c"] == "deep_value");

    // Test non-existent config
    let missing_config = provider.get_module_config("nonexistent");
    assert!(missing_config.is_none());
}

// Placeholder tests for comprehensive lifecycle testing
// These would work with additional runner infrastructure that allows
// injecting test registries instead of using inventory discovery

/*
#[tokio::test]
async fn test_lifecycle_init_failure() {
    // This test demonstrates how we would test init phase failures
    // if the runner supported dependency injection of the registry

    let calls = Arc::new(Mutex::new(Vec::new()));
    let failing_module = TestModule::new("failing_module", calls.clone()).fail_init();

    // Would need a version of run() that accepts a pre-built registry
    // let registry = create_test_registry(vec![failing_module]).unwrap();
    // let result = run_with_registry(opts, registry).await;
    // assert!(result.is_err());
    // assert!(result.unwrap_err().to_string().contains("Init failed"));
}

#[tokio::test]
async fn test_lifecycle_complete_success() {
    // Demonstrates testing a complete successful lifecycle
    let calls = Arc::new(Mutex::new(Vec::new()));
    let modules = vec![
        TestModule::new("module1", calls.clone()),
        TestModule::new("module2", calls.clone()),
    ];

    // Would need runner API changes to support this
    // let registry = create_test_registry(modules).unwrap();
    // let result = run_with_registry(opts, registry).await;
    // assert!(result.is_ok());

    // Verify lifecycle call order
    // let call_log = calls.lock().unwrap();
    // assert!(call_log.contains(&"module1.init".to_string()));
    // assert!(call_log.contains(&"module2.init".to_string()));
}
*/