Files
FabledCurator/tests/test_api_posts.py
T
bvandeusen aea2701c28
CI / lint (push) Successful in 3s
CI / frontend-build (push) Successful in 18s
CI / backend-lint-and-test (push) Successful in 27s
CI / integration (push) Successful in 3m52s
feat(translation): tunable acceptance floor (0.90) + per-post sticky override (#155)
The gate at a fixed 0.80 couldn't catch the real pain: Interpreter (fresh ==
cached, verified by probe) confidently mis-detects short ASCII English like
"... WIP Part 1" as German at 0.86 — above the floor — so it was accepted and a
re-translate reproduced it. Confidence alone can't separate the 0.86 collision
(genuine German lands there too), and single-word mis-flags sit at a confident
1.0 no floor catches.

Two operator-approved levers:

- Acceptance floor is now a live Settings value (ImportSettings.
  translation_min_confidence, default 0.90; surfaced in the Translation card), so
  it's tunable without a redeploy. _accept takes the threshold as a parameter.

- Per-post sticky override (Post.translation_override: auto/force/original).
  'force' stores a translation even below the floor (rescue a skipped
  legit-foreign title); 'original' keeps the original and clears any stored
  translation (kill a confident mis-flag no floor catches). The sweep honors it
  on every run and _reset_translations skips 'original', so the choice survives a
  Re-translate-all. POST /api/posts/<id>/translation-override applies it
  immediately (translate now when the service is up, else queue for the sweep).
  UI: PostTranslationControl on the posts-feed card.

Migration 0084 (both columns + a CHECK on the override). The feed + provenance
serializers expose translation_override.

With a stricter floor the rollback finally works: raise it -> Re-translate all ->
the 0.86 mis-flags are rejected and restored to the original; force /
keep-original handle the residual either way.

Tests: gate thresholds against the param (0.86 rejected at 0.90, explicit-floor
cases); sweep force/original + re-translate-skips-original; override endpoint
(validation, original clears, force queues when disabled, feed exposes it);
settings min_confidence default/save/validate.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CgZP9v2otxVJymiYsnVuMy
2026-07-10 22:38:25 -04:00

294 lines
9.9 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_list_text_search_propagates(client, seeded_post):
_, _, post = seeded_post # title "Hello", description "<p>hi</p>"
hit = await client.get("/api/posts?q=hello")
assert hit.status_code == 200
assert [it["id"] for it in (await hit.get_json())["items"]] == [post.id]
miss = await client.get("/api/posts?q=zzznope")
assert (await miss.get_json())["items"] == []
@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_translation_override_rejects_bad_value(client, seeded_post):
_, _, post = seeded_post
resp = await client.post(
f"/api/posts/{post.id}/translation-override", json={"override": "nope"}
)
assert resp.status_code == 400
assert (await resp.get_json())["error"] == "invalid_override"
@pytest.mark.asyncio
async def test_translation_override_404_for_unknown(client):
resp = await client.post(
"/api/posts/999999/translation-override", json={"override": "original"}
)
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_translation_override_original_clears_and_keeps(client, db, seeded_post):
# 'keep original' clears a stored translation immediately (no Interpreter) and
# marks the post handled (== target). Asserts on the response, which reflects
# the endpoint's own committed session.
_, _, post = seeded_post
post.post_title_translated = "STALE"
post.description_translated = "STALE"
post.translated_source_lang = "de"
await db.commit()
resp = await client.post(
f"/api/posts/{post.id}/translation-override", json={"override": "original"}
)
assert resp.status_code == 200
body = await resp.get_json()
assert body["translation_override"] == "original"
assert body["applied"] == "cleared"
assert body["post_title_translated"] is None
assert body["translated_source_lang"] == "en"
@pytest.mark.asyncio
async def test_translation_override_force_queues_when_disabled(client, seeded_post):
# Translation disabled (default) → can't translate inline; the override is
# saved and the post is queued (columns NULLed) for the next sweep.
_, _, post = seeded_post
resp = await client.post(
f"/api/posts/{post.id}/translation-override", json={"override": "force"}
)
assert resp.status_code == 200
body = await resp.get_json()
assert body["translation_override"] == "force"
assert body["applied"] == "queued"
assert body["translated_source_lang"] is None
@pytest.mark.asyncio
async def test_list_exposes_translation_override(client, seeded_post):
resp = await client.get("/api/posts")
assert resp.status_code == 200
body = await resp.get_json()
assert body["items"][0]["translation_override"] == "auto" # default
@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"