feat: 扩展 Rust gateway 全功能模块,新增 billing/crypto/wallet crate 及完整数据层

- 新增 aether-billing、aether-crypto、aether-wallet 独立 crate
- aether-data 扩展 repository 层:announcements、auth_modules、billing、
  candidate_selection、gemini_file_mappings、global_models、management_tokens、
  oauth_providers、proxy_nodes、quota、users、wallet 等模块
- aether-gateway 新增 api/auth/billing/control/middleware/scheduler/usage/
  video_tasks/hooks/maintenance/model_fetch/provider_transport 等功能模块
- 重构 executor decision 和 gateway state 为模块目录结构
- 新增 gateway router、frontdoor 路由层及对应测试
- Python 侧 API 路由重构,新增 compat/support 模块
- 前端 Logo 组件更新及 Provider 管理页面调整
This commit is contained in:
fawney19
2026-03-31 19:19:04 +08:00
parent b5a0070023
commit ddf18fed9a
690 changed files with 235087 additions and 16301 deletions

View File

@@ -5,8 +5,8 @@ from collections.abc import AsyncGenerator
from types import SimpleNamespace
from unittest.mock import AsyncMock
import httpx
import pytest
from fastapi import Response
from fastapi.responses import StreamingResponse
import src.api.public.gemini_files as gemini_files_mod
@@ -127,12 +127,6 @@ async def test_proxy_request_passes_proxy_snapshot_to_rust_executor(
"execute_sync_json",
_fake_execute_sync_json,
)
monkeypatch.setattr(
gemini_files_mod.HTTPClientPool,
"get_upstream_client",
AsyncMock(side_effect=AssertionError("python fallback should not run")),
)
response = await gemini_files_mod._proxy_request(
"GET",
"https://generativelanguage.googleapis.com/v1beta/files",
@@ -150,57 +144,30 @@ async def test_proxy_request_passes_proxy_snapshot_to_rust_executor(
@pytest.mark.asyncio
async def test_proxy_request_fallback_uses_upstream_client_proxy_context(
async def test_proxy_request_returns_503_when_rust_unavailable(
monkeypatch: pytest.MonkeyPatch,
) -> None:
class _FakeClient:
async def get(self, url: str, headers: dict[str, str]) -> httpx.Response:
assert url == "https://generativelanguage.googleapis.com/v1beta/files"
assert headers == {"x-goog-api-key": "upstream-key"}
return httpx.Response(
200,
request=httpx.Request("GET", url),
json={"files": []},
)
async def _fake_try_rust_sync_proxy_request(*args: object, **kwargs: object) -> None:
async def _fake_try_rust_sync_proxy_request(*args: object, **kwargs: object) -> Response:
del args, kwargs
return None
async def _fake_get_upstream_client(
delegate_cfg: dict[str, object] | None,
*,
proxy_config: dict[str, object] | None = None,
tls_profile: str | None = None,
) -> _FakeClient:
assert delegate_cfg == {"tunnel": True, "node_id": "node-1"}
assert proxy_config == {"enabled": True, "node_id": "node-1"}
assert tls_profile is None
return _FakeClient()
return gemini_files_mod._build_rust_unavailable_response()
monkeypatch.setattr(
gemini_files_mod,
"_try_rust_sync_proxy_request",
_fake_try_rust_sync_proxy_request,
)
monkeypatch.setattr(
gemini_files_mod.HTTPClientPool,
"get_upstream_client",
_fake_get_upstream_client,
)
response = await gemini_files_mod._proxy_request(
"GET",
"https://generativelanguage.googleapis.com/v1beta/files",
{"x-goog-api-key": "upstream-key"},
file_key_id="key-1",
user_id="user-1",
proxy_config={"enabled": True, "node_id": "node-1"},
delegate_config={"tunnel": True, "node_id": "node-1"},
)
assert response.status_code == 200
assert json.loads(response.body) == {"files": []}
body = json.loads(response.body)
assert response.status_code == 503
assert body["error"]["code"] == 503
assert body["error"]["status"] == "UNAVAILABLE"
@pytest.mark.asyncio
@@ -275,13 +242,7 @@ async def test_download_file_uses_enriched_proxy_snapshot_for_regular_files(
"execute_stream",
_fake_execute_stream,
)
monkeypatch.setattr(
gemini_files_mod.HTTPClientPool,
"get_upstream_client",
AsyncMock(side_effect=AssertionError("python fallback should not run")),
)
response = await gemini_files_mod.download_file(
response = await gemini_files_mod._download_file_response(
"file-1",
SimpleNamespace(
headers={},
@@ -294,3 +255,71 @@ async def test_download_file_uses_enriched_proxy_snapshot_for_regular_files(
body = b"".join([chunk async for chunk in response.body_iterator])
assert body == b"file-bytes"
assert dummy_ctx.closed is True
@pytest.mark.asyncio
async def test_download_file_returns_503_when_rust_stream_unavailable(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setattr(config, "executor_backend", "rust")
raw_ctx = UpstreamContext(
upstream_key="upstream-key",
base_url="https://generativelanguage.googleapis.com",
file_key_id="key-1",
user_id="user-1",
provider_id="prov-1",
endpoint_id="ep-1",
)
enriched_ctx = UpstreamContext(
upstream_key="upstream-key",
base_url="https://generativelanguage.googleapis.com",
file_key_id="key-1",
user_id="user-1",
provider_id="prov-1",
endpoint_id="ep-1",
)
monkeypatch.setattr(gemini_files_mod, "_extract_gemini_api_key", lambda request: "client-key")
monkeypatch.setattr(
gemini_files_mod,
"create_session",
lambda: _FakeDBContext(SimpleNamespace()),
)
monkeypatch.setattr(
gemini_files_mod.AuthService,
"authenticate_api_key",
lambda db, key: (SimpleNamespace(id="user-1"), SimpleNamespace(id="user-api-key")),
)
monkeypatch.setattr(gemini_files_mod, "_ensure_balance_access", lambda db, user, api_key: None)
monkeypatch.setattr(
gemini_files_mod,
"_resolve_upstream_context",
AsyncMock(return_value=raw_ctx),
)
monkeypatch.setattr(
gemini_files_mod,
"_enrich_upstream_context_proxy",
AsyncMock(return_value=enriched_ctx),
)
async def _fake_execute_stream(self: object, plan: object) -> RustExecutorStreamResult:
del self, plan
raise rust_client_mod.RustExecutorClientError("executor unavailable")
monkeypatch.setattr(
rust_client_mod.RustExecutorClient,
"execute_stream",
_fake_execute_stream,
)
response = await gemini_files_mod._download_file_response(
"file-1",
SimpleNamespace(
headers={},
query_params={"alt": "media"},
),
)
body = json.loads(response.body)
assert response.status_code == 503
assert body["error"]["code"] == 503
assert body["error"]["status"] == "UNAVAILABLE"

View File

@@ -0,0 +1,133 @@
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from src.database import get_db
def _build_app(
monkeypatch: pytest.MonkeyPatch,
*,
pipeline_result: Any,
) -> tuple[TestClient, list[dict[str, Any]]]:
from src.api.public import gemini_files as mod
app = FastAPI()
app.include_router(mod.router)
app.dependency_overrides[get_db] = lambda: MagicMock()
calls: list[dict[str, Any]] = []
async def _fake_pipeline_run(
*,
adapter: Any,
http_request: object,
db: object,
mode: object,
api_format_hint: str | None = None,
path_params: dict[str, Any] | None = None,
) -> Any:
del http_request, db, api_format_hint, path_params
calls.append(
{
"adapter_type": type(adapter).__name__,
"mode": getattr(mode, "value", mode),
"adapter_state": dict(getattr(adapter, "__dict__", {})),
}
)
return pipeline_result
monkeypatch.setattr(mod.pipeline, "run", _fake_pipeline_run)
return TestClient(app), calls
def test_gemini_files_upload_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"file": {"name": "files/1"}})
response = client.post("/upload/v1beta/files")
assert response.status_code == 200
assert response.json() == {"file": {"name": "files/1"}}
assert calls == [
{
"adapter_type": "PublicGeminiFilesUploadAdapter",
"mode": "public",
"adapter_state": {},
}
]
def test_gemini_files_list_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"files": []})
response = client.get("/v1beta/files?pageSize=20&pageToken=next-1")
assert response.status_code == 200
assert response.json() == {"files": []}
assert calls == [
{
"adapter_type": "PublicGeminiFilesListAdapter",
"mode": "public",
"adapter_state": {
"page_size": 20,
"page_token": "next-1",
},
}
]
def test_gemini_files_download_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"download": "ok"})
response = client.get("/v1beta/files/file-1:download?alt=media")
assert response.status_code == 200
assert response.json() == {"download": "ok"}
assert calls == [
{
"adapter_type": "PublicGeminiFilesDownloadAdapter",
"mode": "public",
"adapter_state": {"file_id": "file-1"},
}
]
def test_gemini_files_get_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"name": "files/file-1"})
response = client.get("/v1beta/files/file-1")
assert response.status_code == 200
assert response.json() == {"name": "files/file-1"}
assert calls == [
{
"adapter_type": "PublicGeminiFilesGetAdapter",
"mode": "public",
"adapter_state": {"file_name": "file-1"},
}
]
def test_gemini_files_delete_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"deleted": True})
response = client.delete("/v1beta/files/file-1")
assert response.status_code == 200
assert response.json() == {"deleted": True}
assert calls == [
{
"adapter_type": "PublicGeminiFilesDeleteAdapter",
"mode": "public",
"adapter_state": {"file_name": "file-1"},
}
]

