From d3b7d2d6b3512887cf4e8c9ac52df0d4280ccec4 Mon Sep 17 00:00:00 2001 From: Nikolay Kim Date: Tue, 26 Dec 2017 16:47:55 -0800 Subject: [PATCH] allow to use application factory for test server --- src/test/mod.rs | 32 +++++++++++++++++++++++++++++++- tests/test_server.rs | 9 ++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/test/mod.rs b/src/test/mod.rs index e3e42082..247753b9 100644 --- a/src/test/mod.rs +++ b/src/test/mod.rs @@ -8,7 +8,7 @@ use tokio_core::net::TcpListener; use server::HttpServer; use handler::Handler; -use channel::IntoHttpHandler; +use channel::{HttpHandler, IntoHttpHandler}; use middlewares::Middleware; use application::{Application, HttpApplication}; @@ -56,6 +56,36 @@ impl TestServer { TestServer::with_state(||(), config) } + /// Start new test server with application factory + pub fn with_factory(factory: F) -> Self + where H: HttpHandler, + F: Sync + Send + 'static + Fn() -> U, + U: IntoIterator + 'static, + V: IntoHttpHandler, + { + let (tx, rx) = mpsc::channel(); + + // run server in separate thread + let join = thread::spawn(move || { + let sys = System::new("actix-test-server"); + let tcp = net::TcpListener::bind("0.0.0.0:0").unwrap(); + let local_addr = tcp.local_addr().unwrap(); + let tcp = TcpListener::from_listener(tcp, &local_addr, Arbiter::handle()).unwrap(); + + HttpServer::new(factory).start_incoming(tcp.incoming(), false); + + tx.send((Arbiter::system(), local_addr)).unwrap(); + let _ = sys.run(); + }); + + let (sys, addr) = rx.recv().unwrap(); + TestServer { + addr: addr, + thread: Some(join), + sys: sys, + } + } + /// Start new test server with custom application state /// /// This methos accepts state factory and configuration method. diff --git a/tests/test_server.rs b/tests/test_server.rs index 0c0a6bd7..d148e9ef 100644 --- a/tests/test_server.rs +++ b/tests/test_server.rs @@ -9,11 +9,18 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use actix_web::*; #[test] -fn test_serve() { +fn test_simple() { let srv = test::TestServer::new(|app| app.handler(httpcodes::HTTPOk)); assert!(reqwest::get(&srv.url("/")).unwrap().status().is_success()); } +#[test] +fn test_application() { + let srv = test::TestServer::with_factory( + || Application::new().resource("/", |r| r.h(httpcodes::HTTPOk))); + assert!(reqwest::get(&srv.url("/")).unwrap().status().is_success()); +} + struct MiddlewareTest { start: Arc, response: Arc,