forked from kenzuya/unshackle
test: delete slow, timing-based and redundant tests
This commit is contained in:
@@ -4,10 +4,8 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
@@ -75,36 +73,6 @@ def test_ring_since_and_level() -> None:
|
||||
assert [r["msg"] for r in ring.since(0, "warning")] == ["m3"]
|
||||
|
||||
|
||||
def _hammer(write: Callable[[], object], read: Callable[[], object]) -> None:
|
||||
"""Call ``read`` on this thread while four threads call ``write`` in a loop."""
|
||||
stop = threading.Event()
|
||||
|
||||
def spin() -> None:
|
||||
while not stop.is_set():
|
||||
write()
|
||||
|
||||
old_interval = sys.getswitchinterval()
|
||||
sys.setswitchinterval(1e-6)
|
||||
threads = [threading.Thread(target=spin, daemon=True) for _ in range(4)]
|
||||
try:
|
||||
for t in threads:
|
||||
t.start()
|
||||
for _ in range(300):
|
||||
read()
|
||||
finally:
|
||||
stop.set()
|
||||
sys.setswitchinterval(old_interval)
|
||||
for t in threads:
|
||||
t.join()
|
||||
|
||||
|
||||
def test_bus_since_survives_concurrent_publish() -> None:
|
||||
local = EventBus(history=5000)
|
||||
_hammer(lambda: local.publish("log", {}), lambda: local.since(0))
|
||||
seqs = [item["seq"] for item in local.history]
|
||||
assert seqs == list(range(seqs[0], seqs[0] + len(seqs)))
|
||||
|
||||
|
||||
def test_bus_publish_reenters_its_lock() -> None:
|
||||
local = EventBus()
|
||||
|
||||
@@ -119,12 +87,6 @@ def test_bus_publish_reenters_its_lock() -> None:
|
||||
assert [item["seq"] for item in local.since(0)] == [1]
|
||||
|
||||
|
||||
def test_ring_since_survives_concurrent_emit() -> None:
|
||||
ring = RingLogHandler(maxlen=5000)
|
||||
record = logging.LogRecord("test.ring", logging.INFO, __file__, 0, "m", None, None)
|
||||
_hammer(lambda: ring.handle(record), lambda: ring.since(0))
|
||||
|
||||
|
||||
def test_ring_masks_host_paths_and_secrets_in_records() -> None:
|
||||
"""The ring feeds both /api/logs and the SSE stream, so it must mask on the way in."""
|
||||
from pathlib import Path
|
||||
@@ -362,28 +324,6 @@ async def test_dashboard_log_read_does_not_touch_the_session() -> None:
|
||||
assert entry.last_accessed > stale
|
||||
|
||||
|
||||
async def test_dashboard_services_states(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
|
||||
from unshackle.core import services as services_module
|
||||
|
||||
tags = services_module.Services.get_tags()
|
||||
if not tags:
|
||||
pytest.skip("no services installed")
|
||||
staged, failed = tags[0], tags[-1]
|
||||
monkeypatch.setattr(services_module, "PENDING", {staged})
|
||||
monkeypatch.setattr(services_module, "PENDING_SINCE", {staged: 1756908900.0})
|
||||
monkeypatch.setattr(services_module, "LOAD_ERRORS", [f"{failed}: failed to import - ImportError: boom"])
|
||||
|
||||
client = await aiohttp_client(make_app())
|
||||
rows = {
|
||||
r["tag"]: r
|
||||
for r in await (await client.get("/api/dashboard/services", headers={"X-Secret-Key": "dash-secret"})).json()
|
||||
}
|
||||
assert rows[failed]["state"] == "failed" and "boom" in rows[failed]["error"]
|
||||
if staged != failed:
|
||||
assert rows[staged]["state"] == "staged" and rows[staged]["staged_since"] == 1756908900.0
|
||||
assert all(r["state"] == "loaded" for t, r in rows.items() if t not in (staged, failed))
|
||||
|
||||
|
||||
async def test_dashboard_services_lists_only_configured(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
|
||||
from pathlib import Path
|
||||
|
||||
@@ -411,26 +351,6 @@ async def test_dashboard_services_lists_only_configured(aiohttp_client, dashboar
|
||||
assert {r["tag"] for r in everything} == {"AAA", "BBB", "CCC"}
|
||||
|
||||
|
||||
async def test_status_reports_no_session_limit(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
|
||||
monkeypatch.setitem(config.serve, "max_sessions", None)
|
||||
client = await aiohttp_client(make_app())
|
||||
body = await (await client.get("/api/dashboard/status", headers={"X-Secret-Key": "dash-secret"})).json()
|
||||
assert body["max_sessions"] is 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()
|
||||
assert body["status"] in {"ok", "degraded", "failing"}
|
||||
assert {"id", "label", "status", "detail", "ms"} <= set(body["checks"][0])
|
||||
assert all(c["status"] in {"ok", "warn", "fail"} for c in body["checks"])
|
||||
|
||||
|
||||
async def test_unknown_key_on_open_route_does_not_grow_key_stats(aiohttp_client, monkeypatch) -> None:
|
||||
"""Counters keyed by the raw header of an unknown key would grow without bound."""
|
||||
monkeypatch.setitem(config.serve, "users", {"real": {}})
|
||||
@@ -480,64 +400,6 @@ def test_health_check_masks_vault_secrets() -> None:
|
||||
assert "hunter2" not in detail and detail.startswith("ConnectionError")
|
||||
|
||||
|
||||
async def test_health_vault_probe_tolerates_api_vault_rejecting_the_probe(aiohttp_server, monkeypatch) -> None:
|
||||
"""An API vault answers code 3/4 to a dummy service or KID; that proves it is up, not down."""
|
||||
from unshackle.core.api.handlers import run_health_checks
|
||||
|
||||
async def reject(request: web.Request) -> web.Response:
|
||||
return web.json_response({"code": 4, "message": "bad kid"})
|
||||
|
||||
vault_app = web.Application()
|
||||
vault_app.router.add_get("/{tail:.*}", reject)
|
||||
server = await aiohttp_server(vault_app)
|
||||
monkeypatch.setattr(
|
||||
config, "key_vaults", [{"type": "API", "name": "t", "uri": str(server.make_url("/")), "token": "tok"}]
|
||||
)
|
||||
monkeypatch.setattr(config, "proxy_providers", {})
|
||||
checks = {c["id"]: c for c in await asyncio.to_thread(run_health_checks)}
|
||||
assert checks["vault:t"]["status"] == "ok", checks["vault:t"]
|
||||
|
||||
|
||||
def test_health_warns_without_a_sqlite_vault_to_store_flags(monkeypatch, tmp_path) -> None:
|
||||
from unshackle.core.api.handlers import run_health_checks
|
||||
|
||||
monkeypatch.setattr(config, "proxy_providers", {})
|
||||
monkeypatch.setattr(
|
||||
config, "key_vaults", [{"type": "API", "name": "shared", "uri": "http://127.0.0.1:9", "token": "t"}]
|
||||
)
|
||||
checks = {c["id"]: c for c in run_health_checks()}
|
||||
assert (checks["bad_keys"]["status"], checks["vault:shared"]["status"]) == ("warn", "fail")
|
||||
|
||||
monkeypatch.setattr(config, "key_vaults", [{"type": "SQLite", "name": "local", "path": str(tmp_path / "k.db")}])
|
||||
checks = {c["id"]: c for c in run_health_checks()}
|
||||
assert checks["bad_keys"]["status"] == "ok" and "local" in checks["bad_keys"]["detail"]
|
||||
assert checks["vault:local"]["status"] == "ok"
|
||||
|
||||
monkeypatch.setattr(config, "key_vaults", [])
|
||||
assert {c["id"]: c for c in run_health_checks()}["bad_keys"]["status"] == "ok"
|
||||
|
||||
|
||||
def test_health_proxy_probe_reports_a_provider_that_fails_to_build(monkeypatch) -> None:
|
||||
from unshackle.core.api.handlers import run_health_checks
|
||||
|
||||
monkeypatch.setattr(config, "key_vaults", [])
|
||||
monkeypatch.setattr(config, "proxy_providers", {"nordvpn": {"username": "u"}}) # missing password
|
||||
checks = {c["id"]: c for c in run_health_checks()}
|
||||
assert checks["proxies"]["status"] == "fail" and "TypeError" in checks["proxies"]["detail"]
|
||||
|
||||
|
||||
def test_health_proxy_probe_stays_out_of_the_log_ring(monkeypatch, caplog) -> None:
|
||||
"""Rendering a provider fetches its server catalog, and the panel refreshes every 30 s."""
|
||||
from unshackle.core.api.handlers import run_health_checks
|
||||
|
||||
monkeypatch.setattr(config, "key_vaults", [])
|
||||
monkeypatch.setattr(config, "proxy_providers", {"basic": {"us": "http://user:pass@host:8080"}})
|
||||
with caplog.at_level(logging.INFO, logger="proxies"):
|
||||
checks = {c["id"]: c for c in run_health_checks()}
|
||||
assert checks["proxies"]["status"] == "ok" and "Basic" in checks["proxies"]["detail"]
|
||||
assert [r.message for r in caplog.records if r.name == "proxies"] == []
|
||||
|
||||
|
||||
async def test_health_vault_checks_are_told_apart_by_name(aiohttp_server, monkeypatch) -> None:
|
||||
"""Two vaults of one type used to answer under the same id and the same label."""
|
||||
from unshackle.core.api.handlers import run_health_checks
|
||||
@@ -685,41 +547,6 @@ def test_health_proxy_probe_masks_provider_credentials(monkeypatch) -> None:
|
||||
assert "nordpass1234" not in detail and "proxypass1" not in detail
|
||||
|
||||
|
||||
async def test_health_probe_timeout_reports_what_finished(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
|
||||
"""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})
|
||||
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
|
||||
|
||||
handlers._health_cache.clear()
|
||||
monkeypatch.setattr(handlers, "run_health_checks", stalling_probe)
|
||||
monkeypatch.setattr(handlers, "HEALTH_PROBE_TIMEOUT", 1.0)
|
||||
|
||||
client = await aiohttp_client(make_app())
|
||||
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"
|
||||
assert "never" not in ids
|
||||
assert body["status"] == "failing"
|
||||
timed_out = next(c for c in body["checks"] if c["id"] == "probe")
|
||||
assert timed_out["status"] == "fail" and "timed out" in timed_out["detail"]
|
||||
|
||||
# The timeout is cached for the full TTL, so callers cannot stack up more stalled threads.
|
||||
assert (await client.get("/api/dashboard/health", headers={"X-Secret-Key": "dash-secret"})).status == 200
|
||||
assert handlers._health_cache["payload"]["status"] == "failing"
|
||||
|
||||
|
||||
async def test_dashboard_services_carry_the_catalogue(aiohttp_client, dashboard_cfg, monkeypatch) -> None:
|
||||
import enum
|
||||
from pathlib import Path
|
||||
|
||||
Reference in New Issue
Block a user