complete tests for logbook

This commit is contained in:
philipp 2023-10-01 15:53:45 +02:00
parent 83e75b1ca9
commit 25d56216f2
3 changed files with 282 additions and 30 deletions

View File

@ -78,6 +78,18 @@ impl Boat {
.ok() .ok()
} }
pub async fn shipmaster_allowed(&self, user: &User) -> bool {
if let Some(owner_id) = self.owner {
return owner_id == user.id;
}
if self.amount_seats == 1 {
return true;
}
user.is_cox
}
pub async fn is_locked(&self, db: &SqlitePool) -> bool { pub async fn is_locked(&self, db: &SqlitePool) -> bool {
sqlx::query!("SELECT * FROM boat_damage WHERE boat_id=? AND lock_boat=true AND user_id_verified is null", self.id).fetch_optional(db).await.unwrap().is_some() sqlx::query!("SELECT * FROM boat_damage WHERE boat_id=? AND lock_boat=true AND user_id_verified is null", self.id).fetch_optional(db).await.unwrap().is_some()
} }
@ -136,7 +148,7 @@ ORDER BY amount_seats DESC
if user.is_admin { if user.is_admin {
return Self::all(db).await; return Self::all(db).await;
} }
let mut boats; let boats;
if user.is_cox { if user.is_cox {
boats = sqlx::query_as!( boats = sqlx::query_as!(
Boat, Boat,

View File

@ -41,7 +41,7 @@ pub struct LogToAdd {
pub rowers: Vec<i64>, pub rowers: Vec<i64>,
} }
#[derive(FromForm)] #[derive(FromForm, Debug)]
pub struct LogToFinalize { pub struct LogToFinalize {
pub destination: String, pub destination: String,
pub distance_in_km: i64, pub distance_in_km: i64,
@ -75,6 +75,7 @@ pub enum LogbookDeleteError {
#[derive(Debug, PartialEq)] #[derive(Debug, PartialEq)]
pub enum LogbookCreateError { pub enum LogbookCreateError {
ArrivalSetButNoDestination, ArrivalSetButNoDestination,
UserNotAllowedToUseBoat,
ArrivalSetButNoDistance, ArrivalSetButNoDistance,
BoatAlreadyOnWater, BoatAlreadyOnWater,
BoatLocked, BoatLocked,
@ -170,7 +171,11 @@ ORDER BY departure DESC
ret ret
} }
pub async fn create(db: &SqlitePool, log: LogToAdd) -> Result<(), LogbookCreateError> { pub async fn create(
db: &SqlitePool,
log: LogToAdd,
created_by_user: &User,
) -> Result<(), LogbookCreateError> {
let Some(boat) = Boat::find_by_id(db, log.boat_id).await else { let Some(boat) = Boat::find_by_id(db, log.boat_id).await else {
return Err(LogbookCreateError::BoatNotFound); return Err(LogbookCreateError::BoatNotFound);
}; };
@ -183,10 +188,9 @@ ORDER BY departure DESC
return Err(LogbookCreateError::BoatAlreadyOnWater); return Err(LogbookCreateError::BoatAlreadyOnWater);
} }
if (User::find_by_id(db, log.shipmaster as i32).await.unwrap()) let shipmaster = User::find_by_id(db, log.shipmaster as i32).await.unwrap();
.on_water(db)
.await if shipmaster.on_water(db).await {
{
return Err(LogbookCreateError::ShipmasterAlreadyOnWater); return Err(LogbookCreateError::ShipmasterAlreadyOnWater);
} }
@ -223,6 +227,10 @@ ORDER BY departure DESC
} }
} }
if !boat.shipmaster_allowed(created_by_user).await {
return Err(LogbookCreateError::UserNotAllowedToUseBoat);
}
//let departure = format!("{}+02:00", &log.departure); //let departure = format!("{}+02:00", &log.departure);
let mut tx = db.begin().await.unwrap(); let mut tx = db.begin().await.unwrap();
@ -431,7 +439,7 @@ mod test {
&pool, &pool,
LogToAdd { LogToAdd {
boat_id: 3, boat_id: 3,
shipmaster: 5, shipmaster: 4,
shipmaster_only_steering: false, shipmaster_only_steering: false,
departure: "2128-05-20T12:00".into(), departure: "2128-05-20T12:00".into(),
arrival: None, arrival: None,
@ -441,6 +449,7 @@ mod test {
logtype: None, logtype: None,
rowers: Vec::new(), rowers: Vec::new(),
}, },
&User::find_by_id(&pool, 4).await.unwrap(),
) )
.await .await
.unwrap() .unwrap()
@ -464,6 +473,7 @@ mod test {
logtype: None, logtype: None,
rowers: Vec::new(), rowers: Vec::new(),
}, },
&User::find_by_id(&pool, 4).await.unwrap(),
) )
.await; .await;
@ -488,6 +498,7 @@ mod test {
logtype: None, logtype: None,
rowers: Vec::new(), rowers: Vec::new(),
}, },
&User::find_by_id(&pool, 4).await.unwrap(),
) )
.await; .await;
@ -512,6 +523,7 @@ mod test {
logtype: None, logtype: None,
rowers: Vec::new(), rowers: Vec::new(),
}, },
&User::find_by_id(&pool, 5).await.unwrap(),
) )
.await; .await;
@ -536,6 +548,7 @@ mod test {
logtype: None, logtype: None,
rowers: Vec::new(), rowers: Vec::new(),
}, },
&User::find_by_id(&pool, 5).await.unwrap(),
) )
.await; .await;
@ -560,6 +573,7 @@ mod test {
logtype: None, logtype: None,
rowers: Vec::new(), rowers: Vec::new(),
}, },
&User::find_by_id(&pool, 2).await.unwrap(),
) )
.await; .await;
@ -584,6 +598,7 @@ mod test {
logtype: None, logtype: None,
rowers: vec![5], rowers: vec![5],
}, },
&User::find_by_id(&pool, 5).await.unwrap(),
) )
.await; .await;
@ -608,6 +623,7 @@ mod test {
logtype: None, logtype: None,
rowers: vec![1], rowers: vec![1],
}, },
&User::find_by_id(&pool, 5).await.unwrap(),
) )
.await; .await;

