1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-28 09:42:40 +01:00
actix-extras/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 04:48:02 +01:00
use std::str::FromStr;
2019-03-02 07:51:32 +01:00
use bytes::Bytes;
use futures::IntoFuture;
use tokio_current_thread::Runtime;
2018-06-01 18:36:16 +02:00
2019-03-02 07:51:32 +01: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 07:51:32 +01:00
use crate::app::State;
use crate::request::Request;
use crate::service::ServiceRequest;
2018-03-20 19:23:35 +01:00
2019-03-02 07:51:32 +01:00
/// Test `Request` builder
2018-03-29 06:49:50 +02:00
///
2019-03-02 07:51:32 +01:00
/// ```rust,ignore
2017-12-27 04:48:02 +01:00
/// # extern crate http;
/// # extern crate actix_web;
/// # use http::{header, StatusCode};
/// # use actix_web::*;
/// use actix_web::test::TestRequest;
///
2018-06-25 06:58:04 +02:00
/// fn index(req: &HttpRequest) -> HttpResponse {
2017-12-27 04:48:02 +01:00
/// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
/// HttpResponse::Ok().into()
2017-12-27 04:48:02 +01:00
/// } else {
/// HttpResponse::BadRequest().into()
2017-12-27 04:48:02 +01:00
/// }
/// }
///
/// fn main() {
/// let resp = TestRequest::with_header("content-type", "text/plain")
2018-06-21 19:21:28 +02:00
/// .run(&index)
2018-06-01 18:36:16 +02:00
/// .unwrap();
2017-12-27 04:48:02 +01:00
/// assert_eq!(resp.status(), StatusCode::OK);
///
2018-06-21 19:21:28 +02:00
/// let resp = TestRequest::default().run(&index).unwrap();
2017-12-27 04:48:02 +01: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 07:51:32 +01:00
params: Path<Url>,
2017-12-27 04:48:02 +01: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 07:51:32 +01:00
params: Path::new(Url::default()),
2017-12-27 04:48:02 +01:00
payload: None,
}
}
}
impl TestRequest<()> {
2018-01-15 22:47:25 +01:00
/// Create TestRequest and set request uri
2017-12-27 04:48:02 +01:00
pub fn with_uri(path: &str) -> TestRequest<()> {
TestRequest::default().uri(path)
}
2018-03-06 04:28:42 +01:00
/// Create TestRequest and set header
2018-04-14 01:02:01 +02:00
pub fn with_hdr<H: Header>(hdr: H) -> TestRequest<()> {
2018-03-06 04:28:42 +01:00
TestRequest::default().set(hdr)
}
2018-01-15 22:47:25 +01:00
/// Create TestRequest and set header
2017-12-27 04:48:02 +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
{
TestRequest::default().header(key, value)
}
}
2018-05-04 20:44:22 +02:00
impl<S: 'static> TestRequest<S> {
2017-12-27 04:48:02 +01:00
/// Start HttpRequest build process with application state
pub fn with_state(state: S) -> TestRequest<S> {
TestRequest {
2018-02-26 23:33:56 +01:00
state,
2017-12-27 04:48:02 +01:00
method: Method::GET,
uri: Uri::from_str("/").unwrap(),
version: Version::HTTP_11,
headers: HeaderMap::new(),
2019-03-02 07:51:32 +01:00
params: Path::new(Url::default()),
2017-12-27 04:48:02 +01: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 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 {
2018-03-06 04:28:42 +01:00
if let Ok(value) = hdr.try_into() {
self.headers.append(H::name(), value);
2018-04-14 01:02:01 +02:00
return self;
2018-03-06 04:28:42 +01:00
}
panic!("Can not set header");
}
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
{
if let Ok(key) = HeaderName::try_from(key) {
2018-03-06 09:43:25 +01:00
if let Ok(value) = value.try_into() {
2017-12-27 04:48:02 +01:00
self.headers.append(key, value);
2018-04-14 01:02:01 +02:00
return self;
2017-12-27 04:48:02 +01: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 12:45:26 +02:00
self.params.add_static(name, value);
2017-12-27 04:48:02 +01:00
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 {
2018-02-20 05:01:38 +01:00
let mut payload = Payload::empty();
2019-03-02 07:51:32 +01:00
payload.unread_data(data.into());
2018-02-20 05:01:38 +01:00
self.payload = Some(payload);
self
}
2018-03-02 04:12:59 +01:00
2017-12-27 04:48:02 +01:00
/// Complete request creation and generate `HttpRequest` instance
2019-03-02 07:51:32 +01:00
pub fn finish(self) -> ServiceRequest<S> {
2018-04-14 01:02:01 +02:00
let TestRequest {
state,
method,
uri,
version,
headers,
2018-07-15 11:12:21 +02:00
mut params,
2018-04-14 01:02:01 +02:00
payload,
} = self;
2018-06-25 06:58:04 +02:00
2019-03-02 07:51:32 +01:00
params.get_mut().update(&uri);
2018-03-07 23:56:53 +01:00
2019-03-02 07:51:32 +01:00
let mut req = HttpRequest::new();
2018-07-04 18:52:49 +02:00
{
let inner = req.inner_mut();
2019-03-02 07:51:32 +01:00
inner.head.uri = uri;
inner.head.method = method;
inner.head.version = version;
inner.head.headers = headers;
2018-07-04 18:52:49 +02:00
*inner.payload.borrow_mut() = payload;
}
2019-03-02 07:51:32 +01:00
Request::new(State::new(state), req, params)
2017-12-27 04:48:02 +01:00
}
/// This method generates `HttpRequest` instance and executes handler
2019-03-02 07:51:32 +01:00
pub fn run_async<F, R, I, E>(self, f: F) -> Result<I, E>
where
2019-03-02 07:51:32 +01:00
F: FnOnce(&Request<S>) -> R,
R: IntoFuture<Item = I, Error = E>,
{
2019-03-02 07:51:32 +01:00
let mut rt = Runtime::new().unwrap();
rt.block_on(f(&self.finish()).into_future())
}
2017-12-27 04:48:02 +01:00
}