|
| 1 | +"""Test API exception handlers.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import json |
| 5 | + |
| 6 | +from openbb_core.api.exception_handlers import ExceptionHandlers |
| 7 | +from openbb_core.provider.utils.errors import MissingCredentialError |
| 8 | + |
| 9 | + |
| 10 | +def get_response_detail(response): |
| 11 | + """Return the JSON response detail.""" |
| 12 | + return json.loads(response.body)["detail"] |
| 13 | + |
| 14 | + |
| 15 | +def test_missing_credential_returns_structured_400(): |
| 16 | + """Return a structured 4xx when a provider credential is missing.""" |
| 17 | + error = MissingCredentialError(provider="eia", credential="eia_api_key") |
| 18 | + |
| 19 | + response = asyncio.run(ExceptionHandlers.missing_credential(None, error)) |
| 20 | + |
| 21 | + assert response.status_code == 400 |
| 22 | + detail = get_response_detail(response) |
| 23 | + assert detail["code"] == "missing_credentials" |
| 24 | + assert detail["provider"] == "eia" |
| 25 | + assert detail["credential"] == "eia_api_key" |
| 26 | + assert "eia_api_key" in detail["message"] |
| 27 | + |
| 28 | + |
| 29 | +def test_missing_credential_message_preserved(): |
| 30 | + """Keep the provider-provided message when one is supplied.""" |
| 31 | + error = MissingCredentialError( |
| 32 | + provider="eia", |
| 33 | + credential="eia_api_key", |
| 34 | + message="API_KEY_MISSING -> No api_key was supplied.", |
| 35 | + ) |
| 36 | + |
| 37 | + response = asyncio.run(ExceptionHandlers.missing_credential(None, error)) |
| 38 | + |
| 39 | + detail = get_response_detail(response) |
| 40 | + assert detail["message"] == "API_KEY_MISSING -> No api_key was supplied." |
| 41 | + |
| 42 | + |
| 43 | +def test_missing_credential_is_openbb_error(): |
| 44 | + """MissingCredentialError must remain an OpenBBError for backward compatibility.""" |
| 45 | + error = MissingCredentialError(provider="eia", credential="eia_api_key") |
| 46 | + |
| 47 | + assert isinstance(error, Exception) |
| 48 | + assert str(error) == error.message |
0 commit comments