mailApp/tests/health_check.rs
2021-11-05 14:17:36 +10:00

83 lines
2.5 KiB
Rust

use std::net::TcpListener;
// Create new instance of the application on a random port and return address [`http://localhost:XXXX`]
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 = mail_app::run(listener).expect("Failed to bind address");
let _ = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
}
#[actix_rt::test]
async fn health_check_works() {
// Arrange
let address = spawn_app();
let client = reqwest::Client::new();
// Perform a 'reqwest' against endpoint
let response = client
.get(&format!("{}/health_check", &address))
.send()
.await
.expect("Failed to execute request.");
// Assert our test
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}
#[actix_rt::test]
async fn subscribe_returns_200_for_valid_form_data() {
// Arrange
let app_address = spawn_app();
let client = reqwest::Client::new();
let body = "name=le%20guin&email=usrula_le_guin%40gmail.com";
// Act
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 test
assert_eq!(200, response.status().as_u16());
}
#[actix_rt::test]
async fn subscrib_returns_400_for_missing_form_data() {
//Arrange
let app_address = spawn_app();
let client = reqwest::Client::new();
let test_cases = vec![
("name=le%20guin", "missing the email"),
("email=ursula_le_guin%40gmail.com", "missing the 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(),
// Customised error message on test failure
"The API did not fail with 400 Bad Request when the payload was {}.", error_message
);
}
}