From f9ae3f42a6240a60d4d03781d140007d17c4a056 Mon Sep 17 00:00:00 2001 From: Alphonse Paix Date: Fri, 26 Sep 2025 20:31:30 +0200 Subject: [PATCH] More tests, not found page and dashboard fixes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When post was deleted, website shows a 404 page insead of an 500 page. Also made the dashboard empty page message more explicit. --- src/routes.rs | 9 ++-- src/routes/admin/posts.rs | 25 ++++++++++- src/routes/posts.rs | 48 +++++++++++++-------- src/startup.rs | 3 +- src/templates.rs | 17 +++++++- templates/dashboard.html | 2 +- tests/api/admin_dashboard.rs | 25 ++++++++++- tests/api/change_password.rs | 22 ++-------- tests/api/helpers.rs | 47 +++++++++++++++++++- tests/api/posts.rs | 83 ++++++++++++++++++++++++++++++++++++ 10 files changed, 233 insertions(+), 48 deletions(-) diff --git a/src/routes.rs b/src/routes.rs index f6757e7..b269bd3 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -25,7 +25,7 @@ pub use unsubscribe::*; use crate::{ authentication::AuthError, - templates::{InternalErrorTemplate, MessageTemplate, NotFoundTemplate}, + templates::{HtmlTemplate, InternalErrorTemplate, MessageTemplate, NotFoundTemplate}, }; pub fn generate_token() -> String { @@ -155,9 +155,6 @@ impl From for AppError { } pub async fn not_found() -> Response { - ( - StatusCode::NOT_FOUND, - Html(NotFoundTemplate.render().unwrap()), - ) - .into_response() + let template = HtmlTemplate(NotFoundTemplate); + (StatusCode::NOT_FOUND, template).into_response() } diff --git a/src/routes/admin/posts.rs b/src/routes/admin/posts.rs index 1e12adc..a7f676d 100644 --- a/src/routes/admin/posts.rs +++ b/src/routes/admin/posts.rs @@ -9,7 +9,7 @@ use anyhow::Context; use askama::Template; use axum::{ Extension, Form, - extract::State, + extract::{Path, State}, response::{Html, IntoResponse, Response}, }; use chrono::Utc; @@ -121,3 +121,26 @@ pub async fn create_newsletter( }; insert_newsletter_issue(transaction, post_title, &template).await } + +pub async fn delete_post( + State(AppState { + connection_pool, .. + }): State, + Path(post_id): Path, +) -> Result { + let res = sqlx::query!("DELETE FROM posts WHERE post_id = $1", post_id) + .execute(&connection_pool) + .await + .context("Failed to delete post from database.") + .map_err(AppError::unexpected_message)?; + if res.rows_affected() > 1 { + Err(AppError::unexpected_message(anyhow::anyhow!( + "We could not find the post in the database." + ))) + } else { + let template = MessageTemplate::Success { + message: "The subscriber has been deleted.".into(), + }; + Ok(template.render().unwrap().into_response()) + } +} diff --git a/src/routes/posts.rs b/src/routes/posts.rs index 48d0eb6..422fc92 100644 --- a/src/routes/posts.rs +++ b/src/routes/posts.rs @@ -1,8 +1,8 @@ use crate::{ domain::PostEntry, - routes::AppError, + routes::{AppError, not_found}, startup::AppState, - templates::{PostListTemplate, PostTemplate, PostsTemplate}, + templates::{HtmlTemplate, PostListTemplate, PostTemplate, PostsTemplate}, }; use anyhow::Context; use askama::Template; @@ -75,27 +75,41 @@ pub async fn see_post( Query(PostParams { origin }): Query, ) -> Result { if let Some(origin) = origin { - sqlx::query!( - "UPDATE notifications_delivered SET opened = TRUE WHERE email_id = $1", - origin, - ) - .execute(&connection_pool) - .await - .context("Failed to mark email as opened.") - .map_err(AppError::unexpected_page)?; + mark_email_as_opened(&connection_pool, origin).await?; return Ok(Redirect::to(&format!("/posts/{}", post_id)).into_response()); } - let post = get_post_data(&connection_pool, post_id) + + if let Some(post) = get_post_data(&connection_pool, post_id) .await .context(format!("Failed to fetch post #{}", post_id)) .map_err(AppError::unexpected_page)? - .to_html() - .context("Could not render markdown with extension.")?; - let template = PostTemplate { post }; - Ok(Html(template.render().unwrap()).into_response()) + { + let post = post + .to_html() + .context("Could not render markdown with extension.")?; + let template = HtmlTemplate(PostTemplate { post }); + Ok(template.into_response()) + } else { + Ok(not_found().await) + } } -async fn get_post_data(connection_pool: &PgPool, post_id: Uuid) -> Result { +async fn mark_email_as_opened(connection_pool: &PgPool, email_id: Uuid) -> Result<(), AppError> { + sqlx::query!( + "UPDATE notifications_delivered SET opened = TRUE WHERE email_id = $1", + email_id, + ) + .execute(connection_pool) + .await + .context("Failed to mark email as opened.") + .map_err(AppError::unexpected_page)?; + Ok(()) +} + +async fn get_post_data( + connection_pool: &PgPool, + post_id: Uuid, +) -> Result, sqlx::Error> { sqlx::query_as!( PostEntry, r#" @@ -106,7 +120,7 @@ async fn get_post_data(connection_pool: &PgPool, post_id: Uuid) -> Result(pub T); + +impl IntoResponse for HtmlTemplate +where + T: Template, +{ + fn into_response(self) -> axum::response::Response { + match self.0.render() { + Ok(html) => Html(html).into_response(), + Err(err) => AppError::unexpected_page(anyhow::anyhow!(err)).into_response(), + } + } +} + #[derive(Template)] pub enum MessageTemplate { #[template(path = "../templates/success.html")] diff --git a/templates/dashboard.html b/templates/dashboard.html index 157ab95..d934b6f 100644 --- a/templates/dashboard.html +++ b/templates/dashboard.html @@ -122,7 +122,7 @@

No data available

-

Content may have shifted due to recent updates.

+

Content may have shifted due to recent updates or list is empty.

{% else %} {% for subscriber in subscribers %} diff --git a/tests/api/admin_dashboard.rs b/tests/api/admin_dashboard.rs index a46adad..474aa6b 100644 --- a/tests/api/admin_dashboard.rs +++ b/tests/api/admin_dashboard.rs @@ -25,9 +25,32 @@ async fn logout_clears_session_state(connection_pool: PgPool) { assert!(html_page.contains("Connected as")); assert!(html_page.contains(&app.test_user.username)); - let response = app.post_logout().await; + let response = app.logout().await; assert_is_redirect_to(&response, "/login"); let response = app.get_admin_dashboard().await; assert_is_redirect_to(&response, "/login"); } + +#[sqlx::test] +async fn subscribers_are_visible_on_the_dashboard(connection_pool: PgPool) { + let app = TestApp::spawn(connection_pool).await; + app.admin_login().await; + + let response = app.get_admin_dashboard_html().await; + assert!(response.contains("No data available")); + + app.create_confirmed_subscriber().await; + let subscriber = sqlx::query!("SELECT id, email FROM subscriptions") + .fetch_one(&app.connection_pool) + .await + .unwrap(); + + let response = app.get_admin_dashboard_html().await; + assert!(response.contains(&subscriber.email)); + + app.delete_subscriber(subscriber.id).await; + let response = app.get_admin_dashboard_html().await; + assert!(response.contains("No data available")); + assert!(!response.contains(&subscriber.email)); +} diff --git a/tests/api/change_password.rs b/tests/api/change_password.rs index bdbd7f2..5ab97d5 100644 --- a/tests/api/change_password.rs +++ b/tests/api/change_password.rs @@ -22,11 +22,7 @@ async fn you_must_be_logged_in_to_change_your_password(connection_pool: PgPool) async fn new_password_fields_must_match(connection_pool: PgPool) { let app = TestApp::spawn(connection_pool).await; - app.post_login(&serde_json::json!({ - "username": app.test_user.username, - "password": app.test_user.password, - })) - .await; + app.admin_login().await; let new_password = Uuid::new_v4().to_string(); let another_new_password = Uuid::new_v4().to_string(); @@ -47,11 +43,7 @@ async fn new_password_fields_must_match(connection_pool: PgPool) { async fn current_password_is_invalid(connection_pool: PgPool) { let app = TestApp::spawn(connection_pool).await; - app.post_login(&serde_json::json!({ - "username": app.test_user.username, - "password": app.test_user.password, - })) - .await; + app.admin_login().await; let new_password = Uuid::new_v4().to_string(); let response = app @@ -70,13 +62,7 @@ async fn current_password_is_invalid(connection_pool: PgPool) { #[sqlx::test] async fn changing_password_works(connection_pool: PgPool) { let app = TestApp::spawn(connection_pool).await; - - let login_body = &serde_json::json!({ - "username": app.test_user.username, - "password": app.test_user.password, - }); - let response = app.post_login(login_body).await; - assert_is_redirect_to(&response, "/admin/dashboard"); + app.admin_login().await; let new_password = Uuid::new_v4().to_string(); let response = app @@ -91,7 +77,7 @@ async fn changing_password_works(connection_pool: PgPool) { let html_page_fragment = response.text().await.unwrap(); assert!(html_page_fragment.contains("Your password has been changed")); - let response = app.post_logout().await; + let response = app.logout().await; assert_is_redirect_to(&response, "/login"); let login_body = &serde_json::json!({ diff --git a/tests/api/helpers.rs b/tests/api/helpers.rs index 842007f..11c3d23 100644 --- a/tests/api/helpers.rs +++ b/tests/api/helpers.rs @@ -160,6 +160,17 @@ impl TestApp { .unwrap(); } + pub async fn delete_subscriber(&self, subscriber_id: Uuid) { + self.api_client + .delete(format!( + "{}/admin/subscribers/{}", + self.address, subscriber_id + )) + .send() + .await + .expect("Could not delete subscriber"); + } + pub async fn dispatch_all_pending_emails(&self) { loop { if let ExecutionOutcome::EmptyQueue = @@ -228,6 +239,30 @@ impl TestApp { self.get_admin_dashboard().await.text().await.unwrap() } + pub async fn get_posts(&self) -> reqwest::Response { + self.api_client + .get(format!("{}/posts", &self.address)) + .send() + .await + .expect("Failed to execute request") + } + + pub async fn get_posts_html(&self) -> String { + self.get_posts().await.text().await.unwrap() + } + + pub async fn get_post(&self, post_id: Uuid) -> reqwest::Response { + self.api_client + .get(format!("{}/posts/{}", &self.address, post_id)) + .send() + .await + .expect("Failed to execute request") + } + + pub async fn get_post_html(&self, post_id: Uuid) -> String { + self.get_post(post_id).await.text().await.unwrap() + } + pub async fn post_subscriptions(&self, body: String) -> reqwest::Response { self.api_client .post(format!("{}/subscriptions", self.address)) @@ -270,9 +305,9 @@ impl TestApp { self.post_login(&login_body).await; } - pub async fn post_logout(&self) -> reqwest::Response { + pub async fn logout(&self) -> reqwest::Response { self.api_client - .post(format!("{}/admin/logout", self.address)) + .get(format!("{}/admin/logout", self.address)) .send() .await .expect("Failed to execute request") @@ -302,6 +337,14 @@ impl TestApp { .expect("Failed to execute request") } + pub async fn delete_post(&self, post_id: Uuid) { + self.api_client + .delete(format!("{}/admin/posts/{}", self.address, post_id)) + .send() + .await + .expect("Could not delete post"); + } + pub async fn post_unsubscribe(&self, body: &Body) -> reqwest::Response where Body: serde::Serialize, diff --git a/tests/api/posts.rs b/tests/api/posts.rs index 3ae4dee..e6b81ed 100644 --- a/tests/api/posts.rs +++ b/tests/api/posts.rs @@ -82,3 +82,86 @@ async fn confirmed_subscribers_are_notified_when_a_new_post_is_published(connect app.dispatch_all_pending_emails().await; } + +#[sqlx::test] +async fn new_posts_are_visible_on_the_website(connection_pool: PgPool) { + let app = TestApp::spawn(connection_pool).await; + + let html = app.get_posts_html().await; + assert!(html.contains("No posts yet")); + + let title = subject(); + let content = content(); + let body = serde_json::json!({ + "title": title, + "content": content, + "idempotency_key": Uuid::new_v4(), + + }); + app.admin_login().await; + app.post_create_post(&body).await; + + app.logout().await; + let html = app.get_posts_html().await; + assert!(html.contains(&title)); + + let post = sqlx::query!("SELECT post_id FROM posts") + .fetch_one(&app.connection_pool) + .await + .unwrap(); + let html = app.get_post_html(post.post_id).await; + assert!(html.contains(&title)); +} + +#[sqlx::test] +async fn visitor_can_read_a_blog_post(connection_pool: PgPool) { + let app = TestApp::spawn(connection_pool).await; + + let title = subject(); + let content = content(); + let body = serde_json::json!({ + "title": title, + "content": content, + "idempotency_key": Uuid::new_v4(), + + }); + app.admin_login().await; + app.post_create_post(&body).await; + app.logout().await; + + let html = app.get_posts_html().await; + assert!(html.contains(&title)); + + let post = sqlx::query!("SELECT post_id FROM posts") + .fetch_one(&app.connection_pool) + .await + .unwrap(); + let html = app.get_post_html(post.post_id).await; + assert!(html.contains(&title)); +} + +#[sqlx::test] +async fn a_deleted_blog_post_returns_404(connection_pool: PgPool) { + let app = TestApp::spawn(connection_pool).await; + app.admin_login().await; + + let title = subject(); + let content = content(); + let body = serde_json::json!({ + "title": title, + "content": content, + "idempotency_key": Uuid::new_v4(), + + }); + app.post_create_post(&body).await; + + let post = sqlx::query!("SELECT post_id FROM posts") + .fetch_one(&app.connection_pool) + .await + .unwrap(); + + app.delete_post(post.post_id).await; + + let html = app.get_post_html(post.post_id).await; + assert!(html.contains("Not Found")); +}