2017-12-27 01:35:00 +01:00
|
|
|
//! Various helpers for Actix applications to use during testing.
|
2019-03-04 22:25:35 +01:00
|
|
|
use std::cell::RefCell;
|
2019-03-03 01:24:14 +01:00
|
|
|
use std::rc::Rc;
|
2017-12-27 01:35:00 +01:00
|
|
|
|
2019-05-19 04:36:28 +02:00
|
|
|
use actix_http::http::header::{ContentType, Header, HeaderName, IntoHeaderValue};
|
2019-04-15 04:52:12 +02:00
|
|
|
use actix_http::http::{HttpTryFrom, Method, StatusCode, Uri, Version};
|
2019-03-03 07:03:45 +01:00
|
|
|
use actix_http::test::TestRequest as HttpTestRequest;
|
2019-05-05 04:43:49 +02:00
|
|
|
use actix_http::{cookie::Cookie, Extensions, Request};
|
2019-03-09 16:39:34 +01:00
|
|
|
use actix_router::{Path, ResourceDef, Url};
|
2019-06-12 12:15:06 +02:00
|
|
|
use actix_rt::{System, SystemRunner};
|
2019-03-09 18:49:11 +01:00
|
|
|
use actix_server_config::ServerConfig;
|
2019-05-12 17:34:51 +02:00
|
|
|
use actix_service::{IntoNewService, IntoService, NewService, Service};
|
2019-04-15 01:25:45 +02:00
|
|
|
use bytes::{Bytes, BytesMut};
|
2019-04-29 18:34:14 +02:00
|
|
|
use futures::future::{lazy, ok, Future, IntoFuture};
|
|
|
|
use futures::Stream;
|
2019-04-15 01:25:45 +02:00
|
|
|
use serde::de::DeserializeOwned;
|
2019-05-22 20:18:33 +02:00
|
|
|
use serde::Serialize;
|
2019-04-15 01:25:45 +02:00
|
|
|
use serde_json;
|
2017-12-27 01:35:00 +01:00
|
|
|
|
2019-04-12 23:00:45 +02:00
|
|
|
pub use actix_http::test::TestBuffer;
|
|
|
|
|
2019-03-09 23:06:24 +01:00
|
|
|
use crate::config::{AppConfig, AppConfigInner};
|
2019-05-05 04:43:49 +02:00
|
|
|
use crate::data::Data;
|
2019-04-15 01:25:45 +02:00
|
|
|
use crate::dev::{Body, MessageBody, Payload};
|
2019-04-08 08:06:21 +02:00
|
|
|
use crate::request::HttpRequestPool;
|
2019-03-09 16:39:34 +01:00
|
|
|
use crate::rmap::ResourceMap;
|
2019-04-07 23:43:07 +02:00
|
|
|
use crate::service::{ServiceRequest, ServiceResponse};
|
2019-03-24 05:29:16 +01:00
|
|
|
use crate::{Error, HttpRequest, HttpResponse};
|
2018-03-20 19:23:35 +01:00
|
|
|
|
2019-03-04 22:25:35 +01:00
|
|
|
thread_local! {
|
2019-04-29 19:14:08 +02:00
|
|
|
static RT: RefCell<Inner> = {
|
2019-06-12 12:15:06 +02:00
|
|
|
RefCell::new(Inner(Some(System::builder().build())))
|
2019-03-04 22:25:35 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-06-12 12:15:06 +02:00
|
|
|
struct Inner(Option<SystemRunner>);
|
2019-04-29 19:14:08 +02:00
|
|
|
|
|
|
|
impl Inner {
|
2019-06-12 12:15:06 +02:00
|
|
|
fn get_mut(&mut self) -> &mut SystemRunner {
|
2019-04-29 19:14:08 +02:00
|
|
|
self.0.as_mut().unwrap()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Drop for Inner {
|
|
|
|
fn drop(&mut self) {
|
|
|
|
std::mem::forget(self.0.take().unwrap())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-04 22:25:35 +01:00
|
|
|
/// Runs the provided future, blocking the current thread until the future
|
|
|
|
/// completes.
|
|
|
|
///
|
|
|
|
/// This function can be used to synchronously block the current thread
|
|
|
|
/// until the provided `future` has resolved either successfully or with an
|
|
|
|
/// error. The result of the future is then returned from this function
|
|
|
|
/// call.
|
|
|
|
///
|
|
|
|
/// Note that this function is intended to be used only for testing purpose.
|
|
|
|
/// This function panics on nested call.
|
|
|
|
pub fn block_on<F>(f: F) -> Result<F::Item, F::Error>
|
|
|
|
where
|
2019-04-30 03:42:21 +02:00
|
|
|
F: IntoFuture,
|
2019-03-04 22:25:35 +01:00
|
|
|
{
|
2019-04-30 03:42:21 +02:00
|
|
|
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(f.into_future()))
|
2019-03-04 22:25:35 +01:00
|
|
|
}
|
|
|
|
|
2019-06-29 06:38:16 +02:00
|
|
|
/// Runs the provided function, blocking the current thread until the result
|
2019-04-29 18:34:14 +02:00
|
|
|
/// future completes.
|
|
|
|
///
|
|
|
|
/// This function can be used to synchronously block the current thread
|
|
|
|
/// until the provided `future` has resolved either successfully or with an
|
|
|
|
/// error. The result of the future is then returned from this function
|
|
|
|
/// call.
|
|
|
|
///
|
|
|
|
/// Note that this function is intended to be used only for testing purpose.
|
|
|
|
/// This function panics on nested call.
|
|
|
|
pub fn block_fn<F, R>(f: F) -> Result<R::Item, R::Error>
|
|
|
|
where
|
|
|
|
F: FnOnce() -> R,
|
|
|
|
R: IntoFuture,
|
|
|
|
{
|
2019-04-29 19:14:08 +02:00
|
|
|
RT.with(move |rt| rt.borrow_mut().get_mut().block_on(lazy(|| f())))
|
2019-04-29 18:34:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
2019-03-13 06:57:09 +01:00
|
|
|
/// Runs the provided function, with runtime enabled.
|
|
|
|
///
|
|
|
|
/// Note that this function is intended to be used only for testing purpose.
|
|
|
|
/// This function panics on nested call.
|
2019-03-28 13:04:39 +01:00
|
|
|
pub fn run_on<F, R>(f: F) -> R
|
2019-03-13 06:57:09 +01:00
|
|
|
where
|
2019-04-17 19:28:27 +02:00
|
|
|
F: FnOnce() -> R,
|
2019-03-13 06:57:09 +01:00
|
|
|
{
|
2019-04-29 19:14:08 +02:00
|
|
|
RT.with(move |rt| {
|
|
|
|
rt.borrow_mut()
|
|
|
|
.get_mut()
|
|
|
|
.block_on(lazy(|| Ok::<_, ()>(f())))
|
|
|
|
})
|
|
|
|
.unwrap()
|
2019-03-13 06:57:09 +01:00
|
|
|
}
|
|
|
|
|
2019-03-30 18:04:38 +01:00
|
|
|
/// Create service that always responds with `HttpResponse::Ok()`
|
2019-04-13 23:50:54 +02:00
|
|
|
pub fn ok_service(
|
|
|
|
) -> impl Service<Request = ServiceRequest, Response = ServiceResponse<Body>, Error = Error>
|
|
|
|
{
|
2019-03-24 05:29:16 +01:00
|
|
|
default_service(StatusCode::OK)
|
|
|
|
}
|
|
|
|
|
2019-03-30 18:04:38 +01:00
|
|
|
/// Create service that responds with response with specified status code
|
2019-03-24 05:29:16 +01:00
|
|
|
pub fn default_service(
|
|
|
|
status_code: StatusCode,
|
2019-04-13 23:50:54 +02:00
|
|
|
) -> impl Service<Request = ServiceRequest, Response = ServiceResponse<Body>, Error = Error>
|
|
|
|
{
|
2019-05-12 17:34:51 +02:00
|
|
|
(move |req: ServiceRequest| {
|
2019-03-24 05:29:16 +01:00
|
|
|
req.into_response(HttpResponse::build(status_code).finish())
|
|
|
|
})
|
2019-05-12 17:34:51 +02:00
|
|
|
.into_service()
|
2019-03-24 05:29:16 +01:00
|
|
|
}
|
|
|
|
|
2019-03-06 03:47:18 +01:00
|
|
|
/// This method accepts application builder instance, and constructs
|
|
|
|
/// service.
|
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// ```rust
|
2019-03-06 03:52:29 +01:00
|
|
|
/// use actix_service::Service;
|
2019-03-25 01:13:17 +01:00
|
|
|
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
|
2019-03-06 03:47:18 +01:00
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// #[test]
|
|
|
|
/// fn test_init_service() {
|
2019-03-06 03:52:29 +01:00
|
|
|
/// let mut app = test::init_service(
|
2019-03-06 03:47:18 +01:00
|
|
|
/// App::new()
|
2019-03-25 01:13:17 +01:00
|
|
|
/// .service(web::resource("/test").to(|| HttpResponse::Ok()))
|
2019-03-06 03:52:29 +01:00
|
|
|
/// );
|
2019-03-06 03:47:18 +01:00
|
|
|
///
|
2019-03-06 03:52:29 +01:00
|
|
|
/// // Create request object
|
|
|
|
/// let req = test::TestRequest::with_uri("/test").to_request();
|
|
|
|
///
|
|
|
|
/// // Execute application
|
|
|
|
/// let resp = test::block_on(app.call(req)).unwrap();
|
2019-03-06 03:47:18 +01:00
|
|
|
/// assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn init_service<R, S, B, E>(
|
|
|
|
app: R,
|
2019-03-09 18:49:11 +01:00
|
|
|
) -> impl Service<Request = Request, Response = ServiceResponse<B>, Error = E>
|
2019-03-06 03:47:18 +01:00
|
|
|
where
|
2019-05-12 17:34:51 +02:00
|
|
|
R: IntoNewService<S>,
|
2019-03-09 18:49:11 +01:00
|
|
|
S: NewService<
|
2019-05-12 17:34:51 +02:00
|
|
|
Config = ServerConfig,
|
2019-03-09 18:49:11 +01:00
|
|
|
Request = Request,
|
|
|
|
Response = ServiceResponse<B>,
|
|
|
|
Error = E,
|
|
|
|
>,
|
2019-03-06 03:47:18 +01:00
|
|
|
S::InitError: std::fmt::Debug,
|
|
|
|
{
|
2019-03-09 18:49:11 +01:00
|
|
|
let cfg = ServerConfig::new("127.0.0.1:8080".parse().unwrap());
|
2019-04-17 19:28:27 +02:00
|
|
|
let srv = app.into_new_service();
|
|
|
|
let fut = run_on(move || srv.new_service(&cfg));
|
|
|
|
block_on(fut).unwrap()
|
2019-03-06 03:47:18 +01:00
|
|
|
}
|
|
|
|
|
2019-03-06 07:10:08 +01:00
|
|
|
/// Calls service and waits for response future completion.
|
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// ```rust
|
2019-03-06 07:10:08 +01:00
|
|
|
/// use actix_web::{test, App, HttpResponse, http::StatusCode};
|
|
|
|
/// use actix_service::Service;
|
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// #[test]
|
|
|
|
/// fn test_response() {
|
2019-03-06 07:10:08 +01:00
|
|
|
/// let mut app = test::init_service(
|
|
|
|
/// App::new()
|
2019-03-25 01:13:17 +01:00
|
|
|
/// .service(web::resource("/test").to(|| HttpResponse::Ok()))
|
2019-03-06 07:10:08 +01:00
|
|
|
/// );
|
|
|
|
///
|
|
|
|
/// // Create request object
|
|
|
|
/// let req = test::TestRequest::with_uri("/test").to_request();
|
|
|
|
///
|
|
|
|
/// // Call application
|
2019-04-15 16:44:07 +02:00
|
|
|
/// let resp = test::call_service(&mut app, req);
|
2019-03-06 07:10:08 +01:00
|
|
|
/// assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-04-15 16:44:07 +02:00
|
|
|
pub fn call_service<S, R, B, E>(app: &mut S, req: R) -> S::Response
|
2019-03-06 07:10:08 +01:00
|
|
|
where
|
2019-03-09 18:49:11 +01:00
|
|
|
S: Service<Request = R, Response = ServiceResponse<B>, Error = E>,
|
2019-03-06 07:10:08 +01:00
|
|
|
E: std::fmt::Debug,
|
|
|
|
{
|
2019-04-17 19:28:27 +02:00
|
|
|
block_on(run_on(move || app.call(req))).unwrap()
|
2019-03-06 07:10:08 +01:00
|
|
|
}
|
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
/// Helper function that returns a response body of a TestRequest
|
|
|
|
/// This function blocks the current thread until futures complete.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{test, web, App, HttpResponse, http::header};
|
|
|
|
/// use bytes::Bytes;
|
|
|
|
///
|
|
|
|
/// #[test]
|
|
|
|
/// fn test_index() {
|
|
|
|
/// let mut app = test::init_service(
|
|
|
|
/// App::new().service(
|
|
|
|
/// web::resource("/index.html")
|
|
|
|
/// .route(web::post().to(
|
|
|
|
/// || HttpResponse::Ok().body("welcome!")))));
|
|
|
|
///
|
|
|
|
/// let req = test::TestRequest::post()
|
|
|
|
/// .uri("/index.html")
|
|
|
|
/// .header(header::CONTENT_TYPE, "application/json")
|
|
|
|
/// .to_request();
|
|
|
|
///
|
|
|
|
/// let result = test::read_response(&mut app, req);
|
|
|
|
/// assert_eq!(result, Bytes::from_static(b"welcome!"));
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn read_response<S, B>(app: &mut S, req: Request) -> Bytes
|
|
|
|
where
|
|
|
|
S: Service<Request = Request, Response = ServiceResponse<B>, Error = Error>,
|
|
|
|
B: MessageBody,
|
|
|
|
{
|
2019-04-17 19:28:27 +02:00
|
|
|
block_on(run_on(move || {
|
|
|
|
app.call(req).and_then(|mut resp: ServiceResponse<B>| {
|
|
|
|
resp.take_body()
|
|
|
|
.fold(BytesMut::new(), move |mut body, chunk| {
|
|
|
|
body.extend_from_slice(&chunk);
|
|
|
|
Ok::<_, Error>(body)
|
|
|
|
})
|
|
|
|
.map(|body: BytesMut| body.freeze())
|
|
|
|
})
|
2019-04-15 04:52:12 +02:00
|
|
|
}))
|
|
|
|
.unwrap_or_else(|_| panic!("read_response failed at block_on unwrap"))
|
|
|
|
}
|
|
|
|
|
2019-04-22 23:22:08 +02:00
|
|
|
/// Helper function that returns a response body of a ServiceResponse.
|
|
|
|
/// This function blocks the current thread until futures complete.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{test, web, App, HttpResponse, http::header};
|
|
|
|
/// use bytes::Bytes;
|
|
|
|
///
|
|
|
|
/// #[test]
|
|
|
|
/// fn test_index() {
|
|
|
|
/// let mut app = test::init_service(
|
|
|
|
/// App::new().service(
|
|
|
|
/// web::resource("/index.html")
|
|
|
|
/// .route(web::post().to(
|
|
|
|
/// || HttpResponse::Ok().body("welcome!")))));
|
|
|
|
///
|
|
|
|
/// let req = test::TestRequest::post()
|
|
|
|
/// .uri("/index.html")
|
|
|
|
/// .header(header::CONTENT_TYPE, "application/json")
|
|
|
|
/// .to_request();
|
|
|
|
///
|
2019-05-21 19:43:18 +02:00
|
|
|
/// let resp = test::call_service(&mut app, req);
|
2019-04-22 23:22:08 +02:00
|
|
|
/// let result = test::read_body(resp);
|
|
|
|
/// assert_eq!(result, Bytes::from_static(b"welcome!"));
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn read_body<B>(mut res: ServiceResponse<B>) -> Bytes
|
|
|
|
where
|
|
|
|
B: MessageBody,
|
|
|
|
{
|
|
|
|
block_on(run_on(move || {
|
|
|
|
res.take_body()
|
|
|
|
.fold(BytesMut::new(), move |mut body, chunk| {
|
|
|
|
body.extend_from_slice(&chunk);
|
|
|
|
Ok::<_, Error>(body)
|
|
|
|
})
|
|
|
|
.map(|body: BytesMut| body.freeze())
|
|
|
|
}))
|
|
|
|
.unwrap_or_else(|_| panic!("read_response failed at block_on unwrap"))
|
|
|
|
}
|
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
/// Helper function that returns a deserialized response body of a TestRequest
|
|
|
|
/// This function blocks the current thread until futures complete.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::{App, test, web, HttpResponse, http::header};
|
|
|
|
/// use serde::{Serialize, Deserialize};
|
|
|
|
///
|
|
|
|
/// #[derive(Serialize, Deserialize)]
|
|
|
|
/// pub struct Person {
|
|
|
|
/// id: String,
|
|
|
|
/// name: String
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// #[test]
|
|
|
|
/// fn test_add_person() {
|
|
|
|
/// let mut app = test::init_service(
|
|
|
|
/// App::new().service(
|
|
|
|
/// web::resource("/people")
|
|
|
|
/// .route(web::post().to(|person: web::Json<Person>| {
|
|
|
|
/// HttpResponse::Ok()
|
|
|
|
/// .json(person.into_inner())})
|
|
|
|
/// )));
|
|
|
|
///
|
|
|
|
/// let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
|
|
|
|
///
|
|
|
|
/// let req = test::TestRequest::post()
|
|
|
|
/// .uri("/people")
|
|
|
|
/// .header(header::CONTENT_TYPE, "application/json")
|
|
|
|
/// .set_payload(payload)
|
|
|
|
/// .to_request();
|
|
|
|
///
|
|
|
|
/// let result: Person = test::read_response_json(&mut app, req);
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
pub fn read_response_json<S, B, T>(app: &mut S, req: Request) -> T
|
|
|
|
where
|
|
|
|
S: Service<Request = Request, Response = ServiceResponse<B>, Error = Error>,
|
|
|
|
B: MessageBody,
|
|
|
|
T: DeserializeOwned,
|
|
|
|
{
|
2019-04-17 19:28:27 +02:00
|
|
|
block_on(run_on(move || {
|
|
|
|
app.call(req).and_then(|mut resp: ServiceResponse<B>| {
|
|
|
|
resp.take_body()
|
|
|
|
.fold(BytesMut::new(), move |mut body, chunk| {
|
|
|
|
body.extend_from_slice(&chunk);
|
|
|
|
Ok::<_, Error>(body)
|
|
|
|
})
|
|
|
|
.and_then(|body: BytesMut| {
|
|
|
|
ok(serde_json::from_slice(&body).unwrap_or_else(|_| {
|
|
|
|
panic!("read_response_json failed during deserialization")
|
|
|
|
}))
|
|
|
|
})
|
|
|
|
})
|
2019-04-15 04:52:12 +02:00
|
|
|
}))
|
|
|
|
.unwrap_or_else(|_| panic!("read_response_json failed at block_on unwrap"))
|
|
|
|
}
|
|
|
|
|
2019-03-04 22:25:35 +01:00
|
|
|
/// Test `Request` builder.
|
|
|
|
///
|
|
|
|
/// For unit testing, actix provides a request builder type and a simple handler runner. TestRequest implements a builder-like pattern.
|
|
|
|
/// You can generate various types of request via TestRequest's methods:
|
|
|
|
/// * `TestRequest::to_request` creates `actix_http::Request` instance.
|
2019-04-30 03:42:21 +02:00
|
|
|
/// * `TestRequest::to_srv_request` creates `ServiceRequest` instance, which is used for testing middlewares and chain adapters.
|
|
|
|
/// * `TestRequest::to_srv_response` creates `ServiceResponse` instance.
|
2019-03-04 22:25:35 +01:00
|
|
|
/// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers.
|
2018-03-29 06:49:50 +02:00
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// ```rust
|
2019-03-06 04:03:59 +01:00
|
|
|
/// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage};
|
|
|
|
/// use actix_web::http::{header, StatusCode};
|
2017-12-27 04:48:02 +01:00
|
|
|
///
|
2019-03-03 22:53:31 +01:00
|
|
|
/// fn index(req: HttpRequest) -> HttpResponse {
|
2017-12-27 04:48:02 +01:00
|
|
|
/// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
|
2018-03-31 08:07:33 +02:00
|
|
|
/// HttpResponse::Ok().into()
|
2017-12-27 04:48:02 +01:00
|
|
|
/// } else {
|
2018-03-31 08:07:33 +02:00
|
|
|
/// HttpResponse::BadRequest().into()
|
2017-12-27 04:48:02 +01:00
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
///
|
2019-04-15 04:52:12 +02:00
|
|
|
/// #[test]
|
|
|
|
/// fn test_index() {
|
2019-03-04 22:25:35 +01:00
|
|
|
/// let req = test::TestRequest::with_header("content-type", "text/plain")
|
|
|
|
/// .to_http_request();
|
|
|
|
///
|
2019-04-30 03:42:21 +02:00
|
|
|
/// let resp = test::block_on(index(req)).unwrap();
|
2017-12-27 04:48:02 +01:00
|
|
|
/// assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
///
|
2019-03-04 22:25:35 +01:00
|
|
|
/// let req = test::TestRequest::default().to_http_request();
|
2019-04-30 03:42:21 +02:00
|
|
|
/// let resp = test::block_on(index(req)).unwrap();
|
2017-12-27 04:48:02 +01:00
|
|
|
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
|
|
|
/// }
|
|
|
|
/// ```
|
2019-03-03 07:03:45 +01:00
|
|
|
pub struct TestRequest {
|
|
|
|
req: HttpTestRequest,
|
2019-03-09 16:39:34 +01:00
|
|
|
rmap: ResourceMap,
|
2019-03-09 23:06:24 +01:00
|
|
|
config: AppConfigInner,
|
2019-04-15 04:52:12 +02:00
|
|
|
path: Path<Url>,
|
2019-05-05 04:43:49 +02:00
|
|
|
app_data: Extensions,
|
2017-12-27 04:48:02 +01:00
|
|
|
}
|
|
|
|
|
2019-03-03 07:03:45 +01:00
|
|
|
impl Default for TestRequest {
|
|
|
|
fn default() -> TestRequest {
|
|
|
|
TestRequest {
|
|
|
|
req: HttpTestRequest::default(),
|
2019-03-09 16:39:34 +01:00
|
|
|
rmap: ResourceMap::new(ResourceDef::new("")),
|
2019-03-09 23:06:24 +01:00
|
|
|
config: AppConfigInner::default(),
|
2019-04-15 04:52:12 +02:00
|
|
|
path: Path::new(Url::new(Uri::default())),
|
2019-05-05 04:43:49 +02:00
|
|
|
app_data: Extensions::new(),
|
2017-12-27 04:48:02 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-17 05:35:02 +01:00
|
|
|
#[allow(clippy::wrong_self_convention)]
|
2019-03-03 07:03:45 +01:00
|
|
|
impl TestRequest {
|
2018-01-15 22:47:25 +01:00
|
|
|
/// Create TestRequest and set request uri
|
2019-03-03 07:03:45 +01:00
|
|
|
pub fn with_uri(path: &str) -> TestRequest {
|
2019-04-12 20:15:58 +02:00
|
|
|
TestRequest::default().uri(path)
|
2017-12-27 04:48:02 +01:00
|
|
|
}
|
|
|
|
|
2018-03-06 04:28:42 +01:00
|
|
|
/// Create TestRequest and set header
|
2019-03-03 07:03:45 +01:00
|
|
|
pub fn with_hdr<H: Header>(hdr: H) -> TestRequest {
|
2019-04-12 20:15:58 +02:00
|
|
|
TestRequest::default().set(hdr)
|
2018-03-06 04:28:42 +01:00
|
|
|
}
|
|
|
|
|
2018-01-15 22:47:25 +01:00
|
|
|
/// Create TestRequest and set header
|
2019-03-03 07:03:45 +01:00
|
|
|
pub fn with_header<K, V>(key: K, value: V) -> TestRequest
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
HeaderName: HttpTryFrom<K>,
|
|
|
|
V: IntoHeaderValue,
|
2017-12-27 04:48:02 +01:00
|
|
|
{
|
2019-04-12 20:15:58 +02:00
|
|
|
TestRequest::default().header(key, value)
|
2017-12-27 04:48:02 +01:00
|
|
|
}
|
|
|
|
|
2019-03-06 03:47:18 +01:00
|
|
|
/// Create TestRequest and set method to `Method::GET`
|
|
|
|
pub fn get() -> TestRequest {
|
2019-04-12 20:15:58 +02:00
|
|
|
TestRequest::default().method(Method::GET)
|
2019-03-06 03:47:18 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Create TestRequest and set method to `Method::POST`
|
|
|
|
pub fn post() -> TestRequest {
|
2019-04-12 20:15:58 +02:00
|
|
|
TestRequest::default().method(Method::POST)
|
2019-03-06 03:47:18 +01:00
|
|
|
}
|
2019-04-20 02:23:17 +02:00
|
|
|
|
2019-04-19 00:06:32 +02:00
|
|
|
/// Create TestRequest and set method to `Method::PUT`
|
|
|
|
pub fn put() -> TestRequest {
|
|
|
|
TestRequest::default().method(Method::PUT)
|
|
|
|
}
|
2019-04-20 02:23:17 +02:00
|
|
|
|
2019-04-19 00:06:32 +02:00
|
|
|
/// Create TestRequest and set method to `Method::PATCH`
|
|
|
|
pub fn patch() -> TestRequest {
|
|
|
|
TestRequest::default().method(Method::PATCH)
|
|
|
|
}
|
2019-03-06 03:47:18 +01:00
|
|
|
|
2019-04-29 18:14:36 +02:00
|
|
|
/// Create TestRequest and set method to `Method::DELETE`
|
|
|
|
pub fn delete() -> TestRequest {
|
|
|
|
TestRequest::default().method(Method::DELETE)
|
|
|
|
}
|
|
|
|
|
2017-12-27 04:48:02 +01:00
|
|
|
/// Set HTTP version of this request
|
|
|
|
pub fn version(mut self, ver: Version) -> Self {
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.version(ver);
|
2017-12-27 04:48:02 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set HTTP method of this request
|
|
|
|
pub fn method(mut self, meth: Method) -> Self {
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.method(meth);
|
2017-12-27 04:48:02 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set HTTP Uri of this request
|
|
|
|
pub fn uri(mut self, path: &str) -> Self {
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.uri(path);
|
2017-12-27 04:48:02 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2018-03-06 04:28:42 +01:00
|
|
|
/// Set a header
|
2018-04-14 01:02:01 +02:00
|
|
|
pub fn set<H: Header>(mut self, hdr: H) -> Self {
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.set(hdr);
|
|
|
|
self
|
2018-03-06 04:28:42 +01:00
|
|
|
}
|
|
|
|
|
2017-12-27 04:48:02 +01:00
|
|
|
/// Set a header
|
|
|
|
pub fn header<K, V>(mut self, key: K, value: V) -> Self
|
2018-04-14 01:02:01 +02:00
|
|
|
where
|
|
|
|
HeaderName: HttpTryFrom<K>,
|
|
|
|
V: IntoHeaderValue,
|
2017-12-27 04:48:02 +01:00
|
|
|
{
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.header(key, value);
|
2017-12-27 04:48:02 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-03-11 01:10:41 +01:00
|
|
|
/// Set cookie for this request
|
2019-03-17 05:35:02 +01:00
|
|
|
pub fn cookie(mut self, cookie: Cookie) -> Self {
|
2019-03-11 01:10:41 +01:00
|
|
|
self.req.cookie(cookie);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
/// Set request path pattern parameter
|
|
|
|
pub fn param(mut self, name: &'static str, value: &'static str) -> Self {
|
|
|
|
self.path.add_static(name, value);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2018-02-20 05:01:38 +01:00
|
|
|
/// Set request payload
|
2019-03-02 07:51:32 +01:00
|
|
|
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
|
2019-03-03 01:24:14 +01:00
|
|
|
self.req.set_payload(data);
|
2018-02-20 05:01:38 +01:00
|
|
|
self
|
|
|
|
}
|
2018-03-02 04:12:59 +01:00
|
|
|
|
2019-05-19 04:36:28 +02:00
|
|
|
/// Serialize `data` to JSON and set it as the request payload. The `Content-Type` header is
|
|
|
|
/// set to `application/json`.
|
|
|
|
pub fn set_json<T: Serialize>(mut self, data: &T) -> Self {
|
2019-05-22 20:18:33 +02:00
|
|
|
let bytes =
|
|
|
|
serde_json::to_string(data).expect("Failed to serialize test data to json");
|
2019-05-19 04:36:28 +02:00
|
|
|
self.req.set_payload(bytes);
|
|
|
|
self.req.set(ContentType::json());
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-03-17 17:52:41 +01:00
|
|
|
/// Set application data. This is equivalent of `App::data()` method
|
|
|
|
/// for testing purpose.
|
2019-05-05 04:43:49 +02:00
|
|
|
pub fn data<T: 'static>(mut self, data: T) -> Self {
|
|
|
|
self.app_data.insert(Data::new(data));
|
2019-03-17 17:52:41 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-03-09 23:06:24 +01:00
|
|
|
#[cfg(test)]
|
|
|
|
/// Set request config
|
|
|
|
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
|
|
|
|
self.rmap = rmap;
|
2019-03-04 00:32:47 +01:00
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2019-04-07 23:43:07 +02:00
|
|
|
/// Complete request creation and generate `Request` instance
|
2019-04-13 23:50:54 +02:00
|
|
|
pub fn to_request(mut self) -> Request {
|
2019-04-07 23:43:07 +02:00
|
|
|
self.req.finish()
|
|
|
|
}
|
|
|
|
|
2019-03-03 01:24:14 +01:00
|
|
|
/// Complete request creation and generate `ServiceRequest` instance
|
2019-04-13 23:50:54 +02:00
|
|
|
pub fn to_srv_request(mut self) -> ServiceRequest {
|
2019-04-08 08:06:21 +02:00
|
|
|
let (head, payload) = self.req.finish().into_parts();
|
2019-04-15 04:52:12 +02:00
|
|
|
self.path.get_mut().update(&head.uri);
|
2019-03-03 01:24:14 +01:00
|
|
|
|
2019-05-22 20:49:27 +02:00
|
|
|
ServiceRequest::new(HttpRequest::new(
|
2019-04-15 04:52:12 +02:00
|
|
|
self.path,
|
2019-04-08 08:06:21 +02:00
|
|
|
head,
|
2019-05-22 20:49:27 +02:00
|
|
|
payload,
|
2019-03-09 16:39:34 +01:00
|
|
|
Rc::new(self.rmap),
|
2019-03-09 23:06:24 +01:00
|
|
|
AppConfig::new(self.config),
|
2019-05-05 04:43:49 +02:00
|
|
|
Rc::new(self.app_data),
|
2019-04-08 08:06:21 +02:00
|
|
|
HttpRequestPool::create(),
|
2019-05-22 20:49:27 +02:00
|
|
|
))
|
2019-03-03 01:24:14 +01:00
|
|
|
}
|
|
|
|
|
2019-04-01 05:43:00 +02:00
|
|
|
/// Complete request creation and generate `ServiceResponse` instance
|
|
|
|
pub fn to_srv_response<B>(self, res: HttpResponse<B>) -> ServiceResponse<B> {
|
|
|
|
self.to_srv_request().into_response(res)
|
|
|
|
}
|
|
|
|
|
2017-12-27 04:48:02 +01:00
|
|
|
/// Complete request creation and generate `HttpRequest` instance
|
2019-03-04 06:02:01 +01:00
|
|
|
pub fn to_http_request(mut self) -> HttpRequest {
|
2019-05-22 20:49:27 +02:00
|
|
|
let (head, payload) = self.req.finish().into_parts();
|
2019-04-15 04:52:12 +02:00
|
|
|
self.path.get_mut().update(&head.uri);
|
2019-03-03 01:24:14 +01:00
|
|
|
|
2019-05-05 04:43:49 +02:00
|
|
|
HttpRequest::new(
|
2019-04-15 04:52:12 +02:00
|
|
|
self.path,
|
2019-04-08 08:06:21 +02:00
|
|
|
head,
|
2019-05-22 20:49:27 +02:00
|
|
|
payload,
|
2019-03-09 16:39:34 +01:00
|
|
|
Rc::new(self.rmap),
|
2019-03-09 23:06:24 +01:00
|
|
|
AppConfig::new(self.config),
|
2019-05-05 04:43:49 +02:00
|
|
|
Rc::new(self.app_data),
|
2019-04-08 08:06:21 +02:00
|
|
|
HttpRequestPool::create(),
|
2019-05-05 04:43:49 +02:00
|
|
|
)
|
2019-03-03 01:24:14 +01:00
|
|
|
}
|
2019-03-03 09:57:48 +01:00
|
|
|
|
2019-04-07 23:43:07 +02:00
|
|
|
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
|
|
|
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
|
2019-04-08 08:06:21 +02:00
|
|
|
let (head, payload) = self.req.finish().into_parts();
|
2019-04-15 04:52:12 +02:00
|
|
|
self.path.get_mut().update(&head.uri);
|
2019-03-03 09:57:48 +01:00
|
|
|
|
2019-05-05 04:43:49 +02:00
|
|
|
let req = HttpRequest::new(
|
2019-04-15 04:52:12 +02:00
|
|
|
self.path,
|
2019-04-08 08:06:21 +02:00
|
|
|
head,
|
2019-05-22 20:49:27 +02:00
|
|
|
Payload::None,
|
2019-03-09 16:39:34 +01:00
|
|
|
Rc::new(self.rmap),
|
2019-03-09 23:06:24 +01:00
|
|
|
AppConfig::new(self.config),
|
2019-05-05 04:43:49 +02:00
|
|
|
Rc::new(self.app_data),
|
2019-04-08 08:06:21 +02:00
|
|
|
HttpRequestPool::create(),
|
|
|
|
);
|
2019-05-05 04:43:49 +02:00
|
|
|
|
2019-04-08 08:06:21 +02:00
|
|
|
(req, payload)
|
2019-03-03 09:57:48 +01:00
|
|
|
}
|
2019-04-15 04:52:12 +02:00
|
|
|
}
|
2019-04-15 01:25:45 +02:00
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2019-05-19 04:36:28 +02:00
|
|
|
use actix_http::httpmessage::HttpMessage;
|
2019-04-15 04:52:12 +02:00
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use std::time::SystemTime;
|
|
|
|
|
|
|
|
use super::*;
|
|
|
|
use crate::{http::header, web, App, HttpResponse};
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_basics() {
|
|
|
|
let req = TestRequest::with_hdr(header::ContentType::json())
|
|
|
|
.version(Version::HTTP_2)
|
|
|
|
.set(header::Date(SystemTime::now().into()))
|
|
|
|
.param("test", "123")
|
2019-05-05 04:43:49 +02:00
|
|
|
.data(10u32)
|
2019-04-15 04:52:12 +02:00
|
|
|
.to_http_request();
|
|
|
|
assert!(req.headers().contains_key(header::CONTENT_TYPE));
|
|
|
|
assert!(req.headers().contains_key(header::DATE));
|
|
|
|
assert_eq!(&req.match_info()["test"], "123");
|
|
|
|
assert_eq!(req.version(), Version::HTTP_2);
|
2019-05-05 04:43:49 +02:00
|
|
|
let data = req.get_app_data::<u32>().unwrap();
|
|
|
|
assert!(req.get_app_data::<u64>().is_none());
|
2019-04-15 04:52:12 +02:00
|
|
|
assert_eq!(*data, 10);
|
|
|
|
assert_eq!(*data.get_ref(), 10);
|
2019-05-05 04:43:49 +02:00
|
|
|
|
|
|
|
assert!(req.app_data::<u64>().is_none());
|
|
|
|
let data = req.app_data::<u32>().unwrap();
|
|
|
|
assert_eq!(*data, 10);
|
2019-04-15 04:52:12 +02:00
|
|
|
}
|
|
|
|
|
2019-04-19 00:06:32 +02:00
|
|
|
#[test]
|
|
|
|
fn test_request_methods() {
|
|
|
|
let mut app = init_service(
|
|
|
|
App::new().service(
|
|
|
|
web::resource("/index.html")
|
|
|
|
.route(web::put().to(|| HttpResponse::Ok().body("put!")))
|
2019-04-29 18:14:36 +02:00
|
|
|
.route(web::patch().to(|| HttpResponse::Ok().body("patch!")))
|
2019-04-29 18:26:12 +02:00
|
|
|
.route(web::delete().to(|| HttpResponse::Ok().body("delete!"))),
|
2019-04-19 00:06:32 +02:00
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
let put_req = TestRequest::put()
|
|
|
|
.uri("/index.html")
|
|
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
|
|
.to_request();
|
|
|
|
|
|
|
|
let result = read_response(&mut app, put_req);
|
|
|
|
assert_eq!(result, Bytes::from_static(b"put!"));
|
|
|
|
|
|
|
|
let patch_req = TestRequest::patch()
|
|
|
|
.uri("/index.html")
|
|
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
|
|
.to_request();
|
|
|
|
|
|
|
|
let result = read_response(&mut app, patch_req);
|
|
|
|
assert_eq!(result, Bytes::from_static(b"patch!"));
|
2019-04-29 18:14:36 +02:00
|
|
|
|
2019-04-29 18:26:12 +02:00
|
|
|
let delete_req = TestRequest::delete().uri("/index.html").to_request();
|
2019-04-29 18:14:36 +02:00
|
|
|
let result = read_response(&mut app, delete_req);
|
|
|
|
assert_eq!(result, Bytes::from_static(b"delete!"));
|
2019-04-19 00:06:32 +02:00
|
|
|
}
|
|
|
|
|
2019-04-15 04:52:12 +02:00
|
|
|
#[test]
|
|
|
|
fn test_response() {
|
|
|
|
let mut app = init_service(
|
|
|
|
App::new().service(
|
|
|
|
web::resource("/index.html")
|
|
|
|
.route(web::post().to(|| HttpResponse::Ok().body("welcome!"))),
|
|
|
|
),
|
|
|
|
);
|
|
|
|
|
|
|
|
let req = TestRequest::post()
|
|
|
|
.uri("/index.html")
|
|
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
|
|
.to_request();
|
|
|
|
|
|
|
|
let result = read_response(&mut app, req);
|
|
|
|
assert_eq!(result, Bytes::from_static(b"welcome!"));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
|
|
pub struct Person {
|
|
|
|
id: String,
|
|
|
|
name: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_response_json() {
|
|
|
|
let mut app = init_service(App::new().service(web::resource("/people").route(
|
|
|
|
web::post().to(|person: web::Json<Person>| {
|
|
|
|
HttpResponse::Ok().json(person.into_inner())
|
|
|
|
}),
|
|
|
|
)));
|
|
|
|
|
|
|
|
let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes();
|
|
|
|
|
|
|
|
let req = TestRequest::post()
|
|
|
|
.uri("/people")
|
|
|
|
.header(header::CONTENT_TYPE, "application/json")
|
|
|
|
.set_payload(payload)
|
|
|
|
.to_request();
|
|
|
|
|
|
|
|
let result: Person = read_response_json(&mut app, req);
|
|
|
|
assert_eq!(&result.id, "12345");
|
2019-04-15 01:25:45 +02:00
|
|
|
}
|
2019-04-29 18:45:37 +02:00
|
|
|
|
2019-05-19 04:36:28 +02:00
|
|
|
#[test]
|
|
|
|
fn test_request_response_json() {
|
|
|
|
let mut app = init_service(App::new().service(web::resource("/people").route(
|
|
|
|
web::post().to(|person: web::Json<Person>| {
|
|
|
|
HttpResponse::Ok().json(person.into_inner())
|
|
|
|
}),
|
|
|
|
)));
|
|
|
|
|
2019-05-22 20:18:33 +02:00
|
|
|
let payload = Person {
|
|
|
|
id: "12345".to_string(),
|
|
|
|
name: "User name".to_string(),
|
|
|
|
};
|
2019-05-19 04:36:28 +02:00
|
|
|
|
|
|
|
let req = TestRequest::post()
|
|
|
|
.uri("/people")
|
|
|
|
.set_json(&payload)
|
|
|
|
.to_request();
|
|
|
|
|
|
|
|
assert_eq!(req.content_type(), "application/json");
|
|
|
|
|
|
|
|
let result: Person = read_response_json(&mut app, req);
|
|
|
|
assert_eq!(&result.id, "12345");
|
|
|
|
assert_eq!(&result.name, "User name");
|
|
|
|
}
|
|
|
|
|
2019-04-29 18:45:37 +02:00
|
|
|
#[test]
|
|
|
|
fn test_async_with_block() {
|
|
|
|
fn async_with_block() -> impl Future<Item = HttpResponse, Error = Error> {
|
|
|
|
web::block(move || Some(4).ok_or("wrong")).then(|res| match res {
|
|
|
|
Ok(value) => HttpResponse::Ok()
|
|
|
|
.content_type("text/plain")
|
|
|
|
.body(format!("Async with block value: {}", value)),
|
|
|
|
Err(_) => panic!("Unexpected"),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
let mut app = init_service(
|
|
|
|
App::new().service(web::resource("/index.html").to_async(async_with_block)),
|
|
|
|
);
|
|
|
|
|
|
|
|
let req = TestRequest::post().uri("/index.html").to_request();
|
2019-04-29 19:14:08 +02:00
|
|
|
let res = block_fn(|| app.call(req)).unwrap();
|
2019-04-29 18:45:37 +02:00
|
|
|
assert!(res.status().is_success());
|
|
|
|
}
|
2019-06-12 12:15:06 +02:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_actor() {
|
|
|
|
use actix::Actor;
|
|
|
|
|
|
|
|
struct MyActor;
|
|
|
|
|
|
|
|
struct Num(usize);
|
|
|
|
impl actix::Message for Num {
|
|
|
|
type Result = usize;
|
|
|
|
}
|
|
|
|
impl actix::Actor for MyActor {
|
|
|
|
type Context = actix::Context<Self>;
|
|
|
|
}
|
|
|
|
impl actix::Handler<Num> for MyActor {
|
|
|
|
type Result = usize;
|
|
|
|
fn handle(&mut self, msg: Num, _: &mut Self::Context) -> Self::Result {
|
|
|
|
msg.0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let addr = run_on(|| MyActor.start());
|
|
|
|
let mut app = init_service(App::new().service(
|
|
|
|
web::resource("/index.html").to_async(move || {
|
|
|
|
addr.send(Num(1)).from_err().and_then(|res| {
|
|
|
|
if res == 1 {
|
|
|
|
HttpResponse::Ok()
|
|
|
|
} else {
|
|
|
|
HttpResponse::BadRequest()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}),
|
|
|
|
));
|
|
|
|
|
|
|
|
let req = TestRequest::post().uri("/index.html").to_request();
|
|
|
|
let res = block_fn(|| app.call(req)).unwrap();
|
|
|
|
assert!(res.status().is_success());
|
|
|
|
}
|
2019-03-03 01:24:14 +01:00
|
|
|
}
|