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.
This commit is contained in:
Nick Bland 2021-11-08 15:41:52 +10:00
parent dd527eb839
commit a746b45f78
No known key found for this signature in database
GPG Key ID: B46CF88E4DAB4A2C
8 changed files with 120 additions and 32 deletions

View File

@ -13,6 +13,7 @@ steps:
image: postgres:12-alpine image: postgres:12-alpine
environment: environment:
PGPASSWORD: password PGPASSWORD: password
DATABASE_URL: postgres://postgres:password@postgres:5432/newsletter
commands: commands:
- sleep 35 - sleep 35
- "psql -U postgres -d newsletter -h postgres" - "psql -U postgres -d newsletter -h postgres"
@ -22,7 +23,6 @@ steps:
commands: commands:
- apt update && apt install -y build-essential pkg-config libssl-dev # Dependancies for sqlx - 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 - cargo install --version=0.5.7 sqlx-cli --no-default-features --features postgres # Install sqlx
- sqlx database create
- sqlx migrate run - sqlx migrate run
- name: test - name: test
@ -38,5 +38,4 @@ services:
environment: environment:
POSTGRES_USER: postgres POSTGRES_USER: postgres
POSTGRES_PASSWORD: password POSTGRES_PASSWORD: password
POSTGRES_DB: newsletter POSTGRES_DB: newsletter
DATABASE_URL: postgres://postgres:password@postgres:5432/newsletter

16
Cargo.lock generated
View File

@ -347,6 +347,7 @@ dependencies = [
"libc", "libc",
"num-integer", "num-integer",
"num-traits 0.2.14", "num-traits 0.2.14",
"time 0.1.43",
"winapi", "winapi",
] ]
@ -960,11 +961,13 @@ version = "0.1.0"
dependencies = [ dependencies = [
"actix-rt", "actix-rt",
"actix-web", "actix-web",
"chrono",
"config", "config",
"reqwest", "reqwest",
"serde 1.0.130", "serde 1.0.130",
"sqlx", "sqlx",
"tokio", "tokio",
"uuid",
] ]
[[package]] [[package]]
@ -1901,6 +1904,16 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "time"
version = "0.1.43"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca8a50ef2360fbd1eeb0ecd46795a87a19024eb4b53c5dc916ca1fd95fe62438"
dependencies = [
"libc",
"winapi",
]
[[package]] [[package]]
name = "time" name = "time"
version = "0.2.27" version = "0.2.27"
@ -2138,6 +2151,9 @@ name = "uuid"
version = "0.8.2" version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7"
dependencies = [
"getrandom",
]
[[package]] [[package]]
name = "vcpkg" name = "vcpkg"

View File

@ -11,6 +11,8 @@ path = "src/lib.rs"
actix-web = "4.0.0-beta.8" actix-web = "4.0.0-beta.8"
config = "0.11.0" config = "0.11.0"
serde = { version = "1", features = ["derive"]} serde = { version = "1", features = ["derive"]}
uuid = { version = "0.8.1", features = ["v4"] }
chrono = "0.4.15"
[dependencies.sqlx] [dependencies.sqlx]
version = "0.5.7" version = "0.5.7"
@ -28,3 +30,4 @@ features = [
actix-rt = "2" actix-rt = "2"
reqwest = "0.11" reqwest = "0.11"
tokio = "1" tokio = "1"

View File

@ -31,4 +31,11 @@ impl DatabaseSettings {
self.username, self.password, self.host, self.port, self.database_name 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
)
}
} }

View File

@ -1,14 +1,20 @@
use mail_app::startup::run; use mail_app::startup::run;
use mail_app::configuration::get_configuration; use mail_app::configuration::get_configuration;
use std::net::TcpListener; use std::net::TcpListener;
use sqlx::PgPool;
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
// Attempt to read from config // Attempt to read from config
let configuration = get_configuration().expect("Failed to read configuration data."); 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 // Take port from settings file
let address = format!("127.0.0.1:{}", configuration.application_port); let address = format!("127.0.0.1:{}", configuration.application_port);
let listener = TcpListener::bind(address)?; let listener = TcpListener::bind(address)?;
run(listener)?.await run(listener, connection_pool)?.await
} }

View File

