Skip to content

Commit

Permalink
Refactor integration tests, share server startup code between prod an…
Browse files Browse the repository at this point in the history
…d test
  • Loading branch information
samituga committed Jun 13, 2024
1 parent a49e473 commit f73886a
Show file tree
Hide file tree
Showing 8 changed files with 223 additions and 217 deletions.
10 changes: 5 additions & 5 deletions src/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,22 @@ use sqlx::ConnectOptions;

use crate::domain::SubscriberEmail;

#[derive(serde::Deserialize)]
#[derive(serde::Deserialize, Clone)]
pub struct Settings {
pub application: ApplicationSettings,
pub database: DatabaseSettings,
pub aws: AwsSettings,
pub email_client: EmailClientSettings,
}

#[derive(serde::Deserialize)]
#[derive(serde::Deserialize, Clone)]
pub struct ApplicationSettings {
#[serde(deserialize_with = "deserialize_number_from_string")]
pub port: u16,
pub host: String,
}

#[derive(serde::Deserialize)]
#[derive(serde::Deserialize, Clone)]
pub struct DatabaseSettings {
pub username: String,
pub password: Secret<String>,
Expand Down Expand Up @@ -60,7 +60,7 @@ impl DatabaseSettings {
}
}

#[derive(serde::Deserialize)]
#[derive(serde::Deserialize, Clone)]
pub struct AwsSettings {
region: String,
access_key_id: String,
Expand Down Expand Up @@ -98,7 +98,7 @@ impl AwsSettings {
}
}

#[derive(serde::Deserialize)]
#[derive(serde::Deserialize, Clone)]
pub struct EmailClientSettings {
pub sender_email: String,
}
Expand Down
38 changes: 6 additions & 32 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,41 +1,15 @@
use std::net::TcpListener;

use sqlx::postgres::PgPoolOptions;

use zero2prod::configuration::get_configuration;
use zero2prod::email_client::{AwsSesEmailSender, EmailService};
use zero2prod::startup::run;
use zero2prod::startup::Application;
use zero2prod::telemetry::{get_subscriber, init_subscriber};

#[tokio::main]
async fn main() -> Result<(), std::io::Error> {
let subscriber = get_subscriber("zero2prod".into(), "info".into(), std::io::stdout);
init_subscriber(subscriber);
let telemetry_subscriber = get_subscriber("zero2prod".into(), "info".into(), std::io::stdout);
init_subscriber(telemetry_subscriber);

let configuration = get_configuration().expect("Failed to read configuration.");
let server = Application::build(configuration).await?;

let connection_pool = PgPoolOptions::new()
.connect_with(configuration.database.with_db_name())
.await
.expect("Failed to connect to the database");

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

let aws_client = AwsSesEmailSender::new(configuration.aws.ses_client().await);
let sender_email = configuration
.email_client
.sender()
.expect("Invalid sender email address.");

let email_client = EmailService::new(aws_client, sender_email);

let address = format!(
"{}:{}",
configuration.application.host, configuration.application.port
);
let listener = TcpListener::bind(address)?;
run(listener, connection_pool, email_client)?.await
server.run_until_stopped().await?;
Ok(())
}
51 changes: 50 additions & 1 deletion src/startup.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,57 @@
use std::net::TcpListener;

use crate::email_client::{AwsSesEmailSender, EmailService};
use actix_web::dev::Server;
use actix_web::{web, App, HttpServer};
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use tracing_actix_web::TracingLogger;

use crate::configuration::{DatabaseSettings, Settings};
use crate::email_client::{AwsSesEmailSender, EmailService};
use crate::routes::{health_check, subscribe};

pub struct Application {
port: u16,
server: Server,
}

impl Application {
pub async fn build(configuration: Settings) -> Result<Self, std::io::Error> {
let connection_pool = get_connection_pool(&configuration.database);

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

let aws_ses_client = AwsSesEmailSender::new(configuration.aws.ses_client().await);
let sender_email = configuration
.email_client
.sender()
.expect("Invalid sender email address.");

let email_client = EmailService::new(aws_ses_client, sender_email);

let address = format!(
"{}:{}",
configuration.application.host, configuration.application.port
);
let listener = TcpListener::bind(address)?;
let port = listener.local_addr().unwrap().port();
let server = run(listener, connection_pool, email_client)?;

Ok(Self { port, server })
}

pub fn port(&self) -> u16 {
self.port
}

pub async fn run_until_stopped(self) -> Result<(), std::io::Error> {
self.server.await
}
}

