Add MockConnectInfo (#1767)

This commit is contained in:
David Pedersen
2023-02-17 13:09:29 +01:00
committed by GitHub
parent cd86f7ec7a
commit 143c415955
3 changed files with 139 additions and 3 deletions
+25
View File
@@ -4,7 +4,10 @@
//! cargo test -p example-testing
//! ```
use std::net::SocketAddr;
use axum::{
extract::ConnectInfo,
routing::{get, post},
Json, Router,
};
@@ -43,6 +46,10 @@ fn app() -> Router {
Json(serde_json::json!({ "data": payload.0 }))
}),
)
.route(
"/requires-connect-into",
get(|ConnectInfo(addr): ConnectInfo<SocketAddr>| async move { format!("Hi {addr}") }),
)
// We can still add middleware
.layer(TraceLayer::new_for_http())
}
@@ -52,6 +59,7 @@ mod tests {
use super::*;
use axum::{
body::Body,
extract::connect_info::MockConnectInfo,
http::{self, Request, StatusCode},
};
use serde_json::{json, Value};
@@ -164,4 +172,21 @@ mod tests {
let response = app.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
// Here we're calling `/requires-connect-into` which requires `ConnectInfo`
//
// That is normally set with `Router::into_make_service_with_connect_info` but we can't easily
// use that during tests. The solution is instead to set the `MockConnectInfo` layer during
// tests.
#[tokio::test]
async fn with_into_make_service_with_connect_info() {
let mut app = app().layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 3000))));
let request = Request::builder()
.uri("/requires-connect-into")
.body(Body::empty())
.unwrap();
let response = app.ready().await.unwrap().call(request).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}