1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 09:42:40 +01:00

update extractor tests

This commit is contained in:
Nikolay Kim 2019-03-02 22:03:45 -08:00
parent 352e7b7a75
commit d5c54a1867
6 changed files with 97 additions and 146 deletions

View File

@ -29,7 +29,8 @@ pub trait HttpServiceFactory<Request> {
fn create(self) -> Self::Factory; fn create(self) -> Self::Factory;
} }
/// Application builder /// Application builder - structure that follows the builder pattern
/// for building application instances.
pub struct App<P, T> pub struct App<P, T>
where where
T: NewService<Request = ServiceRequest<PayloadStream>, Response = ServiceRequest<P>>, T: NewService<Request = ServiceRequest<PayloadStream>, Response = ServiceRequest<P>>,
@ -69,11 +70,8 @@ where
InitError = (), InitError = (),
>, >,
{ {
/// Create application with specified state. Application can be /// Set application state. Applicatin state could be accessed
/// configured with a builder-like pattern. /// by using `State<T>` extractor where `T` is state type.
///
/// State is shared with all resources within same application and
/// could be accessed with `HttpRequest::state()` method.
/// ///
/// **Note**: http server accepts an application factory rather than /// **Note**: http server accepts an application factory rather than
/// an application instance. Http server constructs an application /// an application instance. Http server constructs an application
@ -86,7 +84,7 @@ where
self self
} }
/// Set application state. This function is /// Set application state factory. This function is
/// similar to `.state()` but it accepts state factory. State get /// similar to `.state()` but it accepts state factory. State get
/// constructed asynchronously during application initialization. /// constructed asynchronously during application initialization.
pub fn state_factory<S, F, Out>(mut self, state: F) -> Self pub fn state_factory<S, F, Out>(mut self, state: F) -> Self
@ -119,14 +117,14 @@ where
/// `/users/{userid}/{friend}` and store `userid` and `friend` in /// `/users/{userid}/{friend}` and store `userid` and `friend` in
/// the exposed `Params` object: /// the exposed `Params` object:
/// ///
/// ```rust,ignore /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::{http, App, HttpResponse}; /// use actix_web::{web, http, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().resource("/users/{userid}/{friend}", |r| { /// let app = App::new().resource("/users/{userid}/{friend}", |r| {
/// r.get(|r| r.to(|_| HttpResponse::Ok())); /// r.route(web::get().to(|| HttpResponse::Ok()))
/// r.head(|r| r.to(|_| HttpResponse::MethodNotAllowed())) /// .route(web::head().to(|| HttpResponse::MethodNotAllowed()))
/// }); /// });
/// } /// }
/// ``` /// ```
@ -294,14 +292,16 @@ where
/// `/users/{userid}/{friend}` and store `userid` and `friend` in /// `/users/{userid}/{friend}` and store `userid` and `friend` in
/// the exposed `Params` object: /// the exposed `Params` object:
/// ///
/// ```rust,ignore /// ```rust
/// # extern crate actix_web; /// use actix_web::{web, http, App, HttpResponse};
/// use actix_web::{http, App, HttpResponse};
/// ///
/// fn main() { /// fn main() {
/// let app = App::new().resource("/users/{userid}/{friend}", |r| { /// let app = App::new()
/// r.get(|r| r.to(|_| HttpResponse::Ok())); /// .resource("/users/{userid}/{friend}", |r| {
/// r.head(|r| r.to(|_| HttpResponse::MethodNotAllowed())) /// r.route(web::to(|| HttpResponse::Ok()))
/// })
/// .resource("/index.html", |r| {
/// r.route(web::head().to(|| HttpResponse::MethodNotAllowed()))
/// }); /// });
/// } /// }
/// ``` /// ```

View File

