1
0
mirror of https://github.com/fafhrd91/actix-net synced 2024-11-23 21:51:06 +01:00

use actix-testing instead of test server

This commit is contained in:
Nikolay Kim 2019-09-25 09:51:28 +06:00
parent 41e49e8093
commit c859d13e3b
7 changed files with 46 additions and 204 deletions

View File

@ -23,7 +23,6 @@ members = [
"actix-server",
"actix-server-config",
"actix-testing",
"actix-test-server",
"actix-threadpool",
"actix-tower",
"actix-utils",

View File

@ -57,5 +57,5 @@ webpki = { version = "0.19", optional = true }
[dev-dependencies]
bytes = "0.4"
actix-test-server = { version="0.2.2", features=["ssl"] }
actix-testing = { version="0.1.0" }
actix-server-config = "0.1.0"

View File

@ -1,13 +1,12 @@
use actix_codec::{BytesCodec, Framed};
use actix_server_config::Io;
use actix_service::{service_fn, NewService, Service};
use actix_test_server::TestServer;
use actix_testing::{self as test, TestServer};
use bytes::Bytes;
use futures::{future::lazy, Future, Sink};
use http::{HttpTryFrom, Uri};
use trust_dns_resolver::config::{ResolverConfig, ResolverOpts};
use actix_connect::{default_connector, Connect};
use actix_connect::Connect;
#[cfg(feature = "ssl")]
#[test]
@ -44,7 +43,7 @@ fn test_rustls_string() {
}
#[test]
fn test_static_str() {
let mut srv = TestServer::with(|| {
let srv = TestServer::with(|| {
service_fn(|io: Io<tokio_tcp::TcpStream>| {
Framed::new(io.into_parts().0, BytesCodec)
.send(Bytes::from_static(b"test"))
@ -52,33 +51,29 @@ fn test_static_str() {
})
});
let resolver = srv
.block_on(lazy(
|| Ok::<_, ()>(actix_connect::start_default_resolver()),
))
.unwrap();
let mut conn = srv
.block_on(lazy(|| {
Ok::<_, ()>(actix_connect::new_connector(resolver.clone()))
}))
.unwrap();
let resolver = test::block_on(lazy(
|| Ok::<_, ()>(actix_connect::start_default_resolver()),
))
.unwrap();
let con = srv
.block_on(conn.call(Connect::with("10", srv.addr())))
.unwrap();
let mut conn = test::block_on(lazy(|| {
Ok::<_, ()>(actix_connect::new_connector(resolver.clone()))
}))
.unwrap();
let con = test::block_on(conn.call(Connect::with("10", srv.addr()))).unwrap();
assert_eq!(con.peer_addr().unwrap(), srv.addr());
let connect = Connect::new(srv.host().to_owned());
let mut conn = srv
.block_on(lazy(|| Ok::<_, ()>(actix_connect::new_connector(resolver))))
.unwrap();
let con = srv.block_on(conn.call(connect));
let mut conn =
test::block_on(lazy(|| Ok::<_, ()>(actix_connect::new_connector(resolver)))).unwrap();
let con = test::block_on(conn.call(connect));
assert!(con.is_err());
}
#[test]
fn test_new_service() {
let mut srv = TestServer::with(|| {
let srv = TestServer::with(|| {
service_fn(|io: Io<tokio_tcp::TcpStream>| {
Framed::new(io.into_parts().0, BytesCodec)
.send(Bytes::from_static(b"test"))
@ -86,24 +81,20 @@ fn test_new_service() {
})
});
let resolver = srv
.block_on(lazy(|| {
Ok::<_, ()>(actix_connect::start_resolver(
ResolverConfig::default(),
ResolverOpts::default(),
))
}))
.unwrap();
let factory = srv
.block_on(lazy(|| {
Ok::<_, ()>(actix_connect::new_connector_factory(resolver))
}))
.unwrap();
let resolver = test::block_on(lazy(|| {
Ok::<_, ()>(actix_connect::start_resolver(
ResolverConfig::default(),
ResolverOpts::default(),
))
}))
.unwrap();
let factory = test::block_on(lazy(|| {
Ok::<_, ()>(actix_connect::new_connector_factory(resolver))
}))
.unwrap();
let mut conn = srv.block_on(factory.new_service(&())).unwrap();
let con = srv
.block_on(conn.call(Connect::with("10", srv.addr())))
.unwrap();
let mut conn = test::block_on(factory.new_service(&())).unwrap();
let con = test::block_on(conn.call(Connect::with("10", srv.addr()))).unwrap();
assert_eq!(con.peer_addr().unwrap(), srv.addr());
}
@ -120,7 +111,7 @@ fn test_uri() {
let mut conn = default_connector();
let addr = Uri::try_from(format!("https://localhost:{}", srv.port())).unwrap();
let con = srv.run_on(move || conn.call(addr.into())).unwrap();
let con = test::run_on(move || conn.call(addr.into())).unwrap();
assert_eq!(con.peer_addr().unwrap(), srv.addr());
}
@ -137,6 +128,6 @@ fn test_rustls_uri() {
let mut conn = default_connector();
let addr = Uri::try_from(format!("https://localhost:{}", srv.port())).unwrap();
let con = srv.run_on(move || conn.call(addr.into())).unwrap();
let con = test::run_on(move || conn.call(addr.into())).unwrap();
assert_eq!(con.peer_addr().unwrap(), srv.addr());
}

View File

@ -29,7 +29,7 @@ log = "0.4"
[dev-dependencies]
actix-rt = "0.2.2"
actix-connect = "0.2.0"
actix-test-server = "0.2.2"
actix-testing = "0.1.0"
actix-server-config = "0.1.1"
tokio-tcp = "0.1"
tokio-timer = "0.2"

View File

@ -5,7 +5,7 @@ use std::time::Duration;
use actix_codec::BytesCodec;
use actix_server_config::Io;
use actix_service::{new_apply_fn, Service};
use actix_test_server::TestServer;
use actix_testing::{self as test, TestServer};
use futures::Future;
use tokio_tcp::TcpStream;
use tokio_timer::sleep;
@ -19,7 +19,7 @@ fn test_disconnect() -> std::io::Result<()> {
let disconnect = Arc::new(AtomicBool::new(false));
let disconnect1 = disconnect.clone();
let mut srv = TestServer::with(move || {
let srv = TestServer::with(move || {
let disconnect1 = disconnect1.clone();
new_apply_fn(
@ -41,15 +41,14 @@ fn test_disconnect() -> std::io::Result<()> {
})
.finish(|_t| Ok(None));
let conn = srv
.block_on(
actix_connect::default_connector()
.call(actix_connect::Connect::with(String::new(), srv.addr())),
)
.unwrap();
let conn = test::block_on(
actix_connect::default_connector()
.call(actix_connect::Connect::with(String::new(), srv.addr())),
)
.unwrap();
srv.block_on(client.call(conn.into_parts().0)).unwrap();
let _ = srv.block_on(
test::block_on(client.call(conn.into_parts().0)).unwrap();
let _ = test::block_on(
sleep(Duration::from_millis(100))
.map(|_| ())
.map_err(|_| ()),

View File

@ -1,6 +1,6 @@
[package]
name = "actix-test-server"
version = "0.2.2"
version = "0.2.3"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix test server"
keywords = ["network", "framework", "async", "futures"]
@ -11,7 +11,6 @@ categories = ["network-programming", "asynchronous"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
workspace = ".."
[lib]
name = "actix_test_server"
@ -21,6 +20,7 @@ path = "src/lib.rs"
actix-rt = "0.2.1"
actix-server = "0.5.0"
actix-server-config = "0.1.0"
actix-testing = "0.1.0"
log = "0.4"
net2 = "0.2"

View File

@ -1,149 +1,2 @@
//! Various helpers for Actix applications to use during testing.
use std::sync::mpsc;
use std::{net, thread};
use actix_rt::{Runtime, System};
use actix_server::{Server, StreamServiceFactory};
pub use actix_server_config::{Io, ServerConfig};
use futures::future::{lazy, Future, IntoFuture};
use net2::TcpBuilder;
use tokio_reactor::Handle;
use tokio_tcp::TcpStream;
/// The `TestServer` type.
///
/// `TestServer` is very simple test server that simplify process of writing
/// integration tests for actix-net applications.
///
/// # Examples
///
/// ```rust
/// use actix_service::{service_fn, IntoNewService};
/// use actix_test_server::TestServer;
///
/// fn main() {
/// let srv = TestServer::with(|| service_fn(
/// |sock| {
/// println!("New connection: {:?}", sock);
/// Ok::<_, ()>(())
/// }
/// ));
///
/// println!("SOCKET: {:?}", srv.connect());
/// }
/// ```
pub struct TestServer;
/// Test server runstime
pub struct TestServerRuntime {
addr: net::SocketAddr,
host: String,
port: u16,
rt: Runtime,
}
impl TestServer {
/// Start new test server with application factory
pub fn with<F: StreamServiceFactory>(factory: F) -> TestServerRuntime {
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 rt = Runtime::new().unwrap();
let host = format!("{}", addr.ip());
let port = addr.port();
TestServerRuntime {
addr,
rt,
host,
port,
}
}
/// Get firat available unused local 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 TestServerRuntime {
/// Execute future on current runtime
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)
}
/// Runs the provided function, with runtime enabled.
pub fn run_on<F, R>(&mut self, f: F) -> Result<R::Item, R::Error>
where
F: FnOnce() -> R,
R: IntoFuture,
{
self.rt.block_on(lazy(|| f().into_future()))
}
/// Spawn future to the current runtime
pub fn spawn<F>(&mut self, fut: F)
where
F: Future<Item = (), Error = ()> + 'static,
{
self.rt.spawn(fut);
}
/// Test server host
pub fn host(&self) -> &str {
&self.host
}
/// Test server port
pub fn port(&self) -> u16 {
self.port
}
/// Get test server address
pub fn addr(&self) -> net::SocketAddr {
self.addr
}
/// Stop http server
fn stop(&mut self) {
System::current().stop();
}
/// Connect to server, return tokio TcpStream
pub fn connect(&self) -> std::io::Result<TcpStream> {
TcpStream::from_std(net::TcpStream::connect(self.addr)?, &Handle::default())
}
}
impl Drop for TestServerRuntime {
fn drop(&mut self) {
self.stop()
}
}
pub use actix_testing::*;