mailApp/tests/health_check.rs

146 lines
4.4 KiB
Rust
Raw Permalink Normal View History

use mail_app::configuration::{get_configuration, DatabaseSettings};
use mail_app::startup::run;
use mail_app::telemetry::{get_subscriber, init_subscriber};
use once_cell::sync::Lazy;
use sqlx::{Connection, Executor, PgConnection, PgPool};
use std::net::TcpListener;
use uuid::Uuid;
2023-08-31 23:57:30 +10:00
static TRACING: Lazy<()> = Lazy::new(|| {
let default_filter_level = "info".to_string();
let subscriber_name = "test".to_string();
if std::env::var("TEST_LOG").is_ok() {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::stdout);
init_subscriber(subscriber);
} else {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::sink);
init_subscriber(subscriber);
};
});
pub struct TestApp {
pub address: String,
pub db_pool: PgPool,
}
async fn spawn_app() -> TestApp {
Lazy::force(&TRACING);
2023-08-31 23:57:30 +10:00
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port.");
let port = listener.local_addr().unwrap().port();
let address = format!("http://127.0.0.1:{}", port);
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 server = run(listener, connection_pool.clone()).expect("Failed to bind address");
2023-08-31 23:57:30 +10:00
// Launch in background
let _ = tokio::spawn(server);
TestApp {
address,
db_pool: connection_pool,
}
}
2023-08-31 23:57:30 +10:00
pub async fn configure_database(config: &DatabaseSettings) -> PgPool {
// Create Database
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_str())
.await
.expect("Failed to create database.");
// Migrate 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.");
// Return connection pool
connection_pool
2023-08-31 23:57:30 +10:00
}
#[tokio::test]
async fn health_check_works() {
// Arrange
let app = spawn_app().await;
let client = reqwest::Client::new();
// Act
let response = client
.get(&format!("{}/health_check", &app.address))
.send()
.await
.expect("Failed to execute request");
// Assert
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}
2023-08-31 23:57:30 +10:00
#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
// Arrange
let app = spawn_app().await;
2023-08-31 23:57:30 +10:00
let client = reqwest::Client::new();
2023-08-31 23:57:30 +10:00
// Act
let body = "name=le%20guin&email=ursula_le_guin%40gmail.com";
let response = client
.post(&format!("{}/subscriptions", &app.address))
2023-08-31 23:57:30 +10:00
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.expect("Failed to execute request.");
// Assert
assert_eq!(200, response.status().as_u16());
let saved = sqlx::query!("SELECT email, name FROM subscriptions",)
.fetch_one(&app.db_pool)
2023-08-31 23:57:30 +10:00
.await
.expect("Failed to fetch saved subscription.");
2023-08-31 23:57:30 +10:00
assert_eq!(saved.email, "ursula_le_guin@gmail.com");
assert_eq!(saved.name, "le guin");
}
#[tokio::test]
async fn subscribe_returns_a_400_when_data_is_missing() {
// Arrange
let app = spawn_app().await;
2023-08-31 23:57:30 +10:00
let client = reqwest::Client::new();
let test_cases = vec![
("name=le%20guin", "missing email"),
("email=ursula_le_guin%40gmail.com", "missing name"),
("", "missing both name and email"),
];
for (invalid_body, error_message) in test_cases {
// Act
let response = client
.post(&format!("{}/subscriptions", &app.address))
2023-08-31 23:57:30 +10:00
.header("Content-Type", "application/x-www-form-urlencoded")
.body(invalid_body)
.send()
.await
.expect("Failed to execute request.");
// Assert
assert_eq!(
400,
response.status().as_u16(),
"The API id not fail wth 400 Bad Request when the payload was {}.",
error_message
);
}
}