Update tests to use new #[catch] macro

This commit is contained in:
Matthew Pomes 2024-07-02 13:18:09 -05:00
parent f8c8bb87e6
commit dea224ff98
No known key found for this signature in database
GPG Key ID: B8C0D93B8D8FBDB7
12 changed files with 67 additions and 76 deletions

View File

@ -1,6 +1,6 @@
use devise::{Spanned, SpanWrapped, Result, FromMeta};
use devise::ext::{SpanDiagnosticExt, TypeExt};
use indexmap::{IndexSet, IndexMap};
use indexmap::IndexSet;
use proc_macro2::Span;
use crate::attribute::suppress::Lint;

View File

@ -2,7 +2,6 @@
#[macro_use] extern crate rocket;
use rocket::http::uri::Origin;
use rocket::request::Request;
async fn noop() { }
@ -19,7 +18,7 @@ async fn repeated_query(sort: Vec<&str>) -> &str {
}
#[catch(404)]
async fn not_found(req: &Request<'_>) -> String {
async fn not_found(uri: &Origin<'_>) -> String {
noop().await;
format!("{} not found", req.uri())
format!("{} not found", uri)
}

View File

@ -5,14 +5,18 @@
#[macro_use] extern crate rocket;
use rocket::{Request, Rocket, Build};
use rocket::{Rocket, Build};
use rocket::local::blocking::Client;
use rocket::http::Status;
use rocket::http::{Status, uri::Origin};
#[catch(404)] fn not_found_0() -> &'static str { "404-0" }
#[catch(404)] fn not_found_1(_: &Request<'_>) -> &'static str { "404-1" }
#[catch(404)] fn not_found_2(_: Status, _: &Request<'_>) -> &'static str { "404-2" }
#[catch(default)] fn all(_: Status, r: &Request<'_>) -> String { r.uri().to_string() }
#[catch(404)]
fn not_found_0() -> &'static str { "404-0" }
#[catch(404)]
fn not_found_1() -> &'static str { "404-1" }
#[catch(404, status = "<_s>")]
fn not_found_2(_s: Status) -> &'static str { "404-2" }
#[catch(default, status = "<_s>")]
fn all(_s: Status, uri: &Origin<'_>) -> String { uri.to_string() }
#[test]
fn test_simple_catchers() {
@ -37,10 +41,14 @@ fn test_simple_catchers() {
}
#[get("/<code>")] fn forward(code: u16) -> Status { Status::new(code) }
#[catch(400)] fn forward_400(status: Status, _: &Request<'_>) -> String { status.code.to_string() }
#[catch(404)] fn forward_404(status: Status, _: &Request<'_>) -> String { status.code.to_string() }
#[catch(444)] fn forward_444(status: Status, _: &Request<'_>) -> String { status.code.to_string() }
#[catch(500)] fn forward_500(status: Status, _: &Request<'_>) -> String { status.code.to_string() }
#[catch(400, status = "<status>")]
fn forward_400(status: Status) -> String { status.code.to_string() }
#[catch(404, status = "<status>")]
fn forward_404(status: Status) -> String { status.code.to_string() }
#[catch(444, status = "<status>")]
fn forward_444(status: Status) -> String { status.code.to_string() }
#[catch(500, status = "<status>")]
fn forward_500(status: Status) -> String { status.code.to_string() }
#[test]
fn test_status_param() {
@ -60,11 +68,11 @@ fn test_status_param() {
}
#[catch(404)]
fn bad_req_untyped(_: Status, _: &Request<'_>) -> &'static str { "404" }
#[catch(404)]
fn bad_req_string(_: &String, _: Status, _: &Request<'_>) -> &'static str { "404 String" }
#[catch(404)]
fn bad_req_tuple(_: &(), _: Status, _: &Request<'_>) -> &'static str { "404 ()" }
fn bad_req_untyped() -> &'static str { "404" }
#[catch(404, error = "<_e>")]
fn bad_req_string(_e: &String) -> &'static str { "404 String" }
#[catch(404, error = "<_e>")]
fn bad_req_tuple(_e: &()) -> &'static str { "404 ()" }
#[test]
fn test_typed_catchers() {

View File

@ -1,6 +1,7 @@
#[macro_use] extern crate rocket;
use rocket::local::blocking::Client;
use rocket_http::Method;
// Test that raw idents can be used for route parameter names
@ -15,8 +16,8 @@ fn swap(r#raw: String, bare: String) -> String {
}
#[catch(400)]
fn catch(r#raw: &rocket::Request<'_>) -> String {
format!("{}", raw.method())
fn catch(r#raw: Method) -> String {
format!("{}", raw)
}
#[test]

View File

@ -76,8 +76,7 @@ use super::ErasedError;
/// ```rust,no_run
/// #[macro_use] extern crate rocket;
///
/// use rocket::Request;
/// use rocket::http::Status;
/// use rocket::http::{Status, uri::Origin};
///
/// #[catch(500)]
/// fn internal_error() -> &'static str {
@ -85,13 +84,13 @@ use super::ErasedError;
/// }
///
/// #[catch(404)]
/// fn not_found(req: &Request) -> String {
/// format!("I couldn't find '{}'. Try something else?", req.uri())
/// fn not_found(uri: &Origin) -> String {
/// format!("I couldn't find '{}'. Try something else?", uri)
/// }
///
/// #[catch(default)]
/// fn default(status: Status, req: &Request) -> String {
/// format!("{} ({})", status, req.uri())
/// #[catch(default, status = "<status>")]
/// fn default(status: Status, uri: &Origin) -> String {
/// format!("{} ({})", status, uri)
/// }
///
/// #[launch]
@ -100,13 +99,6 @@ use super::ErasedError;
/// }
/// ```
///
/// A function decorated with `#[catch]` may take zero, one, or two arguments.
/// It's type signature must be one of the following, where `R:`[`Responder`]:
///
/// * `fn() -> R`
/// * `fn(`[`&Request`]`) -> R`
/// * `fn(`[`Status`]`, `[`&Request`]`) -> R`
///
/// See the [`catch`] documentation for full details.
///
/// [`catch`]: crate::catch

View File

@ -379,7 +379,7 @@ impl Rocket<Build> {
///
/// ```rust,no_run
/// # #[macro_use] extern crate rocket;
/// use rocket::Request;
/// use rocket::http::uri::Origin;
///
/// #[catch(500)]
/// fn internal_error() -> &'static str {
@ -387,8 +387,8 @@ impl Rocket<Build> {
/// }
///
/// #[catch(404)]
/// fn not_found(req: &Request) -> String {
/// format!("I couldn't find '{}'. Try something else?", req.uri())
/// fn not_found(uri: &Origin) -> String {
/// format!("I couldn't find '{}'. Try something else?", uri)
/// }
///
/// #[launch]

View File

@ -1,11 +1,10 @@
#[macro_use] extern crate rocket;
use rocket::request::Request;
use rocket::http::CookieJar;
#[catch(404)]
fn not_found(request: &Request<'_>) -> &'static str {
request.cookies().add(("not_found", "404"));
fn not_found(jar: &CookieJar<'_>) -> &'static str {
jar.add(("not_found", "404"));
"404 - Not Found"
}

View File

@ -1981,14 +1981,14 @@ Application processing is fallible. Errors arise from the following sources:
* A routing failure.
If any of these occur, Rocket returns an error to the client. To generate the
error, Rocket invokes the _catcher_ corresponding to the error's status code and
scope. Catchers are similar to routes except in that:
error, Rocket invokes the _catcher_ corresponding to the error's status code,
scope, and type. Catchers are similar to routes except in that:
1. Catchers are only invoked on error conditions.
2. Catchers are declared with the `catch` attribute.
3. Catchers are _registered_ with [`register()`] instead of [`mount()`].
4. Any modifications to cookies are cleared before a catcher is invoked.
5. Error catchers cannot invoke guards.
// 5. Error catchers cannot invoke guards.
6. Error catchers should not fail to produce a response.
7. Catchers are scoped to a path prefix.
@ -2000,26 +2000,20 @@ instance, to declare a catcher for `404 Not Found` errors, you'd write:
# #[macro_use] extern crate rocket;
# fn main() {}
use rocket::Request;
#[catch(404)]
fn not_found(req: &Request) { /* .. */ }
fn not_found() { /* .. */ }
```
Catchers may take zero, one, or two arguments. If the catcher takes one
argument, it must be of type [`&Request`]. It it takes two, they must be of type
[`Status`] and [`&Request`], in that order. As with routes, the return type must
implement `Responder`. A concrete implementation may look like:
TODO: See the catcher documentation
```rust
# #[macro_use] extern crate rocket;
# fn main() {}
# use rocket::Request;
# use rocket::http::uri::Origin;
#[catch(404)]
fn not_found(req: &Request) -> String {
format!("Sorry, '{}' is not a valid path.", req.uri())
fn not_found(uri: &Origin) -> String {
format!("Sorry, '{}' is not a valid path.", uri)
}
```
@ -2032,8 +2026,7 @@ looks like:
```rust
# #[macro_use] extern crate rocket;
# use rocket::Request;
# #[catch(404)] fn not_found(req: &Request) { /* .. */ }
# #[catch(404)] fn not_found() { /* .. */ }
fn main() {
rocket::build().register("/", catchers![not_found]);
@ -2106,8 +2099,8 @@ similarly be registered with [`register()`]:
use rocket::Request;
use rocket::http::Status;
#[catch(default)]
fn default_catcher(status: Status, request: &Request) { /* .. */ }
#[catch(default, status = "<status>")]
fn default_catcher(status: Status) { /* .. */ }
#[launch]
fn rocket() -> _ {

View File

@ -25,19 +25,19 @@ fn forced_error() {
assert_eq!(response.into_string().unwrap(), expected.0);
let request = client.get("/405");
let expected = super::default_catcher(Status::MethodNotAllowed, request.inner());
let expected = super::default_catcher(Status::MethodNotAllowed, request.uri());
let response = request.dispatch();
assert_eq!(response.status(), Status::MethodNotAllowed);
assert_eq!(response.into_string().unwrap(), expected.1);
let request = client.get("/533");
let expected = super::default_catcher(Status::new(533), request.inner());
let expected = super::default_catcher(Status::new(533), request.uri());
let response = request.dispatch();
assert_eq!(response.status(), Status::new(533));
assert_eq!(response.into_string().unwrap(), expected.1);
let request = client.get("/700");
let expected = super::default_catcher(Status::InternalServerError, request.inner());
let expected = super::default_catcher(Status::InternalServerError, request.uri());
let response = request.dispatch();
assert_eq!(response.status(), Status::InternalServerError);
assert_eq!(response.into_string().unwrap(), expected.1);
@ -51,8 +51,7 @@ fn test_hello_invalid_age() {
let request = client.get(format!("/hello/{}", path));
let expected = super::param_error(
&IntErr(path.split_once("/").unwrap().1.parse::<i8>().unwrap_err()),
Status::UnprocessableEntity,
request.inner()
request.uri()
);
let response = request.dispatch();
assert_eq!(response.status(), Status::UnprocessableEntity);
@ -62,7 +61,7 @@ fn test_hello_invalid_age() {
{
let path = &"foo/bar/baz";
let request = client.get(format!("/hello/{}", path));
let expected = super::hello_not_found(request.inner());
let expected = super::hello_not_found(request.uri());
let response = request.dispatch();
assert_eq!(response.status(), Status::NotFound);
assert_eq!(response.into_string().unwrap(), expected.0);

View File

@ -122,7 +122,7 @@ fn maybe_redir(name: &str) -> Result<&'static str, Redirect> {
/***************************** `content` Responders ***************************/
use rocket::Request;
use rocket::http::{Accept, uri::Origin};
use rocket::response::content;
// NOTE: This example explicitly uses the `RawJson` type from
@ -144,14 +144,14 @@ fn json() -> content::RawJson<&'static str> {
}
#[catch(404)]
fn not_found(request: &Request<'_>) -> content::RawHtml<String> {
let html = match request.format() {
Some(ref mt) if !(mt.is_xml() || mt.is_html()) => {
fn not_found(format: Option<&Accept>, uri: &Origin) -> content::RawHtml<String> {
let html = match format {
Some(ref mt) if !mt.media_types().any(|m| m.is_xml() || m.is_html()) => {
format!("<p>'{}' requests are not supported.</p>", mt)
}
_ => format!("<p>Sorry, '{}' is an invalid path! Try \
/hello/&lt;name&gt;/&lt;age&gt; instead.</p>",
request.uri())
uri)
};
content::RawHtml(html)

View File

@ -1,4 +1,4 @@
use rocket::Request;
use rocket::http::uri::Origin;
use rocket::response::Redirect;
use rocket_dyn_templates::{Template, handlebars, context};
@ -28,9 +28,9 @@ pub fn about() -> Template {
}
#[catch(404)]
pub fn not_found(req: &Request<'_>) -> Template {
pub fn not_found(uri: &Origin<'_>) -> Template {
Template::render("hbs/error/404", context! {
uri: req.uri()
uri,
})
}

View File

@ -1,4 +1,4 @@
use rocket::Request;
use rocket::http::uri::Origin;
use rocket::response::Redirect;
use rocket_dyn_templates::{Template, tera::Tera, context};
@ -25,9 +25,9 @@ pub fn about() -> Template {
}
#[catch(404)]
pub fn not_found(req: &Request<'_>) -> Template {
pub fn not_found(uri: &Origin<'_>) -> Template {
Template::render("tera/error/404", context! {
uri: req.uri()
uri,
})
}