1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-09-08 20:58:26 +00:00
actix-web/src/test.rs

395 lines
12 KiB
Rust
Raw Normal View History

//! Various helpers for Actix applications to use during testing.
use std::cell::RefCell;
2019-03-03 00:24:14 +00:00
use std::rc::Rc;
2019-03-30 04:13:39 +00:00
use actix_http::cookie::Cookie;
2019-03-02 06:51:32 +00:00
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
2019-03-24 04:29:16 +00:00
use actix_http::http::{HttpTryFrom, Method, StatusCode, Version};
2019-03-03 06:03:45 +00:00
use actix_http::test::TestRequest as HttpTestRequest;
2019-03-17 16:52:41 +00:00
use actix_http::{Extensions, PayloadStream, Request};
use actix_router::{Path, ResourceDef, Url};
use actix_rt::Runtime;
use actix_server_config::ServerConfig;
2019-03-24 04:29:16 +00:00
use actix_service::{FnService, IntoNewService, NewService, Service};
2019-03-03 00:24:14 +00:00
use bytes::Bytes;
2019-03-13 05:57:09 +00:00
use futures::future::{lazy, Future};
use crate::config::{AppConfig, AppConfigInner};
2019-03-17 16:52:41 +00:00
use crate::data::RouteData;
2019-04-07 21:43:07 +00:00
use crate::dev::{Body, Payload};
use crate::request::HttpRequestPool;
use crate::rmap::ResourceMap;
2019-04-07 21:43:07 +00:00
use crate::service::{ServiceRequest, ServiceResponse};
2019-03-24 04:29:16 +00:00
use crate::{Error, HttpRequest, HttpResponse};
2018-03-20 18:23:35 +00:00
thread_local! {
static RT: RefCell<Runtime> = {
RefCell::new(Runtime::new().unwrap())
};
}
/// 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
F: Future,
{
RT.with(move |rt| rt.borrow_mut().block_on(f))
}
2019-03-13 05:57:09 +00: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 12:04:39 +00:00
pub fn run_on<F, R>(f: F) -> R
2019-03-13 05:57:09 +00:00
where
2019-03-28 12:04:39 +00:00
F: Fn() -> R,
2019-03-13 05:57:09 +00:00
{
2019-03-28 12:04:39 +00:00
RT.with(move |rt| rt.borrow_mut().block_on(lazy(|| Ok::<_, ()>(f()))))
.unwrap()
2019-03-13 05:57:09 +00:00
}
2019-03-30 17:04:38 +00:00
/// Create service that always responds with `HttpResponse::Ok()`
2019-03-24 04:29:16 +00:00
pub fn ok_service() -> impl Service<
Request = ServiceRequest<PayloadStream>,
Response = ServiceResponse<Body>,
Error = Error,
> {
default_service(StatusCode::OK)
}
2019-03-30 17:04:38 +00:00
/// Create service that responds with response with specified status code
2019-03-24 04:29:16 +00:00
pub fn default_service(
status_code: StatusCode,
) -> impl Service<
Request = ServiceRequest<PayloadStream>,
Response = ServiceResponse<Body>,
Error = Error,
> {
FnService::new(move |req: ServiceRequest<PayloadStream>| {
req.into_response(HttpResponse::build(status_code).finish())
})
}
2019-03-06 02:47:18 +00:00
/// This method accepts application builder instance, and constructs
/// service.
///
2019-03-06 03:03:59 +00:00
/// ```rust,ignore
2019-03-06 02:52:29 +00:00
/// use actix_service::Service;
2019-03-25 00:13:17 +00:00
/// use actix_web::{test, web, App, HttpResponse, http::StatusCode};
2019-03-06 02:47:18 +00:00
///
/// fn main() {
2019-03-06 02:52:29 +00:00
/// let mut app = test::init_service(
2019-03-06 02:47:18 +00:00
/// App::new()
2019-03-25 00:13:17 +00:00
/// .service(web::resource("/test").to(|| HttpResponse::Ok()))
2019-03-06 02:52:29 +00:00
/// );
2019-03-06 02:47:18 +00:00
///
2019-03-06 02:52:29 +00: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 02:47:18 +00:00
/// assert_eq!(resp.status(), StatusCode::OK);
/// }
/// ```
pub fn init_service<R, S, B, E>(
app: R,
) -> impl Service<Request = Request, Response = ServiceResponse<B>, Error = E>
2019-03-06 02:47:18 +00:00
where
R: IntoNewService<S, ServerConfig>,
S: NewService<
ServerConfig,
Request = Request,
Response = ServiceResponse<B>,
Error = E,
>,
2019-03-06 02:47:18 +00:00
S::InitError: std::fmt::Debug,
{
let cfg = ServerConfig::new("127.0.0.1:8080".parse().unwrap());
block_on(app.into_new_service().new_service(&cfg)).unwrap()
2019-03-06 02:47:18 +00:00
}
/// Calls service and waits for response future completion.
///
/// ```rust,ignore
/// use actix_web::{test, App, HttpResponse, http::StatusCode};
/// use actix_service::Service;
///
/// fn main() {
/// let mut app = test::init_service(
/// App::new()
2019-03-25 00:13:17 +00:00
/// .service(web::resource("/test").to(|| HttpResponse::Ok()))
/// );
///
/// // Create request object
/// let req = test::TestRequest::with_uri("/test").to_request();
///
/// // Call application
/// let resp = test::call_success(&mut app, req);
/// assert_eq!(resp.status(), StatusCode::OK);
/// }
/// ```
pub fn call_success<S, R, B, E>(app: &mut S, req: R) -> S::Response
where
S: Service<Request = R, Response = ServiceResponse<B>, Error = E>,
E: std::fmt::Debug,
{
block_on(app.call(req)).unwrap()
}
/// 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.
/// * `TestRequest::to_service` creates `ServiceRequest` instance, which is used for testing middlewares and chain adapters.
/// * `TestRequest::to_from` creates `ServiceFromRequest` instance, which is used for testing extractors.
/// * `TestRequest::to_http_request` creates `HttpRequest` instance, which is used for testing handlers.
2018-03-29 04:49:50 +00:00
///
2019-03-02 06:51:32 +00:00
/// ```rust,ignore
2019-03-06 03:03:59 +00:00
/// # use futures::IntoFuture;
/// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage};
/// use actix_web::http::{header, StatusCode};
2017-12-27 03:48:02 +00:00
///
/// fn index(req: HttpRequest) -> HttpResponse {
2017-12-27 03:48:02 +00:00
/// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
/// HttpResponse::Ok().into()
2017-12-27 03:48:02 +00:00
/// } else {
/// HttpResponse::BadRequest().into()
2017-12-27 03:48:02 +00:00
/// }
/// }
///
/// fn main() {
/// let req = test::TestRequest::with_header("content-type", "text/plain")
/// .to_http_request();
///
2019-03-06 03:03:59 +00:00
/// let resp = test::block_on(index(req).into_future()).unwrap();
2017-12-27 03:48:02 +00:00
/// assert_eq!(resp.status(), StatusCode::OK);
///
/// let req = test::TestRequest::default().to_http_request();
2019-03-06 03:03:59 +00:00
/// let resp = test::block_on(index(req).into_future()).unwrap();
2017-12-27 03:48:02 +00:00
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
/// }
/// ```
2019-03-03 06:03:45 +00:00
pub struct TestRequest {
req: HttpTestRequest,
rmap: ResourceMap,
config: AppConfigInner,
2019-03-17 16:52:41 +00:00
route_data: Extensions,
2017-12-27 03:48:02 +00:00
}
2019-03-03 06:03:45 +00:00
impl Default for TestRequest {
fn default() -> TestRequest {
TestRequest {
req: HttpTestRequest::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
config: AppConfigInner::default(),
2019-03-17 16:52:41 +00:00
route_data: Extensions::new(),
2017-12-27 03:48:02 +00:00
}
}
}
#[allow(clippy::wrong_self_convention)]
2019-03-03 06:03:45 +00:00
impl TestRequest {
2018-01-15 21:47:25 +00:00
/// Create TestRequest and set request uri
2019-03-03 06:03:45 +00:00
pub fn with_uri(path: &str) -> TestRequest {
TestRequest {
req: HttpTestRequest::default().uri(path).take(),
rmap: ResourceMap::new(ResourceDef::new("")),
config: AppConfigInner::default(),
2019-03-17 16:52:41 +00:00
route_data: Extensions::new(),
2019-03-03 00:24:14 +00:00
}
2017-12-27 03:48:02 +00:00
}
2018-03-06 03:28:42 +00:00
/// Create TestRequest and set header
2019-03-03 06:03:45 +00:00
pub fn with_hdr<H: Header>(hdr: H) -> TestRequest {
TestRequest {
req: HttpTestRequest::default().set(hdr).take(),
config: AppConfigInner::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
2019-03-17 16:52:41 +00:00
route_data: Extensions::new(),
2019-03-03 00:24:14 +00:00
}
2018-03-06 03:28:42 +00:00
}
2018-01-15 21:47:25 +00:00
/// Create TestRequest and set header
2019-03-03 06:03:45 +00:00
pub fn with_header<K, V>(key: K, value: V) -> TestRequest
2018-04-13 23:02:01 +00:00
where
HeaderName: HttpTryFrom<K>,
V: IntoHeaderValue,
2017-12-27 03:48:02 +00:00
{
2019-03-03 06:03:45 +00:00
TestRequest {
req: HttpTestRequest::default().header(key, value).take(),
config: AppConfigInner::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
2019-03-17 16:52:41 +00:00
route_data: Extensions::new(),
2017-12-27 03:48:02 +00:00
}
}
2019-03-06 02:47:18 +00:00
/// Create TestRequest and set method to `Method::GET`
pub fn get() -> TestRequest {
TestRequest {
req: HttpTestRequest::default().method(Method::GET).take(),
config: AppConfigInner::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
2019-03-17 16:52:41 +00:00
route_data: Extensions::new(),
2019-03-06 02:47:18 +00:00
}
}
/// Create TestRequest and set method to `Method::POST`
pub fn post() -> TestRequest {
TestRequest {
req: HttpTestRequest::default().method(Method::POST).take(),
config: AppConfigInner::default(),
rmap: ResourceMap::new(ResourceDef::new("")),
2019-03-17 16:52:41 +00:00
route_data: Extensions::new(),
2019-03-06 02:47:18 +00:00
}
}
2017-12-27 03:48:02 +00:00
/// Set HTTP version of this request
pub fn version(mut self, ver: Version) -> Self {
2019-03-03 00:24:14 +00:00
self.req.version(ver);
2017-12-27 03:48:02 +00:00
self
}
/// Set HTTP method of this request
pub fn method(mut self, meth: Method) -> Self {
2019-03-03 00:24:14 +00:00
self.req.method(meth);
2017-12-27 03:48:02 +00:00
self
}
/// Set HTTP Uri of this request
pub fn uri(mut self, path: &str) -> Self {
2019-03-03 00:24:14 +00:00
self.req.uri(path);
2017-12-27 03:48:02 +00:00
self
}
2018-03-06 03:28:42 +00:00
/// Set a header
2018-04-13 23:02:01 +00:00
pub fn set<H: Header>(mut self, hdr: H) -> Self {
2019-03-03 00:24:14 +00:00
self.req.set(hdr);
self
2018-03-06 03:28:42 +00:00
}
2017-12-27 03:48:02 +00:00
/// Set a header
pub fn header<K, V>(mut self, key: K, value: V) -> Self
2018-04-13 23:02:01 +00:00
where
HeaderName: HttpTryFrom<K>,
V: IntoHeaderValue,
2017-12-27 03:48:02 +00:00
{
2019-03-03 00:24:14 +00:00
self.req.header(key, value);
2017-12-27 03:48:02 +00:00
self
}
2019-03-11 00:10:41 +00:00
/// Set cookie for this request
pub fn cookie(mut self, cookie: Cookie) -> Self {
2019-03-11 00:10:41 +00:00
self.req.cookie(cookie);
self
}
2018-02-20 04:01:38 +00:00
/// Set request payload
2019-03-02 06:51:32 +00:00
pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self {
2019-03-03 00:24:14 +00:00
self.req.set_payload(data);
2018-02-20 04:01:38 +00:00
self
}
2018-03-02 03:12:59 +00:00
2019-03-17 16:52:41 +00:00
/// Set application data. This is equivalent of `App::data()` method
/// for testing purpose.
pub fn app_data<T: 'static>(self, data: T) -> Self {
self.config.extensions.borrow_mut().insert(data);
self
}
2019-03-17 16:52:41 +00:00
/// Set route data. This is equivalent of `Route::data()` method
/// for testing purpose.
pub fn route_data<T: 'static>(mut self, data: T) -> Self {
self.route_data.insert(RouteData::new(data));
self
}
#[cfg(test)]
/// Set request config
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
self.rmap = rmap;
2019-03-03 23:32:47 +00:00
self
}
2019-04-07 21:43:07 +00:00
/// Complete request creation and generate `Request` instance
pub fn to_request(mut self) -> Request<PayloadStream> {
self.req.finish()
}
2019-03-03 00:24:14 +00:00
/// Complete request creation and generate `ServiceRequest` instance
2019-04-01 03:43:00 +00:00
pub fn to_srv_request(mut self) -> ServiceRequest<PayloadStream> {
let (head, payload) = self.req.finish().into_parts();
2019-03-03 00:24:14 +00:00
let req = HttpRequest::new(
Path::new(Url::new(head.uri.clone())),
head,
Rc::new(self.rmap),
AppConfig::new(self.config),
HttpRequestPool::create(),
);
ServiceRequest::from_parts(req, payload)
2019-03-03 00:24:14 +00:00
}
2019-04-01 03:43:00 +00: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 03:48:02 +00:00
/// Complete request creation and generate `HttpRequest` instance
2019-03-04 05:02:01 +00:00
pub fn to_http_request(mut self) -> HttpRequest {
let (head, _) = self.req.finish().into_parts();
2019-03-03 00:24:14 +00:00
let mut req = HttpRequest::new(
Path::new(Url::new(head.uri.clone())),
head,
Rc::new(self.rmap),
AppConfig::new(self.config),
HttpRequestPool::create(),
);
2019-04-07 21:43:07 +00:00
req.set_route_data(Some(Rc::new(self.route_data)));
req
2019-03-03 00:24:14 +00:00
}
2019-03-03 08:57:48 +00:00
2019-04-07 21:43:07 +00:00
/// Complete request creation and generate `HttpRequest` and `Payload` instances
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
let (head, payload) = self.req.finish().into_parts();
2019-03-03 08:57:48 +00:00
let mut req = HttpRequest::new(
Path::new(Url::new(head.uri.clone())),
head,
Rc::new(self.rmap),
AppConfig::new(self.config),
HttpRequestPool::create(),
);
2019-04-07 21:43:07 +00:00
req.set_route_data(Some(Rc::new(self.route_data)));
(req, payload)
2019-03-03 08:57:48 +00: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
F: Future,
{
block_on(f)
}
2019-03-03 00:24:14 +00:00
}