1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 00:21:08 +01:00

move TestServer to separate crate

This commit is contained in:
Nikolay Kim 2019-01-27 10:59:07 -08:00
parent 42277c5c8f
commit c3d3e8b465
12 changed files with 345 additions and 277 deletions

View File

@ -39,15 +39,13 @@ ssl = ["openssl", "actix-connector/ssl"]
[dependencies] [dependencies]
actix-service = "0.1.6" actix-service = "0.1.6"
actix-codec = "0.1.0" actix-codec = "0.1.0"
actix-connector = "0.1.0" # actix-connector = "0.1.0"
actix-rt = "0.1.0" # actix-utils = "0.1.0"
actix-server = "0.1.0" actix-connector = { git = "https://github.com/actix/actix-net.git" }
actix-utils = "0.1.0" actix-utils = { git = "https://github.com/actix/actix-net.git" }
# actix-codec = { path="../actix-net/actix-codec/" } # actix-codec = { path="../actix-net/actix-codec/" }
# actix-connector = { path="../actix-net/actix-connector/" } # actix-connector = { path="../actix-net/actix-connector/" }
# actix-rt = { path="../actix-net/actix-rt/" }
# actix-server = { path="../actix-net/actix-server/" }
# actix-utils = { path="../actix-net/actix-utils/" } # actix-utils = { path="../actix-net/actix-utils/" }
base64 = "0.10" base64 = "0.10"
@ -64,7 +62,6 @@ httparse = "1.3"
indexmap = "1.0" indexmap = "1.0"
log = "0.4" log = "0.4"
mime = "0.3" mime = "0.3"
net2 = "0.2"
percent-encoding = "1.0" percent-encoding = "1.0"
rand = "0.6" rand = "0.6"
serde = "1.0" serde = "1.0"
@ -73,19 +70,17 @@ sha1 = "0.6"
slab = "0.4" slab = "0.4"
serde_urlencoded = "0.5.3" serde_urlencoded = "0.5.3"
time = "0.1" time = "0.1"
tokio-tcp = "0.1"
tokio-timer = "0.2" tokio-timer = "0.2"
tokio-current-thread = "0.1"
trust-dns-resolver = { version="0.11.0-alpha.1", default-features = false } trust-dns-resolver = { version="0.11.0-alpha.1", default-features = false }
# openssl # openssl
openssl = { version="0.10", optional = true } openssl = { version="0.10", optional = true }
[dev-dependencies] [dev-dependencies]
actix-rt = "0.1.0"
actix-web = "0.7" actix-web = "0.7"
actix-server = "0.1"
actix-http-test = { path="test-server" }
env_logger = "0.6" env_logger = "0.6"
serde_derive = "1.0" serde_derive = "1.0"
[profile.release]
lto = true
opt-level = 3
codegen-units = 1

View File

