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

@@ -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
)
}
}

View File

@@ -1,11 +1,16 @@
use std::net::TcpListener;
use email_newsletter_api::{configuration::get_configuration, startup};
use sqlx::PgPool;
#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let configuration = get_configuration().expect("Failed to read configuration");
let db_conn = PgPool::connect(&configuration.database.connection_string())
.await
.expect("Failed to connect to PostgreSQL");
let port_number = configuration.application_port;
let listener = TcpListener::bind(format!("127.0.0.1:{}", port_number))
@@ -13,5 +18,5 @@ async fn main() -> Result<(), std::io::Error> {
// Move the error up the call stack
// otherwise await for the HttpServer
startup::run(listener)?.await
startup::run(listener, db_conn)?.await
}

View File

@@ -1,4 +1,7 @@
use actix_web::{web, HttpResponse};
use chrono::Utc;
use sqlx::PgPool;
use uuid::Uuid;
#[derive(serde::Deserialize)]
pub struct FormData {
@@ -6,6 +9,27 @@ pub struct FormData {
name: String,
}
pub async fn subscribe_route(_form: web::Form<FormData>) -> HttpResponse {
HttpResponse::Ok().finish()
pub async fn subscribe_route(
form: web::Form<FormData>,
db_conn_pool: web::Data<PgPool>,
) -> HttpResponse {
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(db_conn_pool.get_ref())
.await
{
Ok(_) => HttpResponse::Ok().finish(),
Err(e) => {
println!("Failed to execute query: {}", e);
HttpResponse::InternalServerError().finish()
}
}
}

View File

@@ -1,13 +1,19 @@
use crate::routes::{healthcheck_route, subscribe_route};
use actix_web::dev::Server;
use actix_web::{web, App, HttpServer};
use sqlx::PgPool;
use std::net::TcpListener;
pub fn run(listener: TcpListener) -> Result<Server, std::io::Error> {
let server = HttpServer::new(|| {
pub fn run(listener: TcpListener, db_conn_pool: PgPool) -> Result<Server, std::io::Error> {
// under the hood, web::Data::new will create an Arc
// to make the TCP connection to PostgreSQL clone-able
let db_conn_pool = web::Data::new(db_conn_pool);
let server = HttpServer::new(move || {
App::new()
.route("/health_check", web::get().to(healthcheck_route))
.route("/subscribe", web::post().to(subscribe_route))
.app_data(db_conn_pool.clone())
})
.listen(listener)?
.run();