reinhardt-testkit 0.2.0-rc.1

Core testing infrastructure for Reinhardt framework (no functional crate dependencies)
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
//! Dependency Injection fixtures for testing
//!
//! This module provides rstest fixtures for FastAPI-style dependency injection testing.
//! It simplifies the setup of `InjectionContext` and `SingletonScope` in tests.
//!
//! ## Key Fixtures
//!
//! - [`singleton_scope`]: Provides an `Arc<SingletonScope>` for dependency caching
//! - [`injection_context`]: Provides an `InjectionContext` with empty request scope
//!
//! ## Usage Example
//!
//! ```rust,no_run
//! use reinhardt_di::{Injectable, DiResult};
//! use reinhardt_testkit::fixtures::{injection_context, singleton_scope};
//! use rstest::*;
//!
//! #[derive(Clone, Debug)]
//! struct Database {
//!     connection_string: String,
//! }
//!
//! #[async_trait::async_trait]
//! impl Injectable for Database {
//!     async fn inject(_ctx: &reinhardt_di::InjectionContext) -> DiResult<Self> {
//!         Ok(Database {
//!             connection_string: "postgres://localhost/test".to_string(),
//!         })
//!     }
//! }
//!
//! #[rstest]
//! #[tokio::test]
//! async fn test_with_di_fixture(injection_context: reinhardt_di::InjectionContext) {
//!     let db = Database::inject(&injection_context).await.unwrap();
//!     assert_eq!(db.connection_string, "postgres://localhost/test");
//! }
//! ```
//!
//! ## FastAPI-Style Pattern
//!
//! Similar to FastAPI's `Depends()`, these fixtures enable clean dependency injection
//! in tests without boilerplate setup code:
//!
//! ```rust,no_run
//! use reinhardt_di::Depends;
//! use reinhardt_testkit::fixtures::injection_context;
//! use rstest::*;
//!
//! #[rstest]
//! #[tokio::test]
//! async fn test_depends_pattern(injection_context: reinhardt_di::InjectionContext) {
//!     // Use Depends<T> for automatic dependency resolution
//!     let config = Depends::<Config>::builder()
//!         .resolve(&injection_context)
//!         .await
//!         .unwrap();
//!
//!     // Test with resolved dependency
//! }
//! ```
//!
//! ## Dependency Overrides
//!
//! Similar to FastAPI's `app.dependency_overrides`, you can override dependencies
//! in the singleton scope for testing:
//!
//! ```rust,no_run
//! use reinhardt_di::{Injectable, DiResult, InjectionContext};
//! use reinhardt_testkit::fixtures::{injection_context_with_overrides, singleton_scope};
//! use rstest::*;
//! use std::sync::Arc;
//!
//! #[derive(Clone, Debug)]
//! struct Database {
//!     url: String,
//! }
//!
//! #[async_trait::async_trait]
//! impl Injectable for Database {
//!     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
//!         Ok(Database { url: "prod://db".to_string() })
//!     }
//! }
//!
//! #[rstest]
//! #[tokio::test]
//! async fn test_with_mock_database(singleton_scope: Arc<reinhardt_di::SingletonScope>) {
//!     // Override Database with a mock
//!     let mock_db = Database { url: "test://db".to_string() };
//!     singleton_scope.set(mock_db);
//!
//!     let ctx = reinhardt_di::InjectionContext::builder(singleton_scope).build();
//!
//!     // This will return the mock database from singleton scope
//!     let db = Database::inject(&ctx).await.unwrap();
//!     assert_eq!(db.url, "test://db");
//! }
//! ```

use reinhardt_di::resolve_context::{RESOLVE_CTX, ResolveContext};
use reinhardt_di::{InjectionContext, SingletonScope};
use rstest::*;
use std::future::Future;
use std::sync::Arc;

