Confirm subscription endpoint

This commit is contained in:
Alphonse Paix
2025-08-25 17:46:03 +02:00
parent 73ff7c04fe
commit d1cf1f6c4f
14 changed files with 421 additions and 39 deletions

View File

@@ -6,7 +6,7 @@ async fn health_check_works() {
let client = reqwest::Client::new();
let response = client
.get(format!("http://{}/health_check", app.address))
.get(format!("{}/health_check", app.address))
.send()
.await
.unwrap();

View File

@@ -1,6 +1,8 @@
use linkify::LinkFinder;
use once_cell::sync::Lazy;
use sqlx::{Connection, Executor, PgConnection, PgPool};
use uuid::Uuid;
use wiremock::MockServer;
use zero2prod::{
configuration::{DatabaseSettings, get_configuration},
startup::Application,
@@ -15,26 +17,67 @@ static TRACING: Lazy<()> = Lazy::new(|| {
}
});
pub struct ConfirmationLinks {
pub html: reqwest::Url,
pub text: reqwest::Url,
}
pub struct TestApp {
pub address: String,
pub connection_pool: PgPool,
pub email_server: wiremock::MockServer,
pub port: u16,
}
impl TestApp {
pub fn get_confirmation_links(&self, request: &wiremock::Request) -> ConfirmationLinks {
let body: serde_json::Value = serde_json::from_slice(&request.body).unwrap();
let get_link = |s: &str| {
let links: Vec<_> = LinkFinder::new()
.links(s)
.filter(|l| *l.kind() == linkify::LinkKind::Url)
.collect();
assert_eq!(links.len(), 1);
let raw_link = links[0].as_str();
let mut confirmation_link = reqwest::Url::parse(raw_link).unwrap();
assert_eq!(confirmation_link.host_str().unwrap(), "127.0.0.1");
confirmation_link.set_port(Some(self.port)).unwrap();
confirmation_link
};
let html = get_link(body["html"].as_str().unwrap());
let text = get_link(body["text"].as_str().unwrap());
ConfirmationLinks { html, text }
}
pub async fn spawn() -> Self {
Lazy::force(&TRACING);
let mut configuration = get_configuration().expect("Failed to read configuration");
configuration.database.database_name = Uuid::new_v4().to_string();
configuration.application.port = 0;
let email_server = MockServer::start().await;
let configuration = {
let mut c = get_configuration().expect("Failed to read configuration");
c.database.database_name = Uuid::new_v4().to_string();
c.application.port = 0;
c.email_client.base_url = email_server.uri();
c
};
let connection_pool = configure_database(&configuration.database).await;
let application = Application::build(configuration)
.await
.expect("Failed to build application");
let address = application.address();
let local_addr = application.local_addr();
let port = local_addr
.split(":")
.last()
.unwrap()
.parse::<u16>()
.unwrap();
let address = format!("http://{}", application.local_addr());
let app = TestApp {
address,
connection_pool,
email_server,
port,
};
tokio::spawn(application.run_until_stopped());
@@ -44,7 +87,7 @@ impl TestApp {
pub async fn post_subscriptions(&self, body: String) -> reqwest::Response {
reqwest::Client::new()
.post(format!("http://{}/subscriptions", self.address))
.post(format!("{}/subscriptions", self.address))
.header("Content-Type", "application/x-www-form-urlencoded")
.body(body)
.send()

View File

@@ -1,3 +1,4 @@
mod health_check;
mod helpers;
mod subscriptions;
mod subscriptions_confirm;

View File

@@ -1,21 +1,48 @@
use crate::helpers::TestApp;
use wiremock::{
Mock, ResponseTemplate,
matchers::{method, path},
};
#[tokio::test]
async fn subscribe_returns_a_200_for_valid_form_data() {
let app = TestApp::spawn().await;
let body = "name=alphonse&email=alphonse.paix%40outlook.com";
Mock::given(path("/v1/email"))
.and(method("POST"))
.respond_with(ResponseTemplate::new(200))
.mount(&app.email_server)
.await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com";
let response = app.post_subscriptions(body.into()).await;
assert_eq!(200, response.status().as_u16());
}
#[tokio::test]
async fn subscribe_persists_the_new_subscriber() {
let app = TestApp::spawn().await;
Mock::given(path("/v1/email"))
.and(method("POST"))
.respond_with(ResponseTemplate::new(200))
.mount(&app.email_server)
.await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com";
let response = app.post_subscriptions(body.into()).await;
assert_eq!(200, response.status().as_u16());
let saved = sqlx::query!("SELECT email, name FROM subscriptions")
let saved = sqlx::query!("SELECT email, name, status FROM subscriptions")
.fetch_one(&app.connection_pool)
.await
.expect("Failed to fetch saved subscription");
assert_eq!(saved.email, "alphonse.paix@outlook.com");
assert_eq!(saved.name, "alphonse");
assert_eq!(saved.name, "Alphonse");
assert_eq!(saved.status, "pending_confirmation");
}
#[tokio::test]
@@ -59,3 +86,39 @@ async fn subscribe_returns_a_400_when_fields_are_present_but_invalid() {
);
}
}
#[tokio::test]
async fn subscribe_sends_a_confirmation_email_for_valid_data() {
let app = TestApp::spawn().await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com";
Mock::given(path("v1/email"))
.and(method("POST"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&app.email_server)
.await;
app.post_subscriptions(body.into()).await;
}
#[tokio::test]
async fn subscribe_sends_a_confirmation_email_with_a_link() {
let app = TestApp::spawn().await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com";
Mock::given(path("v1/email"))
.and(method("POST"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&app.email_server)
.await;
app.post_subscriptions(body.into()).await;
let email_request = &app.email_server.received_requests().await.unwrap()[0];
let confirmation_links = app.get_confirmation_links(email_request);
assert_eq!(confirmation_links.html, confirmation_links.text);
}

View File

@@ -0,0 +1,69 @@
use crate::helpers::TestApp;
use wiremock::{
Mock, ResponseTemplate,
matchers::{method, path},
};
#[tokio::test]
async fn confirmation_links_without_token_are_rejected_with_a_400() {
let app = TestApp::spawn().await;
let response = reqwest::get(&format!("{}/subscriptions/confirm", &app.address))
.await
.unwrap();
assert_eq!(400, response.status().as_u16());
}
#[tokio::test]
async fn the_link_returned_by_subscribe_returns_a_200_if_called() {
let app = TestApp::spawn().await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com";
Mock::given(path("v1/email"))
.and(method("POST"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&app.email_server)
.await;
app.post_subscriptions(body.into()).await;
let email_request = &app.email_server.received_requests().await.unwrap()[0];
let confirmation_links = app.get_confirmation_links(email_request);
let response = reqwest::get(confirmation_links.html).await.unwrap();
assert_eq!(response.status().as_u16(), 200);
}
#[tokio::test]
async fn clicking_on_the_confirmation_link_confirms_a_subscriber() {
let app = TestApp::spawn().await;
let body = "name=Alphonse&email=alphonse.paix%40outlook.com";
Mock::given(path("v1/email"))
.and(method("POST"))
.respond_with(ResponseTemplate::new(200))
.expect(1)
.mount(&app.email_server)
.await;
app.post_subscriptions(body.into()).await;
let email_request = &app.email_server.received_requests().await.unwrap()[0];
let confirmation_links = app.get_confirmation_links(email_request);
reqwest::get(confirmation_links.html)
.await
.unwrap()
.error_for_status()
.unwrap();
let saved = sqlx::query!("SELECT email, name, status FROM subscriptions")
.fetch_one(&app.connection_pool)
.await
.expect("Failed to fetch saved subscription");
assert_eq!(saved.email, "alphonse.paix@outlook.com");
assert_eq!(saved.name, "Alphonse");
assert_eq!(saved.status, "confirmed");
}