466e63dc19
Wrapper async tipizzati sui sei servizi MCP HTTP che Cerbero Bite consuma in autonomia. 277 test pass, copertura clients 93%, mypy strict pulito, ruff clean. Base layer: - clients/_base.py: HttpToolClient con httpx + tenacity (retry esponenziale 3x, timeout 8s, mapping HTTP→eccezioni tipizzate). - clients/_exceptions.py: McpAuthError, McpServerError, McpToolError, McpDataAnomalyError, McpNotFoundError, McpTimeoutError. - config/mcp_endpoints.py: risoluzione URL via Docker DNS (mcp-deribit:9011, ...) con override per servizio via env var; caricamento bearer token da secrets/core.token o CERBERO_BITE_CORE_TOKEN_FILE. Wrapper: - clients/macro.py: next_high_severity_within() per filtro entry §2.5. - clients/sentiment.py: funding_cross_median_annualized() con annualizzazione per period nativo per exchange (Binance/Bybit/OKX 1095, Hyperliquid 8760). - clients/hyperliquid.py: funding_rate_annualized() per filtro §2.6. - clients/portfolio.py: total_equity_eur(), asset_pct_of_portfolio() per sizing engine + filtro §2.7. - clients/telegram.py: notify-only (no callback queue, no conferme — Bite auto-execute). - clients/deribit.py: environment_info, index_price_eth, latest_dvol, options_chain, get_tickers, orderbook_depth_top3, get_account_summary, get_positions, place_combo_order (combo atomico), cancel_order. CLI: - cerbero-bite ping: health-check parallelo di tutti gli MCP con tabella rich (OK/FAIL/SKIPPED). Docker: - Dockerfile multi-stage Python 3.13 + uv, user non-root. - docker-compose.yml con rete external "cerbero-suite", secret core_token montato a /run/secrets/core_token, env per ogni MCP. - secrets/README.md documenta il setup del token. Documentazione di intervento: - docs/12-mcp-deribit-changes.md: spec delle modifiche apportate al server mcp-deribit (place_combo_order + override testnet via DERIBIT_TESTNET). Dipendenze: - aggiunto pytest-httpx per i test HTTP. - rimosso mcp>=1.0 (non usiamo l'SDK MCP, parliamo via HTTP REST). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
169 lines
5.2 KiB
Python
169 lines
5.2 KiB
Python
"""Tests for :class:`HttpToolClient`."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import httpx
|
|
import pytest
|
|
from pytest_httpx import HTTPXMock
|
|
|
|
from cerbero_bite.clients._base import HttpToolClient
|
|
from cerbero_bite.clients._exceptions import (
|
|
McpAuthError,
|
|
McpNotFoundError,
|
|
McpServerError,
|
|
McpTimeoutError,
|
|
McpToolError,
|
|
)
|
|
|
|
|
|
def _make_client(**overrides: object) -> HttpToolClient:
|
|
base: dict[str, object] = {
|
|
"service": "test",
|
|
"base_url": "http://mcp-test:9000",
|
|
"token": "tok",
|
|
"retry_max": 1,
|
|
}
|
|
base.update(overrides)
|
|
return HttpToolClient(**base) # type: ignore[arg-type]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_returns_parsed_payload(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_response(
|
|
url="http://mcp-test:9000/tools/get_thing",
|
|
json={"result": [1, 2, 3]},
|
|
)
|
|
client = _make_client()
|
|
out = await client.call("get_thing", {"x": 1})
|
|
assert out == {"result": [1, 2, 3]}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_attaches_bearer_token(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_response(json={"ok": True})
|
|
client = _make_client(token="abc123")
|
|
await client.call("any")
|
|
request = httpx_mock.get_request()
|
|
assert request is not None
|
|
assert request.headers["Authorization"] == "Bearer abc123"
|
|
assert request.headers["Content-Type"] == "application/json"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_raises_auth_error_on_401(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_response(status_code=401, json={"detail": "nope"})
|
|
client = _make_client()
|
|
with pytest.raises(McpAuthError):
|
|
await client.call("any")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_raises_auth_error_on_403(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_response(status_code=403, json={"detail": "forbidden"})
|
|
client = _make_client()
|
|
with pytest.raises(McpAuthError):
|
|
await client.call("any")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_raises_not_found_on_404(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_response(status_code=404, text="missing")
|
|
client = _make_client()
|
|
with pytest.raises(McpNotFoundError):
|
|
await client.call("any")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_raises_server_error_on_500(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_response(status_code=500, text="boom")
|
|
client = _make_client()
|
|
with pytest.raises(McpServerError):
|
|
await client.call("any")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_raises_tool_error_on_state_error_envelope(
|
|
httpx_mock: HTTPXMock,
|
|
) -> None:
|
|
httpx_mock.add_response(json={"state": "error", "error": "bad params"})
|
|
client = _make_client()
|
|
with pytest.raises(McpToolError) as info:
|
|
await client.call("any")
|
|
assert "bad params" in str(info.value)
|
|
assert info.value.payload == {"state": "error", "error": "bad params"}
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_raises_tool_error_on_4xx_other(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_response(status_code=422, text="invalid")
|
|
client = _make_client()
|
|
with pytest.raises(McpToolError):
|
|
await client.call("any")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_raises_server_error_when_response_not_json(
|
|
httpx_mock: HTTPXMock,
|
|
) -> None:
|
|
httpx_mock.add_response(content=b"not-json", headers={"content-type": "text/plain"})
|
|
client = _make_client()
|
|
with pytest.raises(McpServerError, match="not JSON"):
|
|
await client.call("any")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_passes_through_list_response(httpx_mock: HTTPXMock) -> None:
|
|
"""Some MCP tools (e.g. portfolio.get_holdings) return a list."""
|
|
httpx_mock.add_response(json=[1, 2, 3])
|
|
client = _make_client()
|
|
out = await client.call("any")
|
|
assert out == [1, 2, 3]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_raises_timeout(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_exception(httpx.ReadTimeout("slow"))
|
|
client = _make_client()
|
|
with pytest.raises(McpTimeoutError):
|
|
await client.call("any")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_retries_on_server_error_then_succeeds(
|
|
httpx_mock: HTTPXMock,
|
|
) -> None:
|
|
httpx_mock.add_response(status_code=500, text="down")
|
|
httpx_mock.add_response(json={"ok": True})
|
|
|
|
sleeps: list[float] = []
|
|
|
|
async def _fake_sleep(seconds: float) -> None:
|
|
sleeps.append(seconds)
|
|
|
|
client = _make_client(retry_max=3, sleep=_fake_sleep)
|
|
out = await client.call("any")
|
|
assert out == {"ok": True}
|
|
# one retry → at least one sleep recorded
|
|
assert sleeps, "expected the retrier to sleep before retry"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_call_does_not_retry_auth_error(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_response(status_code=401, json={"detail": "no"})
|
|
client = _make_client(retry_max=3)
|
|
with pytest.raises(McpAuthError):
|
|
await client.call("any")
|
|
# only one request made; no retry on auth
|
|
requests = httpx_mock.get_requests()
|
|
assert len(requests) == 1
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_base_url_trailing_slash_is_stripped(httpx_mock: HTTPXMock) -> None:
|
|
httpx_mock.add_response(
|
|
url="http://mcp-test:9000/tools/foo",
|
|
json={"ok": True},
|
|
)
|
|
client = _make_client(base_url="http://mcp-test:9000///")
|
|
await client.call("foo")
|