Files
ImageApi/src/testhelpers.rs
Cameron Cordes 69fe307516
Some checks failed
Core Repos/ImageApi/pipeline/pr-master There was a failure building this commit
Update to Actix 4
2022-03-01 20:38:41 -05:00

82 lines
1.9 KiB
Rust

use actix_web::body::MessageBody;
use actix_web::{body::BoxBody, HttpResponse};
use serde::de::DeserializeOwned;
use crate::database::{models::User, UserDao};
use std::cell::RefCell;
use std::option::Option;
pub struct TestUserDao {
pub user_map: RefCell<Vec<User>>,
}
impl TestUserDao {
pub fn new() -> Self {
Self {
user_map: RefCell::new(Vec::new()),
}
}
}
impl UserDao for TestUserDao {
fn create_user(&self, username: &str, password: &str) -> Option<User> {
let u = User {
id: (self.user_map.borrow().len() + 1) as i32,
username: username.to_string(),
password: password.to_string(),
};
self.user_map.borrow_mut().push(u.clone());
Some(u)
}
fn get_user(&self, user: &str, pass: &str) -> Option<User> {
match self
.user_map
.borrow()
.iter()
.find(|&u| u.username == user && u.password == pass)
{
Some(u) => {
let copy = (*u).clone();
Some(copy)
}
None => None,
}
}
fn user_exists(&self, user: &str) -> bool {
self.user_map
.borrow()
.iter()
.find(|&u| u.username == user)
.is_some()
}
}
pub trait BodyReader {
fn read_to_str(self) -> String;
}
impl BodyReader for HttpResponse<BoxBody> {
fn read_to_str(self) -> String {
let body = self.into_body().try_into_bytes().unwrap();
std::str::from_utf8(&body).unwrap().to_string()
}
}
pub trait TypedBodyReader<T>
where
T: DeserializeOwned,
{
fn read_body(self) -> T;
}
impl<T: DeserializeOwned> TypedBodyReader<T> for HttpResponse<BoxBody> {
fn read_body(self) -> T {
let body = self.read_to_str();
serde_json::from_value(serde_json::Value::String(body.clone())).unwrap()
}
}