Files
StarPunk/tests/test_micropub.py
T
PhilandClaude Opus 5.5 978c13358b 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>
2026-11-11 17:05:38 -07:00

394 lines
13 KiB
Python

"""
Tests for Micropub endpoint
Tests the /micropub endpoint for creating posts via IndieWeb clients.
Covers both form-encoded and JSON requests, authentication, and error handling.
Note: After Phase 4 (ADR-030), StarPunk no longer issues tokens. Tests mock
external token verification responses.
"""
import pytest
from unittest.mock import patch
from starpunk.notes import get_note
# Mock token verification responses
@pytest.fixture
def mock_valid_token():
"""Mock response from external token verification (valid token)"""
def verify_token(token):
if token == "valid_token":
return {
"me": "https://user.example",
"client_id": "https://client.example",
"scope": "create"
}
return None
return verify_token
@pytest.fixture
def mock_invalid_token():
"""Mock response from external token verification (invalid token)"""
def verify_token(token):
return None
return verify_token
@pytest.fixture
def mock_read_only_token():
"""Mock response for token without create scope"""
def verify_token(token):
if token == "read_only_token":
return {
"me": "https://user.example",
"client_id": "https://client.example",
"scope": "read"
}
return None
return verify_token
# Authentication Tests
def test_micropub_no_token(client):
"""Test Micropub endpoint rejects requests without token"""
response = client.post('/micropub', data={
'h': 'entry',
'content': 'Test post'
})
assert response.status_code == 401
data = response.get_json()
assert data['error'] == 'unauthorized'
assert 'No access token' in data['error_description']
def test_micropub_invalid_token(client, mock_invalid_token):
"""Test Micropub endpoint rejects invalid tokens"""
with patch('starpunk.routes.micropub.verify_access_token', mock_invalid_token):
response = client.post(
'/micropub',
data={'h': 'entry', 'content': 'Test post'},
headers={'Authorization': 'Bearer invalid_token'}
)
assert response.status_code == 401
data = response.get_json()
assert data['error'] == 'unauthorized'
assert 'Invalid or expired' in data['error_description']
def test_micropub_insufficient_scope(client, mock_read_only_token):
"""Test Micropub endpoint rejects token without create scope"""
with patch('starpunk.routes.micropub.verify_access_token', mock_read_only_token):
response = client.post(
'/micropub',
data={'h': 'entry', 'content': 'Test post'},
headers={'Authorization': 'Bearer read_only_token'}
)
assert response.status_code == 403
data = response.get_json()
assert data['error'] == 'insufficient_scope'
# Create Post Tests
def test_micropub_create_note_form(client, app, mock_valid_token):
"""Test creating a note via form-encoded request"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.post(
'/micropub',
data={
'h': 'entry',
'content': 'This is a test note from Micropub',
},
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 201
assert 'Location' in response.headers
# Verify note was created
location = response.headers['Location']
slug = location.split('/')[-1]
with app.app_context():
note = get_note(slug)
assert note is not None
assert note.content == 'This is a test note from Micropub'
assert note.published is True
def test_micropub_create_note_json(client, app, mock_valid_token):
"""Test creating a note via JSON request"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.post(
'/micropub',
json={
'type': ['h-entry'],
'properties': {
'content': ['JSON test note']
}
},
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 201
assert 'Location' in response.headers
location = response.headers['Location']
slug = location.split('/')[-1]
with app.app_context():
note = get_note(slug)
assert note.content == 'JSON test note'
def test_micropub_create_with_name(client, app, mock_valid_token):
"""Test creating a note with a title (name property)"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.post(
'/micropub',
json={
'type': ['h-entry'],
'properties': {
'name': ['My Test Title'],
'content': ['Content goes here']
}
},
headers={'Authorization': 'Bearer valid_token'}
)
# Verify note was created successfully
assert response.status_code == 201
assert 'Location' in response.headers
# 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 == 'Content goes here'
assert note.title == 'My Test Title'
def test_micropub_create_with_name_already_heading(client, app, mock_valid_token):
"""A name that matches the content's heading is not added twice"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.post(
'/micropub',
json={
'type': ['h-entry'],
'properties': {
'name': ['Same Title'],
'content': ['# Same Title\n\nBody']
}
},
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 201
slug = response.headers['Location'].rstrip('/').split('/')[-1]
with app.app_context():
note = get_note(slug)
assert (note.title, note.content) == ('Same Title', 'Body')
def test_micropub_create_with_categories(client, app, mock_valid_token):
"""Test creating a note with tags (category property)"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.post(
'/micropub',
json={
'type': ['h-entry'],
'properties': {
'content': ['Tagged post'],
'category': ['test', 'micropub', 'indieweb']
}
},
headers={'Authorization': 'Bearer valid_token'}
)
# Verify note was created successfully
assert response.status_code == 201
assert 'Location' in response.headers
def test_micropub_create_with_custom_slug_form(client, app, mock_valid_token):
"""Test creating a note with custom slug via form-encoded request"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.post(
'/micropub',
data={
'h': 'entry',
'content': 'This is a test for custom slugs',
'mp-slug': 'my-custom-slug'
},
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 201
assert 'Location' in response.headers
# Verify the custom slug was used
location = response.headers['Location']
assert location.endswith('/note/my-custom-slug')
# Verify note exists with the custom slug
with app.app_context():
note = get_note('my-custom-slug')
assert note is not None
assert note.slug == 'my-custom-slug'
assert note.content == 'This is a test for custom slugs'
def test_micropub_create_with_custom_slug_json(client, app, mock_valid_token):
"""Test creating a note with custom slug via JSON request"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.post(
'/micropub',
json={
'type': ['h-entry'],
'properties': {
'content': ['JSON test with custom slug']
},
'mp-slug': 'json-custom-slug'
},
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 201
assert 'Location' in response.headers
# Verify the custom slug was used
location = response.headers['Location']
assert location.endswith('/note/json-custom-slug')
# Verify note exists with the custom slug
with app.app_context():
note = get_note('json-custom-slug')
assert note is not None
assert note.slug == 'json-custom-slug'
assert note.content == 'JSON test with custom slug'
# Query Tests
def test_micropub_query_config(client, mock_valid_token):
"""Test q=config endpoint"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.get(
'/micropub?q=config',
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 200
data = response.get_json()
# Config endpoint returns server capabilities
# Check that it's a valid config response
assert isinstance(data, dict)
def test_micropub_query_source(client, mock_valid_token):
"""Test q=source endpoint"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
# First create a note
create_response = client.post(
'/micropub',
json={
'type': ['h-entry'],
'properties': {
'content': ['Source test']
}
},
headers={'Authorization': 'Bearer valid_token'}
)
location = create_response.headers['Location']
# Query for source
response = client.get(
f'/micropub?q=source&url={location}',
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 200
data = response.get_json()
assert 'properties' in data
assert data['properties']['content'][0] == 'Source test'
# url must be the real permalink (was /notes/<slug>, a 404)
assert data['properties']['url'] == [location]
# A note without a heading has no name
assert 'name' not in data['properties']
def test_micropub_query_source_with_name(client, mock_valid_token):
"""q=source returns name and content the way they were posted"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
create_response = client.post(
'/micropub',
json={
'type': ['h-entry'],
'properties': {
'name': ['Round Trip'],
'content': ['Body text']
}
},
headers={'Authorization': 'Bearer valid_token'}
)
location = create_response.headers['Location']
response = client.get(
f'/micropub?q=source&url={location}',
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 200
properties = response.get_json()['properties']
assert properties['name'] == ['Round Trip']
assert properties['content'] == ['Body text']
assert properties['url'] == [location]
# Error Handling Tests
def test_micropub_missing_content(client, mock_valid_token):
"""Test creating note without content fails"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.post(
'/micropub',
json={
'type': ['h-entry'],
'properties': {}
},
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 400
data = response.get_json()
assert data['error'] == 'invalid_request'
def test_micropub_update_delete_need_scope(client, mock_valid_token):
"""A create-only token can't update or delete (v2.4.0)"""
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
for action in ('update', 'delete', 'undelete'):
response = client.post(
'/micropub',
json={'action': action, 'url': 'https://example.com/note/123', 'replace': {}},
headers={'Authorization': 'Bearer valid_token'}
)
assert response.status_code == 403, action
assert response.get_json()['error'] == 'insufficient_scope'
def test_micropub_unknown_action(client, mock_valid_token):
with patch('starpunk.routes.micropub.verify_access_token', mock_valid_token):
response = client.post('/micropub', json={'action': 'frobnicate'},
headers={'Authorization': 'Bearer valid_token'})
assert response.status_code == 400