View File

@@ -0,0 +1,117 @@
from __future__ import annotations
from typing import Any
import pytest
from starlette.requests import Request
def _make_request(path: str, method: str = "POST", headers: list[tuple[bytes, bytes]] | None = None) -> Request:
scope = {
"type": "http",
"asgi": {"version": "3.0"},
"http_version": "1.1",
"method": method,
"scheme": "http",
"path": path,
"raw_path": path.encode(),
"query_string": b"",
"headers": headers or [],
"client": ("127.0.0.1", 12345),
"server": ("testserver", 80),
}
return Request(scope)
@pytest.mark.asyncio
@pytest.mark.parametrize(
("route", "model", "stream"),
[
("v1beta_generate", "gemini-2.5-flash", False),
("v1beta_stream", "gemini-2.5-flash", True),
("v1_generate", "gemini-2.5-flash", False),
("v1_stream", "gemini-2.5-flash", True),
],
)
async def test_public_gemini_routes_use_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
route: str,
model: str,
stream: bool,
) -> None:
from src.api.public import gemini as mod
captured: dict[str, Any] = {}
async def fake_run(*, adapter, http_request, db, mode, api_format_hint, path_params, **_kwargs):
captured.update(
{
"adapter": adapter,
"request": http_request,
"db": db,
"mode": mode,
"api_format_hint": api_format_hint,
"path_params": path_params,
}
)
return {"ok": True}
monkeypatch.setattr(mod.pipeline, "run", fake_run)
db = object()
request = _make_request(f"/{route}")
if route == "v1beta_generate":
result = await mod.generate_content(model=model, http_request=request, db=db)
elif route == "v1beta_stream":
result = await mod.stream_generate_content(model=model, http_request=request, db=db)
elif route == "v1_generate":
result = await mod.generate_content_v1(model=model, http_request=request, db=db)
else:
result = await mod.stream_generate_content_v1(model=model, http_request=request, db=db)
assert result == {"ok": True}
assert isinstance(captured["adapter"], mod.PublicGeminiContentAdapter)
assert captured["adapter"].model == model
assert captured["adapter"].stream is stream
assert captured["request"] is request
assert captured["db"] is db
assert captured["mode"] == captured["adapter"].mode
assert captured["api_format_hint"] == "gemini:chat"
assert captured["path_params"] == {"model": model, "stream": stream}
@pytest.mark.asyncio
async def test_public_gemini_shell_detects_cli_request_for_api_format_hint(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from src.api.public import gemini as mod
captured: dict[str, Any] = {}
async def fake_run(*, adapter, http_request, db, mode, api_format_hint, path_params, **_kwargs):
captured.update(
{
"adapter": adapter,
"request": http_request,
"db": db,
"mode": mode,
"api_format_hint": api_format_hint,
"path_params": path_params,
}
)
return {"ok": True}
monkeypatch.setattr(mod.pipeline, "run", fake_run)
request = _make_request(
"/v1beta/models/gemini-2.5-flash:generateContent",
headers=[(b"x-app", b"gemini-cli")],
)
result = await mod.generate_content(model="gemini-2.5-flash", http_request=request, db=object())
assert result == {"ok": True}
assert isinstance(captured["adapter"], mod.PublicGeminiContentAdapter)
assert captured["api_format_hint"] == "gemini:cli"
assert captured["path_params"] == {"model": "gemini-2.5-flash", "stream": False}

View File

@@ -0,0 +1,153 @@
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from src.database import get_db
def _build_app(
monkeypatch: pytest.MonkeyPatch,
module_name: str,
*,
pipeline_result: Any,
) -> tuple[TestClient, list[dict[str, Any]]]:
module = __import__(module_name, fromlist=["router", "pipeline"])
app = FastAPI()
app.include_router(module.router)
app.dependency_overrides[get_db] = lambda: MagicMock()
calls: list[dict[str, Any]] = []
async def _fake_pipeline_run(
*,
adapter: Any,
http_request: object,
db: object,
mode: object,
api_format_hint: str | None = None,
path_params: dict[str, Any] | None = None,
) -> Any:
del http_request, db, api_format_hint, path_params
calls.append(
{
"adapter_type": type(adapter).__name__,
"mode": getattr(mode, "value", mode),
"adapter_state": dict(getattr(adapter, "__dict__", {})),
}
)
return pipeline_result
monkeypatch.setattr(module.pipeline, "run", _fake_pipeline_run)
return TestClient(app), calls
def test_public_site_info_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(
monkeypatch,
"src.api.public.catalog",
pipeline_result={"site_name": "Aether", "site_subtitle": "AI Gateway"},
)
response = client.get("/api/public/site-info")
assert response.status_code == 200
assert response.json() == {"site_name": "Aether", "site_subtitle": "AI Gateway"}
assert calls == [
{
"adapter_type": "PublicSiteInfoAdapter",
"mode": "public",
"adapter_state": {},
}
]
def test_public_modules_auth_status_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(
monkeypatch,
"src.api.public.modules",
pipeline_result=[{"name": "oauth", "display_name": "OAuth", "active": True}],
)
response = client.get("/api/modules/auth-status")
assert response.status_code == 200
assert response.json() == [{"name": "oauth", "display_name": "OAuth", "active": True}]
assert calls == [
{
"adapter_type": "PublicAuthModulesStatusAdapter",
"mode": "public",
"adapter_state": {},
}
]
def test_public_capabilities_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(
monkeypatch,
"src.api.public.capabilities",
pipeline_result={"capabilities": []},
)
response = client.get("/api/capabilities")
assert response.status_code == 200
assert response.json() == {"capabilities": []}
assert calls == [
{
"adapter_type": "PublicCapabilitiesListAdapter",
"mode": "public",
"adapter_state": {},
}
]
def test_public_user_configurable_capabilities_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(
monkeypatch,
"src.api.public.capabilities",
pipeline_result={"capabilities": [{"name": "vision"}]},
)
response = client.get("/api/capabilities/user-configurable")
assert response.status_code == 200
assert response.json() == {"capabilities": [{"name": "vision"}]}
assert calls == [
{
"adapter_type": "PublicUserConfigurableCapabilitiesAdapter",
"mode": "public",
"adapter_state": {},
}
]
def test_public_model_capabilities_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(
monkeypatch,
"src.api.public.capabilities",
pipeline_result={"model": "gpt-5", "supported_capabilities": []},
)
response = client.get("/api/capabilities/model/gpt-5")
assert response.status_code == 200
assert response.json() == {"model": "gpt-5", "supported_capabilities": []}
assert calls == [
{
"adapter_type": "PublicModelCapabilitiesAdapter",
"mode": "public",
"adapter_state": {"model_name": "gpt-5"},
}
]

View File

@@ -0,0 +1,130 @@
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from src.database import get_db
def _build_app(
monkeypatch: pytest.MonkeyPatch,
*,
pipeline_result: Any,
) -> tuple[TestClient, list[dict[str, Any]]]:
from src.api.public import models as mod
app = FastAPI()
app.include_router(mod.router)
app.dependency_overrides[get_db] = lambda: MagicMock()
calls: list[dict[str, Any]] = []
async def _fake_pipeline_run(
*,
adapter: Any,
http_request: object,
db: object,
mode: object,
api_format_hint: str | None = None,
path_params: dict[str, Any] | None = None,
) -> Any:
del http_request, db, api_format_hint, path_params
calls.append(
{
"adapter_type": type(adapter).__name__,
"mode": getattr(mode, "value", mode),
"adapter_state": dict(getattr(adapter, "__dict__", {})),
}
)
return pipeline_result
monkeypatch.setattr(mod.pipeline, "run", _fake_pipeline_run)
return TestClient(app), calls
def test_public_openai_models_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"object": "list", "data": []})
response = client.get("/v1/models?after_id=model-a&limit=12")
assert response.status_code == 200
assert response.json() == {"object": "list", "data": []}
assert calls == [
{
"adapter_type": "PublicModelsListAdapter",
"mode": "public",
"adapter_state": {
"before_id": None,
"after_id": "model-a",
"limit": 12,
"page_size": 50,
"page_token": None,
},
}
]
def test_public_model_detail_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"id": "gpt-5"})
response = client.get("/v1/models/gpt-5")
assert response.status_code == 200
assert response.json() == {"id": "gpt-5"}
assert calls == [
{
"adapter_type": "PublicModelDetailAdapter",
"mode": "public",
"adapter_state": {
"model_id": "gpt-5",
"force_gemini_name": False,
},
}
]
def test_public_gemini_models_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"models": []})
response = client.get("/v1beta/models?pageSize=25&pageToken=next-1")
assert response.status_code == 200
assert response.json() == {"models": []}
assert calls == [
{
"adapter_type": "PublicModelsListAdapter",
"mode": "public",
"adapter_state": {
"before_id": None,
"after_id": None,
"limit": 20,
"page_size": 25,
"page_token": "next-1",
},
}
]
def test_public_gemini_model_detail_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"name": "models/gemini-2.5-pro"})
response = client.get("/v1beta/models/models/gemini-2.5-pro")
assert response.status_code == 200
assert response.json() == {"name": "models/gemini-2.5-pro"}
assert calls == [
{
"adapter_type": "PublicModelDetailAdapter",
"mode": "public",
"adapter_state": {
"model_id": "models/gemini-2.5-pro",
"force_gemini_name": True,
},
}
]

