mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 12:21:04 -04:00
Log Fuelprices.dk outages at info level (#193785)
This commit is contained in:
@@ -5,14 +5,17 @@ from datetime import timedelta
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, override
|
||||
|
||||
from aiohttp import ClientResponseError
|
||||
from aiohttp import ClientConnectionError, ClientResponseError
|
||||
from pybraendstofpriser import Braendstofpriser
|
||||
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryAuthFailed
|
||||
from homeassistant.helpers.aiohttp_client import SERVER_SOFTWARE
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
|
||||
from homeassistant.helpers.update_coordinator import (
|
||||
DataUpdateCoordinator,
|
||||
UpdateFailedUnreachable,
|
||||
)
|
||||
|
||||
from .const import CONF_STATION, DOMAIN, SUBENTRY_TYPE_STATION
|
||||
|
||||
@@ -68,7 +71,27 @@ class FuelPricesDKCoordinator(DataUpdateCoordinator[dict[int, FuelPricesDKStatio
|
||||
except ClientResponseError as exc:
|
||||
if exc.status == 401:
|
||||
raise ConfigEntryAuthFailed(exc) from exc
|
||||
if exc.status == 429:
|
||||
raise UpdateFailedUnreachable(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="rate_limit_exceeded",
|
||||
) from exc
|
||||
if 500 <= exc.status < 600:
|
||||
raise UpdateFailedUnreachable(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="server_error",
|
||||
) from exc
|
||||
raise
|
||||
except TimeoutError as exc:
|
||||
raise UpdateFailedUnreachable(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="request_timeout",
|
||||
) from exc
|
||||
except ClientConnectionError as exc:
|
||||
raise UpdateFailedUnreachable(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="cannot_connect",
|
||||
) from exc
|
||||
|
||||
return {
|
||||
item["station"]["id"]: FuelPricesDKStation(
|
||||
|
||||
@@ -43,7 +43,7 @@ rules:
|
||||
docs-installation-parameters: todo
|
||||
entity-unavailable: done
|
||||
integration-owner: done
|
||||
log-when-unavailable: todo
|
||||
log-when-unavailable: done
|
||||
parallel-updates: done
|
||||
reauthentication-flow: done
|
||||
test-coverage: done
|
||||
|
||||
@@ -93,5 +93,19 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"exceptions": {
|
||||
"cannot_connect": {
|
||||
"message": "[%key:common::config_flow::error::cannot_connect%]"
|
||||
},
|
||||
"rate_limit_exceeded": {
|
||||
"message": "[%key:component::fuelprices_dk::config::abort::rate_limit_exceeded%]"
|
||||
},
|
||||
"request_timeout": {
|
||||
"message": "[%key:common::config_flow::error::timeout_connect%]"
|
||||
},
|
||||
"server_error": {
|
||||
"message": "Fuelprices.dk returned a server error."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, call
|
||||
|
||||
from aiohttp import ClientConnectionError
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
from pybraendstofpriser import Flist
|
||||
import pytest
|
||||
@@ -130,12 +131,39 @@ async def test_stations_use_flist(
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("side_effect", "expected_state"),
|
||||
("side_effect", "expected_state", "expected_translation"),
|
||||
[
|
||||
(client_error(401), ConfigEntryState.SETUP_ERROR),
|
||||
(client_error(500), ConfigEntryState.SETUP_RETRY),
|
||||
pytest.param(
|
||||
client_error(401),
|
||||
ConfigEntryState.SETUP_ERROR,
|
||||
(None, None),
|
||||
id="auth_failed",
|
||||
),
|
||||
pytest.param(
|
||||
client_error(429),
|
||||
ConfigEntryState.SETUP_RETRY,
|
||||
(DOMAIN, "rate_limit_exceeded"),
|
||||
id="rate_limit",
|
||||
),
|
||||
pytest.param(
|
||||
client_error(500),
|
||||
ConfigEntryState.SETUP_RETRY,
|
||||
(DOMAIN, "server_error"),
|
||||
id="server_error",
|
||||
),
|
||||
pytest.param(
|
||||
TimeoutError(),
|
||||
ConfigEntryState.SETUP_RETRY,
|
||||
(DOMAIN, "request_timeout"),
|
||||
id="timeout",
|
||||
),
|
||||
pytest.param(
|
||||
ClientConnectionError("Connection failed"),
|
||||
ConfigEntryState.SETUP_RETRY,
|
||||
(DOMAIN, "cannot_connect"),
|
||||
id="cannot_connect",
|
||||
),
|
||||
],
|
||||
ids=["auth_failed", "cannot_connect"],
|
||||
)
|
||||
async def test_setup_error_handling(
|
||||
hass: HomeAssistant,
|
||||
@@ -143,6 +171,7 @@ async def test_setup_error_handling(
|
||||
mock_config_entry: MockConfigEntry,
|
||||
side_effect: Exception,
|
||||
expected_state: ConfigEntryState,
|
||||
expected_translation: tuple[str | None, str | None],
|
||||
) -> None:
|
||||
"""Test setup handles API errors during the first refresh."""
|
||||
mock_braendstofpriser.get_prices_bulk.side_effect = side_effect
|
||||
@@ -150,6 +179,10 @@ async def test_setup_error_handling(
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
assert mock_config_entry.state is expected_state
|
||||
assert (
|
||||
mock_config_entry.error_reason_translation_domain,
|
||||
mock_config_entry.error_reason_translation_key,
|
||||
) == expected_translation
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"""Test sensor platform for Fuelprices.dk."""
|
||||
|
||||
import logging
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
from aiohttp import ClientConnectionError
|
||||
from freezegun.api import FrozenDateTimeFactory
|
||||
import pytest
|
||||
from pytest_homeassistant.common import (
|
||||
@@ -200,21 +202,33 @@ async def test_station_missing_at_setup(
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mock_config_entry", [2], indirect=True)
|
||||
@pytest.mark.parametrize("status", [500, 429])
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
pytest.param(client_error(500), id="server_error"),
|
||||
pytest.param(client_error(429), id="rate_limit"),
|
||||
pytest.param(ClientConnectionError("Connection failed"), id="connection"),
|
||||
pytest.param(TimeoutError(), id="timeout"),
|
||||
],
|
||||
)
|
||||
async def test_failed_update_recovers(
|
||||
hass: HomeAssistant,
|
||||
mock_braendstofpriser: AsyncMock,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
freezer: FrozenDateTimeFactory,
|
||||
status: int,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
error: Exception,
|
||||
) -> None:
|
||||
"""Test a failed bulk request marks all stations unavailable until recovery."""
|
||||
mock_braendstofpriser.get_prices_bulk.return_value = (
|
||||
await async_load_json_array_fixture(hass, "bulk_prices.json", DOMAIN)
|
||||
)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
logger = "homeassistant.components.fuelprices_dk.coordinator"
|
||||
caplog.set_level(logging.INFO, logger=logger)
|
||||
caplog.clear()
|
||||
|
||||
mock_braendstofpriser.get_prices_bulk.side_effect = client_error(status)
|
||||
mock_braendstofpriser.get_prices_bulk.side_effect = error
|
||||
freezer.tick(3600)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
@@ -222,6 +236,18 @@ async def test_failed_update_recovers(
|
||||
assert hass.states.get("sensor.aarhus_c_blyfri95").state == STATE_UNAVAILABLE
|
||||
assert hass.states.get("sensor.aarhus_n_blyfri95").state == STATE_UNAVAILABLE
|
||||
|
||||
outage_logs = [record for record in caplog.records if record.name == logger]
|
||||
assert len(outage_logs) == 1
|
||||
assert outage_logs[0].levelno == logging.INFO
|
||||
assert "is unavailable" in outage_logs[0].getMessage()
|
||||
caplog.clear()
|
||||
|
||||
freezer.tick(3600)
|
||||
async_fire_time_changed(hass)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert not [record for record in caplog.records if record.name == logger]
|
||||
|
||||
mock_braendstofpriser.get_prices_bulk.side_effect = None
|
||||
freezer.tick(3600)
|
||||
async_fire_time_changed(hass)
|
||||
@@ -229,6 +255,9 @@ async def test_failed_update_recovers(
|
||||
|
||||
assert hass.states.get("sensor.aarhus_c_blyfri95").state == "14.29"
|
||||
assert hass.states.get("sensor.aarhus_n_blyfri95").state == "15.29"
|
||||
assert [record for record in caplog.record_tuples if record[0] == logger] == [
|
||||
(logger, logging.INFO, f"Fetching {DOMAIN} data recovered")
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mock_config_entry", [2], indirect=True)
|
||||
|
||||
Reference in New Issue
Block a user