@ -999,73 +999,60 @@ tuple_from_req!(
(9, J) (9, J)
); );
// #[cfg(test)] #[cfg(test)]
// mod tests { mod tests {
// use super::*; use actix_http::http::header;
// use actix_http::http::header; use bytes::Bytes;
// use actix_http::test::TestRequest; use serde_derive::Deserialize;
// use bytes::Bytes;
// use futures::{Async, Future};
// use mime;
// use serde::{Deserialize, Serialize};
// use crate::resource::Resource; use super::*;
// // use crate::router::{ResourceDef, Router}; use crate::test::TestRequest;
// #[derive(Deserialize, Debug, PartialEq)] #[derive(Deserialize, Debug, PartialEq)]
// struct Info { struct Info {
// hello: String, hello: String,
// } }
// #[test] #[test]
// fn test_bytes() { fn test_bytes() {
// let cfg = PayloadConfig::default(); let mut rt = actix_rt::Runtime::new().unwrap();
// let req = TestRequest::with_header(header::CONTENT_LENGTH, "11") let mut req = TestRequest::with_header(header::CONTENT_LENGTH, "11")
// .set_payload(Bytes::from_static(b"hello=world")) .set_payload(Bytes::from_static(b"hello=world"))
// .finish(); .finish()
.into();
// match Bytes::from_request(&req, &cfg).unwrap().poll().unwrap() { let s = rt.block_on(Bytes::from_request(&mut req)).unwrap();
// Async::Ready(s) => { assert_eq!(s, Bytes::from_static(b"hello=world"));
// assert_eq!(s, Bytes::from_static(b"hello=world")); }
// }
// _ => unreachable!(),
// }
// }
// #[test] #[test]
// fn test_string() { fn test_string() {
// let cfg = PayloadConfig::default(); let mut rt = actix_rt::Runtime::new().unwrap();
// let req = TestRequest::with_header(header::CONTENT_LENGTH, "11") let mut req = TestRequest::with_header(header::CONTENT_LENGTH, "11")
// .set_payload(Bytes::from_static(b"hello=world")) .set_payload(Bytes::from_static(b"hello=world"))
// .finish(); .finish()
.into();
// match String::from_request(&req, &cfg).unwrap().poll().unwrap() { let s = rt.block_on(String::from_request(&mut req)).unwrap();
// Async::Ready(s) => { assert_eq!(s, "hello=world");
// assert_eq!(s, "hello=world"); }
// }
// _ => unreachable!(),
// }
// }
// #[test] #[test]
// fn test_form() { fn test_form() {
// let req = TestRequest::with_header( let mut rt = actix_rt::Runtime::new().unwrap();
// header::CONTENT_TYPE, let mut req = TestRequest::with_header(
// "application/x-www-form-urlencoded", header::CONTENT_TYPE,
// ) "application/x-www-form-urlencoded",
// .header(header::CONTENT_LENGTH, "11") )
// .set_payload(Bytes::from_static(b"hello=world")) .header(header::CONTENT_LENGTH, "11")
// .finish(); .set_payload(Bytes::from_static(b"hello=world"))
.finish()
.into();
// let mut cfg = FormConfig::default(); let s = rt.block_on(Form::<Info>::from_request(&mut req)).unwrap();
// cfg.limit(4096); assert_eq!(s.hello, "world");
// match Form::<Info>::from_request(&req, &cfg).poll().unwrap() { }
// Async::Ready(s) => { }
// assert_eq!(s.hello, "world");
// }
// _ => unreachable!(),
// }
// }
// #[test] // #[test]
// fn test_option() { // fn test_option() {

View File