View File

@@ -5,6 +5,7 @@ from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
from fastapi import HTTPException
def _build_provider_fixture() -> SimpleNamespace:
@@ -65,10 +66,7 @@ async def test_test_connection_prefers_rust_executor(
rust_call = AsyncMock(return_value=rust_response)
monkeypatch.setattr(mod, "_try_rust_test_connection_response", rust_call)
get_upstream_client = AsyncMock(side_effect=AssertionError("python upstream client should not be used"))
monkeypatch.setattr(mod.HTTPClientPool, "get_upstream_client", get_upstream_client)
result = await mod.test_connection(
result = await mod._test_connection_response(
request=SimpleNamespace(query_params={}),
db=MagicMock(),
provider=None,
@@ -79,11 +77,10 @@ async def test_test_connection_prefers_rust_executor(
assert result["status"] == "success"
assert result["response_id"] == "resp_rust"
rust_call.assert_awaited_once()
get_upstream_client.assert_not_awaited()
@pytest.mark.asyncio
async def test_test_connection_fallback_uses_transport_aware_client(
async def test_test_connection_returns_503_when_rust_unavailable(
monkeypatch: pytest.MonkeyPatch,
) -> None:
from src.api.public import system_catalog as mod
@@ -105,38 +102,29 @@ async def test_test_connection_fallback_uses_transport_aware_client(
lambda *_args, **_kwargs: "https://upstream.test/v1/chat/completions",
)
proxy_config = {"enabled": True, "url": "http://proxy.test:8080"}
delegate_cfg = {"node_id": "node-1", "tunnel": True}
monkeypatch.setattr(
mod,
"_build_test_connection_transport_context",
AsyncMock(return_value=(proxy_config, delegate_cfg, None)),
AsyncMock(return_value=({"enabled": True}, {"node_id": "node-1", "tunnel": True}, None)),
)
monkeypatch.setattr(mod, "_try_rust_test_connection_response", AsyncMock(return_value=None))
monkeypatch.setattr(
mod,
"_try_rust_test_connection_response",
AsyncMock(
side_effect=HTTPException(
status_code=503,
detail="System catalog test-connection requires Rust executor",
)
),
)
with pytest.raises(HTTPException) as exc_info:
await mod._test_connection_response(
request=SimpleNamespace(query_params={}),
db=MagicMock(),
provider=None,
model="gpt-test",
api_format=None,
)
upstream_response = httpx.Response(
200,
request=httpx.Request("POST", "https://upstream.test/v1/chat/completions"),
json={"id": "resp_python"},
)
upstream_client = MagicMock()
upstream_client.post = AsyncMock(return_value=upstream_response)
get_upstream_client = AsyncMock(return_value=upstream_client)
monkeypatch.setattr(mod.HTTPClientPool, "get_upstream_client", get_upstream_client)
result = await mod.test_connection(
request=SimpleNamespace(query_params={}),
db=MagicMock(),
provider=None,
model="gpt-test",
api_format=None,
)
assert result["status"] == "success"
assert result["response_id"] == "resp_python"
get_upstream_client.assert_awaited_once_with(delegate_cfg, proxy_config=proxy_config)
upstream_client.post.assert_awaited_once_with(
"https://upstream.test/v1/chat/completions",
json={"model": "gpt-test"},
headers={"authorization": "Bearer test"},
)
assert exc_info.value.status_code == 503
assert exc_info.value.detail == "System catalog test-connection requires Rust executor"

View File

@@ -0,0 +1,164 @@
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from src.database import get_db
def _build_app(
monkeypatch: pytest.MonkeyPatch,
*,
pipeline_result: Any,
) -> tuple[TestClient, list[dict[str, Any]]]:
from src.api.public import system_catalog as mod
app = FastAPI()
app.include_router(mod.router)
app.dependency_overrides[get_db] = lambda: MagicMock()
calls: list[dict[str, Any]] = []
async def _fake_pipeline_run(
*,
adapter: Any,
http_request: object,
db: object,
mode: object,
api_format_hint: str | None = None,
path_params: dict[str, Any] | None = None,
) -> Any:
del http_request, db, api_format_hint, path_params
calls.append(
{
"adapter_type": type(adapter).__name__,
"mode": getattr(mode, "value", mode),
"adapter_state": dict(getattr(adapter, "__dict__", {})),
}
)
return pipeline_result
monkeypatch.setattr(mod.pipeline, "run", _fake_pipeline_run)
return TestClient(app), calls
def test_system_catalog_health_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"status": "ok"})
response = client.get("/v1/health")
assert response.status_code == 200
assert response.json() == {"status": "ok"}
assert calls == [
{
"adapter_type": "PublicServiceHealthAdapter",
"mode": "public",
"adapter_state": {},
}
]
def test_system_catalog_simple_health_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"status": "healthy"})
response = client.get("/health")
assert response.status_code == 200
assert response.json() == {"status": "healthy"}
assert calls == [
{
"adapter_type": "PublicSimpleHealthCheckAdapter",
"mode": "public",
"adapter_state": {},
}
]
def test_system_catalog_root_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"status": "running"})
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"status": "running"}
assert calls == [
{
"adapter_type": "PublicRootCatalogAdapter",
"mode": "public",
"adapter_state": {},
}
]
def test_system_catalog_provider_list_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"providers": []})
response = client.get("/v1/providers?include_models=true&include_endpoints=true&active_only=false")
assert response.status_code == 200
assert response.json() == {"providers": []}
assert calls == [
{
"adapter_type": "PublicProvidersListAdapter",
"mode": "public",
"adapter_state": {
"include_models": True,
"include_endpoints": True,
"active_only": False,
},
}
]
def test_system_catalog_provider_detail_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"id": "provider-1"})
response = client.get("/v1/providers/provider-1?include_models=true")
assert response.status_code == 200
assert response.json() == {"id": "provider-1"}
assert calls == [
{
"adapter_type": "PublicProviderDetailAdapter",
"mode": "public",
"adapter_state": {
"provider_identifier": "provider-1",
"include_models": True,
"include_endpoints": False,
},
}
]
def test_system_catalog_test_connection_route_is_pipeline_shell(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"status": "success"})
response = client.get("/v1/test-connection?provider=openai&model=gpt-5&api_format=openai:chat")
assert response.status_code == 200
assert response.json() == {"status": "success"}
assert calls == [
{
"adapter_type": "PublicTestConnectionAdapter",
"mode": "public",
"adapter_state": {
"provider": "openai",
"model": "gpt-5",
"api_format": "openai:chat",
},
}
]

