diff --git a/homeassistant/components/google/api.py b/homeassistant/components/google/api.py index ea3d23dcb01..80c66d7af0c 100644 --- a/homeassistant/components/google/api.py +++ b/homeassistant/components/google/api.py @@ -5,6 +5,7 @@ from __future__ import annotations from collections.abc import Awaitable, Callable import datetime import logging +import time from typing import Any from googleapiclient import discovery as google_discovery @@ -58,7 +59,7 @@ class DeviceAuth(config_entry_oauth2_flow.LocalOAuth2Implementation): "refresh_token": creds.refresh_token, "scope": " ".join(creds.scopes), "token_type": "Bearer", - "expires_in": creds.token_expiry.timestamp(), + "expires_in": creds.token_expiry.timestamp() - time.time(), } @@ -157,16 +158,16 @@ def _async_google_creds(hass: HomeAssistant, token: dict[str, Any]) -> Credentia client_id=conf[CONF_CLIENT_ID], client_secret=conf[CONF_CLIENT_SECRET], refresh_token=token["refresh_token"], - token_expiry=token["expires_at"], + token_expiry=datetime.datetime.fromtimestamp(token["expires_at"]), token_uri=oauth2client.GOOGLE_TOKEN_URI, scopes=[conf[CONF_CALENDAR_ACCESS].scope], user_agent=None, ) -def _api_time_format(time: datetime.datetime | None) -> str | None: +def _api_time_format(date_time: datetime.datetime | None) -> str | None: """Convert a datetime to the api string format.""" - return time.isoformat("T") if time else None + return date_time.isoformat("T") if date_time else None class GoogleCalendarService: diff --git a/tests/components/google/test_config_flow.py b/tests/components/google/test_config_flow.py index a5467b95dcb..e96a4c3fd5f 100644 --- a/tests/components/google/test_config_flow.py +++ b/tests/components/google/test_config_flow.py @@ -97,6 +97,12 @@ async def test_full_flow( assert "data" in result data = result["data"] assert "token" in data + assert 0 < data["token"]["expires_in"] < 8 * 86400 + assert ( + datetime.datetime.now().timestamp() + <= data["token"]["expires_at"] + < (datetime.datetime.now() + datetime.timedelta(days=8)).timestamp() + ) data["token"].pop("expires_at") data["token"].pop("expires_in") assert data == {