forked from kenzuya/unshackle
test: delete slow, timing-based and redundant tests
This commit is contained in:
@@ -6,27 +6,22 @@ The clients are real ones, and the silence is a moved clock: the limits are the
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import math
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from collections.abc import Callable, Iterator
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
from threading import Event
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
import pytest
|
||||
import requests
|
||||
from aiohttp import web
|
||||
|
||||
from tests.remote.unit.test_remote_loopback import server # noqa: F401
|
||||
from tests.remote.unit.test_remote_loopback import (
|
||||
KEY,
|
||||
OTHER_KEY,
|
||||
StubService,
|
||||
make_client,
|
||||
on_loop,
|
||||
)
|
||||
@@ -43,28 +38,21 @@ from tests.remote.unit.test_session_lifetime import ( # noqa: F401
|
||||
from tests.remote.unit.test_tunnel import wait_until
|
||||
from unshackle.core.api import session_store
|
||||
from unshackle.core.api.client_presence import (
|
||||
AWAY_LIMIT,
|
||||
FIRST_CONTACT_LIMIT,
|
||||
LEFT_LIMIT,
|
||||
ClientPresence,
|
||||
ClientState,
|
||||
)
|
||||
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT, InputBridge
|
||||
from unshackle.core.api.session_store import SessionEntry, SessionStore
|
||||
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT
|
||||
from unshackle.core.api.session_store import SessionEntry
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.remote_channel import CDM_CLOSE_TIMEOUT, RECONNECT_DELAY, RECONNECT_MAX
|
||||
from unshackle.core.remote_lifetime import END_TIMEOUT
|
||||
from unshackle.core.remote_protocol import (
|
||||
CHANNEL_ROUTE,
|
||||
CHANNEL_SESSION_GONE,
|
||||
SESSION_CREATE_ROUTE,
|
||||
SESSION_ROUTE,
|
||||
TITLES_ROUTE,
|
||||
APIErrorCode,
|
||||
AuthStatus,
|
||||
)
|
||||
from unshackle.core.remote_service import RemoteError
|
||||
from unshackle.core.tunnel import HEARTBEAT
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -138,100 +126,6 @@ def killed(server: SimpleNamespace, client: Start) -> Callable[[], SessionEntry]
|
||||
return run
|
||||
|
||||
|
||||
def test_the_sweep_ends_the_session_of_a_killed_client_at_the_away_limit(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
killed: Callable[..., SessionEntry],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
assert session_store.SWEEP_INTERVAL <= 5
|
||||
monkeypatch.setattr(session_store, "SWEEP_INTERVAL", 0.02)
|
||||
entry = killed()
|
||||
directory = store_token(entry)
|
||||
on_loop(server, session_store.get_session_store().start_cleanup_loop())
|
||||
silent_for(entry, AWAY_LIMIT - 5)
|
||||
assert not wait_until(lambda: sessions() == [], 0.5)
|
||||
silent_for(entry, AWAY_LIMIT + 1)
|
||||
assert wait_until(lambda: sessions() == [] and not directory.exists(), DEADLINE)
|
||||
|
||||
|
||||
def test_the_login_of_a_killed_client_stops_at_the_away_limit(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
killed: Callable[..., SessionEntry],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
stopped = Event()
|
||||
|
||||
def wait_for_approval(stub: StubService, cookies: Any, credential: Any) -> None:
|
||||
try:
|
||||
while not stopped.wait(0.01):
|
||||
stub._input_bridge.ensure_active()
|
||||
finally:
|
||||
stopped.set()
|
||||
|
||||
monkeypatch.setattr(StubService, "authenticate", wait_for_approval)
|
||||
entry = killed(logs_in=False)
|
||||
assert not stopped.is_set()
|
||||
assert ends_after(server, entry, AWAY_LIMIT)
|
||||
assert stopped.wait(DEADLINE)
|
||||
assert wait_until(lambda: not session_store.get_session_store()._logins, DEADLINE)
|
||||
|
||||
|
||||
def test_a_request_of_a_killed_client_does_not_keep_its_session(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
killed: Callable[..., SessionEntry],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The request holds the lock, and its end is no sign of the client that asked for it."""
|
||||
release = Event()
|
||||
monkeypatch.setitem(StubService.hooks, "titles", lambda stub: release.wait(DEADLINE))
|
||||
events: list[str] = []
|
||||
monkeypatch.setattr(session_store, "_publish", lambda action, *a, **k: events.append(action))
|
||||
replies: list[Any] = []
|
||||
|
||||
def ask(entry: SessionEntry) -> None:
|
||||
replies.append(in_thread(lambda: get(server, TITLES_ROUTE, entry)))
|
||||
assert wait_until(entry.lock.locked, DEADLINE)
|
||||
|
||||
try:
|
||||
entry = killed(before=ask)
|
||||
assert entry.lock.locked()
|
||||
assert ends_after(server, entry, AWAY_LIMIT)
|
||||
with pytest.raises(RuntimeError, match="cancelled"):
|
||||
entry.input_bridge.ensure_active() # type: ignore[union-attr]
|
||||
finally:
|
||||
release.set()
|
||||
assert replies[0]().status_code == 200
|
||||
assert entry.presence.silence > AWAY_LIMIT
|
||||
assert events[-1] == "delete"
|
||||
|
||||
|
||||
def test_a_request_that_waits_for_the_lock_does_not_start_after_the_end(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
) -> None:
|
||||
release = Event()
|
||||
started: list[StubService] = []
|
||||
StubService.hooks["titles"] = lambda stub: (started.append(stub), release.wait(DEADLINE)) and None
|
||||
session_id = str(uuid.uuid4())
|
||||
assert create(server.url, session_id).status_code == 200
|
||||
(entry,) = sessions()
|
||||
assert logged_in(entry)
|
||||
entry.presence.attached()
|
||||
try:
|
||||
first = in_thread(lambda: get(server, TITLES_ROUTE, entry))
|
||||
assert wait_until(lambda: len(started) == 1, DEADLINE)
|
||||
second = in_thread(lambda: get(server, TITLES_ROUTE, entry))
|
||||
assert wait_until(lambda: bool(entry.lock._waiters), DEADLINE)
|
||||
on_loop(server, session_store.get_session_store().delete(session_id))
|
||||
finally:
|
||||
release.set()
|
||||
assert first().status_code == 200
|
||||
assert second().json()["error_code"] == APIErrorCode.SESSION_NOT_FOUND
|
||||
assert len(started) == 1
|
||||
|
||||
|
||||
def test_a_delete_after_the_close_of_the_channel_returns_the_login_cache(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
@@ -266,51 +160,6 @@ def test_a_session_ends_when_no_delete_follows_the_close_of_the_channel(
|
||||
service.close()
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def half_open_gateway(server: SimpleNamespace) -> Iterator[str]: # noqa: F811
|
||||
"""A gateway that passes the channel upgrade to the server, then drops it and answers the client 502."""
|
||||
|
||||
async def forward(request: web.Request) -> web.StreamResponse:
|
||||
async with aiohttp.ClientSession(auto_decompress=False) as http:
|
||||
headers = {k: v for k, v in request.headers.items() if k.startswith("X-") or k == "Content-Type"}
|
||||
if request.path.endswith("/channel"):
|
||||
async with http.ws_connect(server.url + request.path, headers=headers) as ws:
|
||||
await ws.receive()
|
||||
ws._response.connection.transport.abort() # type: ignore[union-attr]
|
||||
return web.Response(status=502)
|
||||
url, body = server.url + request.path_qs, await request.read()
|
||||
async with http.request(request.method, url, headers=headers, data=body) as reply:
|
||||
return web.Response(status=reply.status, body=await reply.read(), content_type="application/json")
|
||||
|
||||
async def start() -> web.AppRunner:
|
||||
app = web.Application()
|
||||
app.router.add_route("*", "/{path:.*}", forward)
|
||||
runner = web.AppRunner(app)
|
||||
await runner.setup()
|
||||
await web.TCPSite(runner, "127.0.0.1", 0).start()
|
||||
return runner
|
||||
|
||||
runner = on_loop(server, start())
|
||||
try:
|
||||
yield f"http://127.0.0.1:{runner.addresses[0][1]}"
|
||||
finally:
|
||||
on_loop(server, runner.cleanup())
|
||||
|
||||
|
||||
def test_a_refused_channel_upgrade_stops_the_client_with_one_line(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
) -> None:
|
||||
with half_open_gateway(server) as url:
|
||||
service = make_client(url)
|
||||
try:
|
||||
with pytest.raises(RemoteError, match=r"^The remote server at \S+ refused the session channel: HTTP 502$"):
|
||||
service.authenticate()
|
||||
finally:
|
||||
service.close()
|
||||
assert wait_until(lambda: sessions() == [], DEADLINE)
|
||||
|
||||
|
||||
Socket = aiohttp.ClientWebSocketResponse
|
||||
|
||||
|
||||
@@ -332,92 +181,6 @@ def channel(server: SimpleNamespace, logins: list[Any]) -> Callable[..., None]:
|
||||
return run
|
||||
|
||||
|
||||
async def close_code(socket: Socket) -> Any:
|
||||
"""Read until the server closes the socket; its close code."""
|
||||
while (msg := await socket.receive()).type is aiohttp.WSMsgType.TEXT:
|
||||
pass
|
||||
return msg.data
|
||||
|
||||
|
||||
async def a_state_is(entry: SessionEntry, state: ClientState) -> bool:
|
||||
return await asyncio.to_thread(state_is, entry, state)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("close", "state"),
|
||||
[
|
||||
(lambda ws: ws.close(code=1000), ClientState.LEFT),
|
||||
(lambda ws: ws.close(code=1001), ClientState.AWAY),
|
||||
(lambda ws: ws.send_frame(b"", aiohttp.WSMsgType.CLOSE), ClientState.AWAY),
|
||||
],
|
||||
ids=["1000", "1001", "no-code"],
|
||||
)
|
||||
def test_only_a_close_with_1000_of_the_client_is_a_leave(
|
||||
channel: Callable[..., None], close: Callable[[Socket], Any], state: ClientState
|
||||
) -> None:
|
||||
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
|
||||
socket = await connect()
|
||||
assert await a_state_is(entry, ClientState.PRESENT)
|
||||
await close(socket)
|
||||
assert await a_state_is(entry, state)
|
||||
await socket.close()
|
||||
|
||||
channel(check)
|
||||
|
||||
|
||||
def test_a_replaced_socket_does_not_mark_the_new_one_away(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
channel: Callable[..., None],
|
||||
) -> None:
|
||||
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
|
||||
first = await connect()
|
||||
assert await a_state_is(entry, ClientState.PRESENT)
|
||||
old = entry.channel.ws
|
||||
second = await connect()
|
||||
assert await close_code(first) == 1000
|
||||
await first.close()
|
||||
assert await asyncio.to_thread(wait_until, lambda: old is not None and old.close_code is not None, DEADLINE)
|
||||
assert entry.presence.state is ClientState.PRESENT
|
||||
assert await asyncio.to_thread(stays, server, entry)
|
||||
await second.close()
|
||||
assert await a_state_is(entry, ClientState.LEFT)
|
||||
|
||||
channel(check)
|
||||
|
||||
|
||||
def test_the_end_of_the_session_is_no_leave(server: SimpleNamespace, channel: Callable[..., None]) -> None: # noqa: F811
|
||||
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
|
||||
socket = await connect()
|
||||
assert await a_state_is(entry, ClientState.PRESENT)
|
||||
assert (await asyncio.to_thread(delete, server.url, entry.session_id)).ok
|
||||
assert await close_code(socket) == CHANNEL_SESSION_GONE
|
||||
assert await a_state_is(entry, ClientState.AWAY)
|
||||
|
||||
channel(check)
|
||||
|
||||
|
||||
def test_a_new_channel_or_a_request_after_the_leave_is_a_client_that_still_works(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
channel: Callable[..., None],
|
||||
) -> None:
|
||||
"""A client that gives up on a slow channel closes it with 1000, then opens a new one or sends a request."""
|
||||
|
||||
async def check(entry: SessionEntry, connect: Callable[[], Any]) -> None:
|
||||
await (await connect()).close()
|
||||
assert await a_state_is(entry, ClientState.LEFT)
|
||||
socket = await connect()
|
||||
assert await a_state_is(entry, ClientState.PRESENT)
|
||||
await socket.close()
|
||||
assert await a_state_is(entry, ClientState.LEFT)
|
||||
assert (await asyncio.to_thread(get, server, SESSION_ROUTE, entry, OTHER_KEY)).status_code == 403
|
||||
assert entry.presence.state is ClientState.LEFT
|
||||
assert (await asyncio.to_thread(get, server, SESSION_ROUTE, entry)).ok
|
||||
assert entry.presence.state is ClientState.AWAY
|
||||
assert await asyncio.to_thread(ends_after, server, entry, AWAY_LIMIT)
|
||||
|
||||
channel(check)
|
||||
|
||||
|
||||
def test_a_client_that_never_comes_back_for_its_session_loses_it(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
@@ -444,48 +207,3 @@ def test_a_client_without_the_session_channel_is_refused(
|
||||
assert titles.status_code == 426 and titles.json()["error_code"] == APIErrorCode.CLIENT_OUTDATED
|
||||
assert get(server, SESSION_ROUTE, entry).ok
|
||||
assert entry.presence.state is ClientState.AWAITED
|
||||
|
||||
|
||||
@pytest.mark.parametrize("busy", [False, True], ids=["idle", "busy"])
|
||||
@pytest.mark.parametrize("ttl_seconds", [30, 100, 300, 1200, 3600])
|
||||
async def test_no_session_stays_for_longer_than_its_ttl_lets_it(
|
||||
monkeypatch: pytest.MonkeyPatch, ttl_seconds: int, busy: bool
|
||||
) -> None:
|
||||
"""Work for a client keeps its session past a short TTL, as before, until the client is gone."""
|
||||
monkeypatch.setitem(config.serve, "session_ttl", ttl_seconds)
|
||||
store = SessionStore()
|
||||
entry = await store.create("EXAMPLE", None, input_bridge=InputBridge())
|
||||
entry.input_bridge.login_status = AuthStatus.AUTHENTICATED # type: ignore[union-attr]
|
||||
entry.presence.detached(left=False)
|
||||
if busy:
|
||||
await entry.lock.acquire()
|
||||
limit = max(180, ttl_seconds / 2) if busy else min(ttl_seconds, max(180, ttl_seconds / 2))
|
||||
for silence, count in ((limit - 5, 0), (limit + 1, 1)):
|
||||
silent_for(entry, silence)
|
||||
entry.idle_since = entry.presence.seen_at
|
||||
assert await store.cleanup_expired() == count
|
||||
|
||||
|
||||
def test_each_limit_is_longer_than_the_silence_of_a_client_that_still_works() -> None:
|
||||
"""The numbers of the client: a ping is lost, the DELETE is late, or the create reply never arrives."""
|
||||
detection = HEARTBEAT * 1.5
|
||||
delete_arrives = 5 + CDM_CLOSE_TIMEOUT + 3 * END_TIMEOUT
|
||||
reconnects = sum(min(RECONNECT_DELAY * 2**n, RECONNECT_MAX) for n in range(6))
|
||||
assert 120 + END_TIMEOUT < FIRST_CONTACT_LIMIT <= 150
|
||||
assert detection + reconnects < AWAY_LIMIT <= 180
|
||||
assert max(delete_arrives, reconnects) < LEFT_LIMIT <= 90
|
||||
|
||||
|
||||
def test_a_client_that_is_present_has_no_limit() -> None:
|
||||
presence = ClientPresence()
|
||||
presence.attached()
|
||||
assert presence.limit(TTL) == math.inf
|
||||
|
||||
|
||||
@pytest.mark.parametrize("left", [True, False])
|
||||
def test_the_loss_of_the_channel_restarts_the_clock(left: bool) -> None:
|
||||
presence = ClientPresence()
|
||||
presence.attached()
|
||||
presence.seen_at -= 10 * TTL
|
||||
presence.detached(left)
|
||||
assert presence.silence < 5 and not presence.gone(TTL)
|
||||
|
||||
Reference in New Issue
Block a user