Fix tests

This commit is contained in:
Adrian Woźniak 2023-09-14 15:51:29 +02:00
parent c2fc9cda9b
commit 586d4f419a
6 changed files with 88 additions and 167 deletions

View File

@ -4,8 +4,6 @@ use test_setup::prelude::*;
#[cfg(test)] #[cfg(test)]
mod get_request_is_success { mod get_request_is_success {
extern crate serde_derive; extern crate serde_derive;
use super::create_app;
use super::BodyTest;
use actix_admin::prelude::*; use actix_admin::prelude::*;
use actix_web::body::to_bytes; use actix_web::body::to_bytes;
use actix_web::test; use actix_web::test;
@ -14,6 +12,8 @@ mod get_request_is_success {
use sea_orm::EntityTrait; use sea_orm::EntityTrait;
use sea_orm::PaginatorTrait; use sea_orm::PaginatorTrait;
use sea_orm::QueryOrder; use sea_orm::QueryOrder;
use super::create_app;
use super::BodyTest;
#[actix_web::test] #[actix_web::test]
async fn get_admin_index() { async fn get_admin_index() {
@ -33,17 +33,12 @@ mod get_request_is_success {
let db = super::setup_db(true).await; let db = super::setup_db(true).await;
let page = 5; let page = 5;
let page_size = 50; // Verify with default size in list.rs let page_size = 50; // Verify with default size in list.rs
let url = format!( let url = format!("/admin/{}/list?page={}&entities_per_page={}", crate::Post::get_entity_name(), page, page_size);
"/admin/{}/list?page={}&entities_per_page={}",
crate::Post::get_entity_name(),
page,
page_size
);
let entities = crate::Post::find() let entities = crate::Post::find()
.order_by_asc(crate::post::Column::Id) .order_by_asc(crate::post::Column::Id)
.paginate(&db, page_size) .paginate(&db, page_size)
.fetch_page(page - 1) .fetch_page(page-1)
.await .await
.unwrap(); .unwrap();
@ -54,12 +49,9 @@ mod get_request_is_success {
#[actix_web::test] #[actix_web::test]
async fn get_post_list_search() { async fn get_post_list_search() {
let db = super::setup_db(true).await; let db = super::setup_db(true).await;
let url = format!( let url = format!("/admin/{}/list?search=Test%20155", crate::Post::get_entity_name());
"/admin/{}/list?search=Test%20155",
crate::Post::get_entity_name()
);
test_response_contains(url.as_str(), &db, vec!["Test 155".to_string()]).await test_response_contains(url.as_str(), &db, vec!("Test 155".to_string())).await
} }
#[actix_web::test] #[actix_web::test]
@ -67,12 +59,7 @@ mod get_request_is_success {
let db = super::setup_db(true).await; let db = super::setup_db(true).await;
let search_string_encoded = "Test%2015"; let search_string_encoded = "Test%2015";
let entities_per_page = 11; let entities_per_page = 11;
let url = format!( let url = format!("/admin/{}/list?search={}&entities_per_page={}", crate::Comment::get_entity_name(), search_string_encoded, entities_per_page);
"/admin/{}/list?search={}&entities_per_page={}",
crate::Comment::get_entity_name(),
search_string_encoded,
entities_per_page
);
let mut elements_to_verify = Vec::new(); let mut elements_to_verify = Vec::new();
elements_to_verify.push("Test 15".to_string()); elements_to_verify.push("Test 15".to_string());
@ -89,12 +76,7 @@ mod get_request_is_success {
let page = 17; let page = 17;
let page_size = 20; // Verify with default size in list.rs let page_size = 20; // Verify with default size in list.rs
let url = format!( let url = format!("/admin/{}/list?page={}&entities_per_page={}", crate::Comment::get_entity_name(), page, page_size);
"/admin/{}/list?page={}&entities_per_page={}",
crate::Comment::get_entity_name(),
page,
page_size
);
let query = if page_size == 5 { let query = if page_size == 5 {
crate::Comment::find().order_by_asc(crate::comment::Column::Id) crate::Comment::find().order_by_asc(crate::comment::Column::Id)
@ -104,7 +86,7 @@ mod get_request_is_success {
let entities = query let entities = query
.paginate(&db, page_size) .paginate(&db, page_size)
.fetch_page(page - 1) .fetch_page(page-1)
.await .await
.unwrap(); .unwrap();
@ -137,7 +119,11 @@ mod get_request_is_success {
async fn get_comment_show() { async fn get_comment_show() {
let db = super::setup_db(true).await; let db = super::setup_db(true).await;
let url = format!("/admin/{}/show/{}", crate::Comment::get_entity_name(), 1); let url = format!(
"/admin/{}/show/{}",
crate::Comment::get_entity_name(),
1
);
test_get_is_success(url.as_str(), &db).await test_get_is_success(url.as_str(), &db).await
} }
@ -145,38 +131,39 @@ mod get_request_is_success {
async fn get_post_show() { async fn get_post_show() {
let db = super::setup_db(true).await; let db = super::setup_db(true).await;
let url = format!("/admin/{}/show/{}", crate::Comment::get_entity_name(), 1); let url = format!(
"/admin/{}/show/{}",
crate::Comment::get_entity_name(),
1
);
test_get_is_success(url.as_str(), &db).await test_get_is_success(url.as_str(), &db).await
} }
async fn test_response_contains( async fn test_response_contains(url: &str, db: &DatabaseConnection, elements_to_verify: Vec<String>) {
url: &str,
db: &DatabaseConnection,
elements_to_verify: Vec<String>,
) {
let app = create_app!(db); let app = create_app!(db);
let req = test::TestRequest::get().uri(url).to_request(); let req = test::TestRequest::get()
.uri(url)
.to_request();
let resp = test::call_service(&app, req).await; let resp = test::call_service(&app, req).await;
let body = to_bytes(resp.into_body()).await.unwrap(); let body = to_bytes(resp.into_body()).await.unwrap();
let body = body.as_str(); let body = body.as_str();
for element in elements_to_verify { for element in elements_to_verify {
assert!( assert!(body.contains(&element), "Body did not contain element {}: \n{}", element, body);
body.contains(&element),
"Body did not contain element {}: \n{}",
element,
body
);
} }
} }
async fn test_get_is_success(url: &str, db: &DatabaseConnection) { async fn test_get_is_success(url: &str, db: &DatabaseConnection) {
let app = create_app!(db); let app = create_app!(db);
let req = test::TestRequest::get().uri(url).to_request(); let req = test::TestRequest::get()
.uri(url)
.to_request();
let resp = test::call_service(&app, req).await; let resp = test::call_service(&app, req).await;
assert!(resp.status().is_success()); assert!(resp.status().is_success());
} }
} }

View File

@ -4,12 +4,16 @@ use test_setup::prelude::*;
#[cfg(test)] #[cfg(test)]
mod post_create_and_edit_is_success { mod post_create_and_edit_is_success {
use actix_admin::prelude::*; use actix_admin::prelude::*;
use actix_web::{http::header::ContentType, test, App}; use actix_web::{
use chrono::{NaiveDate, NaiveDateTime}; test,
use sea_orm::{prelude::Decimal, EntityTrait, PaginatorTrait}; App,
use serde::Serialize; http::header::ContentType
};
use chrono::{ NaiveDateTime, NaiveDate };
use serde::{Serialize};
use sea_orm::{ PaginatorTrait, EntityTrait, prelude::Decimal};
use crate::create_app; use crate::{create_app};
#[derive(Serialize, Clone)] #[derive(Serialize, Clone)]
pub struct CommentModel { pub struct CommentModel {
@ -19,7 +23,7 @@ mod post_create_and_edit_is_success {
user: &'static str, user: &'static str,
is_visible: &'static str, is_visible: &'static str,
post_id: Option<&'static str>, post_id: Option<&'static str>,
my_decimal: &'static str, my_decimal: &'static str
} }
#[derive(Serialize, Clone)] #[derive(Serialize, Clone)]
@ -44,7 +48,7 @@ mod post_create_and_edit_is_success {
user: "test", user: "test",
is_visible: "true", is_visible: "true",
post_id: None, post_id: None,
my_decimal: "113.141", // must be larger than 100 my_decimal: "113.141" // must be larger than 100
}; };
let req = test::TestRequest::post() let req = test::TestRequest::post()
@ -65,15 +69,12 @@ mod post_create_and_edit_is_success {
assert_eq!(entities.len(), 1, "After post, db does not contain 1 model"); assert_eq!(entities.len(), 1, "After post, db does not contain 1 model");
let entity = entities.first().unwrap(); let entity = entities.first().unwrap();
assert_eq!(entity.id, 1); assert_eq!(entity.id, 1);
assert_eq!(entity.comment, "test"); assert_eq!(entity.comment,"test");
assert_eq!(entity.user, "test"); assert_eq!(entity.user, "test");
assert!(entity.is_visible); assert!(entity.is_visible);
assert!(entity.post_id.is_none()); assert!(entity.post_id.is_none());
assert_eq!(entity.my_decimal, Decimal::new(113141, 3)); assert_eq!(entity.my_decimal, Decimal::new(113141, 3));
assert_eq!( assert_eq!(entity.insert_date, NaiveDateTime::parse_from_str("1977-04-01T14:00", "%Y-%m-%dT%H:%M").unwrap());
entity.insert_date,
NaiveDateTime::parse_from_str("1977-04-01T14:00", "%Y-%m-%dT%H:%M").unwrap()
);
// update entity // update entity
model.my_decimal = "213.141"; model.my_decimal = "213.141";
@ -97,11 +98,7 @@ mod post_create_and_edit_is_success {
.await .await
.expect("could not retrieve entities"); .expect("could not retrieve entities");
assert_eq!( assert_eq!(entities.len(), 1, "After edit post, db does not contain 1 model");
entities.len(),
1,
"After edit post, db does not contain 1 model"
);
let entity = entities.first().unwrap(); let entity = entities.first().unwrap();
assert_eq!(entity.id, 1); assert_eq!(entity.id, 1);
assert_eq!(entity.comment, "updated"); assert_eq!(entity.comment, "updated");
@ -109,10 +106,7 @@ mod post_create_and_edit_is_success {
assert!(!entity.is_visible); assert!(!entity.is_visible);
assert!(entity.post_id.is_none()); assert!(entity.post_id.is_none());
assert_eq!(entity.my_decimal, Decimal::new(213141, 3)); assert_eq!(entity.my_decimal, Decimal::new(213141, 3));
assert_eq!( assert_eq!(entity.insert_date, NaiveDateTime::parse_from_str("1987-04-01T14:00", "%Y-%m-%dT%H:%M").unwrap());
entity.insert_date,
NaiveDateTime::parse_from_str("1987-04-01T14:00", "%Y-%m-%dT%H:%M").unwrap()
);
} }
#[actix_web::test] #[actix_web::test]
@ -125,7 +119,7 @@ mod post_create_and_edit_is_success {
insert_date: "1977-04-01", insert_date: "1977-04-01",
title: "test", title: "test",
text: "test", text: "test",
tea_mandatory: "EverydayTea", tea_mandatory: "EverydayTea"
}; };
let req = test::TestRequest::post() let req = test::TestRequest::post()
@ -146,16 +140,10 @@ mod post_create_and_edit_is_success {
assert_eq!(entities.len(), 1, "After post, db does not contain 1 model"); assert_eq!(entities.len(), 1, "After post, db does not contain 1 model");
let entity = entities.first().unwrap(); let entity = entities.first().unwrap();
assert_eq!(entity.id, 1); assert_eq!(entity.id, 1);
assert_eq!( assert_eq!(entity.tea_mandatory, super::test_setup::post::Tea::EverydayTea);
entity.tea_mandatory,
super::test_setup::post::Tea::EverydayTea
);
assert_eq!(entity.title, model.title); assert_eq!(entity.title, model.title);
assert_eq!(entity.text, model.text); assert_eq!(entity.text, model.text);
assert_eq!( assert_eq!(entity.insert_date, NaiveDate::parse_from_str("1977-04-01", "%Y-%m-%d").unwrap());
entity.insert_date,
NaiveDate::parse_from_str("1977-04-01", "%Y-%m-%d").unwrap()
);
// update entity // update entity
model.tea_mandatory = "BreakfastTea"; model.tea_mandatory = "BreakfastTea";
@ -178,18 +166,11 @@ mod post_create_and_edit_is_success {
.await .await
.expect("could not retrieve entities"); .expect("could not retrieve entities");
assert_eq!( assert_eq!(entities.len(), 1, "After edit post, db does not contain 1 model");
entities.len(),
1,
"After edit post, db does not contain 1 model"
);
let entity = entities.first().unwrap(); let entity = entities.first().unwrap();
assert_eq!(entity.id, 1); assert_eq!(entity.id, 1);
assert_eq!(entity.text, "updated"); assert_eq!(entity.text, "updated");
assert_eq!(entity.title, "updated"); assert_eq!(entity.title, "updated");
assert_eq!( assert_eq!(entity.insert_date, NaiveDate::parse_from_str("1987-04-01", "%Y-%m-%d").unwrap());
entity.insert_date,
NaiveDate::parse_from_str("1987-04-01", "%Y-%m-%d").unwrap()
);
} }
} }

View File

@ -1,18 +1,10 @@
use super::Post;
use actix_admin::prelude::*;
use sea_orm::entity::prelude::*; use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use actix_admin::prelude::*;
use super::Post;
#[derive( #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize,
Clone, DeriveActixAdmin, DeriveActixAdminModel, DeriveActixAdminViewModel
Debug,
PartialEq,
DeriveEntityModel,
Deserialize,
Serialize,
DeriveActixAdmin,
DeriveActixAdminModel,
DeriveActixAdminViewModel,
)] )]
#[sea_orm(table_name = "comment")] #[sea_orm(table_name = "comment")]
pub struct Model { pub struct Model {
@ -28,9 +20,9 @@ pub struct Model {
#[sea_orm(column_type = "DateTime")] #[sea_orm(column_type = "DateTime")]
pub insert_date: DateTime, pub insert_date: DateTime,
pub is_visible: bool, pub is_visible: bool,
#[actix_admin(select_list = "Post")] #[actix_admin(select_list="Post")]
pub post_id: Option<i32>, pub post_id: Option<i32>,
pub my_decimal: Decimal, pub my_decimal: Decimal
} }
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)] #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
@ -55,10 +47,7 @@ impl ActixAdminModelValidationTrait<ActiveModel> for Entity {
fn validate(model: &ActiveModel) -> HashMap<String, String> { fn validate(model: &ActiveModel) -> HashMap<String, String> {
let mut errors = HashMap::new(); let mut errors = HashMap::new();
if model.my_decimal.clone().unwrap() < Decimal::from(100 as i16) { if model.my_decimal.clone().unwrap() < Decimal::from(100 as i16) {
errors.insert( errors.insert("my_decimal".to_string(), "Must be larger than 100".to_string());
"my_decimal".to_string(),
"Must be larger than 100".to_string(),
);
} }
errors errors
} }

View File

@ -1,10 +1,10 @@
use actix_admin::prelude::*; use actix_admin::prelude::*;
use actix_session::Session; use actix_session::Session;
use actix_web::web;
use actix_web::web::Bytes;
use actix_web::Error;
use actix_web::HttpRequest; use actix_web::HttpRequest;
use actix_web::web;
use actix_web::Error;
use actix_web::HttpResponse; use actix_web::HttpResponse;
use actix_web::web::Bytes;
use chrono::Local; use chrono::Local;
use sea_orm::prelude::Decimal; use sea_orm::prelude::Decimal;
use sea_orm::{ConnectOptions, DatabaseConnection, EntityTrait, Set}; use sea_orm::{ConnectOptions, DatabaseConnection, EntityTrait, Set};
@ -78,7 +78,7 @@ pub fn create_actix_admin_builder() -> ActixAdminBuilder {
login_link: None, login_link: None,
logout_link: None, logout_link: None,
file_upload_directory: "./file_uploads", file_upload_directory: "./file_uploads",
navbar_title: "test", navbar_title: "test"
}; };
let mut admin_builder = ActixAdminBuilder::new(configuration); let mut admin_builder = ActixAdminBuilder::new(configuration);

View File

@ -1,18 +1,22 @@
// setup // setup
use sea_orm::sea_query::{ColumnDef, ForeignKeyCreateStatement, TableCreateStatement}; use sea_orm::sea_query::{ForeignKeyCreateStatement, ColumnDef, TableCreateStatement};
use sea_orm::{error::*, sea_query, ConnectionTrait, DbConn, ExecResult}; use sea_orm::{error::*, sea_query, ConnectionTrait, DbConn, ExecResult};
pub mod comment; pub mod comment;
pub mod helper;
pub mod post; pub mod post;
pub mod helper;
pub use comment::Entity as Comment; pub use comment::Entity as Comment;
pub use post::Entity as Post; pub use post::Entity as Post;
pub mod prelude { pub mod prelude {
pub use crate::test_setup::helper::{
create_actix_admin_builder,
setup_db,
BodyTest
};
pub use super::comment; pub use super::comment;
pub use super::post; pub use super::post;
pub use super::Comment; pub use super::Comment;
pub use super::Post; pub use super::Post;
pub use crate::test_setup::helper::{create_actix_admin_builder, setup_db, BodyTest};
} }
// setup // setup
@ -34,11 +38,7 @@ pub async fn create_tables(db: &DbConn) -> Result<ExecResult, DbErr> {
) )
.col(ColumnDef::new(post::Column::Title).string().not_null()) .col(ColumnDef::new(post::Column::Title).string().not_null())
.col(ColumnDef::new(post::Column::Text).string().not_null()) .col(ColumnDef::new(post::Column::Text).string().not_null())
.col( .col(ColumnDef::new(post::Column::TeaMandatory).string().not_null())
ColumnDef::new(post::Column::TeaMandatory)
.string()
.not_null(),
)
.col(ColumnDef::new(post::Column::TeaOptional).string()) .col(ColumnDef::new(post::Column::TeaOptional).string())
.col(ColumnDef::new(post::Column::InsertDate).date()) .col(ColumnDef::new(post::Column::InsertDate).date())
.to_owned(); .to_owned();
@ -57,21 +57,9 @@ pub async fn create_tables(db: &DbConn) -> Result<ExecResult, DbErr> {
) )
.col(ColumnDef::new(comment::Column::Comment).string().not_null()) .col(ColumnDef::new(comment::Column::Comment).string().not_null())
.col(ColumnDef::new(comment::Column::User).string().not_null()) .col(ColumnDef::new(comment::Column::User).string().not_null())
.col( .col(ColumnDef::new(comment::Column::InsertDate).date_time().not_null())
ColumnDef::new(comment::Column::InsertDate) .col(ColumnDef::new(comment::Column::IsVisible).boolean().not_null())
.date_time() .col(ColumnDef::new(comment::Column::MyDecimal).decimal().not_null())
.not_null(),
)
.col(
ColumnDef::new(comment::Column::IsVisible)
.boolean()
.not_null(),
)
.col(
ColumnDef::new(comment::Column::MyDecimal)
.decimal()
.not_null(),
)
.col(ColumnDef::new(comment::Column::PostId).integer()) .col(ColumnDef::new(comment::Column::PostId).integer())
.foreign_key( .foreign_key(
ForeignKeyCreateStatement::new() ForeignKeyCreateStatement::new()

View File

@ -1,22 +1,11 @@
use actix_admin::prelude::*;
use sea_orm::entity::prelude::*; use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use actix_admin::prelude::*;
use std::fmt; use std::fmt;
use std::fmt::Display; use std::fmt::Display;
use std::str::FromStr; use std::str::FromStr;
#[derive( #[derive(Clone, Debug, PartialEq, DeriveEntityModel, Deserialize, Serialize, DeriveActixAdmin, DeriveActixAdminViewModel, DeriveActixAdminModel, DeriveActixAdminModelSelectList)]
Clone,
Debug,
PartialEq,
DeriveEntityModel,
Deserialize,
Serialize,
DeriveActixAdmin,
DeriveActixAdminViewModel,
DeriveActixAdminModel,
DeriveActixAdminModelSelectList,
)]
#[sea_orm(table_name = "post")] #[sea_orm(table_name = "post")]
pub struct Model { pub struct Model {
#[sea_orm(primary_key)] #[sea_orm(primary_key)]
@ -28,9 +17,9 @@ pub struct Model {
#[sea_orm(column_type = "Text")] #[sea_orm(column_type = "Text")]
#[actix_admin(searchable, textarea)] #[actix_admin(searchable, textarea)]
pub text: String, pub text: String,
#[actix_admin(select_list = "Tea")] #[actix_admin(select_list="Tea")]
pub tea_mandatory: Tea, pub tea_mandatory: Tea,
#[actix_admin(select_list = "Tea")] #[actix_admin(select_list="Tea")]
pub tea_optional: Option<Tea>, pub tea_optional: Option<Tea>,
pub insert_date: Date, pub insert_date: Date,
} }
@ -38,7 +27,7 @@ pub struct Model {
impl Display for Model { impl Display for Model {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
match &*self { match &*self {
_ => write!(formatter, "{} {}", &self.title, &self.insert_date), _ => write!(formatter, "{} {}", &self.title, &self.insert_date),
} }
} }
} }
@ -57,20 +46,7 @@ impl Related<super::comment::Entity> for Entity {
impl ActiveModelBehavior for ActiveModel {} impl ActiveModelBehavior for ActiveModel {}
<<<<<<< HEAD
#[derive(Debug, Clone, PartialEq, EnumIter, DeriveDisplay, DeriveActiveEnum, Deserialize, Serialize, DeriveActixAdminEnumSelectList)] #[derive(Debug, Clone, PartialEq, EnumIter, DeriveDisplay, DeriveActiveEnum, Deserialize, Serialize, DeriveActixAdminEnumSelectList)]
=======
#[derive(
Debug,
Clone,
PartialEq,
EnumIter,
DeriveActiveEnum,
Deserialize,
Serialize,
DeriveActixAdminEnumSelectList,
)]
>>>>>>> 7db2971 (Trim input name)
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "tea")] #[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "tea")]
pub enum Tea { pub enum Tea {
#[sea_orm(string_value = "EverydayTea")] #[sea_orm(string_value = "EverydayTea")]
@ -84,9 +60,9 @@ impl FromStr for Tea {
fn from_str(input: &str) -> Result<Tea, Self::Err> { fn from_str(input: &str) -> Result<Tea, Self::Err> {
match input { match input {
"EverydayTea" => Ok(Tea::EverydayTea), "EverydayTea" => Ok(Tea::EverydayTea),
"BreakfastTea" => Ok(Tea::BreakfastTea), "BreakfastTea" => Ok(Tea::BreakfastTea),
_ => Err(()), _ => Err(()),
} }
} }
} }