← Files Dispensa: lista de comprasARCHIVED FILE

tests/test_server_health.py

9.45 KB · Nov 19, 2026 · 00:38 UTC

↓ Download file

See the change to this file →

import asyncio
import json
import logging
import runpy
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock, patch

import httpx
import pytest
from fastmcp.server.auth.providers.workos import AuthKitProvider
from starlette.testclient import TestClient

from mcp_despensa_hub.domain.errors import (
    MSG_FALHA_COMUNICACAO_FONTE,
    MSG_TIMEOUT_FONTE,
    MSG_USUARIO_NAO_AUTORIZADO,
)
from mcp_despensa_hub.server import build_mcp, com_sub, health, main

TOOLS = {
    "ping_despensa",
    "adicionar_item",
    "ver_lista",
    "remover_item",
    "registrar_compra",
    "corrigir_compra",
    "ver_historico",
    "ver_preferencia",
    "ajustar_preferencia",
    "o_que_esta_faltando",
    "exportar_meus_dados",
    "apagar_meus_dados",
}


def _settings():
    return SimpleNamespace(
        workos_authkit_domain="https://auth.example.com",
        mcp_base_url="https://mcp.example.com",
        port=8000,
        openai_apps_challenge="",
    )


def _token(sub: str = "user_123"):
    return SimpleNamespace(claims={"sub": sub}, token="jwt-workos-secreto")


def test_health_retorna_status_ok_sem_dependencias_externas():
    response = asyncio.run(health(None))

    assert response.status_code == 200
    assert json.loads(response.body) == {"status": "ok"}


def test_build_mcp_conjunto_exato_de_tools():
    mcp = build_mcp(_settings())

    assert mcp.name == "mcp-despensa-hub"
    assert isinstance(mcp.auth, AuthKitProvider)
    assert any(
        route.path == "/health" and "GET" in route.methods
        for route in mcp._additional_http_routes
    )
    tools = asyncio.run(mcp.list_tools())
    nomes = {tool.name for tool in tools}
    assert nomes == TOOLS


def test_toda_tool_tem_hints_openai():
    mcp = build_mcp(_settings())
    tools = asyncio.run(mcp.list_tools())
    hints = ("readOnlyHint", "openWorldHint", "destructiveHint")
    for tool in tools:
        anns = tool.annotations
        assert anns is not None, tool.name
        for hint in hints:
            valor = getattr(anns, hint)
            assert valor is True or valor is False, (tool.name, hint, valor)


def test_oauth_protected_resource_na_raiz_devolve_metadados_rfc9728():
    mcp = build_mcp(_settings())
    app = mcp.http_app()

    with TestClient(app) as client:
        resposta = client.get("/.well-known/oauth-protected-resource")
        saude = client.get("/health")

    assert resposta.status_code == 200
    corpo = resposta.json()
    assert corpo["resource"] == "https://mcp.example.com/mcp"
    assert corpo["authorization_servers"] == ["https://auth.example.com"]
    assert corpo["bearer_methods_supported"] == ["header"]
    assert saude.status_code == 200
    assert saude.json() == {"status": "ok"}


def test_home_e_support_respondem_html_publico():
    """Website URL e Customer support URL da submissão OpenAI."""
    mcp = build_mcp(_settings())
    app = mcp.http_app()

    with TestClient(app) as client:
        home = client.get("/")
        suporte = client.get("/support")

    for resposta in (home, suporte):
        assert resposta.status_code == 200
        assert resposta.headers["content-type"].startswith("text/html")

    assert "Despensa Hub" in home.text
    assert "https://mcp.example.com/mcp" in home.text
    for destino in ("/privacy", "/terms", "/support"):
        assert destino in home.text
    assert "mailto:" in suporte.text


def test_privacy_e_terms_respondem_html_publico():
    """Exigidas pela submissão OpenAI: precisam abrir sem token."""
    mcp = build_mcp(_settings())
    app = mcp.http_app()

    with TestClient(app) as client:
        privacidade = client.get("/privacy")
        termos = client.get("/terms")

    for resposta in (privacidade, termos):
        assert resposta.status_code == 200
        assert resposta.headers["content-type"].startswith("text/html")

    assert "Privacy Policy" in privacidade.text
    assert "Política de Privacidade" in privacidade.text
    assert "Terms of Service" in termos.text
    assert "Termos de Uso" in termos.text


def test_privacidade_cita_os_controles_reais_do_titular():
    """As duas tools de titular têm de aparecer: é o que a OpenAI cobra."""
    mcp = build_mcp(_settings())
    app = mcp.http_app()

    with TestClient(app) as client:
        texto = client.get("/privacy").text

    assert "exportar_meus_dados" in texto
    assert "apagar_meus_dados" in texto


def test_privacidade_nao_promete_criptografia_que_nao_existe():
    """Não há criptografia em nível de aplicação; a política não pode alegar."""
    mcp = build_mcp(_settings())
    app = mcp.http_app()

    with TestClient(app) as client:
        texto = client.get("/privacy").text.lower()

    assert "without application-level encryption at rest" in texto
    assert "sem\ncriptografia em nível de aplicação" in texto or (
        "criptografia em nível de aplicação" in texto
    )


