Files
FabledCurator/tests/test_source_service.py
T
bvandeusen 2f66de2928
CI / lint (push) Failing after 3s
CI / backend-lint-and-test (push) Successful in 11s
CI / frontend-build (push) Successful in 17s
CI / intimp (push) Failing after 2m15s
CI / intapi (push) Failing after 2m18s
CI / intcore (push) Failing after 2m17s
feat(model): nullable Post.source_id + denormalized Post.artist_id; retire sidecar synthetics
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.
2026-06-01 14:17:52 -04:00

172 lines
5.4 KiB
Python

import pytest
from sqlalchemy import select
from backend.app.models import Artist, Source
from backend.app.services.source_service import (
KNOWN_PLATFORMS,
ArtistNotFoundError,
DuplicateSourceError,
EmptyUrlError,
InvalidConfigError,
SourceService,
UnknownPlatformError,
)
pytestmark = pytest.mark.integration
async def _artist(db, name="Alice"):
a = Artist(name=name, slug=name.lower())
db.add(a)
await db.flush()
return a
@pytest.mark.asyncio
async def test_known_platforms_is_gs_six(db):
assert KNOWN_PLATFORMS == frozenset({
"patreon", "subscribestar", "hentaifoundry",
"discord", "pixiv", "deviantart",
})
assert "fanbox" not in KNOWN_PLATFORMS
@pytest.mark.asyncio
async def test_create_flips_is_subscription_on_first_source(db):
artist = await _artist(db)
svc = SourceService(db)
rec = await svc.create(
artist_id=artist.id, platform="patreon", url="https://patreon.com/alice",
)
assert rec.id is not None
is_sub = (await db.execute(
select(Artist.is_subscription).where(Artist.id == artist.id)
)).scalar_one()
assert is_sub is True
@pytest.mark.asyncio
async def test_delete_last_source_flips_is_subscription_off(db):
artist = await _artist(db)
svc = SourceService(db)
rec = await svc.create(
artist_id=artist.id, platform="patreon", url="https://patreon.com/alice",
)
await svc.delete(rec.id)
is_sub = (await db.execute(
select(Artist.is_subscription).where(Artist.id == artist.id)
)).scalar_one()
assert is_sub is False
@pytest.mark.asyncio
async def test_create_rejects_unknown_platform(db):
artist = await _artist(db)
svc = SourceService(db)
with pytest.raises(UnknownPlatformError):
await svc.create(
artist_id=artist.id, platform="myspace", url="https://m/x",
)
@pytest.mark.asyncio
async def test_create_rejects_non_dict_config(db):
artist = await _artist(db)
svc = SourceService(db)
with pytest.raises(InvalidConfigError):
await svc.create(
artist_id=artist.id, platform="patreon",
url="https://patreon.com/alice", config_overrides=[1, 2, 3],
)
@pytest.mark.asyncio
async def test_create_rejects_empty_url(db):
artist = await _artist(db)
svc = SourceService(db)
with pytest.raises(EmptyUrlError):
await svc.create(artist_id=artist.id, platform="patreon", url=" ")
@pytest.mark.asyncio
async def test_create_rejects_unknown_artist(db):
svc = SourceService(db)
with pytest.raises(ArtistNotFoundError):
await svc.create(artist_id=99999, platform="patreon", url="https://x/y")
@pytest.mark.asyncio
async def test_create_duplicate_raises_with_existing_id(db):
artist = await _artist(db)
svc = SourceService(db)
first = await svc.create(
artist_id=artist.id, platform="patreon", url="https://patreon.com/alice",
)
with pytest.raises(DuplicateSourceError) as exc:
await svc.create(
artist_id=artist.id, platform="patreon",
url="https://patreon.com/alice",
)
assert exc.value.existing_id == first.id
@pytest.mark.asyncio
async def test_list_filters_by_artist(db):
a = await _artist(db, "Alice")
b = await _artist(db, "Bob")
svc = SourceService(db)
await svc.create(artist_id=a.id, platform="patreon", url="https://patreon.com/a")
await svc.create(artist_id=b.id, platform="patreon", url="https://patreon.com/b")
only_a = await svc.list(artist_id=a.id)
assert [s.artist_id for s in only_a] == [a.id]
all_rows = await svc.list()
assert len(all_rows) == 2
@pytest.mark.asyncio
async def test_update_changes_fields(db):
artist = await _artist(db)
svc = SourceService(db)
rec = await svc.create(
artist_id=artist.id, platform="patreon", url="https://patreon.com/a",
)
updated = await svc.update(rec.id, enabled=False, config_overrides={"videos": False})
assert updated.enabled is False
assert updated.config_overrides == {"videos": False}
@pytest.mark.asyncio
async def test_list_hides_sidecar_synthetic_anchors(db):
"""Filesystem-import synthetic Sources (url='sidecar:<platform>:<slug>',
enabled=False — historical pre-alembic-0030 artifact) used to leak into the
Subscriptions UI as phantom subscriptions because list() didn't filter
them. They aren't pollable feeds; hide by default."""
artist = await _artist(db, "Alice")
real = Source(
artist_id=artist.id, platform="patreon",
url="https://patreon.com/alice", enabled=True, config_overrides={},
)
synthetic = Source(
artist_id=artist.id, platform="patreon",
url="sidecar:patreon:alice", enabled=False, config_overrides={},
)
db.add_all([real, synthetic])
await db.commit()
svc = SourceService(db)
visible = await svc.list()
visible_urls = {s.url for s in visible}
assert "https://patreon.com/alice" in visible_urls
assert "sidecar:patreon:alice" not in visible_urls
# Same filter applies to the artist-scoped list path (the artist detail
# page hits /api/sources?artist_id=N).
artist_scoped = await svc.list(artist_id=artist.id)
assert {s.url for s in artist_scoped} == {"https://patreon.com/alice"}
# include_synthetic=True opts back in for admin tooling.
everything = await svc.list(include_synthetic=True)
assert {s.url for s in everything} >= {
"https://patreon.com/alice", "sidecar:patreon:alice",
}