mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Add weather warning entities to irm_kmi (#193423)
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
"""Support for IRM KMI weather warnings."""
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, override
|
||||
|
||||
from irm_kmi_api import WarningData
|
||||
|
||||
from homeassistant.components.binary_sensor import (
|
||||
BinarySensorDeviceClass,
|
||||
BinarySensorEntity,
|
||||
)
|
||||
from homeassistant.const import CONF_UNIQUE_ID
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .coordinator import IrmKmiConfigEntry, IrmKmiCoordinator
|
||||
from .entity import IrmKmiBaseEntity
|
||||
|
||||
# Coordinator is used to centralize the data updates
|
||||
PARALLEL_UPDATES = 0
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: IrmKmiConfigEntry,
|
||||
async_add_entities: AddConfigEntryEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up the binary sensor platform."""
|
||||
async_add_entities([IrmKmiWarning(entry)])
|
||||
|
||||
|
||||
def _is_active(warning: WarningData, now: datetime) -> bool:
|
||||
"""Return whether the warning covers the given time."""
|
||||
return warning["starts_at"] <= now < warning["ends_at"]
|
||||
|
||||
|
||||
class IrmKmiWarning(IrmKmiBaseEntity[IrmKmiCoordinator], BinarySensorEntity):
|
||||
"""Weather warning binary sensor."""
|
||||
|
||||
_attr_device_class = BinarySensorDeviceClass.SAFETY
|
||||
_attr_translation_key = "warning"
|
||||
_unrecorded_attributes = frozenset({"warnings"})
|
||||
|
||||
def __init__(self, entry: IrmKmiConfigEntry) -> None:
|
||||
"""Create a new instance of the warning sensor from a configuration entry."""
|
||||
super().__init__(entry, entry.runtime_data.weather)
|
||||
self._attr_unique_id = f"{entry.data[CONF_UNIQUE_ID]}-warning"
|
||||
|
||||
@property
|
||||
@override
|
||||
def is_on(self) -> bool:
|
||||
"""Return True if at least one warning is in effect right now."""
|
||||
now = dt_util.utcnow()
|
||||
return any(
|
||||
_is_active(warning, now) for warning in self.coordinator.data.warnings
|
||||
)
|
||||
|
||||
@property
|
||||
@override
|
||||
def extra_state_attributes(self) -> dict[str, Any]:
|
||||
"""Return every warning the provider published, active or not."""
|
||||
now = dt_util.utcnow()
|
||||
return {
|
||||
"warnings": [
|
||||
{**warning, "is_active": _is_active(warning, now)}
|
||||
for warning in self.coordinator.data.warnings
|
||||
]
|
||||
}
|
||||
@@ -17,7 +17,7 @@ from homeassistant.components.weather import (
|
||||
from homeassistant.const import Platform, __version__
|
||||
|
||||
DOMAIN: Final = "irm_kmi"
|
||||
PLATFORMS: Final = [Platform.SENSOR, Platform.WEATHER]
|
||||
PLATFORMS: Final = [Platform.BINARY_SENSOR, Platform.SENSOR, Platform.WEATHER]
|
||||
|
||||
OUT_OF_BENELUX: Final = [
|
||||
"außerhalb der Benelux (Brussels)",
|
||||
|
||||
@@ -106,6 +106,7 @@ class IrmKmiCoordinator(TimestampDataUpdateCoordinator[ProcessedCoordinatorData]
|
||||
daily_forecast=self._api.get_daily_forecast(tz, lang),
|
||||
hourly_forecast=self._api.get_hourly_forecast(tz),
|
||||
country=self._api.get_country(),
|
||||
warnings=self._api.get_warnings(lang),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from irm_kmi_api import CurrentWeatherData, ExtendedForecast
|
||||
from irm_kmi_api import CurrentWeatherData, ExtendedForecast, WarningData
|
||||
|
||||
from homeassistant.components.weather import Forecast
|
||||
|
||||
@@ -13,5 +13,6 @@ class ProcessedCoordinatorData:
|
||||
|
||||
current_weather: CurrentWeatherData
|
||||
country: str | None
|
||||
warnings: list[WarningData]
|
||||
hourly_forecast: list[Forecast] = field(default_factory=list)
|
||||
daily_forecast: list[ExtendedForecast] = field(default_factory=list)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import Final, override
|
||||
|
||||
from irm_kmi_api import PollenName, PollenParser
|
||||
@@ -23,6 +24,7 @@ from homeassistant.const import (
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
|
||||
from homeassistant.helpers.typing import StateType
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .coordinator import IrmKmiConfigEntry, IrmKmiCoordinator, IrmKmiPollenCoordinator
|
||||
from .data import ProcessedCoordinatorData
|
||||
@@ -38,7 +40,20 @@ POLLEN_LEVELS: Final = [level.value for level in PollenParser.get_option_values(
|
||||
class IrmKmiSensorEntityDescription(SensorEntityDescription):
|
||||
"""Class describing IRM KMI sensor entities."""
|
||||
|
||||
value_fn: Callable[[ProcessedCoordinatorData], StateType]
|
||||
value_fn: Callable[[ProcessedCoordinatorData], StateType | datetime]
|
||||
|
||||
|
||||
def _next_warning(data: ProcessedCoordinatorData) -> datetime | None:
|
||||
"""Return when the next warning starts, or None if none is pending."""
|
||||
now = dt_util.utcnow()
|
||||
return min(
|
||||
(
|
||||
warning["starts_at"]
|
||||
for warning in data.warnings
|
||||
if now < warning["starts_at"]
|
||||
),
|
||||
default=None,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True, kw_only=True)
|
||||
@@ -93,6 +108,12 @@ SENSOR_TYPES: tuple[IrmKmiSensorEntityDescription, ...] = (
|
||||
native_unit_of_measurement=UV_INDEX,
|
||||
value_fn=lambda data: data.current_weather.get("uv_index"),
|
||||
),
|
||||
IrmKmiSensorEntityDescription(
|
||||
key="next_warning",
|
||||
translation_key="next_warning",
|
||||
device_class=SensorDeviceClass.TIMESTAMP,
|
||||
value_fn=_next_warning,
|
||||
),
|
||||
)
|
||||
|
||||
POLLEN_SENSOR_TYPES: tuple[IrmKmiPollenSensorEntityDescription, ...] = tuple(
|
||||
@@ -141,7 +162,7 @@ class IrmKmiSensor(IrmKmiBaseEntity[IrmKmiCoordinator], SensorEntity):
|
||||
|
||||
@property
|
||||
@override
|
||||
def native_value(self) -> StateType:
|
||||
def native_value(self) -> StateType | datetime:
|
||||
"""Return the current value of the sensor."""
|
||||
return self.entity_description.value_fn(self.coordinator.data)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"common": {
|
||||
"language_override_description": "Override the Home Assistant language for the textual weather forecast."
|
||||
"language_override_description": "Override the Home Assistant language for forecast texts and warnings."
|
||||
},
|
||||
"config": {
|
||||
"abort": {
|
||||
@@ -23,7 +23,20 @@
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"binary_sensor": {
|
||||
"warning": {
|
||||
"name": "Warning",
|
||||
"state_attributes": {
|
||||
"warnings": {
|
||||
"name": "Warnings"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"sensor": {
|
||||
"next_warning": {
|
||||
"name": "Next warning"
|
||||
},
|
||||
"pollen_alder": {
|
||||
"name": "Alder pollen",
|
||||
"state": {
|
||||
|
||||
@@ -15,7 +15,7 @@ from homeassistant.const import (
|
||||
CONF_UNIQUE_ID,
|
||||
)
|
||||
|
||||
from .const import CURRENT_WEATHER, POLLEN
|
||||
from .const import CURRENT_WEATHER, POLLEN, WARNINGS
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -61,6 +61,7 @@ def mock_irm_kmi_api() -> Generator[MagicMock]:
|
||||
irm_kmi.get_current_weather.return_value = CURRENT_WEATHER
|
||||
irm_kmi.get_daily_forecast.return_value = []
|
||||
irm_kmi.get_hourly_forecast.return_value = []
|
||||
irm_kmi.get_warnings.return_value = WARNINGS
|
||||
irm_kmi.get_pollen.return_value = POLLEN
|
||||
yield irm_kmi
|
||||
|
||||
|
||||
@@ -1,14 +1,46 @@
|
||||
"""Constants shared by the IRM KMI integration tests."""
|
||||
|
||||
from irm_kmi_api import CurrentWeatherData, PollenLevel, PollenName
|
||||
from datetime import datetime
|
||||
|
||||
from irm_kmi_api import (
|
||||
CurrentWeatherData,
|
||||
PollenLevel,
|
||||
PollenName,
|
||||
WarningData,
|
||||
WarningType,
|
||||
)
|
||||
|
||||
WEATHER_ENTITY_ID = "weather.brussels"
|
||||
|
||||
WARNING_ENTITY_ID = "binary_sensor.brussels_warning"
|
||||
|
||||
ALDER_POLLEN_ENTITY_ID = "sensor.brussels_alder_pollen"
|
||||
NEXT_WARNING_ENTITY_ID = "sensor.brussels_next_warning"
|
||||
TEMPERATURE_ENTITY_ID = "sensor.brussels_temperature"
|
||||
WIND_DIRECTION_ENTITY_ID = "sensor.brussels_wind_direction"
|
||||
WIND_GUST_SPEED_ENTITY_ID = "sensor.brussels_wind_gust_speed"
|
||||
|
||||
WARNINGS = [
|
||||
WarningData(
|
||||
slug=WarningType.FOG,
|
||||
id=7,
|
||||
level=1,
|
||||
friendly_name="Fog",
|
||||
text="Visibility is locally reduced to less than 200 meters.",
|
||||
starts_at=datetime.fromisoformat("2023-12-28T16:00:00+01:00"),
|
||||
ends_at=datetime.fromisoformat("2023-12-28T20:00:00+01:00"),
|
||||
),
|
||||
WarningData(
|
||||
slug=WarningType.ICE_OR_SNOW,
|
||||
id=2,
|
||||
level=2,
|
||||
friendly_name="Ice or snow",
|
||||
text="Roads are slippery in the morning.",
|
||||
starts_at=datetime.fromisoformat("2023-12-29T06:00:00+01:00"),
|
||||
ends_at=datetime.fromisoformat("2023-12-29T12:00:00+01:00"),
|
||||
),
|
||||
]
|
||||
|
||||
CURRENT_WEATHER = CurrentWeatherData(
|
||||
condition="cloudy",
|
||||
temperature=7.2,
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
{
|
||||
"cityName": "Antwerp",
|
||||
"country": "BE",
|
||||
"obs": {
|
||||
"temp": 25,
|
||||
"timestamp": "2025-06-18T18:40:00+02:00",
|
||||
"ww": 0,
|
||||
"dayNight": "d"
|
||||
},
|
||||
"for": {
|
||||
"daily": [],
|
||||
"hourly": [],
|
||||
"showWarningTab": true,
|
||||
"warning": [
|
||||
{
|
||||
"icon_country": "BE",
|
||||
"warningType": {
|
||||
"id": "10",
|
||||
"name": {
|
||||
"fr": "Chaleur",
|
||||
"nl": "Hitte",
|
||||
"en": "Heat",
|
||||
"de": "Hitze"
|
||||
}
|
||||
},
|
||||
"warningLevel": "1",
|
||||
"text": {
|
||||
"fr": "Les températures maximales atteindront ou dépasseront les 25 degrés dans de nombreux endroits, excepté au littoral et sur le relief ardennais. De vendredi à dimanche, elles oscilleront même autour de 30 degrés ou les dépasseront dans certaines régions.",
|
||||
"nl": "Op veel plaatsen klimmen de maxima naar 25 graden of meer, behalve in de Kuststreek en op het Ardense reliëf. Vanaf vrijdag tot en met zondag schommelen de maxima zelfs rond 30 graden of meer op sommige plaatsen.",
|
||||
"en": "By such temperatures, measures should be taken to protect older and weaker persons by giving them more often to drink and to not let them stand or sit in direct sunlight. Be careful.",
|
||||
"de": "Bei solchen Temperaturwerten können Maßnahmen zum Schutz älterer und schwächerer Menschen ergriffen werden durch: mehr trinken, keinem direkten Sonnenlicht aussetzen. Seien Sie vorsichtig."
|
||||
},
|
||||
"fromTimestamp": "2025-06-18T00:00:00+02:00",
|
||||
"toTimestamp": "2025-06-23T00:00:00+02:00"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
# serializer version: 1
|
||||
# name: test_warning[binary_sensor.brussels_warning-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('irm_kmi', '01JIRMKMI00000000000000000')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'binary_sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'binary_sensor.brussels_warning',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Warning',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <BinarySensorDeviceClass.SAFETY: 'safety'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Warning',
|
||||
'platform': 'irm_kmi',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'warning',
|
||||
'unique_id': 'brussels be-warning',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_warning[binary_sensor.brussels_warning-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.ATTRIBUTION: 'attribution'>: 'Weather data from the Royal Meteorological Institute of Belgium meteo.be',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'safety',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Brussels Warning',
|
||||
'warnings': list([
|
||||
dict({
|
||||
'ends_at': datetime.datetime(2023, 12, 28, 20, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600))),
|
||||
'friendly_name': 'Fog',
|
||||
'id': 7,
|
||||
'is_active': True,
|
||||
'level': 1,
|
||||
'slug': <WarningType.FOG: 'fog'>,
|
||||
'starts_at': datetime.datetime(2023, 12, 28, 16, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600))),
|
||||
'text': 'Visibility is locally reduced to less than 200 meters.',
|
||||
}),
|
||||
dict({
|
||||
'ends_at': datetime.datetime(2023, 12, 29, 12, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600))),
|
||||
'friendly_name': 'Ice or snow',
|
||||
'id': 2,
|
||||
'is_active': False,
|
||||
'level': 2,
|
||||
'slug': <WarningType.ICE_OR_SNOW: 'ice_or_snow'>,
|
||||
'starts_at': datetime.datetime(2023, 12, 29, 6, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600))),
|
||||
'text': 'Roads are slippery in the morning.',
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'binary_sensor.brussels_warning',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'on',
|
||||
})
|
||||
# ---
|
||||
# name: test_warning_from_a_recorded_forecast[antwerp_with_heat_warning.json]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.ATTRIBUTION: 'attribution'>: 'Weather data from the Royal Meteorological Institute of Belgium meteo.be',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'safety',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Brussels Warning',
|
||||
'warnings': list([
|
||||
dict({
|
||||
'ends_at': HAFakeDatetime(2025, 6, 23, 0, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200))),
|
||||
'friendly_name': 'Heat',
|
||||
'id': 10,
|
||||
'is_active': True,
|
||||
'level': 1,
|
||||
'slug': <WarningType.HEAT: 'heat'>,
|
||||
'starts_at': HAFakeDatetime(2025, 6, 18, 0, 0, tzinfo=datetime.timezone(datetime.timedelta(seconds=7200))),
|
||||
'text': 'By such temperatures, measures should be taken to protect older and weaker persons by giving them more often to drink and to not let them stand or sit in direct sunlight. Be careful.',
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'binary_sensor.brussels_warning',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'on',
|
||||
})
|
||||
# ---
|
||||
@@ -484,6 +484,58 @@
|
||||
'state': 'active',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensors[sensor.brussels_next_warning-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': None,
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': None,
|
||||
'device_class': None,
|
||||
'device_id': <DeviceEntry identifiers=[('irm_kmi', '01JIRMKMI00000000000000000')]>,
|
||||
'disabled_by': None,
|
||||
'domain': 'sensor',
|
||||
'entity_category': None,
|
||||
'entity_id': 'sensor.brussels_next_warning',
|
||||
'has_entity_name': True,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': 'Next warning',
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': <SensorDeviceClass.TIMESTAMP: 'timestamp'>,
|
||||
'original_icon': None,
|
||||
'original_name': 'Next warning',
|
||||
'platform': 'irm_kmi',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': 0,
|
||||
'translation_key': 'next_warning',
|
||||
'unique_id': 'brussels be-next_warning',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_sensors[sensor.brussels_next_warning-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.ATTRIBUTION: 'attribution'>: 'Weather data from the Royal Meteorological Institute of Belgium meteo.be',
|
||||
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'timestamp',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Brussels Next warning',
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'sensor.brussels_next_warning',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': '2023-12-28T15:00:00+00:00',
|
||||
})
|
||||
# ---
|
||||
# name: test_sensors[sensor.brussels_oak_pollen-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Tests for the IRM KMI binary sensor platform."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry, snapshot_platform
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.irm_kmi.const import CONF_LANGUAGE_OVERRIDE
|
||||
from homeassistant.const import STATE_OFF, STATE_ON, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from . import setup_integration
|
||||
from .const import WARNING_ENTITY_ID
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def override_platforms() -> Generator[None]:
|
||||
"""Load only the binary sensor platform."""
|
||||
with patch("homeassistant.components.irm_kmi.PLATFORMS", [Platform.BINARY_SENSOR]):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2023-12-28T18:00:00+01:00")
|
||||
@pytest.mark.usefixtures("mock_irm_kmi_api")
|
||||
async def test_warning(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test the warning binary sensor while one of two warnings is in effect."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("now", "expected_state"),
|
||||
[
|
||||
pytest.param("2023-12-28T15:59:59+01:00", STATE_OFF, id="before_the_warning"),
|
||||
pytest.param("2023-12-28T16:00:00+01:00", STATE_ON, id="as_it_starts"),
|
||||
pytest.param("2023-12-28T18:00:00+01:00", STATE_ON, id="during_the_warning"),
|
||||
pytest.param("2023-12-28T20:00:00+01:00", STATE_OFF, id="as_it_ends"),
|
||||
pytest.param("2023-12-28T20:00:01+01:00", STATE_OFF, id="after_the_warning"),
|
||||
pytest.param("2023-12-29T09:00:00+01:00", STATE_ON, id="during_the_next_one"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("mock_irm_kmi_api")
|
||||
async def test_warning_is_on_within_its_window_only(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
now: str,
|
||||
expected_state: str,
|
||||
) -> None:
|
||||
"""Test the sensor is on strictly between the start and the end of a warning."""
|
||||
freezer.move_to(now)
|
||||
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
state = hass.states.get(WARNING_ENTITY_ID)
|
||||
assert state
|
||||
assert state.state == expected_state
|
||||
|
||||
|
||||
async def test_warning_without_any_warning(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_irm_kmi_api: MagicMock,
|
||||
) -> None:
|
||||
"""Test the sensor is off without warnings."""
|
||||
mock_irm_kmi_api.get_warnings.return_value = []
|
||||
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
state = hass.states.get(WARNING_ENTITY_ID)
|
||||
assert state
|
||||
assert state.state == STATE_OFF
|
||||
assert state.attributes["warnings"] == []
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_forecasts_coord")
|
||||
@pytest.mark.parametrize("forecast_fixture", ["antwerp_with_heat_warning.json"])
|
||||
@pytest.mark.freeze_time("2025-06-18T18:40:00+02:00")
|
||||
async def test_warning_from_a_recorded_forecast(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test a warning of a recorded forecast."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
assert hass.states.get(WARNING_ENTITY_ID) == snapshot
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_get_forecasts_coord")
|
||||
@pytest.mark.parametrize("forecast_fixture", ["antwerp_with_heat_warning.json"])
|
||||
@pytest.mark.parametrize(
|
||||
("hass_language", "options", "expected_name"),
|
||||
[
|
||||
pytest.param("en", {}, "Heat", id="english"),
|
||||
pytest.param("en", {CONF_LANGUAGE_OVERRIDE: "fr"}, "Chaleur", id="override_fr"),
|
||||
pytest.param("en", {CONF_LANGUAGE_OVERRIDE: "nl"}, "Hitte", id="override_nl"),
|
||||
pytest.param("nl", {}, "Hitte", id="follow_home_assistant"),
|
||||
],
|
||||
)
|
||||
@pytest.mark.freeze_time("2025-06-18T18:40:00+02:00")
|
||||
async def test_warning_language(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
hass_language: str,
|
||||
options: dict[str, str],
|
||||
expected_name: str,
|
||||
) -> None:
|
||||
"""Test the warning text is fetched in the language the user asked for."""
|
||||
hass.config.language = hass_language
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
hass.config_entries.async_update_entry(mock_config_entry, options=options)
|
||||
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get(WARNING_ENTITY_ID)
|
||||
assert state
|
||||
assert state.attributes["warnings"][0]["friendly_name"] == expected_name
|
||||
@@ -33,7 +33,7 @@ async def test_load_unload_config_entry(
|
||||
for entity in er.async_entries_for_config_entry(
|
||||
entity_registry, mock_config_entry.entry_id
|
||||
)
|
||||
} == {"sensor", "weather"}
|
||||
} == {"binary_sensor", "sensor", "weather"}
|
||||
|
||||
await hass.config_entries.async_unload(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Tests for the IRM KMI recorder exclusions."""
|
||||
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
from pytest_homeassistant.components.recorder.common import async_wait_recording_done
|
||||
|
||||
from homeassistant.components.recorder.history import get_significant_states
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import setup_integration
|
||||
from .const import WARNING_ENTITY_ID
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("recorder_mock", "mock_irm_kmi_api")
|
||||
async def test_exclude_attributes(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry
|
||||
) -> None:
|
||||
"""Test the warnings are not recorded."""
|
||||
now = dt_util.utcnow()
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
assert "warnings" in hass.states.get(WARNING_ENTITY_ID).attributes
|
||||
await async_wait_recording_done(hass)
|
||||
|
||||
states = await hass.async_add_executor_job(
|
||||
get_significant_states, hass, now, None, [WARNING_ENTITY_ID]
|
||||
)
|
||||
assert len(states[WARNING_ENTITY_ID]) == 1
|
||||
assert "warnings" not in states[WARNING_ENTITY_ID][0].attributes
|
||||
@@ -11,6 +11,7 @@ from irm_kmi_api import (
|
||||
PollenLevel,
|
||||
PollenName,
|
||||
PollenParser,
|
||||
WarningData,
|
||||
)
|
||||
import pytest
|
||||
from pytest_homeassistant.common import (
|
||||
@@ -28,8 +29,10 @@ from . import setup_integration
|
||||
from .const import (
|
||||
ALDER_POLLEN_ENTITY_ID,
|
||||
CURRENT_WEATHER,
|
||||
NEXT_WARNING_ENTITY_ID,
|
||||
POLLEN,
|
||||
TEMPERATURE_ENTITY_ID,
|
||||
WARNINGS,
|
||||
WIND_DIRECTION_ENTITY_ID,
|
||||
WIND_GUST_SPEED_ENTITY_ID,
|
||||
)
|
||||
@@ -188,3 +191,58 @@ async def test_pollen_kept_when_forecasts_fail(
|
||||
|
||||
assert hass.states.get(TEMPERATURE_ENTITY_ID).state == STATE_UNAVAILABLE
|
||||
assert hass.states.get(ALDER_POLLEN_ENTITY_ID).state == PollenLevel.RED
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("now", "warnings", "expected_state"),
|
||||
[
|
||||
pytest.param(
|
||||
"2023-12-28T15:30:00+01:00",
|
||||
WARNINGS,
|
||||
"2023-12-28T15:00:00+00:00",
|
||||
id="before_any_warning",
|
||||
),
|
||||
pytest.param(
|
||||
"2023-12-28T18:00:00+01:00",
|
||||
WARNINGS,
|
||||
"2023-12-29T05:00:00+00:00",
|
||||
id="while_one_is_in_effect",
|
||||
),
|
||||
pytest.param(
|
||||
"2023-12-29T06:00:00+01:00",
|
||||
WARNINGS,
|
||||
STATE_UNKNOWN,
|
||||
id="as_the_last_one_starts",
|
||||
),
|
||||
pytest.param(
|
||||
"2023-12-29T13:00:00+01:00",
|
||||
WARNINGS,
|
||||
STATE_UNKNOWN,
|
||||
id="after_every_warning",
|
||||
),
|
||||
pytest.param(
|
||||
"2023-12-28T15:30:00+01:00",
|
||||
[],
|
||||
STATE_UNKNOWN,
|
||||
id="without_any_warning",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_next_warning(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_irm_kmi_api: MagicMock,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
now: str,
|
||||
warnings: list[WarningData],
|
||||
expected_state: str,
|
||||
) -> None:
|
||||
"""Test the sensor reports the start of the earliest upcoming warning."""
|
||||
freezer.move_to(now)
|
||||
mock_irm_kmi_api.get_warnings.return_value = warnings
|
||||
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
state = hass.states.get(NEXT_WARNING_ENTITY_ID)
|
||||
assert state
|
||||
assert state.state == expected_state
|
||||
|
||||
Reference in New Issue
Block a user