feat: add persistance

This commit is contained in:
Sandro Eiler 2024-01-29 22:18:05 +01:00
parent 68e825c942
commit f2552a74ed
6 changed files with 81 additions and 69 deletions

View file

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