Ensure native_templow <= native_temperature

This commit is contained in:
Jules 2024-01-22 18:32:55 +01:00
parent 21abf641e5
commit ce79abbefe
Signed by: jdejaegh
GPG key ID: 99D6D184CA66933A
5 changed files with 1711 additions and 1 deletions

View file

@ -295,6 +295,14 @@ class IrmKmiCoordinator(DataUpdateCoordinator):
is_daytime=is_daytime, is_daytime=is_daytime,
text=f.get('text', {}).get(self.hass.config.language, ""), text=f.get('text', {}).get(self.hass.config.language, ""),
) )
# Swap temperature and templow if needed
if (forecast['native_templow'] is not None
and forecast['native_temperature'] is not None
and forecast['native_templow'] > forecast['native_temperature']):
(forecast['native_templow'], forecast['native_temperature']) = \
(forecast['native_temperature'], forecast['native_templow'])
forecasts.append(forecast) forecasts.append(forecast)
if is_daytime or idx == 0: if is_daytime or idx == 0:
n_days += 1 n_days += 1

View file

@ -129,8 +129,16 @@ class IrmKmiWeather(CoordinatorEntity, WeatherEntity):
return None return None
if len(data) > 1 and not data[0].get('is_daytime') and data[1].get('native_templow') is None: if len(data) > 1 and not data[0].get('is_daytime') and data[1].get('native_templow') is None:
data[1]['native_templow'] = data[0].get('native_templow') data[1]['native_templow'] = data[0].get('native_templow')
if data[1]['native_templow'] > data[1]['native_temperature']:
(data[1]['native_templow'], data[1]['native_temperature']) = \
(data[1]['native_temperature'], data[1]['native_templow'])
if len(data) > 0 and not data[0].get('is_daytime'): if len(data) > 0 and not data[0].get('is_daytime'):
return data return data
if len(data) > 1 and data[0].get('native_templow') is None and not data[1].get('is_daytime'): if len(data) > 1 and data[0].get('native_templow') is None and not data[1].get('is_daytime'):
data[0]['native_templow'] = data[1].get('native_templow') data[0]['native_templow'] = data[1].get('native_templow')
if data[0]['native_templow'] > data[0]['native_temperature']:
(data[0]['native_templow'], data[0]['native_temperature']) = \
(data[0]['native_temperature'], data[0]['native_templow'])
return [f for f in data if f.get('is_daytime')] return [f for f in data if f.get('is_daytime')]

View file

@ -31,7 +31,7 @@ async def patched(url: str, params: dict | None = None) -> bytes:
elif "getLocalizationLayerNL" in url: elif "getLocalizationLayerNL" in url:
file_name = "tests/fixtures/loc_layer_nl.png" file_name = "tests/fixtures/loc_layer_nl.png"
else: else:
raise ValueError("Not a valid parameter for the mock") raise ValueError(f"Not a valid parameter for the mock: {url}")
with open(file_name, "rb") as file: with open(file_name, "rb") as file:
return file.read() return file.read()
@ -180,6 +180,22 @@ def mock_image_and_nl_forecast_irm_kmi_api(request: pytest.FixtureRequest) -> Ge
yield irm_kmi yield irm_kmi
@pytest.fixture()
def mock_image_and_high_temp_irm_kmi_api(request: pytest.FixtureRequest) -> Generator[None, MagicMock, None]:
"""Return a mocked IrmKmi api client."""
fixture: str = "high_low_temp.json"
forecast = json.loads(load_fixture(fixture))
with patch(
"custom_components.irm_kmi.coordinator.IrmKmiApiClient", autospec=True
) as irm_kmi_api_mock:
irm_kmi = irm_kmi_api_mock.return_value
irm_kmi.get_image.side_effect = patched
irm_kmi.get_forecasts_coord.return_value = forecast
yield irm_kmi
@pytest.fixture() @pytest.fixture()
def mock_coordinator(request: pytest.FixtureRequest) -> Generator[None, MagicMock, None]: def mock_coordinator(request: pytest.FixtureRequest) -> Generator[None, MagicMock, None]:
"""Return a mocked coordinator.""" """Return a mocked coordinator."""

1647
tests/fixtures/high_low_temp.json vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,9 @@
from datetime import datetime from datetime import datetime
from typing import List
from unittest.mock import AsyncMock from unittest.mock import AsyncMock
from freezegun import freeze_time from freezegun import freeze_time
from homeassistant.components.weather import Forecast
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from pytest_homeassistant_custom_component.common import MockConfigEntry from pytest_homeassistant_custom_component.common import MockConfigEntry
@ -31,3 +33,32 @@ async def test_weather_nl(
# When getting daily forecast, the min temperature of the current day # When getting daily forecast, the min temperature of the current day
# should be the min temperature of the coming night # should be the min temperature of the coming night
assert result[0]['native_templow'] == 9 assert result[0]['native_templow'] == 9
@freeze_time(datetime.fromisoformat("2024-01-21T14:15:00+01:00"))
async def test_weather_higher_temp_at_night(
hass: HomeAssistant,
mock_image_and_high_temp_irm_kmi_api: AsyncMock,
mock_config_entry: MockConfigEntry
) -> None:
# Test case for https://github.com/jdejaegh/irm-kmi-ha/issues/8
hass.states.async_set(
"zone.home",
0,
{"latitude": 50.738681639, "longitude": 4.054077148},
)
coordinator = IrmKmiCoordinator(hass, mock_config_entry)
await coordinator.async_config_entry_first_refresh()
weather = IrmKmiWeather(coordinator, mock_config_entry)
result: List[Forecast] = await weather.async_forecast_daily()
for f in result:
if f['native_temperature'] is not None and f['native_templow'] is not None:
assert f['native_temperature'] >= f['native_templow']
result: List[Forecast] = await weather.async_forecast_twice_daily()
for f in result:
if f['native_temperature'] is not None and f['native_templow'] is not None:
assert f['native_temperature'] >= f['native_templow']