From 4e8f8d0b936aa9201a39bab601a0029d6f78490f Mon Sep 17 00:00:00 2001 From: Tommaso Allevi Date: Wed, 13 Nov 2019 18:20:24 +0100 Subject: [PATCH] Add tests in examples (#185) * Add test in json example * Add test in hello world example * Remove extern crate --- hello-world/src/main.rs | 29 +++++++++++++++++++++++++++++ json/src/main.rs | 33 ++++++++++++++++++++++++++++++--- 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/hello-world/src/main.rs b/hello-world/src/main.rs index ac294063..b671ff0a 100644 --- a/hello-world/src/main.rs +++ b/hello-world/src/main.rs @@ -19,3 +19,32 @@ fn main() -> std::io::Result<()> { .bind("127.0.0.1:8080")? .run() } + +#[cfg(test)] +mod tests { + use super::*; + use actix_web::dev::Service; + use actix_web::{test, web, App, http, Error}; + + #[test] + fn test_index() -> Result<(), Error> { + let app = App::new().route("/", web::get().to(index)); + let mut app = test::init_service(app); + + let req = test::TestRequest::get() + .uri("/") + .to_request(); + let resp = test::block_on(app.call(req)).unwrap(); + + assert_eq!(resp.status(), http::StatusCode::OK); + + let response_body = match resp.response().body().as_ref() { + Some(actix_web::body::Body::Bytes(bytes)) => bytes, + _ => panic!("Response error"), + }; + + assert_eq!(response_body, r##"Hello world!"##); + + Ok(()) + } +} diff --git a/json/src/main.rs b/json/src/main.rs index 86f2a242..293cf5e7 100644 --- a/json/src/main.rs +++ b/json/src/main.rs @@ -1,6 +1,3 @@ -#[macro_use] -extern crate json; - use actix_web::{ error, middleware, web, App, Error, HttpRequest, HttpResponse, HttpServer, }; @@ -99,3 +96,33 @@ fn main() -> std::io::Result<()> { .bind("127.0.0.1:8080")? .run() } + +#[cfg(test)] +mod tests { + use super::*; + use actix_web::dev::Service; + use actix_web::{test, web, App, http}; + + #[test] + fn test_index() -> Result<(), Error> { + let app = App::new().route("/", web::post().to(index)); + let mut app = test::init_service(app); + + let req = test::TestRequest::post() + .uri("/") + .set_json(&MyObj { name: "my-name".to_owned(), number: 43 }) + .to_request(); + let resp = test::block_on(app.call(req)).unwrap(); + + assert_eq!(resp.status(), http::StatusCode::OK); + + let response_body = match resp.response().body().as_ref() { + Some(actix_web::body::Body::Bytes(bytes)) => bytes, + _ => panic!("Response error"), + }; + + assert_eq!(response_body, r##"{"name":"my-name","number":43}"##); + + Ok(()) + } +}