reinhardt-dispatch 0.3.18

URL dispatcher and request routing for Reinhardt framework
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
//! Base HTTP request handler
//!
//! This module provides the base handler for processing HTTP requests,
//! similar to Django's `django.core.handlers.base.BaseHandler`.

use hyper::StatusCode;
use reinhardt_core::signals::{
	RequestFinishedEvent, RequestStartedEvent, request_finished, request_started,
};
use reinhardt_http::Handler;
use reinhardt_http::{Request, Response};
use reinhardt_urls::routers::DefaultRouter;
use std::sync::Arc;
use tracing::{debug, error, trace, warn};

use crate::{DispatchError, exception::exception_to_dispatch_error};

/// Base HTTP request handler
///
/// Handles the complete request lifecycle including URL resolution,
/// view execution, and signal emission.
pub struct BaseHandler {
	/// Whether the handler operates in async mode.
	///
	/// This flag mirrors Django's `BaseHandler._is_async` and is read by
	/// `Dispatcher` to choose between sync and async code paths. When
	/// `false`, async dispatch still works but callers may opt for a
	/// blocking wrapper.
	// Allow dead_code: read via is_async() accessor; behavioral branching planned
	#[allow(dead_code)]
	is_async: bool,
	router: Option<Arc<DefaultRouter>>,
}

impl BaseHandler {
	/// Create a new base handler
	pub fn new() -> Self {
		Self {
			is_async: true,
			router: None,
		}
	}

	/// Create a handler with a router
	///
	/// # Examples
	///
	/// ```
	/// use reinhardt_dispatch::BaseHandler;
	/// use reinhardt_urls::routers::DefaultRouter;
	/// use std::sync::Arc;
	///
	/// let router = DefaultRouter::new();
	/// let handler = BaseHandler::with_router(Arc::new(router));
	/// assert!(handler.is_async());
	/// ```
	pub fn with_router(router: Arc<DefaultRouter>) -> Self {
		Self {
			is_async: true,
			router: Some(router),
		}
	}

	/// Handle an HTTP request
	///
	/// This is the main entry point for request processing. It:
	/// 1. Emits `request_started` signal
	/// 2. Resolves URL and dispatches to view
	/// 3. Emits `request_finished` signal
	/// 4. Converts an unmatched route into a 404 response
	pub async fn handle_request(
		&self,
		request: Request,
	) -> std::result::Result<Response, DispatchError> {
		match self.handle_request_with_errors(request).await {
			Err(DispatchError::UrlResolution(_)) => Ok(Response::new(StatusCode::NOT_FOUND)),
			response => response,
		}
	}

	/// Handle a request while preserving routing and view failures for an outer
	/// exception handler.
	async fn handle_request_with_errors(
		&self,
		request: Request,
	) -> std::result::Result<Response, DispatchError> {
		self.handle_request_with_framework_errors(request)
			.await
			.map_err(exception_to_dispatch_error)
	}

	/// Handle a request while preserving the original framework error variants.
	///
	/// The HTTP exception-handler adapter uses this path so an endpoint's
	/// authentication, authorization, validation, or conflict error reaches the
	/// application handler without being reclassified as a generic view error.
	async fn handle_request_with_framework_errors(
		&self,
		request: Request,
	) -> reinhardt_core::exception::Result<Response> {
		trace!("Handling request: {:?}", request.uri);

		// Emit request_started signal
		let event = RequestStartedEvent::new();
		if let Err(e) = request_started().send(event).await {
			warn!("Failed to send request_started signal: {}", e);
		}

		// Get response with router
		let response = Self::get_response_async(request, self.router.as_ref()).await;

		// Emit request_finished signal
		let event = RequestFinishedEvent::new();
		if let Err(e) = request_finished().send(event).await {
			warn!("Failed to send request_finished signal: {}", e);
		}

		response
	}

	/// Get response for a request (async version) with URL resolution
	///
	/// This is the core request processing logic that:
	/// - Resolves the URL using the router
	/// - Dispatches to the matched handler
	/// - Returns a routing error if no route matches
	/// - Returns an error for handler failures
	async fn get_response_async(
		request: Request,
		router: Option<&Arc<DefaultRouter>>,
	) -> reinhardt_core::exception::Result<Response> {
		debug!("Getting response for: {}", request.uri.path());

		// URL resolution with router
		if let Some(router) = router {
			trace!("Attempting to route request through router");

			// Use the router to handle the request
			match router.handle(request).await {
				Ok(response) => {
					trace!("Route handled successfully");
					return Ok(response);
				}
				Err(reinhardt_core::exception::Error::NotFound(msg)) => {
					debug!("No route matched: {}", msg);
					return Err(reinhardt_core::exception::Error::NotFound(msg));
				}
				Err(e) => {
					error!("Handler error: {}", e);
					// Return the original error so an installed exception handler can
					// preserve its status and variant.
					return Err(e);
				}
			}
		}

		// Fallback: router not configured, so no routes can match.
		debug!("No router configured, returning a URL resolution error");
		Err(reinhardt_core::exception::Error::NotFound(
			"No router configured".to_owned(),
		))
	}

