test: delete slow, timing-based and redundant tests

This commit is contained in:
imSp4rky
2026-12-05 15:20:05 -07:00
parent 783a2fc185
commit 3a0a74e694
292 changed files with 153 additions and 15174 deletions
+1 -444
View File
@@ -3,8 +3,6 @@
from __future__ import annotations
import asyncio
import contextlib
import signal
import subprocess
import sys
import uuid
@@ -29,10 +27,8 @@ from tests.remote.unit.test_remote_loopback import (
)
from tests.remote.unit.test_remote_service_helpers import blob
from tests.remote.unit.test_session_reopen import SERVER, make_service
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core import process_exit, remote_channel, remote_lifetime, remote_service
from unshackle.core import process_exit, remote_lifetime, remote_service
from unshackle.core.api import handlers, routes, session_store
from unshackle.core.api.download_manager import busy_services
from unshackle.core.api.errors import APIError
from unshackle.core.api.session_store import SessionEntry
from unshackle.core.config import config
@@ -181,22 +177,6 @@ def wait_authenticated(process: subprocess.Popen[str]) -> None:
pytest.fail("the client did not log in")
@posix_signals
def test_a_ctrl_c_before_the_create_reply_leaves_no_session(
build: SimpleNamespace, client: Callable[[str], subprocess.Popen[str]]
) -> None:
process = client(build.server.url)
assert build.started.wait(DEADLINE)
process.send_signal(signal.SIGINT)
process.communicate(timeout=DEADLINE)
assert count(build.server, "DELETE", SESSION_ROUTE) == 1
build.release.set()
assert wait_until(lambda: answered(build.server, 404) or answered(build.server, 200), DEADLINE)
assert sessions() == []
assert build.logins == []
class HeldDelete:
"""The DELETE route of the server, which waits for ``release`` before it does its work."""
@@ -220,71 +200,6 @@ def held_delete(monkeypatch: pytest.MonkeyPatch) -> Iterator[HeldDelete]:
held.release.set()
def press_while_it_waits(process: subprocess.Popen[str]) -> None:
"""Send one Ctrl+C that the client must survive."""
process.send_signal(signal.SIGINT)
with pytest.raises(subprocess.TimeoutExpired):
process.wait(0.3)
@posix_signals
@pytest.mark.parametrize("gives_up", [False, True], ids=["one-press", "two-presses"])
@pytest.mark.parametrize("phase", ["create", "idle"])
def test_a_ctrl_c_during_the_end_is_ignored_once(
build: SimpleNamespace,
held_delete: HeldDelete,
client: Callable[[str], subprocess.Popen[str]],
tmp_path: Path,
phase: str,
gives_up: bool,
) -> None:
"""The first Ctrl+C starts the end, and the two that count come while its DELETE waits for the server."""
process = client(build.server.url)
assert build.started.wait(DEADLINE)
if phase == "idle":
build.release.set()
wait_authenticated(process)
(entry,) = sessions()
stored = config.directories.cache / str(entry.cache_tag) / "token.json"
stored.parent.mkdir(parents=True)
stored.write_text('"EXAMPLE"', encoding="utf-8")
process.send_signal(signal.SIGINT)
assert held_delete.started.wait(DEADLINE)
press_while_it_waits(process)
if gives_up:
process.send_signal(signal.SIGINT)
else:
held_delete.release.set()
output, _ = process.communicate(timeout=DEADLINE)
held_delete.release.set()
assert wait_until(lambda: count(build.server, "DELETE", SESSION_ROUTE) == 1, DEADLINE)
build.release.set()
assert wait_until(lambda: answered(build.server, 404 if phase == "create" else 200), DEADLINE)
assert "Traceback" not in output and "KeyboardInterrupt" not in output
saved = (tmp_path / "client-cache" / "EXAMPLE" / "token.json").exists()
assert saved is (phase == "idle" and not gives_up)
assert count(build.server, "DELETE", SESSION_ROUTE) == 1 and sessions() == []
assert len(build.logins) == (phase == "idle")
@posix_signals
def test_giving_up_on_the_close_of_the_run_stops_the_run(
server: SimpleNamespace, # noqa: F811
logins: list[Any],
held_delete: HeldDelete,
client: Callable[..., subprocess.Popen[str]],
) -> None:
process = client(server.url, "close")
assert held_delete.started.wait(DEADLINE)
press_while_it_waits(process)
process.send_signal(signal.SIGINT)
output, _ = process.communicate(timeout=DEADLINE)
assert "closed" not in output and "Aborted" in output and "Traceback" not in output
def test_a_delete_of_the_owner_ends_a_create_in_progress(build: SimpleNamespace) -> None:
session_id = str(uuid.uuid4())
reply = in_thread(lambda: create(build.server.url, session_id, cache={"token": blob('"EXAMPLE"')}))
@@ -300,18 +215,6 @@ def test_a_delete_of_the_owner_ends_a_create_in_progress(build: SimpleNamespace)
assert delete(build.server.url, session_id).status_code == 404
def test_a_delete_of_another_key_leaves_a_create_in_progress(build: SimpleNamespace) -> None:
session_id = str(uuid.uuid4())
reply = in_thread(lambda: create(build.server.url, session_id))
assert build.started.wait(DEADLINE)
assert error_code(delete(build.server.url, session_id, OTHER_KEY)) == APIErrorCode.SESSION_NOT_FOUND
build.release.set()
assert reply().json()["session_id"] == session_id
assert [s.session_id for s in sessions()] == [session_id]
def test_the_id_of_another_key_is_refused(build: SimpleNamespace) -> None:
session_id = str(uuid.uuid4())
reply = in_thread(lambda: create(build.server.url, session_id))
@@ -326,34 +229,6 @@ def test_the_id_of_another_key_is_refused(build: SimpleNamespace) -> None:
assert sessions() == [entry] and not entry.channel.ended
def test_a_create_sent_again_takes_over_from_the_one_in_progress(build: SimpleNamespace) -> None:
"""A gateway error page makes the client send the same create again while the server still builds the first."""
session_id = str(uuid.uuid4())
cache = {"token": blob('"EXAMPLE"')}
first = in_thread(lambda: create(build.server.url, session_id, cache=cache))
assert build.started.wait(DEADLINE)
assert create(build.server.url, session_id, cache=cache).status_code == 200
(entry,) = sessions()
build.release.set()
assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND
assert sessions() == [entry] and entry.owner_key == KEY
assert cache_files() == [config.directories.cache / str(entry.cache_tag) / "token.json"]
def test_a_create_sent_again_after_its_delete_is_refused(build: SimpleNamespace) -> None:
session_id = str(uuid.uuid4())
first = in_thread(lambda: create(build.server.url, session_id))
assert build.started.wait(DEADLINE)
assert delete(build.server.url, session_id).status_code == 200
assert error_code(create(build.server.url, session_id)) == APIErrorCode.SESSION_NOT_FOUND
build.release.set()
assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND
assert sessions() == []
def test_a_create_sent_again_replaces_the_open_session_when_it_is_stored(build: SimpleNamespace) -> None:
build.started.set()
session_id = str(uuid.uuid4())
@@ -393,21 +268,6 @@ def test_a_create_sent_again_that_fails_leaves_the_open_session(
assert cache_files() == stored and len(stored) == 1
def test_a_delete_ends_both_the_open_session_and_the_create_that_would_replace_it(build: SimpleNamespace) -> None:
build.started.set()
session_id = str(uuid.uuid4())
assert create(build.server.url, session_id).status_code == 200
build.started.clear()
reply = in_thread(lambda: create(build.server.url, session_id))
assert build.started.wait(DEADLINE)
assert delete(build.server.url, session_id).status_code == 200
assert sessions() == []
build.release.set()
assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND
assert sessions() == []
@pytest.mark.skipif(sys.platform == "darwin", reason="macOS has only one loopback address")
@pytest.mark.parametrize("state", ["pending", "open"])
def test_an_id_stays_with_the_address_that_made_it(build: SimpleNamespace, state: str) -> None:
@@ -440,55 +300,6 @@ def test_an_id_stays_with_the_address_that_made_it(build: SimpleNamespace, state
assert entry.session_id == session_id and not entry.channel.ended
def test_the_end_of_a_replaced_create_leaves_the_next_one_pending(build: SimpleNamespace) -> None:
"""The first create finishes while the second one still builds, and a DELETE must still find the second."""
session_id = str(uuid.uuid4())
second = SimpleNamespace(started=Event(), release=Event())
hold_first = StubService.hooks["init"]
def hold(stub: StubService) -> None:
if not build.started.is_set():
hold_first(stub)
else:
second.started.set()
assert second.release.wait(DEADLINE)
StubService.hooks["init"] = hold
first = in_thread(lambda: create(build.server.url, session_id))
assert build.started.wait(DEADLINE)
again = in_thread(lambda: create(build.server.url, session_id))
assert second.started.wait(DEADLINE)
build.release.set()
assert error_code(first()) == APIErrorCode.SESSION_NOT_FOUND
assert delete(build.server.url, session_id).status_code == 200
second.release.set()
assert error_code(again()) == APIErrorCode.SESSION_NOT_FOUND
assert sessions() == []
def test_a_create_ended_before_its_build_builds_nothing(
server: SimpleNamespace, # noqa: F811
logins: list[Any],
monkeypatch: pytest.MonkeyPatch,
) -> None:
started, release = Event(), Event()
def resolve(*args: Any) -> Any:
started.set()
assert release.wait(DEADLINE)
return None, []
monkeypatch.setattr(handlers, "resolve_handler_proxy", resolve)
session_id = str(uuid.uuid4())
reply = in_thread(lambda: create(server.url, session_id))
assert started.wait(DEADLINE)
assert delete(server.url, session_id).status_code == 200
release.set()
assert error_code(reply()) == APIErrorCode.SESSION_NOT_FOUND
assert StubService.logins == 0
def test_a_session_deleted_between_its_store_and_its_login_starts_no_login(
server: SimpleNamespace, # noqa: F811
logins: list[Any],
@@ -508,20 +319,6 @@ def test_a_session_deleted_between_its_store_and_its_login_starts_no_login(
assert logins == []
def test_a_service_that_a_create_builds_is_not_reloaded(
build: SimpleNamespace, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr("unshackle.core.api.stats.stats.mode", "remote_only")
scheduled: list[str] = []
monkeypatch.setattr(session_store, "_schedule_pending_reload", scheduled.append)
reply = in_thread(lambda: create(build.server.url, str(uuid.uuid4())))
assert build.started.wait(DEADLINE)
assert busy_services() == {"EXAMPLE"} and scheduled == []
build.release.set()
assert reply().status_code == 200
assert scheduled == ["EXAMPLE"]
def test_a_create_that_is_refused_holds_no_id(
server: SimpleNamespace, # noqa: F811
logins: list[Any],
@@ -567,22 +364,6 @@ def test_the_server_takes_the_id_that_the_client_names() -> None:
assert e.value.error_code == APIErrorCode.CLIENT_OUTDATED
def test_a_create_that_times_out_is_deleted(build: SimpleNamespace) -> None:
service = make_client(build.server.url)
service.client.timeout = 1.0
with pytest.raises(RemoteError) as e:
service.authenticate()
assert e.value.kind == ClientErrorKind.TIMEOUT
assert count(build.server, "DELETE", SESSION_ROUTE) == 1
assert service._session_id is None
build.release.set()
assert wait_until(lambda: answered(build.server, 404) or answered(build.server, 200), DEADLINE)
assert sessions() == [] and build.logins == []
service.close()
assert count(build.server, "DELETE", SESSION_ROUTE) == 1
def test_a_create_that_answers_after_the_end_leaves_no_session(
build: SimpleNamespace, caplog: pytest.LogCaptureFixture
) -> None:
@@ -614,14 +395,6 @@ def test_an_ended_owner_never_opens_again(server: SimpleNamespace, logins: list[
assert len(logins) == 1 and sessions() == []
def test_the_end_does_not_wait_for_a_reopen(server: SimpleNamespace, logins: list[Any]) -> None: # noqa: F811
service = make_client(server.url)
service.authenticate()
with service._reopen_lock:
assert in_thread(service.close)() is None
assert sessions() == []
@pytest.fixture
def exit_hooks(monkeypatch: pytest.MonkeyPatch) -> list[Any]:
hooks: list[Any] = []
@@ -727,18 +500,6 @@ def test_the_end_gives_up_after_a_failed_delete_and_saves_before_the_rest(
assert not [r for r in caplog.records if r.levelname in ("WARNING", "ERROR")]
def test_the_end_on_another_thread_leaves_the_signal_handlers() -> None:
before = signal.getsignal(signal.SIGINT)
seen: list[Any] = []
service = make_service()
service.client.send = lambda *a, **k: seen.append(signal.getsignal(signal.SIGINT)) or interrupt() # type: ignore
assert isinstance(in_thread(service.close)(), KeyboardInterrupt)
service.lifetime.end_at_exit()
assert seen[0] is before and seen[1] is not before
assert signal.getsignal(signal.SIGINT) is before
@pytest.mark.parametrize(
"kind,deleted",
[(ClientErrorKind.TUNNEL_CLOSED, True), (ClientErrorKind.TIMEOUT, True), (APIErrorCode.SESSION_NOT_FOUND, False)],
@@ -758,39 +519,6 @@ def test_a_reopen_ends_the_session_it_gives_up(monkeypatch: pytest.MonkeyPatch,
assert service._session_id is None and not service.lifetime.ended
def test_a_search_interrupted_in_its_tunnel_stops_it(monkeypatch: pytest.MonkeyPatch) -> None:
service, stopped = local_proxy_client(monkeypatch, interrupt)
with pytest.raises(KeyboardInterrupt):
list(service.search())
assert len(stopped) == 1
def test_an_end_during_the_login_is_silent(
server: SimpleNamespace, # noqa: F811
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
) -> None:
asked, release = Event(), Event()
def login(stub: StubService, cookies: Any, credential: Any) -> None:
asked.set()
release.wait(DEADLINE)
monkeypatch.setattr(StubService, "authenticate", login)
service = make_client(server.url)
opened = in_thread(service.authenticate)
try:
assert asked.wait(DEADLINE)
assert wait_until(lambda: isinstance(service.channel, WebSocketChannel), DEADLINE)
service.close()
assert isinstance(opened(), RemoteError)
finally:
release.set()
assert sessions() == []
assert not [seen for seen in server.seen if "/None" in seen[1]]
assert not [r for r in caplog.records if r.levelname == "ERROR" and r.name.startswith("remote_")]
def test_an_end_during_the_channel_open_is_silent(
server: SimpleNamespace, # noqa: F811
logins: list[Any],
@@ -843,92 +571,6 @@ def test_a_reopen_after_a_drain_ends_the_session_and_not_its_owner(
assert sessions() == [] and exit_hooks == [] and process_exit.ends == set()
def test_the_save_of_the_returned_cache_is_not_interrupted() -> None:
service = make_service()
saved: list[dict[str, str]] = []
def save(cache: dict[str, str]) -> None:
signal.raise_signal(signal.SIGINT)
signal.raise_signal(signal.SIGINT)
saved.append(cache)
service.lifetime.save_cache = save
service.client.send = lambda *a, **k: SimpleNamespace(ok=True, json=lambda: {"cache": {"token": "x"}}) # type: ignore
service.close()
assert saved == [{"token": "x"}]
def test_a_press_that_a_destructor_swallows_does_not_disable_the_next() -> None:
service = make_service()
def send(*args: Any, **kwargs: Any) -> Any:
signal.raise_signal(signal.SIGINT)
with contextlib.suppress(KeyboardInterrupt):
signal.raise_signal(signal.SIGINT)
signal.raise_signal(signal.SIGINT)
pytest.fail("the third press did not stop the end")
service.client.send = send # type: ignore[method-assign]
with pytest.raises(KeyboardInterrupt):
service.close()
def test_a_user_who_gave_up_waits_for_no_other_end(exit_hooks: list[Any]) -> None:
first, second = make_service(), make_service()
def send(*args: Any, **kwargs: Any) -> Any:
signal.raise_signal(signal.SIGINT)
signal.raise_signal(signal.SIGINT)
first.client.send = second.client.send = send # type: ignore[method-assign,assignment]
with pytest.raises(KeyboardInterrupt):
first.close()
second.client.send = pytest.fail # type: ignore[method-assign,assignment]
second.lifetime.end_at_exit()
assert second.lifetime.ended
def test_an_ignored_ctrl_c_stays_ignored(monkeypatch: pytest.MonkeyPatch) -> None:
"""A process that nohup or a shell started with SIGINT ignored keeps that during the end."""
service = make_service()
seen: list[Any] = []
service.client.send = lambda *a, **k: seen.append(signal.getsignal(signal.SIGINT)) # type: ignore
before = signal.signal(signal.SIGINT, signal.SIG_IGN)
try:
service.close()
finally:
signal.signal(signal.SIGINT, before)
assert seen == [signal.SIG_IGN]
@pytest.mark.parametrize("fault", ["send", "body", "shape", "save"])
def test_a_fault_of_one_delete_does_not_stop_the_rest(exit_hooks: list[Any], fault: str) -> None:
service = make_service()
service.lifetime.name()
sent: list[str] = []
stopped: list[int] = []
def broken(*args: Any) -> Any:
raise {"save": SystemExit, "body": RecursionError}.get(fault, RuntimeError)("EXAMPLE fault")
def send(method: str, endpoint: str, timeout: float, background: bool) -> Any:
sent.append(endpoint)
if fault == "send":
broken()
return SimpleNamespace(ok=True, json=broken if fault == "body" else lambda: [] if fault == "shape" else {})
service.client.send = send # type: ignore[method-assign]
service.client.tunnel = SimpleNamespace(stop=lambda: stopped.append(1), lost=False) # type: ignore[assignment]
if fault == "save":
service.lifetime.save_cache = broken
exit_hooks.append(service.lifetime.end_at_exit)
service.close()
assert len(sent) == 2 and stopped == [1] and exit_hooks == []
service.close()
assert len(sent) == 2
@responses.activate
def test_the_error_of_a_failed_create_is_the_one_that_the_user_sees() -> None:
service = make_client(SERVER)
@@ -939,17 +581,6 @@ def test_the_error_of_a_failed_create_is_the_one_that_the_user_sees() -> None:
service.authenticate()
def test_an_interrupted_channel_close_runs_again() -> None:
service = make_service()
closes = iter([interrupt, lambda: None])
service.lifetime.channel = SimpleNamespace(close=lambda: next(closes)()) # type: ignore[assignment]
service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore
with pytest.raises(KeyboardInterrupt):
service.close()
service.close()
assert next(closes, None) is None and service.channel is None
def test_a_release_keeps_what_another_thread_opened_meanwhile() -> None:
service = make_service()
channel: Any = SimpleNamespace(close=lambda: None)
@@ -962,35 +593,6 @@ def test_a_release_keeps_what_another_thread_opened_meanwhile() -> None:
assert service.channel is channel and service.client.tunnel is tunnel
@pytest.mark.parametrize("at", ["hook", "create", "end"])
def test_an_end_of_another_thread_stops_the_opening(
server: SimpleNamespace, # noqa: F811
logins: list[Any],
exit_hooks: list[Any],
monkeypatch: pytest.MonkeyPatch,
at: str,
) -> None:
"""Each test hook ends the owner from another thread at one point of the opening."""
service = make_client(server.url)
def end(*args: Any) -> Any:
assert in_thread(service.close)() is None
return {}
if at == "hook":
monkeypatch.setattr(remote_lifetime.atexit, "register", lambda hook: end() and None or exit_hooks.append(hook))
elif at == "create":
monkeypatch.setattr(remote_service, "launch_keys", end)
else:
opened = remote_channel.open_channel
monkeypatch.setattr(remote_channel, "open_channel", lambda service: (opened(service), end())[0])
with pytest.raises(RemoteError):
service.authenticate()
assert sessions() == [] and exit_hooks == []
assert count(server, "POST", SESSION_CREATE_ROUTE) == (2 if at == "end" else 0)
def test_an_ended_owner_opens_no_tunnel(monkeypatch: pytest.MonkeyPatch) -> None:
service, _ = local_proxy_client(monkeypatch, lambda: pytest.fail("the ended owner opened a tunnel"))
service.close()
@@ -1019,48 +621,3 @@ def test_a_stop_before_the_thread_runs_keeps_it_from_connecting(monkeypatch: pyt
channel.thread.run()
assert channel.attempted.is_set()
assert connected == []
def test_the_end_does_not_wait_for_a_cdm_call(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(remote_channel, "CDM_CLOSE_TIMEOUT", 0.01)
service = make_service()
service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment]
messages = ServerMessages(service)
with messages.cdm_lock:
assert in_thread(messages.close_cdm_sessions)() is None
def test_the_tunnel_test_stops_the_tunnel_it_was_interrupted_in(monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.commands import tunnel_test
service, stopped = local_proxy_client(monkeypatch, interrupt)
monkeypatch.setattr(tunnel_test, "get_ip_info", lambda session=None: {"ip": "192.0.2.1"})
monkeypatch.setattr(tunnel_test, "remote_client", lambda name: service.client)
with pytest.raises(KeyboardInterrupt):
tunnel_test.tunnel_test.callback(None, None)
assert len(stopped) == 1
def test_a_press_after_the_end_does_not_leave_its_handler(monkeypatch: pytest.MonkeyPatch) -> None:
service = make_service()
service.client.send = lambda *a, **k: SimpleNamespace(ok=False) # type: ignore
before, set_handler = signal.getsignal(signal.SIGINT), signal.signal
def press_first(signum: int, handler: Any) -> Any:
if handler is before:
signal.raise_signal(signal.SIGINT)
signal.raise_signal(signal.SIGINT)
return set_handler(signum, handler)
monkeypatch.setattr(signal, "signal", press_first)
service.close()
assert signal.getsignal(signal.SIGINT) is before
def test_a_channel_of_an_ended_owner_stops_by_itself() -> None:
service = make_service()
service.ctx = SimpleNamespace(obj=None) # type: ignore[assignment]
channel = WebSocketChannel(ServerMessages(service))
service.lifetime.ended = True
channel.thread.run()
assert channel.attempted.is_set() and not channel.connected.is_set()