1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-25 08:52:42 +01:00
actix-web/src/test.rs

475 lines
13 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;
2018-11-19 06:48:20 +01:00
use std::sync::mpsc;
use std::{net, thread};
2018-12-11 03:08:33 +01:00
use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_rt::{Runtime, System};
use actix_server::{Server, StreamServiceFactory};
use actix_service::Service;
2018-06-01 18:36:16 +02:00
use bytes::Bytes;
2017-12-27 04:48:02 +01:00
use cookie::Cookie;
2018-11-19 06:48:20 +01:00
use futures::future::{lazy, Future};
2018-04-14 01:02:01 +02:00
use http::header::HeaderName;
use http::{HeaderMap, HttpTryFrom, Method, Uri, Version};
use net2::TcpBuilder;
2018-12-06 23:32:52 +01:00
use crate::body::MessageBody;
use crate::client::{
2018-11-19 06:48:20 +01:00
ClientRequest, ClientRequestBuilder, ClientResponse, Connect, Connection, Connector,
ConnectorError, SendRequestError,
};
2018-12-06 23:32:52 +01:00
use crate::header::{Header, IntoHeaderValue};
use crate::payload::Payload;
use crate::request::Request;
use crate::ws;
2017-12-27 04:48:02 +01:00
2018-10-05 20:04:59 +02:00
/// Test `Request` builder
2017-12-27 04:48:02 +01:00
///
2018-10-05 20:04:59 +02: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-10-05 20:04:59 +02:00
/// fn index(req: &HttpRequest) -> Response {
2017-12-27 04:48:02 +01:00
/// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) {
2018-10-05 20:04:59 +02:00
/// Response::Ok().into()
2017-12-27 04:48:02 +01:00
/// } else {
2018-10-05 20:04:59 +02:00
/// Response::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);
/// }
/// ```
2018-10-05 06:14:18 +02:00
pub struct TestRequest {
2017-12-27 04:48:02 +01:00
version: Version,
method: Method,
uri: Uri,
headers: HeaderMap,
2018-10-05 06:14:18 +02:00
_cookies: Option<Vec<Cookie<'static>>>,
2017-12-27 04:48:02 +01:00
payload: Option<Payload>,
2018-07-15 12:24:22 +02:00
prefix: u16,
2017-12-27 04:48:02 +01:00
}
2018-10-05 06:14:18 +02:00
impl Default for TestRequest {
fn default() -> TestRequest {
2017-12-27 04:48:02 +01:00
TestRequest {
method: Method::GET,
uri: Uri::from_str("/").unwrap(),
version: Version::HTTP_11,
headers: HeaderMap::new(),
2018-10-05 06:14:18 +02:00
_cookies: None,
2017-12-27 04:48:02 +01:00
payload: None,
2018-07-15 12:24:22 +02:00
prefix: 0,
2017-12-27 04:48:02 +01:00
}
}
}
2018-10-05 06:14:18 +02:00
impl TestRequest {
2018-01-15 22:47:25 +01:00
/// Create TestRequest and set request uri
2018-10-05 06:14:18 +02:00
pub fn with_uri(path: &str) -> TestRequest {
2017-12-27 04:48:02 +01:00
TestRequest::default().uri(path)
}
2018-03-06 04:28:42 +01:00
/// Create TestRequest and set header
2018-10-05 06:14:18 +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
2018-10-05 06:14:18 +02: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)
}
/// 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");
}
2018-02-20 05:01:38 +01:00
/// Set request payload
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();
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
2018-07-15 12:24:22 +02:00
/// Set request's prefix
pub fn prefix(mut self, prefix: u16) -> Self {
self.prefix = prefix;
self
}
2018-10-05 06:14:18 +02:00
/// Complete request creation and generate `Request` instance
pub fn finish(self) -> Request {
2018-04-14 01:02:01 +02:00
let TestRequest {
method,
uri,
version,
headers,
2018-10-05 06:14:18 +02:00
_cookies: _,
2018-04-14 01:02:01 +02:00
payload,
2018-10-05 06:14:18 +02:00
prefix: _,
2018-04-14 01:02:01 +02:00
} = self;
2018-03-07 23:56:53 +01:00
2018-10-05 06:14:18 +02:00
let mut req = Request::new();
2018-07-04 18:52:49 +02:00
{
let inner = req.inner_mut();
2018-11-19 05:08:43 +01:00
inner.head.uri = uri;
2018-11-16 07:34:29 +01:00
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;
}
2018-10-05 06:14:18 +02:00
// req.set_cookies(cookies);
2018-06-25 06:58:04 +02:00
req
}
2018-10-05 06:14:18 +02:00
// /// This method generates `HttpRequest` instance and runs handler
// /// with generated request.
2018-10-05 20:04:59 +02:00
// pub fn run<H: Handler<S>>(self, h: &H) -> Result<Response, Error> {
2018-10-05 06:14:18 +02:00
// let req = self.finish();
// let resp = h.handle(&req);
// match resp.respond_to(&req) {
// Ok(resp) => match resp.into().into() {
// AsyncResultItem::Ok(resp) => Ok(resp),
// AsyncResultItem::Err(err) => Err(err),
// AsyncResultItem::Future(fut) => {
// let mut sys = System::new("test");
// sys.block_on(fut)
// }
// },
// Err(err) => Err(err.into()),
// }
// }
// /// This method generates `HttpRequest` instance and runs handler
// /// with generated request.
// ///
// /// This method panics is handler returns actor.
2018-10-05 20:04:59 +02:00
// pub fn run_async<H, R, F, E>(self, h: H) -> Result<Response, E>
2018-10-05 06:14:18 +02:00
// where
// H: Fn(HttpRequest<S>) -> F + 'static,
// F: Future<Item = R, Error = E> + 'static,
// R: Responder<Error = E> + 'static,
// E: Into<Error> + 'static,
// {
// let req = self.finish();
// let fut = h(req.clone());
// let mut sys = System::new("test");
// match sys.block_on(fut) {
// Ok(r) => match r.respond_to(&req) {
// Ok(reply) => match reply.into().into() {
// AsyncResultItem::Ok(resp) => Ok(resp),
// _ => panic!("Nested async replies are not supported"),
// },
// Err(e) => Err(e),
// },
// Err(err) => Err(err),
// }
// }
// /// This method generates `HttpRequest` instance and executes handler
// pub fn run_async_result<F, R, I, E>(self, f: F) -> Result<I, E>
// where
// F: FnOnce(&HttpRequest<S>) -> R,
// R: Into<AsyncResult<I, E>>,
// {
// let req = self.finish();
// let res = f(&req);
// match res.into().into() {
// AsyncResultItem::Ok(resp) => Ok(resp),
// AsyncResultItem::Err(err) => Err(err),
// AsyncResultItem::Future(fut) => {
// let mut sys = System::new("test");
// sys.block_on(fut)
// }
// }
// }
// /// This method generates `HttpRequest` instance and executes handler
2018-10-05 20:04:59 +02:00
// pub fn execute<F, R>(self, f: F) -> Result<Response, Error>
2018-10-05 06:14:18 +02:00
// where
// F: FnOnce(&HttpRequest<S>) -> R,
// R: Responder + 'static,
// {
// let req = self.finish();
// let resp = f(&req);
// match resp.respond_to(&req) {
// Ok(resp) => match resp.into().into() {
// AsyncResultItem::Ok(resp) => Ok(resp),
// AsyncResultItem::Err(err) => Err(err),
// AsyncResultItem::Future(fut) => {
// let mut sys = System::new("test");
// sys.block_on(fut)
// }
// },
// Err(err) => Err(err.into()),
// }
// }
2017-12-27 04:48:02 +01:00
}
2018-11-19 06:48:20 +01:00
/// The `TestServer` type.
///
/// `TestServer` is very simple test server that simplify process of writing
/// integration tests cases for actix web applications.
///
/// # Examples
///
/// ```rust
/// # extern crate actix_web;
/// # use actix_web::*;
/// #
/// # fn my_handler(req: &HttpRequest) -> HttpResponse {
/// # HttpResponse::Ok().into()
/// # }
/// #
/// # fn main() {
/// use actix_web::test::TestServer;
///
/// let mut srv = TestServer::new(|app| app.handler(my_handler));
///
/// let req = srv.get().finish().unwrap();
/// let response = srv.execute(req.send()).unwrap();
/// assert!(response.status().is_success());
/// # }
/// ```
pub struct TestServer;
///
pub struct TestServerRuntime<T> {
addr: net::SocketAddr,
conn: T,
rt: Runtime,
}
impl TestServer {
/// Start new test server with application factory
pub fn with_factory<F: StreamServiceFactory>(
factory: F,
) -> TestServerRuntime<
2018-11-30 20:57:57 +01:00
impl Service<Connect, Response = impl Connection, Error = ConnectorError> + Clone,
2018-11-19 06:48:20 +01:00
> {
let (tx, rx) = mpsc::channel();
// run server in separate thread
thread::spawn(move || {
let sys = System::new("actix-test-server");
let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
let local_addr = tcp.local_addr().unwrap();
2018-12-11 03:08:33 +01:00
Server::build()
2018-11-19 06:48:20 +01:00
.listen("test", tcp, factory)
.workers(1)
.disable_signals()
.start();
tx.send((System::current(), local_addr)).unwrap();
sys.run();
});
let (system, addr) = rx.recv().unwrap();
System::set_current(system);
let mut rt = Runtime::new().unwrap();
let conn = rt
.block_on(lazy(|| Ok::<_, ()>(TestServer::new_connector())))
.unwrap();
TestServerRuntime { addr, conn, rt }
}
fn new_connector(
2018-12-06 23:32:52 +01:00
) -> impl Service<Connect, Response = impl Connection, Error = ConnectorError> + Clone
2018-11-30 20:57:57 +01:00
{
2018-11-19 06:48:20 +01:00
#[cfg(feature = "ssl")]
{
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
builder.set_verify(SslVerifyMode::NONE);
Connector::default().ssl(builder.build()).service()
}
#[cfg(not(feature = "ssl"))]
{
Connector::default().service()
}
}
/// Get firat available unused address
pub fn unused_addr() -> net::SocketAddr {
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
let socket = TcpBuilder::new_v4().unwrap();
socket.bind(&addr).unwrap();
socket.reuse_address(true).unwrap();
let tcp = socket.to_tcp_listener().unwrap();
tcp.local_addr().unwrap()
}
}
impl<T> TestServerRuntime<T> {
/// Execute future on current core
pub fn block_on<F, I, E>(&mut self, fut: F) -> Result<I, E>
where
F: Future<Item = I, Error = E>,
{
self.rt.block_on(fut)
}
2018-11-20 01:39:40 +01:00
/// Execute future on current core
pub fn execute<F, I, E>(&mut self, fut: F) -> Result<I, E>
where
F: Future<Item = I, Error = E>,
{
self.rt.block_on(fut)
}
2018-11-19 06:48:20 +01:00
/// Construct test server url
pub fn addr(&self) -> net::SocketAddr {
self.addr
}
/// Construct test server url
pub fn url(&self, uri: &str) -> String {
if uri.starts_with('/') {
2018-12-11 03:08:33 +01:00
format!("http://127.0.0.1:{}{}", self.addr.port(), uri)
2018-11-19 06:48:20 +01:00
} else {
2018-12-11 03:08:33 +01:00
format!("http://127.0.0.1:{}/{}", self.addr.port(), uri)
2018-11-19 06:48:20 +01:00
}
}
/// Create `GET` request
pub fn get(&self) -> ClientRequestBuilder {
ClientRequest::get(self.url("/").as_str())
}
/// Create `POST` request
pub fn post(&self) -> ClientRequestBuilder {
ClientRequest::post(self.url("/").as_str())
}
/// Create `HEAD` request
pub fn head(&self) -> ClientRequestBuilder {
ClientRequest::head(self.url("/").as_str())
}
/// Connect to test http server
pub fn client(&self, meth: Method, path: &str) -> ClientRequestBuilder {
ClientRequest::build()
.method(meth)
.uri(self.url(path).as_str())
.take()
}
/// Http connector
pub fn connector(&mut self) -> &mut T {
&mut self.conn
}
/// Http connector
pub fn new_connector(&mut self) -> T
where
T: Clone,
{
self.conn.clone()
}
/// Stop http server
fn stop(&mut self) {
System::current().stop();
}
}
impl<T> TestServerRuntime<T>
where
2018-11-30 20:57:57 +01:00
T: Service<Connect, Error = ConnectorError> + Clone,
2018-11-19 06:48:20 +01:00
T::Response: Connection,
{
/// Connect to websocket server at a given path
pub fn ws_at(
&mut self,
path: &str,
) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, ws::ClientError> {
let url = self.url(path);
self.rt
2018-11-19 23:57:12 +01:00
.block_on(lazy(|| ws::Client::default().call(ws::Connect::new(url))))
2018-11-19 06:48:20 +01:00
}
/// Connect to a websocket server
pub fn ws(
&mut self,
) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, ws::ClientError> {
self.ws_at("/")
}
/// Send request and read response message
pub fn send_request<B: MessageBody>(
&mut self,
req: ClientRequest<B>,
) -> Result<ClientResponse, SendRequestError> {
self.rt.block_on(req.send(&mut self.conn))
}
}
impl<T> Drop for TestServerRuntime<T> {
fn drop(&mut self) {
self.stop()
}
}