feat: v2.21.0 paging for homepage, likes and admin dashboard
The homepage showed only the 20 newest notes and /likes the 50 newest, with no way back. The admin dashboard paged list_notes()'s default 50 newest, so it always said 'Page 1 of 2'. All three now count with count_notes() and fetch one page with limit/offset. Public pages get '<- Newer / Page N of M / Older ->' with rel=prev/next (h-feed paging), ?page=1 redirects to the bare URL, bad pages 404; the dashboard falls back to the nearest valid page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9074c9a08c
commit
615354d17e
11 files changed
+373
-60
No files matched your search
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
## [2.21.0] - 2026-11-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- The homepage pages through every note: 20 per page, with "← Newer" and "Older →" links and "Page N of M" at the bottom. Before, it showed only the 20 newest notes and older ones could only be found through tags, search or the feeds. Page 1 stays at `/`; later pages are `/?page=2` and on (`/?page=1` redirects to `/`), and their title starts "Page N ·". The links carry `rel="prev"`/`rel="next"`, so IndieWeb readers can page back through the h-feed
|
||||||
|
- The Likes page pages the same way, 50 per page (it showed only the 50 newest likes)
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- The admin dashboard only ever listed the 50 newest notes ("Page 1 of 2" whatever the real count), because it paged the default 50-note result of `list_notes()`. It now counts all notes and fetches just the requested page. A bad `?page=` no longer raises a server error; it goes to the nearest valid page
|
||||||
|
- Public list pages answer a page number that isn't a positive whole number, or is past the last page, with 404
|
||||||
|
|
||||||
## [2.20.3] - 2026-11-27
|
## [2.20.3] - 2026-11-27
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# v2.21.0: Paging for the homepage, likes and admin dashboard
|
||||||
|
|
||||||
|
## Why
|
||||||
|
|
||||||
|
The production site has 141 notes (140 published), but:
|
||||||
|
|
||||||
|
| Page | Showed | Cause |
|
||||||
|
|---|---|---|
|
||||||
|
| Homepage `/` | the 20 newest | `list_notes(..., limit=20)`, no paging |
|
||||||
|
| `/likes` | the 50 newest likes | `list_notes(..., limit=50)`, no paging |
|
||||||
|
| Admin dashboard | the 50 newest, as "Page 1 of 2" | it paged the result of `list_notes()`, whose default `limit` is 50 (since v1.6.0) |
|
||||||
|
|
||||||
|
So 120 published notes couldn't be reached from the homepage, and 91 notes
|
||||||
|
couldn't be reached from the admin list.
|
||||||
|
|
||||||
|
## How the homepage displays it
|
||||||
|
|
||||||
|
- The same note previews as before, 20 per page, newest first. Likes stay on
|
||||||
|
`/likes`, drafts are never shown.
|
||||||
|
- Below the last note: `← Newer` · `Page 2 of 7` · `Older →`. Page 1 has no
|
||||||
|
"Newer" link, the last page has no "Older" link, and a site with one page
|
||||||
|
of notes shows no pager at all.
|
||||||
|
- URLs: page 1 is `/` (and `/?page=1` redirects there with a 301). Later
|
||||||
|
pages are `/?page=N`. Their browser title is `Page N · <site name>`.
|
||||||
|
- `/likes` works the same way with 50 per page (`Likes · Page N · …`).
|
||||||
|
- The links are `<a rel="prev">` / `<a rel="next">` inside the h-feed, so
|
||||||
|
IndieWeb readers and Microsub clients can page back through the feed.
|
||||||
|
- A page number that isn't a positive whole number, or is past the last
|
||||||
|
page, is a 404.
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
|
||||||
|
| Area | Change |
|
||||||
|
|---|---|
|
||||||
|
| `notes.count_notes(published_only, likes)` | New. `SELECT COUNT(*)` with the same filters as `list_notes()` (shared `_list_filters()`) |
|
||||||
|
| `routes/public.py` | `_paged_notes()` parses `?page=`, counts, and fetches one page with `limit`/`offset`. `_prepare_for_listing()` attaches media, tags, contexts and response counts (was duplicated in `index` and `likes`). `HOME_PER_PAGE = 20`, `LIKES_PER_PAGE = 50` |
|
||||||
|
| `templates/partials/pager.html` | `pager(endpoint, page, total_pages)` macro, used by `index.html` and `likes.html` |
|
||||||
|
| `routes/admin.py` dashboard | Counts with `count_notes()` and fetches only the requested 25. A bad or out-of-range `?page=` goes to the nearest valid page (admin only, so no 404) |
|
||||||
|
| `static/css/style.css` | `.pager` row: newer on the left, position in the middle, older on the right |
|
||||||
|
|
||||||
|
Feeds (RSS, Atom, JSON) are unchanged: they list the newest items only.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
`tests/test_paging.py`:
|
||||||
|
- `count_notes` filters;
|
||||||
|
- homepage first, middle and last pages, with `rel` links and titles;
|
||||||
|
- every published note reachable exactly once;
|
||||||
|
- drafts and likes never listed;
|
||||||
|
- the `?page=1` redirect;
|
||||||
|
- 404 for bad and out-of-range pages;
|
||||||
|
- no pager when there's a single page, and an empty site;
|
||||||
|
- likes page 2;
|
||||||
|
- the admin dashboard past 50 notes, including drafts, with bad-page
|
||||||
|
fallback.
|
||||||
@@ -484,5 +484,5 @@ def create_app(config=None):
|
|||||||
|
|
||||||
# Package version (Semantic Versioning 2.0.0)
|
# Package version (Semantic Versioning 2.0.0)
|
||||||
# See docs/standards/versioning-strategy.md for details
|
# See docs/standards/versioning-strategy.md for details
|
||||||
__version__ = "2.20.3"
|
__version__ = "2.21.0"
|
||||||
__version_info__ = (2, 20, 3)
|
__version_info__ = (2, 21, 0)
|
||||||
+26
-12
@@ -519,6 +519,30 @@ def get_note(
|
|||||||
return note
|
return note
|
||||||
|
|
||||||
|
|
||||||
|
def _list_filters(published_only: bool, likes: Optional[bool]) -> tuple[str, list]:
|
||||||
|
"""WHERE clause shared by list_notes() and count_notes()"""
|
||||||
|
where = "deleted_at IS NULL"
|
||||||
|
if published_only:
|
||||||
|
where += " AND published = 1"
|
||||||
|
# likes: None = all notes, False = leave likes out, True = only likes (v2.5.0)
|
||||||
|
if likes is True:
|
||||||
|
where += " AND like_of IS NOT NULL"
|
||||||
|
elif likes is False:
|
||||||
|
where += " AND like_of IS NULL"
|
||||||
|
return where, []
|
||||||
|
|
||||||
|
|
||||||
|
def count_notes(published_only: bool = False, likes: Optional[bool] = None) -> int:
|
||||||
|
"""
|
||||||
|
Number of notes list_notes() would return with no limit (v2.21.0)
|
||||||
|
|
||||||
|
Same filters as list_notes(); used to work out page counts.
|
||||||
|
"""
|
||||||
|
where, params = _list_filters(published_only, likes)
|
||||||
|
db = get_db(current_app)
|
||||||
|
return db.execute(f"SELECT COUNT(*) FROM notes WHERE {where}", params).fetchone()[0]
|
||||||
|
|
||||||
|
|
||||||
def list_notes(
|
def list_notes(
|
||||||
published_only: bool = False,
|
published_only: bool = False,
|
||||||
limit: int = 50,
|
limit: int = 50,
|
||||||
@@ -611,18 +635,8 @@ def list_notes(
|
|||||||
raise ValueError("Offset must be >= 0")
|
raise ValueError("Offset must be >= 0")
|
||||||
|
|
||||||
# 2. BUILD QUERY
|
# 2. BUILD QUERY
|
||||||
# Start with base query
|
where, params = _list_filters(published_only, likes)
|
||||||
query = "SELECT * FROM notes WHERE deleted_at IS NULL"
|
query = f"SELECT * FROM notes WHERE {where}"
|
||||||
|
|
||||||
# Add filters
|
|
||||||
params = []
|
|
||||||
if published_only:
|
|
||||||
query += " AND published = 1"
|
|
||||||
# likes: None = all notes, False = leave likes out, True = only likes (v2.5.0)
|
|
||||||
if likes is True:
|
|
||||||
query += " AND like_of IS NOT NULL"
|
|
||||||
elif likes is False:
|
|
||||||
query += " AND like_of IS NULL"
|
|
||||||
|
|
||||||
# Add ordering (safe because order_by validated above)
|
# Add ordering (safe because order_by validated above)
|
||||||
query += f" ORDER BY {order_by} {order_dir}"
|
query += f" ORDER BY {order_by} {order_dir}"
|
||||||
|
|||||||
+10
-12
@@ -14,6 +14,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
from starpunk.auth import require_auth
|
from starpunk.auth import require_auth
|
||||||
from starpunk.notes import (
|
from starpunk.notes import (
|
||||||
|
count_notes,
|
||||||
create_note,
|
create_note,
|
||||||
delete_note,
|
delete_note,
|
||||||
list_notes,
|
list_notes,
|
||||||
@@ -60,21 +61,18 @@ def dashboard():
|
|||||||
from flask import current_app
|
from flask import current_app
|
||||||
import math
|
import math
|
||||||
|
|
||||||
# Get pagination params (v1.6.0)
|
# Pagination (v1.6.0). Until v2.21.0 this paged list_notes()'s default
|
||||||
page = int(request.args.get('page', 1))
|
# 50 newest notes, so older notes never showed; now it counts all notes
|
||||||
|
# and fetches only the requested page. A bad ?page= falls back to the
|
||||||
|
# nearest valid page instead of a server error.
|
||||||
per_page = 25
|
per_page = 25
|
||||||
|
total_notes = count_notes()
|
||||||
# Get all notes (published and drafts)
|
|
||||||
all_notes = list_notes()
|
|
||||||
|
|
||||||
# Calculate pagination
|
|
||||||
total_notes = len(all_notes)
|
|
||||||
total_pages = math.ceil(total_notes / per_page) if total_notes > 0 else 1
|
total_pages = math.ceil(total_notes / per_page) if total_notes > 0 else 1
|
||||||
|
raw_page = request.args.get('page', '1')
|
||||||
|
page = int(raw_page) if raw_page.isdigit() else 1
|
||||||
|
page = min(max(page, 1), total_pages)
|
||||||
|
|
||||||
# Slice for current page
|
notes = list_notes(limit=per_page, offset=(page - 1) * per_page)
|
||||||
start_idx = (page - 1) * per_page
|
|
||||||
end_idx = start_idx + per_page
|
|
||||||
notes = all_notes[start_idx:end_idx]
|
|
||||||
|
|
||||||
# Get pending webmention count (v1.6.0)
|
# Get pending webmention count (v1.6.0)
|
||||||
webmention_pending_count = 0
|
webmention_pending_count = 0
|
||||||
|
|||||||
+57
-32
@@ -10,7 +10,7 @@ from datetime import datetime, timedelta, timezone
|
|||||||
|
|
||||||
from flask import Blueprint, abort, redirect, render_template, Response, current_app, request, send_from_directory, url_for
|
from flask import Blueprint, abort, redirect, render_template, Response, current_app, request, send_from_directory, url_for
|
||||||
|
|
||||||
from starpunk.notes import list_notes, get_note
|
from starpunk.notes import count_notes, list_notes, get_note
|
||||||
from starpunk.websub import embed_hub
|
from starpunk.websub import embed_hub
|
||||||
from starpunk.feed import generate_feed_streaming # Legacy RSS
|
from starpunk.feed import generate_feed_streaming # Legacy RSS
|
||||||
from starpunk.feeds import (
|
from starpunk.feeds import (
|
||||||
@@ -279,36 +279,65 @@ def preview(name: str):
|
|||||||
return response
|
return response
|
||||||
|
|
||||||
|
|
||||||
@bp.route("/")
|
HOME_PER_PAGE = 20
|
||||||
def index():
|
LIKES_PER_PAGE = 50
|
||||||
"""
|
|
||||||
Homepage displaying recent published notes with media
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Rendered homepage template with note list including media
|
|
||||||
|
|
||||||
Template: templates/index.html
|
def _paged_notes(endpoint: str, per_page: int, likes: bool):
|
||||||
Microformats: h-feed containing h-entry items with u-photo
|
|
||||||
"""
|
"""
|
||||||
|
Published notes for the requested ?page= of a public list (v2.21.0)
|
||||||
|
|
||||||
|
Returns (notes, page, total_pages), or a redirect Response for ?page=1
|
||||||
|
(page 1 lives at the bare URL). A page that isn't a positive whole
|
||||||
|
number, or is past the last page, is a 404.
|
||||||
|
"""
|
||||||
|
raw = request.args.get("page")
|
||||||
|
if raw is None:
|
||||||
|
page = 1
|
||||||
|
elif not raw.isdigit() or int(raw) < 1:
|
||||||
|
abort(404)
|
||||||
|
else:
|
||||||
|
page = int(raw)
|
||||||
|
if page == 1:
|
||||||
|
return redirect(url_for(endpoint), code=301)
|
||||||
|
total = count_notes(published_only=True, likes=likes)
|
||||||
|
total_pages = max(1, -(-total // per_page))
|
||||||
|
if page > total_pages:
|
||||||
|
abort(404)
|
||||||
|
notes = list_notes(published_only=True, limit=per_page,
|
||||||
|
offset=(page - 1) * per_page, likes=likes)
|
||||||
|
return notes, page, total_pages
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare_for_listing(notes) -> None:
|
||||||
|
"""Media, tags, contexts and response counts for listed notes"""
|
||||||
from starpunk.media import get_note_media
|
from starpunk.media import get_note_media
|
||||||
from starpunk.tags import get_note_tags
|
from starpunk.tags import get_note_tags
|
||||||
|
|
||||||
# Get recent published notes (limit 20); likes have their own page (v2.5.0)
|
|
||||||
notes = list_notes(published_only=True, limit=20, likes=False)
|
|
||||||
|
|
||||||
# Attach media and tags to each note for display
|
|
||||||
for note in notes:
|
for note in notes:
|
||||||
media = get_note_media(note.id)
|
|
||||||
# Use object.__setattr__ since Note is frozen dataclass
|
# Use object.__setattr__ since Note is frozen dataclass
|
||||||
object.__setattr__(note, 'media', media)
|
object.__setattr__(note, 'media', get_note_media(note.id))
|
||||||
|
object.__setattr__(note, '_cached_tags', get_note_tags(note.id))
|
||||||
# Attach tags (v1.3.0 Phase 3)
|
|
||||||
tags = get_note_tags(note.id)
|
|
||||||
object.__setattr__(note, '_cached_tags', tags)
|
|
||||||
|
|
||||||
attach_contexts(notes)
|
attach_contexts(notes)
|
||||||
attach_response_counts(notes)
|
attach_response_counts(notes)
|
||||||
return render_template("index.html", notes=notes)
|
|
||||||
|
|
||||||
|
@bp.route("/")
|
||||||
|
def index():
|
||||||
|
"""
|
||||||
|
Homepage: published notes, newest first, 20 per page (paged in v2.21.0)
|
||||||
|
|
||||||
|
Likes have their own page (v2.5.0). Older notes are at /?page=2 and on.
|
||||||
|
|
||||||
|
Template: templates/index.html
|
||||||
|
Microformats: h-feed containing h-entry items, with rel=prev/next paging
|
||||||
|
"""
|
||||||
|
result = _paged_notes("public.index", HOME_PER_PAGE, likes=False)
|
||||||
|
if not isinstance(result, tuple): # redirect for ?page=1
|
||||||
|
return result
|
||||||
|
notes, page, total_pages = result
|
||||||
|
_prepare_for_listing(notes)
|
||||||
|
return render_template("index.html", notes=notes, page=page, total_pages=total_pages)
|
||||||
|
|
||||||
|
|
||||||
def attach_response_counts(notes) -> None:
|
def attach_response_counts(notes) -> None:
|
||||||
@@ -341,17 +370,13 @@ def attach_contexts(notes) -> None:
|
|||||||
|
|
||||||
@bp.route("/likes")
|
@bp.route("/likes")
|
||||||
def likes():
|
def likes():
|
||||||
"""Likes, kept off the home page and feeds (v2.5.0)"""
|
"""Likes, kept off the home page and feeds (v2.5.0); paged in v2.21.0"""
|
||||||
from starpunk.media import get_note_media
|
result = _paged_notes("public.likes", LIKES_PER_PAGE, likes=True)
|
||||||
from starpunk.tags import get_note_tags
|
if not isinstance(result, tuple): # redirect for ?page=1
|
||||||
|
return result
|
||||||
notes = list_notes(published_only=True, limit=50, likes=True)
|
notes, page, total_pages = result
|
||||||
for note in notes:
|
_prepare_for_listing(notes)
|
||||||
object.__setattr__(note, 'media', get_note_media(note.id))
|
return render_template("likes.html", notes=notes, page=page, total_pages=total_pages)
|
||||||
object.__setattr__(note, '_cached_tags', get_note_tags(note.id))
|
|
||||||
attach_contexts(notes)
|
|
||||||
attach_response_counts(notes)
|
|
||||||
return render_template("likes.html", notes=notes)
|
|
||||||
|
|
||||||
|
|
||||||
def _note_was_deleted(slug: str) -> bool:
|
def _note_was_deleted(slug: str) -> bool:
|
||||||
|
|||||||
@@ -130,6 +130,10 @@ main { flex: 1; margin-bottom: var(--spacing-xl); }
|
|||||||
.note-tags .p-category::before { content: "#"; opacity: 0.7; }
|
.note-tags .p-category::before { content: "#"; opacity: 0.7; }
|
||||||
.h-entry:not(.note-preview) .note-meta { margin-top: var(--spacing-md); }
|
.h-entry:not(.note-preview) .note-meta { margin-top: var(--spacing-md); }
|
||||||
.note-nav { margin-top: var(--spacing-lg); font-size: 0.9375rem; }
|
.note-nav { margin-top: var(--spacing-lg); font-size: 0.9375rem; }
|
||||||
|
.pager { display: flex; justify-content: space-between; align-items: center; gap: var(--spacing-md); margin-top: var(--spacing-lg); font-size: 0.9375rem; }
|
||||||
|
.pager-position { color: var(--color-text-light); margin: 0 auto; }
|
||||||
|
.pager [rel="next"] { margin-left: auto; }
|
||||||
|
.pager [rel="prev"] + .pager-position { margin-left: auto; }
|
||||||
.empty-state { text-align: center; padding: var(--spacing-xl); color: var(--color-text-light); }
|
.empty-state { text-align: center; padding: var(--spacing-xl); color: var(--color-text-light); }
|
||||||
|
|
||||||
.form-group { margin-bottom: var(--spacing-md); }
|
.form-group { margin-bottom: var(--spacing-md); }
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% from "partials/note_preview.html" import note_preview %}
|
{% from "partials/note_preview.html" import note_preview %}
|
||||||
|
{% from "partials/pager.html" import pager %}
|
||||||
|
|
||||||
{% block title %}{{ config.SITE_NAME }}{% endblock %}
|
{% block title %}{% if page and page > 1 %}Page {{ page }} · {% endif %}{{ config.SITE_NAME }}{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="h-feed">
|
<div class="h-feed">
|
||||||
@@ -39,5 +40,7 @@
|
|||||||
{% else %}
|
{% else %}
|
||||||
<p class="empty-state">No notes published yet. Check back soon!</p>
|
<p class="empty-state">No notes published yet. Check back soon!</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
{{ pager('public.index', page, total_pages) }}
|
||||||
</div>
|
</div>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -1,7 +1,8 @@
|
|||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% from "partials/note_preview.html" import note_preview %}
|
{% from "partials/note_preview.html" import note_preview %}
|
||||||
|
{% from "partials/pager.html" import pager %}
|
||||||
|
|
||||||
{% block title %}Likes · {{ config.SITE_NAME }}{% endblock %}
|
{% block title %}Likes · {% if page and page > 1 %}Page {{ page }} · {% endif %}{{ config.SITE_NAME }}{% endblock %}
|
||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="h-feed">
|
<div class="h-feed">
|
||||||
@@ -21,6 +22,8 @@
|
|||||||
<p class="empty-state">Nothing liked yet.</p>
|
<p class="empty-state">Nothing liked yet.</p>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|
||||||
|
{{ pager('public.likes', page, total_pages) }}
|
||||||
|
|
||||||
<nav class="note-nav">
|
<nav class="note-nav">
|
||||||
<a href="/">← All notes</a>
|
<a href="/">← All notes</a>
|
||||||
</nav>
|
</nav>
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
{# Newer/older links for paged public lists (v2.21.0). Page 1 is the bare
|
||||||
|
URL. rel=prev/next let IndieWeb readers page through the h-feed. #}
|
||||||
|
{% macro pager(endpoint, page, total_pages) %}
|
||||||
|
{% if total_pages > 1 %}
|
||||||
|
<nav class="pager" aria-label="More notes">
|
||||||
|
{% if page > 1 %}
|
||||||
|
<a rel="prev" href="{{ url_for(endpoint, page=page - 1) if page > 2 else url_for(endpoint) }}">← Newer</a>
|
||||||
|
{% endif %}
|
||||||
|
<span class="pager-position">Page {{ page }} of {{ total_pages }}</span>
|
||||||
|
{% if page < total_pages %}
|
||||||
|
<a rel="next" href="{{ url_for(endpoint, page=page + 1) }}">Older →</a>
|
||||||
|
{% endif %}
|
||||||
|
</nav>
|
||||||
|
{% endif %}
|
||||||
|
{% endmacro %}
|
||||||
@@ -0,0 +1,184 @@
|
|||||||
|
"""
|
||||||
|
Paging of the homepage, likes page and admin dashboard (v2.21.0)
|
||||||
|
|
||||||
|
Before v2.21.0 the homepage showed only the 20 newest notes, the likes page
|
||||||
|
the 50 newest likes, and the admin dashboard paged list_notes()'s default
|
||||||
|
50 newest notes, so older notes were unreachable from all three.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
from datetime import datetime, timedelta, timezone
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from starpunk import create_app
|
||||||
|
from starpunk.auth import create_session
|
||||||
|
from starpunk.notes import count_notes, create_note
|
||||||
|
|
||||||
|
START = datetime(2026, 1, 1, tzinfo=timezone.utc)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def app(tmp_path):
|
||||||
|
data = tmp_path / "data"
|
||||||
|
data.mkdir(parents=True, exist_ok=True)
|
||||||
|
return create_app(config={
|
||||||
|
"TESTING": True,
|
||||||
|
"DATABASE_PATH": data / "starpunk.db",
|
||||||
|
"DATA_PATH": data,
|
||||||
|
"NOTES_PATH": data / "notes",
|
||||||
|
"SESSION_SECRET": "test-secret-key",
|
||||||
|
"ADMIN_ME": "https://test.example.com",
|
||||||
|
"SITE_URL": "http://localhost:5000",
|
||||||
|
"SITE_NAME": "Test Site",
|
||||||
|
"DEV_MODE": False,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(app):
|
||||||
|
return app.test_client()
|
||||||
|
|
||||||
|
|
||||||
|
def make_notes(app, published=0, drafts=0, likes=0):
|
||||||
|
"""Notes one minute apart, oldest first; content says which is which"""
|
||||||
|
n = 0
|
||||||
|
with app.app_context():
|
||||||
|
for i in range(published):
|
||||||
|
create_note(content=f"Published note {i:03d}", published=True,
|
||||||
|
created_at=START + timedelta(minutes=n))
|
||||||
|
n += 1
|
||||||
|
for i in range(drafts):
|
||||||
|
create_note(content=f"Draft note {i:03d}", published=False,
|
||||||
|
created_at=START + timedelta(minutes=n))
|
||||||
|
n += 1
|
||||||
|
for i in range(likes):
|
||||||
|
create_note(content=f"Liked thing {i:03d}", published=True,
|
||||||
|
like_of=f"https://example.com/liked/{i}",
|
||||||
|
created_at=START + timedelta(minutes=n))
|
||||||
|
n += 1
|
||||||
|
|
||||||
|
|
||||||
|
def shown(html, prefix):
|
||||||
|
return sorted(set(re.findall(rf"{prefix} (\d{{3}})", html)))
|
||||||
|
|
||||||
|
|
||||||
|
def rel_link(html, rel):
|
||||||
|
m = re.search(rf'<a rel="{rel}" href="([^"]+)"', html)
|
||||||
|
return m.group(1) if m else None
|
||||||
|
|
||||||
|
|
||||||
|
class TestCountNotes:
|
||||||
|
def test_count_matches_filters(self, app):
|
||||||
|
make_notes(app, published=7, drafts=3, likes=4)
|
||||||
|
with app.app_context():
|
||||||
|
assert count_notes() == 14
|
||||||
|
assert count_notes(published_only=True) == 11
|
||||||
|
assert count_notes(published_only=True, likes=False) == 7
|
||||||
|
assert count_notes(published_only=True, likes=True) == 4
|
||||||
|
|
||||||
|
|
||||||
|
class TestHomepagePaging:
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def notes(self, app):
|
||||||
|
# 45 published notes = 3 pages of 20; drafts and likes stay off
|
||||||
|
make_notes(app, published=45, drafts=2, likes=3)
|
||||||
|
|
||||||
|
def test_first_page_is_newest_20(self, client):
|
||||||
|
html = client.get("/").get_data(as_text=True)
|
||||||
|
assert shown(html, "Published note") == [f"{i:03d}" for i in range(25, 45)]
|
||||||
|
assert "Page 1 of 3" in html
|
||||||
|
assert rel_link(html, "prev") is None
|
||||||
|
assert rel_link(html, "next") == "/?page=2"
|
||||||
|
|
||||||
|
def test_middle_page_links_both_ways(self, client):
|
||||||
|
html = client.get("/?page=2").get_data(as_text=True)
|
||||||
|
assert shown(html, "Published note") == [f"{i:03d}" for i in range(5, 25)]
|
||||||
|
# page 1 is the bare URL
|
||||||
|
assert rel_link(html, "prev") == "/"
|
||||||
|
assert rel_link(html, "next") == "/?page=3"
|
||||||
|
assert "<title>Page 2 · Test Site</title>" in html
|
||||||
|
|
||||||
|
def test_last_page_has_the_oldest(self, client):
|
||||||
|
html = client.get("/?page=3").get_data(as_text=True)
|
||||||
|
assert shown(html, "Published note") == [f"{i:03d}" for i in range(0, 5)]
|
||||||
|
assert rel_link(html, "next") is None
|
||||||
|
assert rel_link(html, "prev") == "/?page=2"
|
||||||
|
|
||||||
|
def test_every_published_note_reachable_once(self, client):
|
||||||
|
seen = []
|
||||||
|
for p in ("/", "/?page=2", "/?page=3"):
|
||||||
|
seen += re.findall(r"Published note (\d{3})", client.get(p).get_data(as_text=True))
|
||||||
|
assert sorted(set(seen)) == [f"{i:03d}" for i in range(45)]
|
||||||
|
|
||||||
|
def test_drafts_and_likes_never_listed(self, client):
|
||||||
|
for p in ("/", "/?page=2", "/?page=3"):
|
||||||
|
html = client.get(p).get_data(as_text=True)
|
||||||
|
assert "Draft note" not in html
|
||||||
|
assert "Liked thing" not in html
|
||||||
|
|
||||||
|
def test_page_one_redirects_to_bare_url(self, client):
|
||||||
|
r = client.get("/?page=1")
|
||||||
|
assert r.status_code == 301
|
||||||
|
assert r.headers["Location"].endswith("/")
|
||||||
|
assert "page=" not in r.headers["Location"]
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("page", ["4", "0", "-1", "abc", "2.5", ""])
|
||||||
|
def test_bad_or_out_of_range_page_is_404(self, client, page):
|
||||||
|
assert client.get(f"/?page={page}").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
class TestHomepageSmall:
|
||||||
|
def test_no_pager_when_one_page(self, app, client):
|
||||||
|
make_notes(app, published=5)
|
||||||
|
html = client.get("/").get_data(as_text=True)
|
||||||
|
assert 'class="pager"' not in html
|
||||||
|
assert "<title>Test Site</title>" in html
|
||||||
|
|
||||||
|
def test_empty_site_still_renders(self, client):
|
||||||
|
r = client.get("/")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert "No notes published yet" in r.get_data(as_text=True)
|
||||||
|
|
||||||
|
|
||||||
|
class TestLikesPaging:
|
||||||
|
def test_likes_page_two(self, app, client):
|
||||||
|
make_notes(app, published=2, likes=55) # 50 per page
|
||||||
|
first = client.get("/likes").get_data(as_text=True)
|
||||||
|
assert len(shown(first, "Liked thing")) == 50
|
||||||
|
assert rel_link(first, "next") == "/likes?page=2"
|
||||||
|
second = client.get("/likes?page=2").get_data(as_text=True)
|
||||||
|
assert shown(second, "Liked thing") == [f"{i:03d}" for i in range(0, 5)]
|
||||||
|
assert rel_link(second, "prev") == "/likes"
|
||||||
|
assert "Published note" not in first + second
|
||||||
|
assert client.get("/likes?page=3").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
class TestAdminDashboardPaging:
|
||||||
|
@pytest.fixture
|
||||||
|
def admin(self, app, client):
|
||||||
|
with app.test_request_context():
|
||||||
|
token = create_session("https://test.example.com")
|
||||||
|
client.set_cookie("starpunk_session", token)
|
||||||
|
return client
|
||||||
|
|
||||||
|
def test_all_notes_reachable_past_fifty(self, app, admin):
|
||||||
|
# 60 published + 5 drafts = 65 notes = 3 pages of 25
|
||||||
|
make_notes(app, published=60, drafts=5)
|
||||||
|
html = admin.get("/admin/").get_data(as_text=True)
|
||||||
|
assert "Page 1 of 3" in html
|
||||||
|
last = admin.get("/admin/?page=3").get_data(as_text=True)
|
||||||
|
# the 15 oldest notes, which the old 50-note cap hid
|
||||||
|
assert shown(last, "Published note") == [f"{i:03d}" for i in range(0, 15)]
|
||||||
|
|
||||||
|
def test_drafts_listed(self, app, admin):
|
||||||
|
make_notes(app, published=3, drafts=2)
|
||||||
|
assert "Draft note 000" in admin.get("/admin/").get_data(as_text=True)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("page,expected", [("99", "Page 3 of 3"), ("abc", "Page 1 of 3"),
|
||||||
|
("0", "Page 1 of 3")])
|
||||||
|
def test_bad_page_falls_back(self, app, admin, page, expected):
|
||||||
|
make_notes(app, published=60)
|
||||||
|
r = admin.get(f"/admin/?page={page}")
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert expected in r.get_data(as_text=True)
|
||||||
Reference in new issue
Block a user