Deploy Development / deploy (push) Successful in 53s
Test Suite / pytest-backend (push) Failing after 29s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 16s
Test Suite / k6 /health Baseline (push) Successful in 35s
Test Suite / playwright-tests (push) Failing after 7m42s
The exercise list turns the live catalog on or off for the caller's edit rights. A distribution key reads that current selection and the changes since its last cursor. Co-authored-by: Cursor <cursoragent@cursor.com>
395 lines
14 KiB
Python
395 lines
14 KiB
Python
"""Vertrag v1, Referenzfall, Rollen und Bestätigung nach Rückzug."""
|
|
from __future__ import annotations
|
|
|
|
import inspect
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
import pytest
|
|
from fastapi import HTTPException
|
|
from fastapi.testclient import TestClient
|
|
|
|
os.environ.setdefault("SKIP_DB_MIGRATE", "1")
|
|
|
|
from auth import require_auth
|
|
from distribution_service import _lock_recipient, release_keys_for_exercise
|
|
from distribution_contract import (
|
|
InvalidCursor,
|
|
actions_cover,
|
|
cursor_secret,
|
|
decide_confirm,
|
|
decode_cursor,
|
|
encode_cursor,
|
|
exercise_offerable,
|
|
package_state,
|
|
scope_denial,
|
|
manifest_bytes,
|
|
official_write_allowed,
|
|
plan_available,
|
|
rate_decision,
|
|
catalog_available,
|
|
catalog_changes,
|
|
catalog_document,
|
|
catalog_hash,
|
|
changed_areas,
|
|
release_denial,
|
|
retrievable_release_ids,
|
|
sha256_bytes,
|
|
)
|
|
from main import app
|
|
from routers.exercises import _assert_can_edit_exercise
|
|
from tenant_context import TenantContext, get_tenant_context
|
|
|
|
FIXTURE = json.loads(
|
|
(Path(__file__).resolve().parents[2] / "docs" / "architecture" / "distribution" / "Shinkan_Lara_Felix_Referenzfall_v1.json").read_text(
|
|
encoding="utf-8"
|
|
)
|
|
)
|
|
|
|
|
|
def test_fixture_manifest_hashes_match_contract_order() -> None:
|
|
for release in FIXTURE["releases"].values():
|
|
body = manifest_bytes(release["manifest"])
|
|
assert sha256_bytes(body) == release["manifest_sha256"]
|
|
assert not body.endswith(b"\n")
|
|
|
|
|
|
def test_reference_case_retrieval_and_plan_effect() -> None:
|
|
lara_events = FIXTURE["channels"]["lara_felix"]["events"]
|
|
second_events = FIXTURE["channels"]["zweiter_verein"]["events"]
|
|
assert retrievable_release_ids(lara_events) == set(FIXTURE["expected"]["lara_felix_can_retrieve_after_withdrawal"])
|
|
assert retrievable_release_ids(second_events) == set(FIXTURE["expected"]["zweiter_verein_can_retrieve"])
|
|
manifests = {item["manifest"]["release_id"]: item["manifest"] for item in FIXTURE["releases"].values()}
|
|
blocked = []
|
|
available = []
|
|
for name, plan in FIXTURE["plans"].items():
|
|
if plan_available(plan, manifests[plan["release_id"]], lara_events):
|
|
available.append(name)
|
|
else:
|
|
blocked.append(name)
|
|
assert set(blocked) == set(FIXTURE["expected"]["blocked_plans_after_withdrawal"])
|
|
assert set(available) == set(FIXTURE["expected"]["available_plans_after_withdrawal"])
|
|
film_actions = FIXTURE["releases"]["vereinsfassung_1"]["manifest"]["rights"][1]["actions"]
|
|
assert actions_cover(film_actions, ["stream", "course_display", "commercial_course_use"]) is FIXTURE["expected"]["course_film_allowed"]
|
|
assert ("download" in film_actions) is FIXTURE["expected"]["film_download_allowed"]
|
|
|
|
|
|
def test_replay_keeps_release_id_and_explicit_reconfirm_mints_a_new_one() -> None:
|
|
drafts: dict[str, str] = {}
|
|
releases: dict[str, dict] = {}
|
|
events: list[tuple[str, str]] = []
|
|
|
|
def confirm(draft_id: str, revision: int, cut: str) -> tuple[str, bool]:
|
|
release_id, created = decide_confirm(drafts.get(draft_id), f"rel-{len(releases) + 1}")
|
|
if created:
|
|
drafts[draft_id] = release_id
|
|
releases[release_id] = {"withdrawn": False, "revision": revision, "cut": cut}
|
|
events.append(("published", release_id))
|
|
return release_id, created
|
|
|
|
first, created = confirm("draft-1", 1, "same-cut")
|
|
again, replayed = confirm("draft-1", 1, "same-cut")
|
|
assert first == again
|
|
assert created is True
|
|
assert replayed is False
|
|
assert events == [("published", first)]
|
|
|
|
releases[first]["withdrawn"] = True
|
|
second, created_again = confirm("draft-2", 1, "same-cut")
|
|
assert created_again is True
|
|
assert second != first
|
|
assert releases[first]["withdrawn"] is True
|
|
assert releases[second]["revision"] == 1
|
|
assert releases[second]["cut"] == "same-cut"
|
|
assert [kind for kind, _ in events] == ["published", "published"]
|
|
|
|
|
|
def test_key_scope_follows_the_role_context() -> None:
|
|
assert scope_denial("user", ["exercise"], ["official", "club", "private"]) is None
|
|
assert scope_denial("personal", ["exercise"], ["private"]) is None
|
|
assert scope_denial("personal", ["exercise"], ["official"])
|
|
assert scope_denial("club", ["exercise", "framework"], ["club", "private"]) is None
|
|
assert scope_denial("club", ["exercise"], ["official"])
|
|
assert scope_denial("platform", ["training_plan"], ["official", "private"]) is None
|
|
assert scope_denial("platform", [], ["official"])
|
|
|
|
|
|
def test_availability_keeps_the_copy_and_stops_new_offers() -> None:
|
|
assert package_state(fetch_blocked=False, retired=False) == "available"
|
|
assert package_state(fetch_blocked=False, retired=True) == "retired"
|
|
assert package_state(fetch_blocked=True, retired=True) == "withdrawn"
|
|
status, offerable = exercise_offerable("approved", ["available"])
|
|
assert status == "approved" and offerable is True
|
|
status, offerable = exercise_offerable("archived", ["available"])
|
|
assert status == "archived" and offerable is False
|
|
status, offerable = exercise_offerable(None, ["withdrawn"])
|
|
assert status == "deleted" and offerable is False
|
|
status, offerable = exercise_offerable("approved", ["retired", "withdrawn"])
|
|
assert offerable is False
|
|
|
|
|
|
def test_cursor_is_bound_to_recipient() -> None:
|
|
secret = cursor_secret()
|
|
token = encode_cursor(secret, "recipient-a", 4)
|
|
assert decode_cursor(secret, "recipient-a", token) == 4
|
|
assert decode_cursor(secret, "recipient-a", None) == 0
|
|
with pytest.raises(InvalidCursor):
|
|
decode_cursor(secret, "recipient-b", token)
|
|
|
|
|
|
def test_rate_window_blocks_at_sixty() -> None:
|
|
hits, blocked = rate_decision(59, 10)
|
|
assert hits == 60 and blocked is False
|
|
hits, blocked = rate_decision(60, 10)
|
|
assert blocked is True
|
|
hits, blocked = rate_decision(60, 61)
|
|
assert hits == 1 and blocked is False
|
|
|
|
|
|
def test_official_release_and_edit_roles() -> None:
|
|
assert official_write_allowed("official", "superadmin") is True
|
|
assert official_write_allowed("official", "admin") is False
|
|
assert official_write_allowed("official", "club_admin") is False
|
|
assert official_write_allowed("club", "admin") is True
|
|
assert release_denial(
|
|
visibility="official",
|
|
role="admin",
|
|
publisher_kind="platform",
|
|
is_owner=True,
|
|
is_club_admin=False,
|
|
)
|
|
assert release_denial(
|
|
visibility="official",
|
|
role="superadmin",
|
|
publisher_kind="platform",
|
|
is_owner=False,
|
|
is_club_admin=False,
|
|
) is None
|
|
assert release_denial(
|
|
visibility="private",
|
|
role="trainer",
|
|
publisher_kind="own",
|
|
is_owner=True,
|
|
is_club_admin=False,
|
|
) is None
|
|
assert release_denial(
|
|
visibility="private",
|
|
role="admin",
|
|
publisher_kind="own",
|
|
is_owner=False,
|
|
is_club_admin=False,
|
|
)
|
|
assert release_denial(
|
|
visibility="club",
|
|
role="trainer",
|
|
publisher_kind="club",
|
|
is_owner=True,
|
|
is_club_admin=False,
|
|
publisher_club_id=4,
|
|
exercise_club_id=4,
|
|
)
|
|
assert release_denial(
|
|
visibility="club",
|
|
role="trainer",
|
|
publisher_kind="club",
|
|
is_owner=False,
|
|
is_club_admin=True,
|
|
publisher_club_id=4,
|
|
exercise_club_id=4,
|
|
) is None
|
|
assert release_denial(
|
|
visibility="club",
|
|
role="trainer",
|
|
publisher_kind="club",
|
|
is_owner=False,
|
|
is_club_admin=True,
|
|
publisher_club_id=9,
|
|
exercise_club_id=4,
|
|
)
|
|
|
|
|
|
def _tenant(role: str, profile_id: int = 7) -> TenantContext:
|
|
return TenantContext(
|
|
profile_id=profile_id,
|
|
global_role=role,
|
|
effective_club_id=None,
|
|
club_ids=frozenset(),
|
|
memberships=[],
|
|
)
|
|
|
|
|
|
def test_assert_edit_rejects_admin_and_club_role_for_official() -> None:
|
|
cur = MagicMock()
|
|
cur.fetchone.return_value = {"created_by": 7, "visibility": "official", "club_id": None}
|
|
for role in ("admin", "trainer", "club_admin"):
|
|
with pytest.raises(HTTPException) as caught:
|
|
_assert_can_edit_exercise(cur, 3, _tenant(role))
|
|
assert caught.value.status_code == 403
|
|
_assert_can_edit_exercise(cur, 3, _tenant("superadmin", profile_id=1))
|
|
|
|
|
|
@pytest.fixture
|
|
def client() -> TestClient:
|
|
return TestClient(app)
|
|
|
|
|
|
def test_distribution_read_is_hidden_while_disabled(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.delenv("DISTRIBUTION_ENABLED", raising=False)
|
|
response = client.get("/api/distribution/v1/changes", headers={"Authorization": "Bearer shk.abc.def"})
|
|
assert response.status_code == 404
|
|
assert response.headers.get("cache-control") == "private, no-store"
|
|
|
|
|
|
class _DroppingCursor:
|
|
"""Ein neues execute verwirft ein noch nicht gelesenes Ergebnis, wie psycopg2."""
|
|
|
|
def __init__(self, key: dict) -> None:
|
|
self._key = key
|
|
self._pending = None
|
|
|
|
def execute(self, sql, _params=None):
|
|
if self._pending is not None:
|
|
raise AssertionError("Ergebnis wurde vor dem Lesen überschrieben")
|
|
self._pending = [self._key] if "FROM distribution_keys" in sql else []
|
|
|
|
def fetchall(self):
|
|
rows = self._pending
|
|
self._pending = None
|
|
return rows or []
|
|
|
|
def fetchone(self):
|
|
rows = self.fetchall()
|
|
return rows[0] if rows else None
|
|
|
|
|
|
def test_release_screen_keeps_the_application_key() -> None:
|
|
key = {
|
|
"id": "key-1",
|
|
"label": "Lara",
|
|
"context_kind": "user",
|
|
"context_club_id": None,
|
|
"context_profile_id": 7,
|
|
"club_ids": [3],
|
|
"recipient_id": "rec-1",
|
|
"api_enabled": True,
|
|
}
|
|
cur = _DroppingCursor(key)
|
|
keys, block = release_keys_for_exercise(
|
|
cur,
|
|
{"visibility": "official", "club_id": None, "created_by": 7},
|
|
7,
|
|
"superadmin",
|
|
)
|
|
assert block is None
|
|
assert [item["label"] for item in keys] == ["Lara"]
|
|
|
|
|
|
def _catalog_exercise() -> dict:
|
|
return {
|
|
"public_id": "11111111-1111-1111-1111-111111111111",
|
|
"title": "Stand",
|
|
"summary": "",
|
|
"goal": "Sehen",
|
|
"execution": "Weg",
|
|
"preparation": "",
|
|
"trainer_notes": "",
|
|
"equipment": None,
|
|
"duration_min": None,
|
|
"duration_max": None,
|
|
}
|
|
|
|
|
|
def test_catalog_reports_variant_and_media_order_changes() -> None:
|
|
exercise = _catalog_exercise()
|
|
base_variant = [{"id": 1, "public_id": "var-1", "variant_name": "Karte", "description": "", "execution_changes": "Alt", "sequence_order": 1}]
|
|
base_media = [
|
|
{"id": 1, "public_id": "med-1", "media_type": "image", "title": "A", "sort_order": 1},
|
|
{"id": 2, "public_id": "med-2", "media_type": "image", "title": "B", "sort_order": 2},
|
|
]
|
|
original = catalog_hash(catalog_document(exercise, base_variant, base_media))
|
|
changed_variant = [{**base_variant[0], "execution_changes": "Neu"}]
|
|
reordered = [base_media[1] | {"sort_order": 1}, base_media[0] | {"sort_order": 2}]
|
|
assert catalog_hash(catalog_document(exercise, changed_variant, base_media)) != original
|
|
assert catalog_hash(catalog_document(exercise, base_variant, reordered)) != original
|
|
assert catalog_hash(catalog_document(exercise, base_variant, base_media)) == original
|
|
source = exercise["public_id"]
|
|
assert catalog_changes({source: original}, {source: original}) == []
|
|
updated = catalog_hash(catalog_document(exercise, changed_variant, base_media))
|
|
assert catalog_changes({source: original}, {source: updated}) == [
|
|
{"source_id": source, "change": "updated", "content_hash": updated}
|
|
]
|
|
assert catalog_changes({source: original}, {}) == [{"source_id": source, "change": "removed"}]
|
|
assert catalog_changes({}, {source: original}) == [
|
|
{"source_id": source, "change": "added", "content_hash": original}
|
|
]
|
|
|
|
|
|
def test_catalog_hides_unselected_and_out_of_scope_exercises() -> None:
|
|
assert catalog_available(True, True) is True
|
|
assert catalog_available(False, True) is False
|
|
assert catalog_available(True, False) is False
|
|
|
|
|
|
def test_changed_areas_names_the_edited_instruction() -> None:
|
|
exercise = {
|
|
"title": "Stand",
|
|
"summary": "",
|
|
"goal": "Sehen",
|
|
"execution": "Neuer Weg",
|
|
"preparation": "",
|
|
"trainer_notes": "",
|
|
"equipment": None,
|
|
"duration_min": None,
|
|
"duration_max": None,
|
|
}
|
|
manifest = {
|
|
"exercise": {
|
|
"title": "Stand",
|
|
"summary": None,
|
|
"parts": [
|
|
{"role": "goal", "text": "Sehen"},
|
|
{"role": "instructions", "text": "Alter Weg"},
|
|
],
|
|
"variants": [{"id": "v", "label": "Standard"}],
|
|
"assets": [],
|
|
}
|
|
}
|
|
assert changed_areas(exercise, [], [], manifest) == ["Durchführung"]
|
|
exercise["execution"] = "Alter Weg"
|
|
assert changed_areas(exercise, [], [], manifest) == []
|
|
|
|
|
|
def test_channel_sequence_is_locked() -> None:
|
|
assert "FOR UPDATE" in inspect.getsource(_lock_recipient)
|
|
|
|
|
|
def test_variant_and_media_routes_reject_admin_on_official(client: TestClient) -> None:
|
|
app.dependency_overrides[require_auth] = lambda: {"profile_id": 4, "role": "admin"}
|
|
app.dependency_overrides[get_tenant_context] = lambda: _tenant("admin", 4)
|
|
mock_cur = MagicMock()
|
|
mock_cur.fetchone.return_value = {"created_by": 4, "visibility": "official", "club_id": None}
|
|
mock_cm = MagicMock()
|
|
mock_cm.__enter__.return_value = MagicMock()
|
|
mock_cm.__exit__.return_value = False
|
|
try:
|
|
with patch("routers.exercises.get_db", return_value=mock_cm), patch(
|
|
"routers.exercises.get_cursor", return_value=mock_cur
|
|
):
|
|
variant = client.post(
|
|
"/api/exercises/9/variants",
|
|
headers={"X-Auth-Token": "t"},
|
|
json={"variant_name": "Kartenweg"},
|
|
)
|
|
media = client.post(
|
|
"/api/exercises/9/media/from-asset",
|
|
headers={"X-Auth-Token": "t"},
|
|
json={"media_asset_id": 3},
|
|
)
|
|
assert variant.status_code == 403
|
|
assert media.status_code == 403
|
|
finally:
|
|
app.dependency_overrides.pop(require_auth, None)
|
|
app.dependency_overrides.pop(get_tenant_context, None)
|