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

197 lines
5.3 KiB
Rust
Raw Normal View History

//! Various helpers for Actix applications to use during testing.
2017-12-27 03:48:02 +00:00
use std::str::FromStr;
2019-03-02 06:51:32 +00:00
use bytes::Bytes;
use futures::IntoFuture;
use tokio_current_thread::Runtime;
2018-06-01 16:36:16 +00:00
2019-03-02 06:51:32 +00:00
use actix_http::dev::Payload;
use actix_http::http::header::{Header, HeaderName, IntoHeaderValue};
use actix_http::http::{HeaderMap, HttpTryFrom, Method, Uri, Version};
use actix_http::Request as HttpRequest;
use actix_router::{Path, Url};
2019-03-02 06:51:32 +00:00
use crate::app::State;
use crate::request::Request;
use crate::service::ServiceRequest;
2018-03-20 18:23:35 +00:00
2019-03-02 06:51:32 +00:00
/// Test `Request` builder
2018-03-29 04:49:50 +00:00
///
2019-03-02 06:51:32 +00:00
/// ```rust,ignore
2017-12-27 03:48:02 +00:00
/// # extern crate http;
/// # extern crate actix_web;
/// # use http::{header, StatusCode};
/// # use actix_web::*;
/// use actix_web::test::TestRequest;
///
2018-06-25 04:58:04 +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 resp = TestRequest::with_header("content-type", "text/plain")
2018-06-21 17:21:28 +00:00
/// .run(&index)
2018-06-01 16:36:16 +00:00
/// .unwrap();
2017-12-27 03:48:02 +00:00
/// assert_eq!(resp.status(), StatusCode::OK);
///
2018-06-21 17:21:28 +00:00
/// let resp = TestRequest::default().run(&index).unwrap();
2017-12-27 03:48:02 +00:00
/// assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
/// }
/// ```
pub struct TestRequest<S> {
state: S,
version: Version,
method: Method,
uri: Uri,
headers: HeaderMap,
2019-03-02 06:51:32 +00:00
params: Path<Url>,
2017-12-27 03:48:02 +00:00
payload: Option<Payload>,
}
impl Default for TestRequest<()> {
fn default() -> TestRequest<()> {
TestRequest {
state: (),
method: Method::GET,
uri: Uri::from_str("/").unwrap(),
version: Version::HTTP_11,
headers: HeaderMap::new(),
2019-03-02 06:51:32 +00:00
params: Path::new(Url::default()),
2017-12-27 03:48:02 +00:00
payload: None,
}
}
}
impl TestRequest<()> {
2018-01-15 21:47:25 +00:00
/// Create TestRequest and set request uri
2017-12-27 03:48:02 +00:00
pub fn with_uri(path: &str) -> TestRequest<()> {
TestRequest::default().uri(path)
}
2018-03-06 03:28:42 +00:00
/// Create TestRequest and set header
2018-04-13 23:02:01 +00:00
pub fn with_hdr<H: Header>(hdr: H) -> TestRequest<()> {
2018-03-06 03:28:42 +00:00
TestRequest::default().set(hdr)
}
2018-01-15 21:47:25 +00:00
/// Create TestRequest and set header
2017-12-27 03:48:02 +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
{
TestRequest::default().header(key, value)
}
}
2018-05-04 18:44:22 +00:00
impl<S: 'static> TestRequest<S> {
2017-12-27 03:48:02 +00:00
/// Start HttpRequest build process with application state
pub fn with_state(state: S) -> TestRequest<S> {
TestRequest {
2018-02-26 22:33:56 +00:00
state,
2017-12-27 03:48:02 +00:00
method: Method::GET,
uri: Uri::from_str("/").unwrap(),
version: Version::HTTP_11,
headers: HeaderMap::new(),
2019-03-02 06:51:32 +00:00
params: Path::new(Url::default()),
2017-12-27 03:48:02 +00:00
payload: None,
}
}
/// Set HTTP version of this request
pub fn version(mut self, ver: Version) -> Self {
self.version = ver;
self
}
/// Set HTTP method of this request
pub fn method(mut self, meth: Method) -> Self {
self.method = meth;
self
}
/// Set HTTP Uri of this request
pub fn uri(mut self, path: &str) -> Self {
self.uri = Uri::from_str(path).unwrap();
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 {
2018-03-06 03:28:42 +00:00
if let Ok(value) = hdr.try_into() {
self.headers.append(H::name(), value);
2018-04-13 23:02:01 +00:00
return self;
2018-03-06 03:28:42 +00:00
}
panic!("Can not set header");
}
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
{
if let Ok(key) = HeaderName::try_from(key) {
2018-03-06 08:43:25 +00:00
if let Ok(value) = value.try_into() {
2017-12-27 03:48:02 +00:00
self.headers.append(key, value);
2018-04-13 23:02:01 +00:00
return self;
2017-12-27 03:48:02 +00:00
}
}
panic!("Can not create header");
}
/// Set request path pattern parameter
pub fn param(mut self, name: &'static str, value: &'static str) -> Self {
2018-06-19 10:45:26 +00:00
self.params.add_static(name, value);
2017-12-27 03:48:02 +00:00
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 {
2018-02-20 04:01:38 +00:00
let mut payload = Payload::empty();
2019-03-02 06:51:32 +00:00
payload.unread_data(data.into());
2018-02-20 04:01:38 +00:00
self.payload = Some(payload);
self
}
2018-03-02 03:12:59 +00:00
2017-12-27 03:48:02 +00:00
/// Complete request creation and generate `HttpRequest` instance
2019-03-02 06:51:32 +00:00
pub fn finish(self) -> ServiceRequest<S> {
2018-04-13 23:02:01 +00:00
let TestRequest {
state,
method,
uri,
version,
headers,
2018-07-15 09:12:21 +00:00
mut params,
2018-04-13 23:02:01 +00:00
payload,
} = self;
2018-06-25 04:58:04 +00:00
2019-03-02 06:51:32 +00:00
params.get_mut().update(&uri);
2018-03-07 22:56:53 +00:00
2019-03-02 06:51:32 +00:00
let mut req = HttpRequest::new();
2018-07-04 16:52:49 +00:00
{
let inner = req.inner_mut();
2019-03-02 06:51:32 +00:00
inner.head.uri = uri;
inner.head.method = method;
inner.head.version = version;
inner.head.headers = headers;
2018-07-04 16:52:49 +00:00
*inner.payload.borrow_mut() = payload;
}
2019-03-02 06:51:32 +00:00
Request::new(State::new(state), req, params)
2017-12-27 03:48:02 +00:00
}
/// This method generates `HttpRequest` instance and executes handler
2019-03-02 06:51:32 +00:00
pub fn run_async<F, R, I, E>(self, f: F) -> Result<I, E>
where
2019-03-02 06:51:32 +00:00
F: FnOnce(&Request<S>) -> R,
R: IntoFuture<Item = I, Error = E>,
{
2019-03-02 06:51:32 +00:00
let mut rt = Runtime::new().unwrap();
rt.block_on(f(&self.finish()).into_future())
}
2017-12-27 03:48:02 +00:00
}