Use runtime_data in geonetnz_quakes (#144319)

This commit is contained in:
epenet 2025-05-06 11:58:25 +02:00 committed by GitHub
parent 9479874bb4
commit 62877c2c58
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 25 additions and 40 deletions

View File

@ -31,7 +31,6 @@ from .const import (
DEFAULT_RADIUS, DEFAULT_RADIUS,
DEFAULT_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL,
DOMAIN, DOMAIN,
FEED,
PLATFORMS, PLATFORMS,
) )
@ -59,6 +58,8 @@ CONFIG_SCHEMA = vol.Schema(
extra=vol.ALLOW_EXTRA, extra=vol.ALLOW_EXTRA,
) )
type GeonetnzQuakesConfigEntry = ConfigEntry[GeonetnzQuakesFeedEntityManager]
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the GeoNet NZ Quakes component.""" """Set up the GeoNet NZ Quakes component."""
@ -89,11 +90,10 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
return True return True
async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: async def async_setup_entry(
hass: HomeAssistant, config_entry: GeonetnzQuakesConfigEntry
) -> bool:
"""Set up the GeoNet NZ Quakes component as config entry.""" """Set up the GeoNet NZ Quakes component as config entry."""
hass.data.setdefault(DOMAIN, {})
feeds = hass.data[DOMAIN].setdefault(FEED, {})
radius = config_entry.data[CONF_RADIUS] radius = config_entry.data[CONF_RADIUS]
if hass.config.units is US_CUSTOMARY_SYSTEM: if hass.config.units is US_CUSTOMARY_SYSTEM:
radius = DistanceConverter.convert( radius = DistanceConverter.convert(
@ -101,16 +101,17 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b
) )
# Create feed entity manager for all platforms. # Create feed entity manager for all platforms.
manager = GeonetnzQuakesFeedEntityManager(hass, config_entry, radius) manager = GeonetnzQuakesFeedEntityManager(hass, config_entry, radius)
feeds[config_entry.entry_id] = manager config_entry.runtime_data = manager
_LOGGER.debug("Feed entity manager added for %s", config_entry.entry_id) _LOGGER.debug("Feed entity manager added for %s", config_entry.entry_id)
await manager.async_init() await manager.async_init()
return True return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(
hass: HomeAssistant, entry: GeonetnzQuakesConfigEntry
) -> bool:
"""Unload an GeoNet NZ Quakes component config entry.""" """Unload an GeoNet NZ Quakes component config entry."""
manager = hass.data[DOMAIN][FEED].pop(entry.entry_id) await entry.runtime_data.async_stop()
await manager.async_stop()
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@ -11,8 +11,6 @@ PLATFORMS = [Platform.GEO_LOCATION, Platform.SENSOR]
CONF_MINIMUM_MAGNITUDE = "minimum_magnitude" CONF_MINIMUM_MAGNITUDE = "minimum_magnitude"
CONF_MMI = "mmi" CONF_MMI = "mmi"
FEED = "feed"
DEFAULT_FILTER_TIME_INTERVAL = timedelta(days=7) DEFAULT_FILTER_TIME_INTERVAL = timedelta(days=7)
DEFAULT_MINIMUM_MAGNITUDE = 0.0 DEFAULT_MINIMUM_MAGNITUDE = 0.0
DEFAULT_MMI = 3 DEFAULT_MMI = 3

View File

@ -5,28 +5,23 @@ from __future__ import annotations
from typing import Any from typing import Any
from homeassistant.components.diagnostics import async_redact_data from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from . import GeonetnzQuakesFeedEntityManager from . import GeonetnzQuakesConfigEntry
from .const import DOMAIN, FEED
TO_REDACT = {CONF_LATITUDE, CONF_LONGITUDE} TO_REDACT = {CONF_LATITUDE, CONF_LONGITUDE}
async def async_get_config_entry_diagnostics( async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry hass: HomeAssistant, config_entry: GeonetnzQuakesConfigEntry
) -> dict[str, Any]: ) -> dict[str, Any]:
"""Return diagnostics for a config entry.""" """Return diagnostics for a config entry."""
data: dict[str, Any] = { data: dict[str, Any] = {
"info": async_redact_data(config_entry.data, TO_REDACT), "info": async_redact_data(config_entry.data, TO_REDACT),
} }
manager: GeonetnzQuakesFeedEntityManager = hass.data[DOMAIN][FEED][ status_info = config_entry.runtime_data.status_info()
config_entry.entry_id
]
status_info = manager.status_info()
if status_info: if status_info:
data["service"] = { data["service"] = {
"status": status_info.status, "status": status_info.status,

View File

@ -9,7 +9,6 @@ from typing import Any
from aio_geojson_geonetnz_quakes.feed_entry import GeonetnzQuakesFeedEntry from aio_geojson_geonetnz_quakes.feed_entry import GeonetnzQuakesFeedEntry
from homeassistant.components.geo_location import GeolocationEvent from homeassistant.components.geo_location import GeolocationEvent
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_TIME, UnitOfLength from homeassistant.const import ATTR_TIME, UnitOfLength
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registry as er from homeassistant.helpers import entity_registry as er
@ -18,8 +17,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.unit_conversion import DistanceConverter from homeassistant.util.unit_conversion import DistanceConverter
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
from . import GeonetnzQuakesFeedEntityManager from . import GeonetnzQuakesConfigEntry, GeonetnzQuakesFeedEntityManager
from .const import DOMAIN, FEED
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -39,11 +37,11 @@ SOURCE = "geonetnz_quakes"
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
entry: ConfigEntry, entry: GeonetnzQuakesConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback, async_add_entities: AddConfigEntryEntitiesCallback,
) -> None: ) -> None:
"""Set up the GeoNet NZ Quakes Feed platform.""" """Set up the GeoNet NZ Quakes Feed platform."""
manager: GeonetnzQuakesFeedEntityManager = hass.data[DOMAIN][FEED][entry.entry_id] manager = entry.runtime_data
@callback @callback
def async_add_geolocation( def async_add_geolocation(

View File

@ -5,13 +5,12 @@ from __future__ import annotations
import logging import logging
from homeassistant.components.sensor import SensorEntity from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util import dt as dt_util from homeassistant.util import dt as dt_util
from .const import DOMAIN, FEED from . import GeonetnzQuakesConfigEntry
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -32,11 +31,11 @@ PARALLEL_UPDATES = 0
async def async_setup_entry( async def async_setup_entry(
hass: HomeAssistant, hass: HomeAssistant,
entry: ConfigEntry, entry: GeonetnzQuakesConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback, async_add_entities: AddConfigEntryEntitiesCallback,
) -> None: ) -> None:
"""Set up the GeoNet NZ Quakes Feed platform.""" """Set up the GeoNet NZ Quakes Feed platform."""
manager = hass.data[DOMAIN][FEED][entry.entry_id] manager = entry.runtime_data
sensor = GeonetnzQuakesSensor(entry.entry_id, entry.unique_id, entry.title, manager) sensor = GeonetnzQuakesSensor(entry.entry_id, entry.unique_id, entry.title, manager)
async_add_entities([sensor]) async_add_entities([sensor])
_LOGGER.debug("Sensor setup done") _LOGGER.debug("Sensor setup done")

View File

@ -5,9 +5,8 @@ from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory from freezegun.api import FrozenDateTimeFactory
from homeassistant.components import geonetnz_quakes
from homeassistant.components.geo_location import ATTR_SOURCE from homeassistant.components.geo_location import ATTR_SOURCE
from homeassistant.components.geonetnz_quakes import DEFAULT_SCAN_INTERVAL, DOMAIN, FEED from homeassistant.components.geonetnz_quakes import DEFAULT_SCAN_INTERVAL, DOMAIN
from homeassistant.components.geonetnz_quakes.geo_location import ( from homeassistant.components.geonetnz_quakes.geo_location import (
ATTR_DEPTH, ATTR_DEPTH,
ATTR_EXTERNAL_ID, ATTR_EXTERNAL_ID,
@ -38,7 +37,7 @@ from . import _generate_mock_feed_entry
from tests.common import async_fire_time_changed from tests.common import async_fire_time_changed
CONFIG = {geonetnz_quakes.DOMAIN: {CONF_RADIUS: 200}} CONFIG = {DOMAIN: {CONF_RADIUS: 200}}
async def test_setup( async def test_setup(
@ -74,7 +73,7 @@ async def test_setup(
freezer.move_to(utcnow) freezer.move_to(utcnow)
with patch("aio_geojson_client.feed.GeoJsonFeed.update") as mock_feed_update: with patch("aio_geojson_client.feed.GeoJsonFeed.update") as mock_feed_update:
mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3] mock_feed_update.return_value = "OK", [mock_entry_1, mock_entry_2, mock_entry_3]
assert await async_setup_component(hass, geonetnz_quakes.DOMAIN, CONFIG) assert await async_setup_component(hass, DOMAIN, CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
# Artificially trigger update and collect events. # Artificially trigger update and collect events.
hass.bus.async_fire(EVENT_HOMEASSISTANT_START) hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
@ -188,7 +187,7 @@ async def test_setup_imperial(
patch("aio_geojson_client.feed.GeoJsonFeed.last_timestamp", create=True), patch("aio_geojson_client.feed.GeoJsonFeed.last_timestamp", create=True),
): ):
mock_feed_update.return_value = "OK", [mock_entry_1] mock_feed_update.return_value = "OK", [mock_entry_1]
assert await async_setup_component(hass, geonetnz_quakes.DOMAIN, CONFIG) assert await async_setup_component(hass, DOMAIN, CONFIG)
await hass.async_block_till_done() await hass.async_block_till_done()
# Artificially trigger update and collect events. # Artificially trigger update and collect events.
hass.bus.async_fire(EVENT_HOMEASSISTANT_START) hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
@ -201,10 +200,7 @@ async def test_setup_imperial(
) )
# Test conversion of 200 miles to kilometers. # Test conversion of 200 miles to kilometers.
feeds = hass.data[DOMAIN][FEED] manager = hass.config_entries.async_loaded_entries(DOMAIN)[0].runtime_data
assert feeds is not None
assert len(feeds) == 1
manager = list(feeds.values())[0]
# Ensure that the filter value in km is correctly set. # Ensure that the filter value in km is correctly set.
assert manager._feed_manager._feed._filter_radius == 321.8688 assert manager._feed_manager._feed._filter_radius == 321.8688

View File

@ -2,7 +2,6 @@
from unittest.mock import patch from unittest.mock import patch
from homeassistant.components.geonetnz_quakes import DOMAIN, FEED
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
@ -16,8 +15,7 @@ async def test_component_unload_config_entry(hass: HomeAssistant, config_entry)
assert await hass.config_entries.async_setup(config_entry.entry_id) assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
assert mock_feed_manager_update.call_count == 1 assert mock_feed_manager_update.call_count == 1
assert hass.data[DOMAIN][FEED][config_entry.entry_id] is not None
# Unload config entry. # Unload config entry.
assert await hass.config_entries.async_unload(config_entry.entry_id) assert await hass.config_entries.async_unload(config_entry.entry_id)
await hass.async_block_till_done() await hass.async_block_till_done()
assert hass.data[DOMAIN][FEED].get(config_entry.entry_id) is None