diff --git a/homeassistant/components/data_grand_lyon/__init__.py b/homeassistant/components/data_grand_lyon/__init__.py index fe02dd13708e..085eb7e3c13a 100644 --- a/homeassistant/components/data_grand_lyon/__init__.py +++ b/homeassistant/components/data_grand_lyon/__init__.py @@ -10,6 +10,7 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from .coordinator import ( + DataGrandLyonAlertsCoordinator, DataGrandLyonConfigEntry, DataGrandLyonData, DataGrandLyonParkAndRideCoordinator, @@ -17,7 +18,7 @@ from .coordinator import ( DataGrandLyonVelovCoordinator, ) -PLATFORMS: list[Platform] = [Platform.BINARY_SENSOR, Platform.SENSOR] +PLATFORMS: list[Platform] = [Platform.BINARY_SENSOR, Platform.CALENDAR, Platform.SENSOR] async def async_setup_entry( @@ -34,11 +35,13 @@ async def async_setup_entry( tcl_coordinator = DataGrandLyonTclCoordinator(hass, entry, client) velov_coordinator = DataGrandLyonVelovCoordinator(hass, entry, client) park_and_ride_coordinator = DataGrandLyonParkAndRideCoordinator(hass, entry, client) + alerts_coordinator = DataGrandLyonAlertsCoordinator(hass, entry, client) coordinators: list[DataUpdateCoordinator] = [ tcl_coordinator, velov_coordinator, park_and_ride_coordinator, + alerts_coordinator, ] await asyncio.gather(*(c.async_config_entry_first_refresh() for c in coordinators)) @@ -46,6 +49,7 @@ async def async_setup_entry( tcl_coordinator=tcl_coordinator, velov_coordinator=velov_coordinator, park_and_ride_coordinator=park_and_ride_coordinator, + alerts_coordinator=alerts_coordinator, ) entry.async_on_unload(entry.add_update_listener(async_update_entry)) diff --git a/homeassistant/components/data_grand_lyon/calendar.py b/homeassistant/components/data_grand_lyon/calendar.py new file mode 100644 index 000000000000..bba2615ac314 --- /dev/null +++ b/homeassistant/components/data_grand_lyon/calendar.py @@ -0,0 +1,102 @@ +"""Calendar platform for the Data Grand Lyon integration.""" + +from datetime import datetime +from typing import override + +from data_grand_lyon_ha import TclAlert, filter_tcl_active_alerts + +from homeassistant.components.calendar import ( + CalendarEntity, + CalendarEntityDescription, + CalendarEvent, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.util import dt as dt_util + +from .const import SUBENTRY_TYPE_LINE, TZ_PARIS +from .coordinator import DataGrandLyonConfigEntry +from .entity import DataGrandLyonLineEntity + +PARALLEL_UPDATES = 0 + +ALERTS_DESCRIPTION = CalendarEntityDescription( + key="alerts", + translation_key="alerts", +) + + +def _tcl_now() -> datetime: + """Return the current time as a naive Paris datetime, as TCL publishes them.""" + return dt_util.utcnow().astimezone(TZ_PARIS).replace(tzinfo=None) + + +def _calendar_event(alert: TclAlert) -> CalendarEvent: + """Convert a TCL alert into a calendar event.""" + # TCL's `n` field is a positional index that changes on every fetch, so no + # stable event uid can be derived from the data. + return CalendarEvent( + start=alert.debut.replace(tzinfo=TZ_PARIS), + end=alert.fin.replace(tzinfo=TZ_PARIS), + summary=alert.titre.strip(), + description=f"{alert.message}\n\nCause: {alert.cause}\nType: {alert.type}", + ) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: DataGrandLyonConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up Data Grand Lyon calendar entities.""" + alerts_coordinator = entry.runtime_data.alerts_coordinator + + for subentry in entry.get_subentries_of_type(SUBENTRY_TYPE_LINE): + async_add_entities( + [ + DataGrandLyonLineCalendar( + alerts_coordinator, subentry, ALERTS_DESCRIPTION + ) + ], + config_subentry_id=subentry.subentry_id, + ) + + +class DataGrandLyonLineCalendar(DataGrandLyonLineEntity, CalendarEntity): + """Calendar of TCL traffic alerts for a line.""" + + @property + @override + def event(self) -> CalendarEvent | None: + """Return the most severe alert in progress, or the soonest upcoming one.""" + now = _tcl_now() + alerts = filter_tcl_active_alerts(self.coordinator.data[self._subentry_id], now) + if not alerts: + return None + # HA derives the on/off state and its next transition from this event. + if started := [alert for alert in alerts if alert.debut <= now]: + return _calendar_event( + min(started, key=lambda alert: (alert.niveau_severite, alert.debut)) + ) + return _calendar_event( + min(alerts, key=lambda alert: (alert.debut, alert.niveau_severite)) + ) + + @override + async def async_get_events( + self, hass: HomeAssistant, start_date: datetime, end_date: datetime + ) -> list[CalendarEvent]: + """Return the line's alerts overlapping the requested window.""" + # Compare in UTC: Paris-aware datetimes sharing a tzinfo compare naively, + # ignoring fold across the DST rollback. + window_start = dt_util.as_utc(start_date) + window_end = dt_util.as_utc(end_date) + return [ + _calendar_event(alert) + for alert in sorted( + self.coordinator.data[self._subentry_id], + key=lambda alert: dt_util.as_utc(alert.debut.replace(tzinfo=TZ_PARIS)), + ) + if dt_util.as_utc(alert.debut.replace(tzinfo=TZ_PARIS)) < window_end + and dt_util.as_utc(alert.fin.replace(tzinfo=TZ_PARIS)) > window_start + ] diff --git a/homeassistant/components/data_grand_lyon/config_flow.py b/homeassistant/components/data_grand_lyon/config_flow.py index b409ea3ea973..c32f10e5dae2 100644 --- a/homeassistant/components/data_grand_lyon/config_flow.py +++ b/homeassistant/components/data_grand_lyon/config_flow.py @@ -7,6 +7,7 @@ from typing import Any, override from aiohttp import ClientError, ClientResponseError from data_grand_lyon_ha import ( DataGrandLyonClient, + TclLinePictogram, TclParkAndRide, TclStop, VelovStation, @@ -37,6 +38,7 @@ from .const import ( CONF_STATION_ID, CONF_STOP_ID, DOMAIN, + SUBENTRY_TYPE_LINE, SUBENTRY_TYPE_PARK_AND_RIDE, SUBENTRY_TYPE_STOP, SUBENTRY_TYPE_VELOV_STATION, @@ -75,6 +77,7 @@ class DataGrandLyonConfigFlow(ConfigFlow, domain=DOMAIN): SUBENTRY_TYPE_STOP: StopSubentryFlowHandler, SUBENTRY_TYPE_VELOV_STATION: VelovStationSubentryFlowHandler, SUBENTRY_TYPE_PARK_AND_RIDE: ParkAndRideSubentryFlowHandler, + SUBENTRY_TYPE_LINE: LineSubentryFlowHandler, } @override @@ -479,3 +482,77 @@ class ParkAndRideSubentryFlowHandler(ConfigSubentryFlow): def _park_and_ride_label(park: TclParkAndRide) -> str: return f"{park.nom} - {park.id}" + + +class LineSubentryFlowHandler(ConfigSubentryFlow): + """Handle a subentry flow for adding a TCL line.""" + + def __init__(self) -> None: + """Initialize the flow.""" + self._lines: list[TclLinePictogram] = [] + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> SubentryFlowResult: + """Pick a line from the list fetched from the API, or enter one manually.""" + if not self._lines: + if error := await self._async_load_lines(): + return self.async_abort(reason=error) + + errors: dict[str, str] = {} + if user_input is not None: + line_code = user_input[CONF_LINE].strip() + if not line_code: + errors[CONF_LINE] = "invalid_line" + else: + return self._create_line(line_code) + + schema = probatio.Schema( + { + probatio.Required(CONF_LINE): SelectSelector( + SelectSelectorConfig( + options=sorted({line.code_ligne for line in self._lines}), + mode=SelectSelectorMode.DROPDOWN, + sort=False, + custom_value=True, + ) + ) + } + ) + return self.async_show_form(step_id="user", data_schema=schema, errors=errors) + + async def _async_load_lines(self) -> str | None: + """Fetch TCL lines from the API, returning an error key on failure.""" + entry = self._get_entry() + session = async_get_clientsession(self.hass) + client = DataGrandLyonClient( + session=session, + username=entry.data[CONF_USERNAME], + password=entry.data[CONF_PASSWORD], + ) + try: + self._lines = await client.get_tcl_line_pictograms() + except ClientResponseError as err: + if err.status in (401, 403): + return "invalid_auth" + return "cannot_connect" + except ClientError, TimeoutError: + return "cannot_connect" + except Exception: + _LOGGER.exception("Unexpected error fetching Data Grand Lyon TCL lines") + return "unknown" + return None + + def _create_line(self, line: str) -> SubentryFlowResult: + """Create the line subentry, aborting on duplicate.""" + entry = self._get_entry() + unique_id = f"line_{line}" + for subentry in entry.subentries.values(): + if subentry.unique_id == unique_id: + return self.async_abort(reason="already_configured") + + return self.async_create_entry( + title=f"Line {line}", + data={CONF_LINE: line}, + unique_id=unique_id, + ) diff --git a/homeassistant/components/data_grand_lyon/const.py b/homeassistant/components/data_grand_lyon/const.py index e77e2fcda134..8465bfde9854 100644 --- a/homeassistant/components/data_grand_lyon/const.py +++ b/homeassistant/components/data_grand_lyon/const.py @@ -1,13 +1,18 @@ """Constants for the Data Grand Lyon integration.""" import logging +from zoneinfo import ZoneInfo DOMAIN = "data_grand_lyon" LOGGER = logging.getLogger(__package__) +# TCL publishes naive datetimes in local Paris time. +TZ_PARIS = ZoneInfo("Europe/Paris") + SUBENTRY_TYPE_STOP = "stop" SUBENTRY_TYPE_VELOV_STATION = "velov_station" SUBENTRY_TYPE_PARK_AND_RIDE = "park_and_ride" +SUBENTRY_TYPE_LINE = "line" CONF_LINE = "line" CONF_STOP_ID = "stop_id" diff --git a/homeassistant/components/data_grand_lyon/coordinator.py b/homeassistant/components/data_grand_lyon/coordinator.py index 46514a916a50..d4d49b1a5bbd 100644 --- a/homeassistant/components/data_grand_lyon/coordinator.py +++ b/homeassistant/components/data_grand_lyon/coordinator.py @@ -7,9 +7,11 @@ from typing import override from aiohttp import ClientError, ClientResponseError from data_grand_lyon_ha import ( DataGrandLyonClient, + TclAlert, TclParkAndRide, TclPassage, VelovStation, + filter_tcl_alerts_by_line, filter_tcl_passages_by_lines_stops, find_tcl_park_and_ride_by_id, find_velov_stations_by_ids, @@ -28,6 +30,7 @@ from .const import ( CONF_STOP_ID, DOMAIN, LOGGER, + SUBENTRY_TYPE_LINE, SUBENTRY_TYPE_PARK_AND_RIDE, SUBENTRY_TYPE_STOP, SUBENTRY_TYPE_VELOV_STATION, @@ -41,6 +44,7 @@ class DataGrandLyonData: tcl_coordinator: DataGrandLyonTclCoordinator velov_coordinator: DataGrandLyonVelovCoordinator park_and_ride_coordinator: DataGrandLyonParkAndRideCoordinator + alerts_coordinator: DataGrandLyonAlertsCoordinator type DataGrandLyonConfigEntry = ConfigEntry[DataGrandLyonData] @@ -238,3 +242,60 @@ class DataGrandLyonParkAndRideCoordinator( subentry.subentry_id, ) return parks + + +class DataGrandLyonAlertsCoordinator(DataUpdateCoordinator[dict[str, list[TclAlert]]]): + """Coordinator for TCL traffic alerts.""" + + config_entry: DataGrandLyonConfigEntry + + def __init__( + self, + hass: HomeAssistant, + entry: DataGrandLyonConfigEntry, + client: DataGrandLyonClient, + ) -> None: + """Initialize the coordinator.""" + self.client = client + super().__init__( + hass, + LOGGER, + config_entry=entry, + name=f"{DOMAIN}_alerts", + update_interval=timedelta(minutes=5), + ) + + @override + async def _async_update_data(self) -> dict[str, list[TclAlert]]: + """Fetch alerts for all monitored lines.""" + line_subentries = list( + self.config_entry.get_subentries_of_type(SUBENTRY_TYPE_LINE) + ) + if not line_subentries: + return {} + + try: + all_alerts = await self.client.get_tcl_alerts() + except ClientResponseError as err: + if err.status in (401, 403): + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, + translation_key="auth_failed", + ) from err + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="update_failed_alerts", + ) from err + except (ClientError, TimeoutError) as err: + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="update_failed_alerts", + ) from err + + # A line with no alert must stay available, so its key is always set. + return { + subentry.subentry_id: filter_tcl_alerts_by_line( + all_alerts, subentry.data[CONF_LINE] + ) + for subentry in line_subentries + } diff --git a/homeassistant/components/data_grand_lyon/diagnostics.py b/homeassistant/components/data_grand_lyon/diagnostics.py index 3907b40a6b75..44a953e83672 100644 --- a/homeassistant/components/data_grand_lyon/diagnostics.py +++ b/homeassistant/components/data_grand_lyon/diagnostics.py @@ -31,5 +31,9 @@ async def async_get_config_entry_diagnostics( subentry_id: asdict(park) for subentry_id, park in entry.runtime_data.park_and_ride_coordinator.data.items() }, + "alerts": { + subentry_id: [asdict(alert) for alert in alerts] + for subentry_id, alerts in entry.runtime_data.alerts_coordinator.data.items() + }, }, } diff --git a/homeassistant/components/data_grand_lyon/entity.py b/homeassistant/components/data_grand_lyon/entity.py index 3f47311dc697..479c0ad9f2ac 100644 --- a/homeassistant/components/data_grand_lyon/entity.py +++ b/homeassistant/components/data_grand_lyon/entity.py @@ -12,6 +12,7 @@ from homeassistant.helpers.update_coordinator import ( from .const import DOMAIN from .coordinator import ( + DataGrandLyonAlertsCoordinator, DataGrandLyonParkAndRideCoordinator, DataGrandLyonTclCoordinator, DataGrandLyonVelovCoordinator, @@ -94,3 +95,16 @@ class DataGrandLyonParkAndRideEntity( ) -> None: """Initialize the park-and-ride entity.""" super().__init__(coordinator, subentry, description, "TCL", "Park & Ride") + + +class DataGrandLyonLineEntity(DataGrandLyonEntity[DataGrandLyonAlertsCoordinator]): + """Base entity for Data Grand Lyon TCL lines.""" + + def __init__( + self, + coordinator: DataGrandLyonAlertsCoordinator, + subentry: ConfigSubentry, + description: EntityDescription, + ) -> None: + """Initialize the line entity.""" + super().__init__(coordinator, subentry, description, "TCL", "Line") diff --git a/homeassistant/components/data_grand_lyon/icons.json b/homeassistant/components/data_grand_lyon/icons.json index b8351d150a72..f5d3e0ba114c 100644 --- a/homeassistant/components/data_grand_lyon/icons.json +++ b/homeassistant/components/data_grand_lyon/icons.json @@ -8,6 +8,11 @@ } } }, + "calendar": { + "alerts": { + "default": "mdi:transit-detour" + } + }, "sensor": { "accessible_spaces": { "default": "mdi:wheelchair-accessibility" diff --git a/homeassistant/components/data_grand_lyon/sensor.py b/homeassistant/components/data_grand_lyon/sensor.py index 4e72d87c0733..2ea655817d04 100644 --- a/homeassistant/components/data_grand_lyon/sensor.py +++ b/homeassistant/components/data_grand_lyon/sensor.py @@ -4,7 +4,6 @@ from collections.abc import Callable from dataclasses import dataclass from datetime import datetime from typing import override -from zoneinfo import ZoneInfo from data_grand_lyon_ha import TclParkAndRide, TclPassage, TclPassageType, VelovStation @@ -22,6 +21,7 @@ from .const import ( SUBENTRY_TYPE_PARK_AND_RIDE, SUBENTRY_TYPE_STOP, SUBENTRY_TYPE_VELOV_STATION, + TZ_PARIS, ) from .coordinator import DataGrandLyonConfigEntry from .entity import ( @@ -32,8 +32,6 @@ from .entity import ( PARALLEL_UPDATES = 0 -_TZ_PARIS = ZoneInfo("Europe/Paris") - _DEPARTURE_TYPE_OPTIONS = [t.name.lower() for t in TclPassageType] @@ -41,7 +39,7 @@ def _departure_time(departure: TclPassage) -> datetime: """Return the departure time, localized to Europe/Paris if naive.""" dt = departure.heure_passage if dt.tzinfo is None: - return dt.replace(tzinfo=_TZ_PARIS) + return dt.replace(tzinfo=TZ_PARIS) return dt diff --git a/homeassistant/components/data_grand_lyon/strings.json b/homeassistant/components/data_grand_lyon/strings.json index f3d48da4dd52..3baf95b86789 100644 --- a/homeassistant/components/data_grand_lyon/strings.json +++ b/homeassistant/components/data_grand_lyon/strings.json @@ -42,6 +42,31 @@ } }, "config_subentries": { + "line": { + "abort": { + "already_configured": "[%key:common::config_flow::abort::already_configured_service%]", + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", + "unknown": "[%key:common::config_flow::error::unknown%]" + }, + "entry_type": "Transit line", + "error": { + "invalid_line": "Line code cannot be empty." + }, + "initiate_flow": { + "user": "Add transit line" + }, + "step": { + "user": { + "data": { + "line": "[%key:component::data_grand_lyon::config_subentries::stop::step::pick_line::data::line%]" + }, + "data_description": { + "line": "Pick a line, or enter a line code directly." + } + } + } + }, "park_and_ride": { "abort": { "already_configured": "[%key:common::config_flow::abort::already_configured_service%]", @@ -126,6 +151,11 @@ "name": "Station open" } }, + "calendar": { + "alerts": { + "name": "Alerts" + } + }, "sensor": { "accessible_spaces": { "name": "Accessible parking spaces", @@ -212,6 +242,9 @@ "auth_failed": { "message": "Authentication failed for Data Grand Lyon." }, + "update_failed_alerts": { + "message": "Error fetching TCL traffic alerts from Data Grand Lyon." + }, "update_failed_park_and_ride": { "message": "Error fetching park & ride availability from Data Grand Lyon." }, diff --git a/tests/components/data_grand_lyon/conftest.py b/tests/components/data_grand_lyon/conftest.py index 5df5a3401955..8e9f7cfe0850 100644 --- a/tests/components/data_grand_lyon/conftest.py +++ b/tests/components/data_grand_lyon/conftest.py @@ -5,6 +5,10 @@ from datetime import datetime from unittest.mock import AsyncMock, patch from data_grand_lyon_ha import ( + TclAlert, + TclAlertSeverityType, + TclAlertType, + TclLinePictogram, TclParkAndRide, TclPassage, TclPassageType, @@ -23,6 +27,7 @@ from homeassistant.components.data_grand_lyon.const import ( CONF_STATION_ID, CONF_STOP_ID, DOMAIN, + SUBENTRY_TYPE_LINE, SUBENTRY_TYPE_PARK_AND_RIDE, SUBENTRY_TYPE_STOP, SUBENTRY_TYPE_VELOV_STATION, @@ -170,6 +175,104 @@ MOCK_PARK_AND_RIDES = [ ] +MOCK_TCL_ALERTS = [ + TclAlert( + type=TclAlertType.DISRUPTION, + cause="travaux", + debut=datetime(2026, 4, 1, 7, 0), + fin=datetime(2026, 4, 30, 17, 30), + mode="Bus", + ligne_com="C3", + ligne_cli="C3", + titre="Déviée dir. Cordeliers", + message="Les arrêts de Gare St-Paul à Cordeliers ne sont plus desservis.", + last_update_fme=datetime(2026, 4, 10, 9, 15), + n=1, + type_severite=TclAlertSeverityType.SIGNIFICANT_DELAYS, + niveau_severite=20, + type_objet="line", + liste_objet="C3", + ), + TclAlert( + type=TclAlertType.INFORMATION, + cause="événement", + debut=datetime(2026, 3, 1, 4, 30), + fin=datetime(2026, 3, 2, 1, 30), + mode="Bus", + ligne_com="C3", + ligne_cli="C3", + titre="Fête de la Musique", + message="Horaires prolongés.", + last_update_fme=datetime(2026, 3, 1, 9, 15), + n=2, + type_severite=TclAlertSeverityType.OTHER_EFFECT, + niveau_severite=30, + type_objet="line", + liste_objet="C3", + ), + TclAlert( + type=TclAlertType.DISRUPTION, + cause="panne bus", + debut=datetime(2026, 4, 10, 8, 0), + fin=datetime(2026, 4, 10, 20, 0), + mode="Bus", + ligne_com="27", + ligne_cli="27", + titre="Terminus Cordeliers", + message="La ligne est déviée.", + last_update_fme=datetime(2026, 4, 10, 9, 15), + n=3, + type_severite=TclAlertSeverityType.SIGNIFICANT_DELAYS, + niveau_severite=20, + type_objet="line", + liste_objet="27", + ), +] + + +MOCK_TCL_LINE_PICTOGRAMS = [ + TclLinePictogram( + code_ligne="C3", + picto_mode="mode_bus.svg", + picto_ligne="C3_ligne.svg", + picto_complet="C3.svg", + ), + TclLinePictogram( + code_ligne="A", + picto_mode="mode_metro.svg", + picto_ligne="A_ligne.svg", + picto_complet="A.svg", + ), +] + + +@pytest.fixture +def mock_line_subentries() -> list[ConfigSubentryData]: + """Mock TCL line subentries.""" + return [ + ConfigSubentryData( + data={CONF_LINE: "C3"}, + subentry_id="line_1", + subentry_type=SUBENTRY_TYPE_LINE, + title="Line C3", + unique_id="line_C3", + ) + ] + + +@pytest.fixture +def mock_line_config_entry( + mock_line_subentries: list[ConfigSubentryData], +) -> MockConfigEntry: + """Create a mock config entry with TCL line subentries.""" + return MockConfigEntry( + domain=DOMAIN, + title="Data Grand Lyon", + data={CONF_USERNAME: "user", CONF_PASSWORD: "pass"}, + subentries_data=mock_line_subentries, + ) + + @pytest.fixture def mock_setup_entry() -> Generator[AsyncMock]: """Override async_setup_entry.""" @@ -278,4 +381,6 @@ def mock_tcl_client() -> Generator[AsyncMock]: client.get_tcl_stops.return_value = MOCK_TCL_STOPS client.get_velov_stations.return_value = MOCK_VELOV_STATIONS client.get_tcl_park_and_rides.return_value = MOCK_PARK_AND_RIDES + client.get_tcl_alerts.return_value = MOCK_TCL_ALERTS + client.get_tcl_line_pictograms.return_value = MOCK_TCL_LINE_PICTOGRAMS yield client diff --git a/tests/components/data_grand_lyon/snapshots/test_calendar.ambr b/tests/components/data_grand_lyon/snapshots/test_calendar.ambr new file mode 100644 index 000000000000..d5b26d608c63 --- /dev/null +++ b/tests/components/data_grand_lyon/snapshots/test_calendar.ambr @@ -0,0 +1,62 @@ +# serializer version: 1 +# name: test_all_entities[calendar.line_c3_alerts-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'calendar', + 'entity_category': None, + 'entity_id': 'calendar.line_c3_alerts', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Alerts', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Alerts', + 'platform': 'data_grand_lyon', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'alerts', + 'unique_id': 'line_C3-alerts', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[calendar.line_c3_alerts-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : False, + : ''' + Les arrêts de Gare St-Paul à Cordeliers ne sont plus desservis. + + Cause: travaux + Type: Perturbation + ''', + : '2026-04-30 08:30:00', + : 'Line C3 Alerts', + : '', + : 'Déviée dir. Cordeliers', + : '2026-03-31 22:00:00', + }), + 'context': , + 'entity_id': 'calendar.line_c3_alerts', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- diff --git a/tests/components/data_grand_lyon/snapshots/test_diagnostics.ambr b/tests/components/data_grand_lyon/snapshots/test_diagnostics.ambr index 83f752ab32be..7096d57c6a23 100644 --- a/tests/components/data_grand_lyon/snapshots/test_diagnostics.ambr +++ b/tests/components/data_grand_lyon/snapshots/test_diagnostics.ambr @@ -1,5 +1,139 @@ # serializer version: 1 -# name: test_config_entry_diagnostics +# name: test_config_entry_diagnostics[line] + dict({ + 'config_entry': dict({ + 'data': dict({ + 'password': '**REDACTED**', + 'username': '**REDACTED**', + }), + 'disabled_by': None, + 'discovery_keys': dict({ + }), + 'domain': 'data_grand_lyon', + 'minor_version': 1, + 'options': dict({ + }), + 'pref_disable_new_entities': False, + 'pref_disable_polling': False, + 'source': 'user', + 'subentries': list([ + dict({ + 'data': dict({ + 'line': 'C3', + }), + 'subentry_type': 'line', + 'title': 'Line C3', + 'unique_id': 'line_C3', + }), + ]), + 'title': 'Data Grand Lyon', + 'unique_id': None, + 'version': 1, + }), + 'coordinator_data': dict({ + 'alerts': dict({ + 'line_1': list([ + dict({ + 'cause': 'travaux', + 'debut': '2026-04-01T07:00:00', + 'fin': '2026-04-30T17:30:00', + 'last_update_fme': '2026-04-10T09:15:00', + 'ligne_cli': 'C3', + 'ligne_com': 'C3', + 'liste_objet': 'C3', + 'message': 'Les arrêts de Gare St-Paul à Cordeliers ne sont plus desservis.', + 'mode': 'Bus', + 'n': 1, + 'niveau_severite': 20, + 'titre': 'Déviée dir. Cordeliers', + 'type': 'Perturbation', + 'type_objet': 'line', + 'type_severite': 'SIGNIFICANT_DELAYS', + }), + dict({ + 'cause': 'événement', + 'debut': '2026-03-01T04:30:00', + 'fin': '2026-03-02T01:30:00', + 'last_update_fme': '2026-03-01T09:15:00', + 'ligne_cli': 'C3', + 'ligne_com': 'C3', + 'liste_objet': 'C3', + 'message': 'Horaires prolongés.', + 'mode': 'Bus', + 'n': 2, + 'niveau_severite': 30, + 'titre': 'Fête de la Musique', + 'type': 'Information', + 'type_objet': 'line', + 'type_severite': 'OTHER_EFFECT', + }), + ]), + }), + 'park_and_rides': dict({ + }), + 'stops': dict({ + }), + 'velov_stations': dict({ + }), + }), + }) +# --- +# name: test_config_entry_diagnostics[park_and_ride] + dict({ + 'config_entry': dict({ + 'data': dict({ + 'password': '**REDACTED**', + 'username': '**REDACTED**', + }), + 'disabled_by': None, + 'discovery_keys': dict({ + }), + 'domain': 'data_grand_lyon', + 'minor_version': 1, + 'options': dict({ + }), + 'pref_disable_new_entities': False, + 'pref_disable_polling': False, + 'source': 'user', + 'subentries': list([ + dict({ + 'data': dict({ + 'park_id': 'P+R Gorge de Loup', + }), + 'subentry_type': 'park_and_ride', + 'title': 'Gorge de Loup', + 'unique_id': 'park_and_ride_P+R Gorge de Loup', + }), + ]), + 'title': 'Data Grand Lyon', + 'unique_id': None, + 'version': 1, + }), + 'coordinator_data': dict({ + 'alerts': dict({ + }), + 'park_and_rides': dict({ + 'park_1': dict({ + 'capacite': 240, + 'gid': 10, + 'horaires': '24h/24', + 'id': 'P+R Gorge de Loup', + 'last_update': '2026-04-10T14:00:00', + 'last_update_fme': '2026-04-10T13:55:00', + 'nb_tot_place_dispo': 42, + 'nom': 'Gorge de Loup', + 'p_surv': True, + 'place_handi': 6, + }), + }), + 'stops': dict({ + }), + 'velov_stations': dict({ + }), + }), + }) +# --- +# name: test_config_entry_diagnostics[stops] dict({ 'config_entry': dict({ 'data': dict({ @@ -32,6 +166,8 @@ 'version': 1, }), 'coordinator_data': dict({ + 'alerts': dict({ + }), 'park_and_rides': dict({ }), 'stops': dict({ @@ -63,60 +199,7 @@ }), }) # --- -# name: test_config_entry_diagnostics_with_park_and_ride - dict({ - 'config_entry': dict({ - 'data': dict({ - 'password': '**REDACTED**', - 'username': '**REDACTED**', - }), - 'disabled_by': None, - 'discovery_keys': dict({ - }), - 'domain': 'data_grand_lyon', - 'minor_version': 1, - 'options': dict({ - }), - 'pref_disable_new_entities': False, - 'pref_disable_polling': False, - 'source': 'user', - 'subentries': list([ - dict({ - 'data': dict({ - 'park_id': 'P+R Gorge de Loup', - }), - 'subentry_type': 'park_and_ride', - 'title': 'Gorge de Loup', - 'unique_id': 'park_and_ride_P+R Gorge de Loup', - }), - ]), - 'title': 'Data Grand Lyon', - 'unique_id': None, - 'version': 1, - }), - 'coordinator_data': dict({ - 'park_and_rides': dict({ - 'park_1': dict({ - 'capacite': 240, - 'gid': 10, - 'horaires': '24h/24', - 'id': 'P+R Gorge de Loup', - 'last_update': '2026-04-10T14:00:00', - 'last_update_fme': '2026-04-10T13:55:00', - 'nb_tot_place_dispo': 42, - 'nom': 'Gorge de Loup', - 'p_surv': True, - 'place_handi': 6, - }), - }), - 'stops': dict({ - }), - 'velov_stations': dict({ - }), - }), - }) -# --- -# name: test_config_entry_diagnostics_with_velov +# name: test_config_entry_diagnostics[velov] dict({ 'config_entry': dict({ 'data': dict({ @@ -148,6 +231,8 @@ 'version': 1, }), 'coordinator_data': dict({ + 'alerts': dict({ + }), 'park_and_rides': dict({ }), 'stops': dict({ diff --git a/tests/components/data_grand_lyon/test_calendar.py b/tests/components/data_grand_lyon/test_calendar.py new file mode 100644 index 000000000000..2ef0df4e7910 --- /dev/null +++ b/tests/components/data_grand_lyon/test_calendar.py @@ -0,0 +1,356 @@ +"""Tests for the Data Grand Lyon calendar platform.""" + +from dataclasses import replace +from datetime import UTC, datetime +from unittest.mock import AsyncMock, patch + +from data_grand_lyon_ha import TclAlert +from freezegun.api import FrozenDateTimeFactory +import pytest +from pytest_homeassistant.common import MockConfigEntry, snapshot_platform +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.data_grand_lyon.const import TZ_PARIS +from homeassistant.const import STATE_OFF, STATE_ON, Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from .conftest import MOCK_TCL_ALERTS + +ENTITY_ID = "calendar.line_c3_alerts" + + +@pytest.fixture(autouse=True) +def frozen_time(freezer: FrozenDateTimeFactory) -> None: + """Freeze time inside the in-progress alert of MOCK_TCL_ALERTS.""" + freezer.move_to(datetime(2026, 4, 10, 14, 0, tzinfo=TZ_PARIS)) + + +@pytest.mark.usefixtures("mock_tcl_client") +async def test_all_entities( + hass: HomeAssistant, + snapshot: SnapshotAssertion, + entity_registry: er.EntityRegistry, + mock_line_config_entry: MockConfigEntry, +) -> None: + """Test all calendar entities (state, attributes, registry).""" + with patch( + "homeassistant.components.data_grand_lyon.PLATFORMS", [Platform.CALENDAR] + ): + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + await snapshot_platform( + hass, entity_registry, snapshot, mock_line_config_entry.entry_id + ) + + +@pytest.mark.usefixtures("mock_tcl_client") +async def test_state_reflects_alert_in_progress( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, +) -> None: + """Test the calendar is on while an alert is in progress.""" + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(ENTITY_ID) + assert state is not None + assert state.state == STATE_ON + assert state.attributes["message"] == "Déviée dir. Cordeliers" + assert "Cause: travaux" in state.attributes["description"] + + +async def test_state_off_without_alert( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, + mock_tcl_client: AsyncMock, +) -> None: + """Test a line with no alert is available and off.""" + mock_tcl_client.get_tcl_alerts.return_value = [] + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(ENTITY_ID) + assert state is not None + assert state.state == STATE_OFF + + +async def test_state_off_when_every_alert_has_ended( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, + mock_tcl_client: AsyncMock, +) -> None: + """Test a line whose only alert has already ended is off.""" + mock_tcl_client.get_tcl_alerts.return_value = [MOCK_TCL_ALERTS[1]] + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(ENTITY_ID) + assert state is not None + assert state.state == STATE_OFF + + +async def test_state_on_picks_most_severe_started_alert( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, + mock_tcl_client: AsyncMock, +) -> None: + """Test the most severe running alert wins over one that started earlier.""" + mock_tcl_client.get_tcl_alerts.return_value = [ + replace( + MOCK_TCL_ALERTS[0], + debut=datetime(2026, 4, 10, 8, 0), + titre="Earlier minor alert", + niveau_severite=30, + ), + replace( + MOCK_TCL_ALERTS[0], + debut=datetime(2026, 4, 10, 9, 0), + titre="Later severe alert", + niveau_severite=10, + ), + ] + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(ENTITY_ID) + assert state is not None + assert state.state == STATE_ON + assert state.attributes["message"] == "Later severe alert" + + +async def test_state_on_prefers_started_alert_over_later_one( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, + mock_tcl_client: AsyncMock, +) -> None: + """Test a running alert wins over a more severe one starting later today.""" + ongoing = replace( + MOCK_TCL_ALERTS[0], + debut=datetime(2026, 4, 10, 8, 0), + fin=datetime(2026, 4, 10, 20, 0), + titre="Ongoing information", + niveau_severite=30, + ) + later_today = replace( + MOCK_TCL_ALERTS[0], + debut=datetime(2026, 4, 10, 18, 0), + fin=datetime(2026, 4, 10, 22, 0), + titre="Later disruption", + ) + mock_tcl_client.get_tcl_alerts.return_value = [ongoing, later_today] + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(ENTITY_ID) + assert state is not None + assert state.state == STATE_ON + assert state.attributes["message"] == "Ongoing information" + + +@pytest.mark.parametrize( + ("alerts", "expected_message"), + [ + pytest.param( + [ + replace( + MOCK_TCL_ALERTS[0], + debut=datetime(2026, 4, 10, 18, 0), + fin=datetime(2026, 4, 10, 22, 0), + titre="Upcoming disruption", + ) + ], + "Upcoming disruption", + id="single_upcoming_alert", + ), + pytest.param( + [ + replace( + MOCK_TCL_ALERTS[0], + debut=datetime(2026, 4, 10, 16, 0), + fin=datetime(2026, 4, 10, 20, 0), + titre="Soonest information", + niveau_severite=30, + ), + replace( + MOCK_TCL_ALERTS[0], + debut=datetime(2026, 4, 10, 18, 0), + fin=datetime(2026, 4, 10, 22, 0), + titre="Later severe disruption", + ), + ], + "Soonest information", + id="soonest_upcoming_alert_wins_over_severity", + ), + pytest.param( + [ + replace( + MOCK_TCL_ALERTS[0], + debut=datetime(2026, 4, 10, 18, 0), + titre="Minor alert", + niveau_severite=30, + ), + replace( + MOCK_TCL_ALERTS[0], + debut=datetime(2026, 4, 10, 18, 0), + titre="Severe alert", + niveau_severite=10, + ), + ], + "Severe alert", + id="same_start_most_severe_wins", + ), + ], +) +async def test_state_off_with_upcoming_alert_picks_soonest( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, + mock_tcl_client: AsyncMock, + alerts: list[TclAlert], + expected_message: str, +) -> None: + """Test the event is the soonest upcoming alert, not the most severe one.""" + mock_tcl_client.get_tcl_alerts.return_value = alerts + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(ENTITY_ID) + assert state is not None + assert state.state == STATE_OFF + assert state.attributes["message"] == expected_message + + +@pytest.mark.parametrize( + ("start", "end", "expected"), + [ + pytest.param( + datetime(2026, 4, 9, 0, 0, tzinfo=TZ_PARIS), + datetime(2026, 4, 11, 0, 0, tzinfo=TZ_PARIS), + ["Déviée dir. Cordeliers"], + id="inside_ongoing_alert", + ), + pytest.param( + datetime(2026, 2, 1, 0, 0, tzinfo=TZ_PARIS), + datetime(2026, 5, 1, 0, 0, tzinfo=TZ_PARIS), + # Chronological, although the API returns the April alert first. + ["Fête de la Musique", "Déviée dir. Cordeliers"], + id="spans_both_alerts", + ), + pytest.param( + # MOCK_TCL_ALERTS[2] spans this window exactly, on line 27. + datetime(2026, 4, 10, 8, 0, tzinfo=TZ_PARIS), + datetime(2026, 4, 10, 20, 0, tzinfo=TZ_PARIS), + ["Déviée dir. Cordeliers"], + id="excludes_other_lines", + ), + pytest.param( + datetime(2026, 1, 1, 0, 0, tzinfo=TZ_PARIS), + datetime(2026, 1, 2, 0, 0, tzinfo=TZ_PARIS), + [], + id="before_every_alert", + ), + pytest.param( + # MOCK_TCL_ALERTS[0]'s own `fin` as the window start. + datetime(2026, 4, 30, 17, 30, tzinfo=TZ_PARIS), + datetime(2026, 5, 1, 0, 0, tzinfo=TZ_PARIS), + [], + id="ends_exactly_at_window_start", + ), + pytest.param( + datetime(2026, 3, 15, 0, 0, tzinfo=TZ_PARIS), + # MOCK_TCL_ALERTS[0]'s own `debut` as the window end. + datetime(2026, 4, 1, 7, 0, tzinfo=TZ_PARIS), + [], + id="starts_exactly_at_window_end", + ), + ], +) +@pytest.mark.usefixtures("mock_tcl_client") +async def test_get_events( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, + start: datetime, + end: datetime, + expected: list[str], +) -> None: + """Test the requested window selects the overlapping alerts.""" + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + response = await hass.services.async_call( + "calendar", + "get_events", + { + "entity_id": ENTITY_ID, + "start_date_time": start.isoformat(), + "end_date_time": end.isoformat(), + }, + blocking=True, + return_response=True, + ) + summaries = [event["summary"] for event in response[ENTITY_ID]["events"]] + assert summaries == expected + + +@pytest.mark.parametrize( + ("debut", "fin", "start", "end", "expected"), + [ + pytest.param( + datetime(2026, 10, 25, 2, 50), + datetime(2026, 10, 25, 3, 0), + datetime(2026, 10, 25, 0, 45, tzinfo=UTC), + datetime(2026, 10, 25, 1, 15, tzinfo=UTC), + ["DST alert"], + id="overlapping_alert_included", + ), + pytest.param( + datetime(2026, 10, 25, 2, 20), + datetime(2026, 10, 25, 2, 40), + datetime(2026, 10, 25, 1, 15, tzinfo=UTC), + datetime(2026, 10, 25, 2, 0, tzinfo=UTC), + [], + id="earlier_alert_excluded", + ), + ], +) +async def test_get_events_across_dst_rollback( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, + mock_tcl_client: AsyncMock, + debut: datetime, + fin: datetime, + start: datetime, + end: datetime, + expected: list[str], +) -> None: + """Test the window is compared in absolute time when Paris falls back an hour.""" + await hass.config.async_set_time_zone("Europe/Paris") + mock_tcl_client.get_tcl_alerts.return_value = [ + replace(MOCK_TCL_ALERTS[0], debut=debut, fin=fin, titre="DST alert") + ] + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + response = await hass.services.async_call( + "calendar", + "get_events", + { + "entity_id": ENTITY_ID, + "start_date_time": start.isoformat(), + "end_date_time": end.isoformat(), + }, + blocking=True, + return_response=True, + ) + summaries = [event["summary"] for event in response[ENTITY_ID]["events"]] + assert summaries == expected diff --git a/tests/components/data_grand_lyon/test_config_flow.py b/tests/components/data_grand_lyon/test_config_flow.py index e5e5dbe7afc1..5d18d7c432d3 100644 --- a/tests/components/data_grand_lyon/test_config_flow.py +++ b/tests/components/data_grand_lyon/test_config_flow.py @@ -1,6 +1,6 @@ """Test the Data Grand Lyon config flow.""" -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, Mock from aiohttp import ClientConnectionError, ClientResponseError import pytest @@ -13,6 +13,7 @@ from homeassistant.components.data_grand_lyon.const import ( CONF_STATION_ID, CONF_STOP_ID, DOMAIN, + SUBENTRY_TYPE_LINE, SUBENTRY_TYPE_PARK_AND_RIDE, SUBENTRY_TYPE_STOP, SUBENTRY_TYPE_VELOV_STATION, @@ -720,3 +721,138 @@ async def test_park_and_ride_subentry_picker_load_errors( assert result["type"] is FlowResultType.ABORT assert result["reason"] == reason + + +@pytest.mark.parametrize( + ("submitted", "expected"), + [ + pytest.param("C3", "C3", id="from_list"), + pytest.param(" C3 ", "C3", id="padded"), + pytest.param("ZI3", "ZI3", id="custom_value"), + ], +) +@pytest.mark.usefixtures("mock_tcl_client") +async def test_line_subentry_flow( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + submitted: str, + expected: str, +) -> None: + """Test adding a TCL line subentry, including codes absent from the CSV.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + result = await hass.config_entries.subentries.async_init( + (mock_config_entry.entry_id, SUBENTRY_TYPE_LINE), + context={"source": config_entries.SOURCE_USER}, + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {CONF_LINE: submitted} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == f"Line {expected}" + assert result["data"] == {CONF_LINE: expected} + assert result["unique_id"] == f"line_{expected}" + + +@pytest.mark.parametrize( + "line_code", + [ + pytest.param("", id="empty"), + pytest.param(" ", id="whitespace_only"), + ], +) +@pytest.mark.usefixtures("mock_tcl_client") +async def test_line_subentry_flow_rejects_empty_line_code( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + line_code: str, +) -> None: + """Test an empty (or whitespace-only) line code shows an error, then recovers.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + result = await hass.config_entries.subentries.async_init( + (mock_config_entry.entry_id, SUBENTRY_TYPE_LINE), + context={"source": config_entries.SOURCE_USER}, + ) + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {CONF_LINE: line_code} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {CONF_LINE: "invalid_line"} + + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {CONF_LINE: "C3"} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"] == {CONF_LINE: "C3"} + + +@pytest.mark.usefixtures("mock_tcl_client") +async def test_line_subentry_flow_already_configured( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, +) -> None: + """Test adding a line that is already configured aborts.""" + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + result = await hass.config_entries.subentries.async_init( + (mock_line_config_entry.entry_id, SUBENTRY_TYPE_LINE), + context={"source": config_entries.SOURCE_USER}, + ) + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {CONF_LINE: "C3"} + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +@pytest.mark.parametrize( + ("side_effect", "reason"), + [ + pytest.param( + ClientResponseError(Mock(), Mock(), status=401), + "invalid_auth", + id="invalid_auth", + ), + pytest.param( + ClientResponseError(Mock(), Mock(), status=500), + "cannot_connect", + id="cannot_connect_http", + ), + pytest.param( + ClientConnectionError("boom"), "cannot_connect", id="cannot_connect_client" + ), + pytest.param(TimeoutError, "cannot_connect", id="cannot_connect_timeout"), + pytest.param(Exception("boom"), "unknown", id="unknown"), + ], +) +async def test_line_subentry_flow_errors( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_tcl_client: AsyncMock, + side_effect: Exception, + reason: str, +) -> None: + """Test the line subentry flow aborts when the line list cannot be fetched.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + mock_tcl_client.get_tcl_line_pictograms.side_effect = side_effect + + result = await hass.config_entries.subentries.async_init( + (mock_config_entry.entry_id, SUBENTRY_TYPE_LINE), + context={"source": config_entries.SOURCE_USER}, + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == reason diff --git a/tests/components/data_grand_lyon/test_diagnostics.py b/tests/components/data_grand_lyon/test_diagnostics.py index aeb6dfb4f9de..28c040c4f1fd 100644 --- a/tests/components/data_grand_lyon/test_diagnostics.py +++ b/tests/components/data_grand_lyon/test_diagnostics.py @@ -1,7 +1,6 @@ """Tests for the Data Grand Lyon diagnostics.""" -from unittest.mock import AsyncMock - +import pytest from pytest_homeassistant.common import MockConfigEntry from pytest_homeassistant.components.diagnostics import get_diagnostics_for_config_entry from pytest_homeassistant.typing import ClientSessionGenerator @@ -11,52 +10,30 @@ from syrupy.filters import props from homeassistant.core import HomeAssistant +@pytest.mark.parametrize( + "entry_fixture", + [ + pytest.param("mock_config_entry", id="stops"), + pytest.param("mock_velov_config_entry", id="velov"), + pytest.param("mock_park_and_ride_config_entry", id="park_and_ride"), + pytest.param("mock_line_config_entry", id="line"), + ], +) +@pytest.mark.usefixtures("mock_tcl_client") async def test_config_entry_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, - mock_config_entry: MockConfigEntry, - mock_tcl_client: AsyncMock, + request: pytest.FixtureRequest, + entry_fixture: str, snapshot: SnapshotAssertion, ) -> None: - """Test config entry diagnostics.""" - mock_config_entry.add_to_hass(hass) - await hass.config_entries.async_setup(mock_config_entry.entry_id) + """Test config entry diagnostics for every kind of subentry.""" + config_entry: MockConfigEntry = request.getfixturevalue(entry_fixture) + + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert await get_diagnostics_for_config_entry( - hass, hass_client, mock_config_entry - ) == snapshot(exclude=props("created_at", "modified_at", "entry_id", "subentry_id")) - - -async def test_config_entry_diagnostics_with_velov( - hass: HomeAssistant, - hass_client: ClientSessionGenerator, - mock_velov_config_entry: MockConfigEntry, - mock_tcl_client: AsyncMock, - snapshot: SnapshotAssertion, -) -> None: - """Test config entry diagnostics with Vélo'v data.""" - mock_velov_config_entry.add_to_hass(hass) - await hass.config_entries.async_setup(mock_velov_config_entry.entry_id) - await hass.async_block_till_done() - - assert await get_diagnostics_for_config_entry( - hass, hass_client, mock_velov_config_entry - ) == snapshot(exclude=props("created_at", "modified_at", "entry_id", "subentry_id")) - - -async def test_config_entry_diagnostics_with_park_and_ride( - hass: HomeAssistant, - hass_client: ClientSessionGenerator, - mock_park_and_ride_config_entry: MockConfigEntry, - mock_tcl_client: AsyncMock, - snapshot: SnapshotAssertion, -) -> None: - """Test config entry diagnostics with park-and-ride data.""" - mock_park_and_ride_config_entry.add_to_hass(hass) - await hass.config_entries.async_setup(mock_park_and_ride_config_entry.entry_id) - await hass.async_block_till_done() - - assert await get_diagnostics_for_config_entry( - hass, hass_client, mock_park_and_ride_config_entry + hass, hass_client, config_entry ) == snapshot(exclude=props("created_at", "modified_at", "entry_id", "subentry_id")) diff --git a/tests/components/data_grand_lyon/test_init.py b/tests/components/data_grand_lyon/test_init.py index 37b757788841..52b098053459 100644 --- a/tests/components/data_grand_lyon/test_init.py +++ b/tests/components/data_grand_lyon/test_init.py @@ -3,7 +3,8 @@ from types import MappingProxyType from unittest.mock import AsyncMock -from aiohttp import ClientResponseError +from aiohttp import ClientConnectionError, ClientResponseError +import pytest from pytest_homeassistant.common import MockConfigEntry from homeassistant.components.data_grand_lyon.const import ( @@ -46,21 +47,54 @@ async def test_subentry_added_reloads( assert hass.states.get("sensor.t1_stop_200_next_departure_1") is not None +@pytest.mark.parametrize( + ("entry_fixture", "client_method"), + [ + pytest.param("mock_config_entry", "get_tcl_passages", id="passages"), + pytest.param("mock_line_config_entry", "get_tcl_alerts", id="alerts"), + ], +) async def test_setup_triggers_reauth_on_auth_failure( hass: HomeAssistant, - mock_config_entry: MockConfigEntry, mock_tcl_client: AsyncMock, + request: pytest.FixtureRequest, + entry_fixture: str, + client_method: str, ) -> None: """Test that an auth failure during setup triggers a reauth flow.""" - mock_tcl_client.get_tcl_passages.side_effect = ClientResponseError( + getattr(mock_tcl_client, client_method).side_effect = ClientResponseError( None, None, status=401 ) + config_entry: MockConfigEntry = request.getfixturevalue(entry_fixture) - mock_config_entry.add_to_hass(hass) - await hass.config_entries.async_setup(mock_config_entry.entry_id) + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() - assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR + assert config_entry.state is ConfigEntryState.SETUP_ERROR flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN) assert any(flow["context"].get("source") == SOURCE_REAUTH for flow in flows) + + +@pytest.mark.parametrize( + "side_effect", + [ + pytest.param(ClientResponseError(None, None, status=500), id="http_error"), + pytest.param(ClientConnectionError("boom"), id="connection_error"), + pytest.param(TimeoutError, id="timeout"), + ], +) +async def test_alerts_fetch_failure_retries_setup( + hass: HomeAssistant, + mock_line_config_entry: MockConfigEntry, + mock_tcl_client: AsyncMock, + side_effect: Exception, +) -> None: + """Test a failed alerts fetch leaves the entry retrying, not errored.""" + mock_tcl_client.get_tcl_alerts.side_effect = side_effect + mock_line_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_line_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_line_config_entry.state is ConfigEntryState.SETUP_RETRY