def test_openai_apps_challenge_sem_token_e_404():
    mcp = build_mcp(_settings())
    app = mcp.http_app()

    with TestClient(app) as client:
        resposta = client.get("/.well-known/openai-apps-challenge")

    assert resposta.status_code == 404


def test_openai_apps_challenge_devolve_token_em_texto_puro():
    settings = _settings()
    settings.openai_apps_challenge = "token-openai-apps"
    mcp = build_mcp(settings)
    app = mcp.http_app()

    with TestClient(app) as client:
        resposta = client.get("/.well-known/openai-apps-challenge")

    assert resposta.status_code == 200
    assert resposta.headers["content-type"].startswith("text/plain")
    assert resposta.text == "token-openai-apps"


def test_ping_despensa_rejeita_token_sem_sub():
    mcp = build_mcp(_settings())
    tool = asyncio.run(mcp.get_tool("ping_despensa"))

    with patch(
        "mcp_despensa_hub.server.get_access_token",
        return_value=SimpleNamespace(claims={}),
    ):
        resposta = asyncio.run(tool.fn())

    assert resposta == {"erro": MSG_USUARIO_NAO_AUTORIZADO}


def test_ping_despensa_delega_com_sub_sem_vazar_jwt(caplog):
    executar = AsyncMock(return_value={"resultado": "ok", "versao_motor": 1})
    token = _token()

    with (
        patch("mcp_despensa_hub.server.get_access_token", return_value=token),
        patch("mcp_despensa_hub.server.executar_ping_despensa", executar),
        caplog.at_level(logging.INFO, logger="mcp_despensa_hub.server"),
    ):
        mcp = build_mcp(_settings())
        tool = asyncio.run(mcp.get_tool("ping_despensa"))
        resposta = asyncio.run(tool.fn())

    assert resposta == {"resultado": "ok", "versao_motor": 1}
    executar.assert_awaited_once_with(workos_user_id="user_123")
    assert "workos_user_id=user_123" in caplog.text
    assert "jwt-workos-secreto" not in caplog.text


def test_com_sub_nao_vaza_para_o_schema_de_nenhuma_tool():
    mcp = build_mcp(_settings())
    for nome in TOOLS:
        tool = asyncio.run(mcp.get_tool(nome))
        propriedades = tool.parameters.get("properties") or {}
        assert "sub" not in propriedades
        assert "workos_user_id" not in propriedades


def test_schema_publico_das_tools():
    mcp = build_mcp(_settings())

    adicionar = asyncio.run(mcp.get_tool("adicionar_item"))
    assert set(adicionar.parameters["properties"]) == {
        "texto",
        "quantidade",
        "marca",
        "variante",
    }
    assert set(adicionar.parameters["required"]) == {"texto"}

    registrar = asyncio.run(mcp.get_tool("registrar_compra"))
    assert set(registrar.parameters["properties"]) == {
        "itens",
        "local",
        "ocorrido_em",
        "origem",
        "chave_nfe",
        "valor_total",
        "observacao",
    }
    assert set(registrar.parameters["required"]) == {"itens"}

    apagar = asyncio.run(mcp.get_tool("apagar_meus_dados"))
    assert set(apagar.parameters["properties"]) == {"confirmar"}


def test_main_inicia_servidor_http_na_porta_configurada():
    settings = _settings()
    mcp = Mock()

    with (
        patch("mcp_despensa_hub.server.logging.basicConfig") as basic_config,
        patch("mcp_despensa_hub.server.Settings", return_value=settings),
        patch("mcp_despensa_hub.server.build_mcp", return_value=mcp) as build,
    ):
        main()

    basic_config.assert_called_once_with(level=logging.INFO)
    build.assert_called_once_with(settings)
    mcp.run.assert_called_once_with(
        transport="http",
        host="0.0.0.0",
        port=8000,
    )


def test_modulo_principal_chama_main():
    with patch("mcp_despensa_hub.server.main") as server_main:
        runpy.run_module("mcp_despensa_hub.__main__", run_name="__main__")

    server_main.assert_called_once_with()


def test_com_sub_timeout_vira_dict_de_erro():
    async def boom(_sub: str) -> dict:
        raise httpx.ReadTimeout("timed out")

    with patch("mcp_despensa_hub.server.get_access_token", return_value=_token()):
        resposta = asyncio.run(com_sub(boom))

    assert resposta == {"erro": MSG_TIMEOUT_FONTE}


def test_com_sub_connect_error_vira_dict_de_erro():
    async def boom(_sub: str) -> dict:
        raise httpx.ConnectError("connection refused")

    with patch("mcp_despensa_hub.server.get_access_token", return_value=_token()):
        resposta = asyncio.run(com_sub(boom))

    assert resposta == {"erro": MSG_FALHA_COMUNICACAO_FONTE}


def test_com_sub_keyerror_continua_propagando():
    async def boom(_sub: str) -> dict:
        raise KeyError("bug nosso")

    with (
        patch("mcp_despensa_hub.server.get_access_token", return_value=_token()),
        pytest.raises(KeyError, match="bug nosso"),
    ):
        asyncio.run(com_sub(boom))

SHA-256: 9cd6535cefa8f1fc0de649515506493f320b36b918004bf03452437f38881fdd