@ -230,14 +230,14 @@ impl Filter for HeaderFilter {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use crate::test::TestServiceRequest;
use actix_http::http::{header, Method}; use actix_http::http::{header, Method};
use super::*; use super::*;
use crate::test::TestRequest;
#[test] #[test]
fn test_header() { fn test_header() {
let req = TestServiceRequest::with_header(header::TRANSFER_ENCODING, "chunked") let req = TestRequest::with_header(header::TRANSFER_ENCODING, "chunked")
.finish() .finish()
.into_request(); .into_request();
@ -269,8 +269,8 @@ mod tests {
#[test] #[test]
fn test_methods() { fn test_methods() {
let req = TestServiceRequest::default().finish().into_request(); let req = TestRequest::default().finish().into_request();
let req2 = TestServiceRequest::default() let req2 = TestRequest::default()
.method(Method::POST) .method(Method::POST)
.finish() .finish()
.into_request(); .into_request();
@ -280,46 +280,38 @@ mod tests {
assert!(Post().check(&req2)); assert!(Post().check(&req2));
assert!(!Post().check(&req)); assert!(!Post().check(&req));
let r = TestServiceRequest::default().method(Method::PUT).finish(); let r = TestRequest::default().method(Method::PUT).finish();
assert!(Put().check(&r,)); assert!(Put().check(&r,));
assert!(!Put().check(&req,)); assert!(!Put().check(&req,));
let r = TestServiceRequest::default() let r = TestRequest::default().method(Method::DELETE).finish();
.method(Method::DELETE)
.finish();
assert!(Delete().check(&r,)); assert!(Delete().check(&r,));
assert!(!Delete().check(&req,)); assert!(!Delete().check(&req,));
let r = TestServiceRequest::default().method(Method::HEAD).finish(); let r = TestRequest::default().method(Method::HEAD).finish();
assert!(Head().check(&r,)); assert!(Head().check(&r,));
assert!(!Head().check(&req,)); assert!(!Head().check(&req,));
let r = TestServiceRequest::default() let r = TestRequest::default().method(Method::OPTIONS).finish();
.method(Method::OPTIONS)
.finish();
assert!(Options().check(&r,)); assert!(Options().check(&r,));
assert!(!Options().check(&req,)); assert!(!Options().check(&req,));
let r = TestServiceRequest::default() let r = TestRequest::default().method(Method::CONNECT).finish();
.method(Method::CONNECT)
.finish();
assert!(Connect().check(&r,)); assert!(Connect().check(&r,));
assert!(!Connect().check(&req,)); assert!(!Connect().check(&req,));
let r = TestServiceRequest::default().method(Method::PATCH).finish(); let r = TestRequest::default().method(Method::PATCH).finish();
assert!(Patch().check(&r,)); assert!(Patch().check(&r,));
assert!(!Patch().check(&req,)); assert!(!Patch().check(&req,));
let r = TestServiceRequest::default().method(Method::TRACE).finish(); let r = TestRequest::default().method(Method::TRACE).finish();
assert!(Trace().check(&r,)); assert!(Trace().check(&r,));
assert!(!Trace().check(&req,)); assert!(!Trace().check(&req,));
} }
#[test] #[test]
fn test_preds() { fn test_preds() {
let r = TestServiceRequest::default() let r = TestRequest::default().method(Method::TRACE).request();
.method(Method::TRACE)
.request();
assert!(Not(Get()).check(&r,)); assert!(Not(Get()).check(&r,));
assert!(!Not(Trace()).check(&r,)); assert!(!Not(Trace()).check(&r,));

View File

@ -138,7 +138,7 @@ mod tests {
use actix_service::FnService; use actix_service::FnService;
use super::*; use super::*;
use crate::test::TestServiceRequest; use crate::test::TestRequest;
use crate::{HttpResponse, ServiceRequest}; use crate::{HttpResponse, ServiceRequest};
#[test] #[test]
@ -149,11 +149,11 @@ mod tests {
req.into_response(HttpResponse::Ok().finish()) req.into_response(HttpResponse::Ok().finish())
}); });
let req = TestServiceRequest::default().finish(); let req = TestRequest::default().finish();
let resp = rt.block_on(mw.call(req, &mut srv)).unwrap(); let resp = rt.block_on(mw.call(req, &mut srv)).unwrap();
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
let req = TestServiceRequest::default().finish(); let req = TestRequest::default().finish();
let mut srv = FnService::new(|req: ServiceRequest<_>| { let mut srv = FnService::new(|req: ServiceRequest<_>| {
req.into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish()) req.into_response(HttpResponse::Ok().header(CONTENT_TYPE, "0002").finish())
}); });
@ -169,7 +169,7 @@ mod tests {
req.into_response(HttpResponse::Ok().finish()) req.into_response(HttpResponse::Ok().finish())
}); });
let req = TestServiceRequest::default().finish(); let req = TestRequest::default().finish();
let resp = rt.block_on(mw.call(req, &mut srv)).unwrap(); let resp = rt.block_on(mw.call(req, &mut srv)).unwrap();
assert_eq!( assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(), resp.headers().get(CONTENT_TYPE).unwrap(),

View File

@ -34,19 +34,6 @@ where
} }
} }
impl<T, S> Clone for MiddlewareFactory<T, S>
where
T: Transform<S> + Clone,
S: Service,
{
fn clone(&self) -> Self {
Self {
tr: self.tr.clone(),
_t: PhantomData,
}
}
}
impl<T, S, C> NewTransform<S, C> for MiddlewareFactory<T, S> impl<T, S, C> NewTransform<S, C> for MiddlewareFactory<T, S>
where where
T: Transform<S> + Clone, T: Transform<S> + Clone,

