trillium_testing/
with_server.rs

1use crate::{block_on, ServerConnector};
2use std::{error::Error, future::Future};
3use trillium::Handler;
4use trillium_http::transport::BoxedTransport;
5use url::Url;
6
7/**
8Starts a trillium handler bound to a random available port on
9localhost, run the async tests provided as the second
10argument, and then shut down the server. useful for full
11integration tests that actually exercise the tcp layer.
12
13See
14[`trillium_client::Conn`](https://docs.trillium.rs/trillium_client/struct.conn)
15for usage examples.
16**/
17pub fn with_server<H, Fun, Fut>(handler: H, tests: Fun)
18where
19    H: Handler,
20    Fun: FnOnce(Url) -> Fut,
21    Fut: Future<Output = Result<(), Box<dyn Error>>>,
22{
23    block_on(async move {
24        let port = portpicker::pick_unused_port().expect("could not pick a port");
25        let url = format!("http://localhost:{port}").parse().unwrap();
26        let handle = crate::config()
27            .with_host("localhost")
28            .with_port(port)
29            .spawn(handler);
30        handle.info().await;
31        tests(url).await.unwrap();
32        handle.stop().await;
33    });
34}
35
36/// open an in-memory connection to this handler and call an async
37/// function with an open BoxedTransport
38pub fn with_transport<H, Fun, Fut>(handler: H, tests: Fun)
39where
40    H: Handler,
41    Fun: FnOnce(BoxedTransport) -> Fut,
42    Fut: Future<Output = Result<(), Box<dyn Error>>>,
43{
44    block_on(async move {
45        let transport = ServerConnector::new(handler).connect(false).await;
46        tests(BoxedTransport::new(transport));
47    });
48}