-
Hi! I want to know if there is a good way to wait until Here's how I usually start the server: pub async fn run_server(port: u16) {
let server_state = Arc::new(AxumState {
// ...
});
let cors = CorsLayer::new()
.allow_methods([Method::GET, Method::HEAD])
.allow_origin(Any);
let app = Router::new()
.merge(/**/)
.merge(/**/)
.with_state(server_state)
.layer(cors);
let addr = SocketAddr::from(([127, 0, 0, 1], port));
match axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
{
Ok(_) => tracing::info!("Axum exited cleanly"),
Err(err) => tracing::warn!("Axum exited with an error {}", err),
}
} And the test is here: #[tokio::test]
async fn test_server() -> Result<(), anyhow::Error> {
let server_handle = tokio::spawn(run_server(SERVER_PORT));
// Test fails unless I sleep here
// tokio::time::sleep(Duration::from_secs(1)).await;
// Here I want to do a network call and assert the result
server_handle.abort();
Ok(())
} Is there a "server started" callback that I can use to send a message on a channel? Or something else, so that I don't have to sleep before running the test? Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
You can use https://docs.rs/hyper/0.14.23/hyper/server/struct.Server.html#method.builder |
Beta Was this translation helpful? Give feedback.
-
Or like this https://github.com/tokio-rs/axum/blob/main/examples/testing/src/main.rs#L125 |
Beta Was this translation helpful? Give feedback.
-
Thanks @davidpdrsn but I don't understand how those resources would help me. I forgot to add in my code above that I am already doing reqwest::get(format!("http://127.0.0.1:{SERVER_PORT}/{path}"))
.await?
.error_for_status()? But unless I wait for a little while before issuing the request, the test fails with this: ---- server::tests::test_server stdout ----
Error: error sending request for url (http://127.0.0.1:51130/somepath): error trying to connect: tcp connect error: Connection refused (os error 61) |
Beta Was this translation helpful? Give feedback.
Thanks @davidpdrsn but I don't understand how those resources would help me.
I forgot to add in my code above that I am already doing
But unless I wait for a little while before issuing the request, the test fails with this:
---- server::tests::test_server stdout ---- Error: error sending request for url (http://127.0.0.1:51130/somepath): error trying to connect: tcp connect error: Connection refused (os error 61)