email with token & confirmation works

This commit is contained in:
Andre Heber
2024-02-27 15:21:54 +01:00
parent f4f16d621d
commit fd4ba6ae31
11 changed files with 210 additions and 27 deletions

View File

@ -4,14 +4,21 @@ use uuid::Uuid;
use wiremock::MockServer;
use zero2prod::{configuration::{get_configuration, DatabaseSettings}, startup::{get_connection_pool, Application}, telemetry::{get_subscriber, init_subscriber}};
pub struct ConfirmationLinks {
pub html: String,
pub plain_text: String,
}
pub struct TestApp {
pub address: String,
pub connection_pool: Pool<Postgres>,
pub email_server: MockServer,
pub port: u16,
}
impl TestApp {
pub async fn post_subscriptions(&self, body: String) -> reqwest::Response {
println!("Post Address: {}", &self.address);
reqwest::Client::new()
.post(&format!("{}/subscriptions", &self.address))
.header("Content-Type", "application/x-www-form-urlencoded")
@ -20,6 +27,24 @@ impl TestApp {
.await
.expect("Failed to execute request.")
}
pub fn get_confirmation_links(&self, email_request: &wiremock::Request) -> ConfirmationLinks {
let body: serde_json::Value = serde_json::from_slice(&email_request.body).unwrap();
let get_link = |s: &str| {
let links: Vec<_> = linkify::LinkFinder::new()
.links(s)
.filter(|l| *l.kind() == linkify::LinkKind::Url)
.collect();
assert_eq!(links.len(), 1);
links[0].as_str().to_owned()
};
let html = get_link(body["HtmlBody"].as_str().unwrap());
let plain_text = get_link(body["TextBody"].as_str().unwrap());
ConfirmationLinks { html, plain_text }
}
}
static TRACING: Lazy<()> = Lazy::new(|| {
@ -50,14 +75,16 @@ pub async fn spawn_app() -> TestApp {
configure_database(&config.database).await;
let app = Application::build(config.clone()).await.expect("Failed to build app.");
println!("App built at port: {}", app.port());
let port = app.port();
let address = format!("http://127.0.0.1:{}", app.port());
println!("App Address: {}", address);
let _fut = tokio::spawn(app.run_until_stopped());
TestApp {
address,
connection_pool: get_connection_pool(config.database),
email_server,
port,
}
}

View File

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

View File

@ -114,20 +114,8 @@ async fn subscribe_sends_a_confirmation_email_with_a_link() {
assert_eq!(200, response.status().as_u16());
let email_request = &app.email_server.received_requests().await.unwrap()[0];
let body: serde_json::Value = serde_json::from_slice(&email_request.body).unwrap();
let get_link = |s: &str| {
let links: Vec<_> = linkify::LinkFinder::new()
.links(s)
.filter(|l| *l.kind() == linkify::LinkKind::Url)
.collect();
assert_eq!(links.len(), 1);
links[0].as_str().to_owned()
};
let html_link = get_link(body["HtmlBody"].as_str().unwrap());
let text_link = get_link(body["TextBody"].as_str().unwrap());
let confirmation_links = app.get_confirmation_links(email_request);
// The two links should be identical
assert_eq!(html_link, text_link);
assert_eq!(confirmation_links.html, confirmation_links.plain_text);
}

View File

@ -0,0 +1,46 @@
use reqwest::Url;
use wiremock::{matchers::{method, path}, Mock, ResponseTemplate};
use crate::helpers::spawn_app;
#[tokio::test]
async fn confirmations_without_token_are_rejected_with_a_400() {
let app = spawn_app().await;
let response = reqwest::get(&format!("{}/subscriptions/confirm", app.address)).await.unwrap();
assert_eq!(response.status().as_u16(), 400);
}
#[tokio::test]
async fn the_link_returned_by_subscribe_returns_a_200_if_called() {
let app = spawn_app().await;
Mock::given(path("/email"))
.and(method("POST"))
.respond_with(ResponseTemplate::new(200))
.mount(&app.email_server)
.await;
app.post_subscriptions("name=Andre%20Heber&email=andre.heber%40gmx.net".into()).await;
let email_request = &app.email_server.received_requests().await.unwrap()[0];
let confirmation_links = app.get_confirmation_links(email_request);
let mut confirmation_link = Url::parse(&confirmation_links.html).unwrap();
assert_eq!(confirmation_link.host_str().unwrap(), "127.0.0.1");
confirmation_link.set_port(Some(app.port)).unwrap();
let _response = reqwest::get(confirmation_link)
.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, "andre.heber@gmx.net");
assert_eq!(saved.name, "Andre Heber");
assert_eq!(saved.status, "confirmed");
}