From a746b45f784fc3a78b1520c2b093b8cc51d5b25f Mon Sep 17 00:00:00 2001 From: Nick Bland Date: Mon, 8 Nov 2021 15:41:52 +1000 Subject: [PATCH] Implement changes to allow database connection for insertions Also updated tests to reflect the new PgPool format being used. Tests now create a mock database on creation to determine if it works before removing it. Up to Chapter 4. --- .drone.yml | 5 +-- Cargo.lock | 16 ++++++++ Cargo.toml | 3 ++ src/configuration.rs | 7 ++++ src/main.rs | 8 +++- src/routes/subscriptions.rs | 27 ++++++++++++- src/startup.rs | 7 +++- tests/health_check.rs | 79 ++++++++++++++++++++++++++----------- 8 files changed, 120 insertions(+), 32 deletions(-) diff --git a/.drone.yml b/.drone.yml index 041b87f..22f27d2 100644 --- a/.drone.yml +++ b/.drone.yml @@ -13,6 +13,7 @@ steps: image: postgres:12-alpine environment: PGPASSWORD: password + DATABASE_URL: postgres://postgres:password@postgres:5432/newsletter commands: - sleep 35 - "psql -U postgres -d newsletter -h postgres" @@ -22,7 +23,6 @@ steps: commands: - apt update && apt install -y build-essential pkg-config libssl-dev # Dependancies for sqlx - cargo install --version=0.5.7 sqlx-cli --no-default-features --features postgres # Install sqlx - - sqlx database create - sqlx migrate run - name: test @@ -38,5 +38,4 @@ services: environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password - POSTGRES_DB: newsletter - DATABASE_URL: postgres://postgres:password@postgres:5432/newsletter \ No newline at end of file + POSTGRES_DB: newsletter \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index fe7e704..f2d680f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -347,6 +347,7 @@ dependencies = [ "libc", "num-integer", "num-traits 0.2.14", + "time 0.1.43", "winapi", ] @@ -960,11 +961,13 @@ version = "0.1.0" dependencies = [ "actix-rt", "actix-web", + "chrono", "config", "reqwest", "serde 1.0.130", "sqlx", "tokio", + "uuid", ] [[package]] @@ -1901,6 +1904,16 @@ dependencies = [ "syn", ] +[[package]] +name = "time" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "time" version = "0.2.27" @@ -2138,6 +2151,9 @@ name = "uuid" version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" +dependencies = [ + "getrandom", +] [[package]] name = "vcpkg" diff --git a/Cargo.toml b/Cargo.toml index f91f15c..75816e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,8 @@ path = "src/lib.rs" actix-web = "4.0.0-beta.8" config = "0.11.0" serde = { version = "1", features = ["derive"]} +uuid = { version = "0.8.1", features = ["v4"] } +chrono = "0.4.15" [dependencies.sqlx] version = "0.5.7" @@ -28,3 +30,4 @@ features = [ actix-rt = "2" reqwest = "0.11" tokio = "1" + \ No newline at end of file diff --git a/src/configuration.rs b/src/configuration.rs index 85f9b9f..23e583d 100644 --- a/src/configuration.rs +++ b/src/configuration.rs @@ -31,4 +31,11 @@ impl DatabaseSettings { self.username, self.password, self.host, self.port, self.database_name ) } + + pub fn connection_string_without_db(&self) -> String { + format!( + "postgres://{}:{}@{}:{}", + self.username, self.password, self.host, self.port + ) + } } \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index 5dfe544..93bff68 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,20 @@ use mail_app::startup::run; use mail_app::configuration::get_configuration; use std::net::TcpListener; +use sqlx::PgPool; #[actix_web::main] async fn main() -> std::io::Result<()> { // Attempt to read from config let configuration = get_configuration().expect("Failed to read configuration data."); + // Configure connection to database for our startup + let connection_pool = PgPool::connect(&configuration.database.connection_string()) + .await + .expect("Failed to connect to Postgres."); + // Take port from settings file let address = format!("127.0.0.1:{}", configuration.application_port); let listener = TcpListener::bind(address)?; - run(listener)?.await + run(listener, connection_pool)?.await } \ No newline at end of file diff --git a/src/routes/subscriptions.rs b/src/routes/subscriptions.rs index f2ffee6..13b7edf 100644 --- a/src/routes/subscriptions.rs +++ b/src/routes/subscriptions.rs @@ -1,4 +1,7 @@ use actix_web::{web, HttpResponse}; +use sqlx::PgPool; +use chrono::Utc; +use uuid::Uuid; #[derive(serde::Deserialize)] pub struct FormData { @@ -6,6 +9,26 @@ pub struct FormData { name: String } -pub async fn subscribe(_form: web::Form) -> HttpResponse { - HttpResponse::Ok().finish() +pub async fn subscribe(form: web::Form, pool: web::Data,) -> HttpResponse { + // _connect uses PgPool from the application state as defined in startup.rs + // Use a match statement for the query as it only returns two outcomes + match sqlx::query!( + r#" + INSERT INTO subscriptions (id, email, name, subscribed_at) + VALUES($1, $2, $3, $4) + "#, + Uuid::new_v4(), + form.email, + form.name, + Utc::now() + ) + .execute(pool.as_ref()) + .await + { + Ok(_) => HttpResponse::Ok().finish(), + Err(e) => { + println!("Failed to execute query: {}", e); + HttpResponse::InternalServerError().finish() + } + } } \ No newline at end of file diff --git a/src/startup.rs b/src/startup.rs index 4d3d176..6c4de05 100644 --- a/src/startup.rs +++ b/src/startup.rs @@ -1,14 +1,17 @@ use actix_web::{web, App, HttpServer}; use actix_web::dev::Server; use std::net::TcpListener; +use sqlx::PgPool; use crate::routes; -pub fn run(listener: TcpListener) -> Result { - let server = HttpServer::new(|| { +pub fn run(listener: TcpListener, db_pool: PgPool) -> Result { + let db_pool = web::Data::new(db_pool); // Wrap connection in a smart pointer + let server = HttpServer::new(move || { App::new() .route("/health_check", web::get().to(routes::health_check)) .route("/subscriptions", web::post().to(routes::subscribe)) + .app_data(db_pool.clone()) // Get pointer copy and attach to application state }) .listen(listener)? .run(); diff --git a/tests/health_check.rs b/tests/health_check.rs index 2dbbf47..3eec10a 100644 --- a/tests/health_check.rs +++ b/tests/health_check.rs @@ -1,31 +1,68 @@ use std::net::TcpListener; -use mail_app::startup::run; +use sqlx::{Connection, Executor, PgConnection, PgPool}; +use uuid::Uuid; -use sqlx::{PgConnection, Connection}; -use mail_app::configuration::get_configuration; +use mail_app::startup::run; +use mail_app::configuration::{get_configuration, DatabaseSettings}; + +pub struct TestApp { + pub address: String, + pub db_pool: PgPool, +} // 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"); +async fn spawn_app() -> TestApp { + 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 server = run(listener).expect("Failed to bind address"); + let mut configuration = get_configuration() + .expect("Failed to read configuration."); + configuration.database.database_name = Uuid::new_v4().to_string(); // Adjust database string to be random! + + let connection_pool = configure_database(&configuration.database).await; + let server = run(listener, connection_pool.clone()) + .expect("Failed to bind address"); let _ = tokio::spawn(server); + TestApp { + address, + db_pool: connection_pool, + } +} - format!("http://127.0.0.1:{}", port) +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.database_name)) + .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 } #[actix_rt::test] async fn health_check_works() { // Arrange - let address = spawn_app(); + let app = spawn_app().await; let client = reqwest::Client::new(); - // Perform a 'reqwest' against endpoint - + // Act let response = client - .get(&format!("{}/health_check", &address)) + .get(&format!("{}/health_check", &app.address)) .send() .await .expect("Failed to execute request."); @@ -38,19 +75,13 @@ async fn health_check_works() { #[actix_rt::test] async fn subscribe_returns_200_for_valid_form_data() { // Arrange - let app_address = spawn_app(); - let configuration = get_configuration().expect("Failed to read configuration."); - let connection_string = configuration.database.connection_string(); - // Connection trait MUST be in scope to invoke. - let mut connection = PgConnection::connect(&connection_string) - .await - .expect("Failed to connect to Postgres."); + let app = spawn_app().await; let client = reqwest::Client::new(); - let body = "name=le%20guin&email=usrula_le_guin%40gmail.com"; + let body = "name=le%20guin&email=ursula_le_guin%40gmail.com"; // Act let response = client - .post(&format!("{}/subscriptions", &app_address)) + .post(&format!("{}/subscriptions", &app.address)) .header("Content-Type", "application/x-www-form-urlencoded") .body(body) .send() @@ -61,7 +92,7 @@ async fn subscribe_returns_200_for_valid_form_data() { assert_eq!(200, response.status().as_u16()); let saved = sqlx::query!("SELECT email, name FROM subscriptions",) - .fetch_one(&mut connection) + .fetch_one(&app.db_pool) .await .expect("Failed to fetch saved subscription."); @@ -70,9 +101,9 @@ async fn subscribe_returns_200_for_valid_form_data() { } #[actix_rt::test] -async fn subscrib_returns_400_for_missing_form_data() { +async fn subscribe_returns_400_for_missing_form_data() { //Arrange - let app_address = spawn_app(); + let app = spawn_app().await; let client = reqwest::Client::new(); let test_cases = vec![ ("name=le%20guin", "missing the email"), @@ -83,7 +114,7 @@ async fn subscrib_returns_400_for_missing_form_data() { for (invalid_body, error_message) in test_cases { // Act let response = client - .post(&format!("{}/subscriptions", &app_address)) + .post(&format!("{}/subscriptions", &app.address)) .header("Content-Type", "application/x-www-form-urlencoded") .body(invalid_body) .send()