	/// Process an exception and convert it to a response.
	///
	/// Error details are logged server-side but not included in the response
	/// body to prevent information disclosure.
	pub async fn handle_exception(&self, _request: &Request, error: DispatchError) -> Response {
		error!("Handling exception: {}", error);

		crate::build_error_response(StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error")
	}

	/// Check if handler is configured for async mode
	pub fn is_async(&self) -> bool {
		self.is_async
	}

	/// Set async mode for the handler
	pub fn set_async(&mut self, is_async: bool) {
		self.is_async = is_async;
	}
}

impl Default for BaseHandler {
	fn default() -> Self {
		Self::new()
	}
}

#[async_trait::async_trait]
impl Handler for BaseHandler {
	async fn handle(&self, request: Request) -> reinhardt_core::exception::Result<Response> {
		let has_exception_handler = request
			.extensions
			.contains::<Arc<dyn reinhardt_http::ExceptionHandler>>();
		if has_exception_handler {
			return self.handle_request_with_framework_errors(request).await;
		}
		match self.handle_request_with_errors(request).await {
			Ok(response) => Ok(response),
			Err(DispatchError::UrlResolution(_)) => Ok(Response::new(StatusCode::NOT_FOUND)),
			Err(e) => {
				// Log the detailed error server-side; return generic message to client
				error!("Handler error in BaseHandler::handle: {}", e);
				Ok(crate::build_error_response(
					StatusCode::INTERNAL_SERVER_ERROR,
					"Internal Server Error",
				))
			}
		}
	}
}

#[cfg(test)]
mod tests {
	use std::sync::Mutex;

	use super::*;
	use async_trait::async_trait;
	use bytes::Bytes;
	use hyper::{HeaderMap, Method, Version};
	use reinhardt_http::{ExceptionHandler, ExceptionHandlingHandler, Middleware, MiddlewareChain};
	use reinhardt_urls::routers::{DefaultRouter, Router, path};
	use rstest::rstest;

	// Test handler for routing tests
	struct TestHandler {
		response_body: String,
	}

	#[async_trait]
	impl Handler for TestHandler {
		async fn handle(&self, _req: Request) -> reinhardt_core::exception::Result<Response> {
			Ok(Response::ok().with_body(self.response_body.clone()))
		}
	}

	#[tokio::test]
	async fn test_base_handler_new() {
		let handler = BaseHandler::new();
		assert!(handler.is_async());
	}

	#[tokio::test]
	async fn test_base_handler_handle_request() {
		let handler = BaseHandler::new();
		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = handler.handle_request(request).await;
		let resp = response.unwrap();
		// Handler without router should return 404 Not Found
		assert_eq!(resp.status, StatusCode::NOT_FOUND);
	}

	#[tokio::test]
	async fn test_base_handler_handle_exception() {
		let handler = BaseHandler::new();
		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let error = DispatchError::View("Test error".to_string());

		let response = handler.handle_exception(&request, error).await;
		assert_eq!(response.status, StatusCode::INTERNAL_SERVER_ERROR);
	}

	// ==========================================================================
	// Information Disclosure Prevention Tests (#439)
	// ==========================================================================

	#[tokio::test]
	async fn test_handle_exception_does_not_expose_internal_details() {
		// Arrange
		let handler = BaseHandler::new();
		let request = Request::builder()
			.method(Method::GET)
			.uri("/")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let sensitive_detail = "database connection refused at postgres://admin:secret@db:5432";
		let error = DispatchError::Internal(sensitive_detail.to_string());

		// Act
		let response = handler.handle_exception(&request, error).await;

		// Assert: response must not contain the sensitive detail
		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(response.status, StatusCode::INTERNAL_SERVER_ERROR);
		assert!(!body.contains("database"));
		assert!(!body.contains("postgres"));
		assert!(!body.contains("secret"));
		assert_eq!(body, "Internal Server Error");
	}

