Cargo fmt (#42)

This commit is contained in:
Yong Wen Chua 2018-07-18 13:26:33 +08:00 committed by GitHub
parent 4db0969584
commit 7954d9d078
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 141 additions and 62 deletions

View File

@ -5,8 +5,8 @@ extern crate rocket_cors;
use std::io::Cursor; use std::io::Cursor;
use rocket::Response;
use rocket::http::Method; use rocket::http::Method;
use rocket::Response;
use rocket_cors::{AllowedHeaders, AllowedOrigins, Guard, Responder}; use rocket_cors::{AllowedHeaders, AllowedOrigins, Guard, Responder};
/// Using a `Responder` -- the usual way you would use this /// Using a `Responder` -- the usual way you would use this

View File

@ -5,8 +5,8 @@ extern crate rocket;
extern crate rocket_cors as cors; extern crate rocket_cors as cors;
extern crate serde_json; extern crate serde_json;
use rocket::http::Method;
use cors::{AllowedHeaders, AllowedOrigins, Cors}; use cors::{AllowedHeaders, AllowedOrigins, Cors};
use rocket::http::Method;
fn main() { fn main() {
// The default demonstrates the "All" serialization of several of the settings // The default demonstrates the "All" serialization of several of the settings

View File

@ -5,9 +5,9 @@ extern crate rocket_cors;
use std::io::Cursor; use std::io::Cursor;
use rocket::{Response, State};
use rocket::http::Method; use rocket::http::Method;
use rocket::response::Responder; use rocket::response::Responder;
use rocket::{Response, State};
use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors}; use rocket_cors::{AllowedHeaders, AllowedOrigins, Cors};
/// Using a borrowed Cors /// Using a borrowed Cors

View File

@ -1,8 +1,8 @@
//! Fairing implementation //! Fairing implementation
use std::str::FromStr; use std::str::FromStr;
use rocket::{self, Outcome, Request};
use rocket::http::{self, Header, Status}; use rocket::http::{self, Header, Status};
use rocket::{self, Outcome, Request};
use {actual_request_response, origin, preflight_response, request_headers, validate, Cors, Error}; use {actual_request_response, origin, preflight_response, request_headers, validate, Cors, Error};
@ -123,7 +123,8 @@ impl rocket::fairing::Fairing for Cors {
fn info(&self) -> rocket::fairing::Info { fn info(&self) -> rocket::fairing::Info {
rocket::fairing::Info { rocket::fairing::Info {
name: "CORS", name: "CORS",
kind: rocket::fairing::Kind::Attach | rocket::fairing::Kind::Request kind: rocket::fairing::Kind::Attach
| rocket::fairing::Kind::Request
| rocket::fairing::Kind::Response, | rocket::fairing::Kind::Response,
} }
} }
@ -166,9 +167,9 @@ impl rocket::fairing::Fairing for Cors {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use rocket::Rocket;
use rocket::http::{Method, Status}; use rocket::http::{Method, Status};
use rocket::local::Client; use rocket::local::Client;
use rocket::Rocket;
use {AllOrSome, AllowedHeaders, AllowedOrigins, Cors}; use {AllOrSome, AllowedHeaders, AllowedOrigins, Cors};

View File

@ -5,9 +5,9 @@ use std::fmt;
use std::ops::Deref; use std::ops::Deref;
use std::str::FromStr; use std::str::FromStr;
use rocket::{self, Outcome};
use rocket::http::Status; use rocket::http::Status;
use rocket::request::{self, FromRequest}; use rocket::request::{self, FromRequest};
use rocket::{self, Outcome};
use unicase::UniCase; use unicase::UniCase;
use url; use url;
@ -20,7 +20,11 @@ use url_serde;
#[derive(Eq, PartialEq, Clone, Debug, Hash)] #[derive(Eq, PartialEq, Clone, Debug, Hash)]
#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))] #[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
pub struct HeaderFieldName( pub struct HeaderFieldName(
#[cfg_attr(feature = "serialization", serde(with = "unicase_serde::unicase"))] UniCase<String>, #[cfg_attr(
feature = "serialization",
serde(with = "unicase_serde::unicase")
)]
UniCase<String>,
); );
impl Deref for HeaderFieldName { impl Deref for HeaderFieldName {

View File

@ -501,18 +501,56 @@
//! - [Supplanted W3C CORS Specification](https://www.w3.org/TR/cors/) //! - [Supplanted W3C CORS Specification](https://www.w3.org/TR/cors/)
//! - [Resource Advice](https://w3c.github.io/webappsec-cors-for-developers/#resources) //! - [Resource Advice](https://w3c.github.io/webappsec-cors-for-developers/#resources)
#![deny(const_err, dead_code, deprecated, exceeding_bitshifts, improper_ctypes, missing_docs, #![deny(
mutable_transmutes, no_mangle_const_items, non_camel_case_types, const_err,
non_shorthand_field_patterns, non_upper_case_globals, overflowing_literals, dead_code,
path_statements, plugin_as_library, private_no_mangle_fns, private_no_mangle_statics, deprecated,
stable_features, trivial_casts, trivial_numeric_casts, unconditional_recursion, exceeding_bitshifts,
unknown_crate_types, unreachable_code, unused_allocation, unused_assignments, improper_ctypes,
unused_attributes, unused_comparisons, unused_extern_crates, unused_features, missing_docs,
unused_imports, unused_import_braces, unused_qualifications, unused_must_use, unused_mut, mutable_transmutes,
unused_parens, unused_results, unused_unsafe, unused_variables, variant_size_differences, no_mangle_const_items,
warnings, while_true)] non_camel_case_types,
#![allow(legacy_directory_ownership, missing_copy_implementations, missing_debug_implementations, non_shorthand_field_patterns,
unknown_lints, unsafe_code, intra_doc_link_resolution_failure)] non_upper_case_globals,
overflowing_literals,
path_statements,
plugin_as_library,
private_no_mangle_fns,
private_no_mangle_statics,
stable_features,
trivial_casts,
trivial_numeric_casts,
unconditional_recursion,
unknown_crate_types,
unreachable_code,
unused_allocation,
unused_assignments,
unused_attributes,
unused_comparisons,
unused_extern_crates,
unused_features,
unused_imports,
unused_import_braces,
unused_qualifications,
unused_must_use,
unused_mut,
unused_parens,
unused_results,
unused_unsafe,
unused_variables,
variant_size_differences,
warnings,
while_true
)]
#![allow(
legacy_directory_ownership,
missing_copy_implementations,
missing_debug_implementations,
unknown_lints,
unsafe_code,
intra_doc_link_resolution_failure
)]
#![cfg_attr(test, feature(plugin))] #![cfg_attr(test, feature(plugin))]
#![cfg_attr(test, plugin(rocket_codegen))] #![cfg_attr(test, plugin(rocket_codegen))]
#![doc(test(attr(allow(unused_variables), deny(warnings))))] #![doc(test(attr(allow(unused_variables), deny(warnings))))]
@ -558,13 +596,15 @@ use std::marker::PhantomData;
use std::ops::Deref; use std::ops::Deref;
use std::str::FromStr; use std::str::FromStr;
use rocket::{Outcome, State};
use rocket::http::{self, Status}; use rocket::http::{self, Status};
use rocket::request::{FromRequest, Request}; use rocket::request::{FromRequest, Request};
use rocket::response; use rocket::response;
use rocket::{Outcome, State};
use headers::{AccessControlRequestHeaders, AccessControlRequestMethod, HeaderFieldName, use headers::{
HeaderFieldNamesSet, Origin, Url}; AccessControlRequestHeaders, AccessControlRequestMethod, HeaderFieldName, HeaderFieldNamesSet,
Origin, Url,
};
/// Errors during operations /// Errors during operations
/// ///
@ -722,7 +762,10 @@ impl<T> AllOrSome<T> {
} }
impl AllOrSome<HashSet<Url>> { impl AllOrSome<HashSet<Url>> {
#[deprecated(since = "0.1.3", note = "please use `AllowedOrigins::Some` instead")] #[deprecated(
since = "0.1.3",
note = "please use `AllowedOrigins::Some` instead"
)]
/// New `AllOrSome` from a list of URL strings. /// New `AllOrSome` from a list of URL strings.
/// Returns a tuple where the first element is the struct `AllOrSome`, /// Returns a tuple where the first element is the struct `AllOrSome`,
/// and the second element /// and the second element
@ -833,7 +876,8 @@ impl AllowedOrigins {
/// and the second element /// and the second element
/// is a map of strings which failed to parse into URLs and their associated parse errors. /// is a map of strings which failed to parse into URLs and their associated parse errors.
pub fn some(urls: &[&str]) -> (Self, HashMap<String, url::ParseError>) { pub fn some(urls: &[&str]) -> (Self, HashMap<String, url::ParseError>) {
let (ok_set, error_map): (Vec<_>, Vec<_>) = urls.iter() let (ok_set, error_map): (Vec<_>, Vec<_>) = urls
.iter()
.map(|s| (s.to_string(), Url::from_str(s))) .map(|s| (s.to_string(), Url::from_str(s)))
.partition(|&(_, ref r)| r.is_ok()); .partition(|&(_, ref r)| r.is_ok());
@ -995,7 +1039,10 @@ pub struct Cors {
/// [Resource Processing Model](https://www.w3.org/TR/cors/#resource-processing-model). /// [Resource Processing Model](https://www.w3.org/TR/cors/#resource-processing-model).
/// ///
/// Defaults to `[GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]` /// Defaults to `[GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]`
#[cfg_attr(feature = "serialization", serde(default = "Cors::default_allowed_methods"))] #[cfg_attr(
feature = "serialization",
serde(default = "Cors::default_allowed_methods")
)]
pub allowed_methods: AllowedMethods, pub allowed_methods: AllowedMethods,
/// The list of header field names which can be used when this resource is accessed by allowed /// The list of header field names which can be used when this resource is accessed by allowed
/// origins. /// origins.
@ -1054,14 +1101,20 @@ pub struct Cors {
/// of your existing routes. /// of your existing routes.
/// ///
/// Defaults to "/cors" /// Defaults to "/cors"
#[cfg_attr(feature = "serialization", serde(default = "Cors::default_fairing_route_base"))] #[cfg_attr(
feature = "serialization",
serde(default = "Cors::default_fairing_route_base")
)]
pub fairing_route_base: String, pub fairing_route_base: String,
/// When used as Fairing, Cors will need to redirect failed CORS checks to a custom route /// When used as Fairing, Cors will need to redirect failed CORS checks to a custom route
/// mounted by the fairing. Specify the rank of the route so that it doesn't clash with any /// mounted by the fairing. Specify the rank of the route so that it doesn't clash with any
/// of your existing routes. Remember that a higher ranked route has lower priority. /// of your existing routes. Remember that a higher ranked route has lower priority.
/// ///
/// Defaults to 0 /// Defaults to 0
#[cfg_attr(feature = "serialization", serde(default = "Cors::default_fairing_route_rank"))] #[cfg_attr(
feature = "serialization",
serde(default = "Cors::default_fairing_route_rank")
)]
pub fairing_route_rank: isize, pub fairing_route_rank: isize,
} }
@ -1291,7 +1344,8 @@ impl Response {
} }
if !self.expose_headers.is_empty() { if !self.expose_headers.is_empty() {
let headers: Vec<String> = self.expose_headers let headers: Vec<String> = self
.expose_headers
.iter() .iter()
.map(|s| s.deref().to_string()) .map(|s| s.deref().to_string())
.collect(); .collect();
@ -1303,7 +1357,8 @@ impl Response {
} }
if !self.allow_headers.is_empty() { if !self.allow_headers.is_empty() {
let headers: Vec<String> = self.allow_headers let headers: Vec<String> = self
.allow_headers
.iter() .iter()
.map(|s| s.deref().to_string()) .map(|s| s.deref().to_string())
.collect(); .collect();
@ -1868,8 +1923,8 @@ fn catch_all_options_route_handler<'r>(
mod tests { mod tests {
use std::str::FromStr; use std::str::FromStr;
use rocket::local::Client;
use rocket::http::Header; use rocket::http::Header;
use rocket::local::Client;
#[cfg(feature = "serialization")] #[cfg(feature = "serialization")]
use serde_json; use serde_json;
@ -1976,7 +2031,10 @@ mod tests {
// Build response and check built response header // Build response and check built response header
let expected_header = vec!["https://www.example.com"]; let expected_header = vec!["https://www.example.com"];
let response = response.response(response::Response::new()); let response = response.response(response::Response::new());
let actual_header: Vec<_> = response.headers().get("Access-Control-Allow-Origin").collect(); let actual_header: Vec<_> = response
.headers()
.get("Access-Control-Allow-Origin")
.collect();
assert_eq!(expected_header, actual_header); assert_eq!(expected_header, actual_header);
assert!(response.headers().get("Vary").next().is_none()); assert!(response.headers().get("Vary").next().is_none());
@ -1985,15 +2043,16 @@ mod tests {
#[test] #[test]
fn response_sets_allow_origin_with_vary_correctly() { fn response_sets_allow_origin_with_vary_correctly() {
let response = Response::new(); let response = Response::new();
let response = response.origin( let response =
&FromStr::from_str("https://www.example.com").unwrap(), response.origin(&FromStr::from_str("https://www.example.com").unwrap(), true);
true,
);
// Build response and check built response header // Build response and check built response header
let expected_header = vec!["https://www.example.com"]; let expected_header = vec!["https://www.example.com"];
let response = response.response(response::Response::new()); let response = response.response(response::Response::new());
let actual_header: Vec<_> = response.headers().get("Access-Control-Allow-Origin").collect(); let actual_header: Vec<_> = response
.headers()
.get("Access-Control-Allow-Origin")
.collect();
assert_eq!(expected_header, actual_header); assert_eq!(expected_header, actual_header);
} }
@ -2005,22 +2064,25 @@ mod tests {
// Build response and check built response header // Build response and check built response header
let expected_header = vec!["*"]; let expected_header = vec!["*"];
let response = response.response(response::Response::new()); let response = response.response(response::Response::new());
let actual_header: Vec<_> = response.headers().get("Access-Control-Allow-Origin").collect(); let actual_header: Vec<_> = response
.headers()
.get("Access-Control-Allow-Origin")
.collect();
assert_eq!(expected_header, actual_header); assert_eq!(expected_header, actual_header);
} }
#[test] #[test]
fn response_sets_allow_origin_with_ascii_serialization() { fn response_sets_allow_origin_with_ascii_serialization() {
let response = Response::new(); let response = Response::new();
let response = response.origin( let response = response.origin(&FromStr::from_str("https://аpple.com").unwrap(), false);
&FromStr::from_str("https://аpple.com").unwrap(),
false,
);
// Build response and check built response header // Build response and check built response header
let expected_header = vec!["https://xn--pple-43d.com"]; let expected_header = vec!["https://xn--pple-43d.com"];
let response = response.response(response::Response::new()); let response = response.response(response::Response::new());
let actual_header: Vec<_> = response.headers().get("Access-Control-Allow-Origin").collect(); let actual_header: Vec<_> = response
.headers()
.get("Access-Control-Allow-Origin")
.collect();
assert_eq!(expected_header, actual_header); assert_eq!(expected_header, actual_header);
} }

View File

@ -1,26 +1,38 @@
macro_rules! not_err { macro_rules! not_err {
($e:expr) => (match $e { ($e:expr) => {
match $e {
Ok(e) => e, Ok(e) => e,
Err(e) => panic!("{} failed with {:?}", stringify!($e), e), Err(e) => panic!("{} failed with {:?}", stringify!($e), e),
}) }
};
} }
macro_rules! is_err { macro_rules! is_err {
($e:expr) => (match $e { ($e:expr) => {
Ok(e) => panic!("{} did not return with an error, but with {:?}", stringify!($e), e), match $e {
Ok(e) => panic!(
"{} did not return with an error, but with {:?}",
stringify!($e),
e
),
Err(e) => e, Err(e) => e,
}) }
};
} }
macro_rules! assert_matches { macro_rules! assert_matches {
($e: expr, $p: pat) => (assert_matches!($e, $p, ())); ($e:expr, $p:pat) => {
($e: expr, $p: pat, $f: expr) => (match $e { assert_matches!($e, $p, ())
};
($e:expr, $p:pat, $f:expr) => {
match $e {
$p => $f, $p => $f,
e => { e => panic!(
panic!(
"{}: Expected pattern {} \ndoes not match {:?}", "{}: Expected pattern {} \ndoes not match {:?}",
stringify!($e), stringify!($p), e stringify!($e),
) stringify!($p),
e
),
} }
}) };
} }

View File

@ -8,10 +8,10 @@ extern crate rocket_cors as cors;
use std::str::FromStr; use std::str::FromStr;
use rocket::{Response, State};
use rocket::http::Method; use rocket::http::Method;
use rocket::http::{Header, Status}; use rocket::http::{Header, Status};
use rocket::local::Client; use rocket::local::Client;
use rocket::{Response, State};
#[get("/")] #[get("/")]
fn cors(cors: cors::Guard) -> cors::Responder<&str> { fn cors(cors: cors::Guard) -> cors::Responder<&str> {

View File

@ -8,8 +8,8 @@ extern crate rocket_cors;
use std::ops::Deref; use std::ops::Deref;
use std::str::FromStr; use std::str::FromStr;
use rocket::local::Client;
use rocket::http::Header; use rocket::http::Header;
use rocket::local::Client;
use rocket_cors::headers::*; use rocket_cors::headers::*;
#[get("/request_headers")] #[get("/request_headers")]

View File

@ -8,11 +8,11 @@ extern crate rocket_cors;
use std::str::FromStr; use std::str::FromStr;
use rocket::State;
use rocket::http::Method; use rocket::http::Method;
use rocket::http::{Header, Status}; use rocket::http::{Header, Status};
use rocket::local::Client; use rocket::local::Client;
use rocket::response::Responder; use rocket::response::Responder;
use rocket::State;
use rocket_cors::*; use rocket_cors::*;
/// Using a borrowed `Cors` /// Using a borrowed `Cors`