init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1 @@
"""Tests for the Google integration."""

View File

@@ -0,0 +1,365 @@
"""Test configuration and mocks for the google integration."""
from __future__ import annotations
from collections.abc import AsyncGenerator, Awaitable, Callable, Generator
import datetime
import http
import time
from typing import Any
from unittest.mock import Mock, mock_open, patch
from aiohttp.client_exceptions import ClientError
from gcal_sync.auth import API_BASE_URL
from oauth2client.client import OAuth2Credentials
import pytest
import yaml
from homeassistant.components.application_credentials import (
ClientCredential,
async_import_client_credential,
)
from homeassistant.components.google import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
type ApiResult = Callable[[dict[str, Any]], None]
type ComponentSetup = Callable[[], Awaitable[bool]]
type AsyncYieldFixture[_T] = AsyncGenerator[_T]
CALENDAR_ID = "qwertyuiopasdfghjklzxcvbnm@import.calendar.google.com"
EMAIL_ADDRESS = "user@gmail.com"
# Entities can either be created based on data directly from the API, or from
# the yaml config that overrides the entity name and other settings. A test
# can use a fixture to exercise either case.
TEST_API_ENTITY = "calendar.we_are_we_are_a_test_calendar"
TEST_API_ENTITY_NAME = "We are, we are, a... test calendar"
# Name of the entity when using yaml configuration overrides
TEST_YAML_ENTITY = "calendar.backyard_light"
TEST_YAML_ENTITY_NAME = "Backyard light"
# A calendar object returned from the API
TEST_API_CALENDAR = {
"id": CALENDAR_ID,
"etag": '"3584134138943410"',
"timeZone": "UTC",
"foregroundColor": "#000000",
"selected": True,
"kind": "calendar#calendarListEntry",
"backgroundColor": "#16a765",
"description": "Test Calendar",
"summary": "We are, we are, a... Test Calendar",
"colorId": "8",
"defaultReminders": [],
}
TEST_EVENT = {
"summary": "Test All Day Event",
"start": {},
"end": {},
"location": "Test Cases",
"description": "test event",
"kind": "calendar#event",
"created": "2016-06-23T16:37:57.000Z",
"transparency": "transparent",
"updated": "2016-06-24T01:57:21.045Z",
"reminders": {"useDefault": True},
"organizer": {
"email": "uvrttabwegnui4gtia3vyqb@import.calendar.google.com",
"displayName": "Organizer Name",
"self": True,
},
"sequence": 0,
"creator": {
"email": "uvrttabwegnui4gtia3vyqb@import.calendar.google.com",
"displayName": "Organizer Name",
"self": True,
},
"id": "_c8rinwq863h45qnucyoi43ny8",
"etag": '"2933466882090000"',
"htmlLink": "https://www.google.com/calendar/event?eid=*******",
"iCalUID": "cydrevtfuybguinhomj@google.com",
"status": "confirmed",
}
CLIENT_ID = "client-id"
CLIENT_SECRET = "client-secret"
@pytest.fixture
def calendar_access_role() -> str:
"""Set default access role to use for test_api_calendar in tests."""
return "owner"
@pytest.fixture
def calendar_is_primary() -> bool:
"""Set if the calendar is the primary or not."""
return False
@pytest.fixture(name="test_api_calendar")
def api_calendar(
calendar_access_role: str, calendar_is_primary: bool
) -> dict[str, Any]:
"""Return a test calendar object used in API responses."""
return {
**TEST_API_CALENDAR,
"accessRole": calendar_access_role,
"primary": calendar_is_primary,
}
@pytest.fixture
def calendars_config_track() -> bool:
"""Fixture that determines the 'track' setting in yaml config."""
return True
@pytest.fixture
def calendars_config_ignore_availability() -> bool:
"""Fixture that determines the 'ignore_availability' setting in yaml config."""
return None
@pytest.fixture
def calendars_config_entity(
calendars_config_track: bool, calendars_config_ignore_availability: bool | None
) -> dict[str, Any]:
"""Fixture that creates an entity within the yaml configuration."""
entity = {
"device_id": "backyard_light",
"name": "Backyard Light",
"search": "#Backyard",
"track": calendars_config_track,
}
if calendars_config_ignore_availability is not None:
entity["ignore_availability"] = calendars_config_ignore_availability
return entity
@pytest.fixture
def calendars_config(calendars_config_entity: dict[str, Any]) -> list[dict[str, Any]]:
"""Fixture that specifies the calendar yaml configuration."""
return [
{
"cal_id": CALENDAR_ID,
"entities": [calendars_config_entity],
}
]
@pytest.fixture
def mock_calendars_yaml(
hass: HomeAssistant,
calendars_config: list[dict[str, Any]],
) -> Generator[Mock]:
"""Fixture that prepares the google_calendars.yaml mocks."""
mocked_open_function = mock_open(
read_data=yaml.dump(calendars_config) if calendars_config else None
)
with patch("homeassistant.components.google.open", mocked_open_function):
yield mocked_open_function
@pytest.fixture
def token_scopes() -> list[str]:
"""Fixture for scopes used during test."""
return ["https://www.googleapis.com/auth/calendar"]
@pytest.fixture
def token_expiry() -> datetime.datetime:
"""Expiration time for credentials used in the test."""
# OAuth library returns an offset-naive timestamp
return dt_util.utcnow().replace(tzinfo=None) + datetime.timedelta(hours=1)
@pytest.fixture
def creds(
token_scopes: list[str], token_expiry: datetime.datetime
) -> OAuth2Credentials:
"""Fixture that defines creds used in the test."""
return OAuth2Credentials(
access_token="ACCESS_TOKEN",
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
refresh_token="REFRESH_TOKEN",
token_expiry=token_expiry,
token_uri="http://example.com",
user_agent="n/a",
scopes=token_scopes,
)
@pytest.fixture
def config_entry_token_expiry() -> float:
"""Fixture for token expiration value stored in the config entry."""
return time.time() + 86400
@pytest.fixture
def config_entry_options() -> dict[str, Any] | None:
"""Fixture to set initial config entry options."""
return None
@pytest.fixture
def config_entry_unique_id() -> str:
"""Fixture that returns the default config entry unique id."""
return EMAIL_ADDRESS
@pytest.fixture
def config_entry(
config_entry_unique_id: str,
token_scopes: list[str],
config_entry_token_expiry: float,
config_entry_options: dict[str, Any] | None,
) -> MockConfigEntry:
"""Fixture to create a config entry for the integration."""
return MockConfigEntry(
domain=DOMAIN,
unique_id=config_entry_unique_id,
data={
"auth_implementation": DOMAIN,
"token": {
"access_token": "ACCESS_TOKEN",
"refresh_token": "REFRESH_TOKEN",
"scope": " ".join(token_scopes),
"token_type": "Bearer",
"expires_at": config_entry_token_expiry,
},
},
options=config_entry_options,
)
@pytest.fixture
def mock_events_list(
aioclient_mock: AiohttpClientMocker,
) -> ApiResult:
"""Fixture to construct a fake event list API response."""
def _put_result(
response: dict[str, Any],
calendar_id: str | None = None,
exc: ClientError | None = None,
) -> None:
if calendar_id is None:
calendar_id = CALENDAR_ID
resp = {
**response,
"nextSyncToken": "sync-token",
}
aioclient_mock.get(
f"{API_BASE_URL}/calendars/{calendar_id}/events",
json=resp,
exc=exc,
)
return _put_result
@pytest.fixture
def mock_events_list_items(
mock_events_list: Callable[[dict[str, Any]], None],
) -> Callable[[list[dict[str, Any]]], None]:
"""Fixture to construct an API response containing event items."""
def _put_items(items: list[dict[str, Any]]) -> None:
mock_events_list({"items": items})
return _put_items
@pytest.fixture
def mock_calendars_list(
aioclient_mock: AiohttpClientMocker,
) -> ApiResult:
"""Fixture to construct a fake calendar list API response."""
def _result(response: dict[str, Any], exc: ClientError | None = None) -> None:
resp = {
**response,
"nextSyncToken": "sync-token",
}
aioclient_mock.get(
f"{API_BASE_URL}/users/me/calendarList",
json=resp,
exc=exc,
)
return _result
@pytest.fixture
def mock_calendar_get(
aioclient_mock: AiohttpClientMocker,
) -> Callable[..., None]:
"""Fixture for returning a calendar get response."""
def _result(
calendar_id: str,
response: dict[str, Any],
exc: ClientError | None = None,
status: http.HTTPStatus = http.HTTPStatus.OK,
) -> None:
aioclient_mock.get(
f"{API_BASE_URL}/calendars/{calendar_id}",
json=response,
exc=exc,
status=status,
)
return _result
@pytest.fixture
def mock_insert_event(
aioclient_mock: AiohttpClientMocker,
) -> Callable[..., None]:
"""Fixture for capturing event creation."""
def _expect_result(
calendar_id: str = CALENDAR_ID, exc: ClientError | None = None
) -> None:
aioclient_mock.post(
f"{API_BASE_URL}/calendars/{calendar_id}/events",
exc=exc,
)
return _expect_result
@pytest.fixture(autouse=True)
async def set_time_zone(hass: HomeAssistant) -> None:
"""Set the time zone for the tests."""
# Set our timezone to CST/Regina so we can check calculations
# This keeps UTC-6 all year round
await hass.config.async_set_time_zone("America/Regina")
@pytest.fixture
def component_setup(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> ComponentSetup:
"""Fixture for setting up the integration."""
async def _setup_func() -> bool:
assert await async_setup_component(hass, "application_credentials", {})
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential("client-id", "client-secret"),
)
config_entry.add_to_hass(hass)
return await hass.config_entries.async_setup(config_entry.entry_id)
return _setup_func