	#[tokio::test]
	async fn test_handler_impl_does_not_expose_error_in_body() {
		// Arrange: create a handler that returns a view error with internal paths
		struct FailingHandler;

		#[async_trait]
		impl Handler for FailingHandler {
			async fn handle(&self, _req: Request) -> reinhardt_core::exception::Result<Response> {
				Err(reinhardt_core::exception::Error::Internal(
					"module::secret_handler panicked at /src/app/handlers.rs:42".to_string(),
				))
			}
		}

		let mut router = DefaultRouter::new();
		let failing = Arc::new(FailingHandler);
		let mut route = path("/fail", failing);
		route.name = Some("fail".to_string());
		router.add_route(route);
		let handler = BaseHandler::with_router(Arc::new(router));

		let request = Request::builder()
			.method(Method::GET)
			.uri("/fail")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

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

		// Assert: internal details must not leak
		let body = String::from_utf8(response.body.to_vec()).unwrap();
		assert_eq!(response.status, StatusCode::INTERNAL_SERVER_ERROR);
		assert!(!body.contains("panicked"));
		assert!(!body.contains("handlers.rs"));
		assert!(!body.contains("secret_handler"));
		assert_eq!(body, "Internal Server Error");
	}

	struct TeapotExceptionHandler;

	#[async_trait]
	impl ExceptionHandler for TeapotExceptionHandler {
		async fn handle_exception(
			&self,
			_request: &Request,
			_error: reinhardt_core::exception::Error,
		) -> Response {
			Response::new(StatusCode::IM_A_TEAPOT).with_body("teapot")
		}
	}

	struct StatusExceptionHandler;

	#[async_trait]
	impl ExceptionHandler for StatusExceptionHandler {
		async fn handle_exception(
			&self,
			_request: &Request,
			error: reinhardt_core::exception::Error,
		) -> Response {
			let status = StatusCode::from_u16(error.status_code())
				.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
			Response::new(status)
		}
	}

	#[rstest]
	#[tokio::test]
	async fn base_handler_routing_errors_reach_http_exception_handler() {
		// Arrange
		let base = Arc::new(BaseHandler::with_router(Arc::new(DefaultRouter::new())));
		let handler = ExceptionHandlingHandler::new(base, Arc::new(TeapotExceptionHandler));
		let request = Request::builder()
			.method(Method::GET)
			.uri("/missing")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

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

		// Assert
		assert_eq!(response.status, StatusCode::IM_A_TEAPOT);
		assert_eq!(response.body, Bytes::from_static(b"teapot"));
	}

	#[rstest]
	#[tokio::test]
	async fn base_handler_view_errors_reach_http_exception_handler() {
		struct FailingHandler;

		#[async_trait]
		impl Handler for FailingHandler {
			async fn handle(
				&self,
				_request: Request,
			) -> reinhardt_core::exception::Result<Response> {
				Err(reinhardt_core::exception::Error::Internal(
					"view failed".to_owned(),
				))
			}
		}

		// Arrange
		let mut router = DefaultRouter::new();
		router.add_route(path("/fail", Arc::new(FailingHandler)));
		let base = Arc::new(BaseHandler::with_router(Arc::new(router)));
		let handler = ExceptionHandlingHandler::new(base, Arc::new(TeapotExceptionHandler));
		let request = Request::builder()
			.method(Method::GET)
			.uri("/fail")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

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

		// Assert
		assert_eq!(response.status, StatusCode::IM_A_TEAPOT);
		assert_eq!(response.body, Bytes::from_static(b"teapot"));
	}

	#[rstest]
	#[tokio::test]
	async fn base_handler_preserves_endpoint_error_status_for_http_exception_handler() {
		struct AuthenticationHandler;

		#[async_trait]
		impl Handler for AuthenticationHandler {
			async fn handle(
				&self,
				_request: Request,
			) -> reinhardt_core::exception::Result<Response> {
				Err(reinhardt_core::exception::Error::Authentication(
					"credentials rejected".to_owned(),
				))
			}
		}

		// Arrange
		let mut router = DefaultRouter::new();
		router.add_route(path("/private", Arc::new(AuthenticationHandler)));
		let base = Arc::new(BaseHandler::with_router(Arc::new(router)));
		let handler = ExceptionHandlingHandler::new(base, Arc::new(StatusExceptionHandler));
		let request = Request::builder()
			.method(Method::GET)
			.uri("/private")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

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

		// Assert: the endpoint's authentication error is not reclassified as 500.
		assert_eq!(response.status, StatusCode::UNAUTHORIZED);
	}

