Skip to content

Commit

Permalink
use diffrent ports for middlewares.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
NexVeridian committed Dec 18, 2024
1 parent 481e1d0 commit e9224e1
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 32 deletions.
86 changes: 59 additions & 27 deletions tests/controller/middlewares.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,10 @@ async fn panic(#[case] enable: bool) {
ctx.config.server.middlewares.catch_panic =
Some(middleware::catch_panic::CatchPanic { enable });

let handle = infra_cfg::server::start_with_route(ctx, "/", get(action)).await;
let res = reqwest::get(infra_cfg::server::get_base_url()).await;
let port = infra_cfg::server::get_available_port().await;
let handle =
infra_cfg::server::start_with_route(ctx, "/", get(action), Some(port.clone())).await;
let res = reqwest::get(infra_cfg::server::get_base_url_port(port)).await;

if enable {
let res = res.expect("valid response");
Expand Down Expand Up @@ -64,10 +66,12 @@ async fn etag(#[case] enable: bool) {

ctx.config.server.middlewares.etag = Some(middleware::etag::Etag { enable });

let handle = infra_cfg::server::start_with_route(ctx, "/", get(action)).await;
let port = infra_cfg::server::get_available_port().await;
let handle =
infra_cfg::server::start_with_route(ctx, "/", get(action), Some(port.clone())).await;

let res = reqwest::Client::new()
.get(infra_cfg::server::get_base_url())
.get(infra_cfg::server::get_base_url_port(port))
.header("if-none-match", "loco-etag")
.send()
.await
Expand Down Expand Up @@ -100,10 +104,12 @@ async fn remote_ip(#[case] enable: bool, #[case] expected: &str) {
trusted_proxies: Some(vec!["192.1.1.1/8".to_string()]),
});

let handle = infra_cfg::server::start_with_route(ctx, "/", get(action)).await;
let port = infra_cfg::server::get_available_port().await;
let handle =
infra_cfg::server::start_with_route(ctx, "/", get(action), Some(port.clone())).await;

let res = reqwest::Client::new()
.get(infra_cfg::server::get_base_url())
.get(infra_cfg::server::get_base_url_port(port))
.header(
"x-forwarded-for",
reqwest::header::HeaderValue::from_static("51.50.51.50,192.1.1.1"),
Expand Down Expand Up @@ -134,9 +140,11 @@ async fn timeout(#[case] enable: bool) {
ctx.config.server.middlewares.timeout_request =
Some(middleware::timeout::TimeOut { enable, timeout: 2 });

let handle = infra_cfg::server::start_with_route(ctx, "/", get(action)).await;
let port = infra_cfg::server::get_available_port().await;
let handle =
infra_cfg::server::start_with_route(ctx, "/", get(action), Some(port.clone())).await;

let res = reqwest::get(infra_cfg::server::get_base_url())
let res = reqwest::get(infra_cfg::server::get_base_url_port(port))
.await
.expect("response");

Expand Down Expand Up @@ -183,10 +191,14 @@ async fn cors(

ctx.config.server.middlewares.cors = Some(middleware);

let handle = infra_cfg::server::start_from_ctx(ctx).await;
let port = infra_cfg::server::get_available_port().await;
let handle = infra_cfg::server::start_from_ctx(ctx, Some(port.clone())).await;

let res = reqwest::Client::new()
.request(reqwest::Method::OPTIONS, infra_cfg::server::get_base_url())
.request(
reqwest::Method::OPTIONS,
infra_cfg::server::get_base_url_port(port),
)
.send()
.await
.expect("valid response");
Expand Down Expand Up @@ -229,10 +241,14 @@ async fn limit_payload(#[case] enable: bool) {
body_limit: 0x1B,
});

let handle = infra_cfg::server::start_from_ctx(ctx).await;
let port = infra_cfg::server::get_available_port().await;
let handle = infra_cfg::server::start_from_ctx(ctx, Some(port.clone())).await;

let res = reqwest::Client::new()
.request(reqwest::Method::POST, infra_cfg::server::get_base_url())
.request(
reqwest::Method::POST,
infra_cfg::server::get_base_url_port(port),
)
.body("send body".repeat(100))
.send()
.await
Expand Down Expand Up @@ -279,20 +295,27 @@ async fn static_assets() {
precompressed: false,
});

let handle = infra_cfg::server::start_from_ctx(ctx).await;
let port = infra_cfg::server::get_available_port().await;
let handle = infra_cfg::server::start_from_ctx(ctx, Some(port.clone())).await;

let get_static_html = reqwest::get("http://localhost:5555/static/static.html")
.await
.expect("valid response");
let get_static_html = reqwest::get(format!(
"{}static/static.html",
infra_cfg::server::get_base_url_port(port)
))
.await
.expect("valid response");

assert_eq!(
get_static_html.text().await.expect("text response"),
"<h1>static content</h1>".to_string()
);

let get_fallback = reqwest::get("http://localhost:5555/static/logo.png")
.await
.expect("valid response");
let get_fallback = reqwest::get(format!(
"{}static/logo.png",
infra_cfg::server::get_base_url_port(port)
))
.await
.expect("valid response");

assert_eq!(
get_fallback.text().await.expect("text response"),
Expand Down Expand Up @@ -327,10 +350,14 @@ async fn secure_headers(
},
);

let handle = infra_cfg::server::start_from_ctx(ctx).await;
let port = infra_cfg::server::get_available_port().await;
let handle = infra_cfg::server::start_from_ctx(ctx, Some(port.clone())).await;

let res = reqwest::Client::new()
.request(reqwest::Method::POST, infra_cfg::server::get_base_url())
.request(
reqwest::Method::POST,
infra_cfg::server::get_base_url_port(port),
)
.send()
.await
.expect("response");
Expand Down Expand Up @@ -402,11 +429,15 @@ async fn fallback(

ctx.config.server.middlewares.fallback = Some(fallback_config);

let handle = infra_cfg::server::start_from_ctx(ctx).await;
let port = infra_cfg::server::get_available_port().await;
let handle = infra_cfg::server::start_from_ctx(ctx, Some(port.clone())).await;

let res = reqwest::get(format!("{}not-found", infra_cfg::server::get_base_url()))
.await
.expect("valid response");
let res = reqwest::get(format!(
"{}not-found",
infra_cfg::server::get_base_url_port(port)
))
.await
.expect("valid response");

if let Some(code) = code {
assert_eq!(res.status(), code);
Expand Down Expand Up @@ -438,9 +469,10 @@ async fn powered_by_header(#[case] ident: Option<String>) {

ctx.config.server.ident.clone_from(&ident);

let handle = infra_cfg::server::start_from_ctx(ctx).await;
let port = infra_cfg::server::get_available_port().await;
let handle = infra_cfg::server::start_from_ctx(ctx, Some(port.clone())).await;

let res = reqwest::get(infra_cfg::server::get_base_url())
let res = reqwest::get(infra_cfg::server::get_base_url_port(port))
.await
.expect("valid response");

Expand Down
34 changes: 29 additions & 5 deletions tests/infra_cfg/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
//! hardcoded ports and bindings.
use loco_rs::{boot, controller::AppRoutes, prelude::*, tests_cfg::db::AppHook};
use tokio::net::TcpListener;

/// The port on which the test server will run.
const TEST_PORT_SERVER: i32 = 5555;
Expand All @@ -15,10 +16,29 @@ const TEST_PORT_SERVER: i32 = 5555;
const TEST_BINDING_SERVER: &str = "localhost";

/// Constructs and returns the base URL used for the test server.
#[allow(dead_code)]
pub fn get_base_url() -> String {
format!("http://{TEST_BINDING_SERVER}:{TEST_PORT_SERVER}/")
}

pub fn get_base_url_port(port: i32) -> String {
format!("http://{TEST_BINDING_SERVER}:{port}/")
}

/// Returns the base URL with a unique port number. Increments up by 1 from
/// starting from 59126
pub async fn get_available_port() -> i32 {
let addr = format!("{}:0", TEST_BINDING_SERVER);
let listener = TcpListener::bind(addr)
.await
.expect("Failed to bind to address");
let port = listener
.local_addr()
.expect("Failed to get local address")
.port() as i32;
port
}

/// A simple asynchronous handler for GET requests.
async fn get_action() -> Result<Response> {
format::render().text("text response")
Expand All @@ -34,12 +54,15 @@ async fn post_action(_body: axum::body::Bytes) -> Result<Response> {
///
/// This function spawns a server task that runs asynchronously and sleeps for 2
/// seconds to ensure the server is fully initialized before handling requests.
pub async fn start_from_boot(boot_result: boot::BootResult) -> tokio::task::JoinHandle<()> {
pub async fn start_from_boot(
boot_result: boot::BootResult,
port: Option<i32>,
) -> tokio::task::JoinHandle<()> {
let handle = tokio::spawn(async move {
boot::start::<AppHook>(
boot_result,
boot::ServeParams {
port: TEST_PORT_SERVER,
port: port.unwrap_or(TEST_PORT_SERVER),
binding: TEST_BINDING_SERVER.to_string(),
},
false,
Expand All @@ -54,7 +77,7 @@ pub async fn start_from_boot(boot_result: boot::BootResult) -> tokio::task::Join

/// Starts the server with a basic route (GET and POST) at the root (`/`), using
/// the given application context.
pub async fn start_from_ctx(ctx: AppContext) -> tokio::task::JoinHandle<()> {
pub async fn start_from_ctx(ctx: AppContext, port: Option<i32>) -> tokio::task::JoinHandle<()> {
let app_router = AppRoutes::empty()
.add_route(
Routes::new()
Expand All @@ -70,7 +93,7 @@ pub async fn start_from_ctx(ctx: AppContext) -> tokio::task::JoinHandle<()> {
run_worker: false,
};

start_from_boot(boot).await
start_from_boot(boot, port).await
}

/// Starts the server with a custom route specified by the URI and the HTTP
Expand All @@ -79,6 +102,7 @@ pub async fn start_with_route(
ctx: AppContext,
uri: &str,
method: axum::routing::MethodRouter<AppContext>,
port: Option<i32>,
) -> tokio::task::JoinHandle<()> {
let app_router = AppRoutes::empty()
.add_route(Routes::new().add(uri, method))
Expand All @@ -90,5 +114,5 @@ pub async fn start_with_route(
router: Some(app_router),
run_worker: false,
};
start_from_boot(boot).await
start_from_boot(boot, port).await
}

0 comments on commit e9224e1

Please sign in to comment.