mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-21 00:00:14 +02:00
Add MockConnectInfo (#1767)
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user