"""Every test runs against a real hub app on a throwaway SQLite file. The engine is global, so each test gets its own database URL + a settings-cache reset; that also proves PG/MySQL portability is only a URL swap. """ from __future__ import annotations import time from typing import Any, Callable import pytest from fastapi.testclient import TestClient BASE = "/api/v1" def hub_client(tmp_path, monkeypatch, **extra_env) -> TestClient: """Boot a real hub on a throwaway SQLite file; the caller opens it as a CM. ``extra_env`` is for a module that wants a different switch (see config.py). """ from agenthub.config import reset_settings_cache monkeypatch.setenv("AGENTHUB_DATABASE_URL", f"sqlite+aiosqlite:///{tmp_path / 'hub.db'}") monkeypatch.setenv("AGENTHUB_DATA_DIR", str(tmp_path)) monkeypatch.setenv("AGENTHUB_AUTH_ENABLED", "false") monkeypatch.setenv("AGENTHUB_PRESENCE_ENABLED", "false") monkeypatch.setenv("AGENTHUB_HUB_PUBLIC_URL", "http://127.0.0.1:8100") for key, value in extra_env.items(): monkeypatch.setenv(key, value) reset_settings_cache() from agenthub.app import create_app return TestClient(create_app()) @pytest.fixture() def hub(tmp_path, monkeypatch) -> TestClient: with hub_client(tmp_path, monkeypatch) as client: yield client from agenthub.config import reset_settings_cache reset_settings_cache() # --- helpers --------------------------------------------------------------- def register(client: TestClient, name: str, **fields: Any) -> dict[str, Any]: """建档 + 签发,返回 connector 拿到的那份东西:id + 凭证。 以前这里要先签 enrollment token 再换身份;接入只剩一条路之后, 建 Agent 的时候顺手把凭证签出来就是全部了。 """ response = client.post( f"{BASE}/agents", json={"name": name, "issue_credential": True, **fields}, ) assert response.status_code == 201, response.text body = response.json() assert body.get("agent_token"), response.text return {"agent_id": body["id"], "agent_name": body["name"], "agent_token": body["agent_token"]} def add_agent(client: TestClient, name: str, **fields: Any) -> dict[str, Any]: response = client.post(f"{BASE}/agents", json={"name": name, **fields}) assert response.status_code == 201, response.text return response.json() def mock_agent(client: TestClient, name: str, **config: Any) -> dict[str, Any]: return add_agent(client, name, driver="mock", config=config or {"delay_s": 0}) def wait_for(predicate: Callable[[], Any], timeout: float = 10.0, interval: float = 0.05) -> Any: deadline = time.time() + timeout while time.time() < deadline: value = predicate() if value: return value time.sleep(interval) raise AssertionError("condition never became true") def task_status(client: TestClient, task_id: str) -> str: return client.get(f"{BASE}/tasks/{task_id}").json()["status"] def sse_payloads(text: str) -> list[dict[str, Any]]: import json return [json.loads(line[5:]) for line in text.splitlines() if line.startswith("data: ")]