Fix Freebox disk free space sensor (#99757)

* Fix Freebox disk free space sensor

* Add initial value assert to check results
This commit is contained in:
Quentame 2023-09-07 10:28:08 +02:00 committed by GitHub
parent e1f4a3fa9f
commit 1a22ab77e1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 85 additions and 8 deletions

View File

@ -417,7 +417,6 @@ omit =
homeassistant/components/freebox/device_tracker.py
homeassistant/components/freebox/home_base.py
homeassistant/components/freebox/router.py
homeassistant/components/freebox/sensor.py
homeassistant/components/freebox/switch.py
homeassistant/components/fritz/common.py
homeassistant/components/fritz/device_tracker.py

View File

@ -156,7 +156,12 @@ class FreeboxRouter:
fbx_disks: list[dict[str, Any]] = await self._api.storage.get_disks() or []
for fbx_disk in fbx_disks:
self.disks[fbx_disk["id"]] = fbx_disk
disk: dict[str, Any] = {**fbx_disk}
disk_part: dict[int, dict[str, Any]] = {}
for fbx_disk_part in fbx_disk["partitions"]:
disk_part[fbx_disk_part["id"]] = fbx_disk_part
disk["partitions"] = disk_part
self.disks[fbx_disk["id"]] = disk
async def _update_raids_sensors(self) -> None:
"""Update Freebox raids."""

View File

@ -95,7 +95,7 @@ async def async_setup_entry(
entities.extend(
FreeboxDiskSensor(router, disk, partition, description)
for disk in router.disks.values()
for partition in disk["partitions"]
for partition in disk["partitions"].values()
for description in DISK_PARTITION_SENSORS
)
@ -197,7 +197,8 @@ class FreeboxDiskSensor(FreeboxSensor):
) -> None:
"""Initialize a Freebox disk sensor."""
super().__init__(router, description)
self._partition = partition
self._disk_id = disk["id"]
self._partition_id = partition["id"]
self._attr_name = f"{partition['label']} {description.name}"
self._attr_unique_id = (
f"{router.mac} {description.key} {disk['id']} {partition['id']}"
@ -218,10 +219,10 @@ class FreeboxDiskSensor(FreeboxSensor):
def async_update_state(self) -> None:
"""Update the Freebox disk sensor."""
value = None
if self._partition.get("total_bytes"):
value = round(
self._partition["free_bytes"] * 100 / self._partition["total_bytes"], 2
)
disk: dict[str, Any] = self._router.disks[self._disk_id]
partition: dict[str, Any] = disk["partitions"][self._partition_id]
if partition.get("total_bytes"):
value = round(partition["free_bytes"] * 100 / partition["total_bytes"], 2)
self._attr_native_value = value

View File

@ -0,0 +1,27 @@
"""Common methods used across tests for Freebox."""
from unittest.mock import patch
from homeassistant.components.freebox.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from .const import MOCK_HOST, MOCK_PORT
from tests.common import MockConfigEntry
async def setup_platform(hass: HomeAssistant, platform: str) -> MockConfigEntry:
"""Set up the Freebox platform."""
mock_entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_HOST: MOCK_HOST, CONF_PORT: MOCK_PORT},
unique_id=MOCK_HOST,
)
mock_entry.add_to_hass(hass)
with patch("homeassistant.components.freebox.PLATFORMS", [platform]):
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
return mock_entry

View File

@ -0,0 +1,45 @@
"""Tests for the Freebox sensors."""
from copy import deepcopy
from unittest.mock import Mock
from freezegun.api import FrozenDateTimeFactory
from homeassistant.components.freebox import SCAN_INTERVAL
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.core import HomeAssistant
from .common import setup_platform
from .const import DATA_STORAGE_GET_DISKS
from tests.common import async_fire_time_changed
async def test_disk(
hass: HomeAssistant, freezer: FrozenDateTimeFactory, router: Mock
) -> None:
"""Test disk sensor."""
await setup_platform(hass, SENSOR_DOMAIN)
# Initial state
assert (
router().storage.get_disks.return_value[2]["partitions"][0]["total_bytes"]
== 1960000000000
)
assert (
router().storage.get_disks.return_value[2]["partitions"][0]["free_bytes"]
== 1730000000000
)
assert hass.states.get("sensor.freebox_free_space").state == "88.27"
# Simulate a changed storage size
data_storage_get_disks_changed = deepcopy(DATA_STORAGE_GET_DISKS)
data_storage_get_disks_changed[2]["partitions"][0]["free_bytes"] = 880000000000
router().storage.get_disks.return_value = data_storage_get_disks_changed
# Simulate an update
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
# To execute the save
await hass.async_block_till_done()
assert hass.states.get("sensor.freebox_free_space").state == "44.9"