pub fn run(
listener: TcpListener,
db_pool: PgPool,
Expand All @@ -27,3 +71,8 @@ pub fn run(
.run();
Ok(server)
}

pub fn get_connection_pool(configuration: &DatabaseSettings) -> PgPool {
// TODO Eager connection?
PgPoolOptions::new().connect_lazy_with(configuration.with_db_name())
}
19 changes: 19 additions & 0 deletions tests/api/health_check.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
use crate::helpers::spawn_app;

#[tokio::test]
async fn health_check_works() {
// Arrange
let app = spawn_app().await;
let client = reqwest::Client::new();

// Act
let response = client
.get(&format!("{}/health_check", &app.address))
.send()
.await
.expect("Failed to execute request.");

// Assert
assert!(response.status().is_success());
assert_eq!(Some(0), response.content_length());
}
73 changes: 73 additions & 0 deletions tests/api/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use once_cell::sync::Lazy;
use sqlx::{Connection, Executor, PgConnection, PgPool};
use uuid::Uuid;

use zero2prod::configuration::{get_configuration, DatabaseSettings};
use zero2prod::startup::{get_connection_pool, Application};
use zero2prod::telemetry::{get_subscriber, init_subscriber};

pub struct TestApp {
pub address: String,
pub db_pool: PgPool,
}

impl TestApp {
pub async fn post_subscriptions(&self, body: String) -> reqwest::Response {
reqwest::Client::new()
.post(&format!("{}/subscriptions", &self.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()
.await
.expect("Failed to execute request.")
}
}

static TRACING: Lazy<()> = Lazy::new(|| {
let default_filter_level = "info".to_string();
let subscriber_name = "test".to_string();

if std::env::var("TEST_LOG").is_ok() {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::stdout);
init_subscriber(subscriber);
} else {
let subscriber = get_subscriber(subscriber_name, default_filter_level, std::io::sink);
init_subscriber(subscriber);
};
});

pub async fn spawn_app() -> TestApp {
Lazy::force(&TRACING);

let configuration = {
let mut configuration = get_configuration().expect("Failed to read configuration.");
configuration.database.database_name = Uuid::new_v4().to_string();
configuration.application.port = 0;
configuration
};

create_database(&configuration.database).await;

let application = Application::build(configuration.clone())
.await
.expect("Failed to build application.");
let address = format!("http://127.0.0.1:{}", application.port());

let _ = tokio::spawn(application.run_until_stopped());

TestApp {
address,
db_pool: get_connection_pool(&configuration.database),
}
}

async fn create_database(config: &DatabaseSettings) {
let mut connection = PgConnection::connect_with(&config.without_db_name())
.await
.expect("Failed to connect to Postgres");

connection
.execute(&*format!(r#"CREATE DATABASE "{}";"#, config.database_name))
.await
.expect("Failed to create database.");
}
3 changes: 3 additions & 0 deletions tests/api/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
mod health_check;
mod helpers;
mod subscriptions;
67 changes: 67 additions & 0 deletions tests/api/subscriptions.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use crate::helpers::spawn_app;

#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
// Arrange
let app = spawn_app().await;
let body = "name=le%20guin&email=ursula_le_guin%40gmail.com";

// Act
let response = app.post_subscriptions(body.into()).await;

// 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, "[email protected]");
assert_eq!(saved.name, "le guin");
}

#[tokio::test]
async fn subscribe_returns_a_400_when_data_is_missing() {
// Arrange
let app = spawn_app().await;
let test_cases = vec![
("name=le%20guin", "missing the email"),
("email=ursula_le_guin%40gmail.com", "missing the name"),
("", "missing both name and email"),
];
for (invalid_body, error_message) in test_cases {
// Act
let response = app.post_subscriptions(invalid_body.into()).await;

// Assert
assert_eq!(
400,
response.status().as_u16(),
"The API did not fail with 400 Bad Request when the payload was {}.",
error_message
);
}
}

#[tokio::test]
async fn subscribe_returns_400_when_fields_are_present_but_invalid() {
// Arrange
let app = spawn_app().await;
let test_cases = vec![
("name=&email=ursula_le_guin%40gmail.com", "empty name"),
("name=Ursula&email=", "empty email"),
("name=Ursula&email=definitely-not-an-email", "invalid email"),
];

for (body, description) in test_cases {
// Act
let response = app.post_subscriptions(body.into()).await;

assert_eq!(
400,
response.status().as_u16(),
"The API did not return a 400 Bad Request when the payload was {}.",
description
)
}
}
Loading

0 comments on commit f73886a

Please sign in to comment.