/// Fixture providing a singleton scope for dependency injection.
///
/// Creates a new `SingletonScope` wrapped in `Arc` for each test.
/// This scope can be used to cache singleton dependencies across
/// the lifetime of a test.
///
/// # Returns
///
/// `Arc<SingletonScope>` - A thread-safe singleton scope instance
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_di::SingletonScope;
/// use reinhardt_testkit::fixtures::singleton_scope;
/// use rstest::*;
/// use std::sync::Arc;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_singleton_scope(singleton_scope: Arc<SingletonScope>) {
///     // Use singleton_scope for manual scope management
///     singleton_scope.set("test_value".to_string());
///     let value: Option<Arc<String>> = singleton_scope.get();
///     assert_eq!(*value.unwrap(), "test_value");
/// }
/// ```
#[fixture]
pub fn singleton_scope() -> Arc<SingletonScope> {
	Arc::new(SingletonScope::new())
}

/// Fixture providing an injection context for dependency injection.
///
/// Creates a new `InjectionContext` with an empty request scope.
/// The context is automatically configured with a singleton scope
/// from the `singleton_scope` fixture.
///
/// This fixture is the primary entry point for FastAPI-style dependency
/// injection in tests. It eliminates the boilerplate of manually creating
/// `SingletonScope` and `InjectionContext` in every test.
///
/// # Dependencies
///
/// - `singleton_scope`: Automatically resolved by rstest
///
/// # Returns
///
/// `InjectionContext` - A configured injection context ready for use
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_di::{Injectable, InjectionContext, DiResult};
/// use reinhardt_testkit::fixtures::injection_context;
/// use rstest::*;
///
/// #[derive(Clone)]
/// struct Config {
///     api_key: String,
/// }
///
/// #[async_trait::async_trait]
/// impl Injectable for Config {
///     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
///         Ok(Config {
///             api_key: "test_key".to_string(),
///         })
///     }
/// }
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_injection(injection_context: InjectionContext) {
///     let config = Config::inject(&injection_context).await.unwrap();
///     assert_eq!(config.api_key, "test_key");
/// }
/// ```
///
/// ## With `Depends<T>`
///
/// ```rust,no_run
/// use reinhardt_di::{Depends, Injectable, InjectionContext, DiResult};
/// use reinhardt_testkit::fixtures::injection_context;
/// use rstest::*;
///
/// #[derive(Clone, Default)]
/// struct Database {
///     url: String,
/// }
///
/// #[async_trait::async_trait]
/// impl Injectable for Database {
///     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
///         Ok(Database {
///             url: "postgres://localhost/db".to_string(),
///         })
///     }
/// }
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_with_depends(injection_context: InjectionContext) {
///     // FastAPI-style dependency resolution
///     let db = Depends::<Database>::builder()
///         .resolve(&injection_context)
///         .await
///         .unwrap();
///
///     assert_eq!(db.url, "postgres://localhost/db");
/// }
/// ```
#[fixture]
pub fn injection_context(singleton_scope: Arc<SingletonScope>) -> InjectionContext {
	InjectionContext::builder(singleton_scope).build()
}

/// Helper function to create an injection context with dependency overrides.
///
/// Similar to FastAPI's `app.dependency_overrides`, this function allows you to
/// pre-populate the singleton scope with mock or test values that will be returned
/// instead of calling the `Injectable::inject()` implementation.
///
/// This is useful for:
/// - Replacing database connections with test databases
/// - Injecting mock services for unit testing
/// - Providing test configurations
///
/// # Arguments
///
/// * `singleton_scope` - The singleton scope to use (typically from the fixture)
/// * `overrides` - A closure that receives a mutable reference to the singleton scope
///   and can set override values using `scope.set(value)`
///
/// # Returns
///
/// `InjectionContext` - A configured injection context with overrides applied
///
/// # Examples
///
/// ## Basic Override
///
/// ```rust,no_run
/// use reinhardt_di::{Injectable, DiResult, InjectionContext};
/// use reinhardt_testkit::fixtures::{injection_context_with_overrides, singleton_scope};
/// use rstest::*;
/// use std::sync::Arc;
///
/// #[derive(Clone, Debug, PartialEq)]
/// struct Database {
///     url: String,
/// }
///
/// #[async_trait::async_trait]
/// impl Injectable for Database {
///     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
///         // Production implementation
///         Ok(Database { url: "prod://db".to_string() })
///     }
/// }
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_with_mock_db(singleton_scope: Arc<reinhardt_di::SingletonScope>) {
///     let ctx = reinhardt_testkit::fixtures::injection_context_with_overrides(
///         singleton_scope,
///         |scope| {
///             // Override Database with test value
///             scope.set(Database { url: "test://db".to_string() });
///         },
///     );
///
///     // Database::inject will return the test value from singleton scope
///     let db = Database::inject(&ctx).await.unwrap();
///     assert_eq!(db.url, "test://db");
/// }
/// ```
///
/// ## Multiple Overrides
///
/// ```rust,no_run
/// use reinhardt_di::{Injectable, DiResult, InjectionContext};
/// use reinhardt_testkit::fixtures::{injection_context_with_overrides, singleton_scope};
/// use rstest::*;
/// use std::sync::Arc;
///
/// #[derive(Clone)]
/// struct Config {
///     api_key: String,
/// }
///
/// #[derive(Clone)]
/// struct Database {
///     url: String,
/// }
///
/// #[async_trait::async_trait]
/// impl Injectable for Config {
///     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
///         Ok(Config { api_key: "prod_key".to_string() })
///     }
/// }
///
/// #[async_trait::async_trait]
/// impl Injectable for Database {
///     async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
///         Ok(Database { url: "prod://db".to_string() })
///     }
/// }
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_with_multiple_mocks(singleton_scope: Arc<reinhardt_di::SingletonScope>) {
///     let ctx = reinhardt_testkit::fixtures::injection_context_with_overrides(
///         singleton_scope,
///         |scope| {
///             // Override multiple dependencies
///             scope.set(Config { api_key: "test_key".to_string() });
///             scope.set(Database { url: "test://db".to_string() });
///         },
///     );
///
///     let config = Config::inject(&ctx).await.unwrap();
///     let db = Database::inject(&ctx).await.unwrap();
///
///     assert_eq!(config.api_key, "test_key");
///     assert_eq!(db.url, "test://db");
/// }
/// ```
pub fn injection_context_with_overrides<F>(
	singleton_scope: Arc<SingletonScope>,
	overrides: F,
) -> InjectionContext
where
	F: FnOnce(&SingletonScope),
{
	// Apply overrides to singleton scope
	overrides(&singleton_scope);

	// Build context with overridden singleton scope
	InjectionContext::builder(singleton_scope).build()
}

// ============================================================================
// Server Function Testing with Database Connection
// ============================================================================

/// Fixture providing an injection context with a SQLite database connection.
///
/// This fixture is designed for testing server functions that use `#[inject]`
/// to receive a `DatabaseConnection`. It creates a temporary SQLite database
/// and registers the connection in the singleton scope.
///
/// # Returns
///
/// A tuple containing:
/// - `tempfile::NamedTempFile`: The temporary database file (must be kept alive)
/// - `InjectionContext`: The DI context with `DatabaseConnection` registered
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::injection_context_with_sqlite;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_server_function(
///     #[future] injection_context_with_sqlite: (tempfile::NamedTempFile, reinhardt_di::InjectionContext),
/// ) {
///     let (_temp_file, ctx) = injection_context_with_sqlite.await;
///
///     // Server functions can now resolve DatabaseConnection from the context
///     // let result = my_server_function().await;
/// }
/// ```
///
/// # Note
///
/// The `NamedTempFile` must be kept alive for the duration of the test.
/// When it goes out of scope, the temporary database file will be deleted.
#[fixture]
pub async fn injection_context_with_sqlite() -> (tempfile::NamedTempFile, InjectionContext) {
	use reinhardt_db::orm::connection::DatabaseConnection;

	// Create temp file for SQLite database
	let temp_file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
	let db_path = temp_file.path().to_str().unwrap().to_string();
	let database_url = format!("sqlite://{}?mode=rwc", db_path);

	// Create DatabaseConnection using ORM layer API
	let db_conn = DatabaseConnection::connect_sqlite(&database_url)
		.await
		.expect("Failed to create DatabaseConnection");

	// Build DI context with DatabaseConnection registered in singleton scope
	let singleton_scope = Arc::new(SingletonScope::new());
	singleton_scope.set(db_conn);

	let ctx = InjectionContext::builder(singleton_scope).build();

	(temp_file, ctx)
}

/// Helper function to create an injection context with a custom database URL.
///
/// This is useful when you need to connect to a specific database
/// (e.g., PostgreSQL, MySQL) for testing.
///
/// # Arguments
///
/// * `database_url` - The database connection URL
///
/// # Returns
///
/// `InjectionContext` - A configured injection context with `DatabaseConnection` registered
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::injection_context_with_database;
///
/// #[tokio::test]
/// async fn test_with_postgres() {
///     let ctx = injection_context_with_database("postgres://localhost/test").await;
///     // Use ctx for testing
/// }
/// ```
pub async fn injection_context_with_database(database_url: &str) -> InjectionContext {
	use reinhardt_db::orm::connection::DatabaseConnection;

	// Create DatabaseConnection
	let db_conn = DatabaseConnection::connect(database_url)
		.await
		.expect("Failed to create DatabaseConnection");

	// Build DI context with DatabaseConnection registered
	let singleton_scope = Arc::new(SingletonScope::new());
	singleton_scope.set(db_conn);

	InjectionContext::builder(singleton_scope).build()
}

/// Runs an async test body with an isolated DI context.
///
/// Creates a fresh [`SingletonScope`] and [`InjectionContext`] for each call,
/// sets the task-local `RESOLVE_CTX` so that
/// [`get_di_context`](reinhardt_di::resolve_context::get_di_context) works
/// both in factory execution and in the test body, and returns the
/// closure's result.
///
/// # Parallel Safety
///
/// Each invocation creates its own `SingletonScope` and `InjectionContext`.
/// The `RESOLVE_CTX` is task-local (`tokio::task_local!`), so parallel
/// test tasks do not interfere with each other.
///
/// # Examples
///
/// ```rust,no_run
/// use reinhardt_testkit::fixtures::with_test_di_context;
/// use reinhardt_di::resolve_context::{get_di_context, ContextLevel};
/// use rstest::*;
/// use std::sync::Arc;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_with_di_context() {
///     let result = with_test_di_context(
///         |scope| {
///             scope.set("test_value".to_string());
///         },
///         |di_ctx| async move {
///             // get_di_context works here
///             let root = get_di_context(ContextLevel::Root);
///             assert!(Arc::ptr_eq(&root, &di_ctx));
///             42
///         },
///     ).await;
///
///     assert_eq!(result, 42);
/// }
/// ```
pub async fn with_test_di_context<F, Fut, T>(setup: impl FnOnce(&SingletonScope), f: F) -> T
where
	F: FnOnce(Arc<InjectionContext>) -> Fut,
	Fut: Future<Output = T>,
{
	let scope = Arc::new(SingletonScope::new());
	setup(&scope);
	let ctx = Arc::new(InjectionContext::builder(scope).build());
	let resolve_ctx = ResolveContext {
		root: Arc::clone(&ctx),
		current: Arc::clone(&ctx),
	};
	RESOLVE_CTX.scope(resolve_ctx, f(ctx)).await
}

#[cfg(test)]
mod tests {
	use super::*;
	use reinhardt_di::{Depends, DiResult, Injectable};

	// Test structures
	#[derive(Clone, Debug, PartialEq)]
	struct TestConfig {
		value: String,
	}

	#[async_trait::async_trait]
	impl Injectable for TestConfig {
		async fn inject(_ctx: &InjectionContext) -> DiResult<Self> {
			Ok(TestConfig {
				value: "test_config".to_string(),
			})
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_singleton_scope_fixture(singleton_scope: Arc<SingletonScope>) {
		// Verify singleton_scope is created
		assert!(
			singleton_scope.get::<String>().is_none(),
			"Singleton scope should be empty initially"
		);

		// Set a value
		singleton_scope.set("test".to_string());

		// Retrieve the value
		let value: Option<Arc<String>> = singleton_scope.get();
		assert_eq!(*value.unwrap(), "test");
	}

	#[rstest]
	#[tokio::test]
	async fn test_injection_context_fixture(injection_context: InjectionContext) {
		// Verify injection_context is created and works
		let config = TestConfig::inject(&injection_context).await.unwrap();
		assert_eq!(config.value, "test_config");
	}

	#[rstest]
	#[tokio::test]
	async fn test_fixture_isolation_first(injection_context: InjectionContext) {
		// Set a value in request scope
		injection_context.set_request("first".to_string());

		// Verify we can retrieve it
		let value: Option<Arc<String>> = injection_context.get_request();
		assert_eq!(*value.unwrap(), "first");
	}

	#[rstest]
	#[tokio::test]
	async fn test_fixture_isolation_second(injection_context: InjectionContext) {
		// This test should NOT see the value from test_fixture_isolation_first
		let value: Option<Arc<String>> = injection_context.get_request();
		assert!(
			value.is_none(),
			"Request scope should be isolated between tests"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_depends_with_fixtures(injection_context: InjectionContext) {
		// Register TestConfig in the global registry so Depends<T> can resolve it
		let registry = reinhardt_di::global_registry();
		registry.register_async::<TestConfig, _, _>(
			reinhardt_di::DependencyScope::Request,
			|_ctx| async {
				Ok(TestConfig {
					value: "test_config".to_string(),
				})
			},
		);

		// Test Depends<T> integration with fixtures
		let config = Depends::<TestConfig>::builder()
			.resolve(&injection_context)
			.await
			.unwrap();

		assert_eq!(config.value, "test_config");
	}

	#[rstest]
	#[tokio::test]
	async fn test_request_scope_caching(injection_context: InjectionContext) {
		// First injection - creates and caches
		let config1 = TestConfig::inject(&injection_context).await.unwrap();

		// Second injection - should return same instance from cache
		let config2 = TestConfig::inject(&injection_context).await.unwrap();

		// Verify both are from the same request scope
		assert_eq!(config1, config2);
	}

	#[rstest]
	#[tokio::test]
	async fn test_singleton_scope_sharing(singleton_scope: Arc<SingletonScope>) {
		// Test that singleton scope can be shared across contexts
		let ctx1 = InjectionContext::builder(Arc::clone(&singleton_scope)).build();
		let ctx2 = InjectionContext::builder(Arc::clone(&singleton_scope)).build();

		// Set a value in singleton scope via ctx1
		ctx1.set_singleton("shared_value".to_string());

		// Retrieve from ctx2 - should see the shared value
		let value: Option<Arc<String>> = ctx2.get_singleton();
		assert_eq!(*value.unwrap(), "shared_value");
	}

	// Tests for injection_context_with_overrides

	#[derive(Clone, Debug, PartialEq)]
	struct MockDatabase {
		url: String,
	}

	#[async_trait::async_trait]
	impl Injectable for MockDatabase {
		async fn inject(ctx: &InjectionContext) -> DiResult<Self> {
			// Check singleton scope first
			if let Some(db) = ctx.get_singleton::<MockDatabase>() {
				return Ok((*db).clone());
			}

			// Default production implementation
			Ok(MockDatabase {
				url: "prod://database".to_string(),
			})
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_injection_context_with_overrides_basic(singleton_scope: Arc<SingletonScope>) {
		// Create context with override
		let ctx = injection_context_with_overrides(singleton_scope, |scope| {
			scope.set(MockDatabase {
				url: "test://database".to_string(),
			});
		});

		// Inject should return the overridden value
		let db = MockDatabase::inject(&ctx).await.unwrap();
		assert_eq!(db.url, "test://database");
	}

	#[derive(Clone, Debug, PartialEq)]
	struct MockConfig {
		api_key: String,
	}

	#[async_trait::async_trait]
	impl Injectable for MockConfig {
		async fn inject(ctx: &InjectionContext) -> DiResult<Self> {
			// Check singleton scope first
			if let Some(config) = ctx.get_singleton::<MockConfig>() {
				return Ok((*config).clone());
			}

			// Default production implementation
			Ok(MockConfig {
				api_key: "prod_key".to_string(),
			})
		}
	}

	#[rstest]
	#[tokio::test]
	async fn test_injection_context_with_overrides_multiple(singleton_scope: Arc<SingletonScope>) {
		// Create context with multiple overrides
		let ctx = injection_context_with_overrides(singleton_scope, |scope| {
			scope.set(MockDatabase {
				url: "test://database".to_string(),
			});
			scope.set(MockConfig {
				api_key: "test_key".to_string(),
			});
		});

		// Both injections should return overridden values
		let db = MockDatabase::inject(&ctx).await.unwrap();
		let config = MockConfig::inject(&ctx).await.unwrap();

		assert_eq!(db.url, "test://database");
		assert_eq!(config.api_key, "test_key");
	}

	#[rstest]
	#[tokio::test]
	async fn test_injection_context_without_overrides_uses_default(
		singleton_scope: Arc<SingletonScope>,
	) {
		// Create context WITHOUT overrides
		let ctx = InjectionContext::builder(singleton_scope).build();

		// Should return production values
		let db = MockDatabase::inject(&ctx).await.unwrap();
		let config = MockConfig::inject(&ctx).await.unwrap();

		assert_eq!(db.url, "prod://database");
		assert_eq!(config.api_key, "prod_key");
	}

	#[rstest]
	#[tokio::test]
	async fn test_injection_context_with_overrides_and_depends(
		singleton_scope: Arc<SingletonScope>,
	) {
		// Create context with override
		let ctx = injection_context_with_overrides(singleton_scope, |scope| {
			scope.set(MockDatabase {
				url: "test://database".to_string(),
			});
		});

		// Use Depends<T> - should also get the overridden value
		let db = Depends::<MockDatabase>::builder()
			.resolve(&ctx)
			.await
			.unwrap();

		assert_eq!(db.url, "test://database");
	}

	// Tests for with_test_di_context

	#[rstest]
	#[tokio::test]
	async fn test_with_test_di_context_unique_per_call() {
		// Act
		let ctx1 = with_test_di_context(|_| {}, |ctx| async move { ctx }).await;
		let ctx2 = with_test_di_context(|_| {}, |ctx| async move { ctx }).await;

		// Assert
		assert!(!Arc::ptr_eq(&ctx1, &ctx2));
	}

	#[rstest]
	#[tokio::test]
	async fn test_with_test_di_context_get_di_context_root() {
		use reinhardt_di::resolve_context::{ContextLevel, get_di_context};

		// Act & Assert
		with_test_di_context(
			|_| {},
			|ctx| async move {
				let root = get_di_context(ContextLevel::Root);
				assert!(Arc::ptr_eq(&root, &ctx));
			},
		)
		.await;
	}

	#[rstest]
	#[tokio::test]
	async fn test_with_test_di_context_get_di_context_current() {
		use reinhardt_di::resolve_context::{ContextLevel, get_di_context};

		// Act & Assert
		with_test_di_context(
			|_| {},
			|ctx| async move {
				let current = get_di_context(ContextLevel::Current);
				assert!(Arc::ptr_eq(&current, &ctx));
			},
		)
		.await;
	}

	#[rstest]
	#[tokio::test]
	async fn test_with_test_di_context_setup_registers_singletons() {
		// Arrange & Act
		let result = with_test_di_context(
			|scope| {
				scope.set(TestConfig {
					value: "from_setup".to_string(),
				});
			},
			|ctx| async move {
				// Assert
				let config: Option<Arc<TestConfig>> = ctx.get_singleton();
				config.unwrap().value.clone()
			},
		)
		.await;

		assert_eq!(result, "from_setup");
	}

	#[rstest]
	#[tokio::test]
	async fn test_with_test_di_context_parallel_safety() {
		// Act
		let (val1, val2) = tokio::join!(
			with_test_di_context(
				|scope| {
					scope.set("task_1".to_string());
				},
				|ctx| async move {
					let v: Option<Arc<String>> = ctx.get_singleton();
					v.unwrap().as_str().to_owned()
				},
			),
			with_test_di_context(
				|scope| {
					scope.set("task_2".to_string());
				},
				|ctx| async move {
					let v: Option<Arc<String>> = ctx.get_singleton();
					v.unwrap().as_str().to_owned()
				},
			),
		);

		// Assert
		assert_eq!(val1, "task_1");
		assert_eq!(val2, "task_2");
	}
}