ci: run the unit suite in parallel and keep it off the network

Test servers shut down without the 0.5s poll wait, unit tests refuse non-loopback lookups, and three load-sensitive tests are steadied. Pushes to dev test Python 3.11 only; the docs job builds with uv.
This commit is contained in:
imSp4rky
2026-10-13 19:31:23 -06:00
parent 6b04d7b137
commit 9f82777394
13 changed files with 117 additions and 39 deletions
+40
View File
@@ -0,0 +1,40 @@
"""Suite-wide test setup."""
from __future__ import annotations
import socket
import socketserver
from typing import Any
import pytest
from unshackle.core.update_checker import UpdateChecker
# shutdown() blocks until the serve loop polls again, and the 0.5s default is paid by every
# test server at teardown. The default changes for the whole process, servers in core included.
socketserver.BaseServer.serve_forever.__defaults__ = (0.01,)
@pytest.fixture(autouse=True)
def loopback_only(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> None:
"""Fail a name lookup for any host but loopback, so a stray request cannot hang a unit test."""
if request.node.get_closest_marker("live") or request.node.get_closest_marker("slow"):
return
resolve = socket.getaddrinfo
def offline(host: Any, *args: Any, **kwargs: Any) -> Any:
if host not in (None, "", "localhost", "127.0.0.1", "::1"):
raise socket.gaierror(socket.EAI_NONAME, f"unit tests are offline: {host!r} is not loopback")
return resolve(host, *args, **kwargs)
monkeypatch.setattr(socket, "getaddrinfo", offline)
@pytest.fixture(autouse=True)
def no_update_check(monkeypatch: pytest.MonkeyPatch) -> None:
"""Keep the release lookup of the health route off the network."""
async def no_release(*args: Any, **kwargs: Any) -> None:
return None
monkeypatch.setattr(UpdateChecker, "check_for_updates", no_release)
+3 -1
View File
@@ -104,7 +104,8 @@ def test_encoded_body_is_decoded_on_disk(tmp_path, encoding_server):
assert save_path.read_bytes() == PLAIN
def test_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, encoding_server):
def test_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, encoding_server, monkeypatch):
monkeypatch.setattr(importlib.import_module("unshackle.core.downloaders.requests"), "RETRY_WAIT", 0)
save_path = tmp_path / "sub.vtt"
save_path.with_name("sub.vtt.!dev").write_bytes(PLAIN[:5000])
list(download(url=encoding_server.url, save_path=save_path, session=rq.Session()))
@@ -147,6 +148,7 @@ class _FakeRnetSession:
def test_rnet_encoded_body_discards_a_partial_instead_of_range_resuming(tmp_path, monkeypatch):
dl = importlib.import_module("unshackle.core.downloaders.requests")
monkeypatch.setattr(dl, "is_rnet_session", lambda s: isinstance(s, _FakeRnetSession))
monkeypatch.setattr(dl, "RETRY_WAIT", 0)
session = _FakeRnetSession(PLAIN)
save_path = tmp_path / "sub.vtt"
save_path.with_name("sub.vtt.!dev").write_bytes(PLAIN[:5000])
+2 -2
View File
@@ -25,7 +25,7 @@ SLOW_INDEX = 4
FAST_BODY = b"F" * 4096
SLOW_BODY = b"S" * 40960
TRICKLE_CHUNK = 2048
TRICKLE_DELAY = 0.05
TRICKLE_DELAY = 0.5
class _Handler(BaseHTTPRequestHandler):
@@ -82,7 +82,7 @@ def test_hedge_loser_releases_handles_before_merge(tmp_path, trickle_server, mon
slow_hits = trickle_server.counts[f"/seg/{SLOW_INDEX}"]
assert slow_hits == 2, "hedge never fired; the race under test was not exercised"
# the batch must not stall draining the loser's stream (trickle alone takes ~1s)
# the batch must not stall draining the loser's stream (trickle alone takes ~10s)
assert wall < 5
for i in range(SEGMENTS):
+14 -2
View File
@@ -91,9 +91,21 @@ def test_bucket_holds_aggregate_rate_across_threads():
for t in threads:
t.join()
achieved = sum(totals) / (time.monotonic() - start)
# exceeding the limit is a real failure; undershoot is scheduler noise on a loaded box
# exceeding the limit is a real failure; undershoot is scheduler noise on a loaded box, so no lower bound
assert achieved <= rate * 1.1
assert achieved >= rate * 0.5
def test_bucket_refills_at_the_rate(monkeypatch):
"""On a simulated clock the throughput is exact, so a slow refill fails like a fast one."""
clock = [0.0]
monkeypatch.setattr(requests_downloader, "time", SimpleNamespace(monotonic=lambda: clock[0]))
monkeypatch.setattr(
requests_downloader, "DOWNLOAD_CANCELLED", SimpleNamespace(wait=lambda s: clock.__setitem__(0, clock[0] + s))
)
bucket = TokenBucket(1_000)
for _ in range(50):
bucket.consume(100)
assert clock[0] == pytest.approx(5.0)
def test_bucket_chunk_larger_than_capacity_does_not_deadlock(monkeypatch):
@@ -80,6 +80,7 @@ class FakeService:
def run(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, episodes: dict, **flags: Any) -> Any:
"""Return the Selected ids, the exit code, or None for a run that completes."""
monkeypatch.setattr(Tracks, "tree", lambda self, *a, **k: (_ for _ in ()).throw(Selected(self)))
monkeypatch.setattr("unshackle.core.providers.search_metadata", lambda *a, **k: None)
cmd = Harness.__new__(Harness)
cmd.log = logging.getLogger("test_kind_only")
cmd.service = "FAKE"
+1 -1
View File
@@ -121,7 +121,7 @@ uv run pytest tests/remote -v --live
Run only fast unit tests:
```powershell
uv run pytest tests/remote -m "unit and not slow"
uv run pytest tests/remote -n auto -m "unit and not slow"
```
## Adding a new service to e2e
+10 -4
View File
@@ -6,7 +6,6 @@ import asyncio
import logging
import sys
import threading
import time
from collections.abc import Callable
from datetime import datetime, timedelta, timezone
@@ -354,9 +353,11 @@ async def test_status_reports_no_session_limit(aiohttp_client, dashboard_cfg, mo
assert body["max_sessions"] is None
async def test_dashboard_health(aiohttp_client, dashboard_cfg) -> None:
async def test_dashboard_health(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
from unshackle.core.api import handlers
monkeypatch.setattr(config, "key_vaults", [])
monkeypatch.setattr(config, "proxy_providers", {})
handlers._health_cache.clear()
client = await aiohttp_client(make_app())
body = await (await client.get("/api/dashboard/health", headers={"X-Secret-Key": "dash-secret"})).json()
@@ -617,10 +618,12 @@ async def test_health_probe_timeout_reports_what_finished(aiohttp_client, dashbo
"""A vault that accepts the connection then stalls must not hang the panel forever."""
from unshackle.core.api import handlers
released = threading.Event()
def stalling_probe(checks=None):
checks = [] if checks is None else checks
checks.append({"id": "ffmpeg", "label": "ffmpeg", "status": "ok", "detail": "7.1", "ms": 1.0})
time.sleep(6) # the stalled vault; the deadline fires long before this returns
released.wait(6) # the stalled vault; the deadline fires long before this returns
checks.append({"id": "never", "label": "never", "status": "ok", "detail": "", "ms": 0.0})
return checks
@@ -629,7 +632,10 @@ async def test_health_probe_timeout_reports_what_finished(aiohttp_client, dashbo
monkeypatch.setattr(handlers, "HEALTH_PROBE_TIMEOUT", 1.0)
client = await aiohttp_client(make_app())
body = await (await client.get("/api/dashboard/health", headers={"X-Secret-Key": "dash-secret"})).json()
try:
body = await (await client.get("/api/dashboard/health", headers={"X-Secret-Key": "dash-secret"})).json()
finally:
released.set() # an interpreter exit joins the probe thread, so do not leave it asleep
ids = [c["id"] for c in body["checks"]]
assert "ffmpeg" in ids, "the probe that finished before the deadline must survive"
+2 -15
View File
@@ -233,13 +233,7 @@ async def test_cors_preflight_returns_headers(make_app, aiohttp_client) -> None:
assert "X-Secret-Key" in resp.headers["Access-Control-Allow-Headers"]
async def test_health_endpoint_responds_ok(make_app, aiohttp_client, monkeypatch: pytest.MonkeyPatch) -> None:
from unshackle.core.api import routes as routes_mod
async def no_update(_):
return None
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", no_update)
async def test_health_endpoint_responds_ok(make_app, aiohttp_client) -> None:
app = make_app(remote_only=True)
client = await aiohttp_client(app)
resp = await client.get("/api/health")
@@ -249,14 +243,7 @@ async def test_health_endpoint_responds_ok(make_app, aiohttp_client, monkeypatch
assert "version" in body
async def test_health_bypasses_api_key_auth_middleware(make_app, aiohttp_client, monkeypatch) -> None:
from unshackle.core.api import routes as routes_mod
async def no_update(_):
return None
monkeypatch.setattr(routes_mod.UpdateChecker, "check_for_updates", no_update)
async def test_health_bypasses_api_key_auth_middleware(make_app, aiohttp_client) -> None:
app = make_app(remote_only=True, with_auth_middleware=True)
client = await aiohttp_client(app)
resp = await client.get("/api/health")
+1 -1
View File
@@ -158,7 +158,7 @@ def test_a_music_post_script_command_builds_the_argv_a_script_would_get(monkeypa
dispatch("success", "file", context)
for _ in range(100):
if marker.exists():
if marker.exists() and marker.stat().st_size:
break
import time