Testing with into_make_service_with_connect_info
#748
-
I have been testing happily enough with something resembling the following: let app: Router = build_app(/* details elided */);
let resp = app.oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()).await.unwrap(); But then I needed to extract After figuring out that it was the missing Updated listener creation to use port use my_app::build_app;
use std::net::{SocketAddr, TcpListener};
use tokio::task::JoinHandle;
use url::Url;
pub struct TestApp {
pub base_url: Url,
pub client: reqwest::Client,
server: JoinHandle<()>,
}
impl TestApp {
pub async fn new() -> TestApp {
let app: Router = build_app(/* details elided */);
let listener = TcpListener::bind("127.0.0.1:0").expect("Could not bind ephemeral socket");
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
axum::Server::from_tcp(listener)
.unwrap()
.serve(app.into_make_service_with_connect_info::<SocketAddr, _>())
.await
.unwrap();
});
TestApp {
base_url: Url::parse(&format!("http://{addr}")).unwrap(),
client: reqwest::Client::new(),
server,
}
}
pub fn get(&self, path: &str) -> reqwest::RequestBuilder {
let base_url = Some(&self.base_url);
let base = Url::options().base_url(base_url);
let url = base.parse(path).unwrap();
self.client.get(url)
}
}
impl Drop for TestApp {
fn drop(&mut self) {
tracing::debug!("Dropping test server at {}", self.base_url.as_str());
self.server.abort()
}
} Usage: let app = TestApp::new().await;
let response = app.get(&path).send().await.unwrap(); To be clear, I don't think this is terrible! It's all pretty much done once, using reqwest as a client is a bit more ergonomic anyway, and we're actually testing more of the stack. However, I can't help but wonder if it's a little overkill. Any thoughts? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Overkill how? It's how we test axum internally and we've had no issues with it. So seems fine to me 😊 Whilst I wouldn't recommend it a different way of "faking a connection" is that you manually insert a |
Beta Was this translation helpful? Give feedback.
Overkill how? It's how we test axum internally and we've had no issues with it.
So seems fine to me 😊
Whilst I wouldn't recommend it a different way of "faking a connection" is that you manually insert a
ConnectInfo
of the right type as an extension on the test request. The 500 you're seeing comes from the extension not being set. I wouldn't recommend this because there is no guarantee the internals won't change in the future, although we have no such plans currently.