From f2552a74edf4447ab40ede267b80e219d5039d40 Mon Sep 17 00:00:00 2001 From: Sandro Eiler Date: Mon, 29 Jan 2024 22:18:05 +0100 Subject: [PATCH] feat: add persistance --- Cargo.lock | 5 +- Cargo.toml | 4 +- src/configuration.rs | 7 +++ src/main.rs | 13 ++--- src/startup.rs | 2 +- tests/health_check.rs | 119 +++++++++++++++++++++++------------------- 6 files changed, 81 insertions(+), 69 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 22418c0..5f3e68f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -249,10 +249,7 @@ checksum = "7f2c685bad3eb3d45a01354cedb7d5faa66194d1d58ba6e267a8de788f79db38" dependencies = [ "android-tzdata", "iana-time-zone", - "js-sys", "num-traits", - "serde", - "wasm-bindgen", "windows-targets 0.48.1", ] @@ -986,7 +983,7 @@ dependencies = [ [[package]] name = "learn_axum" -version = "0.1.0" +version = "0.2.0" dependencies = [ "axum", "chrono", diff --git a/Cargo.toml b/Cargo.toml index 6cd0a26..8d5f83a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "learn_axum" -version = "0.1.0" +version = "0.2.0" edition = "2021" [lib] @@ -29,7 +29,7 @@ config = "0.13" # async-trait = "0.1" # strum_macros = "0.25" uuid = { version = "1", features = ["v4", "fast-rng"] } -chrono = { version = "0.4", features = ["serde"] } +chrono = { version = "0.4", default-features = false, features = ["clock"] } [dependencies.sqlx] version = "0.7" diff --git a/src/configuration.rs b/src/configuration.rs index 3d6a08a..5966698 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -44,4 +44,11 @@ impl DatabaseSettings { self.username, self.password, self.host, self.port, self.name ) } + + pub fn connection_string_without_db(&self) -> String { + format!( + "postgres://{}:{}@{}:{}", + self.username, self.password, self.host, self.port + ) + } } diff --git a/src/main.rs b/src/main.rs index 471d70f..98279ba 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,8 +1,6 @@ -use std::time::Duration; - use learn_axum::configuration::get_configuration; use learn_axum::startup; -use sqlx::postgres::PgPoolOptions; +use sqlx::PgPool; use tokio::net::TcpListener; #[tokio::main] @@ -10,11 +8,8 @@ async fn main() { let configuration = get_configuration().expect("Failed to read configuration."); let addr = format!("127.0.0.1:{}", configuration.application_port); let listener = TcpListener::bind(addr).await.unwrap(); //.expect("Unable to bind to port"); - let pool = PgPoolOptions::new() - .max_connections(5) - .acquire_timeout(Duration::from_secs(3)) - .connect(&configuration.database.connection_string()) + let connection_pool = PgPool::connect(&configuration.database.connection_string()) .await - .expect("can't connect to database"); - startup::run(listener, pool).await.unwrap(); + .expect("Failed to connect to Postgres."); + startup::run(listener, connection_pool).await.unwrap(); } diff --git a/src/startup.rs b/src/startup.rs index d471be6..3495c4a 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -8,7 +8,7 @@ use tokio::net::TcpListener; pub fn app(connection: PgPool) -> Router { Router::new() .merge(crate::routes::routes_health_check()) - .merge(crate::routes::routes_subscriptions(connection)) + .merge(crate::routes::routes_subscriptions(connection.clone())) } /// Start the server diff --git a/tests/health_check.rs b/tests/health_check.rs index 7e1e9f9..e54ef2c 100644 --- a/tests/health_check.rs +++ b/tests/health_check.rs @@ -1,11 +1,11 @@ -use std::time::Duration; - -use learn_axum::configuration::get_configuration; -use sqlx::{postgres::PgPoolOptions, Connection, PgConnection}; +use learn_axum::configuration::{get_configuration, DatabaseSettings}; +use sqlx::{Connection, Executor, PgConnection, PgPool}; use tokio::net::TcpListener; +use uuid::Uuid; -struct TestApp { - address: String, +pub struct TestApp { + pub address: String, + pub db_pool: PgPool, } #[tokio::test] @@ -27,42 +27,7 @@ async fn health_check_works() { } #[tokio::test] -async fn subscribe_returns_a_200_for_valid_form_data() { - // Arrange - let TestApp { address } = spawn_app().await; - let configuration = get_configuration().expect("Failed to read configuration"); - let connection_string = configuration.database.connection_string(); - // The `Connection` trait MUST be in scope for us to invoke - // `PgConnection::connect` - it is not an inherent method of the struct! - let mut connection = PgConnection::connect(&connection_string) - .await - .expect("Failed to connect to Postgres."); - let client = reqwest::Client::new(); - - // Act - let body = "name=le%20guin&email=ursula_le_guin%40gmail.com"; - let response = client - .post(&format!("{}/subscriptions", &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."); - - 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() { +async fn subscribe_returns_a_422_when_data_is_missing() { // Arrange let TestApp { address, .. } = spawn_app().await; let client = reqwest::Client::new(); @@ -92,22 +57,70 @@ async fn subscribe_returns_a_400_when_data_is_missing() { } } +#[tokio::test] +async fn subscribe_returns_a_200_for_valid_form_data() { + // Arrange + let app = spawn_app().await; + let client = reqwest::Client::new(); + + // 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(&app.db_pool) + .await + .expect("Failed to fetch saved subscription."); + + assert_eq!(saved.email, "ursula_le_guin@gmail.com"); + assert_eq!(saved.name, "le guin"); +} + async fn spawn_app() -> TestApp { let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let address = format!("http://{}", listener.local_addr().unwrap()); - let configuration = get_configuration().expect("Failed to read configuration."); - let pool = PgPoolOptions::new() - .max_connections(5) - .acquire_timeout(Duration::from_secs(3)) - .connect(&configuration.database.connection_string()) - .await - .expect("can't connect to database"); + let mut configuration = get_configuration().expect("Failed to read configuration."); + configuration.database.name = Uuid::new_v4().to_string(); + let connection_pool = configure_database(&configuration.database).await; + let service = learn_axum::startup::app(connection_pool.clone()); tokio::spawn(async move { - axum::serve(listener, learn_axum::startup::app(pool)) - .await - .unwrap(); + axum::serve(listener, service).await.unwrap(); }); - TestApp { address } + TestApp { + address, + db_pool: connection_pool, + } +} + +pub async fn configure_database(config: &DatabaseSettings) -> PgPool { + // Create database + let mut connection = PgConnection::connect(&config.connection_string_without_db()) + .await + .expect("Failed to connect to Postgres"); + connection + .execute(format!(r#"CREATE DATABASE "{}";"#, config.name).as_str()) + .await + .expect("Failed to create database."); + + // Migrate database + let connection_pool = PgPool::connect(&config.connection_string()) + .await + .expect("Failed to connect to Postgres."); + sqlx::migrate!("./migrations") + .run(&connection_pool) + .await + .expect("Failed to migrate the database"); + + connection_pool }