@ -5,7 +5,6 @@ use std::rc::Rc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use actix_codec::{AsyncRead, AsyncWrite}; use actix_codec::{AsyncRead, AsyncWrite};
use actix_rt::spawn;
use actix_service::Service; use actix_service::Service;
use futures::future::{ok, Either, FutureResult}; use futures::future::{ok, Either, FutureResult};
use futures::sync::oneshot; use futures::sync::oneshot;
@ -265,7 +264,7 @@ where
inner: Rc<RefCell<Inner<Io>>>, inner: Rc<RefCell<Inner<Io>>>,
fut: F, fut: F,
) { ) {
spawn(OpenWaitingConnection { tokio_current_thread::spawn(OpenWaitingConnection {
key, key,
fut, fut,
rx: Some(rx), rx: Some(rx),
@ -408,7 +407,9 @@ where
|| (now - conn.created) > self.conn_lifetime || (now - conn.created) > self.conn_lifetime
{ {
if let Some(timeout) = self.disconnect_timeout { if let Some(timeout) = self.disconnect_timeout {
spawn(CloseConnection::new(conn.io, timeout)) tokio_current_thread::spawn(CloseConnection::new(
conn.io, timeout,
))
} }
} else { } else {
let mut io = conn.io; let mut io = conn.io;
@ -417,7 +418,9 @@ where
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => (), Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => (),
Ok(n) if n > 0 => { Ok(n) if n > 0 => {
if let Some(timeout) = self.disconnect_timeout { if let Some(timeout) = self.disconnect_timeout {
spawn(CloseConnection::new(io, timeout)) tokio_current_thread::spawn(CloseConnection::new(
io, timeout,
))
} }
continue; continue;
} }
@ -433,7 +436,7 @@ where
fn release_close(&mut self, io: Io) { fn release_close(&mut self, io: Io) {
self.acquired -= 1; self.acquired -= 1;
if let Some(timeout) = self.disconnect_timeout { if let Some(timeout) = self.disconnect_timeout {
spawn(CloseConnection::new(io, timeout)) tokio_current_thread::spawn(CloseConnection::new(io, timeout))
} }
} }

View File

@ -4,7 +4,6 @@ use std::rc::Rc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use std::{fmt, net}; use std::{fmt, net};
use actix_rt::spawn;
use bytes::BytesMut; use bytes::BytesMut;
use futures::{future, Future}; use futures::{future, Future};
use log::error; use log::error;
@ -355,10 +354,12 @@ impl DateService {
// periodic date update // periodic date update
let s = self.clone(); let s = self.clone();
spawn(sleep(Duration::from_millis(500)).then(move |_| { tokio_current_thread::spawn(sleep(Duration::from_millis(500)).then(
s.0.reset(); move |_| {
future::ok(()) s.0.reset();
})); future::ok(())
},
));
} }
} }

View File

@ -567,14 +567,15 @@ where
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use crate::test::TestRequest;
use encoding::all::ISO_8859_2; use encoding::all::ISO_8859_2;
use encoding::Encoding; use encoding::Encoding;
use futures::Async; use futures::Async;
use mime; use mime;
use serde_derive::Deserialize; use serde_derive::Deserialize;
use super::*;
use crate::test::TestRequest;
#[test] #[test]
fn test_content_type() { fn test_content_type() {
let req = TestRequest::with_header("content-type", "text/plain").finish(); let req = TestRequest::with_header("content-type", "text/plain").finish();

View File

@ -133,12 +133,12 @@ impl<T: HttpMessage + 'static, U: DeserializeOwned + 'static> Future for JsonBod
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*;
use bytes::Bytes; use bytes::Bytes;
use futures::Async; use futures::Async;
use http::header; use http::header;
use serde_derive::{Deserialize, Serialize}; use serde_derive::{Deserialize, Serialize};
use super::*;
use crate::test::TestRequest; use crate::test::TestRequest;
impl PartialEq for JsonPayloadError { impl PartialEq for JsonPayloadError {

View File

@ -59,9 +59,6 @@
//! * `session` - enables session support, includes `ring` crate as //! * `session` - enables session support, includes `ring` crate as
//! dependency //! dependency
//! //!
// #![warn(missing_docs)]
#![allow(dead_code)]
pub mod body; pub mod body;
pub mod client; pub mod client;
mod config; mod config;

View File

@ -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::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 bytes::Bytes;
use cookie::Cookie; use cookie::Cookie;
use futures::future::{lazy, Future};
use http::header::HeaderName; use http::header::HeaderName;
use http::{HeaderMap, HttpTryFrom, Method, Uri, Version}; 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::header::{Header, IntoHeaderValue};
use crate::payload::Payload; use crate::payload::Payload;
use crate::request::Request; use crate::Request;
use crate::ws;
/// Test `Request` builder /// 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()
}
}

64
test-server/Cargo.toml Normal file
View File

@ -0,0 +1,64 @@
[package]
name = "actix-http-test"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
description = "Actix http"
readme = "README.md"
keywords = ["http", "web", "framework", "async", "futures"]
homepage = "https://actix.rs"
repository = "https://github.com/actix/actix-web.git"
documentation = "https://actix.rs/api/actix-web/stable/actix_web/"
categories = ["network-programming", "asynchronous",
"web-programming::http-server",
"web-programming::websocket"]
license = "MIT/Apache-2.0"
exclude = [".gitignore", ".travis.yml", ".cargo/config", "appveyor.yml"]
edition = "2018"
[package.metadata.docs.rs]
features = ["session"]
[lib]
name = "actix_http_test"
path = "src/lib.rs"
[features]
default = ["session"]
# sessions feature, session require "ring" crate and c compiler
session = ["cookie/secure"]
# openssl
ssl = ["openssl", "actix-http/ssl"]
[dependencies]
actix-codec = "0.1"
actix-service = "0.1.6"
actix-rt = "0.1.0"
actix-server = "0.1.0"
actix-http = { path=".." }
actix-utils = { git = "https://github.com/actix/actix-net.git" }
# actix-codec = { path="../actix-net/actix-codec/" }
# actix-rt = { path="../actix-net/actix-rt/" }
# actix-server = { path="../actix-net/actix-server/" }
base64 = "0.10"
bytes = "0.4"
cookie = { version="0.11", features=["percent-encode"] }
futures = "0.1"
http = "0.1.8"
log = "0.4"
env_logger = "0.6"
net2 = "0.2"
serde = "1.0"
serde_json = "1.0"
sha1 = "0.6"
slab = "0.4"
serde_urlencoded = "0.5.3"
time = "0.1"
tokio-tcp = "0.1"
tokio-timer = "0.2"
# openssl
openssl = { version="0.10", optional = true }

227
test-server/src/lib.rs Normal file
View File

@ -0,0 +1,227 @@
//! Various helpers for Actix applications to use during testing.
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 futures::future::{lazy, Future};
use http::Method;
use net2::TcpBuilder;
use actix_http::body::MessageBody;
use actix_http::client::{
ClientRequest, ClientRequestBuilder, ClientResponse, Connect, Connection, Connector,
ConnectorError, SendRequestError,
};
use actix_http::ws;
/// 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()
}
}

View File

@ -3,7 +3,8 @@ use bytes::Bytes;
use futures::future::{self, ok}; use futures::future::{self, ok};
use actix_http::HttpMessage; use actix_http::HttpMessage;
use actix_http::{client, h1, test::TestServer, Request, Response}; use actix_http::{client, h1, Request, Response};
use actix_http_test::TestServer;
const STR: &str = "Hello World Hello World Hello World Hello World Hello World \ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \ Hello World Hello World Hello World Hello World Hello World \

View File

@ -2,19 +2,20 @@ use std::io::{Read, Write};
use std::time::Duration; use std::time::Duration;
use std::{net, thread}; use std::{net, thread};
use actix_http_test::TestServer;
use actix_service::NewService; use actix_service::NewService;
use bytes::Bytes; use bytes::Bytes;
use futures::future::{self, ok}; use futures::future::{self, ok};
use futures::stream::once; use futures::stream::once;
use actix_http::{ use actix_http::{
body, client, h1, http, test, Body, Error, HttpMessage as HttpMessage2, KeepAlive, body, client, h1, http, Body, Error, HttpMessage as HttpMessage2, KeepAlive,
Request, Response, Request, Response,
}; };
#[test] #[test]
fn test_h1_v2() { fn test_h1_v2() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::build() h1::H1Service::build()
.keep_alive(KeepAlive::Disabled) .keep_alive(KeepAlive::Disabled)
.client_timeout(1000) .client_timeout(1000)
@ -31,7 +32,7 @@ fn test_h1_v2() {
#[test] #[test]
fn test_slow_request() { fn test_slow_request() {
let srv = test::TestServer::with_factory(|| { let srv = TestServer::with_factory(|| {
h1::H1Service::build() h1::H1Service::build()
.client_timeout(100) .client_timeout(100)
.finish(|_| future::ok::<_, ()>(Response::Ok().finish())) .finish(|_| future::ok::<_, ()>(Response::Ok().finish()))
@ -47,7 +48,7 @@ fn test_slow_request() {
#[test] #[test]
fn test_malformed_request() { fn test_malformed_request() {
let srv = test::TestServer::with_factory(|| { let srv = TestServer::with_factory(|| {
h1::H1Service::new(|_| future::ok::<_, ()>(Response::Ok().finish())).map(|_| ()) h1::H1Service::new(|_| future::ok::<_, ()>(Response::Ok().finish())).map(|_| ())
}); });
@ -60,7 +61,7 @@ fn test_malformed_request() {
#[test] #[test]
fn test_keepalive() { fn test_keepalive() {
let srv = test::TestServer::with_factory(|| { let srv = TestServer::with_factory(|| {
h1::H1Service::build() h1::H1Service::build()
.finish(|_| future::ok::<_, ()>(Response::Ok().finish())) .finish(|_| future::ok::<_, ()>(Response::Ok().finish()))
.map(|_| ()) .map(|_| ())
@ -80,7 +81,7 @@ fn test_keepalive() {
#[test] #[test]
fn test_keepalive_timeout() { fn test_keepalive_timeout() {
let srv = test::TestServer::with_factory(|| { let srv = TestServer::with_factory(|| {
h1::H1Service::build() h1::H1Service::build()
.keep_alive(1) .keep_alive(1)
.finish(|_| future::ok::<_, ()>(Response::Ok().finish())) .finish(|_| future::ok::<_, ()>(Response::Ok().finish()))
@ -101,7 +102,7 @@ fn test_keepalive_timeout() {
#[test] #[test]
fn test_keepalive_close() { fn test_keepalive_close() {
let srv = test::TestServer::with_factory(|| { let srv = TestServer::with_factory(|| {
h1::H1Service::build() h1::H1Service::build()
.finish(|_| future::ok::<_, ()>(Response::Ok().finish())) .finish(|_| future::ok::<_, ()>(Response::Ok().finish()))
.map(|_| ()) .map(|_| ())
@ -121,7 +122,7 @@ fn test_keepalive_close() {
#[test] #[test]
fn test_keepalive_http10_default_close() { fn test_keepalive_http10_default_close() {
let srv = test::TestServer::with_factory(|| { let srv = TestServer::with_factory(|| {
h1::H1Service::build() h1::H1Service::build()
.finish(|_| future::ok::<_, ()>(Response::Ok().finish())) .finish(|_| future::ok::<_, ()>(Response::Ok().finish()))
.map(|_| ()) .map(|_| ())
@ -140,7 +141,7 @@ fn test_keepalive_http10_default_close() {
#[test] #[test]
fn test_keepalive_http10() { fn test_keepalive_http10() {
let srv = test::TestServer::with_factory(|| { let srv = TestServer::with_factory(|| {
h1::H1Service::build() h1::H1Service::build()
.finish(|_| future::ok::<_, ()>(Response::Ok().finish())) .finish(|_| future::ok::<_, ()>(Response::Ok().finish()))
.map(|_| ()) .map(|_| ())
@ -166,7 +167,7 @@ fn test_keepalive_http10() {
#[test] #[test]
fn test_keepalive_disabled() { fn test_keepalive_disabled() {
let srv = test::TestServer::with_factory(|| { let srv = TestServer::with_factory(|| {
h1::H1Service::build() h1::H1Service::build()
.keep_alive(KeepAlive::Disabled) .keep_alive(KeepAlive::Disabled)
.finish(|_| future::ok::<_, ()>(Response::Ok().finish())) .finish(|_| future::ok::<_, ()>(Response::Ok().finish()))
@ -191,7 +192,7 @@ fn test_content_length() {
StatusCode, StatusCode,
}; };
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::new(|req: Request| { h1::H1Service::new(|req: Request| {
let indx: usize = req.uri().path()[1..].parse().unwrap(); let indx: usize = req.uri().path()[1..].parse().unwrap();
let statuses = [ let statuses = [
@ -240,7 +241,7 @@ fn test_headers() {
let data = STR.repeat(10); let data = STR.repeat(10);
let data2 = data.clone(); let data2 = data.clone();
let mut srv = test::TestServer::with_factory(move || { let mut srv = TestServer::with_factory(move || {
let data = data.clone(); let data = data.clone();
h1::H1Service::new(move |_| { h1::H1Service::new(move |_| {
let mut builder = Response::Ok(); let mut builder = Response::Ok();
@ -302,7 +303,7 @@ const STR: &str = "Hello World Hello World Hello World Hello World Hello World \
#[test] #[test]
fn test_body() { fn test_body() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::new(|_| future::ok::<_, ()>(Response::Ok().body(STR))).map(|_| ()) h1::H1Service::new(|_| future::ok::<_, ()>(Response::Ok().body(STR))).map(|_| ())
}); });
@ -317,7 +318,7 @@ fn test_body() {
#[test] #[test]
fn test_head_empty() { fn test_head_empty() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::new(|_| ok::<_, ()>(Response::Ok().body(STR))).map(|_| ()) h1::H1Service::new(|_| ok::<_, ()>(Response::Ok().body(STR))).map(|_| ())
}); });
@ -340,7 +341,7 @@ fn test_head_empty() {
#[test] #[test]
fn test_head_binary() { fn test_head_binary() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::new(|_| { h1::H1Service::new(|_| {
ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR)) ok::<_, ()>(Response::Ok().content_length(STR.len() as u64).body(STR))
}) })
@ -366,7 +367,7 @@ fn test_head_binary() {
#[test] #[test]
fn test_head_binary2() { fn test_head_binary2() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::new(|_| ok::<_, ()>(Response::Ok().body(STR))).map(|_| ()) h1::H1Service::new(|_| ok::<_, ()>(Response::Ok().body(STR))).map(|_| ())
}); });
@ -385,7 +386,7 @@ fn test_head_binary2() {
#[test] #[test]
fn test_body_length() { fn test_body_length() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::new(|_| { h1::H1Service::new(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref()))); let body = once(Ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>( ok::<_, ()>(
@ -407,7 +408,7 @@ fn test_body_length() {
#[test] #[test]
fn test_body_chunked_explicit() { fn test_body_chunked_explicit() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::new(|_| { h1::H1Service::new(|_| {
let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref()))); let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(Response::Ok().streaming(body)) ok::<_, ()>(Response::Ok().streaming(body))
@ -428,7 +429,7 @@ fn test_body_chunked_explicit() {
#[test] #[test]
fn test_body_chunked_implicit() { fn test_body_chunked_implicit() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::new(|_| { h1::H1Service::new(|_| {
let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref()))); let body = once::<_, Error>(Ok(Bytes::from_static(STR.as_ref())));
ok::<_, ()>(Response::Ok().streaming(body)) ok::<_, ()>(Response::Ok().streaming(body))
@ -447,7 +448,7 @@ fn test_body_chunked_implicit() {
#[test] #[test]
fn test_response_http_error_handling() { fn test_response_http_error_handling() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
h1::H1Service::new(|_| { h1::H1Service::new(|_| {
let broken_header = Bytes::from_static(b"\0\0\0"); let broken_header = Bytes::from_static(b"\0\0\0");
ok::<_, ()>( ok::<_, ()>(

View File

@ -1,6 +1,7 @@
use std::io; use std::io;
use actix_codec::Framed; use actix_codec::Framed;
use actix_http_test::TestServer;
use actix_service::NewService; use actix_service::NewService;
use actix_utils::framed::IntoFramed; use actix_utils::framed::IntoFramed;
use actix_utils::stream::TakeItem; use actix_utils::stream::TakeItem;
@ -9,7 +10,7 @@ use bytes::{Bytes, BytesMut};
use futures::future::{lazy, ok, Either}; use futures::future::{lazy, ok, Either};
use futures::{Future, Sink, Stream}; use futures::{Future, Sink, Stream};
use actix_http::{h1, test, ws, ResponseError, SendResponse, ServiceConfig}; use actix_http::{h1, ws, ResponseError, SendResponse, ServiceConfig};
fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Error> { fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Error> {
match req { match req {
@ -34,7 +35,7 @@ fn ws_service(req: ws::Frame) -> impl Future<Item = ws::Message, Error = io::Err
#[test] #[test]
fn test_simple() { fn test_simple() {
let mut srv = test::TestServer::with_factory(|| { let mut srv = TestServer::with_factory(|| {
IntoFramed::new(|| h1::Codec::new(ServiceConfig::default())) IntoFramed::new(|| h1::Codec::new(ServiceConfig::default()))
.and_then(TakeItem::new().map_err(|_| ())) .and_then(TakeItem::new().map_err(|_| ()))
.and_then(|(req, framed): (_, Framed<_, _>)| { .and_then(|(req, framed): (_, Framed<_, _>)| {