Don't fail the entry when a per-device status read fails in Fluss+ (#184090)

This commit is contained in:
Francois Botha
2026-12-01 18:18:13 +00:00
committed by GitHub
parent 0ead9a8e25
commit b66de25419
8 changed files with 130 additions and 24 deletions
+1
View File
@@ -239,6 +239,7 @@ homeassistant.components.flexit.*
homeassistant.components.flexit_bacnet.*
homeassistant.components.flic_button.*
homeassistant.components.flow_it.*
homeassistant.components.fluss.*
homeassistant.components.flux_led.*
homeassistant.components.folder_watcher.*
homeassistant.components.foreca.*
+2 -2
View File
@@ -38,8 +38,8 @@ class FlussButton(FlussEntity, ButtonEntity):
@property
@override
def available(self) -> bool:
"""Return True only when the device is online."""
return super().available and self.device["internetConnected"]
"""Return True unless the device is known to be offline."""
return super().available and self.device.get("internetConnected", True)
@override
async def async_press(self) -> None:
+14 -2
View File
@@ -31,6 +31,7 @@ class FlussDataUpdateCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]
) -> None:
"""Initialize the coordinator."""
self.api = FlussApiClient(api_key, session=async_get_clientsession(hass))
self._status_errors: set[str] = set()
super().__init__(
hass,
LOGGER,
@@ -51,9 +52,20 @@ class FlussDataUpdateCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]
response = await self.api.async_get_device_status(device_id)
except FlussDeviceOfflineError:
return {"internetConnected": False}
except FlussApiClientAuthenticationError as err:
raise ConfigEntryAuthFailed(f"Authentication failed: {err}") from err
except FlussApiClientError as err:
raise UpdateFailed(f"Error fetching Fluss device status: {err}") from err
return response["status"]
# Best effort: the trigger buttons work without status, and the API can
# refuse reads for account-level reasons (e.g. an exhausted quota).
if device_id not in self._status_errors:
self._status_errors.add(device_id)
LOGGER.info("Error fetching status for %s: %s", device_id, err)
return {}
if device_id in self._status_errors:
self._status_errors.discard(device_id)
LOGGER.info("Status for %s is available again", device_id)
status: dict[str, Any] = response["status"]
return status
@override
async def _async_update_data(self) -> dict[str, dict[str, Any]]:
+2 -2
View File
@@ -58,8 +58,8 @@ class FlussCover(FlussEntity, CoverEntity):
@property
@override
def available(self) -> bool:
"""Return True only when the device is online."""
return super().available and self.device["internetConnected"]
"""Return True only when the device is known to be online."""
return super().available and self.device.get("internetConnected", False)
@property
@override
Generated
+10
View File
@@ -2137,6 +2137,16 @@ disallow_untyped_defs = true
warn_return_any = true
warn_unreachable = true
[mypy-homeassistant.components.fluss.*]
check_untyped_defs = true
disallow_incomplete_defs = true
disallow_subclassing_any = true
disallow_untyped_calls = true
disallow_untyped_decorators = true
disallow_untyped_defs = true
warn_return_any = true
warn_unreachable = true
[mypy-homeassistant.components.flux_led.*]
check_untyped_defs = true
disallow_incomplete_defs = true
+22 -4
View File
@@ -14,6 +14,7 @@ from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, ButtonService
from homeassistant.components.fluss.const import UPDATE_INTERVAL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, TargetKey
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
@@ -81,13 +82,13 @@ async def test_devices_without_wifi_permission_are_filtered(
mock_api_client.async_get_device_status.assert_called_once_with("allowed")
async def test_button_unavailable_on_status_error(
async def test_button_available_on_status_error(
hass: HomeAssistant,
mock_api_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Buttons become unavailable when a status refresh errors."""
"""Buttons stay usable when a status refresh errors."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("button.device_1").state != STATE_UNAVAILABLE
@@ -98,8 +99,25 @@ async def test_button_unavailable_on_status_error(
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get("button.device_1").state == STATE_UNAVAILABLE
assert hass.states.get("button.device_2").state == STATE_UNAVAILABLE
assert hass.states.get("button.device_1").state != STATE_UNAVAILABLE
assert hass.states.get("button.device_2").state != STATE_UNAVAILABLE
async def test_buttons_setup_with_failing_status(
hass: HomeAssistant,
mock_api_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""A failing status call must not prevent setup from completing."""
mock_api_client.async_get_device_status.side_effect = FlussApiClientError(
"API usage limit exceeded"
)
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
assert hass.states.get("button.device_1").state != STATE_UNAVAILABLE
assert hass.states.get("button.device_2").state != STATE_UNAVAILABLE
async def test_button_unavailable_when_internet_disconnected(
+3 -1
View File
@@ -25,6 +25,7 @@ from homeassistant.const import (
STATE_CLOSED,
STATE_OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
@@ -106,7 +107,7 @@ async def test_cover_unavailable_on_status_error(
entity_registry: er.EntityRegistry,
freezer: FrozenDateTimeFactory,
) -> None:
"""A failed per-device status fetch fails the refresh and marks the cover unavailable."""
"""A failed status fetch leaves the cover unavailable but the button usable."""
mock_api_client.async_get_device_status.return_value = {
"status": {"internetConnected": True, "openCloseStatus": "Closed"}
}
@@ -119,6 +120,7 @@ async def test_cover_unavailable_on_status_error(
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(ENTITY_ID_1).state == STATE_UNAVAILABLE
assert hass.states.get("button.device_1").state == STATE_UNKNOWN
assert entity_registry.async_get(ENTITY_ID_1) is not None
+76 -13
View File
@@ -1,5 +1,6 @@
"""Test script for Fluss+ integration initialization."""
import logging
from typing import Any
from unittest.mock import AsyncMock
@@ -9,9 +10,11 @@ from fluss_api import (
FlussApiClientError,
FlussDeviceOfflineError,
)
from freezegun.api import FrozenDateTimeFactory
import pytest
from pytest_homeassistant.common import MockConfigEntry
from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed
from homeassistant.components.fluss.const import UPDATE_INTERVAL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
@@ -78,27 +81,87 @@ async def test_offline_device_stays_unavailable(
assert hass.states.get("button.device_2").state == STATE_UNKNOWN
@pytest.mark.parametrize(
"exception",
[
FlussApiClientError("boom"),
FlussApiClientAuthenticationError("permission revoked"),
],
)
async def test_failed_status_fails_update(
async def test_failed_status_does_not_fail_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api_client: AsyncMock,
exception: Exception,
) -> None:
"""A non-offline status error fails the whole refresh."""
"""A non-offline status error is best-effort: setup still completes."""
async def _status(device_id: str) -> dict[str, Any]:
if device_id == "2a303030sdj1":
raise exception
raise FlussApiClientError("API usage limit exceeded")
return {"status": {"internetConnected": True}}
mock_api_client.async_get_device_status.side_effect = _status
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
assert mock_config_entry.state is ConfigEntryState.LOADED
# device_1 has no status; it stays usable as a trigger button
assert hass.states.get("button.device_1").state == STATE_UNKNOWN
assert hass.states.get("button.device_2").state == STATE_UNKNOWN
async def test_status_auth_error_starts_reauth(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api_client: AsyncMock,
) -> None:
"""A 401 on the status endpoint is account-level: ask for reauth, do not hide it."""
mock_api_client.async_get_device_status.side_effect = (
FlussApiClientAuthenticationError("Invalid credentials")
)
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
reauth_flows = [
flow
for flow in hass.config_entries.flow.async_progress()
if flow["context"]["source"] == "reauth"
]
assert len(reauth_flows) == 1
async def test_status_error_logged_once_until_recovery(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api_client: AsyncMock,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""A refused status read is logged once, and its recovery is logged once."""
caplog.set_level(logging.INFO, logger="homeassistant.components.fluss")
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
failed = "Error fetching status for 2a303030sdj1"
recovered = "Status for 2a303030sdj1 is available again"
def _logged(message: str) -> list[logging.LogRecord]:
return [record for record in caplog.records if message in record.message]
caplog.clear()
mock_api_client.async_get_device_status.side_effect = FlussApiClientError(
"API usage limit exceeded"
)
for _ in range(2):
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert len(_logged(failed)) == 1
assert _logged(failed)[0].levelno == logging.INFO
mock_api_client.async_get_device_status.side_effect = None
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert len(_logged(recovered)) == 1
assert _logged(recovered)[0].levelno == logging.INFO
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert len(_logged(recovered)) == 1