Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: Use diffrent ports for tests #1093

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions src/testing/request.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,46 @@
use std::net::SocketAddr;

use axum_test::{TestServer, TestServerConfig};
use tokio::net::TcpListener;

use crate::{
app::{AppContext, Hooks},
boot::{self, BootResult},
config::Server,
environment::Environment,
Result,
};

/// The port on which the test server will run.
pub const TEST_PORT_SERVER: i32 = 5555;

/// The hostname to which the test server binds.
pub 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 {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this function still relevant? Also, what about the TEST_PORT_SERVER constant?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not the relevant, get_base_url and TEST_PORT_SERVER could be remove if you want

format!("http://{TEST_BINDING_SERVER}:{TEST_PORT_SERVER}/")
}

/// Constructs and returns the base URL used for the test server.
pub fn get_base_url_port(port: i32) -> String {
format!("http://{TEST_BINDING_SERVER}:{port}/")
}

/// Returns a unique port number. Usually increments by 1 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
}

/// Bootstraps test application with test environment hard coded.
///
/// # Errors
Expand Down Expand Up @@ -37,6 +69,40 @@ pub async fn boot_test<H: Hooks>() -> Result<BootResult> {
H::boot(boot::StartMode::ServerOnly, &Environment::Test, config).await
}

/// Bootstraps test application with test environment hard coded,
/// and with a unique port.
///
/// # Errors
/// when could not bootstrap the test environment
///
/// # Example
///
/// The provided example demonstrates how to boot the test case with the
/// application context, and a with a unique port.
///
/// ```rust,ignore
/// use myapp::app::App;
/// use loco_rs::testing::prelude::*;
/// use migration::Migrator;
///
/// #[tokio::test]
/// async fn test_create_user() {
/// let port = get_available_port().await;
/// let boot = boot_test_unique_port::<App, Migrator>(Some(port)).await;
///
/// /// .....
/// assert!(false)
/// }
pub async fn boot_test_unique_port<H: Hooks>(port: Option<i32>) -> Result<BootResult> {
let mut config = H::load_config(&Environment::Test).await?;
config.server = Server {
port: port.unwrap_or(TEST_PORT_SERVER),
binding: TEST_BINDING_SERVER.to_string(),
..config.server
};
Comment on lines +105 to +109
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if this is working correctly

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this function used?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the user would call boot_test_unique_port in their tests?

H::boot(boot::StartMode::ServerOnly, &Environment::Test, config).await
}

#[allow(clippy::future_not_send)]
/// Initiates a test request with a provided callback.
///
Expand Down
46 changes: 26 additions & 20 deletions tests/controller/into_response.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use crate::infra_cfg;
use loco_rs::{controller, prelude::*, tests_cfg};
use serde::{Deserialize, Serialize};
use serial_test::serial;

use crate::infra_cfg;

#[tokio::test]
#[serial]
async fn not_found() {
let ctx = tests_cfg::app::get_app_context().await;

Expand All @@ -13,9 +12,11 @@ async fn not_found() {
controller::not_found()
}

let handle = infra_cfg::server::start_with_route(ctx, "/", get(action)).await;
let port = 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(get_base_url_port(port))
.await
.expect("Valid response");

Expand All @@ -35,7 +36,6 @@ async fn not_found() {
}

#[tokio::test]
#[serial]
async fn internal_server_error() {
let ctx = tests_cfg::app::get_app_context().await;

Expand All @@ -44,9 +44,11 @@ async fn internal_server_error() {
Err(Error::InternalServerError)
}

let handle = infra_cfg::server::start_with_route(ctx, "/", get(action)).await;
let port = 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(get_base_url_port(port))
.await
.expect("Valid response");

Expand All @@ -66,7 +68,6 @@ async fn internal_server_error() {
}

#[tokio::test]
#[serial]
async fn unauthorized() {
let ctx = tests_cfg::app::get_app_context().await;

Expand All @@ -75,9 +76,11 @@ async fn unauthorized() {
controller::unauthorized("user not unauthorized")
}

let handle = infra_cfg::server::start_with_route(ctx, "/", get(action)).await;
let port = 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(get_base_url_port(port))
.await
.expect("Valid response");

Expand All @@ -97,7 +100,6 @@ async fn unauthorized() {
}

#[tokio::test]
#[serial]
async fn fallback() {
let ctx = tests_cfg::app::get_app_context().await;

Expand All @@ -106,9 +108,11 @@ async fn fallback() {
Err(Error::Message(String::new()))
}

let handle = infra_cfg::server::start_with_route(ctx, "/", get(action)).await;
let port = 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(get_base_url_port(port))
.await
.expect("Valid response");

Expand All @@ -128,7 +132,6 @@ async fn fallback() {
}

#[tokio::test]
#[serial]
async fn custom_error() {
let ctx = tests_cfg::app::get_app_context().await;

Expand All @@ -144,9 +147,11 @@ async fn custom_error() {
))
}

let handle = infra_cfg::server::start_with_route(ctx, "/", get(action)).await;
let port = 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(get_base_url_port(port))
.await
.expect("Valid response");

Expand All @@ -166,7 +171,6 @@ async fn custom_error() {
}

#[tokio::test]
#[serial]
async fn json_rejection() {
let ctx = tests_cfg::app::get_app_context().await;

Expand All @@ -181,11 +185,13 @@ async fn json_rejection() {
format::json(())
}

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

let client = reqwest::Client::new();
let res = client
.post(infra_cfg::server::get_base_url())
.post(get_base_url_port(port))
.json(&serde_json::json!({}))
.send()
.await
Expand Down
Loading