forked from kenzuya/unshackle
test: delete slow, timing-based and redundant tests
This commit is contained in:
@@ -8,11 +8,8 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
import signal
|
||||
import time
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from threading import Event, Lock, Semaphore
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
@@ -20,25 +17,20 @@ import pytest
|
||||
import requests
|
||||
from aiohttp import web
|
||||
|
||||
from tests.remote.unit.test_process_exit import BOUND, lasting_sessions, posix, run, settings, wait_line # noqa: F401
|
||||
from tests.remote.process import BOUND, lasting_sessions, posix, run, settings, wait_line # noqa: F401
|
||||
from tests.remote.unit.test_remote_loopback import KEY, StubService, count, forget, make_client, server # noqa: F401
|
||||
from tests.remote.unit.test_session_lifetime import DEADLINE, error_code, in_thread, logins, sessions # noqa: F401
|
||||
from tests.remote.unit.test_tunnel import wait_until
|
||||
from unshackle.core.api import handlers, routes
|
||||
from unshackle.core.api import handlers
|
||||
from unshackle.core.api.errors import APIError
|
||||
from unshackle.core.api.handlers import (
|
||||
RelayStop,
|
||||
RemoteLease,
|
||||
RemoteLogin,
|
||||
close_remote_pool,
|
||||
end_remote_pool,
|
||||
end_reopening,
|
||||
setup_remote_service,
|
||||
)
|
||||
from unshackle.core.api.routes import setup_routes
|
||||
from unshackle.core.remote_protocol import (
|
||||
SESSION_ROUTE,
|
||||
TITLES_ROUTE,
|
||||
APIErrorCode,
|
||||
)
|
||||
|
||||
@@ -124,208 +116,10 @@ def ask(stub: StubService) -> None:
|
||||
stub._input_bridge.request_input("Enter the EXAMPLE code")
|
||||
|
||||
|
||||
def poll_a_device(stub: StubService) -> None:
|
||||
while True:
|
||||
stub._input_bridge.ensure_active()
|
||||
time.sleep(0.01)
|
||||
|
||||
|
||||
def lose_session(server: SimpleNamespace, stub: StubService) -> None: # noqa: F811
|
||||
for entry in sessions():
|
||||
forget(server, entry.session_id)
|
||||
stub._input_bridge.ensure_active()
|
||||
|
||||
|
||||
def nothing(stub: StubService) -> None:
|
||||
pass
|
||||
|
||||
|
||||
@posix
|
||||
@pytest.mark.parametrize(
|
||||
("server", "login", "titles"),
|
||||
[
|
||||
(True, ask, nothing),
|
||||
(True, poll_a_device, nothing),
|
||||
(True, nothing, ask),
|
||||
],
|
||||
ids=["prompt", "device", "prompt-after-login"],
|
||||
indirect=["server"],
|
||||
)
|
||||
def test_a_stop_ends_a_remote_login(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
relay: Relay,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
login: Callable[[StubService], None],
|
||||
titles: Callable[[StubService], None],
|
||||
) -> None:
|
||||
"""The login waits on the user, so nothing but the stop can end it, and its list call gets an answer."""
|
||||
monkeypatch.setattr(StubService, "authenticate", lambda self, cookies, credential: login(self))
|
||||
StubService.hooks["titles"] = titles
|
||||
reply = relay.list()
|
||||
assert wait_until(lambda: any(entry.channel.attached for entry in sessions()), DEADLINE)
|
||||
assert ask not in (login, titles) or wait_until(relay.asks, DEADLINE)
|
||||
relay.stop()
|
||||
relay.ended_well()
|
||||
assert (reply().status_code, error_code(reply())) == (409, APIErrorCode.SERVER_DRAINING)
|
||||
|
||||
|
||||
@posix
|
||||
def test_no_other_shutdown_hook_delays_the_end_of_a_login(
|
||||
run: Callable[..., Any], # noqa: F811
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
released = tmp_path / "released"
|
||||
relay = Relay(run, server.url, tmp_path / "relay", str(released))
|
||||
relay.list()
|
||||
assert wait_until(relay.asks, DEADLINE)
|
||||
relay.stop()
|
||||
assert wait_until(lambda: sessions() == [], DEADLINE)
|
||||
released.touch()
|
||||
relay.ended_well()
|
||||
|
||||
|
||||
@posix
|
||||
@pytest.mark.parametrize("in_flight", [False, True], ids=["idle", "in-flight"])
|
||||
def test_a_stop_ends_the_pooled_sessions_at_the_same_time(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
relay: Relay,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
in_flight: bool,
|
||||
) -> None:
|
||||
"""No DELETE is answered before the last one has arrived."""
|
||||
ids = ("example-1", "example-2", "example-3")
|
||||
started, release = Semaphore(0), Event()
|
||||
|
||||
def hold(stub: StubService) -> None:
|
||||
started.release()
|
||||
assert release.wait(DEADLINE), "the test did not release the titles"
|
||||
|
||||
if in_flight:
|
||||
StubService.hooks["titles"] = hold
|
||||
replies = [relay.list(title=title) for title in ids]
|
||||
for reply in replies:
|
||||
assert started.acquire(timeout=DEADLINE) if in_flight else reply().status_code == 200
|
||||
assert len(sessions()) == len(ids)
|
||||
together = asyncio.Barrier(len(ids))
|
||||
handler = routes.session_delete_handler
|
||||
|
||||
async def held(session_id: str, request: Any) -> Any:
|
||||
await asyncio.wait_for(together.wait(), DEADLINE)
|
||||
return await handler(session_id, request)
|
||||
|
||||
monkeypatch.setattr(routes, "session_delete_handler", held)
|
||||
relay.stop()
|
||||
if in_flight:
|
||||
wait_line(relay.process, "the shutdown hooks ended")
|
||||
release.set()
|
||||
relay.ended_well()
|
||||
assert [reply().status_code for reply in replies] == [200] * len(ids)
|
||||
|
||||
|
||||
@posix
|
||||
@pytest.mark.parametrize("pooled", [False, True], ids=["first-call", "pooled-session"])
|
||||
def test_a_request_in_flight_finishes_on_its_own_session(
|
||||
run: Callable[..., Any], # noqa: F811
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
tmp_path: Path,
|
||||
pooled: bool,
|
||||
) -> None:
|
||||
"""The first call of a session fetches its titles while its login is still listed."""
|
||||
relay = Relay(run, server.url, tmp_path / "relay", wait=0.2)
|
||||
started, release = Event(), Event()
|
||||
|
||||
def hold(stub: StubService) -> None:
|
||||
started.set()
|
||||
assert release.wait(DEADLINE), "the test did not release the titles"
|
||||
|
||||
if pooled:
|
||||
assert relay.list("list-tracks")().status_code == 200
|
||||
StubService.hooks["titles"] = hold
|
||||
reply = relay.list("list-titles" if pooled else "list-tracks")
|
||||
assert started.wait(DEADLINE)
|
||||
relay.stop()
|
||||
wait_line(relay.process, "the reopens ended")
|
||||
release.set()
|
||||
assert reply().status_code == 200
|
||||
relay.ended_well()
|
||||
assert len(logins) == 1
|
||||
assert count(server, "GET", TITLES_ROUTE) == 1 + pooled
|
||||
assert count(server, "DELETE", SESSION_ROUTE) == 1
|
||||
|
||||
|
||||
@posix
|
||||
def test_a_session_lost_late_in_the_stop_does_not_hold_it(
|
||||
run: Callable[..., Any], # noqa: F811
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
relay = Relay(run, server.url, tmp_path / "relay", wait=0.2)
|
||||
started, release = Event(), Event()
|
||||
|
||||
def lose(stub: StubService) -> None:
|
||||
started.set()
|
||||
assert release.wait(DEADLINE), "the test did not release the titles"
|
||||
lose_session(server, stub)
|
||||
|
||||
def login(stub: StubService, cookies: Any, credential: Any) -> None:
|
||||
if release.is_set():
|
||||
poll_a_device(stub)
|
||||
|
||||
monkeypatch.setattr(StubService, "authenticate", login)
|
||||
StubService.hooks["titles"] = lose
|
||||
reply = relay.list()
|
||||
assert started.wait(DEADLINE)
|
||||
relay.stop()
|
||||
wait_line(relay.process, "the reopens ended")
|
||||
release.set()
|
||||
assert reply().status_code == 409
|
||||
relay.ended_well()
|
||||
|
||||
|
||||
@posix
|
||||
@pytest.mark.parametrize("waits", [True, False], ids=["waits", "finishes"])
|
||||
@pytest.mark.parametrize("pooled", [False, True], ids=["first-call", "pooled-session"])
|
||||
def test_a_request_that_opens_its_lost_session_again_finishes_in_time_or_is_cut(
|
||||
run: Callable[..., Any], # noqa: F811
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
tmp_path: Path,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
pooled: bool,
|
||||
waits: bool,
|
||||
) -> None:
|
||||
"""The upstream server loses the remote session, and the login of the next one waits for an approval."""
|
||||
relay = Relay(run, server.url, tmp_path / "relay", wait=0.2 if waits else DEADLINE)
|
||||
lost, reopening, approved = Event(), Event(), Event()
|
||||
|
||||
def lose(stub: StubService) -> None:
|
||||
StubService.hooks.clear()
|
||||
lost.set()
|
||||
lose_session(server, stub)
|
||||
|
||||
def login(stub: StubService, cookies: Any, credential: Any) -> None:
|
||||
if lost.is_set():
|
||||
reopening.set()
|
||||
while not approved.wait(0.01):
|
||||
stub._input_bridge.ensure_active()
|
||||
|
||||
monkeypatch.setattr(StubService, "authenticate", login)
|
||||
if pooled:
|
||||
assert relay.list("list-tracks")().status_code == 200
|
||||
StubService.hooks["titles"] = lose
|
||||
reply = relay.list()
|
||||
assert reopening.wait(DEADLINE)
|
||||
relay.stop()
|
||||
wait_line(relay.process, "the shutdown hooks ended")
|
||||
if not waits:
|
||||
approved.set()
|
||||
assert reply().status_code == (409 if waits else 200)
|
||||
relay.ended_well()
|
||||
|
||||
|
||||
def relay_app() -> web.Application:
|
||||
app = web.Application()
|
||||
setup_routes(app)
|
||||
@@ -378,26 +172,6 @@ def test_a_login_that_starts_as_the_relay_stops_is_refused(
|
||||
assert server.seen == [] and not handlers._remote_logins
|
||||
|
||||
|
||||
def test_a_login_that_the_stop_reaches_before_its_create_opens_no_session(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
pool: dict[tuple, RemoteLease],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
app, client = relay_app(), make_client(server.url)
|
||||
authenticate = client.authenticate
|
||||
|
||||
def stop_first() -> None:
|
||||
asyncio.run(end_remote_pool(app))
|
||||
authenticate()
|
||||
|
||||
monkeypatch.setattr(client, "authenticate", stop_first)
|
||||
with pytest.raises(APIError) as refused:
|
||||
log_in(app, client, monkeypatch)
|
||||
assert refused.value.error_code == APIErrorCode.SERVER_DRAINING
|
||||
assert server.seen == []
|
||||
|
||||
|
||||
def test_a_request_in_flight_keeps_its_own_error(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
@@ -416,22 +190,6 @@ def test_a_request_in_flight_keeps_its_own_error(
|
||||
assert sessions() == []
|
||||
|
||||
|
||||
def test_the_stop_refuses_before_it_reads_the_logins(
|
||||
pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
app = relay_app()
|
||||
started: list[bool] = []
|
||||
|
||||
class Logins(dict[str, Any]):
|
||||
def values(self) -> Any:
|
||||
started.append(app["relay_stop"].started)
|
||||
return super().values()
|
||||
|
||||
monkeypatch.setattr(handlers, "_remote_logins", Logins())
|
||||
asyncio.run(end_remote_pool(app))
|
||||
assert started == [True]
|
||||
|
||||
|
||||
def test_another_app_of_the_process_still_logs_in(
|
||||
server: SimpleNamespace, # noqa: F811
|
||||
logins: list[Any], # noqa: F811
|
||||
@@ -446,73 +204,6 @@ def test_another_app_of_the_process_still_logs_in(
|
||||
assert len(logins) == 1
|
||||
|
||||
|
||||
async def test_the_stop_waits_for_the_ends_and_not_for_the_default_executor(
|
||||
pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The ends finish while the stop waits. A busy remote session stays open."""
|
||||
closed: list[str] = []
|
||||
begun, finish, free_workers = Event(), Event(), Event()
|
||||
workers = ThreadPoolExecutor(1)
|
||||
asyncio.get_running_loop().set_default_executor(workers)
|
||||
workers.submit(free_workers.wait, DEADLINE)
|
||||
|
||||
def end(name: str) -> None:
|
||||
begun.set()
|
||||
assert finish.wait(DEADLINE)
|
||||
closed.append(name)
|
||||
|
||||
async def finish_later() -> None:
|
||||
while not begun.is_set():
|
||||
await asyncio.sleep(0.01)
|
||||
finish.set()
|
||||
|
||||
monkeypatch.setattr(handlers, "LOGIN_WAIT", DEADLINE / 4)
|
||||
for name in ("a", "b", "busy"):
|
||||
service = SimpleNamespace(close=lambda name=name: end(name))
|
||||
pool[(name,)] = RemoteLease((name,), service=service, busy=int(name == "busy"))
|
||||
app = relay_app()
|
||||
try:
|
||||
later = asyncio.create_task(finish_later())
|
||||
await close_remote_pool(app)
|
||||
assert sorted(closed) == ["a", "b"] and list(pool) == [("busy",)]
|
||||
assert all(thread.daemon for thread in app["relay_stop"].ends)
|
||||
await later
|
||||
finally:
|
||||
free_workers.set()
|
||||
finish.set()
|
||||
|
||||
|
||||
async def test_an_end_that_does_not_finish_holds_the_stop_no_longer_than_the_wait(
|
||||
pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
closed, release = Event(), Event()
|
||||
|
||||
def end() -> None:
|
||||
release.wait(DEADLINE)
|
||||
closed.set()
|
||||
|
||||
monkeypatch.setattr(handlers, "LOGIN_WAIT", 0.05)
|
||||
pool[("stuck",)] = RemoteLease(("stuck",), service=SimpleNamespace(close=end))
|
||||
try:
|
||||
await asyncio.wait_for(close_remote_pool(relay_app()), DEADLINE / 2)
|
||||
assert not closed.is_set()
|
||||
finally:
|
||||
release.set()
|
||||
|
||||
|
||||
async def test_a_reopen_is_ended_once(pool: dict[tuple, RemoteLease], monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
lifetime = SimpleNamespace(ended=False)
|
||||
service = SimpleNamespace(lifetime=lifetime, _reopen_lock=Lock(), close=lambda: setattr(lifetime, "ended", True))
|
||||
monkeypatch.setattr(handlers, "LOGIN_WAIT", DEADLINE)
|
||||
pool[("EXAMPLE",)] = RemoteLease(("EXAMPLE",), service=service, busy=1)
|
||||
stop = RelayStop()
|
||||
with service._reopen_lock:
|
||||
for _ in range(2):
|
||||
end_reopening(stop)
|
||||
stop.ends[0].join(DEADLINE)
|
||||
assert len(stop.ends) == 1
|
||||
|
||||
|
||||
async def test_the_last_call_ends_also_the_login_of_a_request_that_did_not_finish(
|
||||
pool: dict[tuple, RemoteLease],
|
||||
) -> None:
|
||||
|
||||
Reference in New Issue
Block a user