2f66de2928
Operator-asked 2026-06-01 after the Dymkens orphan investigation (Scribe plan #540). The pre-2030 sidecar-synthetic Source pattern (`sidecar:<platform>:<slug>` enabled=false rows) existed solely to satisfy `Post.source_id NOT NULL`, and leaked into the Subscriptions UI as phantom subscriptions. Now the data model says what's true: filesystem-imported content with no live subscription has NULL source_id, full stop. ## Schema (alembic 0030) - `post.artist_id` — NEW NOT NULL FK to artist (CASCADE). Backfilled from source.artist_id in the migration. Indexed for the artist-filter queries. - `post.source_id` — NOT NULL → nullable; FK ondelete CASCADE → SET NULL. Deleting a Source detaches its Posts instead of destroying archived content (subscription ends, archive stays). - `image_provenance.source_id` — same nullable + SET NULL. - Partial unique index `uq_post_artist_external_id_null_source` on (artist_id, external_post_id) WHERE source_id IS NULL — guards filesystem-import dedup since the existing source-bound unique ignores NULLs (Postgres treats NULL != NULL). - Sidecar synthetic Sources deleted: NULL out FKs in post, image_provenance first, then DELETE FROM source WHERE url LIKE 'sidecar:%'. The Dymkens cleanup. ## Model + service changes - `Post.source_id` → `Mapped[int | None]`; new `Post.artist_id` denormalized. - `ImageProvenance.source_id` → `Mapped[int | None]`. - Importer: `_source_for_sidecar` (synthetic-creating) → `_lookup_source_for_sidecar` (returns None when no subscription). `_find_or_create_post` takes required `artist_id`; matches on (source_id, external_post_id) for source-bound posts or (artist_id, external_post_id) for NULL-source posts. - Service queries switched off the Source detour to use Post.artist_id directly: post_feed_service.scroll/around/get_post (LEFT JOIN to Source so NULL-source posts surface); artist_service date_row/ activity/post_count; provenance_service.for_image/for_post (LEFT JOIN); gallery_service._provenance_exists_where_artist via Post.artist_id instead of ImageProvenance.source_id → Source. - `_to_dict` and provenance dict-builders emit `"source": null` for NULL-source rows. ## Frontend - `ProvenancePanel.vue` + `PostCard.vue`: render `e.source?.platform ?? 'filesystem import'` so NULL-source posts get a clear "filesystem import" affordance instead of a NaN crash. ## Tests - `test_importer_upsert_helpers`: removed the four synthetic-anchor tests; added `_find_or_create_post_idempotent_with_null_source` (dedup via the partial unique index) and `_lookup_source_for_sidecar_returns_*` (existing-subscription + none cases). The existing `_find_or_create_post_idempotent` now also passes `artist_id` and asserts it. - 8 other test files updated: every direct `Post(...)` construction gains `artist_id=<artist>.id`. The `_seed_post` helper in `test_post_feed_service` looks up artist_id from the source row so callsites stay one-arg. ## Verification on deploy After alembic 0030 runs: - `SELECT COUNT(*) FROM source WHERE url LIKE 'sidecar:%'` → 0. - `SELECT COUNT(*) FROM post WHERE source_id IS NULL` → count of filesystem-imported posts (Dymkens + any other historical). - Every `post.artist_id` non-null; consistent with source.artist_id for source-bound rows. - Subscriptions tab: no Dymkens phantom row. - Artist detail → Posts/Gallery: Dymkens's content still reachable via Post.artist_id. - Provenance panel renders "filesystem import" chip for NULL-source posts; PostCard same. ## Out of scope - UI to manage/delete orphan NULL-source Posts. Data model is right; UI follows if operator wants it.
222 lines
7.2 KiB
Python
222 lines
7.2 KiB
Python
"""FC-3e: /api/posts API tests.
|
|
|
|
Validates list shape, cursor handling, filter validation, and detail
|
|
endpoint. Service-level fixtures are exercised by test_post_feed_service
|
|
— here we focus on the HTTP surface (validation, status codes, dict shape).
|
|
"""
|
|
from datetime import UTC, datetime, timedelta
|
|
|
|
import pytest
|
|
|
|
from backend.app.models import Artist, Post, Source
|
|
|
|
pytestmark = pytest.mark.integration
|
|
|
|
|
|
@pytest.fixture
|
|
async def seeded_post(db):
|
|
artist = Artist(name="alice-api", slug="alice-api")
|
|
db.add(artist)
|
|
await db.flush()
|
|
source = Source(
|
|
artist_id=artist.id, platform="patreon",
|
|
url="https://p/alice-api", enabled=True,
|
|
)
|
|
db.add(source)
|
|
await db.flush()
|
|
post = Post(
|
|
source_id=source.id, artist_id=artist.id, external_post_id="API1",
|
|
post_title="Hello", post_url="https://p/alice-api/1",
|
|
post_date=datetime.now(UTC),
|
|
description="<p>hi</p>",
|
|
)
|
|
db.add(post)
|
|
await db.commit()
|
|
return artist, source, post
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_returns_items_and_cursor_keys(client, seeded_post):
|
|
resp = await client.get("/api/posts")
|
|
assert resp.status_code == 200
|
|
body = await resp.get_json()
|
|
assert set(body.keys()) == {"items", "next_cursor"}
|
|
assert isinstance(body["items"], list)
|
|
assert body["items"][0]["post_title"] == "Hello"
|
|
assert body["items"][0]["description_plain"] == "hi"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_rejects_malformed_cursor(client):
|
|
resp = await client.get("/api/posts?cursor=garbage!!!")
|
|
assert resp.status_code == 400
|
|
body = await resp.get_json()
|
|
assert body["error"] == "invalid_cursor"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_rejects_unknown_platform(client):
|
|
resp = await client.get("/api/posts?platform=myspace")
|
|
assert resp.status_code == 400
|
|
body = await resp.get_json()
|
|
assert body["error"] == "unknown_platform"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_rejects_non_int_artist_id(client):
|
|
resp = await client.get("/api/posts?artist_id=notanint")
|
|
assert resp.status_code == 400
|
|
body = await resp.get_json()
|
|
assert body["error"] == "invalid_artist_id"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_rejects_limit_out_of_range(client):
|
|
resp = await client.get("/api/posts?limit=0")
|
|
assert resp.status_code == 400
|
|
resp = await client.get("/api/posts?limit=500")
|
|
assert resp.status_code == 400
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_filter_propagates_artist(client, seeded_post):
|
|
artist, _, post = seeded_post
|
|
resp = await client.get(f"/api/posts?artist_id={artist.id}")
|
|
assert resp.status_code == 200
|
|
body = await resp.get_json()
|
|
assert len(body["items"]) == 1
|
|
assert body["items"][0]["id"] == post.id
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_detail_200_for_known(client, seeded_post):
|
|
_, _, post = seeded_post
|
|
resp = await client.get(f"/api/posts/{post.id}")
|
|
assert resp.status_code == 200
|
|
body = await resp.get_json()
|
|
assert body["id"] == post.id
|
|
assert "description_full" in body
|
|
assert body["description_full"] == "hi"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_detail_404_for_unknown(client):
|
|
resp = await client.get("/api/posts/999999")
|
|
assert resp.status_code == 404
|
|
body = await resp.get_json()
|
|
assert body["error"] == "not_found"
|
|
|
|
|
|
@pytest.fixture
|
|
async def post_timeline(db):
|
|
"""Five posts on distinct dates: posts[0] oldest … posts[4] newest."""
|
|
artist = Artist(name="tl-api", slug="tl-api")
|
|
db.add(artist)
|
|
await db.flush()
|
|
source = Source(
|
|
artist_id=artist.id, platform="patreon",
|
|
url="https://p/tl-api", enabled=True,
|
|
)
|
|
db.add(source)
|
|
await db.flush()
|
|
base = datetime(2026, 1, 1, tzinfo=UTC)
|
|
posts = []
|
|
for i in range(5):
|
|
p = Post(
|
|
source_id=source.id, artist_id=artist.id,
|
|
external_post_id=f"TL{i}",
|
|
post_title=f"post {i}", post_date=base + timedelta(days=i),
|
|
)
|
|
db.add(p)
|
|
posts.append(p)
|
|
await db.commit()
|
|
return artist, source, posts
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_around_returns_window_with_anchor(client, post_timeline):
|
|
_, _, posts = post_timeline
|
|
anchor = posts[2]
|
|
resp = await client.get(f"/api/posts?around={anchor.id}&limit=1")
|
|
assert resp.status_code == 200
|
|
body = await resp.get_json()
|
|
assert set(body.keys()) == {"items", "cursor_older", "cursor_newer", "anchor_id"}
|
|
assert body["anchor_id"] == anchor.id
|
|
# limit=1: one newer + anchor + one older, in feed (desc) order.
|
|
assert [it["id"] for it in body["items"]] == [posts[3].id, posts[2].id, posts[1].id]
|
|
assert body["cursor_older"] is not None # posts[0] still older
|
|
assert body["cursor_newer"] is not None # posts[4] still newer
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_around_404_for_unknown(client):
|
|
resp = await client.get("/api/posts?around=999999")
|
|
assert resp.status_code == 404
|
|
assert (await resp.get_json())["error"] == "not_found"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_direction_newer_walks_forward(client, post_timeline):
|
|
_, _, posts = post_timeline
|
|
around = await client.get(f"/api/posts?around={posts[1].id}&limit=1")
|
|
cursor_newer = (await around.get_json())["cursor_newer"]
|
|
assert cursor_newer is not None
|
|
resp = await client.get(f"/api/posts?cursor={cursor_newer}&direction=newer&limit=5")
|
|
assert resp.status_code == 200
|
|
# Newer than the window's newest (posts[2]) → posts[3], posts[4] in desc order.
|
|
assert [it["id"] for it in (await resp.get_json())["items"]] == [posts[4].id, posts[3].id]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_rejects_bad_direction(client):
|
|
resp = await client.get("/api/posts?direction=sideways")
|
|
assert resp.status_code == 400
|
|
assert (await resp.get_json())["error"] == "invalid_direction"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_detail_returns_uncapped_thumbnails(client, db):
|
|
"""Feed query caps thumbnails at 6 for previews; detail endpoint
|
|
returns the full list so PostModal can render the masonry grid."""
|
|
from backend.app.models import ImageRecord
|
|
|
|
a = Artist(name="yuki-api", slug="yuki-api")
|
|
db.add(a)
|
|
await db.flush()
|
|
s = Source(
|
|
artist_id=a.id, platform="patreon",
|
|
url="https://patreon.com/cw/yuki-api", enabled=True,
|
|
)
|
|
db.add(s)
|
|
await db.flush()
|
|
p = Post(
|
|
source_id=s.id, artist_id=a.id, external_post_id="DETAIL10",
|
|
post_title="big post", description="<p>body</p>",
|
|
)
|
|
db.add(p)
|
|
await db.flush()
|
|
# Seed 10 ImageRecord rows linked to this post via primary_post_id.
|
|
for i in range(10):
|
|
sha = f"y{i:x}".ljust(64, "0")[:64]
|
|
rec = ImageRecord(
|
|
path=f"/images/test-yuki-{i}.jpg",
|
|
sha256=sha,
|
|
size_bytes=1,
|
|
mime="image/jpeg",
|
|
width=64,
|
|
height=64,
|
|
origin="downloaded",
|
|
integrity_status="unknown",
|
|
primary_post_id=p.id,
|
|
artist_id=a.id,
|
|
)
|
|
db.add(rec)
|
|
await db.commit()
|
|
|
|
resp = await client.get(f"/api/posts/{p.id}")
|
|
assert resp.status_code == 200
|
|
body = await resp.get_json()
|
|
# Detail returns ALL 10 thumbnails (feed would return 6 + thumbnails_more).
|
|
assert len(body["thumbnails"]) == 10
|
|
assert body["description_full"] == "body"
|