Bump gcal_sync to 0.6.2 and switch to google calendar async iterator api (#70616)

* Switch to google calendar async iterator api

* Update homeassistant/components/google/calendar.py

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>

* Add test coverage for paging through results

* Bump gcal_sync to 0.6.1

* Bump gcal-sync 0.6.2

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Allen Porter 2022-04-27 07:22:15 -07:00 committed by GitHub
parent 25d2c63827
commit 8a13c6744a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 79 additions and 19 deletions

View File

@ -158,7 +158,6 @@ class GoogleCalendarEntity(CalendarEntity):
self, hass: HomeAssistant, start_date: datetime, end_date: datetime self, hass: HomeAssistant, start_date: datetime, end_date: datetime
) -> list[CalendarEvent]: ) -> list[CalendarEvent]:
"""Get all events in a specific time frame.""" """Get all events in a specific time frame."""
event_list: list[dict[str, Any]] = []
request = ListEventsRequest( request = ListEventsRequest(
calendar_id=self._calendar_id, calendar_id=self._calendar_id,
@ -166,20 +165,18 @@ class GoogleCalendarEntity(CalendarEntity):
end_time=end_date, end_time=end_date,
search=self._search, search=self._search,
) )
while True: result_items = []
try: try:
result = await self._calendar_service.async_list_events(request) result = await self._calendar_service.async_list_events(request)
except ApiException as err: async for result_page in result:
_LOGGER.error("Unable to connect to Google: %s", err) result_items.extend(result_page.items)
return [] except ApiException as err:
_LOGGER.error("Unable to connect to Google: %s", err)
event_list.extend(filter(self._event_filter, result.items)) return []
if not result.page_token: return [
break _get_calendar_event(event)
for event in filter(self._event_filter, result_items)
request.page_token = result.page_token ]
return [_get_calendar_event(event) for event in event_list]
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self) -> None: async def async_update(self) -> None:

View File

@ -4,7 +4,7 @@
"config_flow": true, "config_flow": true,
"dependencies": ["auth"], "dependencies": ["auth"],
"documentation": "https://www.home-assistant.io/integrations/calendar.google/", "documentation": "https://www.home-assistant.io/integrations/calendar.google/",
"requirements": ["gcal-sync==0.5.0", "oauth2client==4.1.3"], "requirements": ["gcal-sync==0.6.2", "oauth2client==4.1.3"],
"codeowners": ["@allenporter"], "codeowners": ["@allenporter"],
"iot_class": "cloud_polling", "iot_class": "cloud_polling",
"loggers": ["googleapiclient"] "loggers": ["googleapiclient"]

View File

@ -689,7 +689,7 @@ gTTS==2.2.4
garages-amsterdam==3.0.0 garages-amsterdam==3.0.0
# homeassistant.components.google # homeassistant.components.google
gcal-sync==0.5.0 gcal-sync==0.6.2
# homeassistant.components.geniushub # homeassistant.components.geniushub
geniushub-client==0.6.30 geniushub-client==0.6.30

View File

@ -486,7 +486,7 @@ gTTS==2.2.4
garages-amsterdam==3.0.0 garages-amsterdam==3.0.0
# homeassistant.components.google # homeassistant.components.google
gcal-sync==0.5.0 gcal-sync==0.6.2
# homeassistant.components.usgs_earthquakes_feed # homeassistant.components.usgs_earthquakes_feed
geojson_client==0.6 geojson_client==0.6

View File

@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import copy
import datetime import datetime
from http import HTTPStatus from http import HTTPStatus
from typing import Any from typing import Any
@ -9,15 +10,17 @@ from unittest.mock import patch
import urllib import urllib
from aiohttp.client_exceptions import ClientError from aiohttp.client_exceptions import ClientError
from gcal_sync.auth import API_BASE_URL
import pytest import pytest
from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.helpers.template import DATE_STR_FORMAT from homeassistant.helpers.template import DATE_STR_FORMAT
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
from .conftest import TEST_YAML_ENTITY, TEST_YAML_ENTITY_NAME from .conftest import CALENDAR_ID, TEST_YAML_ENTITY, TEST_YAML_ENTITY_NAME
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
from tests.test_util.aiohttp import AiohttpClientMockResponse
TEST_ENTITY = TEST_YAML_ENTITY TEST_ENTITY = TEST_YAML_ENTITY
TEST_ENTITY_NAME = TEST_YAML_ENTITY_NAME TEST_ENTITY_NAME = TEST_YAML_ENTITY_NAME
@ -471,6 +474,66 @@ async def test_http_api_all_day_event(
} }
@pytest.mark.freeze_time("2022-03-27 12:05:00+00:00")
async def test_http_api_event_paging(
hass, hass_client, aioclient_mock, component_setup
):
"""Test paging through results from the server."""
hass.config.set_time_zone("Asia/Baghdad")
responses = [
{
"nextPageToken": "page-token",
"items": [
{
**TEST_EVENT,
"summary": "event 1",
**upcoming(),
}
],
},
{
"items": [
{
**TEST_EVENT,
"summary": "event 2",
**upcoming(),
}
],
},
]
def next_response(response_list):
results = copy.copy(response_list)
async def get(method, url, data):
return AiohttpClientMockResponse(method, url, json=results.pop(0))
return get
# Setup response for initial entity load
aioclient_mock.get(
f"{API_BASE_URL}/calendars/{CALENDAR_ID}/events",
side_effect=next_response(responses),
)
assert await component_setup()
# Setup response for API request
aioclient_mock.clear_requests()
aioclient_mock.get(
f"{API_BASE_URL}/calendars/{CALENDAR_ID}/events",
side_effect=next_response(responses),
)
client = await hass_client()
response = await client.get(upcoming_event_url())
assert response.status == HTTPStatus.OK
events = await response.json()
assert len(events) == 2
assert events[0]["summary"] == "event 1"
assert events[1]["summary"] == "event 2"
@pytest.mark.parametrize( @pytest.mark.parametrize(
"calendars_config_ignore_availability,transparency,expect_visible_event", "calendars_config_ignore_availability,transparency,expect_visible_event",
[ [