1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-12-18 01:43:58 +01:00
actix-web/actix-http-test/src/lib.rs

320 lines
9.9 KiB
Rust
Raw Normal View History

2019-01-27 19:59:07 +01:00
//! Various helpers for Actix applications to use during testing.
2021-12-08 07:09:56 +01:00
#![deny(rust_2018_idioms, nonstandard_style)]
#![warn(future_incompatible)]
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
2023-02-26 22:55:25 +01:00
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
2021-02-07 04:54:58 +01:00
#[cfg(feature = "openssl")]
extern crate tls_openssl as openssl;
2021-11-15 05:03:33 +01:00
use std::{net, thread, time::Duration};
2019-01-27 19:59:07 +01:00
use actix_codec::{AsyncRead, AsyncWrite, Framed};
2019-12-02 18:33:39 +01:00
use actix_rt::{net::TcpStream, System};
2021-12-27 19:45:31 +01:00
use actix_server::{Server, ServerServiceFactory};
use awc::{
error::PayloadError, http::header::HeaderMap, ws, Client, ClientRequest, ClientResponse,
Connector,
};
2019-03-30 02:51:07 +01:00
use bytes::Bytes;
use futures_core::stream::Stream;
2019-01-27 19:59:07 +01:00
use http::Method;
use socket2::{Domain, Protocol, Socket, Type};
2021-11-15 05:03:33 +01:00
use tokio::sync::mpsc;
2019-01-27 19:59:07 +01:00
/// Start test server.
2019-01-27 19:59:07 +01:00
///
/// `TestServer` is very simple test server that simplify process of writing integration tests cases
/// for HTTP applications.
2019-01-27 19:59:07 +01:00
///
/// # Examples
2019-03-30 05:13:39 +01:00
///
/// ```
/// use actix_http::{HttpService, Response, Error, StatusCode};
/// use actix_http_test::test_server;
/// use actix_service::{fn_service, map_config, ServiceFactoryExt as _};
2019-01-27 19:59:07 +01:00
///
/// #[actix_rt::test]
/// # async fn hidden_test() {}
2019-11-26 06:25:50 +01:00
/// async fn test_example() {
/// let srv = test_server(|| {
/// HttpService::build()
/// .h1(fn_service(|req| async move {
/// Ok::<_, Error>(Response::ok())
/// }))
/// .tcp()
/// .map_err(|_| ())
/// })
/// .await;
2019-01-27 19:59:07 +01:00
///
2019-11-26 06:25:50 +01:00
/// let req = srv.get("/");
/// let response = req.send().await.unwrap();
///
/// assert_eq!(response.status(), StatusCode::OK);
2019-03-26 20:50:51 +01:00
/// }
/// # actix_rt::System::new().block_on(test_example());
2019-01-27 19:59:07 +01:00
/// ```
2021-12-27 19:45:31 +01:00
pub async fn test_server<F: ServerServiceFactory<TcpStream>>(factory: F) -> TestServer {
let tcp = net::TcpListener::bind("127.0.0.1:0").unwrap();
test_server_with_addr(tcp, factory).await
}
2021-11-15 05:03:33 +01:00
/// Start [`test server`](test_server()) on an existing address binding.
2021-12-27 19:45:31 +01:00
pub async fn test_server_with_addr<F: ServerServiceFactory<TcpStream>>(
tcp: net::TcpListener,
factory: F,
) -> TestServer {
2021-11-15 05:03:33 +01:00
let (started_tx, started_rx) = std::sync::mpsc::channel();
let (thread_stop_tx, thread_stop_rx) = mpsc::channel(1);
2019-12-12 18:08:38 +01:00
// run server in separate thread
thread::spawn(move || {
System::new().block_on(async move {
let local_addr = tcp.local_addr().unwrap();
let srv = Server::build()
.workers(1)
.disable_signals()
.system_exit()
.listen("test", tcp, factory)
.expect("test server could not be created");
let srv = srv.run();
started_tx
.send((System::current(), srv.handle(), local_addr))
.unwrap();
// drive server loop
srv.await.unwrap();
});
2021-11-15 05:03:33 +01:00
// notify TestServer that server and system have shut down
// all thread managed resources should be dropped at this point
#[allow(clippy::let_underscore_future)]
2021-11-15 05:03:33 +01:00
let _ = thread_stop_tx.send(());
2019-12-12 18:08:38 +01:00
});
2021-11-15 05:03:33 +01:00
let (system, server, addr) = started_rx.recv().unwrap();
2019-12-12 18:08:38 +01:00
let client = {
2021-11-15 05:03:33 +01:00
#[cfg(feature = "openssl")]
let connector = {
use openssl::ssl::{SslConnector, SslMethod, SslVerifyMode};
let mut builder = SslConnector::builder(SslMethod::tls()).unwrap();
builder.set_verify(SslVerifyMode::NONE);
let _ = builder
.set_alpn_protos(b"\x02h2\x08http/1.1")
.map_err(|e| log::error!("Can not set alpn protocol: {:?}", e));
Connector::new()
.conn_lifetime(Duration::from_secs(0))
.timeout(Duration::from_millis(30000))
.openssl(builder.build())
2021-11-15 05:03:33 +01:00
};
#[cfg(not(feature = "openssl"))]
2019-12-12 18:08:38 +01:00
let connector = {
2021-11-15 05:03:33 +01:00
Connector::new()
.conn_lifetime(Duration::from_secs(0))
.timeout(Duration::from_millis(30000))
2019-12-12 18:08:38 +01:00
};
Client::builder().connector(connector).finish()
2019-12-12 18:08:38 +01:00
};
TestServer {
2021-11-15 05:03:33 +01:00
server,
2019-12-12 18:08:38 +01:00
client,
system,
2021-11-15 05:03:33 +01:00
addr,
thread_stop_rx,
2019-12-12 18:08:38 +01:00
}
}
2019-03-13 22:41:40 +01:00
/// Test server controller
2019-12-12 18:08:38 +01:00
pub struct TestServer {
2021-11-15 05:03:33 +01:00
server: actix_server::ServerHandle,
client: awc::Client,
system: actix_rt::System,
2019-01-27 19:59:07 +01:00
addr: net::SocketAddr,
2021-11-15 05:03:33 +01:00
thread_stop_rx: mpsc::Receiver<()>,
2019-01-27 19:59:07 +01:00
}
impl TestServer {
/// 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('/') {
format!("http://localhost:{}{}", self.addr.port(), uri)
2019-01-27 19:59:07 +01:00
} else {
format!("http://localhost:{}/{}", self.addr.port(), uri)
2019-01-27 19:59:07 +01:00
}
}
2021-02-11 23:39:54 +01:00
/// Construct test HTTPS server URL.
2019-02-06 20:44:15 +01:00
pub fn surl(&self, uri: &str) -> String {
if uri.starts_with('/') {
format!("https://localhost:{}{}", self.addr.port(), uri)
2019-02-06 20:44:15 +01:00
} else {
format!("https://localhost:{}/{}", self.addr.port(), uri)
2019-02-06 20:44:15 +01:00
}
}
2019-01-27 19:59:07 +01:00
/// Create `GET` request
pub fn get<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.get(self.url(path.as_ref()).as_str())
2019-01-27 19:59:07 +01:00
}
2021-02-11 23:39:54 +01:00
/// Create HTTPS `GET` request
pub fn sget<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.get(self.surl(path.as_ref()).as_str())
2019-03-12 00:42:33 +01:00
}
2019-01-27 19:59:07 +01:00
/// Create `POST` request
pub fn post<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.post(self.url(path.as_ref()).as_str())
2019-01-27 19:59:07 +01:00
}
2021-02-11 23:39:54 +01:00
/// Create HTTPS `POST` request
pub fn spost<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.post(self.surl(path.as_ref()).as_str())
2019-01-27 19:59:07 +01:00
}
/// Create `HEAD` request
pub fn head<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.head(self.url(path.as_ref()).as_str())
2019-01-27 19:59:07 +01:00
}
2021-02-11 23:39:54 +01:00
/// Create HTTPS `HEAD` request
pub fn shead<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.head(self.surl(path.as_ref()).as_str())
2019-01-27 19:59:07 +01:00
}
/// Create `PUT` request
pub fn put<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.put(self.url(path.as_ref()).as_str())
}
2021-02-11 23:39:54 +01:00
/// Create HTTPS `PUT` request
pub fn sput<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.put(self.surl(path.as_ref()).as_str())
}
/// Create `PATCH` request
pub fn patch<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.patch(self.url(path.as_ref()).as_str())
}
2021-02-11 23:39:54 +01:00
/// Create HTTPS `PATCH` request
pub fn spatch<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.patch(self.surl(path.as_ref()).as_str())
}
/// Create `DELETE` request
pub fn delete<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.delete(self.url(path.as_ref()).as_str())
}
2021-02-11 23:39:54 +01:00
/// Create HTTPS `DELETE` request
pub fn sdelete<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.delete(self.surl(path.as_ref()).as_str())
}
/// Create `OPTIONS` request
pub fn options<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.options(self.url(path.as_ref()).as_str())
}
2021-02-11 23:39:54 +01:00
/// Create HTTPS `OPTIONS` request
pub fn soptions<S: AsRef<str>>(&self, path: S) -> ClientRequest {
self.client.options(self.surl(path.as_ref()).as_str())
}
2021-02-11 23:39:54 +01:00
/// Connect to test HTTP server
pub fn request<S: AsRef<str>>(&self, method: Method, path: S) -> ClientRequest {
self.client.request(method, path.as_ref())
2019-01-27 19:59:07 +01:00
}
2019-11-19 13:54:19 +01:00
pub async fn load_body<S>(
2019-03-30 02:51:07 +01:00
&mut self,
2019-04-02 23:27:54 +02:00
mut response: ClientResponse<S>,
2019-03-30 02:51:07 +01:00
) -> Result<Bytes, PayloadError>
where
S: Stream<Item = Result<Bytes, PayloadError>> + Unpin + 'static,
2019-03-30 02:51:07 +01:00
{
2019-11-19 13:54:19 +01:00
response.body().limit(10_485_760).await
2019-01-27 19:59:07 +01:00
}
2021-02-12 01:27:20 +01:00
/// Connect to WebSocket server at a given path.
2019-11-19 13:54:19 +01:00
pub async fn ws_at(
2019-01-27 19:59:07 +01:00
&mut self,
path: &str,
2021-02-12 00:03:17 +01:00
) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, awc::error::WsClientError> {
2019-01-27 19:59:07 +01:00
let url = self.url(path);
2019-03-28 02:53:19 +01:00
let connect = self.client.ws(url).connect();
2019-11-19 13:54:19 +01:00
connect.await.map(|(_, framed)| framed)
2019-01-27 19:59:07 +01:00
}
2021-02-12 01:27:20 +01:00
/// Connect to a WebSocket server.
2019-11-19 13:54:19 +01:00
pub async fn ws(
2019-01-27 19:59:07 +01:00
&mut self,
2021-02-12 00:03:17 +01:00
) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, awc::error::WsClientError> {
2019-11-19 13:54:19 +01:00
self.ws_at("/").await
2019-01-27 19:59:07 +01:00
}
2019-03-30 02:51:07 +01:00
/// Get default HeaderMap of Client.
///
/// Returns Some(&mut HeaderMap) when Client object is unique
/// (No other clone of client exists at the same time).
pub fn client_headers(&mut self) -> Option<&mut HeaderMap> {
self.client.headers()
}
/// Stop HTTP server.
2021-11-15 05:03:33 +01:00
///
/// Waits for spawned `Server` and `System` to (force) shutdown.
2021-11-15 05:03:33 +01:00
pub async fn stop(&mut self) {
// signal server to stop
self.server.stop(false).await;
2021-11-15 05:03:33 +01:00
// also signal system to stop
// though this is handled by `ServerBuilder::exit_system` too
2019-09-17 17:45:06 +02:00
self.system.stop();
2021-11-15 05:03:33 +01:00
// wait for thread to be stopped but don't care about result
let _ = self.thread_stop_rx.recv().await;
2019-03-30 02:51:07 +01:00
}
2019-01-27 19:59:07 +01:00
}
2019-12-12 18:08:38 +01:00
impl Drop for TestServer {
2019-01-27 19:59:07 +01:00
fn drop(&mut self) {
2021-11-15 05:03:33 +01:00
// calls in this Drop impl should be enough to shut down the server, system, and thread
// without needing to await anything
// signal server to stop
#[allow(clippy::let_underscore_future)]
2021-11-15 05:03:33 +01:00
let _ = self.server.stop(true);
// signal system to stop
self.system.stop();
2019-01-27 19:59:07 +01:00
}
}
/// Get a localhost socket address with random, unused port.
pub fn unused_addr() -> net::SocketAddr {
let addr: net::SocketAddr = "127.0.0.1:0".parse().unwrap();
let socket = Socket::new(Domain::IPV4, Type::STREAM, Some(Protocol::TCP)).unwrap();
socket.bind(&addr.into()).unwrap();
socket.set_reuse_address(true).unwrap();
let tcp = net::TcpListener::from(socket);
tcp.local_addr().unwrap()
}