ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.
Python ai-agentsamdcomfyuidockerllama-cppllmlocal-ain8nnvidiaopen-webuiragself-hostedspeech-to-textstrix-halotext-to-speechworkflow-automation
"""Shared fixtures for dashboard-api unit tests."""
import json
import os
import sys
import types
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
import pytest
# Add dashboard-api source to path so we can import modules directly.
DASHBOARD_API_DIR = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(DASHBOARD_API_DIR))
# Set env vars BEFORE any app imports so config.py and security.py initialise
# correctly (they read env at module level).
_TEST_API_KEY = "test-key-12345"
_TEST_SHIELD_KEY = "test-shield-key-fixture"
os.environ.setdefault("DASHBOARD_API_KEY", _TEST_API_KEY)
os.environ.setdefault("SHIELD_API_KEY", _TEST_SHIELD_KEY)
os.environ.setdefault("ODS_INSTALL_DIR", "/tmp/ods-test-install")
os.environ.setdefault("ODS_DATA_DIR", "/tmp/ods-test-data")
os.environ.setdefault("ODS_EXTENSIONS_DIR", "/tmp/ods-test-extensions")
os.environ.setdefault("GPU_BACKEND", "nvidia")
os.environ.setdefault("ODS_MODE", "local")
if "fcntl" not in sys.modules:
try:
import fcntl # type: ignore # noqa: F401
except ModuleNotFoundError:
sys.modules["fcntl"] = types.SimpleNamespace(
LOCK_EX=0,
LOCK_UN=0,
flock=lambda *args, **kwargs: None,
)
FIXTURES_DIR = Path(__file__).resolve().parent / "fixtures"
@pytest.fixture
def mock_edge_read_transport(monkeypatch):
"""Reuse the existing fake HTTP client in legacy handler-only tests."""
import httpx
import pixel_edge_read_client
from routers import pixel
original_factory = httpx.AsyncClient
clients = {}
def get_fake():
factory = httpx.AsyncClient
assert factory is not original_factory, 'Handler test must provide a fake edge transport'
if factory not in clients:
clients[factory] = factory()
return clients[factory]
monkeypatch.setattr(pixel, 'get_edge_read_client', get_fake)
monkeypatch.setattr(pixel_edge_read_client, 'get_edge_read_client', get_fake)
@pytest.fixture(autouse=True)
def _no_remembered_portal_status(monkeypatch):
"""Each test starts without an available Portal status remembered by an earlier one."""
from routers import pixel
monkeypatch.setattr(pixel, "_last_available_status", None)
@pytest.fixture(autouse=True)
def _no_remembered_release_check(monkeypatch):
"""Each test starts without a release or a failed check remembered by an earlier one."""
from routers import updates
monkeypatch.setattr(updates, "_version_cache", {"expires_at": 0.0, "payload": None})
monkeypatch.setattr(updates, "_version_hold", {"until": 0.0, "rate_limited": False})
monkeypatch.setattr(updates, "_version_refresh_task", None)
@pytest.fixture(autouse=True)
def _no_remembered_model_management(monkeypatch):
"""Each test starts without a model management proof remembered by an earlier one."""
from routers import models
monkeypatch.setattr(models, "_model_management_remembered", None)
monkeypatch.setattr(models, "_model_management_proof_future", None)
monkeypatch.setattr(models, "_model_management_missed", False)
@pytest.fixture(autouse=True)
def _no_hugging_face_header_reads(monkeypatch):
"""Unit tests never reach Hugging Face; a test that needs a header stubs one."""
import hf_gguf_header
async def unreachable(*_args, **_kwargs):
raise hf_gguf_header.HeaderUnavailable("unreachable", "unit tests do not read Hugging Face")
monkeypatch.setattr(hf_gguf_header, "fetch_gguf_header", unreachable)
@pytest.fixture(autouse=True)
def _no_runtime_probe_requests(monkeypatch):
"""Unit tests never probe a real llama-server (a developer machine may run one on
127.0.0.1:8080). Every loaded copy of the host agent gets an unreachable runtime;
a test that exercises the probes stubs ``_runtime_exchange`` itself."""
def unreachable(*_args, **_kwargs):
raise OSError("unit tests do not probe a real runtime")
for module in list(sys.modules.values()):
if getattr(module, "_profile_model", None) is not None and hasattr(module, "_runtime_exchange"):
monkeypatch.setattr(module, "_runtime_exchange", unreachable)
@pytest.fixture()
def install_dir(tmp_path, monkeypatch):
"""Provide an isolated install directory with a .env file."""
d = tmp_path / "ods"
d.mkdir()
monkeypatch.setattr("helpers.INSTALL_DIR", str(d))
return d
@pytest.fixture()
def data_dir(tmp_path, monkeypatch):
"""Provide an isolated data directory for bootstrap/token files."""
d = tmp_path / "data"
d.mkdir()
monkeypatch.setattr("helpers.DATA_DIR", str(d))
monkeypatch.setattr("helpers._TOKEN_FILE", d / "token_counter.json")
monkeypatch.setattr("helpers._PERF_FILE", d / "model_performance.json")
return d
@pytest.fixture()
def setup_config_dir(tmp_path, monkeypatch):
"""Provide isolated setup files behind a fake host-agent boundary."""
d = tmp_path / "config"
d.mkdir()
import routers.setup as setup_router
def fake_setup_agent(method, path, payload=None, timeout=5):
del timeout
if method == "GET" and path == "/v1/setup/state":
def read_object(name):
state_file = d / name
if not state_file.exists():
return False, None
try:
value = json.loads(state_file.read_text(encoding="utf-8"))
except json.JSONDecodeError:
return True, None
return True, value if isinstance(value, dict) else None
complete_exists, _ = read_object("setup-complete.json")
_, progress = read_object("setup-progress.json")
_, persona_data = read_object("persona.json")
return {
"first_run": not complete_exists,
"step": progress.get("step", 0) if progress else 0,
"persona": persona_data.get("persona") if persona_data else None,
"persona_data": persona_data,
}
if method == "POST" and path == "/v1/setup/persona":
assert payload is not None
(d / "persona.json").write_text(
json.dumps(payload, indent=2),
encoding="utf-8",
)
(d / "setup-progress.json").write_text(
json.dumps({"step": 2, "persona_selected": True}),
encoding="utf-8",
)
return {"success": True}
if method == "POST" and path == "/v1/setup/complete":
(d / "setup-complete.json").write_text(
json.dumps({"completed_at": "now", "version": "1.0.0"}),
encoding="utf-8",
)
(d / "setup-progress.json").unlink(missing_ok=True)
return {"success": True}
raise AssertionError(f"Unexpected setup host-agent request: {method} {path}")
monkeypatch.setattr(setup_router, "request_agent_json", fake_setup_agent)
return d
@pytest.fixture()
def test_client(monkeypatch):
"""Return a FastAPI TestClient pre-configured with Bearer auth."""
import security
monkeypatch.setattr(security, "DASHBOARD_API_KEY", _TEST_API_KEY)
from fastapi.testclient import TestClient
from main import app
client = TestClient(app, raise_server_exceptions=True)
client.auth_headers = {"Authorization": f"Bearer {_TEST_API_KEY}"}
return client
def load_golden_fixture(name: str):
"""Load a JSON or text fixture from tests/fixtures/.
Returns parsed JSON for .json files, raw text for anything else.
"""
path = FIXTURES_DIR / name
text = path.read_text()
if path.suffix == ".json":
return json.loads(text)
return text
@pytest.fixture()
def mock_aiohttp_session():
"""Return a factory that creates a mock aiohttp.ClientSession.
Usage::
session = mock_aiohttp_session(status=200, json_data={"ok": True})
monkeypatch.setattr("helpers._get_aio_session", AsyncMock(return_value=session))
"""
def _factory(status: int = 200, json_data=None, text_data: str = "",
raise_on_get=None):
response = AsyncMock()
response.status = status
response.json = AsyncMock(return_value=json_data or {})
response.text = AsyncMock(return_value=text_data)
ctx = AsyncMock()
ctx.__aenter__ = AsyncMock(return_value=response)
ctx.__aexit__ = AsyncMock(return_value=False)
session = MagicMock()
if raise_on_get:
session.get = MagicMock(side_effect=raise_on_get)
else:
session.get = MagicMock(return_value=ctx)
return session
return _factory