	#[rstest]
	#[tokio::test]
	async fn base_handler_exception_handler_receives_resolved_path_params() {
		struct FailingHandler;

		#[async_trait]
		impl Handler for FailingHandler {
			async fn handle(
				&self,
				_request: Request,
			) -> reinhardt_core::exception::Result<Response> {
				Err(reinhardt_core::exception::Error::Internal(
					"view failed".to_owned(),
				))
			}
		}

		struct PassthroughMiddleware;

		#[async_trait]
		impl Middleware for PassthroughMiddleware {
			async fn process(
				&self,
				request: Request,
				next: Arc<dyn Handler>,
			) -> reinhardt_core::exception::Result<Response> {
				next.handle(request).await
			}
		}

		struct PathParamExceptionHandler {
			observed: Arc<Mutex<Option<String>>>,
		}

		#[async_trait]
		impl ExceptionHandler for PathParamExceptionHandler {
			async fn handle_exception(
				&self,
				request: &Request,
				_error: reinhardt_core::exception::Error,
			) -> Response {
				*self.observed.lock().unwrap() = request.path_params.get("id").cloned();
				Response::new(StatusCode::IM_A_TEAPOT)
			}
		}

		// Arrange
		let observed = Arc::new(Mutex::new(None));
		let mut router = DefaultRouter::new();
		let mut route = path("/items/{id}", Arc::new(FailingHandler));
		route.name = Some("item".to_owned());
		router.add_route(route);
		let base = Arc::new(BaseHandler::with_router(Arc::new(router)));
		let handler = MiddlewareChain::new(base)
			.with_middleware(Arc::new(PassthroughMiddleware))
			.with_exception_handler(Arc::new(PathParamExceptionHandler {
				observed: Arc::clone(&observed),
			}));
		let request = Request::builder()
			.method(Method::GET)
			.uri("/items/42")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

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

		// Assert
		assert_eq!(response.status, StatusCode::IM_A_TEAPOT);
		assert_eq!(*observed.lock().unwrap(), Some("42".to_owned()));
	}

	#[rstest]
	#[tokio::test]
	async fn middleware_chain_exception_handler_refreshes_path_params_for_all_error_paths() {
		struct Endpoint {
			fails: bool,
		}

		#[async_trait]
		impl Handler for Endpoint {
			async fn handle(
				&self,
				_request: Request,
			) -> reinhardt_core::exception::Result<Response> {
				if self.fails {
					Err(reinhardt_core::exception::Error::Internal(
						"endpoint failed".to_owned(),
					))
				} else {
					Ok(Response::ok())
				}
			}
		}

		struct RecordingExceptionHandler {
			observed: Arc<Mutex<Vec<Option<String>>>>,
		}

		#[async_trait]
		impl ExceptionHandler for RecordingExceptionHandler {
			async fn handle_exception(
				&self,
				request: &Request,
				_error: reinhardt_core::exception::Error,
			) -> Response {
				self.observed
					.lock()
					.unwrap()
					.push(request.path_params.get("id").cloned());
				Response::new(StatusCode::IM_A_TEAPOT)
			}
		}

		struct PostProcessingMiddleware {
			fails: bool,
		}

		#[async_trait]
		impl Middleware for PostProcessingMiddleware {
			async fn process(
				&self,
				request: Request,
				next: Arc<dyn Handler>,
			) -> reinhardt_core::exception::Result<Response> {
				let response = next.handle(request).await?;
				if self.fails {
					Err(reinhardt_core::exception::Error::Internal(
						"middleware failed after next".to_owned(),
					))
				} else {
					Ok(response)
				}
			}
		}

		let build_base = |fails| {
			let mut router = DefaultRouter::new();
			router.add_route(path("/items/{id}", Arc::new(Endpoint { fails })));
			Arc::new(BaseHandler::with_router(Arc::new(router))) as Arc<dyn Handler>
		};
		let request = || {
			Request::builder()
				.method(Method::GET)
				.uri("/items/42")
				.version(Version::HTTP_11)
				.headers(HeaderMap::new())
				.body(Bytes::new())
				.build()
				.unwrap()
		};
		let observed = Arc::new(Mutex::new(Vec::new()));
		let exception_handler = || {
			Arc::new(RecordingExceptionHandler {
				observed: Arc::clone(&observed),
			})
		};

		// Arrange and act: the bare chain refreshes the context after routing.
		let bare =
			MiddlewareChain::new(build_base(true)).with_exception_handler(exception_handler());
		let bare_response = bare.handle(request()).await.unwrap();

		// Arrange and act: a single middleware can fail during post-processing.
		let single = MiddlewareChain::new(build_base(false))
			.with_middleware(Arc::new(PostProcessingMiddleware { fails: true }))
			.with_exception_handler(exception_handler());
		let single_response = single.handle(request()).await.unwrap();

		// Arrange and act: the composed multi-middleware path has the same contract.
		let composed = MiddlewareChain::new(build_base(false))
			.with_middleware(Arc::new(PostProcessingMiddleware { fails: true }))
			.with_middleware(Arc::new(PostProcessingMiddleware { fails: false }))
			.with_exception_handler(exception_handler());
		let composed_response = composed.handle(request()).await.unwrap();

		// Assert
		assert_eq!(bare_response.status, StatusCode::IM_A_TEAPOT);
		assert_eq!(single_response.status, StatusCode::IM_A_TEAPOT);
		assert_eq!(composed_response.status, StatusCode::IM_A_TEAPOT);
		assert_eq!(
			*observed.lock().unwrap(),
			vec![
				Some("42".to_owned()),
				Some("42".to_owned()),
				Some("42".to_owned())
			]
		);
	}

