1
0
mirror of https://github.com/home-assistant/core.git synced 2026-02-15 07:36:16 +00:00

Handle missing battery stats in systemmonitor (#158287)

Co-authored-by: mik-laj <12058428+mik-laj@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Joostlek <joostlek@outlook.com>
This commit is contained in:
Kamil Breguła
2026-02-03 10:54:31 +01:00
committed by GitHub
parent e6a60dfe50
commit 4b9d28d0e5
2 changed files with 40 additions and 0 deletions

View File

@@ -284,6 +284,8 @@ class SystemMonitorCoordinator(TimestampDataUpdateCoordinator[SensorData]):
try:
battery = self._psutil.sensors_battery()
_LOGGER.debug("battery: %s", battery)
except (FileNotFoundError, PermissionError) as err:
_LOGGER.debug("OS error when accessing battery sensors: %s", err)
except (AttributeError, FileNotFoundError):
_LOGGER.debug("OS does not provide battery sensors")

View File

@@ -389,6 +389,44 @@ async def test_exception_handling_disk_sensor(
assert disk_sensor.attributes["unit_of_measurement"] == "%"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.freeze_time("2024-02-24 15:00:00", tz_offset=0)
@pytest.mark.parametrize("exception_class", [FileNotFoundError, PermissionError])
async def test_exception_handling_battery_sensor(
hass: HomeAssistant,
mock_psutil: Mock,
mock_os: Mock,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
exception_class: type[Exception],
) -> None:
"""Test the battery failures."""
mock_psutil.sensors_battery.side_effect = exception_class(
"[Errno 2] No such file or directory: '/sys/class/power_supply'"
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert (temp_entity := hass.states.get("sensor.system_monitor_battery"))
assert temp_entity.state == STATE_UNAVAILABLE
assert (temp_entity := hass.states.get("sensor.system_monitor_battery_empty"))
assert temp_entity.state == STATE_UNAVAILABLE
assert "OS error when accessing battery sensors" in caplog.text
mock_psutil.sensors_battery.side_effect = None
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert (temp_entity := hass.states.get("sensor.system_monitor_battery"))
assert temp_entity.state == "93"
assert (temp_entity := hass.states.get("sensor.system_monitor_battery_empty"))
assert temp_entity.state == "2024-02-24T19:38:00+00:00"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_cpu_percentage_is_zero_returns_unknown(
hass: HomeAssistant,