View File

@ -20,7 +20,7 @@ use crate::model::{
LogbookUpdateError, LogbookUpdateError,
}, },
logtype::LogType, logtype::LogType,
user::{AdminUser, User, UserWithWaterStatus}, user::{User, UserWithWaterStatus},
}; };
pub struct KioskCookie(String); pub struct KioskCookie(String);
@ -139,10 +139,11 @@ async fn kiosk(
Template::render("kiosk", context.into_json()) Template::render("kiosk", context.into_json())
} }
async fn create_logbook(db: &SqlitePool, data: Form<LogToAdd>) -> Flash<Redirect> { async fn create_logbook(db: &SqlitePool, data: Form<LogToAdd>, user: &User) -> Flash<Redirect> {
match Logbook::create( match Logbook::create(
db, db,
data.into_inner() data.into_inner(),
user
) )
.await .await
{ {
@ -158,17 +159,14 @@ async fn create_logbook(db: &SqlitePool, data: Form<LogToAdd>) -> Flash<Redirect
Err(LogbookCreateError::ArrivalSetButNoDistance) => Flash::error(Redirect::to("/log"), format!("Distanz notwendig, wenn Ankunftszeit angegeben wurde")), Err(LogbookCreateError::ArrivalSetButNoDistance) => Flash::error(Redirect::to("/log"), format!("Distanz notwendig, wenn Ankunftszeit angegeben wurde")),
Err(LogbookCreateError::ArrivalSetButNoDestination) => Flash::error(Redirect::to("/log"), format!("Ziel notwendig, wenn Ankunftszeit angegeben wurde")), Err(LogbookCreateError::ArrivalSetButNoDestination) => Flash::error(Redirect::to("/log"), format!("Ziel notwendig, wenn Ankunftszeit angegeben wurde")),
Err(LogbookCreateError::ArrivalNotAfterDeparture) => Flash::error(Redirect::to("/log"), format!("Ankunftszeit kann nicht vor der Abfahrtszeit sein")), Err(LogbookCreateError::ArrivalNotAfterDeparture) => Flash::error(Redirect::to("/log"), format!("Ankunftszeit kann nicht vor der Abfahrtszeit sein")),
Err(LogbookCreateError::UserNotAllowedToUseBoat) => Flash::error(Redirect::to("/log"), format!("Schiffsführer darf dieses Boot nicht verwenden")),
} }
} }
#[post("/", data = "<data>", rank = 2)] #[post("/", data = "<data>", rank = 2)]
async fn create( async fn create(db: &State<SqlitePool>, data: Form<LogToAdd>, user: User) -> Flash<Redirect> {
db: &State<SqlitePool>, create_logbook(db, data, &user).await
data: Form<LogToAdd>,
_adminuser: AdminUser,
) -> Flash<Redirect> {
create_logbook(db, data).await
} }
#[post("/", data = "<data>")] #[post("/", data = "<data>")]
@ -177,7 +175,8 @@ async fn create_kiosk(
data: Form<LogToAdd>, data: Form<LogToAdd>,
_kiosk: KioskCookie, _kiosk: KioskCookie,
) -> Flash<Redirect> { ) -> Flash<Redirect> {
create_logbook(db, data).await let creator = User::find_by_id(db, data.shipmaster as i32).await.unwrap();
create_logbook(db, data, &creator).await
} }
async fn home_logbook( async fn home_logbook(
@ -498,6 +497,11 @@ mod test {
let rocket = rocket::build().manage(db.clone()); let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket); let rocket = crate::tera::config(rocket);
sqlx::query("DELETE FROM logbook;")
.execute(&db)
.await
.unwrap();
let mut client = Client::tracked(rocket).await.unwrap(); let mut client = Client::tracked(rocket).await.unwrap();
let req = client.get("/log/kiosk/ekrv2019/Linz"); let req = client.get("/log/kiosk/ekrv2019/Linz");
let _ = req.dispatch().await; let _ = req.dispatch().await;
@ -517,11 +521,81 @@ mod test {
&db, &db,
&mut client, &mut client,
"second_private_boat_from_rower".into(), "second_private_boat_from_rower".into(),
"admin".into(), "rower".into(),
) )
.await; .await;
} }
#[sqlx::test]
fn test_shipowner_can_allow_others_to_drive() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
sqlx::query("DELETE FROM logbook;")
.execute(&db)
.await
.unwrap();
let client = Client::tracked(rocket).await.unwrap();
let login = client
.post("/auth")
.header(ContentType::Form) // Set the content type to form
.body("name=rower&password=rower"); // Add the form data to the request body;
login.dispatch().await;
// Owner can start trip:
let boat_id = Boat::find_by_name(&db, "private_boat_from_rower".into())
.await
.unwrap()
.id;
let shipmaster_id = User::find_by_name(&db, "rower2".into()).await.unwrap().id;
let req = client.post("/log").header(ContentType::Form).body(format!(
"boat_id={boat_id}&shipmaster={shipmaster_id}&departure=1199-12-31T10:00"
));
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/log"));
let flash_cookie = response
.cookies()
.get("_flash")
.expect("Expected flash cookie");
assert_eq!(
flash_cookie.value(),
"7:successAusfahrt erfolgreich hinzugefügt"
);
// Shipmaster can end it
let log_id = Logbook::highest_id(&db).await;
let login = client
.post("/auth")
.header(ContentType::Form) // Set the content type to form
.body("name=rower2&password=rower"); // Add the form data to the request body;
login.dispatch().await;
let req = client
.post(format!("/log/{log_id}"))
.header(ContentType::Form)
.body("destination=Ottensheim&distance_in_km=25");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/log"));
let flash_cookie = response
.cookies()
.get("_flash")
.expect("Expected flash cookie");
assert_eq!(flash_cookie.value(), "7:successSuccessfully updated log");
}
#[sqlx::test] #[sqlx::test]
fn test_normal_user_sees_appropriate_boats() { fn test_normal_user_sees_appropriate_boats() {
let db = testdb!(); let db = testdb!();
@ -529,7 +603,7 @@ mod test {
let rocket = rocket::build().manage(db.clone()); let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket); let rocket = crate::tera::config(rocket);
let client = Client::tracked(rocket).await.unwrap(); let mut client = Client::tracked(rocket).await.unwrap();
let login = client let login = client
.post("/auth") .post("/auth")
.header(ContentType::Form) // Set the content type to form .header(ContentType::Form) // Set the content type to form
@ -541,16 +615,176 @@ mod test {
let text = response.into_string().await.unwrap(); let text = response.into_string().await.unwrap();
sqlx::query("DELETE FROM logbook;")
.execute(&db)
.await
.unwrap();
//Sees all 1x //Sees all 1x
assert!(text.contains("Haichenbach")); assert!(text.contains("Haichenbach"));
can_start_and_end_trip(&db, &mut client, "Haichenbach".into(), "rower".into()).await;
assert!(text.contains("private_boat_from_rower")); assert!(text.contains("private_boat_from_rower"));
can_start_and_end_trip(
&db,
&mut client,
"private_boat_from_rower".into(),
"rower".into(),
)
.await;
assert!(text.contains("second_private_boat_from_rower")); assert!(text.contains("second_private_boat_from_rower"));
can_start_and_end_trip(
&db,
&mut client,
"second_private_boat_from_rower".into(),
"rower".into(),
)
.await;
//Don't see anything else //Don't see anything else
assert!(!text.contains("Joe")); assert!(!text.contains("Joe"));
cant_start_trip(
&db,
&mut client,
"Joe".into(),
"rower".into(),
"Schiffsführer darf dieses Boot nicht verwenden".into(),
)
.await;
assert!(!text.contains("Kaputtes Boot :-(")); assert!(!text.contains("Kaputtes Boot :-("));
cant_start_trip(
&db,
&mut client,
"Kaputtes Boot :-(".into(),
"rower".into(),
"Schiffsführer darf dieses Boot nicht verwenden".into(),
)
.await;
assert!(!text.contains("Sehr kaputtes Boot :-((")); assert!(!text.contains("Sehr kaputtes Boot :-(("));
cant_start_trip(
&db,
&mut client,
"Sehr kaputtes Boot :-((".into(),
"rower".into(),
"Boot gesperrt".into(),
)
.await;
assert!(!text.contains("Ottensheim Boot")); assert!(!text.contains("Ottensheim Boot"));
cant_start_trip(
&db,
&mut client,
"Ottensheim Boot".into(),
"rower".into(),
"Schiffsführer darf dieses Boot nicht verwenden".into(),
)
.await;
}
#[sqlx::test]
fn test_cox_sees_appropriate_boats() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
let mut client = Client::tracked(rocket).await.unwrap();
let login = client
.post("/auth")
.header(ContentType::Form) // Set the content type to form
.body("name=cox&password=cox"); // Add the form data to the request body;
login.dispatch().await;
sqlx::query("DELETE FROM logbook;")
.execute(&db)
.await
.unwrap();
let req = client.get("/log");
let response = req.dispatch().await;
let text = response.into_string().await.unwrap();
//Sees all 1x
assert!(text.contains("Haichenbach"));
can_start_and_end_trip(&db, &mut client, "Haichenbach".into(), "cox".into()).await;
assert!(text.contains("Joe"));
can_start_and_end_trip(&db, &mut client, "Joe".into(), "cox".into()).await;
assert!(text.contains("Kaputtes Boot :-("));
can_start_and_end_trip(&db, &mut client, "Kaputtes Boot :-(".into(), "cox".into()).await;
assert!(text.contains("Sehr kaputtes Boot :-(("));
cant_start_trip(
&db,
&mut client,
"Sehr kaputtes Boot :-((".into(),
"cox".into(),
"Boot gesperrt".into(),
)
.await;
assert!(text.contains("Ottensheim Boot"));
can_start_and_end_trip(&db, &mut client, "Ottensheim Boot".into(), "cox".into()).await;
//Can't use private boats
assert!(!text.contains("private_boat_from_rower"));
cant_start_trip(
&db,
&mut client,
"private_boat_from_rower".into(),
"cox".into(),
"Schiffsführer darf dieses Boot nicht verwenden".into(),
)
.await;
assert!(!text.contains("second_private_boat_from_rower"));
cant_start_trip(
&db,
&mut client,
"second_private_boat_from_rower".into(),
"cox".into(),
"Schiffsführer darf dieses Boot nicht verwenden".into(),
)
.await;
}
#[sqlx::test]
fn test_cant_end_trip_other_user() {
let db = testdb!();
let rocket = rocket::build().manage(db.clone());
let rocket = crate::tera::config(rocket);
let client = Client::tracked(rocket).await.unwrap();
let login = client
.post("/auth")
.header(ContentType::Form) // Set the content type to form
.body("name=rower2&password=rower"); // Add the form data to the request body;
login.dispatch().await;
let req = client
.post("/log/1")
.header(ContentType::Form)
.body("destination=Ottensheim&distance_in_km=25");
let response = req.dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
assert_eq!(response.headers().get("Location").next(), Some("/log"));
let flash_cookie = response
.cookies()
.get("_flash")
.expect("Expected flash cookie");
assert_eq!(
flash_cookie.value(),
"5:errorLogbook with ID 1 could not be updated!"
);
} }
async fn can_start_and_end_trip( async fn can_start_and_end_trip(
@ -559,7 +793,6 @@ mod test {
boat_name: String, boat_name: String,
shipmaster_name: String, shipmaster_name: String,
) { ) {
println!("{boat_name}");
let boat_id = Boat::find_by_name(db, boat_name).await.unwrap().id; let boat_id = Boat::find_by_name(db, boat_name).await.unwrap().id;
let shipmaster_id = User::find_by_name(db, &shipmaster_name).await.unwrap().id; let shipmaster_id = User::find_by_name(db, &shipmaster_name).await.unwrap().id;
@ -576,7 +809,6 @@ mod test {
.get("_flash") .get("_flash")
.expect("Expected flash cookie"); .expect("Expected flash cookie");
println!("{shipmaster_id}");
assert_eq!( assert_eq!(
flash_cookie.value(), flash_cookie.value(),
"7:successAusfahrt erfolgreich hinzugefügt" "7:successAusfahrt erfolgreich hinzugefügt"
@ -599,14 +831,6 @@ mod test {
.expect("Expected flash cookie"); .expect("Expected flash cookie");
assert_eq!(flash_cookie.value(), "7:successSuccessfully updated log"); assert_eq!(flash_cookie.value(), "7:successSuccessfully updated log");
//TODO: Remove the following query?
//sqlx::query(&format!(
// "DELETE FROM logbook WHERE boat_id={boat_id} AND shipmaster={shipmaster_id}"
//))
//.execute(db)
//.await
//.unwrap();
} }
async fn cant_start_trip( async fn cant_start_trip(