Make Portainer disk space sensors opt-in (#173307)

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Erwin Douna
2026-11-12 18:24:32 +01:00
committed by GitHub
co-authored by Copilot Autofix powered by AI
parent 613267a523
commit 79fd2b4e87
12 changed files with 481 additions and 98 deletions
+48 -15
View File
@@ -101,21 +101,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: PortainerConfigEntry) ->
system_version_coordinator = PortainerSystemVersionCoordinator(hass, entry, client)
coordinator.system_version = system_version_coordinator
async def _defer_initial_refreshes(_: HomeAssistant) -> None:
"""Defer the first refresh until Home Assistant has started."""
hass.async_create_task(
docker_disk_space_coordinator.async_refresh(),
"portainer_docker_disk_space_initial_refresh",
)
hass.async_create_task(
system_version_coordinator.async_refresh(),
"portainer_system_version_initial_refresh",
)
# On lower-end hardware, the DF endpoint can take long, and the version check
# waits for GitHub. Do not block the setup, but defer both until HA has started
entry.async_on_unload(async_at_started(hass, _defer_initial_refreshes))
entry.runtime_data = coordinator
entry.async_on_unload(entry.add_update_listener(_async_update_listener))
@@ -135,6 +120,22 @@ async def async_setup_entry(hass: HomeAssistant, entry: PortainerConfigEntry) ->
await hass.config_entries.async_forward_entry_setups(entry, _PLATFORMS)
async def _defer_initial_refreshes(_: HomeAssistant) -> None:
"""Defer the first refresh until Home Assistant has started."""
hass.async_create_task(
docker_disk_space_coordinator.async_refresh(),
"portainer_docker_disk_space_initial_refresh",
)
hass.async_create_task(
system_version_coordinator.async_refresh(),
"portainer_system_version_initial_refresh",
)
# On lower-end hardware, the DF endpoint can take long, and the version check
# waits for GitHub. Do not block the setup, but defer both until HA has started.
# Registered after the platforms, so the DF refresh sees the enabled entities.
entry.async_on_unload(async_at_started(hass, _defer_initial_refreshes))
@callback
def _start_watcher(_hass: HomeAssistant) -> None:
"""Start the image watcher in the event loop."""
@@ -352,6 +353,38 @@ async def async_migrate_entry(hass: HomeAssistant, entry: PortainerConfigEntry)
hass.config_entries.async_update_entry(entry=entry, minor_version=2)
hass.config_entries.async_schedule_reload(entry.entry_id)
if entry.minor_version < 3:
_async_disable_disk_space_sensors(hass, entry)
hass.config_entries.async_update_entry(entry=entry, minor_version=3)
# Fixed at the sensors that existed when they became opt-in.
_DISK_SPACE_TRANSLATION_KEYS = {
"container_disk_usage_reclaimable",
"container_disk_usage_total_size",
"image_disk_usage_reclaimable",
"image_disk_usage_total_size",
"volume_disk_usage_total_size",
"volume_size",
}
@callback
def _async_disable_disk_space_sensors(
hass: HomeAssistant, entry: PortainerConfigEntry
) -> None:
"""Disable the disk space sensors, which became opt-in as Docker computes them slowly."""
entity_registry = er.async_get(hass)
for reg_entry in er.async_entries_for_config_entry(entity_registry, entry.entry_id):
if (
reg_entry.domain == Platform.SENSOR
and reg_entry.translation_key in _DISK_SPACE_TRANSLATION_KEYS
and reg_entry.disabled_by in (None, er.RegistryEntryDisabler.DEVICE)
):
entity_registry.async_update_entity(
reg_entry.entity_id, disabled_by=er.RegistryEntryDisabler.INTEGRATION
)
async def async_remove_config_entry_device(
hass: HomeAssistant,
@@ -79,7 +79,7 @@ class PortainerConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Portainer."""
VERSION = 5
MINOR_VERSION = 2
MINOR_VERSION = 3
@classmethod
@callback
@@ -2,6 +2,7 @@
from abc import abstractmethod
import asyncio
from collections import Counter
from collections.abc import Awaitable, Callable
import dataclasses
from dataclasses import dataclass
@@ -24,10 +25,8 @@ from pyportainer import (
from pyportainer.models.docker import (
DockerContainer,
DockerContainerStats,
DockerDFType,
DockerSystemDF,
DockerVolume,
DockerVolumeUsageData,
LocalImageInformation,
PortainerImageUpdateStatus,
)
@@ -110,6 +109,14 @@ class PortainerVolumeData:
volume: DockerVolume
@dataclass(slots=True)
class PortainerDockerDiskSpaceData:
"""Docker disk space data of an endpoint."""
system_df: DockerSystemDF
volumes: dict[str, dict[str, Any]]
class PortainerBaseCoordinator[_DataT](DataUpdateCoordinator[_DataT]):
"""Base coordinator for Portainer."""
@@ -305,19 +312,10 @@ class PortainerCoordinator(
continue
try:
(
containers,
docker_version,
docker_info,
docker_system_df,
volumes,
) = await asyncio.gather(
containers, docker_version, docker_info, volumes = await asyncio.gather(
self.portainer.get_containers(endpoint.id),
self.portainer.docker_version(endpoint.id),
self.portainer.docker_info(endpoint.id),
self.portainer.docker_system_df(
endpoint.id, data_type=DockerDFType.VOLUME, verbose=True
),
self.portainer.get_volumes(endpoint.id),
)
@@ -418,18 +416,10 @@ class PortainerCoordinator(
else None,
)
volume_usage_map = {
item["Name"]: item
for item in (docker_system_df.volume_disk_usage.items or [])
volume_map = {
volume.name: PortainerVolumeData(volume=volume)
for volume in volumes
}
volume_map: dict[str, PortainerVolumeData] = {}
for volume in volumes:
if item := volume_usage_map.get(volume.name):
volume.usage_data = DockerVolumeUsageData(
size=item["UsageData"]["Size"],
ref_count=item["UsageData"]["RefCount"],
)
volume_map[volume.name] = PortainerVolumeData(volume=volume)
# Separately fetch stats for active containers
active_containers = [
@@ -819,32 +809,62 @@ class PortainerCoordinator(
class PortainerDockerDiskSpaceCoordinator(
PortainerBaseCoordinator[dict[int, DockerSystemDF]]
PortainerBaseCoordinator[dict[int, PortainerDockerDiskSpaceData]]
):
"""Data Update Coordinator for Docker disk space."""
"""Data Update Coordinator for Docker disk space.
Docker sums up every file of every volume for this, which can take long on
slower hosts, so only endpoints with an enabled disk space entity are fetched.
"""
config_entry: PortainerConfigEntry
_update_interval = DEFAULT_DF_SCAN_INTERVAL
def __init__(
self,
hass: HomeAssistant,
config_entry: PortainerConfigEntry,
portainer: Portainer,
) -> None:
"""Initialize."""
super().__init__(hass, config_entry, portainer)
self._entities_per_endpoint: Counter[int] = Counter()
@callback
def async_add_endpoint_entity(self, endpoint_id: int) -> Callable[[], None]:
"""Fetch an endpoint while it has an enabled entity; return the remover."""
self._entities_per_endpoint[endpoint_id] += 1
@callback
def _async_remove() -> None:
self._entities_per_endpoint[endpoint_id] -= 1
if not self._entities_per_endpoint[endpoint_id]:
del self._entities_per_endpoint[endpoint_id]
return _async_remove
@override
async def update_data(self) -> dict[int, DockerSystemDF]:
async def update_data(self) -> dict[int, PortainerDockerDiskSpaceData]:
"""Fetch Docker disk space data independently from Portainer API."""
if not self._entities_per_endpoint:
return {}
endpoints = await self.portainer.get_endpoints()
subentry_endpoint_ids = {
subentry.unique_id
for subentry in self.config_entry.subentries.values()
if subentry.unique_id
}
results: dict[int, DockerSystemDF] = {}
results: dict[int, PortainerDockerDiskSpaceData] = {}
for endpoint in endpoints:
if (
endpoint.status == EndpointStatus.DOWN
or str(endpoint.id) not in subentry_endpoint_ids
or endpoint.id not in self._entities_per_endpoint
):
continue
try:
results[endpoint.id] = await self.portainer.docker_system_df(
endpoint.id
system_df = await self.portainer.docker_system_df(
endpoint.id, verbose=True
)
except PortainerTimeoutError:
_LOGGER.warning(
@@ -853,6 +873,13 @@ class PortainerDockerDiskSpaceCoordinator(
endpoint.id,
)
continue
results[endpoint.id] = PortainerDockerDiskSpaceData(
system_df=system_df,
volumes={
item["Name"]: item
for item in system_df.volume_disk_usage.items or []
},
)
return results
+99 -29
View File
@@ -1,6 +1,6 @@
"""Base class for Portainer entities."""
from typing import TYPE_CHECKING, override
from typing import TYPE_CHECKING, Any, override
from pyportainer.models.docker import DockerVolume
from yarl import URL
@@ -36,6 +36,26 @@ class PortainerDockerDiskSpaceCoordinatorEntity(
"""Base class for Portainer entities using the Docker disk space coordinator."""
_attr_has_entity_name = True
_attr_entity_registry_enabled_default = False
endpoint_id: int
@override
async def async_added_to_hass(self) -> None:
"""Let the coordinator fetch this entity's endpoint."""
await super().async_added_to_hass()
self.async_on_remove(
self.coordinator.async_add_endpoint_entity(self.endpoint_id)
)
@property
@override
def available(self) -> bool:
"""Return if the endpoint has disk space data."""
return (
super().available
and self.coordinator.data is not None
and self.endpoint_id in self.coordinator.data
)
class PortainerServerEntity(CoordinatorEntity[PortainerSystemVersionCoordinator]):
@@ -276,15 +296,28 @@ class PortainerDockerSystemDiskSpaceEndpointEntity(
f"_{entity_description.key}"
)
@property
@override
def available(self) -> bool:
"""Return if the device is available."""
return (
super().available
and self.coordinator.data is not None
and self.endpoint_id in self.coordinator.data
)
def _volume_device_info(
coordinator: PortainerCoordinator | PortainerDockerDiskSpaceCoordinator,
endpoint_id: int,
volume_name: str,
) -> DeviceInfo:
"""Return the device info of a volume."""
entry = coordinator.config_entry
return DeviceInfo(
identifiers={(DOMAIN, f"{entry.entry_id}_{endpoint_id}_volume_{volume_name}")},
manufacturer=DEFAULT_NAME,
configuration_url=URL(
f"{entry.data[CONF_URL]}#!/{endpoint_id}/docker/volumes/{volume_name}"
),
model="Volume",
name=volume_name,
via_device_id=dr.async_get_device_id_by_identifier(
coordinator.hass,
(DOMAIN, f"{entry.entry_id}_{endpoint_id}"),
config_entry_id=entry.entry_id,
),
)
class PortainerVolumeEntity(PortainerCoordinatorEntity):
@@ -304,25 +337,8 @@ class PortainerVolumeEntity(PortainerCoordinatorEntity):
self.volume_name = device_info.name
self.endpoint_id = via_device.endpoint.id
self.endpoint_name = via_device.endpoint.name
self._attr_device_info = DeviceInfo(
identifiers={
(
DOMAIN,
f"{coordinator.config_entry.entry_id}_{self.endpoint_id}_volume_{self.volume_name}",
)
},
manufacturer=DEFAULT_NAME,
configuration_url=URL(
f"{coordinator.config_entry.data[CONF_URL]}#!/{self.endpoint_id}/docker/volumes/{self.volume_name}"
),
model="Volume",
name=self.volume_name,
via_device_id=dr.async_get_device_id_by_identifier(
coordinator.hass,
(DOMAIN, f"{coordinator.config_entry.entry_id}_{self.endpoint_id}"),
config_entry_id=coordinator.config_entry.entry_id,
),
self._attr_device_info = _volume_device_info(
coordinator, self.endpoint_id, self.volume_name
)
self._attr_unique_id = (
f"{coordinator.config_entry.entry_id}"
@@ -344,3 +360,57 @@ class PortainerVolumeEntity(PortainerCoordinatorEntity):
def volume_data(self) -> PortainerVolumeData:
"""Return the coordinator data for this volume."""
return self.coordinator.data[self.endpoint_id].volumes[self.volume_name]
class PortainerDockerDiskSpaceVolumeEntity(PortainerDockerDiskSpaceCoordinatorEntity):
"""Base class for volume entities backed by the Docker disk space coordinator."""
def __init__(
self,
coordinator: PortainerDockerDiskSpaceCoordinator,
entity_description: EntityDescription,
device_info: DockerVolume,
via_device: PortainerCoordinatorData,
) -> None:
"""Initialize a Portainer volume disk space entity."""
super().__init__(coordinator)
self.entity_description = entity_description
self.volume_name = device_info.name
self.endpoint_id = via_device.endpoint.id
self._attr_device_info = _volume_device_info(
coordinator, self.endpoint_id, self.volume_name
)
self._attr_unique_id = (
f"{coordinator.config_entry.entry_id}"
f"_{self.endpoint_id}_volume"
f"_{self.volume_name}_{entity_description.key}"
)
@override
async def async_added_to_hass(self) -> None:
"""Also follow the main coordinator, which notices deleted volumes."""
await super().async_added_to_hass()
self.async_on_remove(
self.coordinator.config_entry.runtime_data.async_add_listener(
self._handle_coordinator_update
)
)
@property
@override
def available(self) -> bool:
"""Return if the volume still exists and its endpoint has disk space data."""
data = self.coordinator.config_entry.runtime_data.data
return (
super().available
and self.endpoint_id in data
and self.volume_name in data[self.endpoint_id].volumes
)
@property
def volume_usage(self) -> dict[str, Any] | None:
"""Return the disk usage item for this volume.
Docker only measures volumes of the local driver without mount options.
"""
return self.coordinator.data[self.endpoint_id].volumes.get(self.volume_name)
+60 -16
View File
@@ -4,7 +4,7 @@ from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from itertools import chain
from typing import TYPE_CHECKING, override
from typing import TYPE_CHECKING, Any, override
from pyportainer import StackType
from pyportainer.models.docker import DockerContainerState, DockerSystemDF
@@ -30,6 +30,7 @@ from .coordinator import (
)
from .entity import (
PortainerContainerEntity,
PortainerDockerDiskSpaceVolumeEntity,
PortainerDockerSystemDiskSpaceEndpointEntity,
PortainerEndpointEntity,
PortainerStackEntity,
@@ -76,6 +77,13 @@ class PortainerVolumeSensorEntityDescription(SensorEntityDescription):
value_fn: Callable[[PortainerVolumeData], StateType]
@dataclass(frozen=True, kw_only=True)
class PortainerVolumeDiskSpaceSensorEntityDescription(SensorEntityDescription):
"""Class to hold Portainer volume disk space sensor description."""
value_fn: Callable[[dict[str, Any]], StateType]
CONTAINER_SENSORS: tuple[PortainerContainerSensorEntityDescription, ...] = (
PortainerContainerSensorEntityDescription(
key="image",
@@ -410,11 +418,16 @@ VOLUME_SENSORS: tuple[PortainerVolumeSensorEntityDescription, ...] = (
translation_key="volume_driver",
value_fn=lambda data: data.volume.driver,
),
PortainerVolumeSensorEntityDescription(
)
VOLUME_DISK_SPACE_SENSORS: tuple[
PortainerVolumeDiskSpaceSensorEntityDescription, ...
] = (
PortainerVolumeDiskSpaceSensorEntityDescription(
key="volume_size",
translation_key="volume_size",
value_fn=lambda data: (
data.volume.usage_data.size if data.volume.usage_data else None
# Docker reports -1 when it fails to walk the volume directory
value_fn=lambda usage: (
size if (size := usage["UsageData"]["Size"]) >= 0 else None
),
device_class=SensorDeviceClass.DATA_SIZE,
state_class=SensorStateClass.MEASUREMENT,
@@ -519,18 +532,33 @@ async def async_setup_entry(
async_add_entities_by_subentry(
async_add_entities,
coordinator.subentry_id_for_endpoint,
(
chain(
(
PortainerVolumeSensor(
coordinator,
entity_description,
volume.volume,
endpoint,
),
endpoint.id,
)
for (endpoint, volume) in volumes
for entity_description in VOLUME_SENSORS
(
PortainerVolumeSensor(
coordinator,
entity_description,
volume.volume,
endpoint,
),
endpoint.id,
)
for (endpoint, volume) in volumes
for entity_description in VOLUME_SENSORS
),
(
(
PortainerVolumeDiskSpaceSensor(
ds_coordinator,
entity_description,
volume.volume,
endpoint,
),
endpoint.id,
)
for (endpoint, volume) in volumes
for entity_description in VOLUME_DISK_SPACE_SENSORS
),
),
)
@@ -606,7 +634,7 @@ class PortainerDockerSystemDiskSpaceSensor(
def native_value(self) -> StateType:
"""Return the state of the sensor."""
endpoint_data = self.coordinator.data[self._device_info.endpoint.id]
return self.entity_description.value_fn(endpoint_data)
return self.entity_description.value_fn(endpoint_data.system_df)
class PortainerStackSensor(PortainerStackEntity, SensorEntity):
@@ -631,3 +659,19 @@ class PortainerVolumeSensor(PortainerVolumeEntity, SensorEntity):
def native_value(self) -> StateType:
"""Return the state of the sensor."""
return self.entity_description.value_fn(self.volume_data)
class PortainerVolumeDiskSpaceSensor(
PortainerDockerDiskSpaceVolumeEntity, SensorEntity
):
"""Representation of a Portainer volume disk space sensor."""
entity_description: PortainerVolumeDiskSpaceSensorEntityDescription
@property
@override
def native_value(self) -> StateType:
"""Return the state of the sensor."""
if (usage := self.volume_usage) is None:
return None
return self.entity_description.value_fn(usage)
+1 -1
View File
@@ -197,7 +197,7 @@ def mock_config_entry() -> MockConfigEntry:
unique_id=TEST_INSTANCE_ID,
entry_id=TEST_ENTRY,
version=5,
minor_version=2,
minor_version=3,
subentries_data=[
ConfigSubentryData(
data={},
@@ -32,6 +32,13 @@
"Size": 67108864,
"RefCount": 1
}
},
{
"Name": "dashy_config",
"UsageData": {
"Size": -1,
"RefCount": 1
}
}
]
},
@@ -12,7 +12,7 @@
}),
'domain': 'portainer',
'entry_id': 'portainer_test_entry_123',
'minor_version': 2,
'minor_version': 3,
'options': dict({
}),
'pref_disable_new_entities': False,
@@ -107,7 +107,7 @@
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '0.0029296875',
'state': 'unknown',
})
# ---
# name: test_all_entities[sensor.dashy_containers-entry]
@@ -364,7 +364,7 @@ async def test_environment_subentry_flow(
data=MOCK_TEST_CONFIG,
unique_id=TEST_INSTANCE_ID,
version=5,
minor_version=2,
minor_version=3,
subentries_data=[
ConfigSubentryData(
data={},
@@ -417,7 +417,7 @@ async def test_environment_subentry_flow_exceptions(
data=MOCK_TEST_CONFIG,
unique_id=TEST_INSTANCE_ID,
version=5,
minor_version=2,
minor_version=3,
subentries_data=[
ConfigSubentryData(
data={},
@@ -489,7 +489,7 @@ async def test_environment_subentry_flow_race_condition(
data=MOCK_TEST_CONFIG,
unique_id=TEST_INSTANCE_ID,
version=5,
minor_version=2,
minor_version=3,
subentries_data=[
ConfigSubentryData(
data={},
+69 -1
View File
@@ -248,7 +248,7 @@ async def test_migration_v5_1_to_v5_2(
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.minor_version == 2
assert entry.minor_version == 3
assert len(entry.subentries) == 1
subentry = next(iter(entry.subentries.values()))
assert subentry.subentry_type == SUBENTRY_TYPE_ENVIRONMENT
@@ -266,6 +266,74 @@ async def test_migration_v5_1_to_v5_2(
assert endpoint_entity_after.unique_id == f"{entry.entry_id}_1_api_version"
@pytest.mark.parametrize(
("unique_id_suffix", "translation_key", "disabled_by", "expected_disabled_by"),
[
pytest.param(
"1_image_disk_usage_total_size",
"image_disk_usage_total_size",
None,
er.RegistryEntryDisabler.INTEGRATION,
id="endpoint_disk_space",
),
pytest.param(
"1_volume_myvolume_volume_size",
"volume_size",
None,
er.RegistryEntryDisabler.INTEGRATION,
id="volume_size",
),
pytest.param(
"1_api_version",
"api_version",
None,
None,
id="not_disk_space",
),
pytest.param(
"1_image_disk_usage_total_size",
"image_disk_usage_total_size",
er.RegistryEntryDisabler.USER,
er.RegistryEntryDisabler.USER,
id="user_disabled",
),
],
)
async def test_migration_v5_2_to_v5_3(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
entity_registry: er.EntityRegistry,
unique_id_suffix: str,
translation_key: str,
disabled_by: er.RegistryEntryDisabler | None,
expected_disabled_by: er.RegistryEntryDisabler | None,
) -> None:
"""Test migration disables the disk space sensors."""
entry = MockConfigEntry(
domain=DOMAIN,
data=MOCK_TEST_CONFIG,
unique_id=TEST_INSTANCE_ID,
version=5,
minor_version=2,
)
entry.add_to_hass(hass)
entity = entity_registry.async_get_or_create(
domain="sensor",
platform=DOMAIN,
unique_id=f"{entry.entry_id}_{unique_id_suffix}",
config_entry=entry,
translation_key=translation_key,
disabled_by=disabled_by,
)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.minor_version == 3
assert (entity_after := entity_registry.async_get(entity.entity_id))
assert entity_after.disabled_by is expected_disabled_by
async def test_unload_entry(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
+135 -1
View File
@@ -31,6 +31,8 @@ from homeassistant.util import dt as dt_util
from . import setup_integration
CPU_USAGE_ENTITY_ID = "sensor.focused_einstein_cpu_usage_total"
DISK_USAGE_ENTITY_ID = "sensor.my_environment_image_disk_usage_total_size"
VOLUME_SIZE_ENTITY_ID = "sensor.myvolume_volume_size"
@pytest.fixture(autouse=True)
@@ -88,7 +90,7 @@ async def test_df_endpoint_timeout_only_marks_that_endpoint_unavailable(
docker_system_df = mock_portainer_client.docker_system_df.return_value
async def _docker_system_df(endpoint_id: int) -> Any:
async def _docker_system_df(endpoint_id: int, **kwargs: Any) -> Any:
if endpoint_id == 42:
raise PortainerTimeoutError("timeout")
return docker_system_df
@@ -109,6 +111,138 @@ async def test_df_endpoint_timeout_only_marks_that_endpoint_unavailable(
assert state.state != STATE_UNAVAILABLE
# Overrides the autouse fixture, so entities get their default enabled state
@pytest.mark.parametrize("enable_all_entities", [None])
@pytest.mark.parametrize(
"entity_id",
[
pytest.param(DISK_USAGE_ENTITY_ID, id="endpoint"),
pytest.param(VOLUME_SIZE_ENTITY_ID, id="volume"),
],
)
async def test_disk_space_only_fetched_for_enabled_entities(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
freezer: FrozenDateTimeFactory,
entity_id: str,
) -> None:
"""Test disk space is disabled by default and only fetched while enabled."""
endpoints = cast(
list[dict[str, Any]],
await async_load_json_array_fixture(hass, "endpoints.json", DOMAIN),
)
for endpoint in endpoints:
endpoint["Status"] = EndpointStatus.UP
mock_portainer_client.get_endpoints.return_value = [
Endpoint.from_dict(endpoint) for endpoint in endpoints
]
await setup_integration(hass, mock_config_entry)
for disk_space_entity_id in (
DISK_USAGE_ENTITY_ID,
"sensor.my_edge_offline_image_disk_usage_total_size",
VOLUME_SIZE_ENTITY_ID,
):
assert (entry := entity_registry.async_get(disk_space_entity_id))
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
mock_portainer_client.docker_system_df.assert_not_called()
entity_registry.async_update_entity(entity_id, disabled_by=None)
await hass.config_entries.async_reload(mock_config_entry.entry_id)
await hass.async_block_till_done(wait_background_tasks=True)
mock_portainer_client.docker_system_df.assert_called_once_with(1, verbose=True)
assert (state := hass.states.get(entity_id))
assert state.state != STATE_UNAVAILABLE
freezer.tick(DEFAULT_DF_SCAN_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow())
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_portainer_client.docker_system_df.call_count == 2
mock_portainer_client.docker_system_df.assert_called_with(1, verbose=True)
entity_registry.async_update_entity(
entity_id, disabled_by=er.RegistryEntryDisabler.USER
)
await hass.async_block_till_done()
freezer.tick(DEFAULT_DF_SCAN_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow())
await hass.async_block_till_done(wait_background_tasks=True)
assert mock_portainer_client.docker_system_df.call_count == 2
async def test_volume_size_from_disk_space(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test volume size comes from the disk space poll, not the regular poll."""
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(VOLUME_SIZE_ENTITY_ID))
assert state.state == "0.09765625"
mock_portainer_client.docker_system_df.reset_mock()
freezer.tick(DEFAULT_SCAN_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow())
await hass.async_block_till_done(wait_background_tasks=True)
mock_portainer_client.docker_system_df.assert_not_called()
mock_portainer_client.docker_system_df.side_effect = PortainerTimeoutError(
"timeout"
)
freezer.tick(DEFAULT_DF_SCAN_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow())
await hass.async_block_till_done(wait_background_tasks=True)
assert (state := hass.states.get(VOLUME_SIZE_ENTITY_ID))
assert state.state == STATE_UNAVAILABLE
assert (state := hass.states.get("sensor.myvolume_volume_driver"))
assert state.state != STATE_UNAVAILABLE
async def test_volume_size_unknown_when_not_measured(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test volume size is unknown when Docker does not measure the volume."""
await setup_integration(hass, mock_config_entry)
mock_portainer_client.docker_system_df.return_value.volume_disk_usage.items = []
freezer.tick(DEFAULT_DF_SCAN_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow())
await hass.async_block_till_done(wait_background_tasks=True)
assert (state := hass.states.get(VOLUME_SIZE_ENTITY_ID))
assert state.state == STATE_UNKNOWN
async def test_volume_size_unavailable_when_volume_deleted(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test volume size follows the regular poll when the volume is deleted."""
await setup_integration(hass, mock_config_entry)
mock_portainer_client.get_volumes.return_value = []
freezer.tick(DEFAULT_SCAN_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow())
await hass.async_block_till_done(wait_background_tasks=True)
assert (state := hass.states.get(VOLUME_SIZE_ENTITY_ID))
assert state.state == STATE_UNAVAILABLE
async def test_endpoint_timeout_keeps_known_entities(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,