Crate hyper_stub[−][src]
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.
Functions
proxy_client |
Creates a hyper client whose requests are converted to responses by being
passed through a hyper |
proxy_client_fn |
Creates a hyper client whose requests are converted to responses by being passed through the given handler function, which returns a future. |
proxy_client_fn_ok |
Creates a hyper client whose requests are converted to responses by being passed through the given handler function. |