mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Migrate nmbs to config entry runtime data (#177453)
Co-authored-by: Erik <erik@montnemery.com>
This commit is contained in:
@@ -1,42 +1,77 @@
|
||||
"""The NMBS component."""
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from pyrail import IRail, PyRailError
|
||||
from pyrail.models import StationDetails
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.exceptions import ConfigEntryError, ConfigEntryNotReady
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers.singleton import singleton
|
||||
|
||||
from .const import DOMAIN, NMBS_STATION_DATA
|
||||
from .const import (
|
||||
CONF_STATION_FROM,
|
||||
CONF_STATION_TO,
|
||||
DOMAIN,
|
||||
NMBS_STATION_DATA,
|
||||
find_station,
|
||||
)
|
||||
|
||||
PLATFORMS = [Platform.SENSOR]
|
||||
|
||||
|
||||
@dataclass
|
||||
class NMBSData:
|
||||
"""Data for an NMBS config entry."""
|
||||
|
||||
station_from: StationDetails
|
||||
station_to: StationDetails
|
||||
|
||||
|
||||
type NMBSConfigEntry = ConfigEntry[NMBSData]
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.empty_config_schema(DOMAIN)
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
"""Set up NMBS from a config entry."""
|
||||
@singleton(NMBS_STATION_DATA, async_=True)
|
||||
async def _async_get_stations(hass: HomeAssistant) -> list[StationDetails]:
|
||||
"""Fetch the station list, which is shared by all entries."""
|
||||
api_client = IRail(session=async_get_clientsession(hass))
|
||||
message = "Unable to fetch the NMBS station list from the iRail API"
|
||||
try:
|
||||
station_response = await api_client.get_stations()
|
||||
except PyRailError as err:
|
||||
raise ConfigEntryNotReady(message) from err
|
||||
if station_response is None or not station_response.stations:
|
||||
raise ConfigEntryNotReady(message)
|
||||
return station_response.stations
|
||||
|
||||
# The station list is shared by all entries, so fetch and cache it only
|
||||
# once. Raise ConfigEntryNotReady if the API is unavailable so setup is
|
||||
# retried instead of failing permanently.
|
||||
if not hass.data.get(NMBS_STATION_DATA):
|
||||
api_client = IRail(session=async_get_clientsession(hass))
|
||||
message = "Unable to fetch the NMBS station list from the iRail API"
|
||||
try:
|
||||
station_response = await api_client.get_stations()
|
||||
except PyRailError as err:
|
||||
raise ConfigEntryNotReady(message) from err
|
||||
if station_response is None:
|
||||
raise ConfigEntryNotReady(message)
|
||||
hass.data[NMBS_STATION_DATA] = station_response.stations
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: NMBSConfigEntry) -> None:
|
||||
"""Set up NMBS from a config entry."""
|
||||
stations = await _async_get_stations(hass)
|
||||
station_from = find_station(stations, entry.data[CONF_STATION_FROM])
|
||||
station_to = find_station(stations, entry.data[CONF_STATION_TO])
|
||||
if station_from is None or station_to is None:
|
||||
raise ConfigEntryError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="station_not_found",
|
||||
translation_placeholders={
|
||||
"station": entry.data[CONF_STATION_FROM]
|
||||
if station_from is None
|
||||
else entry.data[CONF_STATION_TO]
|
||||
},
|
||||
)
|
||||
entry.runtime_data = NMBSData(station_from=station_from, station_to=station_to)
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: NMBSConfigEntry) -> None:
|
||||
"""Unload a config entry."""
|
||||
await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS)
|
||||
|
||||
@@ -5,7 +5,6 @@ from typing import Final
|
||||
from pyrail.models import StationDetails
|
||||
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.util.hass_dict import HassKey
|
||||
|
||||
DOMAIN: Final = "nmbs"
|
||||
@@ -19,9 +18,11 @@ CONF_STATION_LIVE = "station_live"
|
||||
CONF_EXCLUDE_VIAS = "exclude_vias"
|
||||
|
||||
|
||||
def find_station(hass: HomeAssistant, station_name: str):
|
||||
def find_station(
|
||||
stations: list[StationDetails], station_name: str
|
||||
) -> StationDetails | None:
|
||||
"""Find given station_id in the station list."""
|
||||
return next(
|
||||
(s for s in hass.data[NMBS_STATION_DATA] if station_name in s.id),
|
||||
(s for s in stations if station_name in s.id),
|
||||
None,
|
||||
)
|
||||
|
||||
@@ -8,7 +8,6 @@ from pyrail import IRail, PyRailError
|
||||
from pyrail.models import ConnectionDetails, LiveboardDeparture, StationDetails
|
||||
|
||||
from homeassistant.components.sensor import SensorEntity
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import (
|
||||
CONF_NAME,
|
||||
CONF_SHOW_ON_MAP,
|
||||
@@ -20,6 +19,7 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import NMBSConfigEntry
|
||||
from .const import ( # noqa: F401
|
||||
CONF_EXCLUDE_VIAS,
|
||||
CONF_STATION_FROM,
|
||||
@@ -27,7 +27,6 @@ from .const import ( # noqa: F401
|
||||
CONF_STATION_TO,
|
||||
DOMAIN,
|
||||
PLATFORMS,
|
||||
find_station,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -59,7 +58,7 @@ def get_ride_duration(departure_time: datetime, arrival_time: datetime, delay=0)
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
config_entry: ConfigEntry,
|
||||
config_entry: NMBSConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up NMBS sensor entities based on a config entry."""
|
||||
@@ -69,8 +68,8 @@ async def async_setup_entry(
|
||||
show_on_map = config_entry.data.get(CONF_SHOW_ON_MAP, False)
|
||||
excl_vias = config_entry.data.get(CONF_EXCLUDE_VIAS, False)
|
||||
|
||||
station_from = find_station(hass, config_entry.data[CONF_STATION_FROM])
|
||||
station_to = find_station(hass, config_entry.data[CONF_STATION_TO])
|
||||
station_from = config_entry.runtime_data.station_from
|
||||
station_to = config_entry.runtime_data.station_to
|
||||
|
||||
# setup the connection from station to station
|
||||
# setup a disabled liveboard for both from and to station
|
||||
|
||||
@@ -25,5 +25,10 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"exceptions": {
|
||||
"station_not_found": {
|
||||
"message": "Station {station} is not available in the NMBS station list"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,3 +60,17 @@ def mock_config_entry() -> MockConfigEntry:
|
||||
},
|
||||
unique_id="BE.NMBS.008812005_BE.NMBS.008814001",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_second_config_entry() -> MockConfigEntry:
|
||||
"""Mock a config entry for the reverse trip of mock_config_entry."""
|
||||
return MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title="Train from Brussel-Zuid/Bruxelles-Midi to Brussel-Noord/Bruxelles-Nord",
|
||||
data={
|
||||
CONF_STATION_FROM: "BE.NMBS.008814001",
|
||||
CONF_STATION_TO: "BE.NMBS.008812005",
|
||||
},
|
||||
unique_id="BE.NMBS.008814001_BE.NMBS.008812005",
|
||||
)
|
||||
|
||||
@@ -1,12 +1,21 @@
|
||||
"""Test the NMBS integration setup."""
|
||||
|
||||
import asyncio
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
from pyrail import ApiUnavailableError
|
||||
from pyrail.models import StationsApiResponse
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
|
||||
from homeassistant.components.nmbs.const import (
|
||||
CONF_STATION_FROM,
|
||||
CONF_STATION_TO,
|
||||
DOMAIN,
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
|
||||
async def test_setup_entry(
|
||||
@@ -23,33 +32,151 @@ async def test_setup_entry(
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
|
||||
|
||||
async def test_setup_entry_api_unavailable(
|
||||
@pytest.mark.parametrize(
|
||||
("side_effect", "return_value"),
|
||||
[
|
||||
pytest.param(
|
||||
ApiUnavailableError("The iRail API is unavailable"),
|
||||
None,
|
||||
id="api_unavailable",
|
||||
),
|
||||
pytest.param(None, None, id="station_list_not_modified"),
|
||||
pytest.param(
|
||||
None,
|
||||
StationsApiResponse.from_dict(
|
||||
{"version": "1.3", "timestamp": "0", "station": []}
|
||||
),
|
||||
id="empty_station_list",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_setup_retry_after_failed_fetch(
|
||||
hass: HomeAssistant,
|
||||
mock_nmbs_client: AsyncMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
side_effect: Exception | None,
|
||||
return_value: StationsApiResponse | None,
|
||||
) -> None:
|
||||
"""Test the entry is retried when the station list cannot be fetched."""
|
||||
mock_nmbs_client.get_stations.side_effect = ApiUnavailableError(
|
||||
"The iRail API is unavailable"
|
||||
"""Test the entry is retried and refetches the station list after a failure."""
|
||||
stations_response = mock_nmbs_client.get_stations.return_value
|
||||
mock_nmbs_client.get_stations.side_effect = side_effect
|
||||
mock_nmbs_client.get_stations.return_value = return_value
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
mock_nmbs_client.get_stations.side_effect = None
|
||||
mock_nmbs_client.get_stations.return_value = stations_response
|
||||
await hass.config_entries.async_reload(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
assert mock_nmbs_client.get_stations.call_count == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("station_from", "station_to", "missing_station"),
|
||||
[
|
||||
pytest.param(
|
||||
"BE.NMBS.000000000",
|
||||
"BE.NMBS.008814001",
|
||||
"BE.NMBS.000000000",
|
||||
id="departure",
|
||||
),
|
||||
pytest.param(
|
||||
"BE.NMBS.008812005", "BE.NMBS.000000000", "BE.NMBS.000000000", id="arrival"
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("mock_nmbs_client")
|
||||
async def test_setup_entry_unknown_station(
|
||||
hass: HomeAssistant,
|
||||
station_from: str,
|
||||
station_to: str,
|
||||
missing_station: str,
|
||||
) -> None:
|
||||
"""Test the entry errors when a configured station is not in the station list."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
title="Train from an unknown station",
|
||||
data={CONF_STATION_FROM: station_from, CONF_STATION_TO: station_to},
|
||||
unique_id=f"{station_from}_{station_to}",
|
||||
)
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
assert not await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
assert entry.state is ConfigEntryState.SETUP_ERROR
|
||||
assert entry.error_reason_translation_key == "station_not_found"
|
||||
assert entry.error_reason_translation_placeholders == {"station": missing_station}
|
||||
|
||||
|
||||
async def test_setup_entry_station_list_not_modified(
|
||||
async def test_second_entry_reuses_station_list(
|
||||
hass: HomeAssistant,
|
||||
mock_nmbs_client: AsyncMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_second_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test the entry is retried when the station list is not modified."""
|
||||
mock_nmbs_client.get_stations.return_value = None
|
||||
"""Test that a second entry reuses the station list of a loaded entry."""
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
|
||||
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
mock_second_config_entry.add_to_hass(hass)
|
||||
assert await hass.config_entries.async_setup(mock_second_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_second_config_entry.state is ConfigEntryState.LOADED
|
||||
# The two entries use the same stations swapped, so resolving both against
|
||||
# the same shared list yields the very same station objects.
|
||||
assert (
|
||||
mock_second_config_entry.runtime_data.station_from
|
||||
is mock_config_entry.runtime_data.station_to
|
||||
)
|
||||
mock_nmbs_client.get_stations.assert_called_once()
|
||||
|
||||
|
||||
async def test_concurrent_setup_shares_station_fetch(
|
||||
hass: HomeAssistant,
|
||||
mock_nmbs_client: AsyncMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_second_config_entry: MockConfigEntry,
|
||||
) -> None:
|
||||
"""Test that entries set up concurrently share one in-flight station fetch."""
|
||||
stations_response = mock_nmbs_client.get_stations.return_value
|
||||
release_fetch = asyncio.Event()
|
||||
|
||||
async def _blocked_get_stations() -> StationsApiResponse:
|
||||
await release_fetch.wait()
|
||||
return stations_response
|
||||
|
||||
mock_nmbs_client.get_stations.side_effect = _blocked_get_stations
|
||||
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
mock_second_config_entry.add_to_hass(hass)
|
||||
|
||||
setup_task = hass.async_create_task(async_setup_component(hass, DOMAIN, {}))
|
||||
# Release the fetch only after both entry setups are underway, so the
|
||||
# second entry sees the first entry's fetch in flight rather than a
|
||||
# completed task.
|
||||
async with asyncio.timeout(10):
|
||||
while (
|
||||
mock_config_entry.state is not ConfigEntryState.SETUP_IN_PROGRESS
|
||||
or mock_second_config_entry.state is not ConfigEntryState.SETUP_IN_PROGRESS
|
||||
):
|
||||
await asyncio.sleep(0)
|
||||
release_fetch.set()
|
||||
|
||||
assert await setup_task
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
assert mock_second_config_entry.state is ConfigEntryState.LOADED
|
||||
assert (
|
||||
mock_second_config_entry.runtime_data.station_from
|
||||
is mock_config_entry.runtime_data.station_to
|
||||
)
|
||||
mock_nmbs_client.get_stations.assert_called_once()
|
||||
|
||||
Reference in New Issue
Block a user