Files
main-site/apps/core/tests/test_message_handling.py
Claude ff587d9e1b
All checks were successful
CI / nightly-e2e (pull_request) Has been skipped
CI / deploy (pull_request) Has been skipped
CI / ci (pull_request) Successful in 1m25s
CI / pr-e2e (pull_request) Successful in 1m24s
Fix server-rendered admin messages never auto-dismissing
Root cause: Wagtail's w-messages Stimulus controller only auto-clears
messages added dynamically via JavaScript (the add() method).  Server-
rendered messages — the <li> elements produced by Django's messages
framework after a redirect — have no connect() lifecycle handler and
sit in the DOM indefinitely.

PR #64 added data-w-messages-auto-clear-value="8000" which correctly
handles dynamic messages, but server-rendered ones were unaffected.
PR #64 also added {% ifchanged %} for de-duplication, which doesn't
address persistence.

Fix: mark server-rendered <li> elements with data-server-rendered and
add an inline script that removes them after 8 seconds (matching the
auto-clear timeout for dynamic messages).  Also remove the ineffective
{% ifchanged %} de-duplication.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-19 10:55:30 +00:00

121 lines
4.3 KiB
Python

from __future__ import annotations
import pytest
from django.contrib import messages
from django.contrib.auth.models import AnonymousUser
from django.contrib.messages import get_messages
from django.contrib.messages.storage.fallback import FallbackStorage
from django.contrib.sessions.middleware import SessionMiddleware
from django.http import HttpResponse
from django.shortcuts import render
from django.test import RequestFactory, override_settings
from django.urls import include, path
from apps.core.middleware import AdminMessageGuardMiddleware
def admin_message_test_view(request):
messages.success(request, "Page 'Test page' has been updated.")
messages.success(request, "Page 'Test page' has been published.")
return render(request, "wagtailadmin/base.html", {})
urlpatterns = [
path("cms/__tests__/admin-messages/", admin_message_test_view),
path("", include("config.urls")),
]
def _build_request(rf: RequestFactory, path: str):
request = rf.get(path)
SessionMiddleware(lambda req: None).process_request(request)
request.session.save()
request.user = AnonymousUser()
setattr(request, "_messages", FallbackStorage(request))
return request
@pytest.mark.django_db
def test_admin_message_guard_clears_stale_messages_on_frontend(rf):
request = _build_request(rf, "/articles/test/")
messages.success(request, "Page 'Test page' has been updated.")
response = AdminMessageGuardMiddleware(lambda req: HttpResponse("ok"))(request)
assert response.status_code == 200
assert list(get_messages(request)) == []
@pytest.mark.django_db
def test_admin_message_guard_preserves_admin_messages(rf):
request = _build_request(rf, "/cms/pages/1/edit/")
messages.success(request, "Page 'Test page' has been updated.")
response = AdminMessageGuardMiddleware(lambda req: HttpResponse("ok"))(request)
remaining = list(get_messages(request))
assert response.status_code == 200
assert len(remaining) == 1
assert remaining[0].message == "Page 'Test page' has been updated."
@pytest.mark.django_db
@override_settings(ROOT_URLCONF="apps.core.tests.test_message_handling")
def test_admin_messages_have_auto_clear(client, django_user_model):
"""The messages container must set auto-clear so messages dismiss themselves."""
admin = django_user_model.objects.create_superuser(
username="admin-autoclear",
email="admin-autoclear@example.com",
password="admin-pass",
)
client.force_login(admin)
response = client.get("/cms/__tests__/admin-messages/")
content = response.content.decode()
assert response.status_code == 200
assert "data-w-messages-auto-clear-value" in content
@pytest.mark.django_db
@override_settings(ROOT_URLCONF="apps.core.tests.test_message_handling")
def test_server_rendered_messages_have_auto_dismiss_script(client, django_user_model):
"""Server-rendered messages must include an inline script that removes them
after a timeout, because the w-messages Stimulus controller only auto-clears
messages added via JavaScript — not ones already in the HTML."""
admin = django_user_model.objects.create_superuser(
username="admin-dismiss",
email="admin-dismiss@example.com",
password="admin-pass",
)
client.force_login(admin)
response = client.get("/cms/__tests__/admin-messages/")
content = response.content.decode()
assert response.status_code == 200
# Messages are rendered with the data-server-rendered marker
assert "data-server-rendered" in content
# The auto-dismiss script targets those markers
assert "querySelectorAll" in content
assert "[data-server-rendered]" in content
@pytest.mark.django_db
@override_settings(ROOT_URLCONF="apps.core.tests.test_message_handling")
def test_admin_messages_render_all_messages(client, django_user_model):
"""All messages should be rendered (no de-duplication filtering)."""
admin = django_user_model.objects.create_superuser(
username="admin-render",
email="admin-render@example.com",
password="admin-pass",
)
client.force_login(admin)
response = client.get("/cms/__tests__/admin-messages/")
content = response.content.decode()
assert response.status_code == 200
assert "has been updated." in content
assert "has been published." in content