More tests, not found page and dashboard fixes
Some checks failed
Rust / Test (push) Has been cancelled
Rust / Rustfmt (push) Has been cancelled
Rust / Clippy (push) Has been cancelled
Rust / Code coverage (push) Has been cancelled

When post was deleted, website shows a 404 page insead of an 500 page.
Also made the dashboard empty page message more explicit.
This commit is contained in:
Alphonse Paix
2025-09-26 20:31:30 +02:00
parent 0f6b479af9
commit f9ae3f42a6
10 changed files with 233 additions and 48 deletions

View File

@@ -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<AuthError> 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()
}

View File

@@ -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<AppState>,
Path(post_id): Path<Uuid>,
) -> Result<Response, AppError> {
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())
}
}

View File

@@ -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<PostParams>,
) -> Result<Response, AppError> {
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<PostEntry, sqlx::Error> {
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<Option<PostEntry>, sqlx::Error> {
sqlx::query_as!(
PostEntry,
r#"
@@ -106,7 +120,7 @@ async fn get_post_data(connection_pool: &PgPool, post_id: Uuid) -> Result<PostEn
"#,
post_id
)
.fetch_one(connection_pool)
.fetch_optional(connection_pool)
.await
}

View File

@@ -124,7 +124,8 @@ pub fn app(
.route("/password", post(change_password))
.route("/newsletters", post(publish_newsletter))
.route("/posts", post(create_post))
.route("/logout", post(logout))
.route("/posts/{post_id}", delete(delete_post))
.route("/logout", get(logout))
.route("/subscribers", get(get_subscribers_page))
.route("/subscribers/{subscriber_id}", delete(delete_subscriber))
.layer(middleware::from_fn(require_auth));

View File

@@ -1,10 +1,25 @@
use crate::{
domain::{PostEntry, SubscriberEntry},
routes::DashboardStats,
routes::{AppError, DashboardStats},
};
use askama::Template;
use axum::response::{Html, IntoResponse};
use uuid::Uuid;
pub struct HtmlTemplate<T>(pub T);
impl<T> IntoResponse for HtmlTemplate<T>
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")]

View File

@@ -122,7 +122,7 @@
</svg>
</div>
<h3 class="text-lg font-medium text-gray-900 mb-2">No data available</h3>
<p class="text-gray-600 mb-4">Content may have shifted due to recent updates.</p>
<p class="text-gray-600">Content may have shifted due to recent updates or list is empty.</p>
</div>
{% else %}
{% for subscriber in subscribers %}

View File

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

View File

@@ -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!({

View File

@@ -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<Body>(&self, body: &Body) -> reqwest::Response
where
Body: serde::Serialize,

View File

@@ -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"));
}