mailApp/tests/health_check.rs

97 lines
2.9 KiB
Rust
Raw Normal View History

2023-08-31 23:57:30 +10:00
use mail_app::configuration::get_configuration;
use mail_app::startup::run;
use sqlx::{Connection, PgConnection};
use std::net::TcpListener;
2023-08-31 23:57:30 +10:00
fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port.");
let port = listener.local_addr().unwrap().port();
let server = run(listener).expect("Failed to bind address");
// Launch in background
let _spawn = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
}
#[tokio::test]
async fn health_check_works() {
// Arrange
let address = spawn_app();
let client = reqwest::Client::new();
// Act
let response = client
.get(&format!("{}/health_check", &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_address = spawn_app();
let configuration = get_configuration().expect("Failed to get config");
let connection_string = configuration.database.connection_string();
let mut connection = PgConnection::connect(&connection_string)
.await
.expect("Failed to connect to Postgres Database.");
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))
.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(&mut connection)
.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_address = spawn_app();
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))
.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
);
}
}