reinhardt-testkit 0.1.1

Core testing infrastructure for Reinhardt framework (no functional crate dependencies)
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
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
//! Server test fixtures with automatic graceful shutdown.
//!
//! This module provides rstest fixtures for testing HTTP servers with automatic
//! cleanup via RAII pattern.

use reinhardt_di::InjectionContext;
use reinhardt_http::Handler;
use reinhardt_http::{Request, Response};
use reinhardt_server::{
	HttpServer, RateLimitConfig, RateLimitHandler, ShutdownCoordinator, TimeoutHandler,
};
use reinhardt_urls::routers::ServerRouter as Router;
use rstest::fixture;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::TcpListener;
use tokio::task::JoinHandle;

#[cfg(feature = "websockets")]
use reinhardt_server::WebSocketServer;

#[cfg(feature = "graphql")]
use reinhardt_server::GraphQLHandler;

/// Test server guard with automatic graceful shutdown.
///
/// This guard automatically performs graceful shutdown when dropped, ensuring
/// proper cleanup of server resources even if the test panics.
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use reinhardt_urls::routers::ServerRouter as Router;
///
/// #[tokio::test]
/// async fn test_example() {
///     let router = Router::new();
///     let server = test_server_guard(router).await;
///     let response = reqwest::get(&format!("{}/test", server.url))
///         .await
///         .unwrap();
///     assert_eq!(response.status(), 200);
///     // Automatic graceful shutdown when server goes out of scope
/// }
/// ```
pub struct TestServerGuard {
	/// Server URL (e.g., "http://127.0.0.1:12345")
	pub url: String,
	/// Shutdown coordinator for graceful shutdown
	pub coordinator: Arc<ShutdownCoordinator>,
	/// Server task handle
	server_task: Option<JoinHandle<()>>,
}

impl TestServerGuard {
	/// Create a new test server guard.
	///
	/// This function:
	/// 1. Binds to a random port (127.0.0.1:0)
	/// 2. Creates a ShutdownCoordinator
	/// 3. Spawns the server task
	/// 4. Probes the server port until it accepts connections
	///
	/// # Arguments
	///
	/// * `router` - Router to use for handling requests
	async fn new(router: Router) -> Self {
		let shutdown_timeout = Duration::from_secs(5);
		// Bind to random port and keep the listener to avoid TOCTOU race
		let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
		let actual_addr = listener.local_addr().unwrap();
		let url = format!("http://{}", actual_addr);

		// Create shutdown coordinator
		let coordinator = Arc::new(ShutdownCoordinator::new(shutdown_timeout));

		// Spawn server using the already-bound listener to avoid port race
		let server_coordinator = (*coordinator).clone();
		let handler: Arc<dyn Handler> = Arc::new(router);
		let server = HttpServer::new(handler);
		let mut shutdown_rx = server_coordinator.subscribe();
		let server_task = tokio::spawn(async move {
			loop {
				tokio::select! {
					result = listener.accept() => {
						match result {
							Ok((stream, socket_addr)) => {
								let handler_clone = server.handler();
								tokio::spawn(async move {
									if let Err(e) =
										HttpServer::handle_connection(stream, socket_addr, handler_clone, None)
											.await
									{
										eprintln!("Error handling connection: {:?}", e);
									}
								});
							}
							Err(e) => {
								eprintln!("Error accepting connection: {:?}", e);
								break;
							}
						}
					}
					_ = shutdown_rx.recv() => {
						break;
					}
				}
			}
		});

		// Probe server readiness with TCP connect attempts instead of fixed sleep.
		// This avoids flaky failures when the system is under heavy load.
		wait_for_server_ready(actual_addr)
			.await
			.expect("Test server failed to become ready");

		Self {
			url,
			coordinator,
			server_task: Some(server_task),
		}
	}
}

impl Drop for TestServerGuard {
	fn drop(&mut self) {
		// Trigger shutdown signal
		self.coordinator.shutdown();

		// Abort the server task
		// The ShutdownCoordinator will handle graceful shutdown,
		// but we need to ensure the task is terminated
		if let Some(task) = self.server_task.take() {
			task.abort();
		}
	}
}

/// Create a test server guard with the given router.
///
/// This is a helper function (not an rstest fixture) that creates a test server
/// with automatic graceful shutdown. Use it directly in your tests.
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use reinhardt_urls::routers::ServerRouter as Router;
///
/// #[tokio::test]
/// async fn test_server() {
///     let router = Router::new();
///     let server = test_server_guard(router).await;
///     let response = reqwest::get(&format!("{}/hello", server.url))
///         .await
///         .unwrap();
///     assert_eq!(response.status(), 200);
///     // Automatic cleanup on drop
/// }
/// ```
pub async fn test_server_guard(router: Router) -> TestServerGuard {
	TestServerGuard::new(router).await
}

