diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/main.rs | 46 | ||||
| -rw-r--r-- | src/routes/callback.rs | 20 | ||||
| -rw-r--r-- | src/routes/format_msg.rs | 23 | ||||
| -rw-r--r-- | src/routes/mod.rs | 62 | ||||
| -rw-r--r-- | src/routes/not_understood.rs | 14 |
5 files changed, 87 insertions, 78 deletions
diff --git a/src/main.rs b/src/main.rs index 10b3cc7..5462870 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,16 +8,18 @@ pub mod routes; #[macro_use] pub mod schema; -use actix_rt; -use actix_web::{middleware, App, HttpServer}; +use actix_web::{middleware, web, App, HttpServer}; use diesel::pg::PgConnection; -use diesel::prelude::*; -use dotenv::dotenv; +use diesel::r2d2; use std::{env, io::Error}; -#[cfg_attr(tarpaulin, skip)] -fn main() { - if let Err(ref e) = run() { +/// Short-hand for the database pool type to use throughout the app. +type DbPool = r2d2::Pool<r2d2::ConnectionManager<PgConnection>>; + +#[cfg(not(tarpaulin_include))] +#[actix_web::main] +async fn main() { + if let Err(ref e) = run().await { error!("error: {}", e); ::std::process::exit(1); @@ -25,27 +27,31 @@ fn main() { } // Run start-up for the server and dependencies -#[cfg_attr(tarpaulin, skip)] -fn run() -> Result<(), Error> { - dotenv().ok(); - let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); +#[cfg(not(tarpaulin_include))] +async fn run() -> Result<(), Error> { + dotenvy::dotenv().ok(); let bind_address = env::var("BIND_ADDRESS").expect("BIND_ADDRESS must be set"); env_logger::init(); - let sys = actix_rt::System::new("august-offensive"); + let pool = init_db_pool(); - PgConnection::establish(&db_url).expect(&format!("Error connecting to {}", db_url)); - - HttpServer::new(|| { + info!("Started http server: {}", bind_address); + HttpServer::new(move || { App::new() + .app_data(web::Data::new(pool.clone())) .wrap(middleware::Logger::default()) .service(routes::get_scope()) }) .bind(&bind_address)? - .start(); - - info!("Started http server: {}", bind_address); + .run() + .await +} - sys.run()?; - Ok(()) +#[cfg(not(tarpaulin_include))] +fn init_db_pool() -> DbPool { + let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); + let manager = r2d2::ConnectionManager::<PgConnection>::new(db_url); + r2d2::Pool::builder() + .build(manager) + .expect("Database URL is not valid") } diff --git a/src/routes/callback.rs b/src/routes/callback.rs index 8c07166..99313f3 100644 --- a/src/routes/callback.rs +++ b/src/routes/callback.rs @@ -1,7 +1,7 @@ use crate::routes::*; // Sends Callback message with information from HttpRequest. -pub fn callback(req: HttpRequest, query: Query<HashMap<String, String>>) -> JsonMessage<Callback> { +pub async fn callback(req: HttpRequest, query: Query<HashMap<String, String>>) -> JsonMessage<Callback> { let path = req.path(); let method = req.method().as_str(); @@ -20,8 +20,8 @@ mod tests { use crate::routes::tests::*; use actix_web::http::Method; - #[test] - fn test_callback_get() { + #[actix_rt::test] + async fn test_callback_get() { // Arrange let uri = "/api/phpmyadmin/index.rs"; let req = gen_request(uri, None); @@ -32,7 +32,7 @@ mod tests { let query = gen_query(&ref_map); // Act - let result = callback(req, query); + let result = callback(req, query).await; // Assert assert!(result.is_ok()); @@ -44,8 +44,8 @@ mod tests { assert_eq!(val.content.content, ref_map); } - #[test] - fn test_callback_post() { + #[actix_rt::test] + async fn test_callback_post() { // Arrange let uri = "/api/phpmyadmin/index.rs"; let req = gen_request(uri, Some(Method::POST)); @@ -56,7 +56,7 @@ mod tests { let query = gen_query(&ref_map); // Act - let result = callback(req, query); + let result = callback(req, query).await; // Assert assert!(result.is_ok()); @@ -68,15 +68,15 @@ mod tests { assert_eq!(val.content.content, ref_map); } - #[test] - fn test_callback_blank() { + #[actix_rt::test] + async fn test_callback_blank() { // Arrange let uri = "/"; let req = gen_request(uri, None); let query = Query::from_query("").unwrap(); // Act - let result = callback(req, query); + let result = callback(req, query).await; // Assert assert!(result.is_ok()); diff --git a/src/routes/format_msg.rs b/src/routes/format_msg.rs index 83dbd8f..22f0691 100644 --- a/src/routes/format_msg.rs +++ b/src/routes/format_msg.rs @@ -1,4 +1,4 @@ -use actix_web::{http::StatusCode, Error, HttpRequest, HttpResponse, Responder}; +use actix_web::{body::BoxBody, http::StatusCode, HttpRequest, HttpResponse, Responder}; use serde::Serialize; pub struct FormatMsg<T> { @@ -21,18 +21,17 @@ impl<T> FormatMsg<T> { } impl<T: Serialize> Responder for FormatMsg<T> { - type Error = Error; - type Future = Result<HttpResponse, Error>; + type Body = BoxBody; - fn respond_to(self, _: &HttpRequest) -> Self::Future { + fn respond_to(self, _: &HttpRequest) -> HttpResponse<BoxBody> { let body = match serde_json::to_string(&self.message) { - Ok(body) => body, - Err(e) => return Err(e.into()), + Ok(serstr) => serstr, + Err(e) => return HttpResponse::from_error(e), }; - Ok(HttpResponse::build(self.code) + HttpResponse::build(self.code) .content_type("application/json") - .body(body)) + .body(body) } } @@ -87,13 +86,15 @@ mod tests { let request = gen_request("/api/404", None); // Act - let result = &formatted.respond_to(&request).unwrap(); + let result = formatted.respond_to(&request); // Assert assert_eq!(result.status(), StatusCode::NOT_FOUND); assert_eq!(result.headers().get("content-type").unwrap(), "application/json"); - let content = get_message::<NotUnderstood>(result); + let resp = get_message::<NotUnderstood>(result); + assert!(resp.is_ok()); + let content = resp.unwrap(); assert_eq!(content, msg_ref); } @@ -119,6 +120,6 @@ mod tests { let result = formatted.respond_to(&request); // Assert - assert!(result.is_err()); + assert!(result.error().is_some()); } }
\ No newline at end of file diff --git a/src/routes/mod.rs b/src/routes/mod.rs index ac11ad9..00ebe72 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -31,58 +31,66 @@ fn destruct_path(path: &str) -> Vec<String> { #[cfg(test)] mod tests { + use super::*; + use actix_web::body::MessageBody; use actix_web::{http::Method, test::TestRequest}; - use actix_web::{App, dev::Service, test::{block_on, init_service}}; - use actix_web::{HttpResponse, dev::Body}; - use serde::Deserialize; - use std::str; + use actix_web::{App, test::init_service, dev::Service}; + use actix_web::HttpResponse; + use serde::de::DeserializeOwned; - #[test] - fn test_get_scope_callback() { + #[actix_rt::test] + async fn test_get_scope_callback() { // Arrange let req = TestRequest::with_uri("/api/callback").to_request(); let scope = get_scope(); - let mut srv = init_service(App::new().service(scope)); + let srv = init_service(App::new().service(scope)).await; // Act - let resp = &block_on(srv.call(req)).unwrap(); + let result = srv.call(req).await; + let resp = result.expect("Error found for callback response").into_parts().1; // Assert assert_eq!(resp.status(), StatusCode::OK); - let content = get_message::<OutgoingMsg<Callback>>(resp.response()); + let resp = get_message::<OutgoingMsg<Callback>>(resp); + assert!(resp.is_ok()); + let content = resp.unwrap(); assert_eq!(content.result_type, "CALLBACK"); assert_eq!(content.content.path, vec!["api", "callback"]); } - #[test] - fn test_get_scope_not_understood() { + #[actix_rt::test] + async fn test_get_scope_not_understood() { // Arrange let req = TestRequest::with_uri("/api/404").to_request(); let scope = get_scope(); - let mut srv = init_service(App::new().service(scope)); + let srv = init_service(App::new().service(scope)).await; // Act - let resp = &block_on(srv.call(req)).unwrap(); + let result = srv.call(req).await; + let resp = result.expect("Error found for callback response").into_parts().1; // Assert assert_eq!(resp.status(), StatusCode::NOT_FOUND); - let content = get_message::<OutgoingMsg<NotUnderstood>>(resp.response()); + let resp = get_message::<OutgoingMsg<NotUnderstood>>(resp); + assert!(resp.is_ok()); + let content = resp.unwrap(); assert_eq!(content.result_type, "NOT_UNDERSTOOD"); assert_eq!(content.content.path, vec!["api", "404"]); } - #[test] - fn test_get_scope_blank() { + #[actix_rt::test] + async fn test_get_scope_blank() { // Arrange let req = TestRequest::with_uri("/").to_request(); let scope = get_scope(); - let mut srv = init_service(App::new().service(scope)); + let srv = init_service(App::new().service(scope)).await; // Act - let resp = block_on(srv.call(req)).unwrap(); + let result = srv.call(req).await; + let resp = result.expect("Error found for callback response"); // Assert assert_eq!(resp.status(), StatusCode::NOT_FOUND); @@ -139,17 +147,11 @@ mod tests { Query::from_query(&query_str).unwrap() } - pub fn get_message<'a, T: Deserialize<'a>>(response: &'a HttpResponse) -> T { - let body = response.body().as_ref().unwrap(); - let mut array = &[b'0';0][..]; - match body { - Body::Bytes(b) => { - array = b.as_ref(); - }, - _ => {}, - }; - - let van = str::from_utf8(array).unwrap(); - serde_json::from_str(van).unwrap() + pub fn get_message<'a, T: DeserializeOwned>(response: HttpResponse) -> Result<T, serde_json::Error> { + let body = response.into_body(); + let bytes = &body.try_into_bytes().unwrap(); + + let van = std::str::from_utf8(bytes).unwrap(); + serde_json::from_str(van) } } diff --git a/src/routes/not_understood.rs b/src/routes/not_understood.rs index 7ca5ed2..535fafe 100644 --- a/src/routes/not_understood.rs +++ b/src/routes/not_understood.rs @@ -1,7 +1,7 @@ use crate::routes::*; // Sends a default response message when requested an undefined resource. -pub fn not_understood(req: HttpRequest) -> JsonMessage<NotUnderstood> { +pub async fn not_understood(req: HttpRequest) -> JsonMessage<NotUnderstood> { let message = NotUnderstood { path: destruct_path(req.path()), }; @@ -17,14 +17,14 @@ mod tests { use super::*; use crate::routes::tests::*; - #[test] - fn test_not_understood() { + #[actix_rt::test] + async fn test_not_understood() { // Arrange let uri = "/api/phpmyadmin/index.rs"; let req = gen_request(uri, None); // Act - let result = not_understood(req); + let result = not_understood(req).await; // Assert assert!(result.is_ok()); @@ -34,14 +34,14 @@ mod tests { assert_eq!(val.content.path, vec!["api", "phpmyadmin", "index.rs"]); } - #[test] - fn test_not_understood_blank() { + #[actix_rt::test] + async fn test_not_understood_blank() { // Arrange let uri = "/"; let req = gen_request(uri, None); // Act - let result = not_understood(req); + let result = not_understood(req).await; // Assert assert!(result.is_ok()); |
