mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-12-06 07:55:10 +00:00
168 lines
7.1 KiB
Python
168 lines
7.1 KiB
Python
"""Unit tests for unshackle.core.api.session_store.SessionStore."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import threading
|
|
import time
|
|
from datetime import UTC, datetime, timedelta
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
from unshackle.core.api import session_store as session_store_module
|
|
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
|
|
from unshackle.core.api.session_store import SessionEntry, SessionStore
|
|
from unshackle.core.remote_protocol import AuthStatus
|
|
|
|
pytestmark = pytest.mark.unit
|
|
|
|
|
|
class _FakeService:
|
|
"""Minimal stub Service used to fill SessionEntry.service_instance."""
|
|
|
|
def __init__(self, tag: str = "TEST") -> None:
|
|
self.tag = tag
|
|
|
|
|
|
@pytest.fixture
|
|
def store() -> SessionStore:
|
|
return SessionStore()
|
|
|
|
|
|
async def test_delete_removes_and_cancels_bridge(store: SessionStore) -> None:
|
|
entry = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge())
|
|
|
|
deleted = await store.delete(entry.session_id)
|
|
assert deleted is True
|
|
with pytest.raises(RuntimeError, match="cancelled"):
|
|
entry.input_bridge.ensure_active()
|
|
assert entry.channel.ended
|
|
assert entry.auth_status is AuthStatus.AUTHENTICATING # the delete event reports the login state as it was
|
|
assert store.session_count == 0
|
|
|
|
|
|
@pytest.mark.parametrize("via", ["get", "sweep"])
|
|
@pytest.mark.parametrize(
|
|
("ttl", "status", "idle", "expires"),
|
|
[
|
|
(300, AuthStatus.AUTHENTICATING, 301, False),
|
|
(300, AuthStatus.AUTHENTICATING, AUTH_INPUT_TIMEOUT + 1, True),
|
|
(300, AuthStatus.AUTHENTICATED, 301, True),
|
|
(900, AuthStatus.AUTHENTICATING, AUTH_INPUT_TIMEOUT + 1, False),
|
|
(900, AuthStatus.AUTHENTICATING, 901, True),
|
|
(900, AuthStatus.AUTHENTICATED, AUTH_INPUT_TIMEOUT + 1, False),
|
|
(900, AuthStatus.AUTHENTICATED, 901, True),
|
|
],
|
|
)
|
|
async def test_get_and_the_sweep_share_one_expiry_rule(
|
|
store: SessionStore,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
via: str,
|
|
ttl: int,
|
|
status: AuthStatus,
|
|
idle: float,
|
|
expires: bool,
|
|
) -> None:
|
|
"""A login that still runs gets max(ttl, AUTH_INPUT_TIMEOUT), never less than an idle authenticated session."""
|
|
monkeypatch.setattr(type(store), "ttl", property(lambda _: ttl))
|
|
bridge = InputBridge()
|
|
bridge.login_status = status
|
|
entry = await store.create("EXAMPLE", _FakeService(), session_id="s", input_bridge=bridge)
|
|
entry.idle_since = time.monotonic() - idle
|
|
|
|
if via == "get":
|
|
assert (await store.get("s") is None) is expires
|
|
else:
|
|
assert await store.cleanup_expired() == int(expires)
|
|
assert store.session_count == int(not expires)
|
|
|
|
|
|
@pytest.mark.parametrize("step", [1, -1], ids=["forward", "back"])
|
|
@pytest.mark.parametrize("idle", [0, 1], ids=["active", "idle"])
|
|
async def test_a_step_of_the_wall_clock_changes_no_expiry(
|
|
store: SessionStore, monkeypatch: pytest.MonkeyPatch, step: int, idle: int
|
|
) -> None:
|
|
entry = await store.create("EXAMPLE", _FakeService(), session_id="s")
|
|
entry.idle_since -= idle * (store.ttl + 100)
|
|
stepped = datetime.now(UTC) + timedelta(seconds=step * 2 * (store.ttl + 100))
|
|
monkeypatch.setattr(session_store_module, "datetime", SimpleNamespace(now=lambda tz: stepped))
|
|
|
|
assert entry.summary()["idle_seconds"] // (store.ttl + 100) == idle
|
|
assert await store.cleanup_expired() == idle
|
|
assert await store.get("s") is (None if idle else entry)
|
|
|
|
|
|
async def test_session_with_work_in_progress_does_not_expire(store: SessionStore) -> None:
|
|
"""A request that holds the lock for longer than the TTL keeps its session and cache directory."""
|
|
entry = await store.create("EXAMPLE", _FakeService(), session_id="busy")
|
|
entry.idle_since = time.monotonic() - store.ttl - 100
|
|
async with entry.lock:
|
|
assert await store.cleanup_expired() == 0
|
|
assert await store.get("busy") is entry
|
|
|
|
|
|
async def test_close_ends_every_session_and_removes_its_cache_dir(
|
|
store: SessionStore, monkeypatch: pytest.MonkeyPatch
|
|
) -> None:
|
|
"""A shutdown ends each session without a delete event or a staged service reload."""
|
|
removed: list = []
|
|
published: list = []
|
|
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
|
|
monkeypatch.setattr(session_store_module, "_publish", lambda *a, **k: published.append(a))
|
|
monkeypatch.setattr(session_store_module, "_schedule_pending_reload", lambda tag: published.append(tag))
|
|
a = await store.create("EXAMPLE", _FakeService(), input_bridge=InputBridge(), cache_tag="_sessions/k/s/EXAMPLE")
|
|
b = await store.create("OTHER", _FakeService(), input_bridge=InputBridge())
|
|
published.clear()
|
|
|
|
await store.close()
|
|
for entry in (a, b):
|
|
with pytest.raises(RuntimeError, match="cancelled"):
|
|
entry.input_bridge.ensure_active()
|
|
assert entry.channel.ended
|
|
assert removed == [a.cache_tag, None]
|
|
assert store.session_count == 0
|
|
assert published == []
|
|
|
|
|
|
async def test_get_expiry_removes_cache_dir(store: SessionStore, monkeypatch: pytest.MonkeyPatch) -> None:
|
|
removed: list = []
|
|
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
|
|
entry = await store.create("EXAMPLE", _FakeService())
|
|
entry.cache_tag = "_sessions/k/s/EXAMPLE"
|
|
entry.idle_since = time.monotonic() - store.ttl - 100
|
|
assert await store.get(entry.session_id) is None
|
|
assert removed == ["_sessions/k/s/EXAMPLE"]
|
|
|
|
|
|
def test_the_login_state_is_the_one_its_bridge_holds(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
"""A waiting prompt keeps the session authenticating; the bridge alone moves it to authenticated or failed."""
|
|
entry = SessionEntry("s", "EXAMPLE", None, input_bridge=InputBridge())
|
|
bridge = entry.input_bridge
|
|
assert bridge.channel is entry.channel
|
|
offered = threading.Event()
|
|
monkeypatch.setattr(entry.channel, "offer", lambda ask: offered.set() or False)
|
|
answers: list[str] = []
|
|
worker = threading.Thread(target=lambda: answers.append(bridge.request_input("Code?")))
|
|
worker.start()
|
|
assert offered.wait(5)
|
|
assert bridge.get_pending_ask().prompt == "Code?"
|
|
assert entry.auth_status is AuthStatus.AUTHENTICATING
|
|
assert bridge.submit_response("1234")
|
|
worker.join(5)
|
|
assert answers == ["1234"]
|
|
|
|
bridge.login_status = AuthStatus.AUTHENTICATED
|
|
assert entry.summary()["auth_status"] == "authenticated"
|
|
bridge.login_status = AuthStatus.FAILED
|
|
assert entry.summary()["auth_status"] == "failed"
|
|
assert SessionEntry("s", "EXAMPLE", None).auth_status is AuthStatus.AUTHENTICATED
|
|
|
|
|
|
def test_add_tracks_registers_every_track_of_a_title() -> None:
|
|
entry = SessionEntry("s", "EXAMPLE", None)
|
|
video, audio, subtitle, other = (SimpleNamespace(id=i) for i in ("v", "a", "s", "o"))
|
|
entry.add_tracks("t1", SimpleNamespace(videos=[video], audio=[audio], subtitles=[subtitle])) # type: ignore[arg-type]
|
|
entry.add_tracks("t2", SimpleNamespace(videos=[other], audio=[], subtitles=[])) # type: ignore[arg-type]
|
|
assert entry.tracks == {"v": video, "a": audio, "s": subtitle, "o": other}
|
|
assert entry.tracks_by_title == {"t1": {"v": video, "a": audio, "s": subtitle}, "t2": {"o": other}}
|