Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ec41aa7979 | ||
|
|
18d667db74 | ||
|
|
c87de892cf | ||
|
|
615354d17e |
No files matched your search
@@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [2.21.1] - 2026-11-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- Animated GIFs were stored as just their first frame, so they showed as still images. Upload optimization now keeps every frame and its timing. Animated GIFs also no longer get resized variants (thumb/small/medium/large), which would have been stills too; feeds and crossposts use the animated original. GIFs uploaded before this release stay still; upload them again
|
||||
|
||||
## [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
|
||||
|
||||
### 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.
|
||||
@@ -0,0 +1,23 @@
|
||||
# v2.21.1: Animated GIF uploads stay animated
|
||||
|
||||
## Why
|
||||
|
||||
https://starpunk.thesatelliteoflove.com/note/20261128164646 showed its GIF as
|
||||
a still image. The stored file had one frame, but still carried the loop
|
||||
extension and a 150 ms frame duration, so it had been animated when uploaded.
|
||||
|
||||
`optimize_image()` notices animated GIFs so it can skip resizing, then
|
||||
re-serialized them with `img.save(output, format='GIF')`. Without
|
||||
`save_all=True` Pillow writes only the current frame. The one test for this,
|
||||
`test_gif_animation_preserved`, used a single-frame GIF, so it couldn't catch it.
|
||||
|
||||
## Changes
|
||||
|
||||
| Area | Change |
|
||||
|---|---|
|
||||
| `media.optimize_image` | Animated GIFs are saved with `save_all=True`: every frame, per-frame durations and the loop count are kept |
|
||||
| `media.save_media` | Animated GIFs get no thumb/small/medium/large variants. Those would be stills of the first frame, and syndication sends the `large` variant when there is one. With no variants, feeds and syndication use the original, as they already do for pre-v1.4.0 media |
|
||||
| Tests | `test_gif_animation_preserved` uses a real 3-frame GIF with different durations; `test_save_animated_gif_stays_animated` checks the stored file and that no variants are made |
|
||||
|
||||
Animated GIFs uploaded earlier are already stored as one frame and can't be
|
||||
recovered. Upload them again to fix them.
|
||||
@@ -484,5 +484,5 @@ def create_app(config=None):
|
||||
|
||||
# Package version (Semantic Versioning 2.0.0)
|
||||
# See docs/standards/versioning-strategy.md for details
|
||||
__version__ = "2.20.3"
|
||||
__version_info__ = (2, 20, 3)
|
||||
__version__ = "2.21.1"
|
||||
__version_info__ = (2, 21, 1)
|
||||
+9
-2
@@ -316,10 +316,11 @@ def optimize_image(
|
||||
if original_format != 'GIF':
|
||||
img = ImageOps.exif_transpose(img)
|
||||
|
||||
# For animated GIFs, serialize and return (already validated in validate_image)
|
||||
# For animated GIFs, serialize every frame and return (already validated in
|
||||
# validate_image). Without save_all Pillow writes only the first frame (v2.21.1)
|
||||
if original_format == 'GIF' and getattr(img, 'is_animated', False):
|
||||
output = io.BytesIO()
|
||||
img.save(output, format='GIF')
|
||||
img.save(output, format='GIF', save_all=True)
|
||||
return img, img.size[0], img.size[1], output.getvalue()
|
||||
|
||||
# Iterative optimization loop
|
||||
@@ -687,6 +688,12 @@ def save_media(file_data: bytes, filename: str) -> Dict:
|
||||
temp_original_path.write_bytes(optimized_bytes)
|
||||
|
||||
# Step 2: Generate variants to temp directory
|
||||
# Animated GIFs get none (v2.21.1): a resized variant would be a
|
||||
# still of the first frame, and feeds and syndication fall back to
|
||||
# the original when a media item has no variants
|
||||
if getattr(optimized_img, 'is_animated', False):
|
||||
variant_metadata, file_moves = [], []
|
||||
else:
|
||||
variant_metadata, file_moves = generate_all_variants(
|
||||
optimized_img,
|
||||
full_dir,
|
||||
|
||||
+26
-12
@@ -519,6 +519,30 @@ def get_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(
|
||||
published_only: bool = False,
|
||||
limit: int = 50,
|
||||
@@ -611,18 +635,8 @@ def list_notes(
|
||||
raise ValueError("Offset must be >= 0")
|
||||
|
||||
# 2. BUILD QUERY
|
||||
# Start with base query
|
||||
query = "SELECT * FROM notes WHERE deleted_at IS NULL"
|
||||
|
||||
# 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"
|
||||
where, params = _list_filters(published_only, likes)
|
||||
query = f"SELECT * FROM notes WHERE {where}"
|
||||
|
||||
# Add ordering (safe because order_by validated above)
|
||||
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.notes import (
|
||||
count_notes,
|
||||
create_note,
|
||||
delete_note,
|
||||
list_notes,
|
||||
@@ -60,21 +61,18 @@ def dashboard():
|
||||
from flask import current_app
|
||||
import math
|
||||
|
||||
# Get pagination params (v1.6.0)
|
||||
page = int(request.args.get('page', 1))
|
||||
# Pagination (v1.6.0). Until v2.21.0 this paged list_notes()'s default
|
||||
# 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
|
||||
|
||||
# Get all notes (published and drafts)
|
||||
all_notes = list_notes()
|
||||
|
||||
# Calculate pagination
|
||||
total_notes = len(all_notes)
|
||||
total_notes = count_notes()
|
||||
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
|
||||
start_idx = (page - 1) * per_page
|
||||
end_idx = start_idx + per_page
|
||||
notes = all_notes[start_idx:end_idx]
|
||||
notes = list_notes(limit=per_page, offset=(page - 1) * per_page)
|
||||
|
||||
# Get pending webmention count (v1.6.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 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.feed import generate_feed_streaming # Legacy RSS
|
||||
from starpunk.feeds import (
|
||||
@@ -279,36 +279,65 @@ def preview(name: str):
|
||||
return response
|
||||
|
||||
|
||||
@bp.route("/")
|
||||
def index():
|
||||
"""
|
||||
Homepage displaying recent published notes with media
|
||||
HOME_PER_PAGE = 20
|
||||
LIKES_PER_PAGE = 50
|
||||
|
||||
Returns:
|
||||
Rendered homepage template with note list including media
|
||||
|
||||
Template: templates/index.html
|
||||
Microformats: h-feed containing h-entry items with u-photo
|
||||
def _paged_notes(endpoint: str, per_page: int, likes: bool):
|
||||
"""
|
||||
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.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:
|
||||
media = get_note_media(note.id)
|
||||
# Use object.__setattr__ since Note is frozen dataclass
|
||||
object.__setattr__(note, 'media', media)
|
||||
|
||||
# Attach tags (v1.3.0 Phase 3)
|
||||
tags = get_note_tags(note.id)
|
||||
object.__setattr__(note, '_cached_tags', tags)
|
||||
|
||||
object.__setattr__(note, 'media', get_note_media(note.id))
|
||||
object.__setattr__(note, '_cached_tags', get_note_tags(note.id))
|
||||
attach_contexts(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:
|
||||
@@ -341,17 +370,13 @@ def attach_contexts(notes) -> None:
|
||||
|
||||
@bp.route("/likes")
|
||||
def likes():
|
||||
"""Likes, kept off the home page and feeds (v2.5.0)"""
|
||||
from starpunk.media import get_note_media
|
||||
from starpunk.tags import get_note_tags
|
||||
|
||||
notes = list_notes(published_only=True, limit=50, likes=True)
|
||||
for note in notes:
|
||||
object.__setattr__(note, 'media', get_note_media(note.id))
|
||||
object.__setattr__(note, '_cached_tags', get_note_tags(note.id))
|
||||
attach_contexts(notes)
|
||||
attach_response_counts(notes)
|
||||
return render_template("likes.html", notes=notes)
|
||||
"""Likes, kept off the home page and feeds (v2.5.0); paged in v2.21.0"""
|
||||
result = _paged_notes("public.likes", LIKES_PER_PAGE, likes=True)
|
||||
if not isinstance(result, tuple): # redirect for ?page=1
|
||||
return result
|
||||
notes, page, total_pages = result
|
||||
_prepare_for_listing(notes)
|
||||
return render_template("likes.html", notes=notes, page=page, total_pages=total_pages)
|
||||
|
||||
|
||||
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; }
|
||||
.h-entry:not(.note-preview) .note-meta { margin-top: var(--spacing-md); }
|
||||
.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); }
|
||||
|
||||
.form-group { margin-bottom: var(--spacing-md); }
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
{% extends "base.html" %}
|
||||
{% 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 %}
|
||||
<div class="h-feed">
|
||||
@@ -39,5 +40,7 @@
|
||||
{% else %}
|
||||
<p class="empty-state">No notes published yet. Check back soon!</p>
|
||||
{% endif %}
|
||||
|
||||
{{ pager('public.index', page, total_pages) }}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -1,7 +1,8 @@
|
||||
{% extends "base.html" %}
|
||||
{% 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 %}
|
||||
<div class="h-feed">
|
||||
@@ -21,6 +22,8 @@
|
||||
<p class="empty-state">Nothing liked yet.</p>
|
||||
{% endif %}
|
||||
|
||||
{{ pager('public.likes', page, total_pages) }}
|
||||
|
||||
<nav class="note-nav">
|
||||
<a href="/">← All notes</a>
|
||||
</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 %}
|
||||
@@ -47,6 +47,15 @@ def create_test_image(width=800, height=600, format='PNG'):
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def create_animated_gif(width=244, height=134):
|
||||
"""A looping 3-frame GIF with a different duration per frame"""
|
||||
frames = [Image.new('RGB', (width, height), color=c) for c in ('red', 'green', 'blue')]
|
||||
buffer = io.BytesIO()
|
||||
frames[0].save(buffer, format='GIF', save_all=True, append_images=frames[1:],
|
||||
duration=[100, 200, 300], loop=0)
|
||||
return buffer.getvalue()
|
||||
|
||||
|
||||
def create_test_heic(width=800, height=600):
|
||||
"""
|
||||
Generate test HEIC image using pillow-heif
|
||||
@@ -339,15 +348,20 @@ class TestImageOptimization:
|
||||
assert optimized_bytes is not None
|
||||
|
||||
def test_gif_animation_preserved(self):
|
||||
"""Test GIF animation preservation (per Q12)"""
|
||||
# For v1.2.0: Just verify GIF is handled without error
|
||||
# Full animation preservation is complex
|
||||
gif_data = create_test_image(800, 600, 'GIF')
|
||||
optimized, width, height, optimized_bytes = optimize_image(gif_data)
|
||||
"""Every frame, its timing and the loop survive optimization (v2.21.1)"""
|
||||
gif_data = create_animated_gif()
|
||||
img, _, _, _ = validate_image(gif_data, 'anim.gif')
|
||||
optimized, width, height, optimized_bytes = optimize_image(img, len(gif_data))
|
||||
|
||||
assert width > 0
|
||||
assert height > 0
|
||||
assert optimized_bytes is not None
|
||||
assert (width, height) == (244, 134)
|
||||
out = Image.open(io.BytesIO(optimized_bytes))
|
||||
assert out.n_frames == 3
|
||||
assert out.info['loop'] == 0
|
||||
durations = []
|
||||
for i in range(out.n_frames):
|
||||
out.seek(i)
|
||||
durations.append(out.info['duration'])
|
||||
assert durations == [100, 200, 300]
|
||||
|
||||
|
||||
class TestMediaSave:
|
||||
@@ -371,6 +385,19 @@ class TestMediaSave:
|
||||
media_path = Path(app.config['DATA_PATH']) / 'media' / media_info['path']
|
||||
assert media_path.exists()
|
||||
|
||||
def test_save_animated_gif_stays_animated(self, app):
|
||||
"""The stored GIF keeps every frame, and no still variants are made (v2.21.1)"""
|
||||
gif_data = create_animated_gif(1400, 800) # wide enough for every variant size
|
||||
|
||||
with app.app_context():
|
||||
media_info = save_media(gif_data, 'anim.gif')
|
||||
|
||||
media_dir = Path(app.config['DATA_PATH']) / 'media'
|
||||
stored = Image.open(media_dir / media_info['path'])
|
||||
assert stored.n_frames == 3
|
||||
assert media_info['variants'] == []
|
||||
assert not list((media_dir / media_info['path']).parent.glob('*_thumb.gif'))
|
||||
|
||||
def test_uuid_filename(self, app):
|
||||
"""Test UUID-based filename generation (per Q5)"""
|
||||
image_data = create_test_image(800, 600, 'PNG')
|
||||
|
||||
@@ -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