Files
siftlode/backend/tests/test_plex_sync_txn.py
T
peter 4aaaaa7860 chore(comments): drop epic, sprint and review-round ids from the code
The code cited its plan instead of saying why: `E28 review J4`, `(R6 S3b)`, `S1 justified…`,
`deep-review round 5`. That plan lives in the private ops repo, so for every reader of this one the
citation was noise, and a sentence whose subject was the plan step ("round 2 showed…") hid its
lesson behind an id. Each one is gone and the "why" kept: a bare citation is deleted, a sentence
carrying a lesson is reworded around it ("a later attempt showed…").

Measured (`scripts/audit_metrics.py`, product code): 652 lines in 270 files carried an epic code by
the definition the next commit holds (507 / 241 by the old, two-digit-only one) -> 0. Across all
code, tests, scripts and configs: ~1100 epic-code lines plus ~320 sprint/round ids.

Behaviour unchanged, checked mechanically: every changed .py file has the same AST once docstrings
are blanked; css/sh/toml/yml/json files are identical once comments are stripped; the only
non-comment changes in TS/JS are test titles, one description string in a contract table, and five
ESLint messages, whose text is all the gates snapshot diff holds. Not touched: Markdown (docs and
the changelog keep their history), Alembic migrations, TV episode notation (`S2 · E5`), DESIGN.md
ids (`C1`, `B4`, `S3h`), tracker ids (`SEC-16`, `DX-17`).

One stale claim fixed on the way: test_hls_reaper's docstring said the player checkpoints "every
10 s whether or not it is playing", which plex/stream.py calls wrong; it now says what the code does.
2026-10-05 00:19:39 +02:00

91 lines
3.5 KiB
Python

"""DB-backed test for the Plex per-section commit: a PlexError on a LATER library must keep the
libraries already mirrored (committed per section), not roll the whole reconcile back. Uses the DB
lane (`db` fixture) with a faked PlexClient — skipped without Postgres.
"""
from sqlalchemy import select
from app.plex import people, sync
from app.plex.client import PlexError
from app.models import PlexItem, PlexLibrary, PlexPerson
class _FakePlex:
def __enter__(self):
return self
def __exit__(self, *exc):
return False # don't suppress the PlexError
def sections(self):
return [
{"type": "movie", "key": "1", "title": "Lib One"},
{"type": "movie", "key": "2", "title": "Lib Two"},
]
def test_late_section_failure_keeps_earlier_sections(db, monkeypatch):
monkeypatch.setattr(sync.sysconfig, "get_bool", lambda *a, **k: True) # plex_enabled
monkeypatch.setattr(sync, "_enabled_section_keys", lambda db: None) # all sections wanted
monkeypatch.setattr(sync, "PlexClient", lambda db: _FakePlex())
monkeypatch.setattr(sync, "_sync_movies", lambda *a, **k: None) # skip the real Plex fetch
# Section 1 completes and commits; section 2's collections step raises → its work rolls back.
def collections(db, plex, lib, stats):
if lib.plex_key == "2":
raise PlexError("boom on the second library")
monkeypatch.setattr(sync, "_sync_collections", collections)
result = sync.sync(db)
assert "error" in result # the run reports the failure honestly
# Section 1's library survived the section-2 failure (per-section commit); section 2 rolled back.
keys = db.scalars(select(PlexLibrary.plex_key).order_by(PlexLibrary.plex_key)).all()
assert keys == ["1"]
class _FakeMetaPlex:
"""Fake PlexClient whose .metadata() returns the per-item rich metadata dict for a rating_key."""
def __init__(self, by_key):
self._by_key = by_key
def metadata(self, rating_key):
return self._by_key.get(rating_key)
def test_enrich_people_batch_dedupes_shared_cast(db):
"""A cold sync where one person appears across two items in the same batch must NOT crash on the
unique index — before the on_conflict fix, autoflush=False let both rows queue a duplicate
PlexPerson and the batch commit died, leaving plex_people empty. Also covers the prior-NULL photo
back-fill (m1 has no thumb, m2 supplies one for the same person)."""
lib = PlexLibrary(plex_key="1", title="Movies", kind="movie")
db.add(lib)
db.flush()
db.add_all(
[
PlexItem(rating_key="m1", library_id=lib.id, kind="movie", title="Movie One"),
PlexItem(rating_key="m2", library_id=lib.id, kind="movie", title="Movie Two"),
]
)
db.commit()
shared = "Christopher Plummer"
thumb = people.PERSON_IMG_HOST + "cp.jpg"
fake = _FakeMetaPlex(
{
"m1": {"Role": [{"tag": shared, "role": "Self"}, {"tag": "Alice Unique"}]},
"m2": {
"Role": [{"tag": shared, "role": "Self", "thumb": thumb}, {"tag": "Bob Unique"}]
},
}
)
n = sync._enrich_people_batch(db, fake)
assert n == 2 # both items enriched — no unique-violation rollback
rows = {p.name: p for p in db.query(PlexPerson).all()}
assert set(rows) == {shared, "Alice Unique", "Bob Unique"} # exactly one row per name
assert rows[shared].photo_thumb is not None # m2's photo back-filled m1's NULL