Skip to content

Commit

Permalink
Add PgPool and Fix tests
Browse files Browse the repository at this point in the history
Signed-off-by: Anthony M. Bonafide <AnthonyMBonafide@gmail.com>
  • Loading branch information
AnthonyMBonafide committed Mar 27, 2024
1 parent 6b4e97a commit 10f5377
Show file tree
Hide file tree
Showing 5 changed files with 56 additions and 24 deletions.
7 changes: 7 additions & 0 deletions src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ 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
)
}
}

pub fn get_configuration() -> Result<Settings, config::ConfigError> {
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
use std::net::TcpListener;

use sqlx::{Connection, PgConnection};
use sqlx::{Connection, PgPool};
use zero2prod::{configuration::get_configuration, run};

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let config = get_configuration().expect("Failed to read configuration");
let address = format!("127.0.0.1:{}", config.application_port);
let config = get_configuration().expect("Failed to get configuration");
let connection = PgConnection::connect(&config.database.connection_string())
let connection = PgPool::connect(&config.database.connection_string())
.await
.expect("Failed to connect to database");

Expand Down
19 changes: 11 additions & 8 deletions src/routes/subscriptions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use actix_web::{web, HttpResponse};
use chrono::Utc;
use sqlx::PgConnection;
use sqlx::PgPool;
use uuid::Uuid;

#[derive(serde::Deserialize, serde::Serialize)]
Expand All @@ -9,11 +9,8 @@ pub struct FormData {
email: String,
}

pub async fn subscribe(
form: web::Form<FormData>,
connection: web::Data<PgConnection>,
) -> HttpResponse {
sqlx::query!(
pub async fn subscribe(form: web::Form<FormData>, connection: web::Data<PgPool>) -> HttpResponse {
match sqlx::query!(
r#"
INSERT INTO subscriptions (id, email, name, subscribed_at)
VALUES ($1, $2, $3, $4)
Expand All @@ -24,6 +21,12 @@ pub async fn subscribe(
Utc::now()
)
.execute(connection.get_ref())
.await;
HttpResponse::Ok().finish()
.await
{
Ok(_) => HttpResponse::Ok().finish(),
Err(e) => {
println!("Failed to execute query: {}", e);
HttpResponse::InternalServerError().finish()
}
}
}
4 changes: 2 additions & 2 deletions src/startup.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use crate::routes::{health_check, subscribe};
use actix_web::{dev::Server, web, App, HttpServer};
use sqlx::PgConnection;
use sqlx::PgPool;
use std::net::TcpListener;

pub fn run(tcp_listener: TcpListener, connection: PgConnection) -> Result<Server, std::io::Error> {
pub fn run(tcp_listener: TcpListener, connection: PgPool) -> Result<Server, std::io::Error> {
let connection = web::Data::new(connection);
let server = HttpServer::new(move || {
App::new()
Expand Down
46 changes: 34 additions & 12 deletions tests/health_check.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use sqlx::{Connection, PgConnection, Row};
use sqlx::{Connection, Executor, PgConnection, PgPool, Row};
use std::net::TcpListener;
use uuid::Uuid;

use zero2prod::{get_configuration, run};
use zero2prod::{configuration::DatabaseSettings, get_configuration, run};

#[tokio::test]
async fn health_check_works() {
let address = spawn_app();
let address = spawn_app().await;

let client = reqwest::Client::new();

Expand All @@ -21,7 +22,7 @@ async fn health_check_works() {

#[tokio::test]
async fn subscribe_returns_200_for_valid_form_data() {
let address = spawn_app();
let address = spawn_app().await;
let client = reqwest::Client::new();

let body = "name=le%20guin&email=ursula_le_guin%40gmail.com";
Expand All @@ -46,12 +47,12 @@ async fn subscribe_returns_200_for_valid_form_data() {
.expect("Failed to execute query");

assert_eq!("le guin", r.name);
assert_eq!("le_guin@gmail.com", r.email);
assert_eq!("ursula_le_guin@gmail.com", r.email);
}

#[tokio::test]
async fn subscribe_returns_400_for_missing_form_data() {
let address = spawn_app();
let address = spawn_app().await;
let client = reqwest::Client::new();
let test_cases = vec![
("name=le%20guin", "missing email"),
Expand All @@ -76,17 +77,38 @@ async fn subscribe_returns_400_for_missing_form_data() {
)
}
}
fn spawn_app() -> String {
async fn spawn_app() -> String {
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind port");
let port = listener.local_addr().unwrap().port();
let config = get_configuration().expect("Failed to get configuration");
let connection = PgConnection::connect(&config.database.connection_string())
.await
.expect("Failed to connect to database");
let mut config = get_configuration().expect("Failed to get configuration");
config.database.database_name = Uuid::new_v4().to_string();

let server = run(listener, connection).expect("Failed to bind address");
let pool = configure_database(&config.database).await;
let server = run(listener, pool).expect("Failed to bind address");

let _server_run = tokio::spawn(server);
std::mem::drop(_server_run);
format!("http://127.0.0.1:{}", port)
}

async fn configure_database(config: &DatabaseSettings) -> PgPool {
let mut connection = PgConnection::connect(&config.connection_string_without_db())
.await
.expect("Failed to connect to database");

connection
.execute(format!(r#"CREATE DATABASE "{}";"#, config.database_name).as_str())
.await
.expect("Failed to create test database");

let connections_pool = PgPool::connect(&config.connection_string())
.await
.expect("Failed to create connection pool");

sqlx::migrate!("./migrations")
.run(&connections_pool)
.await
.expect("Failed to migrate test database");

connections_pool
}

0 comments on commit 10f5377

Please sign in to comment.