View File

@@ -0,0 +1,123 @@
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from src.database import get_db
def _build_app(monkeypatch: pytest.MonkeyPatch, *, pipeline_result: Any) -> tuple[TestClient, list[dict[str, Any]]]:
from src.api.public import videos as mod
app = FastAPI()
app.include_router(mod.router)
app.dependency_overrides[get_db] = lambda: MagicMock()
calls: list[dict[str, Any]] = []
async def _fake_pipeline_run(
*,
adapter: Any,
http_request: object,
db: object,
mode: object,
api_format_hint: str,
path_params: dict[str, Any] | None = None,
) -> Any:
del http_request, db
calls.append(
{
"adapter_type": type(adapter).__name__,
"mode": getattr(mode, "value", mode),
"api_format_hint": api_format_hint,
"path_params": path_params,
}
)
return pipeline_result
monkeypatch.setattr(mod.pipeline, "run", _fake_pipeline_run)
return TestClient(app), calls
def test_openai_video_create_route_is_pipeline_shell(monkeypatch: pytest.MonkeyPatch) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"ok": True})
response = client.post("/v1/videos", json={"model": "sora", "prompt": "hello"})
assert response.status_code == 200
assert response.json() == {"ok": True}
assert calls == [
{
"adapter_type": "OpenAIVideoAdapter",
"mode": "standard",
"api_format_hint": "openai:video",
"path_params": None,
}
]
def test_openai_video_download_route_passes_task_id_to_pipeline(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"download": True})
response = client.get("/v1/videos/task-123/content")
assert response.status_code == 200
assert response.json() == {"download": True}
assert calls == [
{
"adapter_type": "OpenAIVideoAdapter",
"mode": "standard",
"api_format_hint": "openai:video",
"path_params": {"task_id": "task-123"},
}
]
def test_gemini_video_create_route_passes_model_to_pipeline(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"ok": True})
response = client.post(
"/v1beta/models/veo-3:predictLongRunning",
json={"prompt": "hello"},
)
assert response.status_code == 200
assert response.json() == {"ok": True}
assert calls == [
{
"adapter_type": "GeminiVeoAdapter",
"mode": "standard",
"api_format_hint": "gemini:video",
"path_params": {"model": "veo-3"},
}
]
def test_gemini_video_cancel_route_reconstructs_operation_name(
monkeypatch: pytest.MonkeyPatch,
) -> None:
client, calls = _build_app(monkeypatch, pipeline_result={"ok": True})
response = client.post("/v1beta/models/veo-3/operations/op-1:cancel")
assert response.status_code == 200
assert response.json() == {"ok": True}
assert calls == [
{
"adapter_type": "GeminiVeoAdapter",
"mode": "standard",
"api_format_hint": "gemini:video",
"path_params": {
"task_id": "models/veo-3/operations/op-1",
"action": "cancel",
},
}
]