feat: article titles and summaries stored apart from the text (v2.16.0, ADR-076)

Articles as the IndieWeb defines them: a name separate from the content.

- Migration 023 adds notes.title and notes.summary. A one-time Python data
  step (migrations.DATA_MIGRATIONS) moves each note's '# Heading' first line
  into title, rewrites the file and hash, empties FTS for a rebuild, and puts
  files back if the migration fails. Trashed notes included.
- Micropub: name -> title, summary stored when sent with content, summary
  updatable, q=source returns both. MCP tools take a summary.
- Feeds: titles only for articles (RSS/JSON none, Atom empty); Atom and
  JSON Feed summaries; the title is no longer repeated in the content.
- Pages: p-name/p-summary on the article page. Homepage and tag pages show
  articles as title, summary and "Read more" without images (hidden u-photo
  keeps the post type for parsers).
- Crossposts: articles go out as title, summary, link and hashtags, no
  images; the Bluesky card is the article. Notes unchanged.
- Editor: Title and Summary fields; an article may have no body.
- Fix: a line starting with a hashtag ('#indieweb ...') was rendered as a
  heading and crossposted without its '#' (HashtagLineExtension).
- Fix: excerpts showed raw Markdown; they are plain text now.

Back up the database and the data folder before deploying: the migration
rewrites note files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
PhilandClaude Opus 5.5 committed 2026-11-11 17:05:38 -07:00
1 parent 9a0d82bab2
commit 978c13358b
44 files changed
+943 -356

No files matched your search

