From ef955f1120452802ad5ba96bb609cd0ae532a07b Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Thu, 19 Nov 2026 19:57:59 +0100 Subject: [PATCH] Add diagnostics to Met Office (#193446) Co-authored-by: Claude Co-authored-by: jbouwh <7188918+jbouwh@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: jbouwh --- .../components/metoffice/diagnostics.py | 51 +++++++++++++ .../components/metoffice/quality_scale.yaml | 2 +- tests/components/metoffice/conftest.py | 30 +++++++- .../metoffice/snapshots/test_diagnostics.ambr | 74 +++++++++++++++++++ .../components/metoffice/test_diagnostics.py | 60 +++++++++++++++ tests/components/metoffice/test_weather.py | 24 ------ 6 files changed, 215 insertions(+), 26 deletions(-) create mode 100644 homeassistant/components/metoffice/diagnostics.py create mode 100644 tests/components/metoffice/snapshots/test_diagnostics.ambr create mode 100644 tests/components/metoffice/test_diagnostics.py diff --git a/homeassistant/components/metoffice/diagnostics.py b/homeassistant/components/metoffice/diagnostics.py new file mode 100644 index 000000000000..13ee5857059e --- /dev/null +++ b/homeassistant/components/metoffice/diagnostics.py @@ -0,0 +1,51 @@ +"""Diagnostics support for Met Office.""" + +from typing import Any + +from homeassistant.core import HomeAssistant + +from .coordinator import MetOfficeConfigEntry, MetOfficeUpdateCoordinator + + +async def async_get_config_entry_diagnostics( + hass: HomeAssistant, entry: MetOfficeConfigEntry +) -> dict[str, Any]: + """Return diagnostics for a config entry.""" + data = entry.runtime_data + + # The API key, the configured coordinates and name, and the name, + # coordinates and elevation of the forecast site are left out, as they + # reveal the location. The forecasts are summarized instead of dumped. + return { + "hourly": _coordinator_diagnostics(data.hourly_coordinator), + "daily": _coordinator_diagnostics(data.daily_coordinator), + "twice_daily": _coordinator_diagnostics(data.twice_daily_coordinator), + } + + +def _coordinator_diagnostics( + coordinator: MetOfficeUpdateCoordinator, +) -> dict[str, Any]: + """Return a summary of the forecast of a coordinator.""" + diagnostics: dict[str, Any] = { + "last_update_success": coordinator.last_update_success, + "last_update_success_time": ( + coordinator.last_update_success_time.isoformat() + if coordinator.last_update_success_time is not None + else None + ), + } + # The twice daily coordinator is only refreshed when its forecast is used + if (forecast := coordinator.data_or_none) is None: + diagnostics["forecast"] = None + return diagnostics + timesteps = forecast.timesteps + diagnostics["forecast"] = { + "frequency": forecast.frequency, + "model_run_date": forecast.data_date.isoformat(), + "distance_from_requested_location": forecast.distance_from_requested_location, + "timesteps": len(timesteps), + "first_timestep": timesteps[0]["time"].isoformat() if timesteps else None, + "last_timestep": timesteps[-1]["time"].isoformat() if timesteps else None, + } + return diagnostics diff --git a/homeassistant/components/metoffice/quality_scale.yaml b/homeassistant/components/metoffice/quality_scale.yaml index 04e68ec8fbe5..ffd5a8f97e0b 100644 --- a/homeassistant/components/metoffice/quality_scale.yaml +++ b/homeassistant/components/metoffice/quality_scale.yaml @@ -49,7 +49,7 @@ rules: # Gold devices: done - diagnostics: todo + diagnostics: done discovery-update-info: status: exempt comment: Integration does not support discovery. diff --git a/tests/components/metoffice/conftest.py b/tests/components/metoffice/conftest.py index fdd33574f955..c26824a215c5 100644 --- a/tests/components/metoffice/conftest.py +++ b/tests/components/metoffice/conftest.py @@ -1,12 +1,16 @@ """Fixtures for Met Office weather integration tests.""" +import json from unittest.mock import patch from datapoint.exceptions import APIException import pytest -from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry, async_load_json_object_fixture +import requests_mock +from requests_mock.adapter import _Matcher from homeassistant.components.metoffice.const import DOMAIN +from homeassistant.core import HomeAssistant from .const import ( METOFFICE_CONFIG_KINGSLYNN, @@ -58,3 +62,27 @@ def mock_config_entry2() -> MockConfigEntry: version=2, unique_id=f"{TEST_LATITUDE_KINGSLYNN}_{TEST_LONGITUDE_KINGSLYNN}", ) + + +@pytest.fixture +async def wavertree_data( + hass: HomeAssistant, requests_mock: requests_mock.Mocker +) -> dict[str, _Matcher]: + """Mock data for the Wavertree location.""" + # all metoffice test data encapsulated in here + mock_json = await async_load_json_object_fixture(hass, "metoffice.json", DOMAIN) + wavertree_hourly = json.dumps(mock_json["wavertree_hourly"]) + wavertree_daily = json.dumps(mock_json["wavertree_daily"]) + + wavertree_hourly_mock = requests_mock.get( + "https://data.hub.api.metoffice.gov.uk/sitespecific/v0/point/hourly", + text=wavertree_hourly, + ) + wavertree_daily_mock = requests_mock.get( + "https://data.hub.api.metoffice.gov.uk/sitespecific/v0/point/daily", + text=wavertree_daily, + ) + return { + "wavertree_hourly_mock": wavertree_hourly_mock, + "wavertree_daily_mock": wavertree_daily_mock, + } diff --git a/tests/components/metoffice/snapshots/test_diagnostics.ambr b/tests/components/metoffice/snapshots/test_diagnostics.ambr new file mode 100644 index 000000000000..feead6d69b83 --- /dev/null +++ b/tests/components/metoffice/snapshots/test_diagnostics.ambr @@ -0,0 +1,74 @@ +# serializer version: 1 +# name: test_diagnostics + dict({ + 'daily': dict({ + 'forecast': dict({ + 'distance_from_requested_location': 1975.3601, + 'first_timestep': '2024-11-22T00:00:00+00:00', + 'frequency': 'daily', + 'last_timestep': '2024-11-29T00:00:00+00:00', + 'model_run_date': '2024-11-23T12:00:00+00:00', + 'timesteps': 8, + }), + 'last_update_success': True, + 'last_update_success_time': '2024-11-23T12:00:00+00:00', + }), + 'hourly': dict({ + 'forecast': dict({ + 'distance_from_requested_location': 1975.3601, + 'first_timestep': '2024-11-23T12:00:00+00:00', + 'frequency': 'hourly', + 'last_timestep': '2024-11-25T12:00:00+00:00', + 'model_run_date': '2024-11-23T12:00:00+00:00', + 'timesteps': 49, + }), + 'last_update_success': True, + 'last_update_success_time': '2024-11-23T12:00:00+00:00', + }), + 'twice_daily': dict({ + 'forecast': None, + 'last_update_success': True, + 'last_update_success_time': None, + }), + }) +# --- +# name: test_diagnostics_twice_daily_fetched + dict({ + 'daily': dict({ + 'forecast': dict({ + 'distance_from_requested_location': 1975.3601, + 'first_timestep': '2024-11-22T00:00:00+00:00', + 'frequency': 'daily', + 'last_timestep': '2024-11-29T00:00:00+00:00', + 'model_run_date': '2024-11-23T12:00:00+00:00', + 'timesteps': 8, + }), + 'last_update_success': True, + 'last_update_success_time': '2024-11-23T12:00:00+00:00', + }), + 'hourly': dict({ + 'forecast': dict({ + 'distance_from_requested_location': 1975.3601, + 'first_timestep': '2024-11-23T12:00:00+00:00', + 'frequency': 'hourly', + 'last_timestep': '2024-11-25T12:00:00+00:00', + 'model_run_date': '2024-11-23T12:00:00+00:00', + 'timesteps': 49, + }), + 'last_update_success': True, + 'last_update_success_time': '2024-11-23T12:00:00+00:00', + }), + 'twice_daily': dict({ + 'forecast': dict({ + 'distance_from_requested_location': 1975.3601, + 'first_timestep': '2024-11-22T00:00:00+00:00', + 'frequency': 'twice-daily', + 'last_timestep': '2024-11-29T12:00:00+00:00', + 'model_run_date': '2024-11-23T12:00:00+00:00', + 'timesteps': 16, + }), + 'last_update_success': True, + 'last_update_success_time': '2024-11-23T12:00:00+00:00', + }), + }) +# --- diff --git a/tests/components/metoffice/test_diagnostics.py b/tests/components/metoffice/test_diagnostics.py new file mode 100644 index 000000000000..e4b8e7bf7c93 --- /dev/null +++ b/tests/components/metoffice/test_diagnostics.py @@ -0,0 +1,60 @@ +"""Tests for the Met Office diagnostics.""" + +import datetime as dt + +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 +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.weather import ( + DOMAIN as WEATHER_DOMAIN, + SERVICE_GET_FORECASTS, +) +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import HomeAssistant + + +async def _setup_entry(hass: HomeAssistant, entry: MockConfigEntry) -> None: + """Set up the Met Office config entry.""" + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.LOADED + + +@pytest.mark.freeze_time(dt.datetime(2024, 11, 23, 12, tzinfo=dt.UTC)) +@pytest.mark.usefixtures("wavertree_data") +async def test_diagnostics( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + entry: MockConfigEntry, + snapshot: SnapshotAssertion, +) -> None: + """Test diagnostics before the twice daily forecast is fetched.""" + await _setup_entry(hass, entry) + + assert await get_diagnostics_for_config_entry(hass, hass_client, entry) == snapshot + + +@pytest.mark.freeze_time(dt.datetime(2024, 11, 23, 12, tzinfo=dt.UTC)) +@pytest.mark.usefixtures("wavertree_data") +async def test_diagnostics_twice_daily_fetched( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + entry: MockConfigEntry, + snapshot: SnapshotAssertion, +) -> None: + """Test diagnostics after the twice daily forecast is fetched.""" + await _setup_entry(hass, entry) + # The twice daily forecast is only fetched when it is requested + await hass.services.async_call( + WEATHER_DOMAIN, + SERVICE_GET_FORECASTS, + {"entity_id": "weather.met_office_wavertree", "type": "twice_daily"}, + blocking=True, + return_response=True, + ) + + assert await get_diagnostics_for_config_entry(hass, hass_client, entry) == snapshot diff --git a/tests/components/metoffice/test_weather.py b/tests/components/metoffice/test_weather.py index 5bb0c82a2b55..1c80ed071a83 100644 --- a/tests/components/metoffice/test_weather.py +++ b/tests/components/metoffice/test_weather.py @@ -40,30 +40,6 @@ def no_sensor(): yield mock_setup_entry -@pytest.fixture -async def wavertree_data( - hass: HomeAssistant, requests_mock: requests_mock.Mocker -) -> dict[str, _Matcher]: - """Mock data for the Wavertree location.""" - # all metoffice test data encapsulated in here - mock_json = await async_load_json_object_fixture(hass, "metoffice.json", DOMAIN) - wavertree_hourly = json.dumps(mock_json["wavertree_hourly"]) - wavertree_daily = json.dumps(mock_json["wavertree_daily"]) - - wavertree_hourly_mock = requests_mock.get( - "https://data.hub.api.metoffice.gov.uk/sitespecific/v0/point/hourly", - text=wavertree_hourly, - ) - wavertree_daily_mock = requests_mock.get( - "https://data.hub.api.metoffice.gov.uk/sitespecific/v0/point/daily", - text=wavertree_daily, - ) - return { - "wavertree_hourly_mock": wavertree_hourly_mock, - "wavertree_daily_mock": wavertree_daily_mock, - } - - @pytest.mark.freeze_time(dt.datetime(2024, 11, 23, 12, tzinfo=dt.UTC)) async def test_site_cannot_connect( hass: HomeAssistant,