diff --git a/src/handler.rs b/src/handler.rs index 36035e8..c4fbe8a 100644 --- a/src/handler.rs +++ b/src/handler.rs @@ -12,7 +12,8 @@ pub struct HandlerBuilder { path: String, method: Method, headers: HeaderMap, - status_code: StatusCode + status_code: StatusCode, + response: Vec, } #[allow(dead_code)] @@ -22,7 +23,8 @@ impl HandlerBuilder { path: String::from(path), method: Method::GET, headers: HeaderMap::new(), - status_code: StatusCode::INTERNAL_SERVER_ERROR + status_code: StatusCode::INTERNAL_SERVER_ERROR, + response: Vec::new(), } } @@ -41,16 +43,33 @@ impl HandlerBuilder { self } + pub fn response(mut self, response: Vec) -> HandlerBuilder { + self.response = response; + self + } + pub fn build(self) -> HandlerCallback { - let Self { path, method, status_code, headers } = self; + let Self { + path, + method, + status_code, + headers, + response, + } = self; Arc::new(move |req: Request| { let cloned_path = path.clone(); let cloned_method = method.clone(); let cloned_headers = headers.clone(); + let cloned_response = response.clone(); Box::pin(async move { - if req.uri().path().eq(cloned_path.as_str()) && req.method().eq(&cloned_method) - && Self::contains_headers(req.headers(), &cloned_headers) { - Ok(hyper::Response::builder().status(status_code).body(Body::empty()).unwrap()) + if req.uri().path().eq(cloned_path.as_str()) + && req.method().eq(&cloned_method) + && Self::contains_headers(req.headers(), &cloned_headers) + { + Ok(hyper::Response::builder() + .status(status_code) + .body(cloned_response.into()) + .unwrap()) } else { Ok(hyper::Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(Body::empty()).unwrap()) } diff --git a/src/lib.rs b/src/lib.rs index 3023f27..6cb9e69 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -103,10 +103,10 @@ impl AsyncTestContext for HttpTestContext { #[cfg(test)] mod test { - use hyper::{StatusCode, Method, Request, Body, HeaderMap, Client}; - use crate::{HttpTestContext}; - use test_context::test_context; use crate::handler::HandlerBuilder; + use crate::HttpTestContext; + use hyper::{body::HttpBody, Body, Client, HeaderMap, Method, Request, StatusCode}; + use test_context::test_context; #[test_context(HttpTestContext)] #[tokio::test] @@ -153,6 +153,23 @@ mod test { assert_eq!(200, resp.status()); } + #[test_context(HttpTestContext)] + #[tokio::test] + async fn test_get_with_response(ctx: &mut HttpTestContext) { + ctx.add( + HandlerBuilder::new("/response") + .status_code(StatusCode::OK) + .response("Hello test".into()) + .build(), + ); + + let resp = Client::new().get(ctx.uri("/response")).await.unwrap(); + assert_eq!(200, resp.status()); + + let body = resp.into_body().data().await.unwrap().unwrap(); + assert_eq!("Hello test", body); + } + #[test_context(HttpTestContext)] #[tokio::test] async fn test_post_endpoint(ctx: &mut HttpTestContext) {