feat(test): spin up new logical database tests

- Tests will use new database every run
- Added chrono and uuid dependencies.
- Updated documentation
This commit is contained in:
2024-05-04 15:27:47 -04:00
parent 1c317e3f34
commit 5e6e9c2efe
10 changed files with 106 additions and 26 deletions

View File

@@ -4,12 +4,12 @@ use test_utils::spawn_app;
#[tokio::test]
async fn health_check_works() {
let server_address = spawn_app();
let test_app = spawn_app().await;
let client = reqwest::Client::new();
let response = client
.get(&format!("{}/health_check", &server_address))
.get(&format!("{}/health_check", &test_app.address))
.send()
.await
.expect("Failed to execute health_check request.");

View File

@@ -1,27 +1,17 @@
mod test_utils;
use email_newsletter_api::configuration::{self, get_configuration};
use sqlx::{Connection, PgConnection};
use test_utils::spawn_app;
#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
let server_address = spawn_app();
let configuration = get_configuration().expect("Failed to read configuration");
let postgres_connection_string = configuration.database.connection_string();
let mut connection = PgConnection::connect(&postgres_connection_string)
.await
.expect("Failed to connect to Postgres");
let test_app = spawn_app().await;
let client = reqwest::Client::new();
let body = "name=le%20test&email=le_test%40gmail.com";
let response = client
.post(&format!("{}/subscribe", &server_address))
.post(&format!("{}/subscribe", &test_app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
@@ -32,7 +22,7 @@ async fn subscribe_returns_a_200_for_valid_form_data() {
assert_eq!(Some(0), response.content_length());
let saved = sqlx::query!("SELECT email, name FROM subscriptions")
.fetch_one(&mut connection)
.fetch_one(&test_app.db_pool)
.await
.expect("Failed to fetch saved subscribtions");
@@ -42,7 +32,7 @@ async fn subscribe_returns_a_200_for_valid_form_data() {
#[tokio::test]
async fn subscribe_returns_a_400_when_data_is_missing() {
let server_address = spawn_app();
let test_app = spawn_app().await;
let client = reqwest::Client::new();
@@ -54,7 +44,7 @@ async fn subscribe_returns_a_400_when_data_is_missing() {
for (invalid_body, error_message) in test_cases {
let response = client
.post(&format!("{}/subscribe", &server_address))
.post(&format!("{}/subscribe", &test_app.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(invalid_body)
.send()

View File

@@ -1,17 +1,31 @@
use email_newsletter_api::configuration::{get_configuration, DatabaseSettings};
use sqlx::{Connection, Executor, PgConnection, PgPool};
use std::net::TcpListener;
use uuid::Uuid;
pub struct TestApp {
pub address: String,
pub db_pool: PgPool,
}
#[allow(dead_code)]
#[allow(clippy::let_underscore_future)]
pub fn spawn_app() -> String {
pub async fn spawn_app() -> TestApp {
/* Spawn a app server with a TcpListener bound to localhost:<random port>
*
* Returns a valid IPv4 string (i.e localhost:8080)
*/
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to a random port");
let mut configuration = get_configuration().expect("Failed to read configuration");
configuration.database.database_name = Uuid::new_v4().to_string();
let db_conn_pool = configure_test_database(&configuration.database).await;
let port = listener.local_addr().unwrap().port();
let server = email_newsletter_api::startup::run(listener).expect("Failed to bind address");
let server = email_newsletter_api::startup::run(listener, db_conn_pool.clone())
.expect("Failed to bind address");
/* `tokio::spawn(/*async task*/)` will spawn an async task to be run.
We can continue executing other code concurrently while `task` runs in the background.
@@ -20,5 +34,30 @@ pub fn spawn_app() -> String {
(which `#[tokio::test]` will take care for us in the mean time).*/
let _ = tokio::spawn(server);
format!("http://127.0.0.1:{}", port)
TestApp {
address: format!("http://127.0.0.1:{}", port),
db_pool: db_conn_pool,
}
}
pub async fn configure_test_database(db_config: &DatabaseSettings) -> PgPool {
let mut connection = PgConnection::connect(&db_config.connection_string_without_db())
.await
.expect("Failed to connect to Postgres");
connection
.execute(format!(r#"CREATE DATABASE "{}";"#, db_config.database_name).as_str())
.await
.expect("Failed to create database");
let conn_pool = PgPool::connect(&db_config.connection_string())
.await
.expect("Failed to connect to PostgreSQL pool");
sqlx::migrate!("./migrations")
.run(&conn_pool)
.await
.expect("Failed to migrate the database");
conn_pool
}