use bytes::Bytes;
use http_body_util::Full;
use hyper::Request as HyperRequest;
use rustf::prelude::*;
use rustf::RustF;
fn install_continue() -> Vec<Route> {
let routes = routes![
before: before,
GET "/users/{id}" => show,
];
async fn before(ctx: &mut Context) -> rustf::Result<BeforeAction> {
ctx.repository_set("section", "users");
ctx.repository_set("hook_ran", true);
Ok(BeforeAction::Continue)
}
async fn show(ctx: &mut Context) -> rustf::Result<()> {
let section = ctx
.repository_get("section")
.and_then(|v| v.as_str().map(|s| s.to_string()))
.unwrap_or_default();
let hook_ran = ctx
.repository_get("hook_ran")
.and_then(|v| v.as_bool())
.unwrap_or(false);
ctx.json(json!({
"section": section,
"hook_ran": hook_ran,
}))
}
routes
}
#[tokio::test]
async fn before_runs_and_continues() {
let app = RustF::new().controllers(install_continue());
let req = HyperRequest::builder()
.method("GET")
.uri("/users/42")
.body(Full::<Bytes>::new(Bytes::new()))
.unwrap();
let res = app
.handle_request(req)
.await
.expect("handle_request returned Err");
assert_eq!(
res.status,
hyper::StatusCode::OK,
"expected 200, got {:?}",
res.status
);
let body = String::from_utf8(res.body.as_slice().unwrap().to_vec()).unwrap();
assert!(
body.contains(r#""section":"users""#),
"before's repository value missing from handler response: {}",
body
);
assert!(
body.contains(r#""hook_ran":true"#),
"hook_ran flag not propagated: {}",
body
);
}
fn install_stop() -> Vec<Route> {
async fn before(ctx: &mut Context) -> rustf::Result<BeforeAction> {
ctx.redirect("/login")?;
Ok(BeforeAction::Stop)
}
async fn protected(ctx: &mut Context) -> rustf::Result<()> {
ctx.add_header("X-Handler-Ran", "yes");
ctx.json(json!({"secret": true}))
}
routes![
before: before,
GET "/protected" => protected,
]
}
#[tokio::test]
async fn before_stops_short_circuits_handler() {
let app = RustF::new().controllers(install_stop());
let req = HyperRequest::builder()
.method("GET")
.uri("/protected")
.body(Full::<Bytes>::new(Bytes::new()))
.unwrap();
let res = app
.handle_request(req)
.await
.expect("handle_request returned Err");
assert_eq!(
res.status,
hyper::StatusCode::FOUND,
"Stop with redirect should produce 302, got {:?}",
res.status
);
let location = res
.headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("location"))
.map(|(_, v)| v.as_str())
.unwrap_or("");
assert_eq!(location, "/login", "Location header missing or wrong");
let handler_ran = res
.headers
.iter()
.any(|(k, _)| k.eq_ignore_ascii_case("X-Handler-Ran"));
assert!(
!handler_ran,
"Stop should have prevented the handler from running, but X-Handler-Ran is set"
);
}
fn install_no_hook() -> Vec<Route> {
async fn ping(ctx: &mut Context) -> rustf::Result<()> {
ctx.json(json!({"pong": true}))
}
routes![
GET "/ping" => ping,
]
}
#[tokio::test]
async fn before_absent_is_backward_compatible() {
let routes = install_no_hook();
assert_eq!(routes.len(), 1);
assert!(
routes[0].before.is_none(),
"bare routes![] must leave Route::before as None"
);
let app = RustF::new().controllers(install_no_hook());
let req = HyperRequest::builder()
.method("GET")
.uri("/ping")
.body(Full::<Bytes>::new(Bytes::new()))
.unwrap();
let res = app
.handle_request(req)
.await
.expect("handle_request returned Err");
assert_eq!(res.status, hyper::StatusCode::OK);
let body = String::from_utf8(res.body.as_slice().unwrap().to_vec()).unwrap();
assert!(
body.contains(r#""pong":true"#),
"handler did not run: {}",
body
);
}