Browse Source

Move FormatMsg to routes and add unit tests

admin-impl
Kevin Hoerr 1 year ago
parent
commit
4117f797ce
Signed by: kjhoerr GPG Key ID: 78E4BD33ACC22C86
6 changed files with 133 additions and 46 deletions
  1. +0
    -2
      .travis.yml
  2. +2
    -0
      src/main.rs
  3. +0
    -37
      src/messages/format_msg.rs
  4. +0
    -2
      src/messages/mod.rs
  5. +124
    -0
      src/routes/format_msg.rs
  6. +7
    -5
      src/routes/mod.rs

+ 0
- 2
.travis.yml View File

@ -15,8 +15,6 @@ before_cache:
if [[ "$TRAVIS_RUST_VERSION" == "stable" ]]; then
cargo install -f cargo-tarpaulin
fi
before_script:
- export PATH="$PATH:~/.cargo/bin"
script:
- cargo build --verbose --all
- cargo test --verbose --all


+ 2
- 0
src/main.rs View File

@ -21,6 +21,7 @@ use diesel::prelude::*;
use dotenv::dotenv;
use std::{env, io::Error};
#[cfg_attr(tarpaulin, skip)]
fn main() {
if let Err(ref e) = run() {
error!("error: {}", e);
@ -30,6 +31,7 @@ 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");


+ 0
- 37
src/messages/format_msg.rs View File

@ -1,37 +0,0 @@
use actix_web::{http::StatusCode, Error, HttpRequest, HttpResponse, Responder};
use serde::Serialize;
pub struct FormatMsg<T> {
pub message: T,
pub code: StatusCode,
}
impl<T> FormatMsg<T> {
/// Deconstruct to an inner value
pub fn into_inner(self) -> T {
self.message
}
pub fn ok(message: T) -> Self {
FormatMsg {
message: message,
code: StatusCode::OK,
}
}
}
impl<T: Serialize> Responder for FormatMsg<T> {
type Error = Error;
type Future = Result<HttpResponse, Error>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
let body = match serde_json::to_string(&self.message) {
Ok(body) => body,
Err(e) => return Err(e.into()),
};
Ok(HttpResponse::build(self.code)
.content_type("application/json")
.body(body))
}
}

+ 0
- 2
src/messages/mod.rs View File

@ -1,10 +1,8 @@
use std::marker::Sized;
pub mod format_msg;
pub mod callback;
pub mod not_understood;
pub use self::format_msg::FormatMsg;
pub use self::callback::Callback;
pub use self::not_understood::NotUnderstood;


+ 124
- 0
src/routes/format_msg.rs View File

@ -0,0 +1,124 @@
use actix_web::{http::StatusCode, Error, HttpRequest, HttpResponse, Responder};
use serde::Serialize;
pub struct FormatMsg<T> {
pub message: T,
pub code: StatusCode,
}
impl<T> FormatMsg<T> {
/// Deconstruct to an inner value
pub fn into_inner(self) -> T {
self.message
}
pub fn ok(message: T) -> Self {
FormatMsg {
message: message,
code: StatusCode::OK,
}
}
}
impl<T: Serialize> Responder for FormatMsg<T> {
type Error = Error;
type Future = Result<HttpResponse, Error>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
let body = match serde_json::to_string(&self.message) {
Ok(body) => body,
Err(e) => return Err(e.into()),
};
Ok(HttpResponse::build(self.code)
.content_type("application/json")
.body(body))
}
}
#[cfg(test)]
mod tests {
use super::*;
use routes::*;
use routes::tests::*;
use serde::ser::{Error, Serializer};
#[test]
fn test_into_inner() {
// Arrange
let msg = NotUnderstood {path: vec![]};
let msg_ref = msg.clone();
let formatted = FormatMsg {
message: msg.as_outgoing(),
code: StatusCode::OK,
};
// Act
let result = formatted.into_inner();
// Assert
assert_eq!(result.result_type, "NOT_UNDERSTOOD");
assert_eq!(result.content, msg_ref);
}
#[test]
fn test_ok() {
// Arrange
let msg = NotUnderstood {path: vec![]};
let msg_ref = msg.clone();
// Act
let result = FormatMsg::ok(msg);
// Assert
assert_eq!(result.message, msg_ref);
assert_eq!(result.code, StatusCode::OK);
}
#[test]
fn test_responder() {
// Arrange
let msg = NotUnderstood {path: vec![]};
let msg_ref = msg.clone();
let formatted = FormatMsg {
message: msg,
code: StatusCode::NOT_FOUND,
};
let request = gen_request("/api/404", None);
// Act
let result = &formatted.respond_to(&request).unwrap();
// Assert
assert_eq!(result.status(), StatusCode::NOT_FOUND);
assert_eq!(result.headers().get("content-type").unwrap(), "application/json");
let content = get_message::<NotUnderstood>(result);
assert_eq!(content, msg_ref);
}
struct InvalidMessage {}
impl Serialize for InvalidMessage {
fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error> where S: Serializer {
Err(Error::custom("oops".to_string()))
}
}
#[test]
fn test_responder_serde_error() {
// Arrange
let msg = InvalidMessage {};
let formatted = FormatMsg {
message: msg,
code: StatusCode::NOT_FOUND,
};
let request = gen_request("/api/404", None);
// Act
let result = formatted.respond_to(&request);
// Assert
assert!(result.is_err());
}
}

+ 7
- 5
src/routes/mod.rs View File

@ -3,9 +3,11 @@ use actix_web::http::StatusCode;
use messages::*;
use std::collections::HashMap;
pub mod format_msg;
mod callback;
mod not_understood;
pub use self::format_msg::FormatMsg;
use self::callback::callback;
use self::not_understood::not_understood;
@ -32,7 +34,7 @@ mod tests {
use super::*;
use actix_web::{http::Method, test::TestRequest};
use actix_web::{App, dev::Service, test::{block_on, init_service}};
use actix_web::dev::{Body, ServiceResponse};
use actix_web::{HttpResponse, dev::Body};
use serde::Deserialize;
use std::str;
@ -49,7 +51,7 @@ mod tests {
// Assert
assert_eq!(resp.status(), StatusCode::OK);
let content = get_message::<OutgoingMsg<Callback>>(resp);
let content = get_message::<OutgoingMsg<Callback>>(resp.response());
assert_eq!(content.result_type, "CALLBACK");
assert_eq!(content.content.path, vec!["api", "callback"]);
}
@ -67,7 +69,7 @@ mod tests {
// Assert
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let content = get_message::<OutgoingMsg<NotUnderstood>>(resp);
let content = get_message::<OutgoingMsg<NotUnderstood>>(resp.response());
assert_eq!(content.result_type, "NOT_UNDERSTOOD");
assert_eq!(content.content.path, vec!["api", "404"]);
}
@ -137,8 +139,8 @@ mod tests {
Query::from_query(&query_str).unwrap()
}
fn get_message<'a, T: Deserialize<'a>>(response: &'a ServiceResponse) -> T {
let body = response.response().body().as_ref().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) => {


Loading…
Cancel
Save