"""N01 to N05, the export worker and C07 consent enforcement.""" import httpx import pytest from sqlalchemy import select from app.core.config import get_settings from app.core.database import get_session_factory from app.integrations.storage import get_storage from app.jobs.exports import run_exports from app.modules.settings.models import ConsentEvent, ExportJob from tests.factories import create_session, make_account, session_body, upload from tests.helpers import register async def _events(account_id, category=None) -> list[tuple[str, str]]: async with get_session_factory()() as db: query = select(ConsentEvent.category, ConsentEvent.action).where(ConsentEvent.account_id == account_id) if category: query = query.where(ConsentEvent.category == category) return [tuple(r) for r in (await db.execute(query.order_by(ConsentEvent.created_at))).all()] async def test_get_defaults_without_creating_a_row(client): me = await register(client) response = await client.get("/v1/me/settings", headers=me["headers"]) assert response.status_code == 200 s = response.json()["settings"] assert s["coach_can_see_sessions"] is True and s["share_with_parent"] is False assert s["consented_at"] is None and s["consent_version"] is None and s["version"] == 1 assert s["parent_email"] is None and s["notify_weekly"] is True async def test_settings_require_auth(client): assert (await client.get("/v1/me/settings")).status_code == 401 assert (await client.patch("/v1/me/settings", json={"private_links": True})).status_code == 401 async def test_patch_updates_and_bumps_version(client): me = await register(client) h = me["headers"] response = await client.patch("/v1/me/settings", json={"private_links": True, "expected_version": 1}, headers=h) assert response.status_code == 200 s = response.json()["settings"] assert s["private_links"] is True and s["version"] == 2 again = (await client.get("/v1/me/settings", headers=h)).json()["settings"] assert again == s async def test_patch_stale_version(client): me = await register(client) h = me["headers"] await client.patch("/v1/me/settings", json={"notify_drills": False}, headers=h) response = await client.patch("/v1/me/settings", json={"notify_drills": True, "expected_version": 1}, headers=h) assert response.status_code == 409 and response.json()["error"]["code"] == "STALE_VERSION" async def test_patch_validation(client): h = (await register(client))["headers"] assert (await client.patch("/v1/me/settings", json={}, headers=h)).status_code == 400 assert (await client.patch("/v1/me/settings", json={"private_links": "yes"}, headers=h)).status_code == 400 assert (await client.patch("/v1/me/settings", json={"private_links": None}, headers=h)).status_code == 400 assert (await client.patch("/v1/me/settings", json={"version": 3}, headers=h)).status_code == 400 assert (await client.patch("/v1/me/settings", json={"parent_email": "nope"}, headers=h)).status_code == 400 async def test_auto_report_needs_sharing_and_email(client): h = (await register(client))["headers"] response = await client.patch("/v1/me/settings", json={"auto_monthly_report": True}, headers=h) assert response.status_code == 422 response = await client.patch( "/v1/me/settings", json={"share_with_parent": True, "auto_monthly_report": True}, headers=h) assert response.status_code == 422 response = await client.patch( "/v1/me/settings", json={"share_with_parent": True, "parent_email": "Mum@Example.com", "auto_monthly_report": True}, headers=h) assert response.status_code == 200 s = response.json()["settings"] assert s["parent_email"] == "mum@example.com" and s["auto_monthly_report"] is True off = await client.patch("/v1/me/settings", json={"share_with_parent": False}, headers=h) assert off.json()["settings"]["auto_monthly_report"] is False async def test_opt_ins_are_recorded_as_consent_events(client): me = await register(client) h = me["headers"] await client.patch("/v1/me/settings", json={"help_improve_ai": True, "clips_as_examples": True}, headers=h) await client.patch("/v1/me/settings", json={"help_improve_ai": True}, headers=h) # unchanged: no event await client.patch("/v1/me/settings", json={"help_improve_ai": False}, headers=h) account_id = me["user"]["id"] assert await _events(account_id, "help_improve_ai") == [("help_improve_ai", "accepted"), ("help_improve_ai", "withdrawn")] assert await _events(account_id, "clips_as_examples") == [("clips_as_examples", "accepted")] # the opt-ins never count as analysis consent assert (await client.get("/v1/me/settings", headers=h)).json()["settings"]["consented_at"] is None async def test_consent_accept_and_withdraw(client): me = await register(client) h = me["headers"] response = await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=h) assert response.status_code == 201 consent = response.json()["consent"] assert consent["version"] == "1.0" and consent["withdrawn_at"] is None s = (await client.get("/v1/me/settings", headers=h)).json()["settings"] assert s["consent_version"] == "1.0" and s["consented_at"] == consent["accepted_at"] assert (await client.delete("/v1/me/consent", headers=h)).status_code == 204 assert (await client.delete("/v1/me/consent", headers=h)).status_code == 204 # repeat is a no-op s = (await client.get("/v1/me/settings", headers=h)).json()["settings"] assert s["consented_at"] is None and s["consent_version"] is None assert [a for _, a in await _events(me["user"]["id"], "analysis")] == ["accepted", "withdrawn"] async def test_consent_withdraw_without_acceptance_is_noop(client): me = await register(client) assert (await client.delete("/v1/me/consent", headers=me["headers"])).status_code == 204 assert await _events(me["user"]["id"]) == [] async def test_consent_errors(client): h = (await register(client))["headers"] stale = await client.post("/v1/me/consent", json={"version": "0.1", "accepted": True}, headers=h) assert stale.status_code == 409 and stale.json()["error"]["code"] == "TERMS_CHANGED" for body in ({"version": "1.0", "accepted": False}, {"version": "1.0"}, {"accepted": True}): assert (await client.post("/v1/me/consent", json=body, headers=h)).status_code == 400 assert (await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True})).status_code == 401 assert (await client.delete("/v1/me/consent")).status_code == 401 async def test_consent_idempotent(client): me = await register(client) h = {**me["headers"], "Idempotency-Key": "k1"} body = {"version": "1.0", "accepted": True} first = await client.post("/v1/me/consent", json=body, headers=h) second = await client.post("/v1/me/consent", json=body, headers=h) assert first.status_code == second.status_code == 201 and first.json() == second.json() assert len(await _events(me["user"]["id"], "analysis")) == 1 other = await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=me["headers"]) assert other.json() == first.json() # already accepted: no second event assert len(await _events(me["user"]["id"], "analysis")) == 1 # ---------- exports ---------- class FakeEmail: def __init__(self, fail: bool = False): self.sent: list[tuple[str, str, str]] = [] self.fail = fail async def send(self, to: str, subject: str, text: str) -> None: if self.fail: raise RuntimeError("down") self.sent.append((to, subject, text)) async def _run_exports(email: FakeEmail) -> dict: async with get_session_factory()() as db: return await run_exports(db, get_storage(), email) async def test_export_request_and_worker(client): me = await register(client) h = me["headers"] session = await create_session(client, h) gone = await create_session(client, h) await client.delete(f"/v1/sessions/{gone['id']}", headers=h) response = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=h) assert response.status_code == 202 export = response.json()["export"] assert export["status"] == "queued" and export["delivery"] == "account_email" dup = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=h) assert dup.status_code == 409 and dup.json()["error"]["code"] == "EXPORT_IN_PROGRESS" email = FakeEmail() assert await _run_exports(email) == {"ready": 1, "failed": 0} (to, _, text), = email.sent assert to.endswith("@example.com") and text.count("http") == 1 and session["id"] async with get_session_factory()() as db: job = await db.get(ExportJob, __import__("uuid").UUID(export["id"])) assert job.status == "ready" and job.expires_at is not None assert await _run_exports(email) == {"ready": 0, "failed": 0} again = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=h) assert again.status_code == 202 async def test_export_worker_marks_failed(client): h = (await register(client))["headers"] await client.post("/v1/me/exports", json={"scope": "videos"}, headers=h) assert await _run_exports(FakeEmail(fail=True)) == {"ready": 0, "failed": 1} async with get_session_factory()() as db: job = (await db.scalars(select(ExportJob))).one() assert job.status == "failed" and job.error_code == "DELIVERY_FAILED" async def test_export_validation_auth_and_idempotency(client): me = await register(client) h = me["headers"] assert (await client.post("/v1/me/exports", json={"scope": "consent"}, headers=h)).status_code == 400 assert (await client.post("/v1/me/exports", json={}, headers=h)).status_code == 400 assert (await client.post("/v1/me/exports", json={"scope": "videos"})).status_code == 401 keyed = {**h, "Idempotency-Key": "e1"} first = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=keyed) second = await client.post("/v1/me/exports", json={"scope": "videos"}, headers=keyed) assert first.status_code == second.status_code == 202 and first.json() == second.json() # ---------- C07 ---------- async def _post_session(client, headers) -> httpx.Response: video = await upload(client, headers, "video") thumb = await upload(client, headers, "thumbnail") return await client.post("/v1/sessions", json=session_body(video, thumb), headers=headers) async def test_withdrawn_consent_blocks_new_analysis(client): me = await register(client) h = me["headers"] assert (await _post_session(client, h)).status_code == 201 # no event, consent not required await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=h) assert (await _post_session(client, h)).status_code == 201 await client.delete("/v1/me/consent", headers=h) blocked = await _post_session(client, h) assert blocked.status_code == 403 and blocked.json()["error"]["code"] == "CONSENT_REQUIRED" # saved sessions stay readable assert (await client.get("/v1/sessions", headers=h)).status_code == 200 await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=h) assert (await _post_session(client, h)).status_code == 201 async def test_required_consent_blocks_without_acceptance(client, monkeypatch): monkeypatch.setenv("REQUIRE_ANALYSIS_CONSENT", "true") get_settings.cache_clear() try: h = (await register(client))["headers"] blocked = await _post_session(client, h) assert blocked.status_code == 403 and blocked.json()["error"]["code"] == "CONSENT_REQUIRED" await client.post("/v1/me/consent", json={"version": "1.0", "accepted": True}, headers=h) assert (await _post_session(client, h)).status_code == 201 finally: monkeypatch.undo() get_settings.cache_clear() @pytest.mark.parametrize("role", ["player", "coach"]) async def test_settings_for_both_roles(client, role): account = await make_account(role) assert (await client.get("/v1/me/settings", headers=account["headers"])).status_code == 200