// ============================================================================
// Basic Test Handlers
// ============================================================================

/// Basic handler for testing purposes that returns "OK"
#[derive(Clone)]
pub struct BasicHandler;

#[async_trait::async_trait]
impl Handler for BasicHandler {
	async fn handle(&self, _request: Request) -> reinhardt_core::exception::Result<Response> {
		Ok(Response::ok().with_body("OK"))
	}
}

// ============================================================================
// Client Fixtures
// ============================================================================

/// HTTP client fixture for testing HTTP requests
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_with_client(http_client: reqwest::Client) {
///     let response = http_client
///         .get("http://localhost:8080/api/test")
///         .send()
///         .await
///         .unwrap();
///     assert_eq!(response.status(), 200);
/// }
/// ```
#[fixture]
pub fn http_client() -> reqwest::Client {
	reqwest::Client::builder()
		.timeout(Duration::from_secs(10))
		.build()
		.expect("Failed to create HTTP client")
}
// ============================================================================
// HTTP/1.1 Server Fixtures
// ============================================================================

/// HTTP/1.1 test server fixture
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_http1_server(#[future] http1_server: TestServer) {
///     let server = http1_server.await;
///     let client = reqwest::Client::new();
///     let response = client.get(&server.url).send().await.unwrap();
///     assert_eq!(response.status(), 200);
/// }
/// ```
#[fixture]
pub async fn http1_server() -> TestServer {
	let handler = Arc::new(BasicHandler);
	TestServer::builder()
		.handler(handler)
		.build()
		.await
		.expect("Failed to create HTTP/1.1 server")
}

// ============================================================================
// HTTP/2 Server Fixtures
// ============================================================================

/// HTTP/2 test server fixture
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_http2_server(#[future] http2_server: TestServer) {
///     let server = http2_server.await;
///     // Test with HTTP/2 client
/// }
/// ```
#[fixture]
pub async fn http2_server() -> TestServer {
	let handler = Arc::new(BasicHandler);
	TestServer::builder()
		.handler(handler)
		.http2(true)
		.build()
		.await
		.expect("Failed to create HTTP/2 server")
}

// ============================================================================
// Middleware Server Fixtures
// ============================================================================

/// Server fixture with timeout middleware
///
/// Default timeout: 5 seconds
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_timeout(#[future] server_with_timeout: TestServer) {
///     let server = server_with_timeout.await;
///     // Timeout test
/// }
/// ```
#[fixture]
pub async fn server_with_timeout(
	#[default(Duration::from_secs(5))] timeout: Duration,
) -> TestServer {
	let handler = Arc::new(BasicHandler);
	let timeout_handler = Arc::new(TimeoutHandler::new(handler, timeout));
	TestServer::builder()
		.handler(timeout_handler)
		.build()
		.await
		.expect("Failed to create server with timeout")
}

/// Server fixture with rate limit middleware
///
/// Default rate limit: 100 requests/minute
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_rate_limit(#[future] server_with_rate_limit: TestServer) {
///     let server = server_with_rate_limit.await;
///     // Rate limit test
/// }
/// ```
#[fixture]
pub async fn server_with_rate_limit(#[default(100)] limit: u32) -> TestServer {
	let handler = Arc::new(BasicHandler);
	let config = RateLimitConfig::per_minute(limit as usize);
	let rate_limit_handler = Arc::new(RateLimitHandler::new(handler, config));
	TestServer::builder()
		.handler(rate_limit_handler)
		.build()
		.await
		.expect("Failed to create server with rate limit")
}

/// Server fixture with middleware chain (Timeout + RateLimit)
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_middleware_chain(#[future] server_with_middleware_chain: TestServer) {
///     let server = server_with_middleware_chain.await;
///     // Middleware chain test
/// }
/// ```
#[fixture]
pub async fn server_with_middleware_chain() -> TestServer {
	let handler = Arc::new(BasicHandler);
	let timeout_handler = Arc::new(TimeoutHandler::new(handler, Duration::from_secs(5)));
	let config = RateLimitConfig::per_minute(100);
	let rate_limit_handler = Arc::new(RateLimitHandler::new(timeout_handler, config));

	TestServer::builder()
		.handler(rate_limit_handler)
		.build()
		.await
		.expect("Failed to create server with middleware chain")
}

/// Server fixture with DI context
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_di_context(#[future] server_with_di: (TestServer, Arc<InjectionContext>)) {
///     let (server, di_context) = server_with_di.await;
///     // DI context test
/// }
/// ```
#[fixture]
pub async fn server_with_di() -> (TestServer, Arc<InjectionContext>) {
	use reinhardt_di::SingletonScope;

	let handler = Arc::new(BasicHandler);
	let di_context = Arc::new(InjectionContext::builder(Arc::new(SingletonScope::new())).build());

	let server = TestServer::builder()
		.handler(handler)
		.di_context(di_context.clone())
		.build()
		.await
		.expect("Failed to create server with DI context");

	(server, di_context)
}

// ============================================================================
// WebSocket Server Fixtures (feature: websocket)
// ============================================================================

#[cfg(feature = "websockets")]
/// WebSocket-enabled server fixture
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_websocket_server(#[future] websocket_server: TestServer) {
///     let server = websocket_server.await;
///     // WebSocket test
/// }
/// ```
#[fixture]
pub async fn websocket_server() -> TestServer {
	use reinhardt_server::WebSocketHandler;

	#[derive(Clone)]
	struct EchoHandler;

	#[async_trait::async_trait]
	impl WebSocketHandler for EchoHandler {
		async fn handle_message(&self, message: String) -> Result<String, String> {
			Ok(message) // Echo back
		}

		async fn on_connect(&self) {}
		async fn on_disconnect(&self) {}
	}

	let ws_handler = Arc::new(EchoHandler);
	TestServer::builder()
		.websocket_handler(ws_handler)
		.build()
		.await
		.expect("Failed to create WebSocket server")
}

#[cfg(feature = "websockets")]
/// WebSocket client fixture
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_websocket_client(websocket_client: tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>) {
///     // WebSocket client test
/// }
/// ```
#[fixture]
pub async fn websocket_client(
	#[from(websocket_server)]
	#[future]
	server: TestServer,
) -> tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>> {
	let server = server.await;
	let ws_url = server.url.replace("http://", "ws://");
	let (ws_stream, _) = tokio_tungstenite::connect_async(&ws_url)
		.await
		.expect("Failed to connect WebSocket");
	ws_stream
}

// ============================================================================
// GraphQL Server Fixtures (feature: graphql)
// ============================================================================

#[cfg(feature = "graphql")]
/// GraphQL-enabled server fixture
///
/// # Examples
///
/// ```no_run
/// use reinhardt_testkit::fixtures::*;
/// use rstest::*;
///
/// #[rstest]
/// #[tokio::test]
/// async fn test_graphql_server(#[future] graphql_server: TestServer) {
///     let server = graphql_server.await;
///     // GraphQL test
/// }
/// ```
#[cfg(feature = "graphql")]
#[fixture]
pub async fn graphql_server() -> TestServer {
	use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema};

	struct Query;

	#[Object]
	impl Query {
		async fn hello(&self) -> &'static str {
			"Hello, GraphQL!"
		}
	}

	let schema = Schema::build(Query, EmptyMutation, EmptySubscription).finish();
	let graphql_handler = Arc::new(GraphQLHandler::new(schema));

	TestServer::builder()
		.handler(graphql_handler)
		.build()
		.await
		.expect("Failed to create GraphQL server")
}

// ============================================================================
// TestServer Structure with Builder Pattern
// ============================================================================

/// Test server with automatic graceful shutdown
pub struct TestServer {
	/// Server URL (e.g., "http://127.0.0.1:12345")
	pub url: String,
	/// Server address
	pub addr: SocketAddr,
	/// Shutdown coordinator
	pub coordinator: Arc<ShutdownCoordinator>,
	/// Server task handle
	server_task: Option<JoinHandle<()>>,
}

impl TestServer {
	/// Create a new TestServerBuilder
	pub fn builder() -> TestServerBuilder {
		TestServerBuilder::new()
	}
}

impl Drop for TestServer {
	fn drop(&mut self) {
		// Trigger shutdown signal
		self.coordinator.shutdown();

		// Abort the server task
		if let Some(task) = self.server_task.take() {
			task.abort();
		}
	}
}

/// Builder for TestServer
pub struct TestServerBuilder {
	handler: Option<Arc<dyn Handler>>,
	#[cfg(feature = "websockets")]
	websocket_handler: Option<Arc<dyn reinhardt_server::WebSocketHandler>>,
	di_context: Option<Arc<InjectionContext>>,
	http2: bool,
	shutdown_timeout: Duration,
}

impl TestServerBuilder {
	fn new() -> Self {
		Self {
			handler: None,
			#[cfg(feature = "websockets")]
			websocket_handler: None,
			di_context: None,
			http2: false,
			shutdown_timeout: Duration::from_secs(5),
		}
	}

	/// Set the handler for HTTP requests
	pub fn handler(mut self, handler: Arc<dyn Handler>) -> Self {
		self.handler = Some(handler);
		self
	}

	#[cfg(feature = "websockets")]
	/// Set the WebSocket handler
	pub fn websocket_handler(
		mut self,
		handler: Arc<dyn reinhardt_server::WebSocketHandler>,
	) -> Self {
		self.websocket_handler = Some(handler);
		self
	}

	/// Set the DI context
	pub fn di_context(mut self, context: Arc<InjectionContext>) -> Self {
		self.di_context = Some(context);
		self
	}

	/// Enable HTTP/2
	pub fn http2(mut self, enabled: bool) -> Self {
		self.http2 = enabled;
		self
	}

	/// Set shutdown timeout
	pub fn shutdown_timeout(mut self, timeout: Duration) -> Self {
		self.shutdown_timeout = timeout;
		self
	}

	/// Build the TestServer
	pub async fn build(self) -> Result<TestServer, Box<dyn std::error::Error>> {
		// Bind to random port and keep the listener to avoid TOCTOU race
		let listener = TcpListener::bind("127.0.0.1:0").await?;
		let actual_addr = listener.local_addr()?;
		let url = format!("http://{}", actual_addr);

		// Create shutdown coordinator
		let coordinator = Arc::new(ShutdownCoordinator::new(self.shutdown_timeout));

		// Spawn server based on configuration
		let server_coordinator = (*coordinator).clone();

		#[cfg(feature = "websockets")]
		let websocket_handler = self.websocket_handler;

		let handler = self.handler;
		let di_context = self.di_context;
		let http2 = self.http2;

		let server_task = tokio::spawn(async move {
			// For WebSocket and HTTP/2 servers, we must drop the listener and re-bind
			// because their APIs only accept SocketAddr. This has a small TOCTOU window
			// but these server types are rarely used in parallel tests.
			#[cfg(feature = "websockets")]
			if let Some(ws_handler) = websocket_handler {
				drop(listener);
				let server = WebSocketServer::from_arc(ws_handler);
				let _ = server
					.listen_with_shutdown(actual_addr, server_coordinator)
					.await;
				return;
			}

			if let Some(h) = handler {
				if http2 {
					drop(listener);
					let server = reinhardt_server::Http2Server::new(h);
					let _ = server
						.listen_with_shutdown(actual_addr, server_coordinator)
						.await;
				} else {
					// Use the already-bound listener directly to avoid TOCTOU race
					let server = HttpServer::new(h);
					let mut shutdown_rx = server_coordinator.subscribe();
					loop {
						tokio::select! {
							result = listener.accept() => {
								match result {
									Ok((stream, socket_addr)) => {
										let handler_clone = server.handler();
										let di_ctx = di_context.clone();
										tokio::spawn(async move {
											if let Err(e) =
												HttpServer::handle_connection(stream, socket_addr, handler_clone, di_ctx)
													.await
											{
												eprintln!("Error handling connection: {:?}", e);
											}
										});
									}
									Err(e) => {
										eprintln!("Error accepting connection: {:?}", e);
										break;
									}
								}
							}
							_ = shutdown_rx.recv() => {
								break;
							}
						}
					}
				}
			}
		});

		// Probe server readiness with TCP connect attempts instead of fixed sleep.
		// This avoids flaky failures when the system is under heavy load.
		wait_for_server_ready(actual_addr)
			.await
			.expect("Test server failed to become ready");

		Ok(TestServer {
			url,
			addr: actual_addr,
			coordinator,
			server_task: Some(server_task),
		})
	}
}

// ============================================================================
// Server Readiness Probe
// ============================================================================

/// Maximum number of TCP readiness probe attempts
const SERVER_READY_MAX_ATTEMPTS: u32 = 20;

/// Interval between TCP readiness probe attempts
const SERVER_READY_PROBE_INTERVAL_MS: u64 = 50;

/// Probe the server address with TCP connects until it accepts a connection.
///
/// This replaces a fixed `sleep(100ms)` with an active readiness check,
/// eliminating flaky test failures caused by slow server startup under load.
///
/// # Errors
///
/// Returns an error if the server does not accept a TCP connection within
/// the configured number of probe attempts.
async fn wait_for_server_ready(addr: SocketAddr) -> Result<(), std::io::Error> {
	for attempt in 1..=SERVER_READY_MAX_ATTEMPTS {
		// Try to establish a TCP connection to verify the server is accepting
		match tokio::net::TcpStream::connect(addr).await {
			Ok(_) => return Ok(()),
			Err(_) if attempt < SERVER_READY_MAX_ATTEMPTS => {
				tokio::time::sleep(Duration::from_millis(SERVER_READY_PROBE_INTERVAL_MS)).await;
			}
			Err(e) => {
				return Err(std::io::Error::new(
					std::io::ErrorKind::TimedOut,
					format!(
						"Server at {} not ready after {} attempts: {}",
						addr, SERVER_READY_MAX_ATTEMPTS, e
					),
				));
			}
		}
	}

	Err(std::io::Error::new(
		std::io::ErrorKind::TimedOut,
		format!(
			"Server at {} not ready after {} attempts",
			addr, SERVER_READY_MAX_ATTEMPTS
		),
	))
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::*;

	#[rstest]
	#[tokio::test]
	async fn test_basic_handler_returns_ok() {
		// Arrange
		let handler = BasicHandler;
		let request = Request::builder()
			.method(hyper::Method::GET)
			.uri("/")
			.build()
			.expect("Failed to build request");

		// Act
		let response = handler.handle(request).await;

		// Assert
		assert!(response.is_ok(), "Expected Ok response from BasicHandler");
		let resp = response.unwrap();
		assert_eq!(resp.status, hyper::StatusCode::OK);
	}

	#[rstest]
	#[tokio::test]
	async fn test_test_server_guard_starts() {
		// Arrange
		let router = Router::new();

		// Act
		let server = test_server_guard(router).await;

		// Assert
		assert!(
			server.url.starts_with("http://127.0.0.1:"),
			"Expected URL to start with 'http://127.0.0.1:', got: {}",
			server.url
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_test_server_builder_default() {
		// Arrange
		let handler: Arc<dyn Handler> = Arc::new(BasicHandler);

		// Act
		let result = TestServer::builder().handler(handler).build().await;

		// Assert
		assert!(
			result.is_ok(),
			"Expected TestServer::builder().handler().build() to succeed"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_test_server_url_format() {
		// Arrange
		let handler: Arc<dyn Handler> = Arc::new(BasicHandler);

		// Act
		let server = TestServer::builder()
			.handler(handler)
			.build()
			.await
			.expect("Failed to build TestServer");

		// Assert
		assert!(
			server.url.starts_with("http://127.0.0.1:"),
			"Expected URL format 'http://127.0.0.1:<port>', got: {}",
			server.url
		);
		assert!(
			server.addr.port() > 0,
			"Expected non-zero port, got: {}",
			server.addr.port()
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_test_server_responds_to_request() {
		// Arrange
		let handler: Arc<dyn Handler> = Arc::new(BasicHandler);
		let server = TestServer::builder()
			.handler(handler)
			.build()
			.await
			.expect("Failed to build TestServer");
		let client = reqwest::Client::new();

		// Act
		let response = client.get(&server.url).send().await;

		// Assert
		assert!(response.is_ok(), "Expected GET request to succeed");
		let resp = response.unwrap();
		assert_eq!(resp.status(), reqwest::StatusCode::OK);
	}

	#[rstest]
	fn test_http_client_fixture() {
		// Arrange & Act
		let client = http_client();

		// Assert
		// Verify client was created successfully by making a type assertion
		let _: &reqwest::Client = &client;
	}

	#[rstest]
	#[tokio::test]
	async fn test_test_server_shutdown_timeout() {
		// Arrange
		let handler: Arc<dyn Handler> = Arc::new(BasicHandler);
		let custom_timeout = Duration::from_secs(10);

		// Act
		let result = TestServer::builder()
			.handler(handler)
			.shutdown_timeout(custom_timeout)
			.build()
			.await;

		// Assert
		assert!(
			result.is_ok(),
			"Expected TestServer with custom shutdown timeout to build successfully"
		);
	}

	#[rstest]
	#[tokio::test]
	async fn test_wait_for_server_ready() {
		// Arrange
		let listener = TcpListener::bind("127.0.0.1:0")
			.await
			.expect("Failed to bind listener");
		let addr = listener.local_addr().expect("Failed to get local addr");

		// Act
		let result = wait_for_server_ready(addr).await;

		// Assert
		assert!(
			result.is_ok(),
			"Expected wait_for_server_ready to succeed for a bound address"
		);
	}
}