mirror of
https://github.com/actix/actix-extras.git
synced 2025-07-01 12:15:08 +02:00
move TestServer to separate crate
This commit is contained in:
@ -5,7 +5,6 @@ use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite};
|
||||
use actix_rt::spawn;
|
||||
use actix_service::Service;
|
||||
use futures::future::{ok, Either, FutureResult};
|
||||
use futures::sync::oneshot;
|
||||
@ -265,7 +264,7 @@ where
|
||||
inner: Rc<RefCell<Inner<Io>>>,
|
||||
fut: F,
|
||||
) {
|
||||
spawn(OpenWaitingConnection {
|
||||
tokio_current_thread::spawn(OpenWaitingConnection {
|
||||
key,
|
||||
fut,
|
||||
rx: Some(rx),
|
||||
@ -408,7 +407,9 @@ where
|
||||
|| (now - conn.created) > self.conn_lifetime
|
||||
{
|
||||
if let Some(timeout) = self.disconnect_timeout {
|
||||
spawn(CloseConnection::new(conn.io, timeout))
|
||||
tokio_current_thread::spawn(CloseConnection::new(
|
||||
conn.io, timeout,
|
||||
))
|
||||
}
|
||||
} else {
|
||||
let mut io = conn.io;
|
||||
@ -417,7 +418,9 @@ where
|
||||
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => (),
|
||||
Ok(n) if n > 0 => {
|
||||
if let Some(timeout) = self.disconnect_timeout {
|
||||
spawn(CloseConnection::new(io, timeout))
|
||||
tokio_current_thread::spawn(CloseConnection::new(
|
||||
io, timeout,
|
||||
))
|
||||
}
|
||||
continue;
|
||||
}
|
||||
@ -433,7 +436,7 @@ where
|
||||
fn release_close(&mut self, io: Io) {
|
||||
self.acquired -= 1;
|
||||
if let Some(timeout) = self.disconnect_timeout {
|
||||
spawn(CloseConnection::new(io, timeout))
|
||||
tokio_current_thread::spawn(CloseConnection::new(io, timeout))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -4,7 +4,6 @@ use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
use std::{fmt, net};
|
||||
|
||||
use actix_rt::spawn;
|
||||
use bytes::BytesMut;
|
||||
use futures::{future, Future};
|
||||
use log::error;
|
||||
@ -355,10 +354,12 @@ impl DateService {
|
||||
|
||||
// periodic date update
|
||||
let s = self.clone();
|
||||
spawn(sleep(Duration::from_millis(500)).then(move |_| {
|
||||
s.0.reset();
|
||||
future::ok(())
|
||||
}));
|
||||
tokio_current_thread::spawn(sleep(Duration::from_millis(500)).then(
|
||||
move |_| {
|
||||
s.0.reset();
|
||||
future::ok(())
|
||||
},
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -567,14 +567,15 @@ where
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test::TestRequest;
|
||||
use encoding::all::ISO_8859_2;
|
||||
use encoding::Encoding;
|
||||
use futures::Async;
|
||||
use mime;
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
use super::*;
|
||||
use crate::test::TestRequest;
|
||||
|
||||
#[test]
|
||||
fn test_content_type() {
|
||||
let req = TestRequest::with_header("content-type", "text/plain").finish();
|
||||
|
@ -133,12 +133,12 @@ impl<T: HttpMessage + 'static, U: DeserializeOwned + 'static> Future for JsonBod
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use bytes::Bytes;
|
||||
use futures::Async;
|
||||
use http::header;
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
use super::*;
|
||||
use crate::test::TestRequest;
|
||||
|
||||
impl PartialEq for JsonPayloadError {
|
||||
|
@ -59,9 +59,6 @@
|
||||
//! * `session` - enables session support, includes `ring` crate as
|
||||
//! dependency
|
||||
//!
|
||||
// #![warn(missing_docs)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
pub mod body;
|
||||
pub mod client;
|
||||
mod config;
|
||||
|
227
src/test.rs
227
src/test.rs
@ -1,29 +1,14 @@
|
||||
//! Various helpers for Actix applications to use during testing.
|
||||
//! Test Various helpers for Actix applications to use during testing.
|
||||
use std::str::FromStr;
|
||||
use std::sync::mpsc;
|
||||
use std::{net, thread};
|
||||
|
||||
use actix_codec::{AsyncRead, AsyncWrite, Framed};
|
||||
use actix_rt::{Runtime, System};
|
||||
use actix_server::{Server, StreamServiceFactory};
|
||||
use actix_service::Service;
|
||||
|
||||
use bytes::Bytes;
|
||||
use cookie::Cookie;
|
||||
use futures::future::{lazy, Future};
|
||||
use http::header::HeaderName;
|
||||
use http::{HeaderMap, HttpTryFrom, Method, Uri, Version};
|
||||
use net2::TcpBuilder;
|
||||
|
||||
use crate::body::MessageBody;
|
||||
use crate::client::{
|
||||
ClientRequest, ClientRequestBuilder, ClientResponse, Connect, Connection, Connector,
|
||||
ConnectorError, SendRequestError,
|
||||
};
|
||||
use crate::header::{Header, IntoHeaderValue};
|
||||
use crate::payload::Payload;
|
||||
use crate::request::Request;
|
||||
use crate::ws;
|
||||
use crate::Request;
|
||||
|
||||
/// Test `Request` builder
|
||||
///
|
||||
@ -264,211 +249,3 @@ impl TestRequest {
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
/// 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<
|
||||
impl Service<Connect, Response = impl Connection, Error = ConnectorError> + Clone,
|
||||
> {
|
||||
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()
|
||||
.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(
|
||||
) -> impl Service<Connect, Response = impl Connection, Error = ConnectorError> + Clone
|
||||
{
|
||||
#[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)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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
|
||||
T: Service<Connect, Error = ConnectorError> + Clone,
|
||||
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
|
||||
.block_on(lazy(|| ws::Client::default().call(ws::Connect::new(url))))
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user