Improve calendar error handling to match best practices (#74891)

This commit is contained in:
Allen Porter 2022-07-10 10:04:57 -07:00 committed by GitHub
parent 52130b227e
commit 6f9fcdff99
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 43 additions and 11 deletions

View File

@ -14,6 +14,7 @@ from homeassistant.components import frontend, http
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.config_validation import ( # noqa: F401 from homeassistant.helpers.config_validation import ( # noqa: F401
PLATFORM_SCHEMA, PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE, PLATFORM_SCHEMA_BASE,
@ -336,9 +337,14 @@ class CalendarEventView(http.HomeAssistantView):
if not isinstance(entity, CalendarEntity): if not isinstance(entity, CalendarEntity):
return web.Response(status=HTTPStatus.BAD_REQUEST) return web.Response(status=HTTPStatus.BAD_REQUEST)
calendar_event_list = await entity.async_get_events( try:
request.app["hass"], start_date, end_date calendar_event_list = await entity.async_get_events(
) request.app["hass"], start_date, end_date
)
except HomeAssistantError as err:
return self.json_message(
f"Error reading events: {err}", HTTPStatus.INTERNAL_SERVER_ERROR
)
return self.json( return self.json(
[ [
{ {

View File

@ -282,8 +282,7 @@ class GoogleCalendarEntity(CalendarEntity):
async for result_page in result: async for result_page in result:
result_items.extend(result_page.items) result_items.extend(result_page.items)
except ApiException as err: except ApiException as err:
_LOGGER.error("Unable to connect to Google: %s", err) raise HomeAssistantError(str(err)) from err
return []
return [ return [
_get_calendar_event(event) _get_calendar_event(event)
for event in filter(self._event_filter, result_items) for event in filter(self._event_filter, result_items)

View File

@ -1,8 +1,10 @@
"""The tests for the calendar component.""" """The tests for the calendar component."""
from datetime import timedelta from datetime import timedelta
from http import HTTPStatus from http import HTTPStatus
from unittest.mock import patch
from homeassistant.bootstrap import async_setup_component from homeassistant.bootstrap import async_setup_component
from homeassistant.exceptions import HomeAssistantError
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
@ -11,8 +13,6 @@ async def test_events_http_api(hass, hass_client):
await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}}) await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}})
await hass.async_block_till_done() await hass.async_block_till_done()
client = await hass_client() client = await hass_client()
response = await client.get("/api/calendars/calendar.calendar_2")
assert response.status == HTTPStatus.BAD_REQUEST
start = dt_util.now() start = dt_util.now()
end = start + timedelta(days=1) end = start + timedelta(days=1)
response = await client.get( response = await client.get(
@ -25,6 +25,36 @@ async def test_events_http_api(hass, hass_client):
assert events[0]["summary"] == "Future Event" assert events[0]["summary"] == "Future Event"
async def test_events_http_api_missing_fields(hass, hass_client):
"""Test the calendar demo view."""
await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}})
await hass.async_block_till_done()
client = await hass_client()
response = await client.get("/api/calendars/calendar.calendar_2")
assert response.status == HTTPStatus.BAD_REQUEST
async def test_events_http_api_error(hass, hass_client):
"""Test the calendar demo view."""
await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}})
await hass.async_block_till_done()
client = await hass_client()
start = dt_util.now()
end = start + timedelta(days=1)
with patch(
"homeassistant.components.demo.calendar.DemoCalendar.async_get_events",
side_effect=HomeAssistantError("Failure"),
):
response = await client.get(
"/api/calendars/calendar.calendar_1?start={}&end={}".format(
start.isoformat(), end.isoformat()
)
)
assert response.status == HTTPStatus.INTERNAL_SERVER_ERROR
assert await response.json() == {"message": "Error reading events: Failure"}
async def test_calendars_http_api(hass, hass_client): async def test_calendars_http_api(hass, hass_client):
"""Test the calendar demo view.""" """Test the calendar demo view."""
await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}}) await async_setup_component(hass, "calendar", {"calendar": {"platform": "demo"}})

View File

@ -423,10 +423,7 @@ async def test_http_event_api_failure(
mock_events_list({}, exc=ClientError()) mock_events_list({}, exc=ClientError())
response = await client.get(upcoming_event_url()) response = await client.get(upcoming_event_url())
assert response.status == HTTPStatus.OK assert response.status == HTTPStatus.INTERNAL_SERVER_ERROR
# A failure to talk to the server results in an empty list of events
events = await response.json()
assert events == []
@pytest.mark.freeze_time("2022-03-27 12:05:00+00:00") @pytest.mark.freeze_time("2022-03-27 12:05:00+00:00")