+132
View File
@@ -0,0 +1,132 @@
"""
Articles: titles and summaries stored apart from the text (v2.16.0, ADR-076).
Feeds give only articles a title and never repeat it in the content; the
homepage and tag pages show an article as title, summary and "Read more"
without its images; the admin editor has Title and Summary fields.
"""
import json
import xml.etree.ElementTree as ET
import mf2py
from starpunk.auth import create_session
from starpunk.notes import create_note, get_note
from tests.test_micropub_v240 import SITE, app, client, h # noqa: F401
from tests.test_micropub_v265 import upload
ATOM = {"a": "http://www.w3.org/2005/Atom"}
def micropub(client, h, **props):
response = client.post("/micropub", json={"type": ["h-entry"], "properties": props}, headers=h)
assert response.status_code == 201, response.get_json()
return response.headers["Location"]
def make_both(app):
with app.app_context():
article = create_note(content="The **body**.", title="An Article", summary="The gist.",
published=True, tags=["essay"])
note = create_note(content="# Just a heading\n\nin a note", published=True, tags=["essay"])
return article, note
class TestFeeds:
def test_rss_title_only_for_articles(self, app, client):
article, note = make_both(app)
items = {i.find("link").text: i for i in ET.fromstring(client.get("/feed.rss").data).iter("item")}
a, n = items[f"{SITE}/note/{article.slug}"], items[f"{SITE}/note/{note.slug}"]
assert a.find("title").text == "An Article"
assert "An Article" not in a.find("description").text # not repeated in the body
assert n.find("title") is None
assert n.find("description") is not None
def test_atom_empty_title_and_summary(self, app, client):
article, note = make_both(app)
entries = {e.find("a:id", ATOM).text: e
for e in ET.fromstring(client.get("/feed.atom").data).findall("a:entry", ATOM)}
a, n = entries[f"{SITE}/note/{article.slug}"], entries[f"{SITE}/note/{note.slug}"]
assert a.find("a:title", ATOM).text == "An Article"
assert a.find("a:summary", ATOM).text == "The gist."
assert "An Article" not in a.find("a:content", ATOM).text
assert n.find("a:title", ATOM) is not None and not n.find("a:title", ATOM).text
assert n.find("a:summary", ATOM) is None
def test_json_feed(self, app, client):
article, note = make_both(app)
items = {i["url"]: i for i in json.loads(client.get("/feed.json").data)["items"]}
a, n = items[f"{SITE}/note/{article.slug}"], items[f"{SITE}/note/{note.slug}"]
assert (a["title"], a["summary"]) == ("An Article", "The gist.")
assert "An Article" not in a["content_html"]
assert "title" not in n and "summary" not in n
assert "<h1>Just a heading</h1>" in n["content_html"]
class TestPages:
def test_article_page(self, app, client):
article, _ = make_both(app)
(entry,) = [i for i in mf2py.parse(doc=client.get(f"/note/{article.slug}").data.decode(),
url=f"{SITE}/note/{article.slug}")["items"]
if "h-entry" in i["type"]]
props = entry["properties"]
assert props["name"] == ["An Article"]
assert props["summary"] == ["The gist."]
assert not props["content"][0]["value"].startswith("An Article")
def test_homepage_and_tag_page(self, app, client, h):
photo = upload(client, h)
url = micropub(client, h, name=["Trip"], content=["Day one of the trip."], photo=[photo],
category=["essay"])
micropub(client, h, content=["A photo note"], photo=[upload(client, h, "blue")], category=["essay"])
with app.app_context():
slug = url.rsplit("/", 1)[1]
article = get_note(slug=slug)
for path in ("/", "/tag/essay"):
html = client.get(path).data.decode()
start = html.index(f'href="{url}"')
section = html[html.rindex("<article", 0, start):html.index("</article>", start)]
assert "Trip" in section and "Day one of the trip." in section and "Read more" in section
assert "<img" not in section and "e-content" not in section
assert 'class="u-photo"' in section # parsers still see a photo post
assert html.count("<img") >= 1 # the photo note still shows its image
assert article.title == "Trip"
def test_preview_uses_summary_over_excerpt(self, app, client):
make_both(app)
html = client.get("/").data.decode()
assert "The gist." in html and "The <strong>body</strong>." not in html
class TestAdmin:
def login(self, app, client):
with app.test_request_context():
client.set_cookie("starpunk_session", create_session(app.config["ADMIN_ME"]))
def test_create_and_edit_article(self, app, client):
self.login(app, client)
response = client.post("/admin/new", data={
"title": "From the editor", "summary": "Short.", "content": "Body", "published": "on"})
assert response.status_code == 302
with app.app_context():
from starpunk.notes import list_notes
(note,) = list_notes()
assert (note.title, note.summary, note.content) == ("From the editor", "Short.", "Body")
form = client.get(f"/admin/edit/{note.id}").data.decode()
assert 'value="From the editor"' in form and ">Short.</textarea>" in form
client.post(f"/admin/edit/{note.id}", data={"title": "", "summary": "", "content": "Body",
"published": "on"})
with app.app_context():
note = get_note(id=note.id)
assert (note.title, note.summary) == (None, None)
def test_title_only_article(self, app, client):
self.login(app, client)
client.post("/admin/new", data={"title": "Only a title", "content": "", "published": "on"})
with app.app_context():
from starpunk.notes import list_notes
(note,) = list_notes()
assert note.title == "Only a title" and note.content == ""
+15 -29
View File
@@ -55,7 +55,8 @@ def sample_notes(app):
notes = []
for i in range(5):
note = create_note(
content=f"# Test Note {i}\n\nThis is test content for note {i}.",
content=f"This is test content for note {i}.",
title=f"Test Note {i}",
published=True,
)
notes.append(note)
@@ -141,7 +142,8 @@ class TestGenerateFeed:
import time
for i in range(3):
create_note(
content=f"# Note {i}\n\nContent {i}.",
content=f"Content {i}.",
title=f"Note {i}",
published=True,
)
time.sleep(0.01) # Ensure distinct timestamps
@@ -342,41 +344,25 @@ class TestFormatRFC822Date:
class TestGetNoteTitle:
"""Test get_note_title() function"""
def test_get_note_title_with_heading(self, app):
"""Test title extraction from note with heading"""
def test_get_note_title_article(self, app):
"""An article's item title is its title"""
with app.app_context():
note = create_note(content="# My First Note\n\nContent here.", published=True)
title = get_note_title(note)
assert title == "My First Note"
note = create_note(content="Content here.", title="My First Note", published=True)
assert get_note_title(note) == "My First Note"
def test_get_note_title_without_heading(self, app):
"""Test title extraction from note without heading"""
def test_get_note_title_untitled_note(self, app):
"""Untitled notes have no item title (v2.16.0, ADR-076)"""
with app.app_context():
note = create_note(content="Just some content without heading.", published=True)
title = get_note_title(note)
# Should use first line (Note.title handles this)
assert len(title) > 0
assert "Just some content" in title
assert get_note_title(note) is None
note = create_note(content="# A heading in the body\n\nis not a title", published=True)
assert get_note_title(note) is None
def test_get_note_title_truncates_long_titles(self, app):
"""Test title truncation for long titles"""
with app.app_context():
long_title = "A" * 150
note = create_note(content=f"# {long_title}\n\nContent.", published=True)
title = get_note_title(note)
# Should truncate to reasonable length
assert len(title) <= 103 # 100 chars + "..."
def test_get_note_title_minimal_content(self, app):
"""Test title extraction with minimal content"""
with app.app_context():
note = create_note(content="x", published=True)
title = get_note_title(note)
# Should extract something (single character or slug)
assert len(title) > 0
note = create_note(content="Content.", title="A" * 150, published=True)
assert len(get_note_title(note)) <= 103 # 100 chars + "..."
class TestCleanHTMLForRSS:
+4 -4
View File
@@ -49,7 +49,7 @@ def sample_notes(app):
notes = []
for i in range(5):
note = create_note(
content=f"# Test Note {i}\n\nThis is test content for note {i}.",
title=f"Test Note {i}", content=f"This is test content for note {i}.",
published=True,
)
notes.append(note)
@@ -138,7 +138,7 @@ class TestGenerateAtom:
# Create notes with distinct timestamps
for i in range(3):
create_note(
content=f"# Note {i}\n\nContent {i}.",
title=f"Note {i}", content=f"Content {i}.",
published=True,
)
time.sleep(0.01)
@@ -216,7 +216,7 @@ class TestGenerateAtom:
"""Test ATOM feed includes HTML content properly escaped"""
with app.app_context():
note = create_note(
content="# Test\n\nThis is **bold** and *italic*.",
title="Test", content="This is **bold** and *italic*.",
published=True,
)
@@ -243,7 +243,7 @@ class TestGenerateAtom:
"""Test ATOM feed escapes special XML characters"""
with app.app_context():
note = create_note(
content="# Test & Special <Characters>\n\nContent with 'quotes' and \"doubles\".",
title="Test & Special <Characters>", content="Content with 'quotes' and \"doubles\".",
published=True,
)
+3 -3
View File
@@ -49,7 +49,7 @@ def sample_notes(app):
notes = []
for i in range(5):
note = create_note(
content=f"# Test Note {i}\n\nThis is test content for note {i}.",
title=f"Test Note {i}", content=f"This is test content for note {i}.",
published=True,
)
notes.append(note)
@@ -121,7 +121,7 @@ class TestGenerateJsonFeed:
# Create notes with distinct timestamps
for i in range(3):
create_note(
content=f"# Note {i}\n\nContent {i}.",
title=f"Note {i}", content=f"Content {i}.",
published=True,
)
time.sleep(0.01)
@@ -195,7 +195,7 @@ class TestGenerateJsonFeed:
"""Test JSON Feed includes HTML content"""
with app.app_context():
note = create_note(
content="# Test\n\nThis is **bold** and *italic*.",
title="Test", content="This is **bold** and *italic*.",
published=True,
)
+3 -3
View File
@@ -81,7 +81,7 @@ def note_with_single_media(app):
with app.app_context():
# Create note
note = create_note(
content="# Test Note\n\nNote with one image.",
title="Test Note", content="Note with one image.",
published=True
)
@@ -106,7 +106,7 @@ def note_with_multiple_media(app):
with app.app_context():
# Create note
note = create_note(
content="# Gallery Note\n\nNote with three images.",
title="Gallery Note", content="Note with three images.",
published=True
)
@@ -135,7 +135,7 @@ def note_without_media(app):
"""Create note without media"""
with app.app_context():
note = create_note(
content="# Plain Note\n\nNote without images.",
title="Plain Note", content="Note without images.",
published=True
)
notes = list_notes(published_only=True, limit=1)
+4 -3
View File
@@ -57,13 +57,14 @@ class TestNoteHEntry:
assert props['url'][0] == props['uid'][0], "u-url and u-uid should match"
def test_hentry_pname_only_with_explicit_title(self, client, app, data_dir):
"""p-name only present when note has explicit title (per Q22)"""
"""p-name only present when note has a title (ADR-076, was Q22)"""
from starpunk.notes import create_note
# Create note WITH heading (explicit title)
# Create note WITH a title (an article)
with app.app_context():
note_with_title = create_note(
content="# Explicit Title\n\nThis note has a heading.",
content="This note has a title.",
title="Explicit Title",
custom_slug="note-with-title",
published=True
)
+2 -1
View File
@@ -142,7 +142,8 @@ def test_split_title(content, title):
@pytest.mark.parametrize("content,kind", [
("#indieweb is great, posting from my phone", "note"),
("#\n\nbody text", "note"),
("# A Title\n\nThe body", "article"),
# A heading in the text is no longer a title (v2.16.0, ADR-076)
("# A Title\n\nThe body", "note"),
])
def test_post_type_of_hash_notes(app, client, content, kind):
note = make_note(app, content)
+4 -3
View File
@@ -167,11 +167,11 @@ def test_micropub_create_with_name(client, app, mock_valid_token):
assert response.status_code == 201
assert 'Location' in response.headers
# StarPunk titles are a '# Heading' first line, so name must land there
# name is stored as the title, apart from the content (v2.16.0, ADR-076)
slug = response.headers['Location'].rstrip('/').split('/')[-1]
with app.app_context():
note = get_note(slug)
assert note.content == '# My Test Title\n\nContent goes here'
assert note.content == 'Content goes here'
assert note.title == 'My Test Title'
@@ -193,7 +193,8 @@ def test_micropub_create_with_name_already_heading(client, app, mock_valid_token
assert response.status_code == 201
slug = response.headers['Location'].rstrip('/').split('/')[-1]
with app.app_context():
assert get_note(slug).content == '# Same Title\n\nBody'
note = get_note(slug)
assert (note.title, note.content) == ('Same Title', 'Body')
def test_micropub_create_with_categories(client, app, mock_valid_token):
+21 -1
View File
@@ -114,9 +114,29 @@ class TestUpdate:
def test_replace_and_delete_name(self, app, client, h):
url = create(client, h)
self.update(client, h, url, replace={"name": ["Added"]})
assert note_at(app, url).content.startswith("# Added")
note = note_at(app, url)
assert note.title == "Added" and not note.content.startswith("#")
self.update(client, h, url, delete=["name"])
assert "name" not in source(client, h, url)["properties"]
assert note_at(app, url).title is None
def test_summary(self, app, client, h):
"""summary is stored alongside content, updatable and returned by q=source (v2.16.0)"""
url = create(client, h, name=["Title"], summary=["Short version"])
props = source(client, h, url)["properties"]
assert props["summary"] == ["Short version"] and props["name"] == ["Title"]
assert self.update(client, h, url, replace={"summary": ["Shorter"]}).status_code == 204
assert note_at(app, url).summary == "Shorter"
assert self.update(client, h, url, delete=["summary"]).status_code == 204
assert "summary" not in source(client, h, url)["properties"]
def test_article_body_may_go(self, app, client, h):
"""A titled post may have no text, like a photo post (v2.16.0)"""
url = create(client, h, name=["Only a title"])
assert self.update(client, h, url, delete=["content"]).status_code == 204
assert note_at(app, url).content == ""
url = create(client, h)
assert self.update(client, h, url, delete=["content"]).status_code == 400
def test_categories(self, app, client, h):
url = create(client, h, category=["one", "two"])
+127
View File
@@ -0,0 +1,127 @@
"""
Migration 023 moves '# Heading' titles out of note files into notes.title (v2.16.0, ADR-076).
Starts from a fully migrated database, takes it back to before 023, then
runs the migrations again with the data directory.
"""
import sqlite3
import pytest
from starpunk import create_app
from starpunk.migrations import MigrationError, run_migrations
from starpunk.utils import calculate_content_hash
MIGRATION = "023_note_titles.sql"
TITLED = "# Old Title\n\nThe body."
@pytest.fixture
def setup(tmp_path):
data = tmp_path / "data"
data.mkdir()
db_path = data / "starpunk.db"
create_app(config={"TESTING": True, "DATABASE_PATH": db_path, "DATA_PATH": data,
"SESSION_SECRET": "x", "ADMIN_ME": "https://example.com",
"SITE_URL": "https://blog.example.com"})
files = {
"titled": ("notes/2026/11/titled.md", TITLED, None),
"untitled": ("notes/2026/11/untitled.md", "#indieweb is great", None),
"trashed": ("notes/2026/10/trashed.md", "# Gone\n\nBin.", "2026-11-01"),
}
conn = sqlite3.connect(db_path)
for slug, (rel, text, deleted_at) in files.items():
path = data / rel
if deleted_at: # delete_note_file put it in .trash/<year>/<month>/
path = data / ".trash" / "2026" / "10" / "trashed.md"
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
conn.execute(
"INSERT INTO notes (slug, file_path, published, created_at, updated_at, deleted_at,"
" content_hash) VALUES (?, ?, 1, '2026-11-01', '2026-11-01', ?, ?)",
(slug, rel, deleted_at, calculate_content_hash(text)),
)
conn.execute("INSERT INTO notes_fts (rowid, slug, title, content) VALUES (1, 'titled', 'x', 'y')")
# Back to before migration 023
conn.execute("ALTER TABLE notes DROP COLUMN title")
conn.execute("ALTER TABLE notes DROP COLUMN summary")
conn.execute("DELETE FROM schema_migrations WHERE migration_name = ?", (MIGRATION,))
conn.commit()
conn.close()
return db_path, data
def notes(db_path):
conn = sqlite3.connect(db_path)
conn.row_factory = sqlite3.Row
rows = {r["slug"]: dict(r) for r in conn.execute("SELECT * FROM notes")}
conn.close()
return rows
def test_titles_move_out_of_files(setup):
db_path, data = setup
run_migrations(db_path, data_dir=data)
rows = notes(db_path)
assert rows["titled"]["title"] == "Old Title"
assert (data / "notes/2026/11/titled.md").read_text() == "The body."
assert rows["titled"]["content_hash"] == calculate_content_hash("The body.")
assert rows["untitled"]["title"] is None # a hashtag isn't a heading
assert (data / "notes/2026/11/untitled.md").read_text() == "#indieweb is great"
assert rows["trashed"]["title"] == "Gone" # found in .trash, so undelete still works
assert (data / ".trash/2026/10/trashed.md").read_text() == "Bin."
conn = sqlite3.connect(db_path)
assert conn.execute("SELECT COUNT(*) FROM notes_fts").fetchone()[0] == 0 # rebuilt at startup
assert conn.execute("SELECT 1 FROM schema_migrations WHERE migration_name = ?",
(MIGRATION,)).fetchone()
conn.close()
def test_runs_once(setup):
"""Afterwards a heading in a note's text is just a heading"""
db_path, data = setup
run_migrations(db_path, data_dir=data)
(data / "notes/2026/11/untitled.md").write_text("# Now a heading\n\nNew text")
run_migrations(db_path, data_dir=data)
assert notes(db_path)["untitled"]["title"] is None
assert (data / "notes/2026/11/untitled.md").read_text() == "# Now a heading\n\nNew text"
def test_failure_puts_files_back(setup, monkeypatch):
db_path, data = setup
import starpunk.utils as utils
real_write = utils.write_note_file
written = []
def write_then_fail(path, content):
if written:
raise OSError("disk full")
written.append(path)
real_write(path, content)
monkeypatch.setattr(utils, "write_note_file", write_then_fail)
with pytest.raises(MigrationError):
run_migrations(db_path, data_dir=data)
assert written # one file was changed before the failure...
assert (data / "notes/2026/11/titled.md").read_text() == TITLED # ...and put back
assert (data / ".trash/2026/10/trashed.md").read_text() == "# Gone\n\nBin."
conn = sqlite3.connect(db_path)
assert not conn.execute("SELECT 1 FROM schema_migrations WHERE migration_name = ?",
(MIGRATION,)).fetchone()
assert "title" not in [r[1] for r in conn.execute("PRAGMA table_info(notes)")]
conn.close()
def test_without_data_dir_only_schema(setup):
db_path, data = setup
run_migrations(db_path)
assert notes(db_path)["titled"]["title"] is None
assert (data / "notes/2026/11/titled.md").read_text() == TITLED
+34 -48
View File
@@ -11,6 +11,7 @@ Organized by model:
import pytest
from datetime import datetime, timedelta, timezone
from pathlib import Path
from dataclasses import replace
from starpunk.models import Note, Session, Token, AuthState, split_title
from starpunk.utils import calculate_content_hash
@@ -139,13 +140,12 @@ class TestNoteModel:
html2 = note.html
assert html1 == html2
def test_title_extraction_from_heading(self, tmp_path):
"""Test title extraction from markdown heading"""
def test_title_is_the_column_not_the_content(self, tmp_path):
"""A title comes from notes.title; a heading in the content is just a heading (ADR-076)"""
note_file = tmp_path / "notes" / "2024" / "11" / "test.md"
note_file.parent.mkdir(parents=True)
note_file.write_text("# My Note Title\n\nContent.")
note = Note(
note_file.write_text("# A Heading\n\nContent.")
kwargs = dict(
id=1,
slug="test",
file_path="notes/2024/11/test.md",
@@ -154,29 +154,13 @@ class TestNoteModel:
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
_data_dir=tmp_path,
)
assert Note(**kwargs).title is None
assert "<h1>A Heading</h1>" in Note(**kwargs).html
assert Note(**kwargs, title="My Note Title").title == "My Note Title"
assert note.title == "My Note Title"
def test_title_extraction_from_first_line(self, tmp_path):
"""Test title extraction from first line without heading"""
note_file = tmp_path / "notes" / "2024" / "11" / "test.md"
note_file.parent.mkdir(parents=True)
note_file.write_text("Just a note without heading\n\nMore content.")
note = Note(
id=1,
slug="test",
file_path="notes/2024/11/test.md",
published=True,
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
_data_dir=tmp_path,
)
assert note.title == "Just a note without heading"
def test_title_fallback_to_slug(self):
"""Test title falls back to slug if no content"""
def test_label(self, tmp_path):
"""label: title, else excerpt, else slug"""
assert self._note_with(tmp_path, "Just a note\n\nMore.").label == "Just a note More."
note = Note(
id=1,
slug="my-test-note",
@@ -185,10 +169,10 @@ class TestNoteModel:
created_at=datetime.now(timezone.utc).replace(tzinfo=None),
updated_at=datetime.now(timezone.utc).replace(tzinfo=None),
_data_dir=Path("/nonexistent"),
title="Titled",
)
# Should fall back to slug (file doesn't exist)
assert note.title == "my-test-note"
assert note.label == "Titled"
assert replace(note, title=None).label == "my-test-note"
def test_excerpt_generation(self, tmp_path):
"""Test excerpt generation"""
@@ -208,8 +192,8 @@ class TestNoteModel:
)
excerpt = note.excerpt
assert len(excerpt) <= 203 # EXCERPT_LENGTH + "..."
assert excerpt.endswith("...")
assert len(excerpt) <= 201 # EXCERPT_LENGTH + "…"
assert excerpt.endswith("…")
def test_excerpt_short_content(self, tmp_path):
"""Test excerpt with short content (no ellipsis)"""
@@ -259,6 +243,24 @@ class TestNoteModel:
_data_dir=tmp_path,
)
def test_excerpt_is_plain_text(self, tmp_path):
"""No Markdown in previews, alt text or crosspost teasers (v2.16.0)"""
note = self._note_with(
tmp_path, "Some **bold** and a [link](https://x.example).\n\n![pic](/m.jpg)\n\n- one\n- two")
assert note.excerpt == "Some bold and a link. • one • two"
def test_hashtag_line_is_not_a_heading(self, tmp_path):
"""'#indieweb ...' renders as text; '# Heading' still a heading (v2.16.0)"""
note = self._note_with(tmp_path, "#indieweb is fun\n\n##two\n\n# Real heading")
assert "<p>#indieweb is fun</p>" in note.html
assert "<p>##two</p>" in note.html
assert "<h1>Real heading</h1>" in note.html
assert note.excerpt.startswith("#indieweb is fun ##two")
def test_hashtag_in_code_untouched(self, tmp_path):
note = self._note_with(tmp_path, "```\n#include <x>\n```")
assert "\\" not in note.html and "include" in note.html
def test_split_title(self):
"""A '# Heading' first line is split off as the title"""
assert split_title("# My Title\n\nBody") == ("My Title", "Body")
@@ -266,22 +268,6 @@ class TestNoteModel:
assert split_title("No heading\n# later") == (None, "No heading\n# later")
assert split_title("#\nBody") == (None, "#\nBody")
def test_body_html_leaves_out_title(self, tmp_path):
"""Pages show the title themselves, so the body must not repeat it"""
note = self._note_with(tmp_path, "# My Title\n\nBody text.")
assert "My Title" not in note.body_html
assert "<p>Body text.</p>" in note.body_html
assert "<h1>My Title</h1>" in note.html # html is unchanged
def test_body_html_untitled_matches_html(self, tmp_path):
note = self._note_with(tmp_path, "Plain note.")
assert note.body_html == note.html
def test_excerpt_leaves_out_title(self, tmp_path):
"""Previews show the title above the excerpt, so it is not repeated"""
note = self._note_with(tmp_path, "# Title\n\nShort content.")
assert note.excerpt == "Short content."
def test_permalink(self):
"""Test permalink generation"""
note = Note(
+3 -3
View File
@@ -68,7 +68,7 @@ def sample_notes(app):
notes = []
for i in range(10):
note = create_note(
content=f"# Test Note {i}\n\nContent for note {i}.",
title=f"Test Note {i}", content=f"Content for note {i}.",
published=(i < 7), # First 7 published, last 3 drafts
)
notes.append(note)
@@ -316,7 +316,7 @@ class TestFeedEdgeCases:
"""Test feed handles special characters correctly"""
with app.app_context():
create_note(
content="# Test & Special <Characters>\n\n'Quotes' and \"doubles\".",
title="Test & Special <Characters>", content="'Quotes' and \"doubles\".",
published=True,
)
@@ -330,7 +330,7 @@ class TestFeedEdgeCases:
def test_feed_with_unicode_content(self, client, app):
"""Test feed handles Unicode content"""
with app.app_context():
create_note(content="# Test Unicode 你好 🚀\n\nEmojis and ümlauts.", published=True)
create_note(title="Test Unicode 你好 🚀", content="Emojis and ümlauts.", published=True)
response = client.get("/feed.xml")
assert response.status_code == 200
+34
View File
@@ -121,6 +121,40 @@ class TestCompose:
assert "…" in text
class TestArticles:
"""Articles are crossposted as title, teaser and link, without images (v2.16.0)"""
LINK = "https://blog.example.com/note/x"
def test_title_summary_and_link(self, app):
with app.app_context():
note = create_note(content="Long body " * 100, title="My Article",
summary="The gist.", published=True)
text = compose_text(note, self.LINK, ["IndieWeb"], 500)
assert text == f"My Article\n\nThe gist.\n\n{self.LINK}\n\n#IndieWeb"
def test_without_summary_the_start_of_the_text(self, app):
with app.app_context():
note = create_note(content="Some *markdown* " + "word " * 100, title="T", published=True)
title, teaser, link = compose_text(note, self.LINK, [], 5000).split("\n\n")
assert (title, link) == ("T", self.LINK)
assert teaser.startswith("Some markdown word") and teaser.endswith("…")
assert len(teaser) <= 201
def test_edit_follows_and_no_images(self, app, server, monkeypatch):
looked_up = []
monkeypatch.setattr(syndication, "_media_files", lambda *a, **k: looked_up.append(a) or [])
with app.test_request_context():
note = create_note(content="Body", title="Before", published=True)
select_targets(note.id, ["gotosocial"])
process_due()
update_note(id=note.id, title="After")
process_due()
assert server.statuses["1"]["status"].startswith("After\n\nBody")
assert not server.statuses["1"].get("media_ids")
assert looked_up == []
class TestLifecycle:
def test_publish_creates_status(self, app, server):
note = publish(app, tags=["Test"])
+18
View File
@@ -179,12 +179,30 @@ class TestText:
assert raw[tag["index"]["byteStart"]:tag["index"]["byteEnd"]] == b"#IndieWeb"
assert tag["features"][0]["tag"] == "IndieWeb"
def test_hashtag_at_line_start_stays_a_tag(self):
"""Not turned into a heading and lost (v2.16.0)"""
assert plain_text("#indieweb is fun") == "#indieweb is fun"
assert [f["features"][0]["tag"] for f in bluesky_facets(plain_text("#indieweb is fun"))] == ["indieweb"]
def test_fragment_in_url_is_not_a_tag(self):
facets = bluesky_facets("see https://x.example/page#section and #42 too")
assert [f["features"][0]["$type"] for f in facets] == ["app.bsky.richtext.facet#link"]
class TestLifecycle:
def test_article_posts_teaser_with_its_own_card(self, app, pds):
"""An article's card is the article, even when its text links elsewhere (v2.16.0)"""
with app.test_request_context():
note = create_note(content="See [this](https://elsewhere.example/x) for more.",
title="My Article", summary="The gist.", published=True)
select_targets(note.id, ["bluesky"])
process_due()
record = only_record(pds)
permalink = f"https://blog.example.com/note/{note.slug}"
assert record["text"] == f"My Article\n\nThe gist.\n\n{permalink}"
assert record["embed"]["external"] == {
"uri": permalink, "title": "My Article", "description": "The gist."}
def test_publish_posts_with_link_card(self, app, pds):
note = publish(app, content="Hello **Bluesky**", tags=["IndieWeb"])
record = only_record(pds)