Files
StarPunk/tests/test_media_upload.py
Phil Skentelbery dd822a35b5 feat: v1.2.0-rc.1 - IndieWeb Features Release Candidate
Complete implementation of v1.2.0 "IndieWeb Features" release.

## Phase 1: Custom Slugs
- Optional custom slug field in note creation form
- Auto-sanitization (lowercase, hyphens only)
- Uniqueness validation with auto-numbering
- Read-only after creation to preserve permalinks
- Matches Micropub mp-slug behavior

## Phase 2: Author Discovery + Microformats2
- Automatic h-card discovery from IndieAuth identity URL
- 24-hour caching with graceful fallback
- Never blocks login (per ADR-061)
- Complete h-entry, h-card, h-feed markup
- All required Microformats2 properties
- rel-me links for identity verification
- Passes IndieWeb validation

## Phase 3: Media Upload
- Upload up to 4 images per note (JPEG, PNG, GIF, WebP)
- Automatic optimization with Pillow
  - Auto-resize to 2048px
  - EXIF orientation correction
  - 95% quality compression
- Social media-style layout (media top, text below)
- Optional captions for accessibility
- Integration with all feed formats (RSS, ATOM, JSON Feed)
- Date-organized storage with UUID filenames
- Immutable caching (1 year)

## Database Changes
- migrations/006_add_author_profile.sql - Author discovery cache
- migrations/007_add_media_support.sql - Media storage

## New Modules
- starpunk/author_discovery.py - h-card discovery and caching
- starpunk/media.py - Image upload, validation, optimization

## Documentation
- 4 new ADRs (056, 057, 058, 061)
- Complete design specifications
- Developer Q&A with 40+ questions answered
- 3 implementation reports
- 3 architect reviews (all approved)

## Testing
- 56 new tests for v1.2.0 features
- 842 total tests in suite
- All v1.2.0 feature tests passing

## Dependencies
- Added: mf2py (Microformats2 parser)
- Added: Pillow (image processing)

Version: 1.2.0-rc.1

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-28 15:02:20 -07:00

326 lines
11 KiB
Python

