from fastapi.testclient import TestClient from mcp_common.auth import Principal, TokenStore from mcp_common.server import build_app def test_build_app_health(): store = TokenStore(tokens={}) app = build_app(name="test-mcp", version="0.0.1", token_store=store) client = TestClient(app) r = client.get("/health") assert r.status_code == 200 body = r.json() assert body["status"] == "healthy" assert body["name"] == "test-mcp" assert body["version"] == "0.0.1" assert "uptime_seconds" in body assert "data_timestamp" in body assert r.headers.get("X-Duration-Ms") is not None def test_build_app_adds_token_store(): store = TokenStore(tokens={"t1": Principal("x", {"core"})}) app = build_app(name="t", version="v", token_store=store) assert app.state.token_store is store def test_timestamp_injector_dict_response(): """CER-P5-001: dict response gets data_timestamp + X-Data-Timestamp header.""" store = TokenStore(tokens={}) app = build_app(name="t", version="v", token_store=store) @app.post("/tools/foo") def foo(): return {"ok": True} client = TestClient(app) r = client.post("/tools/foo") assert r.status_code == 200 body = r.json() assert body["ok"] is True assert "data_timestamp" in body assert r.headers.get("X-Data-Timestamp") is not None def test_timestamp_injector_list_of_dicts(): """CER-P5-001: list of dicts → each item gets data_timestamp.""" store = TokenStore(tokens={}) app = build_app(name="t", version="v", token_store=store) @app.post("/tools/list_items") def list_items(): return [{"x": 1}, {"x": 2}] client = TestClient(app) r = client.post("/tools/list_items") body = r.json() assert isinstance(body, list) assert len(body) == 2 for item in body: assert "data_timestamp" in item assert r.headers.get("X-Data-Timestamp") is not None def test_timestamp_injector_preserves_existing(): """CER-P5-001: se già presente, non override.""" store = TokenStore(tokens={}) app = build_app(name="t", version="v", token_store=store) @app.post("/tools/already") def already(): return {"data_timestamp": "2020-01-01T00:00:00Z", "x": 1} client = TestClient(app) body = client.post("/tools/already").json() assert body["data_timestamp"] == "2020-01-01T00:00:00Z" def test_timestamp_injector_empty_list_gets_header_only(): """CER-P5-001: list vuota — no body modification, ma header presente.""" store = TokenStore(tokens={}) app = build_app(name="t", version="v", token_store=store) @app.post("/tools/empty_list") def empty_list(): return [] client = TestClient(app) r = client.post("/tools/empty_list") assert r.json() == [] assert r.headers.get("X-Data-Timestamp") is not None