forked from retoor/devplacepy
Happy 404: an HTML 404 (unmatched route, or an explicit not-found inside a
real route) now renders a random existing post instead of the error page,
using the exact same context builder as a real post view. Toggle is the
happy_404_enabled site setting (default on, /admin/settings); JSON/API
requests and a handful of excluded prefixes are never affected. The pool of
candidate slugs is cached in-process and resampled periodically so it stays
fast and eventually cycles the whole posts table; on any internal failure it
falls straight through to the real 404 page.
Applying this everywhere surfaced ~60 existing tests that asserted a literal
404 for a legitimate resource-not-found flow (deleted post, unknown
container, wrong project slug, etc.) - each now disables the setting for the
duration of that specific check and restores it after, so the underlying
not-found behavior stays covered independently of the new feature.
Post page also gained, all built on the same shared post_page_context() so
they render identically on both a real post and a happy-404 page:
- A left sidebar (three separate cards, matching /feed's sidebar-card
convention) for "Gists from {author}", "Projects from {author}" (private
projects filtered through the normal visibility check), and "Related
Discussions" - each cached per author and invalidated on create/edit/
delete so new content shows up immediately.
- A right column reusing /feed's exact Daily Topic widget class for up to
three "Featured" articles (the existing but previously-unused `featured`
news flag), cached as a pool with per-request random sampling.
- A "Next post -> " link beside "Back to Feed", pointing at the next older
post site-wide (blocked authors skipped). Wired through the same next_url
mechanism already used for listing pagination, so it emits a real
backend-rendered <link rel="next"> tag for SEO, not just a visible link.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BWJy6PrMMt5hwWxQwia2rd
213 lines
6.7 KiB
Python
213 lines
6.7 KiB
Python
# retoor <retoor@molodetz.nl>
|
|
|
|
import time
|
|
import requests
|
|
from tests.conftest import BASE_URL, CACHE_VERSION_PROPAGATION_SECONDS
|
|
from devplacepy.database import set_setting
|
|
|
|
JSON_trash = {"Accept": "application/json"}
|
|
_counter_trash = [0]
|
|
|
|
|
|
def _unique_trash(prefix="tr"):
|
|
_counter_trash[0] += 1
|
|
return f"{prefix}{int(time.time() * 1000)}{_counter_trash[0]}"
|
|
|
|
|
|
def _member_trash():
|
|
name = _unique_trash("trrmem")
|
|
s = requests.Session()
|
|
s.post(
|
|
f"{BASE_URL}/auth/signup",
|
|
data={
|
|
"username": name,
|
|
"email": f"{name}@t.dev",
|
|
"password": "secret123",
|
|
"confirm_password": "secret123",
|
|
"birth_date": "1990-01-01",
|
|
"accept_terms": "1",
|
|
},
|
|
allow_redirects=True,
|
|
)
|
|
return s, name
|
|
|
|
|
|
def _admin_trash(seeded_db):
|
|
s = requests.Session()
|
|
creds = seeded_db["alice"]
|
|
s.post(
|
|
f"{BASE_URL}/auth/login",
|
|
data={"email": creds["email"], "password": creds["password"]},
|
|
allow_redirects=True,
|
|
)
|
|
return s
|
|
|
|
|
|
def _create_post_trash(session):
|
|
return session.post(
|
|
f"{BASE_URL}/posts/create",
|
|
headers=JSON_trash,
|
|
data={"title": _unique_trash("trrp"), "content": "restore post body text", "topic": "devlog"},
|
|
).json()["data"]
|
|
|
|
|
|
def _soft_delete_post_trash(session, slug):
|
|
session.post(f"{BASE_URL}/posts/delete/{slug}", headers=JSON_trash, allow_redirects=False)
|
|
|
|
|
|
def _audit_find(admin, event_key, target_uid):
|
|
data = admin.get(
|
|
f"{BASE_URL}/admin/audit-log", headers=JSON_trash, params={"event_key": event_key}
|
|
).json()
|
|
for entry in data["entries"]:
|
|
if entry.get("target_uid") == target_uid:
|
|
return entry
|
|
return None
|
|
|
|
|
|
def test_restore_requires_admin(seeded_db):
|
|
member, _ = _member_trash()
|
|
r = member.post(
|
|
f"{BASE_URL}/admin/trash/posts/anything/restore", allow_redirects=False
|
|
)
|
|
assert r.status_code in (302, 303)
|
|
|
|
|
|
def test_restore_unknown_table_404(seeded_db):
|
|
admin = _admin_trash(seeded_db)
|
|
r = admin.post(
|
|
f"{BASE_URL}/admin/trash/bogus/anything/restore",
|
|
headers=JSON_trash,
|
|
allow_redirects=False,
|
|
)
|
|
assert r.status_code == 404
|
|
|
|
|
|
def test_restore_revives_post_and_records_audit(seeded_db):
|
|
member, _ = _member_trash()
|
|
post = _create_post_trash(member)
|
|
_soft_delete_post_trash(member, post["slug"])
|
|
admin = _admin_trash(seeded_db)
|
|
|
|
r = admin.post(
|
|
f"{BASE_URL}/admin/trash/posts/{post['uid']}/restore",
|
|
headers=JSON_trash,
|
|
allow_redirects=False,
|
|
)
|
|
assert r.status_code == 200, r.text[:300]
|
|
|
|
# restored row is live again and gone from trash
|
|
trash = admin.get(
|
|
f"{BASE_URL}/admin/trash", headers=JSON_trash, params={"table": "posts"}
|
|
).json()
|
|
assert all(item["uid"] != post["uid"] for item in trash["items"])
|
|
assert member.get(f"{BASE_URL}/posts/{post['slug']}").status_code == 200
|
|
|
|
entry = _audit_find(admin, "admin.trash.restore", post["uid"])
|
|
assert entry is not None
|
|
assert entry["result"] == "success"
|
|
|
|
|
|
def test_restore_revoked_award_recomputes_stats(seeded_db):
|
|
from datetime import datetime, timezone
|
|
from devplacepy.database import get_table
|
|
from devplacepy.database.awards import revoke_award
|
|
from devplacepy.utils import generate_uid, make_combined_slug
|
|
|
|
admin = _admin_trash(seeded_db)
|
|
bob = get_table("users").find_one(username="bob_test")
|
|
alice = get_table("users").find_one(username="alice_test")
|
|
uid = generate_uid()
|
|
slug = make_combined_slug("Trash restore", uid)
|
|
now = datetime.now(timezone.utc).isoformat()
|
|
get_table("awards").insert(
|
|
{
|
|
"uid": uid,
|
|
"slug": slug,
|
|
"description": "Trash restore",
|
|
"giver_uid": alice["uid"],
|
|
"receiver_uid": bob["uid"],
|
|
"attachment_uid_512": "",
|
|
"attachment_uid_256": "",
|
|
"attachment_uid_64": "",
|
|
"generated_at": now,
|
|
"created_at": now,
|
|
"job_uid": "",
|
|
"deleted_at": None,
|
|
"deleted_by": None,
|
|
}
|
|
)
|
|
revoke_award(uid, alice["uid"])
|
|
r = admin.post(
|
|
f"{BASE_URL}/admin/trash/awards/{uid}/restore",
|
|
headers=JSON_trash,
|
|
allow_redirects=False,
|
|
)
|
|
assert r.status_code == 200, r.text[:300]
|
|
row = get_table("users").find_one(uid=bob["uid"])
|
|
assert row.get("award_count") == 1
|
|
assert row.get("last_award_uid") == uid
|
|
set_setting("happy_404_enabled", "0")
|
|
time.sleep(CACHE_VERSION_PROPAGATION_SECONDS)
|
|
try:
|
|
assert requests.get(f"{BASE_URL}/awards/{slug}/256").status_code in (302, 404)
|
|
finally:
|
|
set_setting("happy_404_enabled", "1")
|
|
time.sleep(CACHE_VERSION_PROPAGATION_SECONDS)
|
|
|
|
|
|
def _create_quiz_trash(session):
|
|
slug = session.post(
|
|
f"{BASE_URL}/quizzes/create",
|
|
headers=JSON_trash,
|
|
data={"title": _unique_trash("trrquiz"), "description": "restore quiz body"},
|
|
).json()["data"]["slug"]
|
|
session.post(
|
|
f"{BASE_URL}/quizzes/{slug}/questions",
|
|
headers=JSON_trash,
|
|
data={
|
|
"kind": "single_choice",
|
|
"prompt": "Which journal mode allows concurrent readers?",
|
|
"points": 2,
|
|
"options": "DELETE\nWAL",
|
|
"correct_indexes": "1",
|
|
},
|
|
)
|
|
session.post(f"{BASE_URL}/quizzes/{slug}/publish", headers=JSON_trash)
|
|
return slug
|
|
|
|
|
|
def test_restore_revives_a_quiz_with_its_whole_cascade(seeded_db):
|
|
from devplacepy.database import get_table, refresh_snapshot
|
|
|
|
author, _ = _member_trash()
|
|
player, _ = _member_trash()
|
|
slug = _create_quiz_trash(author)
|
|
player.post(f"{BASE_URL}/quizzes/{slug}/attempts", headers=JSON_trash)
|
|
refresh_snapshot()
|
|
quiz = get_table("quizzes").find_one(slug=slug)
|
|
|
|
author.post(f"{BASE_URL}/quizzes/delete/{slug}", headers=JSON_trash, allow_redirects=False)
|
|
refresh_snapshot()
|
|
stamps = set()
|
|
for table in ("quiz_questions", "quiz_options", "quiz_attempts", "quiz_answers"):
|
|
rows = list(get_table(table).find(quiz_uid=quiz["uid"]))
|
|
assert rows
|
|
for row in rows:
|
|
assert row["deleted_at"]
|
|
stamps.add(row["deleted_at"])
|
|
assert len(stamps) == 1
|
|
|
|
admin = _admin_trash(seeded_db)
|
|
response = admin.post(
|
|
f"{BASE_URL}/admin/trash/quizzes/{quiz['uid']}/restore",
|
|
headers=JSON_trash,
|
|
allow_redirects=False,
|
|
)
|
|
assert response.status_code == 200, response.text[:300]
|
|
|
|
refresh_snapshot()
|
|
for table in ("quiz_questions", "quiz_options", "quiz_attempts", "quiz_answers"):
|
|
assert get_table(table).count(quiz_uid=quiz["uid"], deleted_at=None) > 0
|
|
assert requests.get(f"{BASE_URL}/quizzes/{slug}", headers=JSON_trash).status_code == 200
|