View File

@ -1,10 +1,9 @@
//! Various helpers for Actix applications to use during testing. //! Various helpers for Actix applications to use during testing.
use std::ops::{Deref, DerefMut};
use std::rc::Rc; use std::rc::Rc;
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue}; use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
use actix_http::http::{HttpTryFrom, Method, Version}; use actix_http::http::{HttpTryFrom, Method, Version};
use actix_http::test::TestRequest; use actix_http::test::TestRequest as HttpTestRequest;
use actix_http::{Extensions, PayloadStream}; use actix_http::{Extensions, PayloadStream};
use actix_router::{Path, Url}; use actix_router::{Path, Url};
use bytes::Bytes; use bytes::Bytes;
@ -39,45 +38,45 @@ use crate::service::ServiceRequest;
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST); /// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
/// } /// }
/// ``` /// ```
pub struct TestServiceRequest { pub struct TestRequest {
req: TestRequest, req: HttpTestRequest,
extensions: Extensions, extensions: Extensions,
} }
impl Default for TestServiceRequest { impl Default for TestRequest {
fn default() -> TestServiceRequest { fn default() -> TestRequest {
TestServiceRequest { TestRequest {
req: TestRequest::default(), req: HttpTestRequest::default(),
extensions: Extensions::new(), extensions: Extensions::new(),
} }
} }
} }
impl TestServiceRequest { impl TestRequest {
/// Create TestRequest and set request uri /// Create TestRequest and set request uri
pub fn with_uri(path: &str) -> TestServiceRequest { pub fn with_uri(path: &str) -> TestRequest {
TestServiceRequest { TestRequest {
req: TestRequest::default().uri(path).take(), req: HttpTestRequest::default().uri(path).take(),
extensions: Extensions::new(), extensions: Extensions::new(),
} }
} }
/// Create TestRequest and set header /// Create TestRequest and set header
pub fn with_hdr<H: Header>(hdr: H) -> TestServiceRequest { pub fn with_hdr<H: Header>(hdr: H) -> TestRequest {
TestServiceRequest { TestRequest {
req: TestRequest::default().set(hdr).take(), req: HttpTestRequest::default().set(hdr).take(),
extensions: Extensions::new(), extensions: Extensions::new(),
} }
} }
/// Create TestRequest and set header /// Create TestRequest and set header
pub fn with_header<K, V>(key: K, value: V) -> TestServiceRequest pub fn with_header<K, V>(key: K, value: V) -> TestRequest
where where
HeaderName: HttpTryFrom<K>, HeaderName: HttpTryFrom<K>,
V: IntoHeaderValue, V: IntoHeaderValue,
{ {
TestServiceRequest { TestRequest {
req: TestRequest::default().header(key, value).take(), req: HttpTestRequest::default().header(key, value).take(),
extensions: Extensions::new(), extensions: Extensions::new(),
} }
} }
@ -145,17 +144,3 @@ impl TestServiceRequest {
.into_request() .into_request()
} }
} }
impl Deref for TestServiceRequest {
type Target = TestRequest;
fn deref(&self) -> &TestRequest {
&self.req
}
}
impl DerefMut for TestServiceRequest {
fn deref_mut(&mut self) -> &mut TestRequest {
&mut self.req
}
}