View File

@@ -0,0 +1,13 @@
{
"results": [
{
"elevation": 101.5,
"location": {
"lat": 32.54321,
"lng": -117.12345
},
"resolution": 4.8
}
],
"status": "OK"
}

View File

@@ -0,0 +1,80 @@
# serializer version: 1
# name: test_diagnostics
dict({
'now': '2023-03-13T13:05:00-06:00',
'store': dict({
'calendar#1': dict({
'events': list([
dict({
'attendees': '**REDACTED**',
'attendees_omitted': False,
'description': '**REDACTED**',
'end': dict({
'date': None,
'date_time': '2023-03-13T12:30:00-07:00',
'timezone': None,
}),
'event_type': 'default',
'ical_uuid': '**REDACTED**',
'id': '**REDACTED**',
'location': '**REDACTED**',
'original_start_time': None,
'recurrence': list([
]),
'recurring_event_id': None,
'reminders': dict({
'overrides': list([
]),
'use_default': True,
}),
'start': dict({
'date': None,
'date_time': '2023-03-13T12:00:00-07:00',
'timezone': None,
}),
'status': 'confirmed',
'summary': '**REDACTED**',
'transparency': 'transparent',
'visibility': 'default',
}),
dict({
'attendees': '**REDACTED**',
'attendees_omitted': False,
'description': '**REDACTED**',
'end': dict({
'date': '2022-10-09',
'date_time': None,
'timezone': None,
}),
'event_type': 'default',
'ical_uuid': '**REDACTED**',
'id': '**REDACTED**',
'location': '**REDACTED**',
'original_start_time': None,
'recurrence': list([
'RRULE:FREQ=WEEKLY',
]),
'recurring_event_id': None,
'reminders': dict({
'overrides': list([
]),
'use_default': True,
}),
'start': dict({
'date': '2022-10-08',
'date_time': None,
'timezone': None,
}),
'status': 'confirmed',
'summary': '**REDACTED**',
'transparency': 'transparent',
'visibility': 'default',
}),
]),
'sync_token_version': 2,
}),
}),
'system_timezone': 'tzlocal()',
'timezone': 'America/Regina',
})
# ---

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,849 @@
"""Test the google config flow."""
from __future__ import annotations
import asyncio
from collections.abc import Callable
import datetime
from http import HTTPStatus
from typing import Any
from unittest.mock import Mock, patch
from aiohttp.client_exceptions import ClientError
from freezegun import freeze_time
from freezegun.api import FrozenDateTimeFactory
from oauth2client.client import (
DeviceFlowInfo,
FlowExchangeError,
OAuth2Credentials,
OAuth2DeviceCodeError,
)
import pytest
from homeassistant import config_entries
from homeassistant.components.application_credentials import (
ClientCredential,
async_import_client_credential,
)
from homeassistant.components.google.const import (
CONF_CALENDAR_ACCESS,
CONF_CREDENTIAL_TYPE,
DOMAIN,
CredentialType,
FeatureAccess,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow
from .conftest import CLIENT_ID, CLIENT_SECRET, EMAIL_ADDRESS, AsyncYieldFixture
from tests.common import MockConfigEntry, async_fire_time_changed
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
CODE_CHECK_INTERVAL = 1
CODE_CHECK_ALARM_TIMEDELTA = datetime.timedelta(seconds=CODE_CHECK_INTERVAL * 2)
OAUTH2_AUTHORIZE = "https://accounts.google.com/o/oauth2/v2/auth"
OAUTH2_TOKEN = "https://oauth2.googleapis.com/token"
@pytest.fixture(autouse=True)
async def request_setup(current_request_with_host: None) -> None:
"""Request setup."""
@pytest.fixture(autouse=True)
async def setup_app_creds(hass: HomeAssistant) -> None:
"""Fixture to setup application credentials component."""
await async_setup_component(hass, "application_credentials", {})
@pytest.fixture
async def code_expiration_delta() -> datetime.timedelta:
"""Fixture for code expiration time, defaulting to the future."""
return datetime.timedelta(minutes=3)
@pytest.fixture
async def mock_code_flow(
code_expiration_delta: datetime.timedelta,
) -> AsyncYieldFixture[Mock]:
"""Fixture for initiating OAuth flow."""
with patch(
"homeassistant.components.google.api.OAuth2WebServerFlow.step1_get_device_and_user_codes",
) as mock_flow:
mock_flow.return_value = DeviceFlowInfo.FromResponse(
{
"device_code": "4/4-GMMhmHCXhWEzkobqIHGG_EnNYYsAkukHspeYUk9E8",
"user_code": "GQVQ-JKEC",
"verification_url": "https://www.google.com/device",
"expires_in": code_expiration_delta.total_seconds(),
"interval": CODE_CHECK_INTERVAL,
}
)
yield mock_flow
@pytest.fixture
async def mock_exchange(creds: OAuth2Credentials) -> AsyncYieldFixture[Mock]:
"""Fixture for mocking out the exchange for credentials."""
with patch(
"homeassistant.components.google.api.OAuth2WebServerFlow.step2_exchange",
return_value=creds,
) as mock:
yield mock
@pytest.fixture
async def primary_calendar_email() -> str:
"""Fixture to override the google calendar primary email address."""
return EMAIL_ADDRESS
@pytest.fixture
async def primary_calendar_error() -> ClientError | None:
"""Fixture for tests to inject an error during calendar lookup."""
return None
@pytest.fixture
async def primary_calendar_status() -> HTTPStatus | None:
"""Fixture for tests to inject an error during calendar lookup."""
return HTTPStatus.OK
@pytest.fixture(autouse=True)
async def primary_calendar(
mock_calendar_get: Callable[..., None],
primary_calendar_error: ClientError | None,
primary_calendar_status: HTTPStatus | None,
primary_calendar_email: str,
) -> None:
"""Fixture to return the primary calendar."""
mock_calendar_get(
"primary",
{"id": primary_calendar_email, "summary": "Personal", "accessRole": "owner"},
exc=primary_calendar_error,
status=primary_calendar_status,
)
async def fire_alarm(hass: HomeAssistant, point_in_time: datetime.datetime) -> None:
"""Fire an alarm and wait for callbacks to run."""
with freeze_time(point_in_time):
async_fire_time_changed(hass, point_in_time)
await hass.async_block_till_done()
async def test_full_flow_application_creds(
hass: HomeAssistant,
mock_code_flow: Mock,
mock_exchange: Mock,
) -> None:
"""Test successful creds setup."""
await async_import_client_credential(
hass, DOMAIN, ClientCredential(CLIENT_ID, CLIENT_SECRET), "imported-cred"
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.SHOW_PROGRESS
assert result.get("step_id") == "auth"
assert "description_placeholders" in result
assert "url" in result["description_placeholders"]
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
# Run one tick to invoke the credential exchange check
now = utcnow()
await fire_alarm(hass, now + CODE_CHECK_ALARM_TIMEDELTA)
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"]
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result.get("title") == EMAIL_ADDRESS
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 == {
"auth_implementation": "imported-cred",
"token": {
"access_token": "ACCESS_TOKEN",
"refresh_token": "REFRESH_TOKEN",
"scope": "https://www.googleapis.com/auth/calendar",
"token_type": "Bearer",
},
"credential_type": "device_auth",
}
assert result.get("options") == {"calendar_access": "read_write"}
assert len(mock_setup.mock_calls) == 1
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
async def test_code_error(
hass: HomeAssistant,
mock_code_flow: Mock,
) -> None:
"""Test server error setting up the oauth flow."""
await async_import_client_credential(
hass, DOMAIN, ClientCredential(CLIENT_ID, CLIENT_SECRET), "imported-cred"
)
with patch(
"homeassistant.components.google.api.OAuth2WebServerFlow.step1_get_device_and_user_codes",
side_effect=OAuth2DeviceCodeError("Test Failure"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "oauth_error"
async def test_timeout_error(
hass: HomeAssistant,
mock_code_flow: Mock,
) -> None:
"""Test timeout error setting up the oauth flow."""
await async_import_client_credential(
hass, DOMAIN, ClientCredential(CLIENT_ID, CLIENT_SECRET), "imported-cred"
)
with patch(
"homeassistant.components.google.api.OAuth2WebServerFlow.step1_get_device_and_user_codes",
side_effect=TimeoutError(),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "timeout_connect"
@pytest.mark.parametrize("code_expiration_delta", [datetime.timedelta(seconds=50)])
async def test_expired_after_exchange(
hass: HomeAssistant,
mock_code_flow: Mock,
) -> None:
"""Test credential exchange expires."""
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential(CLIENT_ID, CLIENT_SECRET),
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.SHOW_PROGRESS
assert result.get("step_id") == "auth"
assert "description_placeholders" in result
assert "url" in result["description_placeholders"]
# Fail first attempt then advance clock past exchange timeout
with patch(
"homeassistant.components.google.api.OAuth2WebServerFlow.step2_exchange",
side_effect=FlowExchangeError(),
):
now = utcnow()
await fire_alarm(hass, now + datetime.timedelta(seconds=65))
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(flow_id=result["flow_id"])
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "code_expired"
async def test_exchange_error(
hass: HomeAssistant,
mock_code_flow: Mock,
mock_exchange: Mock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test an error while exchanging the code for credentials."""
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential(CLIENT_ID, CLIENT_SECRET),
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.SHOW_PROGRESS
assert result.get("step_id") == "auth"
assert "description_placeholders" in result
assert "url" in result["description_placeholders"]
# Run one tick to invoke the credential exchange check
step2_exchange_called = asyncio.Event()
def step2_exchange(*args, **kwargs):
hass.loop.call_soon_threadsafe(step2_exchange_called.set)
raise FlowExchangeError
with patch(
"homeassistant.components.google.api.OAuth2WebServerFlow.step2_exchange",
side_effect=step2_exchange,
):
freezer.tick(CODE_CHECK_ALARM_TIMEDELTA)
async_fire_time_changed(hass, utcnow())
await step2_exchange_called.wait()
# Status has not updated, will retry
result = await hass.config_entries.flow.async_configure(flow_id=result["flow_id"])
assert result.get("type") is FlowResultType.SHOW_PROGRESS
assert result.get("step_id") == "auth"
# Run another tick, which attempts credential exchange again
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
freezer.tick(CODE_CHECK_ALARM_TIMEDELTA)
async_fire_time_changed(hass, utcnow())
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"]
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result.get("title") == EMAIL_ADDRESS
assert "data" in result
data = result["data"]
assert "token" in data
data["token"].pop("expires_at")
data["token"].pop("expires_in")
assert data == {
"auth_implementation": DOMAIN,
"token": {
"access_token": "ACCESS_TOKEN",
"refresh_token": "REFRESH_TOKEN",
"scope": "https://www.googleapis.com/auth/calendar",
"token_type": "Bearer",
},
"credential_type": "device_auth",
}
assert len(mock_setup.mock_calls) == 1
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
async def test_duplicate_config_entries(
hass: HomeAssistant,
mock_code_flow: Mock,
mock_exchange: Mock,
config_entry: MockConfigEntry,
) -> None:
"""Test that the same account cannot be setup twice."""
await async_import_client_credential(
hass, DOMAIN, ClientCredential(CLIENT_ID, CLIENT_SECRET)
)
# Load a config entry
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
# Start a new config flow using the same credential
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.SHOW_PROGRESS
assert result.get("step_id") == "auth"
assert "description_placeholders" in result
assert "url" in result["description_placeholders"]
# Run one tick to invoke the credential exchange check
now = utcnow()
await fire_alarm(hass, now + CODE_CHECK_ALARM_TIMEDELTA)
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(flow_id=result["flow_id"])
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "already_configured"
@pytest.mark.parametrize("primary_calendar_email", ["another-email@example.com"])
async def test_multiple_config_entries(
hass: HomeAssistant,
mock_code_flow: Mock,
mock_exchange: Mock,
config_entry: MockConfigEntry,
) -> None:
"""Test that multiple config entries can be set at once."""
await async_import_client_credential(
hass, DOMAIN, ClientCredential(CLIENT_ID, CLIENT_SECRET)
)
# Load a config entry
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
# Start a new config flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.SHOW_PROGRESS
assert result.get("step_id") == "auth"
assert "description_placeholders" in result
assert "url" in result["description_placeholders"]
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
# Run one tick to invoke the credential exchange check
now = utcnow()
await fire_alarm(hass, now + CODE_CHECK_ALARM_TIMEDELTA)
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"]
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result.get("title") == "another-email@example.com"
assert len(mock_setup.mock_calls) == 1
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 2
async def test_missing_configuration(
hass: HomeAssistant,
) -> None:
"""Test can't configure when no authentication source is available."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "missing_credentials"
async def test_wrong_configuration(
hass: HomeAssistant,
) -> None:
"""Test can't use the wrong type of authentication."""
# Google calendar flow currently only supports device auth
config_entry_oauth2_flow.async_register_implementation(
hass,
DOMAIN,
config_entry_oauth2_flow.LocalOAuth2Implementation(
hass,
DOMAIN,
CLIENT_ID,
CLIENT_SECRET,
"http://example/authorize",
"http://example/token",
),
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "oauth_error"
@pytest.mark.parametrize(
("options"),
[
({}),
(
{
CONF_CALENDAR_ACCESS: FeatureAccess.read_write.name,
}
),
(
{
CONF_CALENDAR_ACCESS: FeatureAccess.read_only.name,
}
),
],
)
async def test_reauth_flow(
hass: HomeAssistant,
mock_code_flow: Mock,
mock_exchange: Mock,
options: dict[str, Any] | None,
) -> None:
"""Test reauth of an existing config entry."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation": DOMAIN,
"token": {"access_token": "OLD_ACCESS_TOKEN"},
},
options=options,
)
config_entry.add_to_hass(hass)
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential(CLIENT_ID, CLIENT_SECRET),
)
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"],
user_input={},
)
assert result.get("type") is FlowResultType.SHOW_PROGRESS
assert result.get("step_id") == "auth"
assert "description_placeholders" in result
assert "url" in result["description_placeholders"]
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
# Run one tick to invoke the credential exchange check
now = utcnow()
await fire_alarm(hass, now + CODE_CHECK_ALARM_TIMEDELTA)
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"]
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reauth_successful"
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
data = entries[0].data
assert "token" in data
data["token"].pop("expires_at")
data["token"].pop("expires_in")
assert data == {
"auth_implementation": DOMAIN,
"token": {
"access_token": "ACCESS_TOKEN",
"refresh_token": "REFRESH_TOKEN",
"scope": "https://www.googleapis.com/auth/calendar",
"token_type": "Bearer",
},
"credential_type": "device_auth",
}
# Options are preserved during reauth
assert entries[0].options == options
assert len(mock_setup.mock_calls) == 1
@pytest.mark.parametrize(
("primary_calendar_error", "primary_calendar_status", "reason"),
[
(ClientError(), None, "cannot_connect"),
(None, HTTPStatus.FORBIDDEN, "api_disabled"),
(None, HTTPStatus.SERVICE_UNAVAILABLE, "cannot_connect"),
],
)
async def test_calendar_lookup_failure(
hass: HomeAssistant,
mock_code_flow: Mock,
mock_exchange: Mock,
reason: str,
) -> None:
"""Test successful config flow and title fetch fails gracefully."""
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential(CLIENT_ID, CLIENT_SECRET),
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.SHOW_PROGRESS
assert result.get("step_id") == "auth"
assert "description_placeholders" in result
assert "url" in result["description_placeholders"]
with patch("homeassistant.components.google.async_setup_entry", return_value=True):
# Run one tick to invoke the credential exchange check
now = utcnow()
await fire_alarm(hass, now + CODE_CHECK_ALARM_TIMEDELTA)
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"]
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == reason
async def test_options_flow_triggers_reauth(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test load and unload of a ConfigEntry."""
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
await hass.config_entries.async_setup(config_entry.entry_id)
mock_setup.assert_called_once()
assert config_entry.state is ConfigEntryState.LOADED
assert config_entry.options == {} # Default is read_write
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
data_schema = result["data_schema"].schema
assert set(data_schema) == {"calendar_access"}
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
"calendar_access": "read_only",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert config_entry.options == {"calendar_access": "read_only"}
async def test_options_flow_no_changes(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test load and unload of a ConfigEntry."""
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
await hass.config_entries.async_setup(config_entry.entry_id)
mock_setup.assert_called_once()
assert config_entry.state is ConfigEntryState.LOADED
assert config_entry.options == {} # Default is read_write
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
"calendar_access": "read_write",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert config_entry.options == {"calendar_access": "read_write"}
@pytest.mark.usefixtures("current_request_with_host")
async def test_web_auth_compatibility(
hass: HomeAssistant,
mock_code_flow: Mock,
aioclient_mock: AiohttpClientMocker,
hass_client_no_auth: ClientSessionGenerator,
) -> None:
"""Test that we can callback to web auth tokens."""
await async_import_client_credential(
hass,
DOMAIN,
ClientCredential(CLIENT_ID, CLIENT_SECRET),
)
with patch(
"homeassistant.components.google.api.OAuth2WebServerFlow.step1_get_device_and_user_codes",
side_effect=OAuth2DeviceCodeError(
"Invalid response 401. Error: invalid_client"
),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
assert result["type"] is FlowResultType.EXTERNAL_STEP
assert result["url"] == (
f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}"
"&redirect_uri=https://example.com/auth/external/callback"
f"&state={state}"
"&scope=https://www.googleapis.com/auth/calendar"
"&access_type=offline&prompt=consent"
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post(
OAUTH2_TOKEN,
json={
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
"scope": "https://www.googleapis.com/auth/calendar",
},
)
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.CREATE_ENTRY
token = result.get("data", {}).get("token", {})
del token["expires_at"]
assert token == {
"access_token": "mock-access-token",
"expires_in": 60,
"refresh_token": "mock-refresh-token",
"type": "Bearer",
"scope": "https://www.googleapis.com/auth/calendar",
}
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert len(mock_setup.mock_calls) == 1
@pytest.mark.parametrize(
"entry_data",
[
{},
{CONF_CREDENTIAL_TYPE: CredentialType.WEB_AUTH},
],
)
async def test_web_reauth_flow(
hass: HomeAssistant,
mock_code_flow: Mock,
mock_exchange: Mock,
aioclient_mock: AiohttpClientMocker,
hass_client_no_auth: ClientSessionGenerator,
entry_data: dict[str, Any],
) -> None:
"""Test reauth of an existing config entry with a web credential."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
**entry_data,
"auth_implementation": DOMAIN,
"token": {"access_token": "OLD_ACCESS_TOKEN"},
},
)
config_entry.add_to_hass(hass)
await async_import_client_credential(
hass, DOMAIN, ClientCredential(CLIENT_ID, CLIENT_SECRET)
)
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
with patch(
"homeassistant.components.google.api.OAuth2WebServerFlow.step1_get_device_and_user_codes",
side_effect=OAuth2DeviceCodeError(
"Invalid response 401. Error: invalid_client"
),
):
result = await hass.config_entries.flow.async_configure(
flow_id=result["flow_id"],
user_input={},
)
state = config_entry_oauth2_flow._encode_jwt(
hass,
{
"flow_id": result["flow_id"],
"redirect_uri": "https://example.com/auth/external/callback",
},
)
assert result.get("type") is FlowResultType.EXTERNAL_STEP
assert result["url"] == (
f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}"
"&redirect_uri=https://example.com/auth/external/callback"
f"&state={state}"
"&scope=https://www.googleapis.com/auth/calendar"
"&access_type=offline&prompt=consent"
)
client = await hass_client_no_auth()
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
assert resp.status == 200
assert resp.headers["content-type"] == "text/html; charset=utf-8"
aioclient_mock.post(
OAUTH2_TOKEN,
json={
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"token_type": "Bearer",
"expires_in": 60,
"scope": "https://www.googleapis.com/auth/calendar",
},
)
with patch(
"homeassistant.components.google.async_setup_entry", return_value=True
) as mock_setup:
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
data = dict(entries[0].data)
data["token"].pop("expires_at")
data["token"].pop("expires_in")
assert data == {
"auth_implementation": DOMAIN,
"token": {
"access_token": "mock-access-token",
"refresh_token": "mock-refresh-token",
"scope": "https://www.googleapis.com/auth/calendar",
"token_type": "Bearer",
},
"credential_type": "web_auth",
}
assert len(mock_setup.mock_calls) == 1

View File

@@ -0,0 +1,115 @@
"""Tests for diagnostics platform of google calendar."""
from collections.abc import Callable
import time
from typing import Any
from aiohttp.test_utils import TestClient
from freezegun import freeze_time
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.auth.models import Credentials
from homeassistant.core import HomeAssistant
from .conftest import TEST_EVENT, ApiResult, ComponentSetup
from tests.common import CLIENT_ID, MockConfigEntry, MockUser
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True)
def mock_test_setup(
test_api_calendar: dict[str, Any],
mock_calendars_list: ApiResult,
) -> None:
"""Fixture that sets up the default API responses during integration setup."""
mock_calendars_list({"items": [test_api_calendar]})
async def generate_new_hass_access_token(
hass: HomeAssistant, hass_admin_user: MockUser, hass_admin_credential: Credentials
) -> str:
"""Return an access token to access Home Assistant."""
await hass.auth.async_link_user(hass_admin_user, hass_admin_credential)
refresh_token = await hass.auth.async_create_refresh_token(
hass_admin_user, CLIENT_ID, credential=hass_admin_credential
)
return hass.auth.async_create_access_token(refresh_token)
def _get_test_client_generator(
hass: HomeAssistant, aiohttp_client: ClientSessionGenerator, new_token: str
):
"""Return a test client generator.""."""
async def auth_client() -> TestClient:
return await aiohttp_client(
hass.http.app, headers={"Authorization": f"Bearer {new_token}"}
)
return auth_client
@freeze_time("2023-03-13 12:05:00-07:00")
@pytest.mark.usefixtures("socket_enabled")
async def test_diagnostics(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_events_list_items: Callable[[list[dict[str, Any]]], None],
hass_admin_user: MockUser,
hass_admin_credential: Credentials,
config_entry: MockConfigEntry,
aiohttp_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test diagnostics for the calendar."""
expires_in = 86400
expires_at = time.time() + expires_in
aioclient_mock.post(
"https://oauth2.googleapis.com/token",
json={
"refresh_token": "some-refresh-token",
"access_token": "some-updated-token",
"expires_at": expires_at,
"expires_in": expires_in,
},
)
mock_events_list_items(
[
{
**TEST_EVENT,
"id": "event-id-1",
"iCalUID": "event-id-1@google.com",
"start": {"dateTime": "2023-03-13 12:00:00-07:00"},
"end": {"dateTime": "2023-03-13 12:30:00-07:00"},
},
{
**TEST_EVENT,
"id": "event-id-2",
"iCalUID": "event-id-2@google.com",
"summary": "All Day Event",
"start": {"date": "2022-10-08"},
"end": {"date": "2022-10-09"},
"recurrence": ["RRULE:FREQ=WEEKLY"],
},
]
)
assert await component_setup()
# Since we are freezing time only when we enter this test, we need to
# manually create a new token and clients since the token created by
# the fixtures would not be valid.
new_token = await generate_new_hass_access_token(
hass, hass_admin_user, hass_admin_credential
)
data = await get_diagnostics_for_config_entry(
hass, _get_test_client_generator(hass, aiohttp_client, new_token), config_entry
)
assert data == snapshot

View File

@@ -0,0 +1,955 @@
"""The tests for the Google Calendar component."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
import datetime
import http
import time
from typing import Any
from unittest.mock import Mock, patch
import zoneinfo
from aiohttp.client_exceptions import ClientError
import pytest
import voluptuous as vol
from homeassistant.components.google import DOMAIN, SERVICE_ADD_EVENT
from homeassistant.components.google.calendar import SERVICE_CREATE_EVENT
from homeassistant.components.google.const import CONF_CALENDAR_ACCESS
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_FRIENDLY_NAME, STATE_OFF
from homeassistant.core import HomeAssistant, State
from homeassistant.exceptions import HomeAssistantError, ServiceNotSupported
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import UTC, utcnow
from .conftest import (
CALENDAR_ID,
EMAIL_ADDRESS,
TEST_API_ENTITY,
TEST_API_ENTITY_NAME,
TEST_YAML_ENTITY,
ApiResult,
ComponentSetup,
)
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
EXPIRED_TOKEN_TIMESTAMP = datetime.datetime(2022, 4, 8).timestamp()
# Typing helpers
type HassApi = Callable[[], Awaitable[dict[str, Any]]]
TEST_EVENT_SUMMARY = "Test Summary"
TEST_EVENT_DESCRIPTION = "Test Description"
TEST_EVENT_LOCATION = "Test Location"
def assert_state(actual: State | None, expected: State | None) -> None:
"""Assert that the two states are equal."""
if actual is None or expected is None:
assert actual == expected
return
assert actual.entity_id == expected.entity_id
assert actual.state == expected.state
assert actual.attributes == expected.attributes
@pytest.fixture(
params=[
(
DOMAIN,
SERVICE_ADD_EVENT,
{"calendar_id": CALENDAR_ID},
None,
),
(
DOMAIN,
SERVICE_CREATE_EVENT,
{},
{"entity_id": TEST_API_ENTITY},
),
(
"calendar",
SERVICE_CREATE_EVENT,
{},
{"entity_id": TEST_API_ENTITY},
),
],
ids=("google.add_event", "google.create_event", "calendar.create_event"),
)
def add_event_call_service(
hass: HomeAssistant,
request: pytest.FixtureRequest,
) -> Callable[[dict[str, Any]], Awaitable[None]]:
"""Fixture for calling the add or create event service."""
(domain, service_call, data, target) = request.param
async def call_service(params: dict[str, Any]) -> None:
await hass.services.async_call(
domain,
service_call,
{
**data,
**params,
"summary": TEST_EVENT_SUMMARY,
"description": TEST_EVENT_DESCRIPTION,
},
target=target,
blocking=True,
)
return call_service
async def test_unload_entry(
hass: HomeAssistant,
component_setup: ComponentSetup,
) -> None:
"""Test load and unload of a ConfigEntry."""
await component_setup()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
entry = entries[0]
assert entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(entry.entry_id)
assert entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
"token_scopes", ["https://www.googleapis.com/auth/calendar.readonly"]
)
async def test_existing_token_missing_scope(
hass: HomeAssistant,
token_scopes: list[str],
component_setup: ComponentSetup,
config_entry: MockConfigEntry,
) -> None:
"""Test setup where existing token does not have sufficient scopes."""
await component_setup()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
@pytest.mark.parametrize("config_entry_options", [{CONF_CALENDAR_ACCESS: "read_only"}])
async def test_config_entry_scope_reauth(
hass: HomeAssistant,
token_scopes: list[str],
component_setup: ComponentSetup,
config_entry: MockConfigEntry,
) -> None:
"""Test setup where the config entry options requires reauth to match the scope."""
await component_setup()
assert config_entry.state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
@pytest.mark.parametrize("calendars_config", [[{"cal_id": "invalid-schema"}]])
async def test_calendar_yaml_missing_required_fields(
hass: HomeAssistant,
component_setup: ComponentSetup,
calendars_config: list[dict[str, Any]],
mock_calendars_yaml: None,
config_entry: MockConfigEntry,
) -> None:
"""Test setup with a missing schema fields, ignores the error and continues."""
assert not await component_setup()
assert config_entry.state is ConfigEntryState.SETUP_ERROR
@pytest.mark.parametrize("calendars_config", [[{"missing-cal_id": "invalid-schema"}]])
async def test_invalid_calendar_yaml(
hass: HomeAssistant,
component_setup: ComponentSetup,
calendars_config: list[dict[str, Any]],
mock_calendars_yaml: None,
config_entry: MockConfigEntry,
) -> None:
"""Test setup with missing entity id fields fails to load the platform."""
assert not await component_setup()
assert config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_calendar_yaml_error(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
) -> None:
"""Test setup with yaml file not found."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
with patch("homeassistant.components.google.open", side_effect=FileNotFoundError()):
assert await component_setup()
assert not hass.states.get(TEST_YAML_ENTITY)
assert hass.states.get(TEST_API_ENTITY)
@pytest.mark.parametrize("calendars_config", [None])
async def test_empty_calendar_yaml(
hass: HomeAssistant,
component_setup: ComponentSetup,
calendars_config: list[dict[str, Any]],
mock_calendars_yaml: None,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
) -> None:
"""Test an empty yaml file is equivalent to a missing yaml file."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
assert not hass.states.get(TEST_YAML_ENTITY)
assert hass.states.get(TEST_API_ENTITY)
async def test_init_calendar(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
) -> None:
"""Test finding a calendar from the API."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
state = hass.states.get(TEST_API_ENTITY)
assert state
assert state.name == TEST_API_ENTITY_NAME
assert state.state == STATE_OFF
# No yaml config loaded that overwrites the entity name
assert not hass.states.get(TEST_YAML_ENTITY)
async def test_multiple_config_entries(
hass: HomeAssistant,
component_setup: ComponentSetup,
config_entry: MockConfigEntry,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test finding a calendar from the API."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
state = hass.states.get(TEST_API_ENTITY)
assert state
assert state.state == STATE_OFF
assert state.attributes.get(ATTR_FRIENDLY_NAME) == TEST_API_ENTITY_NAME
config_entry2 = MockConfigEntry(
domain=DOMAIN, data=config_entry.data, unique_id="other-address@example.com"
)
calendar2 = {
**test_api_calendar,
"id": "calendar-id2",
"summary": "Example Calendar 2",
}
aioclient_mock.clear_requests()
mock_calendars_list({"items": [calendar2]})
mock_events_list({}, calendar_id="calendar-id2")
config_entry2.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry2.entry_id)
await hass.async_block_till_done()
state = hass.states.get("calendar.example_calendar_2")
assert state
assert state.attributes.get(ATTR_FRIENDLY_NAME) == "Example calendar 2"
@pytest.mark.parametrize(
("date_fields", "expected_error", "error_match"),
[
(
{},
vol.error.MultipleInvalid,
"must contain at least one of start_date, start_date_time, in",
),
(
{
"start_date": "2022-04-01",
},
vol.error.MultipleInvalid,
"Start and end dates must both be specified",
),
(
{
"end_date": "2022-04-02",
},
vol.error.MultipleInvalid,
"must contain at least one of start_date, start_date_time, in.",
),
(
{
"start_date_time": "2022-04-01T06:00:00",
},
vol.error.MultipleInvalid,
"Start and end datetimes must both be specified",
),
(
{
"end_date_time": "2022-04-02T07:00:00",
},
vol.error.MultipleInvalid,
"must contain at least one of start_date, start_date_time, in.",
),
(
{
"start_date": "2022-04-01",
"start_date_time": "2022-04-01T06:00:00",
"end_date_time": "2022-04-02T07:00:00",
},
vol.error.MultipleInvalid,
"must contain at most one of start_date, start_date_time, in.",
),
(
{
"start_date_time": "2022-04-01T06:00:00",
"end_date_time": "2022-04-01T07:00:00",
"end_date": "2022-04-02",
},
vol.error.MultipleInvalid,
"Start and end dates must both be specified",
),
(
{
"start_date": "2022-04-01",
"end_date_time": "2022-04-02T07:00:00",
},
vol.error.MultipleInvalid,
"Start and end dates must both be specified",
),
(
{
"start_date_time": "2022-04-01T07:00:00",
"end_date": "2022-04-02",
},
vol.error.MultipleInvalid,
"Start and end dates must both be specified",
),
(
{
"in": {
"days": 2,
"weeks": 2,
}
},
vol.error.MultipleInvalid,
"two or more values in the same group of exclusion 'event_types'",
),
(
{
"start_date": "2022-04-01",
"end_date": "2022-04-02",
"in": {
"days": 2,
},
},
vol.error.MultipleInvalid,
"must contain at most one of start_date, start_date_time, in.",
),
(
{
"start_date_time": "2022-04-01T07:00:00",
"end_date_time": "2022-04-01T07:00:00",
"in": {
"days": 2,
},
},
vol.error.MultipleInvalid,
"must contain at most one of start_date, start_date_time, in.",
),
],
ids=[
"missing_all",
"missing_end_date",
"missing_start_date",
"missing_end_datetime",
"missing_start_datetime",
"multiple_start",
"multiple_end",
"missing_end_date",
"missing_end_date_time",
"multiple_in",
"unexpected_in_with_date",
"unexpected_in_with_datetime",
],
)
async def test_add_event_invalid_params(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
add_event_call_service: Callable[[dict[str, Any]], Awaitable[None]],
date_fields: dict[str, Any],
expected_error: type[Exception],
error_match: str | None,
) -> None:
"""Test service calls with incorrect fields."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
with pytest.raises(expected_error, match=error_match):
await add_event_call_service(date_fields)
@pytest.mark.parametrize(
("date_fields", "start_timedelta", "end_timedelta"),
[
(
{"in": {"days": 3}},
datetime.timedelta(days=3),
datetime.timedelta(days=4),
),
(
{"in": {"weeks": 1}},
datetime.timedelta(days=7),
datetime.timedelta(days=8),
),
],
ids=["in_days", "in_weeks"],
)
async def test_add_event_date_in_x(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
mock_insert_event: Callable[..., None],
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
date_fields: dict[str, Any],
start_timedelta: datetime.timedelta,
end_timedelta: datetime.timedelta,
aioclient_mock: AiohttpClientMocker,
add_event_call_service: Callable[[dict[str, Any]], Awaitable[None]],
) -> None:
"""Test service call that adds an event with various time ranges."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
now = datetime.datetime.now()
start_date = now + start_timedelta
end_date = now + end_timedelta
aioclient_mock.clear_requests()
mock_insert_event(
calendar_id=CALENDAR_ID,
)
await add_event_call_service(date_fields)
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == {
"summary": TEST_EVENT_SUMMARY,
"description": TEST_EVENT_DESCRIPTION,
"start": {"date": start_date.date().isoformat()},
"end": {"date": end_date.date().isoformat()},
}
async def test_add_event_date(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_insert_event: Callable[..., None],
mock_events_list: ApiResult,
aioclient_mock: AiohttpClientMocker,
add_event_call_service: Callable[[dict[str, Any]], Awaitable[None]],
) -> None:
"""Test service call that sets a date range."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
now = utcnow()
today = now.date()
end_date = today + datetime.timedelta(days=2)
aioclient_mock.clear_requests()
mock_insert_event(
calendar_id=CALENDAR_ID,
)
await add_event_call_service(
{
"start_date": today.isoformat(),
"end_date": end_date.isoformat(),
},
)
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == {
"summary": TEST_EVENT_SUMMARY,
"description": TEST_EVENT_DESCRIPTION,
"start": {"date": today.isoformat()},
"end": {"date": end_date.isoformat()},
}
async def test_add_event_date_time(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
mock_insert_event: Callable[..., None],
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
aioclient_mock: AiohttpClientMocker,
add_event_call_service: Callable[[dict[str, Any]], Awaitable[None]],
) -> None:
"""Test service call that adds an event with a date time range."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
start_datetime = datetime.datetime.now(tz=zoneinfo.ZoneInfo("America/Regina"))
delta = datetime.timedelta(days=3, hours=3)
end_datetime = start_datetime + delta
aioclient_mock.clear_requests()
mock_insert_event(
calendar_id=CALENDAR_ID,
)
await add_event_call_service(
{
"start_date_time": start_datetime.isoformat(),
"end_date_time": end_datetime.isoformat(),
},
)
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == {
"summary": TEST_EVENT_SUMMARY,
"description": TEST_EVENT_DESCRIPTION,
"start": {
"dateTime": start_datetime.isoformat(timespec="seconds"),
"timeZone": "America/Regina",
},
"end": {
"dateTime": end_datetime.isoformat(timespec="seconds"),
"timeZone": "America/Regina",
},
}
@pytest.mark.parametrize(
"calendars_config",
[
[
{
"cal_id": CALENDAR_ID,
"entities": [
{
"device_id": "backyard_light",
"name": "Backyard Light",
"search": "#Backyard",
},
],
}
],
],
)
async def test_unsupported_create_event(
hass: HomeAssistant,
mock_calendars_yaml: Mock,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
mock_insert_event: Callable[..., None],
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test create event service call is unsupported for virtual calendars."""
await async_setup_component(hass, "homeassistant", {})
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
start_datetime = datetime.datetime.now(tz=zoneinfo.ZoneInfo("America/Regina"))
delta = datetime.timedelta(days=3, hours=3)
end_datetime = start_datetime + delta
entity_id = "calendar.backyard_light"
with pytest.raises(
ServiceNotSupported,
match=f"Entity {entity_id} does not support action google.create_event",
):
await hass.services.async_call(
DOMAIN,
"create_event",
{
# **data,
"start_date_time": start_datetime.isoformat(),
"end_date_time": end_datetime.isoformat(),
"summary": TEST_EVENT_SUMMARY,
"description": TEST_EVENT_DESCRIPTION,
},
target={"entity_id": entity_id},
blocking=True,
)
async def test_add_event_failure(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
mock_insert_event: Callable[..., None],
add_event_call_service: Callable[[dict[str, Any]], Awaitable[None]],
) -> None:
"""Test service calls with incorrect fields."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
mock_insert_event(
calendar_id=CALENDAR_ID,
exc=ClientError(),
)
with pytest.raises(HomeAssistantError):
await add_event_call_service(
{"start_date": "2022-05-01", "end_date": "2022-05-02"}
)
async def test_add_event_location(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_insert_event: Callable[..., None],
mock_events_list: ApiResult,
aioclient_mock: AiohttpClientMocker,
add_event_call_service: Callable[[dict[str, Any]], Awaitable[None]],
) -> None:
"""Test service call that sets a location field."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
now = utcnow()
today = now.date()
end_date = today + datetime.timedelta(days=2)
aioclient_mock.clear_requests()
mock_insert_event(
calendar_id=CALENDAR_ID,
)
await add_event_call_service(
{
"start_date": today.isoformat(),
"end_date": end_date.isoformat(),
"location": TEST_EVENT_LOCATION,
},
)
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[0][2] == {
"summary": TEST_EVENT_SUMMARY,
"description": TEST_EVENT_DESCRIPTION,
"location": TEST_EVENT_LOCATION,
"start": {"date": today.isoformat()},
"end": {"date": end_date.isoformat()},
}
@pytest.mark.parametrize(
"config_entry_token_expiry",
[
(datetime.datetime.max.replace(tzinfo=UTC).timestamp() + 1),
(utcnow().replace(tzinfo=None).timestamp()),
],
ids=["max_timestamp", "timestamp_naive"],
)
async def test_invalid_token_expiry_in_config_entry(
hass: HomeAssistant,
component_setup: ComponentSetup,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Exercise case in issue #69623 with invalid token expiration persisted."""
# The token is refreshed and new expiration values are returned
expires_in = 86400
expires_at = time.time() + expires_in
aioclient_mock.post(
"https://oauth2.googleapis.com/token",
json={
"refresh_token": "some-refresh-token",
"access_token": "some-updated-token",
"expires_at": expires_at,
"expires_in": expires_in,
},
)
assert await component_setup()
# Verify token expiration values are updated
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is ConfigEntryState.LOADED
assert entries[0].data["token"]["access_token"] == "some-updated-token"
assert entries[0].data["token"]["expires_in"] == expires_in
@pytest.mark.parametrize("config_entry_token_expiry", [EXPIRED_TOKEN_TIMESTAMP])
async def test_expired_token_refresh_internal_error(
hass: HomeAssistant,
component_setup: ComponentSetup,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Generic errors on reauth are treated as a retryable setup error."""
aioclient_mock.post(
"https://oauth2.googleapis.com/token",
status=http.HTTPStatus.INTERNAL_SERVER_ERROR,
)
await component_setup()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is ConfigEntryState.SETUP_RETRY
@pytest.mark.parametrize(
"config_entry_token_expiry",
[EXPIRED_TOKEN_TIMESTAMP],
)
async def test_expired_token_requires_reauth(
hass: HomeAssistant,
component_setup: ComponentSetup,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test case where reauth is required for token that cannot be refreshed."""
aioclient_mock.post(
"https://oauth2.googleapis.com/token",
status=http.HTTPStatus.BAD_REQUEST,
)
await component_setup()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
@pytest.mark.parametrize(
("calendars_config", "expect_write_calls"),
[
(
[
{
"cal_id": "ignored",
"entities": {"device_id": "existing", "name": "existing"},
}
],
True,
),
([], False),
],
ids=["has_yaml", "no_yaml"],
)
async def test_calendar_yaml_update(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_yaml: Mock,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
calendars_config: dict[str, Any],
expect_write_calls: bool,
) -> None:
"""Test updating the yaml file with a new calendar."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
mock_calendars_yaml().read.assert_called()
assert mock_calendars_yaml().write.called is expect_write_calls
state = hass.states.get(TEST_API_ENTITY)
assert state
assert state.name == TEST_API_ENTITY_NAME
assert state.state == STATE_OFF
# No yaml config loaded that overwrites the entity name
assert not hass.states.get(TEST_YAML_ENTITY)
async def test_update_will_reload(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
config_entry: MockConfigEntry,
) -> None:
"""Test updating config entry options will trigger a reload."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
await component_setup()
assert config_entry.state is ConfigEntryState.LOADED
assert config_entry.options == {} # read_write is default
with patch(
"homeassistant.config_entries.ConfigEntries.async_reload",
return_value=None,
) as mock_reload:
# No-op does not reload
hass.config_entries.async_update_entry(
config_entry, options={CONF_CALENDAR_ACCESS: "read_write"}
)
await hass.async_block_till_done()
mock_reload.assert_not_called()
# Data change does not trigger reload
hass.config_entries.async_update_entry(
config_entry,
data={
**config_entry.data,
"example": "field",
},
)
await hass.async_block_till_done()
mock_reload.assert_not_called()
# Reload when options changed
hass.config_entries.async_update_entry(
config_entry, options={CONF_CALENDAR_ACCESS: "read_only"}
)
await hass.async_block_till_done()
mock_reload.assert_called_once()
@pytest.mark.parametrize("config_entry_unique_id", [None])
async def test_assign_unique_id(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
mock_calendar_get: Callable[..., None],
config_entry: MockConfigEntry,
) -> None:
"""Test an existing config is updated to have unique id if it does not exist."""
assert config_entry.state is ConfigEntryState.NOT_LOADED
assert config_entry.unique_id is None
mock_calendar_get(
"primary",
{"id": EMAIL_ADDRESS, "summary": "Personal", "accessRole": "owner"},
)
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
assert config_entry.state is ConfigEntryState.LOADED
assert config_entry.unique_id == EMAIL_ADDRESS
@pytest.mark.parametrize(
("config_entry_unique_id", "request_status", "config_entry_status"),
[
(None, http.HTTPStatus.BAD_REQUEST, ConfigEntryState.SETUP_RETRY),
(
None,
http.HTTPStatus.UNAUTHORIZED,
ConfigEntryState.SETUP_ERROR,
),
],
)
async def test_assign_unique_id_failure(
hass: HomeAssistant,
component_setup: ComponentSetup,
mock_calendars_list: ApiResult,
test_api_calendar: dict[str, Any],
config_entry: MockConfigEntry,
mock_events_list: ApiResult,
mock_calendar_get: Callable[..., None],
request_status: http.HTTPStatus,
config_entry_status: ConfigEntryState,
) -> None:
"""Test lookup failures during unique id assignment are handled gracefully."""
assert config_entry.state is ConfigEntryState.NOT_LOADED
assert config_entry.unique_id is None
mock_calendar_get(
"primary",
{},
status=request_status,
)
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
await component_setup()
assert config_entry.state is config_entry_status
assert config_entry.unique_id is None
async def test_remove_entry(
hass: HomeAssistant,
mock_calendars_list: ApiResult,
component_setup: ComponentSetup,
test_api_calendar: dict[str, Any],
mock_events_list: ApiResult,
) -> None:
"""Test load and remove of a ConfigEntry."""
mock_calendars_list({"items": [test_api_calendar]})
mock_events_list({})
assert await component_setup()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
entry = entries[0]
assert entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_remove(entry.entry_id)
assert entry.state is ConfigEntryState.NOT_LOADED