	#[test]
	fn test_base_handler_async_mode() {
		let mut handler = BaseHandler::new();
		assert!(handler.is_async());

		handler.set_async(false);
		assert!(!handler.is_async());
	}

	#[tokio::test]
	async fn test_base_handler_different_methods() {
		let handler = BaseHandler::new();

		for method in [Method::GET, Method::POST, Method::PUT, Method::DELETE] {
			let request = Request::builder()
				.method(method)
				.uri("/")
				.version(Version::HTTP_11)
				.headers(HeaderMap::new())
				.body(Bytes::new())
				.build()
				.unwrap();

			let response = handler.handle_request(request).await;
			assert!(response.is_ok());
		}
	}

	#[tokio::test]
	async fn test_base_handler_different_uris() {
		let handler = BaseHandler::new();

		for path in ["/", "/test", "/api/v1/users", "/admin/login"] {
			let request = Request::builder()
				.method(Method::GET)
				.uri(path)
				.version(Version::HTTP_11)
				.headers(HeaderMap::new())
				.body(Bytes::new())
				.build()
				.unwrap();

			let response = handler.handle_request(request).await;
			assert!(response.is_ok());
		}
	}

	#[tokio::test]
	async fn test_handler_with_router() {
		// Create a router with a test route
		let mut router = DefaultRouter::new();
		let test_handler = Arc::new(TestHandler {
			response_body: "Test response".to_string(),
		});
		let mut route = path("/test", test_handler);
		route.name = Some("test".to_string());
		router.add_route(route);

		// Create BaseHandler with router
		let handler = BaseHandler::with_router(Arc::new(router));

		// Test matching route
		let request = Request::builder()
			.method(Method::GET)
			.uri("/test")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = handler.handle_request(request).await;
		let resp = response.unwrap();
		assert_eq!(resp.status, StatusCode::OK);

		let body = String::from_utf8(resp.body.to_vec()).unwrap();
		assert_eq!(body, "Test response");
	}

	#[tokio::test]
	async fn test_handler_404_not_found() {
		// Create empty router
		let router = DefaultRouter::new();

		// Create BaseHandler with router
		let handler = BaseHandler::with_router(Arc::new(router));

		// Test non-existent route
		let request = Request::builder()
			.method(Method::GET)
			.uri("/nonexistent")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();

		let response = handler.handle_request(request).await;
		let resp = response.unwrap();
		assert_eq!(resp.status, StatusCode::NOT_FOUND);
	}

	#[tokio::test]
	async fn test_handler_multiple_routes() {
		// Create router with multiple routes
		let mut router = DefaultRouter::new();

		let hello_handler = Arc::new(TestHandler {
			response_body: "Hello".to_string(),
		});
		let mut hello_route = path("/hello", hello_handler);
		hello_route.name = Some("hello".to_string());
		router.add_route(hello_route);

		let world_handler = Arc::new(TestHandler {
			response_body: "World".to_string(),
		});
		let mut world_route = path("/world", world_handler);
		world_route.name = Some("world".to_string());
		router.add_route(world_route);

		let handler = BaseHandler::with_router(Arc::new(router));

		// Test first route
		let request = Request::builder()
			.method(Method::GET)
			.uri("/hello")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response = handler.handle_request(request).await.unwrap();
		assert_eq!(response.status, StatusCode::OK);
		assert_eq!(String::from_utf8(response.body.to_vec()).unwrap(), "Hello");

		// Test second route
		let request = Request::builder()
			.method(Method::GET)
			.uri("/world")
			.version(Version::HTTP_11)
			.headers(HeaderMap::new())
			.body(Bytes::new())
			.build()
			.unwrap();
		let response = handler.handle_request(request).await.unwrap();
		assert_eq!(response.status, StatusCode::OK);
		assert_eq!(String::from_utf8(response.body.to_vec()).unwrap(), "World");
	}
}