use std::any::type_name;
use std::sync::{Arc, Mutex};
use anyhow::Context;
use laravel::Application;
use laravel::config::{Config, Env};
use laravel::errors::Errors;
use laravel::foundation::ServiceProvider;
use laravel::http::{File, Request, StatusCode, header};
use laravel::routing::{Params, Router};
use laravel::testing::MakesHttpRequests;
use laravel::validation::InvalidInput;
use serde::Deserialize;
use serde_json::json;
use crate::support::{TempDir, WithDir};
use self::refunds::Refund;
#[derive(Debug, thiserror::Error)]
#[error("The card was declined")]
struct PaymentFailed;
#[derive(Debug, Deserialize)]
#[expect(dead_code, reason = "only deserialized")]
struct NewUser {
name: String,
email: String,
}
fn charge() -> Result<(), PaymentFailed> {
Err(PaymentFailed)
}
async fn checkout() -> laravel::Result<&'static str> {
charge()?;
Ok("paid")
}
async fn invite() -> laravel::Result<&'static str> {
Err(InvalidInput::new().with("email", "That email is already invited."))?
}
async fn disk() -> laravel::Result<&'static str> {
Err(std::io::Error::other("the disk is full"))?
}
async fn checkout_with_context() -> laravel::Result<&'static str> {
charge().context("The order can't be paid for")?;
Ok("paid")
}
async fn checkout_with_error_context() -> laravel::Result<&'static str> {
charge().map_err(|error| laravel::Error::from(error).context("charging order 7"))?;
Ok("paid")
}
async fn send_invoice() -> laravel::Result<&'static str> {
Err(laravel::abort(404).context("loading invoice 42 for tenant acme"))
}
async fn upload() -> laravel::Result<&'static str> {
Err(std::io::Error::other("the disk is full")).context("The upload can't be saved")?
}
fn queue() -> anyhow::Result<()> {
anyhow::bail!("the queue is down")
}
async fn dispatch() -> laravel::Result<&'static str> {
queue()?;
Ok("dispatched")
}
fn app(debug: bool, reported: &Arc<Mutex<Vec<String>>>) -> Application {
let reported = Arc::clone(reported);
Application::configure()
.replace_env(Env::from_iter([("APP_DEBUG", if debug { "true" } else { "false" })]))
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.post("/checkout", checkout);
route.get("/limited-with-invalid-header", || async {
Err::<(), _>(
laravel::abort(429)
.with_header("x-reason", "line\nbreak")
.with_header(header::RETRY_AFTER, "60"),
)
});
route.get("/gzipped-failure", || async {
([(header::CONTENT_ENCODING, "gzip")], laravel::abort(404))
});
route.get("/moved", || async {
Err::<(), _>(laravel::abort(303).with_header(header::LOCATION, "/login"))
});
route.get("/limited-by-handler", || async {
([(header::RETRY_AFTER, "60")], laravel::abort(429))
});
route
.get("/tagged", || async { Err::<(), _>(laravel::abort(404)) })
.middleware(TagResponses);
route
.get("/invoice", || async {
Err::<(), _>(laravel::Error::new(404, MissingInvoice))
})
.middleware(IdentifyTenant);
route.post("/users", |request: Request| async move {
request.parse::<NewUser>()?;
Ok::<_, laravel::Error>("created")
});
route.post("/invite", invite);
route.get("/disk", disk);
route.post("/imports", || async {
Err::<&str, _>(laravel::Error::msg("the import file has no header row"))
});
route.post("/checkout-with-context", checkout_with_context);
route.post("/checkout-with-error-context", checkout_with_error_context);
route.post("/invoices/42/send", send_invoice);
route.post("/upload", upload);
route.post("/dispatch", dispatch);
route.get("/recommendations", || async {
std::fs::read("/no/such/recommendations").unwrap_or_else(|error| {
laravel::report(error);
Vec::new()
});
"no recommendations today"
});
route.get("/upgrading", || async {
Err::<(), _>(laravel::abort_with(503, "We're upgrading. Back in a minute."))
});
route.get("/names/{name}", |Params(name): Params<String>| async move {
Err::<(), _>(laravel::abort_with(403, format!("The name {name} is taken.")))
});
route.get("/report-missing", || async {
laravel::report(laravel::abort(404));
"carried on"
});
route.get("/posts/deleted", || async {
Err::<(), _>(laravel::abort_with(404, "That post was deleted."))
});
#[cfg(feature = "database")]
route.get("/posts/abc", || async {
Err::<(), _>(laravel::Error::from(laravel::model::ModelNotFound {
model: "Post",
key: Some("abc".to_owned()),
}))
});
#[cfg(feature = "database")]
route.get("/posts/sole", || async {
Err::<(), _>(laravel::Error::from(laravel::db::RecordNotFound))
});
});
})
.with_errors(move |errors, _| {
let every = Arc::clone(&reported);
errors
.render(|_: &MissingInvoice, request, status| {
let tenant = request.extension::<Tenant>().map_or("missing", |tenant| tenant.0);
Some((status, format!("No such invoice for {tenant}")))
})
.status::<PaymentFailed>(402)
.report(move |error: &std::io::Error| {
reported.lock().unwrap().push(error.to_string());
})
.report_all(move |error| {
every.lock().unwrap().push(format!("every: {}", error.type_name()));
});
})
.create()
}
struct TagResponses;
impl laravel::http::Middleware for TagResponses {
async fn handle(&self, request: Request, next: laravel::http::Next) -> laravel::Result<laravel::http::Response> {
let mut response = next.run(request).await;
let seen = response
.headers()
.get(header::CONTENT_TYPE)
.cloned()
.unwrap_or_else(|| laravel::http::HeaderValue::from_static("none"));
response.headers_mut().insert("x-route-saw", seen);
Ok(response)
}
}
#[derive(Clone)]
struct Tenant(&'static str);
struct IdentifyTenant;
impl laravel::http::Middleware for IdentifyTenant {
async fn handle(
&self,
mut request: Request,
next: laravel::http::Next,
) -> laravel::Result<laravel::http::Response> {
request.extensions_mut().insert(Tenant("acme"));
Ok(next.run(request).await)
}
}
#[derive(Debug, thiserror::Error)]
#[error("There's no such invoice")]
struct MissingInvoice;
fn quiet_app() -> Application {
app(false, &Arc::default())
}
#[tokio::test]
async fn error_types_respond_with_their_status() {
let response = quiet_app().post("/checkout").header("accept", "application/json").await;
response
.assert_status(402)
.assert_json(json!({ "message": "The card was declined" }))
.assert_nothing_reported();
assert!(response.error().is_some_and(|error| error.is::<PaymentFailed>()));
}
#[tokio::test]
async fn errors_skip_invalid_headers_and_keep_their_status() {
let response = quiet_app().get("/limited-with-invalid-header").await;
response
.assert_status(StatusCode::TOO_MANY_REQUESTS)
.assert_header("retry-after", "60");
assert!(response.headers().get("x-reason").is_none());
}
#[tokio::test]
async fn errors_keep_the_headers_their_handler_and_route_gave_them() {
let app = quiet_app();
app.get("/limited-by-handler")
.await
.assert_status(StatusCode::TOO_MANY_REQUESTS)
.assert_header("retry-after", "60");
}
#[tokio::test]
async fn failures_details_stay_out_of_json_outside_debug_mode() {
let response = quiet_app().get("/disk").header("accept", "application/json").await;
response
.assert_internal_server_error()
.assert_json(json!({ "message": "Server Error" }));
assert!(response.json().get("error").is_none());
assert!(response.json().get("causes").is_none());
let debug = app(true, &Arc::default());
let expected = debug.post("/invite").header("accept", "application/json").await;
assert!(expected.json().get("error").is_none(), "{}", expected.text());
}
#[tokio::test]
async fn an_error_from_a_message_is_a_failure_that_points_to_its_caller() {
let reported = Arc::new(Mutex::new(Vec::new()));
let response = app(false, &reported)
.post("/imports")
.header("accept", "application/json")
.await;
response
.assert_internal_server_error()
.assert_exact_json(json!({ "message": "Server Error" }));
assert_eq!(reported.lock().unwrap().len(), 1);
let debug = app(true, &Arc::default())
.post("/imports")
.header("accept", "application/json")
.await;
let json = debug.json();
assert_eq!(json["message"], "the import file has no header row");
assert_eq!(json["file"], "tests/errors.rs");
}
#[tokio::test]
async fn headers_about_the_body_arent_kept_on_a_rendered_error() {
quiet_app()
.get("/gzipped-failure")
.await
.assert_not_found()
.assert_header_missing("content-encoding");
}
#[tokio::test]
async fn errors_of_ignored_types_arent_reported() {
let reported = Arc::new(Mutex::new(Vec::new()));
let every = Arc::clone(&reported);
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.get("/disk", disk);
});
})
.with_errors(move |errors, _| {
errors
.report_all(move |error| every.lock().unwrap().push(error.to_string()))
.dont_report::<std::io::Error>();
})
.create();
app.get("/disk").await.assert_internal_server_error();
assert!(reported.lock().unwrap().is_empty());
}
#[tokio::test]
async fn responders_adjust_every_rendered_error() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.get("/missing", || async { Err::<(), _>(laravel::abort(404)) });
});
})
.with_errors(|errors, _| {
errors.respond(|mut response, error, _request| {
response.headers_mut().insert(
"x-error-status",
laravel::http::HeaderValue::from(error.status().as_u16()),
);
response
});
})
.create();
app.get("/missing").await.assert_header("x-error-status", "404");
}
#[tokio::test]
async fn route_middleware_see_the_rendered_error() {
quiet_app()
.get("/tagged")
.await
.assert_not_found()
.assert_header("x-route-saw", "text/html; charset=utf-8");
}
#[tokio::test]
async fn errors_are_rendered_with_what_route_middleware_added_to_the_request() {
quiet_app()
.get("/invoice")
.await
.assert_not_found()
.assert_see("No such invoice for acme");
}
#[tokio::test]
async fn invalid_input_names_the_field_in_laravels_shape() {
quiet_app()
.post("/users")
.json(json!({ "name": "Taylor" }))
.await
.assert_unprocessable()
.assert_json(json!({
"message": "The email field is required.",
"errors": { "email": ["The email field is required."] },
}));
}
#[tokio::test]
async fn invalid_input_of_your_own_is_unprocessable_too() {
quiet_app()
.post("/invite")
.json(json!({}))
.await
.assert_unprocessable()
.assert_json_path("errors.email.0", "That email is already invited.");
}
#[tokio::test]
async fn failures_are_reported() {
let reported = Arc::default();
app(false, &reported)
.get("/disk")
.await
.assert_internal_server_error()
.assert_reported::<std::io::Error>();
assert_eq!(
*reported.lock().unwrap(),
[
"the disk is full".to_owned(),
format!("every: {}", type_name::<std::io::Error>())
]
);
}
#[tokio::test]
async fn failures_can_be_reported_without_failing_the_request() {
let reported = Arc::default();
app(false, &reported)
.get("/recommendations")
.await
.assert_ok()
.assert_see("no recommendations today")
.assert_reported::<std::io::Error>();
let reported = reported.lock().unwrap();
assert_eq!(reported.len(), 2, "{reported:?}");
assert_eq!(reported[1], format!("every: {}", type_name::<std::io::Error>()));
}
#[test]
fn reporting_outside_the_application_logs_the_error() {
laravel::report(std::io::Error::other("no application here"));
}
#[tokio::test]
async fn failures_raised_with_abort_show_their_message_only_as_json() {
let app = quiet_app();
app.get("/upgrading")
.header("accept", "application/json")
.await
.assert_status(503)
.assert_json(json!({ "message": "We're upgrading. Back in a minute." }));
app.get("/upgrading")
.await
.assert_status(503)
.assert_see("Service Unavailable")
.assert_dont_see("upgrading");
}
#[tokio::test]
async fn messages_on_the_built_in_error_page_are_escaped() {
quiet_app()
.get("/names/%3Cscript%3Ealert(1)%3C%2Fscript%3E")
.await
.assert_forbidden()
.assert_see_html("The name <script>alert(1)</script> is taken.")
.assert_dont_see_html("<script>alert(1)");
}
#[tokio::test]
async fn expected_outcomes_are_not_reported() {
let reported = Arc::default();
let app = app(false, &reported);
app.get("/missing").await.assert_not_found().assert_nothing_reported();
app.get("/report-missing").await.assert_ok().assert_nothing_reported();
app.get("/moved")
.await
.assert_status(StatusCode::SEE_OTHER)
.assert_header("location", "/login")
.assert_nothing_reported();
assert!(reported.lock().unwrap().is_empty());
}
#[tokio::test]
async fn only_failures_get_the_debug_page() {
let app = app(true, &Arc::default());
app.get("/disk")
.await
.assert_internal_server_error()
.assert_see(type_name::<std::io::Error>())
.assert_see("Server Error")
.assert_dont_see("Internal Server Error");
app.post("/users")
.form([("name", "Taylor")])
.await
.assert_unprocessable()
.assert_see("Unprocessable Content")
.assert_dont_see("Caused by");
}
#[tokio::test]
async fn failures_say_where_they_happened_in_debug_mode() {
let app = app(true, &Arc::default());
let response = app.get("/disk").header("accept", "application/json").await;
let json = response.json();
assert_eq!(json["file"], "tests/errors.rs", "the `?` in `disk`: {json}");
assert!(json["line"].as_u64().is_some(), "{json}");
app.get("/disk")
.await
.assert_see(type_name::<std::io::Error>())
.assert_see("tests/errors.rs:");
}
#[tokio::test]
async fn debug_pages_highlight_the_callers_source_from_the_app_base_path() {
let line = line!() + 1;
let error = laravel::abort_with(500, "Cannot render <script> markup");
let root = tempfile::tempdir().unwrap();
let file = root.path().join(file!());
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
let mut source = vec!["// outside the excerpt"; line as usize + 20];
source[line as usize - 2] = "// before the failure";
source[line as usize - 1] = "return Err(\"<script>alert('source')</script>\");";
source[line as usize] = "// after the failure";
std::fs::write(&file, source.join("\n")).unwrap();
let app = Application::configure()
.replace_env(Env::from_iter([
("APP_BASE_PATH", root.path().to_str().unwrap()),
("APP_DEBUG", "true"),
]))
.with_routing(move |routing, _| {
routing.routes(move |route: &mut Router| {
route.get("/broken", move || {
let error = error.clone();
async move { Err::<(), _>(error) }
});
});
})
.create();
app.get("/broken")
.header("authorization", "Bearer hidden-token")
.header("proxy-authorization", "Basic hidden-proxy-token")
.header("cookie", "secret=hidden-cookie")
.header("x-note", "<b>header</b>")
.await
.assert_internal_server_error()
.assert_see_html("Caller location</h2>")
.assert_see(&format!("{}:{line}", file!()))
.assert_see_html(&format!(
r#"aria-current="true"><span class="line-number">{line}</span>return Err("<script>alert('source')</script>");"#,
))
.assert_see("// before the failure")
.assert_see("// after the failure")
.assert_see_html("Cannot render <script> markup")
.assert_dont_see_html("<script>alert('source')</script>")
.assert_see_html("<b>header</b>")
.assert_dont_see("hidden-token")
.assert_dont_see("hidden-proxy-token")
.assert_dont_see("hidden-cookie");
std::fs::remove_file(file).unwrap();
app.get("/broken")
.await
.assert_internal_server_error()
.assert_see(&format!("{}:{line}", file!()))
.assert_see("Source unavailable.");
}
fn find_report() -> Option<&'static str> {
None
}
const PANIC_LINE: u32 = line!() + 2;
async fn show_report() -> &'static str {
find_report().expect("the report exists")
}
#[tokio::test]
async fn debug_pages_show_where_a_handler_panicked() {
let app = Application::configure()
.replace_env(Env::from_iter([
("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
("APP_DEBUG", "true"),
]))
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.get("/report", show_report);
});
})
.create();
app.get("/report")
.await
.assert_internal_server_error()
.assert_see_html("Panic location</h2>")
.assert_see(&format!("tests/errors.rs:{PANIC_LINE}"))
.assert_see_html(&format!(
r#"aria-current="true"><span class="line-number">{PANIC_LINE}</span>"#
))
.assert_see("the report exists");
let json = app.get("/report").header("accept", "application/json").await.json();
assert_eq!(
(&json["file"], &json["line"]),
(&json!("tests/errors.rs"), &json!(PANIC_LINE)),
"{json}"
);
}
struct MissingGateway;
struct FactoryGateway;
async fn injected_handler(_gateway: laravel::container::Inject<MissingGateway>) {}
#[laravel::http::middleware]
async fn pass_through(request: Request, next: laravel::http::Next) -> laravel::http::Response {
next.run(request).await
}
const EXPLICIT_RESOLUTION_LINE: u32 = line!() + 2;
async fn explicit_resolution() -> laravel::Result<()> {
laravel::resolve::<MissingGateway>().await?;
Ok(())
}
const INJECTION_ROUTE_LINE: u32 = line!() + 2;
fn injection_routes(route: &mut Router) {
route.get("/injected", injected_handler);
route.get("/explicit", explicit_resolution);
route.get("/factory", |_: laravel::container::Inject<FactoryGateway>| async {});
route.get("/factory-explicit", || async {
laravel::resolve::<FactoryGateway>().await?;
Ok::<_, laravel::Error>(())
});
resource_injection_routes(route);
fallback_injection_routes(route);
}
const RESOURCE_INJECTION_LINE: u32 = line!() + 2;
fn resource_injection_routes(route: &mut Router) {
let resource = laravel::routing::Resource::new().index(injected_handler);
route.resource("injected-resource", resource);
}
const FALLBACK_INJECTION_LINE: u32 = line!() + 2;
fn fallback_injection_routes(route: &mut Router) {
route.fallback(injected_handler);
}
#[tokio::test]
async fn missing_services_point_to_the_application_call() {
let factory_line = line!() + 1;
let factory_error = laravel::abort_with(500, "gateway credentials are invalid");
let app = Application::configure()
.replace_env(Env::from_iter([
("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
("APP_DEBUG", "true"),
]))
.with_middleware(|middleware, _| {
middleware.append(pass_through);
})
.with_services(move |services| {
services.singleton(move |_| {
let error = factory_error.clone();
async move { Err::<FactoryGateway, _>(error) }
});
})
.with_routing(|routing, _| {
routing.routes(injection_routes);
})
.create();
for (path, line) in [
("/injected", INJECTION_ROUTE_LINE),
("/explicit", EXPLICIT_RESOLUTION_LINE),
("/injected-resource", RESOURCE_INJECTION_LINE),
("/fallback", FALLBACK_INJECTION_LINE),
] {
let (logs, _guard) = crate::logging::Lines::capture();
app.get(path)
.await
.assert_internal_server_error()
.assert_see("MissingGateway")
.assert_see_html(&format!(
r#"aria-current="true"><span class="line-number">{line}</span>"#
));
let log = logs.report();
let location = log["fields"]["location"].as_str().unwrap();
assert!(location.starts_with(&format!("tests/errors.rs:{line}:")), "{log}");
let json = app.get(path).header("accept", "application/json").await.json();
assert_eq!(json["file"], "tests/errors.rs");
assert_eq!(json["line"], line);
}
for path in ["/factory", "/factory-explicit"] {
let json = app.get(path).header("accept", "application/json").await.json();
assert_eq!(json["file"], "tests/errors.rs");
assert_eq!(json["line"], factory_line);
}
}
const MISSING_VIEW_LINE: u32 = line!() + 2;
async fn missing_view() -> laravel::view::View {
laravel::view("missing-diagnostic-page", ())
}
const MISSING_VIEW_ROUTE_LINE: u32 = line!() + 2;
fn missing_view_routes(route: &mut Router) {
route.view("/view-shortcut", "missing-diagnostic-page");
route.get("/missing-view", missing_view);
}
#[tokio::test]
async fn missing_views_point_to_where_the_view_was_created() {
let app = Application::configure()
.replace_env(Env::from_iter([
("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
("APP_DEBUG", "true"),
]))
.with_middleware(|middleware, _| {
middleware.append(pass_through);
})
.with_routing(|routing, _| {
routing.routes(missing_view_routes);
})
.create();
for (path, line) in [
("/missing-view", MISSING_VIEW_LINE),
("/view-shortcut", MISSING_VIEW_ROUTE_LINE),
] {
app.get(path)
.await
.assert_internal_server_error()
.assert_see("missing-diagnostic-page")
.assert_see_html(&format!(
r#"aria-current="true"><span class="line-number">{line}</span>"#
));
let json = app.get(path).header("accept", "application/json").await.json();
assert_eq!(json["file"], "tests/errors.rs");
assert_eq!(json["line"], line);
}
}
#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn undefined_database_connections_point_to_the_application_call() {
let named_line = line!() + 2;
async fn named() -> laravel::Result<()> {
laravel::db::connection("missing-analytics")?;
Ok(())
}
let default_line = line!() + 2;
async fn default() -> laravel::Result<()> {
laravel::db::default_connection()?;
Ok(())
}
let app = Application::configure()
.replace_env(Env::from_iter([
("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
("APP_DEBUG", "true"),
]))
.with_config(|config, _| {
config.database.default = "missing-default".into();
})
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.get("/named", named);
route.get("/default", default);
});
})
.create();
for (path, line, name) in [
("/named", named_line, "missing-analytics"),
("/default", default_line, "missing-default"),
] {
let (logs, _guard) = crate::logging::Lines::capture();
app.get(path)
.await
.assert_internal_server_error()
.assert_see(&format!("database connection `{name}` isn't defined"))
.assert_see_html(&format!(
r#"aria-current="true"><span class="line-number">{line}</span>"#
));
let log = logs.report();
let location = log["fields"]["location"].as_str().unwrap();
assert!(location.starts_with(&format!("tests/errors.rs:{line}:")), "{log}");
let json = app.get(path).header("accept", "application/json").await.json();
assert_eq!(json["file"], "tests/errors.rs");
assert_eq!(json["line"], line);
}
}
#[cfg(feature = "database-sqlite")]
#[tokio::test]
async fn debug_pages_select_the_application_frame_for_async_database_errors() {
let query_line = line!() + 2;
async fn broken_query() -> laravel::Result<()> {
laravel::db::query!("SELEC id FROM users").select().await?;
Ok(())
}
let app = Application::configure()
.replace_env(Env::from_iter([
("APP_BASE_PATH", env!("CARGO_MANIFEST_DIR")),
("APP_DEBUG", "true"),
("DATABASE_URL", "sqlite::memory:"),
]))
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.get("/broken-query", broken_query);
});
})
.create();
app.get("/broken-query")
.await
.assert_internal_server_error()
.assert_see_html("Application frame</h2>")
.assert_see(&format!("tests/errors.rs:{query_line}"))
.assert_see_html(&format!(
r#"aria-current="true"><span class="line-number">{query_line}</span>"#
))
.assert_see("syntax error");
}
#[tokio::test]
async fn anyhow_errors_convert_with_the_question_mark() {
let response = quiet_app().post("/dispatch").await;
response.assert_internal_server_error();
let error = response.error().expect("the error");
assert_eq!(error.to_string(), "the queue is down");
assert_eq!(error.type_name(), "anyhow::Error");
}
#[rstest::rstest]
#[case::abort("/invoices/42/send", 404, "Not Found", "loading invoice 42 for tenant acme")]
#[case::error_context("/checkout-with-error-context", 402, "The card was declined", "charging order 7")]
#[case::anyhow_context(
"/checkout-with-context",
402,
"The card was declined",
"The order can't be paid for"
)]
#[tokio::test]
async fn client_errors_show_the_message_of_the_error_that_set_their_status(
#[case] path: &str,
#[case] status: u16,
#[case] message: &str,
#[case] context: &str,
) {
let json = app(true, &Arc::default())
.post(path)
.header("accept", "application/json")
.await;
json.assert_status(status).assert_json(json!({ "message": message }));
assert!(json.error().is_some_and(|error| error.to_string().contains(context)));
let production = quiet_app();
production
.post(path)
.header("accept", "application/json")
.await
.assert_status(status)
.assert_json(json!({ "message": message }));
let reason = StatusCode::from_u16(status).unwrap().canonical_reason().unwrap();
production
.post(path)
.await
.assert_status(status)
.assert_see(reason)
.assert_dont_see(context);
}
#[cfg(feature = "database")]
#[rstest::rstest]
#[case::model("/posts/abc", "No query results for model `Post` with the key `abc`.")]
#[case::record("/posts/sole", "No query results.")]
#[tokio::test]
async fn missing_rows_give_their_message_as_json_and_a_not_found_page(#[case] path: &str, #[case] detail: &str) {
for app in [app(true, &Arc::default()), quiet_app()] {
app.get(path)
.header("accept", "application/json")
.await
.assert_not_found()
.assert_json(json!({ "message": detail }));
app.get(path)
.await
.assert_not_found()
.assert_see_html("<title>404 Not Found</title>")
.assert_dont_see(detail);
}
let production = quiet_app();
production
.get("/posts/deleted")
.header("accept", "application/json")
.await
.assert_not_found()
.assert_json(json!({ "message": "That post was deleted." }));
}
#[tokio::test]
async fn context_is_reported_with_its_causes() {
let reported = Arc::default();
let app = app(true, &reported);
app.post("/upload")
.await
.assert_internal_server_error()
.assert_reported::<std::io::Error>()
.assert_see_html("The upload can't be saved")
.assert_see("Caused by")
.assert_see("the disk is full");
assert_eq!(reported.lock().unwrap()[0], "the disk is full");
}
fn checkout_routes(routing: &mut laravel::routing::Routing, _: &Config) {
routing.api(|route: &mut Router| {
route.post("/checkout", checkout);
});
routing.routes(|route: &mut Router| {
route.post("/checkout", checkout);
});
}
#[tokio::test]
async fn errors_on_api_routes_render_as_json_whatever_the_client_accepts() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(checkout_routes)
.with_errors(|errors, _| {
errors.status::<PaymentFailed>(402);
})
.create();
app.post("/api/checkout")
.await
.assert_status(402)
.assert_json(json!({ "message": "The card was declined" }));
app.post("/checkout")
.await
.assert_status(402)
.assert_header("content-type", "text/html; charset=utf-8");
}
struct BillingProvider;
impl ServiceProvider for BillingProvider {
fn register(&self, app: &mut laravel::container::Registrar) {
app.errors()
.status::<PaymentFailed>(409)
.render(|_: &PaymentFailed, _request, status| Some((status, "The package's page")));
}
}
fn billing_app(configure: impl FnOnce(&mut Errors, &Config) + 'static) -> Application {
Application::configure()
.replace_env(Env::default())
.with_routing(checkout_routes)
.with_errors(configure)
.with_providers(|providers| {
providers.add(BillingProvider);
})
.create()
}
#[tokio::test]
async fn providers_give_their_errors_a_status_and_a_renderer() {
billing_app(|_, _| {})
.post("/checkout")
.await
.assert_status(409)
.assert_see("The package's page");
}
#[tokio::test]
async fn the_applications_statuses_and_renderers_replace_a_providers() {
billing_app(|errors, _| {
errors
.status::<PaymentFailed>(402)
.render(|_: &PaymentFailed, _request, status| Some((status, "The application's page")));
})
.post("/checkout")
.await
.assert_status(402)
.assert_see("The application's page");
}
#[tokio::test]
async fn renderers_that_decline_fall_back_to_earlier_ones() {
billing_app(|errors, _| {
errors.render(|_: &PaymentFailed, request, _status| request.expects_json().then_some("The application's JSON"));
})
.post("/checkout")
.await
.assert_status(409)
.assert_see("The package's page");
}
#[tokio::test]
async fn the_application_configures_errors_with_the_final_config() {
Application::configure()
.replace_env(Env::from_iter([("APP_NAME", "Billing")]))
.with_routing(checkout_routes)
.with_errors(|errors, config| {
let name = config.app.name.clone();
errors.render(move |_: &PaymentFailed, _request, status| {
Some((status, format!("{name} can't take payments right now")))
});
})
.create()
.post("/checkout")
.await
.assert_internal_server_error()
.assert_see("Billing can't take payments right now");
}
#[derive(Debug, thiserror::Error, laravel::errors::Status)]
#[error("This time slot is already booked")]
#[status(409)]
struct BookingConflict;
mod refunds {
use laravel::http::{Next, Request, Response, StatusCode};
#[laravel::http::middleware]
pub(super) async fn error(request: Request, next: Next) -> Response {
next.run(request).await
}
#[derive(Debug, thiserror::Error, laravel::errors::Status)]
#[status(400)]
pub(super) enum Refund {
#[error("The card was declined: {reason}")]
#[status(StatusCode::PAYMENT_REQUIRED)]
Declined { reason: &'static str },
#[error("The amount {0} is below the minimum")]
#[status(422)]
BelowMinimum(u64),
#[error("The refund window has closed")]
Closed,
}
}
#[derive(Debug, thiserror::Error, laravel::errors::Status)]
#[error("The booking service is unavailable")]
#[status(503)]
struct BookingsUnavailable(#[source] BookingConflict);
#[derive(Debug, thiserror::Error, laravel::errors::Status)]
enum Ledger {
#[error("The ledger is locked")]
#[status(423)]
Locked,
#[error("The ledger is unreachable")]
Unreachable,
}
#[tokio::test]
async fn derived_statuses_respond_by_type_and_variant_unless_the_application_maps_the_type() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.routes(|route| {
route.post("/bookings", || async {
Err::<(), _>(BookingConflict).context("Booking failed")?;
Ok::<_, laravel::Error>(())
});
route
.post("/declined", || async {
Err::<(), _>(Refund::Declined { reason: "expired" })?;
Ok::<_, laravel::Error>(())
})
.middleware(refunds::error);
route.post("/small", || async {
Err::<(), _>(Refund::BelowMinimum(10))?;
Ok::<_, laravel::Error>(())
});
route.post("/closed", || async {
Err::<(), _>(Refund::Closed)?;
Ok::<_, laravel::Error>(())
});
route.post("/locked", || async {
Err::<(), _>(Ledger::Locked)?;
Ok::<_, laravel::Error>(())
});
route.post("/unreachable", || async {
Err::<(), _>(Ledger::Unreachable)?;
Ok::<_, laravel::Error>(())
});
});
})
.with_errors(|errors, _| {
errors.status::<Ledger>(503);
})
.create();
for (uri, status) in [
("/bookings", 409),
("/declined", 402),
("/small", 422),
("/closed", 400),
("/locked", 503),
("/unreachable", 503),
] {
app.post(uri)
.header("accept", "application/json")
.await
.assert_status(status);
}
app.post("/bookings")
.header("accept", "application/json")
.await
.assert_json(json!({ "message": "This time slot is already booked" }))
.assert_nothing_reported();
}
#[test]
fn errors_report_their_types_derived_status_before_they_are_rendered() {
let statuses = [
laravel::Error::from(BookingConflict).status(),
laravel::Error::from(Refund::BelowMinimum(10)).status(),
laravel::Error::from(Refund::Closed).status(),
laravel::Error::from(Ledger::Unreachable).status(),
laravel::Error::from(InvalidInput::new().with("email", "Taken.")).status(),
laravel::Error::new(418, BookingConflict).status(),
];
assert_eq!(statuses.map(|status| status.as_u16()), [409, 422, 400, 500, 422, 418]);
}
fn bookings() -> Application {
Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.routes(|route| {
route.post("/bookings", || async {
Err::<(), _>(BookingConflict).context("Booking failed")?;
Ok::<_, laravel::Error>(())
});
route.post("/refunds", || async {
Err::<(), _>(Refund::Declined { reason: "expired" })?;
Ok::<_, laravel::Error>(())
});
route.post("/paid", || async { "paid" });
route.post("/unavailable", || async {
Err::<(), _>(BookingsUnavailable(BookingConflict))?;
Ok::<_, laravel::Error>(())
});
});
})
.create()
}
#[tokio::test]
async fn tests_assert_the_type_and_fields_of_a_response_error() {
let app = bookings();
app.post("/bookings")
.await
.assert_status(409)
.assert_error::<BookingConflict>();
app.post("/refunds")
.await
.assert_error_where(|error: &Refund| matches!(error, Refund::Declined { reason: "expired" }));
app.post("/unavailable")
.await
.assert_status(503)
.assert_error::<BookingsUnavailable>()
.assert_error::<BookingConflict>();
}
#[tokio::test]
#[should_panic(expected = "Ledger`\n\n409 Conflict")]
async fn error_assertions_fail_for_another_type() {
bookings().post("/bookings").await.assert_error::<Ledger>();
}
#[tokio::test]
#[should_panic(expected = "Refund` to pass the check, but it was Declined { reason: \"expired\" }")]
async fn error_assertions_fail_when_the_check_does() {
bookings()
.post("/refunds")
.await
.assert_error_where(|error: &Refund| matches!(error, Refund::Closed));
}
#[tokio::test]
#[should_panic(expected = "BookingConflict`, but it has no error\n\n200 OK")]
async fn error_assertions_fail_without_an_error() {
bookings().post("/paid").await.assert_error::<BookingConflict>();
}
#[derive(Debug, thiserror::Error)]
#[error("There's no such page")]
struct NoSuchPage;
fn no_such_page_routes(route: &mut Router) {
route.get("/missing", || async {
Err::<(), _>(laravel::Error::new(404, NoSuchPage))
});
route.get("/also-missing", || async {
Err::<(), _>(laravel::Error::new(404, NoSuchPage))
});
}
#[tokio::test]
async fn a_renderer_that_fails_is_rendered_and_reported_in_its_place() {
let reported = Arc::new(Mutex::new(Vec::new()));
let app = Application::configure()
.replace_env(Env::from_iter([("APP_DEBUG", "false")]))
.with_routing(|routing, _| {
routing.routes(no_such_page_routes);
})
.with_errors({
let reported = Arc::clone(&reported);
move |errors, _| {
errors
.render(|_: &NoSuchPage, _request, _status| Some(laravel::view("errors.no-such-view", ())))
.report_all(move |error| reported.lock().unwrap().push(error.to_string()));
}
})
.create();
for uri in ["/missing", "/also-missing"] {
let response = app.get(uri).await;
response.assert_internal_server_error();
assert!(!response.text().is_empty(), "{uri} rendered an empty page");
}
let reported = reported.lock().unwrap();
assert_eq!(reported.len(), 2, "{reported:?}");
assert!(
reported.iter().all(|error| error.contains("errors.no-such-view")),
"{reported:?}"
);
}
struct PanicsBeforeRouting;
impl laravel::http::Middleware for PanicsBeforeRouting {
async fn handle(&self, _request: Request, _next: laravel::http::Next) -> laravel::Result<laravel::http::Response> {
panic!("the middleware failed");
}
}
#[tokio::test]
async fn panics_in_global_middleware_are_rendered() {
Application::configure()
.replace_env(Env::from_iter([("APP_DEBUG", "true")]))
.with_middleware(|middleware, _| {
middleware.append(PanicsBeforeRouting);
})
.create()
.get("/")
.await
.assert_internal_server_error()
.assert_see("the middleware failed");
}
#[tokio::test]
async fn renderers_can_render_errors_with_a_file() {
let pages = TempDir::with_files("error-pages", &[("404.html", "<h1>No such page</h1>")]);
let page = pages.join("404.html");
let app = Application::configure()
.replace_env(Env::from_iter([("APP_DEBUG", "false")]))
.with_routing(|routing, _| {
routing.routes(no_such_page_routes);
})
.with_errors(move |errors, _| {
errors.render(move |_: &NoSuchPage, _request, status| Some((status, File::new(page.clone()))));
})
.create();
let app = WithDir::new(app, pages);
for uri in ["/missing", "/also-missing"] {
app.get(uri)
.await
.assert_not_found()
.assert_header("content-type", "text/html")
.assert_see("<h1>No such page</h1>");
}
}
#[tokio::test]
async fn a_renderer_that_panics_gets_the_built_in_page() {
let reported = Arc::new(Mutex::new(Vec::new()));
let app = Application::configure()
.replace_env(Env::from_iter([("APP_DEBUG", "false")]))
.with_routing(|routing, _| {
routing.routes(no_such_page_routes);
})
.with_errors({
let reported = Arc::clone(&reported);
move |errors, _| {
errors
.render(|_: &NoSuchPage, _request, _status| -> Option<&str> { panic!("the renderer failed") })
.report_all(move |error| reported.lock().unwrap().push(error.to_string()));
}
})
.create();
app.get("/missing")
.await
.assert_internal_server_error()
.assert_see("Server Error");
app.get("/missing")
.header("accept", "application/json")
.await
.assert_internal_server_error()
.assert_exact_json(json!({ "message": "Server Error" }));
let reported = reported.lock().unwrap();
assert_eq!(reported.len(), 2, "{reported:?}");
assert!(
reported.iter().all(|error| error.contains("the renderer failed")),
"{reported:?}"
);
}
#[tokio::test]
async fn a_renderer_that_panics_in_debug_mode_answers_json_with_the_panic() {
let app = Application::configure()
.replace_env(Env::from_iter([("APP_DEBUG", "true")]))
.with_routing(|routing, _| {
routing.routes(no_such_page_routes);
})
.with_errors(|errors, _| {
errors.render(|_: &NoSuchPage, _request, _status| -> Option<&str> { panic!("the renderer failed") });
})
.create();
let response = app.get("/missing").header("accept", "text/html").await;
response
.assert_internal_server_error()
.assert_header("content-type", "application/json");
let message = response.json()["message"].as_str().unwrap().to_owned();
assert!(message.starts_with("panic at tests/errors.rs:"), "{message}");
assert!(message.ends_with(": the renderer failed"), "{message}");
assert_eq!(response.json().as_object().unwrap().len(), 1, "{}", response.text());
}
#[laravel::http::middleware]
async fn requires_api_key(request: Request, next: laravel::http::Next) -> laravel::Result<laravel::http::Response> {
match request.header("x-api-key") {
Some("explode") => panic!("the group middleware failed"),
Some(_) => Ok(next.run(request).await),
None => Err(laravel::abort(401)),
}
}
#[laravel::http::middleware]
async fn requires_terms(mut request: Request, next: laravel::http::Next) -> laravel::Result<laravel::http::Response> {
request.load_input().await?;
#[derive(serde::Deserialize)]
struct Terms {
terms: Option<serde_json::Value>,
}
if request.parse::<Terms>()?.terms.is_none() {
laravel::validation::invalid!(terms => "Accept the terms.");
}
Ok(next.run(request).await)
}
fn group_middleware_app() -> Application {
Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.app.key = Some(laravel::crypt::Encrypter::generate_key(
laravel::crypt::Cipher::Aes256Cbc,
));
config.session.driver = laravel::config::session::Driver::Memory;
})
.with_routing(|routing, _| {
routing
.web(|route: &mut Router| {
route.post("/posts", || async { "stored" });
})
.api(|route: &mut Router| {
route.get("/status", || async { "ok" });
});
})
.with_middleware(|middleware, _| {
middleware.api(|api| {
api.append(requires_api_key);
});
middleware.web(|web| {
web.append(requires_terms);
});
})
.create()
}
#[tokio::test]
async fn errors_from_api_group_middleware_render_as_json() {
group_middleware_app()
.get("/api/status")
.await
.assert_unauthorized()
.assert_json(json!({ "message": "Unauthorized" }));
}
#[tokio::test]
async fn panics_in_api_group_middleware_render_as_json() {
group_middleware_app()
.get("/api/status")
.header("x-api-key", "explode")
.await
.assert_internal_server_error()
.assert_json(json!({ "message": "Server Error" }));
}
#[tokio::test]
async fn invalid_input_from_web_group_middleware_redirects_back_with_errors() {
group_middleware_app()
.post("/posts")
.header("sec-fetch-site", "same-origin")
.header("referer", "http://localhost/posts/create")
.form([("title", "Hello")])
.await
.assert_redirect_to("http://localhost/posts/create")
.assert_invalid(&["terms"]);
}
#[tokio::test]
async fn application_renderers_replace_the_built_in_responses_for_invalid_input_and_rate_limits() {
let app = Application::configure()
.replace_env(Env::default())
.with_config(|config, _| {
config.app.key = Some(laravel::crypt::Encrypter::generate_key(
laravel::crypt::Cipher::Aes256Cbc,
));
config.session.driver = laravel::config::session::Driver::Memory;
})
.with_routing(|routing, _| {
routing.web(|route| {
route.post("/invite", invite);
route.get("/limited", || async {
laravel::rate_limit::attempt("pin", laravel::rate_limit::Limit::per_minute(1)).await??;
Ok::<_, laravel::Error>("allowed")
});
});
})
.with_errors(|errors, _| {
errors
.render(|_: &InvalidInput, _request, status| Some((status, "Please check the form")))
.render(|_: &laravel::rate_limit::TooManyAttempts, _request, status| {
Some((status, "Please slow down"))
});
})
.create();
app.post("/invite")
.header("sec-fetch-site", "same-origin")
.header("referer", "http://localhost/invitations")
.form([("email", "taylor@example.com")])
.await
.assert_status(422)
.assert_see("Please check the form")
.assert_session_missing("errors");
app.post("/invite")
.header("accept", "application/json")
.await
.assert_status(422)
.assert_see("Please check the form");
app.get("/limited").await.assert_ok();
app.get("/limited")
.await
.assert_status(429)
.assert_see("Please slow down")
.assert_header("retry-after", "60")
.assert_header("x-ratelimit-limit", "1")
.assert_header("x-ratelimit-remaining", "0");
}
#[tokio::test]
async fn a_reporter_that_panics_doesnt_stop_the_response() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.routes(|route: &mut Router| {
route.get("/disk", disk);
route.get("/recommendations", || async {
laravel::report(std::io::Error::other("no recommendations"));
"no recommendations today"
});
});
})
.with_errors(|errors, _| {
errors.report_all(|_| panic!("the error tracker is down"));
})
.create();
app.get("/disk")
.header("accept", "application/json")
.await
.assert_internal_server_error()
.assert_json(json!({ "message": "Server Error" }));
app.get("/disk")
.await
.assert_internal_server_error()
.assert_see("Server Error");
app.get("/recommendations")
.await
.assert_ok()
.assert_see("no recommendations today");
}