2019-01-27 19:59:07 +01:00
|
|
|
//! Various helpers for Actix applications to use during testing.
|
|
|
|
use std::sync::mpsc;
|
2019-03-13 22:41:40 +01:00
|
|
|
use std::{net, thread, time};
|
2019-01-27 19:59:07 +01:00
|
|
|
|
|
|
|
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
|
|
|
use actix_rt::{Runtime, System};
|
|
|
|
use actix_server::{Server, StreamServiceFactory};
|
2019-03-30 02:51:07 +01:00
|
|
|
use awc::{error::PayloadError, ws, Client, ClientRequest, ClientResponse, Connector};
|
|
|
|
use bytes::Bytes;
|
|
|
|
use futures::future::lazy;
|
|
|
|
use futures::{Future, Stream};
|
2019-01-27 19:59:07 +01:00
|
|
|
use http::Method;
|
|
|
|
use net2::TcpBuilder;
|
|
|
|
|
|
|
|
/// The `TestServer` type.
|
|
|
|
///
|
|
|
|
/// `TestServer` is very simple test server that simplify process of writing
|
|
|
|
/// integration tests cases for actix web applications.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
2019-03-26 20:50:51 +01:00
|
|
|
/// use actix_http::HttpService;
|
|
|
|
/// use actix_http_test::TestServer;
|
|
|
|
/// use actix_web::{web, App, HttpResponse};
|
2019-03-30 05:13:39 +01:00
|
|
|
///
|
2019-03-26 20:50:51 +01:00
|
|
|
/// fn my_handler() -> HttpResponse {
|
|
|
|
/// HttpResponse::Ok().into()
|
|
|
|
/// }
|
2019-01-27 19:59:07 +01:00
|
|
|
///
|
2019-03-26 20:50:51 +01:00
|
|
|
/// fn main() {
|
|
|
|
/// let mut srv = TestServer::new(
|
|
|
|
/// || HttpService::new(
|
|
|
|
/// App::new().service(
|
|
|
|
/// web::resource("/").to(my_handler))
|
|
|
|
/// )
|
|
|
|
/// );
|
2019-01-27 19:59:07 +01:00
|
|
|
///
|
2019-03-26 20:50:51 +01:00
|
|
|
/// let req = srv.get();
|
|
|
|
/// let response = srv.block_on(req.send()).unwrap();
|
|
|
|
/// assert!(response.status().is_success());
|
|
|
|
/// }
|
2019-01-27 19:59:07 +01:00
|
|
|
/// ```
|
|
|
|
pub struct TestServer;
|
|
|
|
|
2019-03-13 22:41:40 +01:00
|
|
|
/// Test server controller
|
|
|
|
pub struct TestServerRuntime {
|
2019-01-27 19:59:07 +01:00
|
|
|
addr: net::SocketAddr,
|
|
|
|
rt: Runtime,
|
2019-03-26 19:43:22 +01:00
|
|
|
client: Client,
|
2019-01-27 19:59:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl TestServer {
|
|
|
|
/// Start new test server with application factory
|
2019-03-13 22:41:40 +01:00
|
|
|
pub fn new<F: StreamServiceFactory>(factory: F) -> TestServerRuntime {
|
2019-01-27 19:59:07 +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();
|
|
|
|
|
|
|
|
Server::build()
|
2019-03-09 07:47:49 +01:00
|
|
|
.listen("test", tcp, factory)?
|
2019-01-27 19:59:07 +01:00
|
|
|
.workers(1)
|
|
|
|
.disable_signals()
|
|
|
|
.start();
|
|
|
|
|
|
|
|
tx.send((System::current(), local_addr)).unwrap();
|
2019-03-07 07:56:34 +01:00
|
|
|
sys.run()
|
2019-01-27 19:59:07 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
let (system, addr) = rx.recv().unwrap();
|
2019-03-26 19:43:22 +01:00
|
|
|
let mut rt = Runtime::new().unwrap();
|
|
|
|
|
|
|
|
let client = rt
|
|
|
|
.block_on(lazy(move || {
|
|
|
|
let connector = {
|
|
|
|
#[cfg(feature = "ssl")]
|
|
|
|
{
|
|
|
|
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()
|
|
|
|
.timeout(time::Duration::from_millis(500))
|
|
|
|
.ssl(builder.build())
|
|
|
|
.service()
|
|
|
|
}
|
|
|
|
#[cfg(not(feature = "ssl"))]
|
|
|
|
{
|
|
|
|
Connector::new()
|
|
|
|
.timeout(time::Duration::from_millis(500))
|
|
|
|
.service()
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
Ok::<Client, ()>(Client::build().connector(connector).finish())
|
|
|
|
}))
|
|
|
|
.unwrap();
|
2019-01-27 19:59:07 +01:00
|
|
|
System::set_current(system);
|
2019-03-26 19:43:22 +01:00
|
|
|
TestServerRuntime { addr, rt, client }
|
2019-01-27 19:59:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// 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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-03-13 22:41:40 +01:00
|
|
|
impl TestServerRuntime {
|
2019-01-27 19:59:07 +01:00
|
|
|
/// 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)
|
|
|
|
}
|
|
|
|
|
2019-03-13 22:41:40 +01:00
|
|
|
/// Execute function on current core
|
|
|
|
pub fn execute<F, R>(&mut self, fut: F) -> R
|
2019-01-27 19:59:07 +01:00
|
|
|
where
|
2019-03-13 22:41:40 +01:00
|
|
|
F: FnOnce() -> R,
|
2019-01-27 19:59:07 +01:00
|
|
|
{
|
2019-03-13 22:41:40 +01:00
|
|
|
self.rt.block_on(lazy(|| Ok::<_, ()>(fut()))).unwrap()
|
2019-01-27 19:59:07 +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('/') {
|
|
|
|
format!("http://127.0.0.1:{}{}", self.addr.port(), uri)
|
|
|
|
} else {
|
|
|
|
format!("http://127.0.0.1:{}/{}", self.addr.port(), uri)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-02-06 20:44:15 +01:00
|
|
|
/// Construct test https server url
|
|
|
|
pub fn surl(&self, uri: &str) -> String {
|
|
|
|
if uri.starts_with('/') {
|
|
|
|
format!("https://127.0.0.1:{}{}", self.addr.port(), uri)
|
|
|
|
} else {
|
|
|
|
format!("https://127.0.0.1:{}/{}", self.addr.port(), uri)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-01-27 19:59:07 +01:00
|
|
|
/// Create `GET` request
|
2019-03-30 15:53:45 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2019-03-12 00:42:33 +01:00
|
|
|
/// Create https `GET` request
|
2019-03-30 15:53:45 +01:00
|
|
|
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
|
2019-03-30 15:53:45 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2019-03-26 19:43:22 +01:00
|
|
|
/// Create https `POST` request
|
2019-03-30 15:53:45 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2019-03-26 19:43:22 +01:00
|
|
|
/// Create `HEAD` request
|
2019-03-30 15:53:45 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2019-03-26 19:43:22 +01:00
|
|
|
/// Create https `HEAD` request
|
2019-03-30 15:53:45 +01:00
|
|
|
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
|
|
|
}
|
|
|
|
|
2019-03-26 19:43:22 +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-03-30 02:51:07 +01:00
|
|
|
pub fn load_body<S>(
|
|
|
|
&mut self,
|
|
|
|
response: ClientResponse<S>,
|
|
|
|
) -> Result<Bytes, PayloadError>
|
|
|
|
where
|
|
|
|
S: Stream<Item = Bytes, Error = PayloadError> + 'static,
|
|
|
|
{
|
|
|
|
self.block_on(response.body().limit(10_485_760))
|
2019-01-27 19:59:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Connect to websocket server at a given path
|
|
|
|
pub fn ws_at(
|
|
|
|
&mut self,
|
|
|
|
path: &str,
|
2019-03-28 02:53:19 +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-01-27 19:59:07 +01:00
|
|
|
self.rt
|
2019-03-28 02:53:19 +01:00
|
|
|
.block_on(lazy(move || connect.map(|(_, framed)| framed)))
|
2019-01-27 19:59:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Connect to a websocket server
|
|
|
|
pub fn ws(
|
|
|
|
&mut self,
|
2019-03-28 02:53:19 +01:00
|
|
|
) -> Result<Framed<impl AsyncRead + AsyncWrite, ws::Codec>, awc::error::WsClientError>
|
|
|
|
{
|
2019-01-27 19:59:07 +01:00
|
|
|
self.ws_at("/")
|
|
|
|
}
|
2019-03-30 02:51:07 +01:00
|
|
|
|
|
|
|
/// Stop http server
|
|
|
|
fn stop(&mut self) {
|
|
|
|
System::current().stop();
|
|
|
|
}
|
2019-01-27 19:59:07 +01:00
|
|
|
}
|
|
|
|
|
2019-03-13 22:41:40 +01:00
|
|
|
impl Drop for TestServerRuntime {
|
2019-01-27 19:59:07 +01:00
|
|
|
fn drop(&mut self) {
|
|
|
|
self.stop()
|
|
|
|
}
|
|
|
|
}
|