Merge pull request #64 from seanmonstar/tests-ergo-frames

add ergonomics to testing with frames
This commit is contained in:
Sean McArthur
2017-09-07 20:16:39 -07:00
committed by GitHub
5 changed files with 388 additions and 142 deletions

View File

@@ -53,90 +53,75 @@ fn send_data_without_requesting_capacity() {
fn release_capacity_sends_window_update() {
let _ = ::env_logger::init();
let payload = vec![0; 65_535];
let payload = vec![0u8; 65_535];
let mock = mock_io::Builder::new()
.handshake()
.write(&[
// GET /
0, 0, 16, 1, 5, 0, 0, 0, 1, 130, 135, 65, 139, 157, 41,
172, 75, 143, 168, 233, 25, 151, 33, 233, 132,
])
.write(frames::SETTINGS_ACK)
// Read response
.read(&[0, 0, 1, 1, 4, 0, 0, 0, 1, 0x88])
.read(&[
// DATA
0, 64, 0, 0, 0, 0, 0, 0, 1,
])
.read(&payload[0..16_384])
.read(&[
// DATA
0, 64, 0, 0, 0, 0, 0, 0, 1,
])
.read(&payload[16_384..16_384*2])
.read(&[
// DATA
0, 64, 0, 0, 0, 0, 0, 0, 1,
])
.read(&payload[16_384*2..16_384*3])
.write(&[0, 0, 4, 8, 0, 0, 0, 0, 0, 0, 0, 128, 0])
.write(&[0, 0, 4, 8, 0, 0, 0, 0, 1, 0, 0, 128, 0])
.read(&[
// DATA
0, 63, 255, 0, 1, 0, 0, 0, 1,
])
.read(&payload[16_384*3..16_384*4 - 1])
let (io, srv) = mock::new();
// we send a 2nd stream in order to test the window update is
// is actually written to the socket
.write(&[
// GET /
0, 0, 4, 1, 5, 0, 0, 0, 3, 130, 135, 190, 132,
])
.read(&[0, 0, 1, 1, 5, 0, 0, 0, 3, 0x88])
.build();
let mock = srv.assert_client_handshake().unwrap()
.recv_settings()
.recv_frame(
frames::headers(1)
.request("GET", "https://http2.akamai.com/")
.eos()
)
.send_frame(
frames::headers(1)
.response(200)
)
.send_frame(frames::data(1, &payload[0..16_384]))
.send_frame(frames::data(1, &payload[16_384..16_384 * 2]))
.send_frame(frames::data(1, &payload[16_384 * 2..16_384 * 3]))
.recv_frame(
frames::window_update(0, 32_768)
)
.recv_frame(
frames::window_update(1, 32_768)
)
.send_frame(
frames::data(1, &payload[16_384 * 3..])
.eos()
)
// gotta end the connection
.map(drop);
let mut h2 = Client::handshake(mock)
.wait().unwrap();
let h2 = Client::handshake(io).unwrap()
.and_then(|mut h2| {
let request = Request::builder()
.method(Method::GET)
.uri("https://http2.akamai.com/")
.body(()).unwrap();
let request = Request::builder()
.method(Method::GET)
.uri("https://http2.akamai.com/")
.body(()).unwrap();
let req = h2.request(request, true).unwrap()
.unwrap()
// Get the response
.and_then(|resp| {
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_parts().1;
body.into_future().unwrap()
})
let mut stream = h2.request(request, true).unwrap();
// Get the response
let resp = h2.run(poll_fn(|| stream.poll_response())).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
// read some body to use up window size to below half
let mut body = resp.into_parts().1;
let buf = h2.run(poll_fn(|| body.poll())).unwrap().unwrap();
assert_eq!(buf.len(), 16_384);
let buf = h2.run(poll_fn(|| body.poll())).unwrap().unwrap();
assert_eq!(buf.len(), 16_384);
let buf = h2.run(poll_fn(|| body.poll())).unwrap().unwrap();
assert_eq!(buf.len(), 16_384);
// release some capacity to send a window_update
body.release_capacity(buf.len() * 2).unwrap();
let buf = h2.run(poll_fn(|| body.poll())).unwrap().unwrap();
assert_eq!(buf.len(), 16_383);
// send a 2nd stream to force flushing of window updates
let request = Request::builder()
.method(Method::GET)
.uri("https://http2.akamai.com/")
.body(()).unwrap();
let mut stream = h2.request(request, true).unwrap();
let resp = h2.run(poll_fn(|| stream.poll_response())).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
h2.wait().unwrap();
// read some body to use up window size to below half
.and_then(|(buf, body)| {
assert_eq!(buf.unwrap().len(), 16_384);
body.into_future().unwrap()
})
.and_then(|(buf, body)| {
assert_eq!(buf.unwrap().len(), 16_384);
body.into_future().unwrap()
})
.and_then(|(buf, mut body)| {
let buf = buf.unwrap();
assert_eq!(buf.len(), 16_384);
body.release_capacity(buf.len() * 2).unwrap();
body.into_future().unwrap()
})
.and_then(|(buf, _)| {
assert_eq!(buf.unwrap().len(), 16_383);
Ok(())
});
h2.unwrap().join(req)
});
h2.join(mock).wait().unwrap();
}
#[test]
@@ -145,63 +130,52 @@ fn release_capacity_of_small_amount_does_not_send_window_update() {
let payload = [0; 16];
let mock = mock_io::Builder::new()
.handshake()
.write(&[
// GET /
0, 0, 16, 1, 5, 0, 0, 0, 1, 130, 135, 65, 139, 157, 41,
172, 75, 143, 168, 233, 25, 151, 33, 233, 132,
])
.write(frames::SETTINGS_ACK)
// Read response
.read(&[0, 0, 1, 1, 4, 0, 0, 0, 1, 0x88])
.read(&[
// DATA
0, 0, 16, 0, 1, 0, 0, 0, 1,
])
.read(&payload[..])
// write() or WINDOW_UPDATE purposefully excluded
let (io, srv) = mock::new();
// we send a 2nd stream in order to test the window update is
// is actually written to the socket
.write(&[
// GET /
0, 0, 4, 1, 5, 0, 0, 0, 3, 130, 135, 190, 132,
])
.read(&[0, 0, 1, 1, 5, 0, 0, 0, 3, 0x88])
.build();
let mock = srv.assert_client_handshake().unwrap()
.recv_settings()
.recv_frame(
frames::headers(1)
.request("GET", "https://http2.akamai.com/")
.eos()
)
.send_frame(
frames::headers(1)
.response(200)
)
.send_frame(frames::data(1, &payload[..]).eos())
// gotta end the connection
.map(drop);
let mut h2 = Client::handshake(mock)
.wait().unwrap();
let h2 = Client::handshake(io).unwrap()
.and_then(|mut h2| {
let request = Request::builder()
.method(Method::GET)
.uri("https://http2.akamai.com/")
.body(()).unwrap();
let request = Request::builder()
.method(Method::GET)
.uri("https://http2.akamai.com/")
.body(()).unwrap();
let mut stream = h2.request(request, true).unwrap();
// Get the response
let resp = h2.run(poll_fn(|| stream.poll_response())).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
let mut body = resp.into_parts().1;
let buf = h2.run(poll_fn(|| body.poll())).unwrap().unwrap();
// release some capacity to send a window_update
body.release_capacity(buf.len()).unwrap();
// send a 2nd stream to force flushing of window updates
let request = Request::builder()
.method(Method::GET)
.uri("https://http2.akamai.com/")
.body(()).unwrap();
let mut stream = h2.request(request, true).unwrap();
let resp = h2.run(poll_fn(|| stream.poll_response())).unwrap();
assert_eq!(resp.status(), StatusCode::OK);
h2.wait().unwrap();
let req = h2.request(request, true).unwrap()
.unwrap()
// Get the response
.and_then(|resp| {
assert_eq!(resp.status(), StatusCode::OK);
let body = resp.into_parts().1;
body.into_future().unwrap()
})
// read the small body and then release it
.and_then(|(buf, mut body)| {
let buf = buf.unwrap();
assert_eq!(buf.len(), 16);
body.release_capacity(buf.len()).unwrap();
body.into_future().unwrap()
})
.and_then(|(buf, _)| {
assert!(buf.is_none());
Ok(())
});
h2.unwrap().join(req)
});
h2.join(mock).wait().unwrap();
}
#[test]

159
tests/support/src/frames.rs Normal file
View File

@@ -0,0 +1,159 @@
use std::fmt;
use bytes::{Bytes, IntoBuf};
use http::{self, HeaderMap, HttpTryFrom};
use h2::frame::{self, Frame, StreamId};
use super::SendFrame;
pub const SETTINGS: &'static [u8] = &[0, 0, 0, 4, 0, 0, 0, 0, 0];
pub const SETTINGS_ACK: &'static [u8] = &[0, 0, 0, 4, 1, 0, 0, 0, 0];
// ==== helper functions to easily construct h2 Frames ====
pub fn headers<T>(id: T) -> MockHeaders
where T: Into<StreamId>,
{
MockHeaders(frame::Headers::new(
id.into(),
frame::Pseudo::default(),
HeaderMap::default(),
))
}
pub fn data<T, B>(id: T, buf: B) -> MockData
where T: Into<StreamId>,
B: Into<Bytes>,
{
MockData(frame::Data::new(id.into(), buf.into()))
}
pub fn window_update<T>(id: T, sz: u32) -> frame::WindowUpdate
where T: Into<StreamId>,
{
frame::WindowUpdate::new(id.into(), sz)
}
// Headers helpers
pub struct MockHeaders(frame::Headers);
impl MockHeaders {
pub fn request<M, U>(self, method: M, uri: U) -> Self
where M: HttpTryInto<http::Method>,
U: HttpTryInto<http::Uri>,
{
let method = method.try_into().unwrap();
let uri = uri.try_into().unwrap();
let (id, _, fields) = self.into_parts();
let frame = frame::Headers::new(
id,
frame::Pseudo::request(method, uri),
fields
);
MockHeaders(frame)
}
pub fn response<S>(self, status: S) -> Self
where S: HttpTryInto<http::StatusCode>,
{
let status = status.try_into().unwrap();
let (id, _, fields) = self.into_parts();
let frame = frame::Headers::new(
id,
frame::Pseudo::response(status),
fields
);
MockHeaders(frame)
}
pub fn fields(self, fields: HeaderMap) -> Self {
let (id, pseudo, _) = self.into_parts();
let frame = frame::Headers::new(id, pseudo, fields);
MockHeaders(frame)
}
pub fn eos(mut self) -> Self {
self.0.set_end_stream();
self
}
fn into_parts(self) -> (StreamId, frame::Pseudo, HeaderMap) {
assert!(!self.0.is_end_stream(), "eos flag will be lost");
assert!(self.0.is_end_headers(), "unset eoh will be lost");
let id = self.0.stream_id();
let parts = self.0.into_parts();
(id, parts.0, parts.1)
}
}
impl fmt::Debug for MockHeaders {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl From<MockHeaders> for Frame {
fn from(src: MockHeaders) -> Self {
Frame::Headers(src.0)
}
}
impl From<MockHeaders> for SendFrame {
fn from(src: MockHeaders) -> Self {
Frame::Headers(src.0)
}
}
// Data helpers
pub struct MockData(frame::Data);
impl MockData {
pub fn eos(mut self) -> Self {
self.0.set_end_stream(true);
self
}
}
impl fmt::Debug for MockData {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl From<MockData> for Frame {
fn from(src: MockData) -> Self {
Frame::Data(src.0)
}
}
impl From<MockData> for SendFrame {
fn from(src: MockData) -> Self {
let id = src.0.stream_id();
let eos = src.0.is_end_stream();
let payload = src.0.into_payload();
let mut frame = frame::Data::new(id, payload.into_buf());
frame.set_end_stream(eos);
Frame::Data(frame)
}
}
// ==== "trait alias" for types that are HttpTryFrom and have Debug Errors ====
pub trait HttpTryInto<T> {
type Error: fmt::Debug;
fn try_into(self) -> Result<T, Self::Error>;
}
impl<T, U> HttpTryInto<T> for U
where T: HttpTryFrom<U>,
T::Error: fmt::Debug,
{
type Error = T::Error;
fn try_into(self) -> Result<T, Self::Error> {
T::try_from(self)
}
}

View File

@@ -16,6 +16,7 @@ mod assert;
#[macro_use]
pub mod raw;
pub mod frames;
pub mod prelude;
pub mod mock;

View File

@@ -3,13 +3,13 @@ use {FutureExt, SendFrame};
use h2::{self, SendError, RecvError};
use h2::frame::{self, Frame};
use futures::{Future, Stream, Poll};
use futures::{Async, Future, Stream, Poll};
use futures::task::{self, Task};
use tokio_io::{AsyncRead, AsyncWrite};
use tokio_io::io::read_exact;
use std::{cmp, io};
use std::{cmp, fmt, io};
use std::io::ErrorKind::WouldBlock;
use std::sync::{Arc, Mutex};
@@ -303,3 +303,118 @@ impl AsyncWrite for Pipe {
Ok(().into())
}
}
pub trait HandleFutureExt {
fn recv_settings(self) -> RecvFrame<Box<Future<Item=(Option<Frame>, Handle), Error=()>>>
where Self: Sized + 'static,
Self: Future<Item=(frame::Settings, Handle)>,
Self::Error: fmt::Debug,
{
let map = self.map(|(settings, handle)| (Some(settings.into()), handle)).unwrap();
let boxed: Box<Future<Item=(Option<Frame>, Handle), Error=()>> = Box::new(map);
RecvFrame {
inner: boxed,
frame: frame::Settings::default().into(),
}
}
fn recv_frame<T>(self, frame: T) -> RecvFrame<<Self as IntoRecvFrame>::Future>
where Self: IntoRecvFrame + Sized,
T: Into<Frame>,
{
self.into_recv_frame(frame.into())
}
fn send_frame<T>(self, frame: T) -> SendFrameFut<Self>
where Self: Sized,
T: Into<SendFrame>,
{
SendFrameFut {
inner: self,
frame: Some(frame.into()),
}
}
}
pub struct RecvFrame<T> {
inner: T,
frame: Frame,
}
impl<T> Future for RecvFrame<T>
where T: Future<Item=(Option<Frame>, Handle)>,
T::Error: fmt::Debug,
{
type Item = Handle;
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let (frame, handle) = match self.inner.poll().unwrap() {
Async::Ready((frame, handle)) => (frame, handle),
Async::NotReady => return Ok(Async::NotReady),
};
assert_eq!(frame.unwrap(), self.frame);
Ok(Async::Ready(handle))
}
}
pub struct SendFrameFut<T> {
inner: T,
frame: Option<SendFrame>,
}
impl<T> Future for SendFrameFut<T>
where T: Future<Item=Handle>,
T::Error: fmt::Debug,
{
type Item = Handle;
type Error = ();
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
let mut handle = match self.inner.poll().unwrap() {
Async::Ready(handle) => handle,
Async::NotReady => return Ok(Async::NotReady),
};
handle.send(self.frame.take().unwrap()).unwrap();
Ok(Async::Ready(handle))
}
}
impl<T> HandleFutureExt for T
where T: Future + 'static,
{
}
pub trait IntoRecvFrame {
type Future: Future;
fn into_recv_frame(self, frame: Frame) -> RecvFrame<Self::Future>;
}
impl IntoRecvFrame for Handle {
type Future = ::futures::stream::StreamFuture<Self>;
fn into_recv_frame(self, frame: Frame) -> RecvFrame<Self::Future> {
RecvFrame {
inner: self.into_future(),
frame: frame,
}
}
}
impl<T> IntoRecvFrame for T
where T: Future<Item=Handle> + 'static,
T::Error: fmt::Debug,
{
type Future = Box<Future<Item=(Option<Frame>, Handle), Error=()>>;
fn into_recv_frame(self, frame: Frame) -> RecvFrame<Self::Future> {
let into_fut = Box::new(self.unwrap()
.and_then(|handle| handle.into_future().unwrap())
);
RecvFrame {
inner: into_fut,
frame: frame,
}
}
}

View File

@@ -8,7 +8,10 @@ pub use self::h2::client::{self, Client};
pub use self::h2::server::{self, Server};
// Re-export mock
pub use super::mock;
pub use super::mock::{self, HandleFutureExt};
// Re-export frames helpers
pub use super::frames;
// Re-export some type defines
pub use super::{Codec, SendFrame};
@@ -100,9 +103,3 @@ impl<T, B> ClientExt for Client<T, B>
}
}
pub mod frames {
//! Some useful frames
pub const SETTINGS: &'static [u8] = &[0, 0, 0, 4, 0, 0, 0, 0, 0];
pub const SETTINGS_ACK: &'static [u8] = &[0, 0, 0, 4, 1, 0, 0, 0, 0];
}