"""
Tests for media upload functionality (v1.2.0 Phase 3)
Tests media upload, validation, optimization, and display per ADR-057 and ADR-058.
Uses generated test images (PIL Image.new()) per Q31.
"""
import pytest
from PIL import Image
import io
from pathlib import Path
from starpunk.media import (
validate_image,
optimize_image,
save_media,
attach_media_to_note,
get_note_media,
delete_media,
MAX_FILE_SIZE,
MAX_DIMENSION,
RESIZE_DIMENSION,
MAX_IMAGES_PER_NOTE,
)
def create_test_image(width=800, height=600, format='PNG'):
"""
Generate test image using PIL
Per Q31: Use generated test images, not real files
Args:
width: Image width in pixels
height: Image height in pixels
format: Image format (PNG, JPEG, GIF, WEBP)
Returns:
Bytes of image data
"""
img = Image.new('RGB', (width, height), color='red')
buffer = io.BytesIO()
img.save(buffer, format=format)
buffer.seek(0)
return buffer.getvalue()
class TestImageValidation:
"""Test validate_image function"""
def test_valid_jpeg(self):
"""Test validation of valid JPEG image"""
image_data = create_test_image(800, 600, 'JPEG')
mime_type, width, height = validate_image(image_data, 'test.jpg')
assert mime_type == 'image/jpeg'
assert width == 800
assert height == 600
def test_valid_png(self):
"""Test validation of valid PNG image"""
image_data = create_test_image(800, 600, 'PNG')
mime_type, width, height = validate_image(image_data, 'test.png')
assert mime_type == 'image/png'
assert width == 800
assert height == 600
def test_valid_gif(self):
"""Test validation of valid GIF image"""
image_data = create_test_image(800, 600, 'GIF')
mime_type, width, height = validate_image(image_data, 'test.gif')
assert mime_type == 'image/gif'
assert width == 800
assert height == 600
def test_valid_webp(self):
"""Test validation of valid WebP image"""
image_data = create_test_image(800, 600, 'WEBP')
mime_type, width, height = validate_image(image_data, 'test.webp')
assert mime_type == 'image/webp'
assert width == 800
assert height == 600
def test_file_too_large(self):
"""Test rejection of >10MB file (per Q6)"""
# Create data larger than MAX_FILE_SIZE
large_data = b'x' * (MAX_FILE_SIZE + 1)
with pytest.raises(ValueError) as exc_info:
validate_image(large_data, 'large.jpg')
assert "File too large" in str(exc_info.value)
def test_dimensions_too_large(self):
"""Test rejection of >4096px image (per ADR-058)"""
large_image = create_test_image(5000, 5000, 'PNG')
with pytest.raises(ValueError) as exc_info:
validate_image(large_image, 'huge.png')
assert "dimensions too large" in str(exc_info.value).lower()
def test_corrupted_image(self):
"""Test rejection of corrupted image data"""
corrupted_data = b'not an image'
with pytest.raises(ValueError) as exc_info:
validate_image(corrupted_data, 'corrupt.jpg')
assert "Invalid or corrupted" in str(exc_info.value)
class TestImageOptimization:
"""Test optimize_image function"""
def test_no_resize_needed(self):
"""Test image within limits is not resized"""
image_data = create_test_image(1024, 768, 'PNG')
optimized, width, height = optimize_image(image_data)
assert width == 1024
assert height == 768
def test_resize_large_image(self):
"""Test auto-resize of >2048px image (per ADR-058)"""
large_image = create_test_image(3000, 2000, 'PNG')
optimized, width, height = optimize_image(large_image)
# Should be resized to 2048px on longest edge
assert width == RESIZE_DIMENSION
# Height should be proportionally scaled
assert height == int(2000 * (RESIZE_DIMENSION / 3000))
def test_aspect_ratio_preserved(self):
"""Test aspect ratio is maintained during resize"""
image_data = create_test_image(3000, 1500, 'PNG')
optimized, width, height = optimize_image(image_data)
# Original aspect ratio: 2:1
# After resize: should still be 2:1
assert width / height == pytest.approx(2.0, rel=0.01)
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 = optimize_image(gif_data)
assert width > 0
assert height > 0
class TestMediaSave:
"""Test save_media function"""
def test_save_valid_image(self, app, db):
"""Test saving valid image"""
image_data = create_test_image(800, 600, 'PNG')
with app.app_context():
media_info = save_media(image_data, 'test.png')
assert media_info['id'] > 0
assert media_info['filename'] == 'test.png'
assert media_info['mime_type'] == 'image/png'
assert media_info['width'] == 800
assert media_info['height'] == 600
assert media_info['size'] > 0
# Check file was created
media_path = Path(app.config['DATA_PATH']) / 'media' / media_info['path']
assert media_path.exists()
def test_uuid_filename(self, app, db):
"""Test UUID-based filename generation (per Q5)"""
image_data = create_test_image(800, 600, 'PNG')
with app.app_context():
media_info = save_media(image_data, 'original-name.png')
# Stored filename should be different from original
assert media_info['stored_filename'] != 'original-name.png'
# Should end with .png
assert media_info['stored_filename'].endswith('.png')
# Path should be YYYY/MM/uuid.ext (per Q2)
parts = media_info['path'].split('/')
assert len(parts) == 3 # year/month/filename
assert len(parts[0]) == 4 # Year
assert len(parts[1]) == 2 # Month
def test_auto_resize_on_save(self, app, db):
"""Test image >2048px is automatically resized"""
large_image = create_test_image(3000, 2000, 'PNG')
with app.app_context():
media_info = save_media(large_image, 'large.png')
# Should be resized
assert media_info['width'] == RESIZE_DIMENSION
assert media_info['height'] < 2000
class TestMediaAttachment:
"""Test attach_media_to_note function"""
def test_attach_single_image(self, app, db, sample_note):
"""Test attaching single image to note"""
image_data = create_test_image(800, 600, 'PNG')
with app.app_context():
# Save media
media_info = save_media(image_data, 'test.png')
# Attach to note
attach_media_to_note(sample_note.id, [media_info['id']], ['Test caption'])
# Verify attachment
media_list = get_note_media(sample_note.id)
assert len(media_list) == 1
assert media_list[0]['id'] == media_info['id']
assert media_list[0]['caption'] == 'Test caption'
assert media_list[0]['display_order'] == 0
def test_attach_multiple_images(self, app, db, sample_note):
"""Test attaching multiple images (up to 4)"""
with app.app_context():
media_ids = []
captions = []
for i in range(4):
image_data = create_test_image(800, 600, 'PNG')
media_info = save_media(image_data, f'test{i}.png')
media_ids.append(media_info['id'])
captions.append(f'Caption {i}')
attach_media_to_note(sample_note.id, media_ids, captions)
media_list = get_note_media(sample_note.id)
assert len(media_list) == 4
# Verify order
for i, media_item in enumerate(media_list):
assert media_item['display_order'] == i
assert media_item['caption'] == f'Caption {i}'
def test_reject_more_than_4_images(self, app, db, sample_note):
"""Test rejection of 5th image (per Q6)"""
with app.app_context():
media_ids = []
captions = []
for i in range(5):
image_data = create_test_image(800, 600, 'PNG')
media_info = save_media(image_data, f'test{i}.png')
media_ids.append(media_info['id'])
captions.append('')
with pytest.raises(ValueError) as exc_info:
attach_media_to_note(sample_note.id, media_ids, captions)
assert "Maximum 4 images" in str(exc_info.value)
def test_optional_captions(self, app, db, sample_note):
"""Test captions are optional (per Q7)"""
image_data = create_test_image(800, 600, 'PNG')
with app.app_context():
media_info = save_media(image_data, 'test.png')
# Attach without caption
attach_media_to_note(sample_note.id, [media_info['id']], [''])
media_list = get_note_media(sample_note.id)
assert media_list[0]['caption'] is None or media_list[0]['caption'] == ''
class TestMediaDeletion:
"""Test delete_media function"""
def test_delete_media_file(self, app, db):
"""Test deletion of media file and record"""
image_data = create_test_image(800, 600, 'PNG')
with app.app_context():
media_info = save_media(image_data, 'test.png')
media_id = media_info['id']
media_path = Path(app.config['DATA_PATH']) / 'media' / media_info['path']
# Verify file exists
assert media_path.exists()
# Delete media
delete_media(media_id)
# Verify file deleted
assert not media_path.exists()
def test_delete_orphaned_associations(self, app, db, sample_note):
"""Test cascade deletion of note_media associations"""
image_data = create_test_image(800, 600, 'PNG')
with app.app_context():
media_info = save_media(image_data, 'test.png')
attach_media_to_note(sample_note.id, [media_info['id']], ['Test'])
# Delete media
delete_media(media_info['id'])
# Verify association also deleted
media_list = get_note_media(sample_note.id)
assert len(media_list) == 0
@pytest.fixture
def sample_note(app, db):
"""Create a sample note for testing"""
from starpunk.notes import create_note
with app.app_context():
note = create_note("Test note content", published=True)
yield note