Email client, application startup logic and tests

This commit is contained in:
Alphonse Paix
2025-08-24 11:31:03 +02:00
parent 85ab04f254
commit 4389873bf4
14 changed files with 636 additions and 410 deletions

16
tests/api/health_check.rs Normal file
View File

@@ -0,0 +1,16 @@
use crate::helpers::TestApp;
#[tokio::test]
async fn health_check_works() {
let app = TestApp::spawn().await;
let client = reqwest::Client::new();
let response = client
.get(format!("http://{}/health_check", app.address))
.send()
.await
.unwrap();
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}

74
tests/api/helpers.rs Normal file
View File

@@ -0,0 +1,74 @@
use once_cell::sync::Lazy;
use sqlx::{Connection, Executor, PgConnection, PgPool};
use uuid::Uuid;
use zero2prod::{
configuration::{DatabaseSettings, get_configuration},
startup::Application,
telemetry::init_subscriber,
};
static TRACING: Lazy<()> = Lazy::new(|| {
if std::env::var("TEST_LOG").is_ok() {
init_subscriber(std::io::stdout);
} else {
init_subscriber(std::io::sink);
}
});
pub struct TestApp {
pub address: String,
pub connection_pool: PgPool,
}
impl TestApp {
pub async fn spawn() -> Self {
Lazy::force(&TRACING);
let mut configuration = get_configuration().expect("Failed to read configuration");
configuration.database.database_name = Uuid::new_v4().to_string();
configuration.application.port = 0;
let connection_pool = configure_database(&configuration.database).await;
let application = Application::build(configuration)
.await
.expect("Failed to build application");
let address = application.address();
let app = TestApp {
address,
connection_pool,
};
tokio::spawn(application.run_until_stopped());
app
}
pub async fn post_subscriptions(&self, body: String) -> reqwest::Response {
reqwest::Client::new()
.post(format!("http://{}/subscriptions", self.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.expect("Failed to execute request")
}
}
async fn configure_database(config: &DatabaseSettings) -> PgPool {
let mut connection = PgConnection::connect_with(&config.without_db())
.await
.expect("Failed to connect to Postgres");
connection
.execute(format!(r#"CREATE DATABASE "{}";"#, config.database_name).as_ref())
.await
.expect("Failed to create the database");
let connection_pool = PgPool::connect_with(config.with_db())
.await
.expect("Failed to connect to Postgres");
sqlx::migrate!("./migrations")
.run(&connection_pool)
.await
.expect("Failed to migrate the database");
connection_pool
}

3
tests/api/main.rs Normal file
View File

@@ -0,0 +1,3 @@
mod health_check;
mod helpers;
mod subscriptions;

View File

@@ -0,0 +1,61 @@
use crate::helpers::TestApp;
#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
let app = TestApp::spawn().await;
let body = "name=alphonse&email=alphonse.paix%40outlook.com";
let response = app.post_subscriptions(body.into()).await;
assert_eq!(200, response.status().as_u16());
let saved = sqlx::query!("SELECT email, name FROM subscriptions")
.fetch_one(&app.connection_pool)
.await
.expect("Failed to fetch saved subscription");
assert_eq!(saved.email, "alphonse.paix@outlook.com");
assert_eq!(saved.name, "alphonse");
}
#[tokio::test]
async fn subscribe_returns_a_422_when_data_is_missing() {
let app = TestApp::spawn().await;
let test_cases = [
("name=Alphonse", "missing the email"),
("email=alphonse.paix%40outlook.com", "missing the name"),
("", "missing both name and email"),
];
for (invalid_body, error_message) in test_cases {
let response = app.post_subscriptions(invalid_body.into()).await;
assert_eq!(
422,
response.status().as_u16(),
"the API did not fail with 422 Unprocessable Entity when the payload was {}.",
error_message
);
}
}
#[tokio::test]
async fn subscribe_returns_a_400_when_fields_are_present_but_invalid() {
let app = TestApp::spawn().await;
let test_cases = [
("name=&email=alphonse.paix%40outlook.com", "empty name"),
("name=Alphonse&email=", "empty email"),
("name=Alphonse&email=not-an-email", "invalid email"),
];
for (body, description) in test_cases {
let response = app.post_subscriptions(body.into()).await;
assert_eq!(
400,
response.status().as_u16(),
"the API did not return a 400 Bad Request when the payload had an {}.",
description
);
}
}

View File

@@ -1,159 +0,0 @@
use once_cell::sync::Lazy;
use sqlx::{Connection, Executor, PgConnection, PgPool};
use tokio::net::TcpListener;
use uuid::Uuid;
use zero2prod::{
configuration::{DatabaseSettings, get_configuration},
telemetry::init_subscriber,
};
static TRACING: Lazy<()> = Lazy::new(|| {
if std::env::var("TEST_LOG").is_ok() {
init_subscriber(std::io::stdout);
} else {
init_subscriber(std::io::sink);
}
});
pub struct TestApp {
pub address: String,
pub connection_pool: PgPool,
}
#[tokio::test]
async fn health_check_works() {
let app = spawn_app().await;
let client = reqwest::Client::new();
let response = client
.get(format!("http://{}/health_check", app.address))
.send()
.await
.unwrap();
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}
#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
let app = spawn_app().await;
let client = reqwest::Client::new();
let body = "name=alphonse&email=alphonse.paix%40outlook.com";
let response = client
.post(format!("http://{}/subscriptions", app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.unwrap();
assert_eq!(200, response.status().as_u16());
let saved = sqlx::query!("SELECT email, name FROM subscriptions")
.fetch_one(&app.connection_pool)
.await
.expect("Failed to fetch saved subscription");
assert_eq!(saved.email, "alphonse.paix@outlook.com");
assert_eq!(saved.name, "alphonse");
}
#[tokio::test]
async fn subscribe_returns_a_422_when_data_is_missing() {
let app = spawn_app().await;
let client = reqwest::Client::new();
let test_cases = [
("name=Alphonse", "missing the email"),
("email=alphonse.paix%40outlook.com", "missing the name"),
("", "missing both name and email"),
];
for (invalid_body, error_message) in test_cases {
let response = client
.post(format!("http://{}/subscriptions", app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(invalid_body)
.send()
.await
.unwrap();
assert_eq!(
422,
response.status().as_u16(),
"the API did not fail with 422 Unprocessable Entity when the payload was {}.",
error_message
);
}
}
#[tokio::test]
async fn subscribe_returns_a_400_when_fields_are_present_but_invalid() {
let app = spawn_app().await;
let client = reqwest::Client::new();
let test_cases = [
("name=&email=alphonse.paix%40outlook.com", "empty name"),
("name=Alphonse&email=", "empty email"),
("name=Alphonse&email=not-an-email", "invalid email"),
];
for (body, description) in test_cases {
let response = client
.post(format!("http://{}/subscriptions", app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.unwrap();
assert_eq!(
400,
response.status().as_u16(),
"the API did not return a 400 Bad Request when the payload had an {}.",
description
);
}
}
async fn spawn_app() -> TestApp {
Lazy::force(&TRACING);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap().to_string();
let mut configuration = get_configuration().expect("Failed to read configuration");
configuration.database.database_name = Uuid::new_v4().to_string();
let connection_pool = configure_database(&configuration.database).await;
let app = TestApp {
address,
connection_pool: connection_pool.clone(),
};
tokio::spawn(async move {
zero2prod::startup::run(listener, connection_pool).await;
});
app
}
async fn configure_database(config: &DatabaseSettings) -> PgPool {
let mut connection = PgConnection::connect_with(&config.without_db())
.await
.expect("Failed to connect to Postgres");
connection
.execute(format!(r#"CREATE DATABASE "{}";"#, config.database_name).as_ref())
.await
.expect("Failed to create the database");
let connection_pool = PgPool::connect_with(config.with_db())
.await
.expect("Failed to connect to Postgres");
sqlx::migrate!("./migrations")
.run(&connection_pool)
.await
.expect("Failed to migrate the database");
connection_pool
}