1 unstable release
Uses old Rust 2015
0.1.0 | Jun 16, 2018 |
---|
#48 in #stub
14KB
222 lines
hyper-stub
hyper-stub is a Rust library that provides functions to create hyper clients that convert requests to responses using predefined functions, without doing any actual networking. This means the entire request/response lifecycle happens in a single process, and should have performance and stability improvements over, for example, binding to a port. One potential use case for this is stubbing HTTP interactions in tests to avoid slow/flakey/absent internet connections.
For API reference and usage examples, see the documentation.
lib.rs
:
hyper-stub provides functions to create hyper clients that convert requests to responses using predefined functions, without doing any actual networking. This means the entire request/response lifecycle happens in a single process, and should have performance and stability improvements over, for example, binding to a port. One potential use case for this is stubbing HTTP interactions in tests to avoid slow/flakey/absent internet connections.
The simplest case uses proxy_client_fn_ok
to create a client bound to a
simple function that directly maps from a request to a response:
#
use futures::{Future, Stream};
use hyper::{Request, Response, Uri};
use hyper_stub::proxy_client_fn_ok;
use tokio::runtime::current_thread::Runtime;
let echo_client = proxy_client_fn_ok(|request| {
let body = request.into_body();
Response::new(body)
});
let url: Uri = "http://example.com".parse().unwrap();
let mut builder = Request::post(url);
let request = builder.body("hello world".into()).unwrap();
let future = echo_client.request(request)
.and_then(|res| res.into_body().concat2())
.map(|bytes| {
let body = String::from_utf8(bytes.to_vec()).unwrap();
println!("{}", body);
})
.map_err(|error| panic!("ERROR: {:?}", error));
Runtime::new().unwrap().block_on(future).unwrap();
If the function needs to return an error, or respond to the request
asynchronously, proxy_client_fn
can be used.
Finally, an advanced use case is using hyper services
instead of simple
functions. This can be done with the proxy_client
function.
Dependencies
~8MB
~131K SLoC