@ -1,4 +1,7 @@
use actix_web::{web, HttpResponse}; use actix_web::{web, HttpResponse};
use sqlx::PgPool;
use chrono::Utc;
use uuid::Uuid;
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
pub struct FormData { pub struct FormData {
@ -6,6 +9,26 @@ pub struct FormData {
name: String name: String
} }
pub async fn subscribe(_form: web::Form<FormData>) -> HttpResponse { pub async fn subscribe(form: web::Form<FormData>, pool: web::Data<PgPool>,) -> HttpResponse {
HttpResponse::Ok().finish() // _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()
}
}
} }

View File

@ -1,14 +1,17 @@
use actix_web::{web, App, HttpServer}; use actix_web::{web, App, HttpServer};
use actix_web::dev::Server; use actix_web::dev::Server;
use std::net::TcpListener; use std::net::TcpListener;
use sqlx::PgPool;
use crate::routes; use crate::routes;
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> { pub fn run(listener: TcpListener, db_pool: PgPool) -> Result<Server, std::io::Error> {
let server = HttpServer::new(|| { let db_pool = web::Data::new(db_pool); // Wrap connection in a smart pointer
let server = HttpServer::new(move || {
App::new() App::new()
.route("/health_check", web::get().to(routes::health_check)) .route("/health_check", web::get().to(routes::health_check))
.route("/subscriptions", web::post().to(routes::subscribe)) .route("/subscriptions", web::post().to(routes::subscribe))
.app_data(db_pool.clone()) // Get pointer copy and attach to application state
}) })
.listen(listener)? .listen(listener)?
.run(); .run();

View File

@ -1,31 +1,68 @@
use std::net::TcpListener; 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::startup::run;
use mail_app::configuration::get_configuration; 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`] // Create new instance of the application on a random port and return address [`http://localhost:XXXX`]
fn spawn_app() -> String { async fn spawn_app() -> TestApp {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port"); let listener = TcpListener::bind("127.0.0.1:0")
.expect("Failed to bind to random port");
let port = listener.local_addr().unwrap().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); 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] #[actix_rt::test]
async fn health_check_works() { async fn health_check_works() {
// Arrange // Arrange
let address = spawn_app(); let app = spawn_app().await;
let client = reqwest::Client::new(); let client = reqwest::Client::new();
// Perform a 'reqwest' against endpoint // Act
let response = client let response = client
.get(&format!("{}/health_check", &address)) .get(&format!("{}/health_check", &app.address))
.send() .send()
.await .await
.expect("Failed to execute request."); .expect("Failed to execute request.");
@ -38,19 +75,13 @@ async fn health_check_works() {
#[actix_rt::test] #[actix_rt::test]
async fn subscribe_returns_200_for_valid_form_data() { async fn subscribe_returns_200_for_valid_form_data() {
// Arrange // Arrange
let app_address = spawn_app(); let app = spawn_app().await;
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 client = reqwest::Client::new(); 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 // Act
let response = client let response = client
.post(&format!("{}/subscriptions", &app_address)) .post(&format!("{}/subscriptions", &app.address))
.header("Content-Type", "application/x-www-form-urlencoded") .header("Content-Type", "application/x-www-form-urlencoded")
.body(body) .body(body)
.send() .send()
@ -61,7 +92,7 @@ async fn subscribe_returns_200_for_valid_form_data() {
assert_eq!(200, response.status().as_u16()); assert_eq!(200, response.status().as_u16());
let saved = sqlx::query!("SELECT email, name FROM subscriptions",) let saved = sqlx::query!("SELECT email, name FROM subscriptions",)
.fetch_one(&mut connection) .fetch_one(&app.db_pool)
.await .await
.expect("Failed to fetch saved subscription."); .expect("Failed to fetch saved subscription.");
@ -70,9 +101,9 @@ async fn subscribe_returns_200_for_valid_form_data() {
} }
#[actix_rt::test] #[actix_rt::test]
async fn subscrib_returns_400_for_missing_form_data() { async fn subscribe_returns_400_for_missing_form_data() {
//Arrange //Arrange
let app_address = spawn_app(); let app = spawn_app().await;
let client = reqwest::Client::new(); let client = reqwest::Client::new();
let test_cases = vec![ let test_cases = vec![
("name=le%20guin", "missing the email"), ("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 { for (invalid_body, error_message) in test_cases {
// Act // Act
let response = client let response = client
.post(&format!("{}/subscriptions", &app_address)) .post(&format!("{}/subscriptions", &app.address))
.header("Content-Type", "application/x-www-form-urlencoded") .header("Content-Type", "application/x-www-form-urlencoded")
.body(invalid_body) .body(invalid_body)
.send() .send()