Files
core/tests/components/update/test_init.py
T

1700 lines
57 KiB
Python

"""The tests for the Update component."""
from collections.abc import Generator, Iterable
from typing import Any
from unittest.mock import MagicMock, patch
from awesomeversion import AwesomeVersion, AwesomeVersionStrategy
import pytest
from pytest_homeassistant.common import (
MockConfigEntry,
MockEntityPlatform,
MockModule,
MockPlatform,
MockUser,
mock_config_flow,
mock_integration,
mock_platform,
mock_restore_cache,
setup_test_component_platform,
)
from pytest_homeassistant.typing import WebSocketGenerator
from homeassistant.components.update import (
DOMAIN,
RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,
UpdateDeviceClass,
UpdateEntity,
UpdateEntityDescription,
UpdateEntityStateAttribute,
UpdateReleaseNotesMessage,
UpdateReleaseNotesMessageSeverity,
UpdateService,
UpdateServiceArgument,
)
from homeassistant.components.update.const import UpdateEntityFeature
from homeassistant.config_entries import ConfigEntry, ConfigFlow
from homeassistant.const import (
CONF_PLATFORM,
STATE_OFF,
STATE_ON,
STATE_UNKNOWN,
EntityCategory,
EntityStateAttribute,
Platform,
TargetKey,
)
from homeassistant.core import Context, HomeAssistant, State, callback
from homeassistant.exceptions import HomeAssistantError, Unauthorized
from homeassistant.helpers import system_state
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.translation import async_get_translations
from homeassistant.setup import async_setup_component
from .common import MockUpdateEntity
TEST_DOMAIN = "test"
async def test_update(hass: HomeAssistant) -> None:
"""Test getting data from the mocked update entity."""
update = UpdateEntity()
update.hass = hass
update.platform = MockEntityPlatform(hass)
update._attr_installed_version = "1.0.0"
update._attr_latest_version = "1.0.1"
update._attr_release_summary = "Summary"
update._attr_release_url = "https://example.com"
update._attr_title = "Title"
assert update.entity_category is EntityCategory.DIAGNOSTIC
assert update.entity_picture == "/api/brands/integration/test_platform/icon.png"
assert update.installed_version == "1.0.0"
assert update.latest_version == "1.0.1"
assert update.release_summary == "Summary"
assert update.release_url == "https://example.com"
assert update.title == "Title"
assert update.in_progress is False
assert update.state == STATE_ON
assert update.state_attributes == {
UpdateEntityStateAttribute.AUTO_UPDATE: False,
UpdateEntityStateAttribute.DISPLAY_PRECISION: 0,
UpdateEntityStateAttribute.INSTALLED_VERSION: "1.0.0",
UpdateEntityStateAttribute.IN_PROGRESS: False,
UpdateEntityStateAttribute.LATEST_VERSION: "1.0.1",
UpdateEntityStateAttribute.RELEASE_SUMMARY: "Summary",
UpdateEntityStateAttribute.RELEASE_URL: "https://example.com",
UpdateEntityStateAttribute.SKIPPED_VERSION: None,
UpdateEntityStateAttribute.TITLE: "Title",
UpdateEntityStateAttribute.UPDATE_PERCENTAGE: None,
}
# Test no update available
update._attr_installed_version = "1.0.0"
update._attr_latest_version = "1.0.0"
assert update.state is STATE_OFF
# Test state becomes unknown if installed version is unknown
update._attr_installed_version = None
update._attr_latest_version = "1.0.0"
assert update.state is None
# Test state becomes unknown if latest version is unknown
update._attr_installed_version = "1.0.0"
update._attr_latest_version = None
assert update.state is None
# Test no update if new version is not an update
update._attr_installed_version = "1.0.0"
update._attr_latest_version = "0.9.0"
assert update.state is STATE_OFF
# Test update if new version is not considered a valid version
update._attr_installed_version = "1.0.0"
update._attr_latest_version = "awesome_update"
assert update.state is STATE_ON
# Test entity category becomes config when its possible to install
update._attr_supported_features = UpdateEntityFeature.INSTALL
assert update.entity_category is EntityCategory.CONFIG
# UpdateEntityDescription was set
update._attr_supported_features = 0
update.entity_description = UpdateEntityDescription(key="F5 - Its very refreshing")
assert update.device_class is None
assert update.entity_category is EntityCategory.CONFIG
del update.device_class
update.entity_description = UpdateEntityDescription(
key="F5 - Its very refreshing",
device_class=UpdateDeviceClass.FIRMWARE,
entity_category=None,
)
assert update.device_class is UpdateDeviceClass.FIRMWARE
assert update.entity_category is None
# Device class via attribute (override entity description)
update._attr_device_class = None
assert update.device_class is None
update._attr_device_class = UpdateDeviceClass.FIRMWARE
assert update.device_class is UpdateDeviceClass.FIRMWARE
# Entity Attribute via attribute (override entity description)
update._attr_entity_category = None
assert update.entity_category is None
update._attr_entity_category = EntityCategory.DIAGNOSTIC
assert update.entity_category is EntityCategory.DIAGNOSTIC
with pytest.raises(NotImplementedError):
await update.async_install(version=None, backup=True)
with pytest.raises(NotImplementedError):
update.install(version=None, backup=False)
update.install = MagicMock()
await update.async_install(version="1.0.1", backup=True)
assert update.install.called
assert update.install.call_args[0][0] == "1.0.1"
assert update.install.call_args[0][1] is True
async def test_entity_with_no_install(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
) -> None:
"""Test entity with no updates."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
# Update is available
state = hass.states.get("update.update_no_install")
assert state
assert state.state == STATE_ON
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
# Should not be able to install as the entity doesn't support that
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.update_no_install"},
blocking=True,
)
# Nothing changed
state = hass.states.get("update.update_no_install")
assert state
assert state.state == STATE_ON
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] is None
# We can mark the update as skipped
await hass.services.async_call(
DOMAIN,
UpdateService.SKIP,
{TargetKey.ENTITY_ID: "update.update_no_install"},
blocking=True,
)
state = hass.states.get("update.update_no_install")
assert state
assert state.state == STATE_OFF
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] == "1.0.1"
# We can clear the skipped marker again
await hass.services.async_call(
DOMAIN,
"clear_skipped",
{TargetKey.ENTITY_ID: "update.update_no_install"},
blocking=True,
)
state = hass.states.get("update.update_no_install")
assert state
assert state.state == STATE_ON
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] is None
async def test_entity_with_no_updates(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
) -> None:
"""Test entity with no updates."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
# No update available
state = hass.states.get("update.no_update")
assert state
assert state.state == STATE_OFF
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.0"
# Should not be able to skip when there is no update available
with pytest.raises(HomeAssistantError, match="No update available to skip for"):
await hass.services.async_call(
DOMAIN,
UpdateService.SKIP,
{TargetKey.ENTITY_ID: "update.no_update"},
blocking=True,
)
# Should not be able to install an update when there is no update available
with pytest.raises(HomeAssistantError, match="No update available for"):
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.no_update"},
blocking=True,
)
# Updating to a specific version is not supported by this entity
with pytest.raises(
HomeAssistantError,
match="Installing a specific version is not supported for",
):
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{
UpdateServiceArgument.VERSION: "0.9.0",
TargetKey.ENTITY_ID: "update.no_update",
},
blocking=True,
)
async def test_entity_with_auto_update(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test update entity that has auto update feature."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
state = hass.states.get("update.update_with_auto_update")
assert state
assert state.state == STATE_ON
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] is None
# Should be able to manually install an update even if it can auto update
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.update_with_auto_update"},
blocking=True,
)
# Should not be able to skip the update
with pytest.raises(
HomeAssistantError,
match="Skipping update is not supported for update.update_with_auto_update",
):
await hass.services.async_call(
DOMAIN,
UpdateService.SKIP,
{TargetKey.ENTITY_ID: "update.update_with_auto_update"},
blocking=True,
)
# Should not be able to clear a skipped the update
with pytest.raises(
HomeAssistantError,
match="Clearing skipped update is not supported"
" for update.update_with_auto_update",
):
await hass.services.async_call(
DOMAIN,
"clear_skipped",
{TargetKey.ENTITY_ID: "update.update_with_auto_update"},
blocking=True,
)
async def test_entity_with_updates_available(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test basic update entity with updates available."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
# Entity has an update available
state = hass.states.get("update.update_available")
assert state
assert state.state == STATE_ON
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] is None
# Skip skip the update
await hass.services.async_call(
DOMAIN,
UpdateService.SKIP,
{TargetKey.ENTITY_ID: "update.update_available"},
blocking=True,
)
# The state should have changed to off, skipped version should be set
state = hass.states.get("update.update_available")
assert state
assert state.state == STATE_OFF
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] == "1.0.1"
# Even though skipped, we can still update if we want to
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.update_available"},
blocking=True,
)
# The state should have changed to off, skipped version should be set
state = hass.states.get("update.update_available")
assert state
assert state.state == STATE_OFF
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] is None
assert "Installed latest update" in caplog.text
@pytest.mark.parametrize(
("service", "state_after_admin_call"),
[
pytest.param(UpdateService.INSTALL, STATE_OFF, id="install"),
pytest.param(UpdateService.SKIP, STATE_OFF, id="skip"),
pytest.param("clear_skipped", STATE_ON, id="clear_skipped"),
],
)
async def test_services_require_admin(
hass: HomeAssistant,
hass_admin_user: MockUser,
hass_read_only_user: MockUser,
mock_update_entities: list[MockUpdateEntity],
service: str,
state_after_admin_call: str,
) -> None:
"""Test the update services require an admin user."""
# Grant control of all entities, so the call is only rejected for not being admin
hass_read_only_user.mock_policy({"entities": {"all": {"control": True}}})
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
with pytest.raises(Unauthorized):
await hass.services.async_call(
DOMAIN,
service,
{TargetKey.ENTITY_ID: "update.update_available"},
blocking=True,
context=Context(user_id=hass_read_only_user.id),
)
state = hass.states.get("update.update_available")
assert state
assert state.state == STATE_ON
await hass.services.async_call(
DOMAIN,
service,
{TargetKey.ENTITY_ID: "update.update_available"},
blocking=True,
context=Context(user_id=hass_admin_user.id),
)
state = hass.states.get("update.update_available")
assert state
assert state.state == state_after_admin_call
async def test_entity_with_unknown_version(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test update entity that has an unknown version."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
state = hass.states.get("update.update_unknown")
assert state
assert state.state == STATE_UNKNOWN
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] is None
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] is None
# Should not be able to install an update when there is no update available
with pytest.raises(HomeAssistantError, match="No update available for"):
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.update_unknown"},
blocking=True,
)
# Should not be to skip the update
with pytest.raises(HomeAssistantError, match="Cannot skip an unknown version for"):
await hass.services.async_call(
DOMAIN,
UpdateService.SKIP,
{TargetKey.ENTITY_ID: "update.update_unknown"},
blocking=True,
)
async def test_entity_with_specific_version(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test update entity that support specific version."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
state = hass.states.get("update.update_specific_version")
assert state
assert state.state == STATE_OFF
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.0"
# Update to a specific version
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{
UpdateServiceArgument.VERSION: "0.9.9",
TargetKey.ENTITY_ID: "update.update_specific_version",
},
blocking=True,
)
# Version has changed, state should be on as there is an update available
state = hass.states.get("update.update_specific_version")
assert state
assert state.state == STATE_ON
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "0.9.9"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.0"
assert "Installed update with version: 0.9.9" in caplog.text
# Update back to the latest version
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.update_specific_version"},
blocking=True,
)
state = hass.states.get("update.update_specific_version")
assert state
assert state.state == STATE_OFF
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.0"
assert "Installed latest update" in caplog.text
# This entity does not support doing a backup before upgrade
with pytest.raises(HomeAssistantError, match="Backup is not supported for"):
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{
UpdateServiceArgument.VERSION: "0.9.9",
UpdateServiceArgument.BACKUP: True,
TargetKey.ENTITY_ID: "update.update_specific_version",
},
blocking=True,
)
async def test_entity_with_backup_support(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test update entity with backup support."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
# This entity support backing up before install the update
state = hass.states.get("update.update_backup")
assert state
assert state.state == STATE_ON
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
# Without a backup
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{
UpdateServiceArgument.BACKUP: False,
TargetKey.ENTITY_ID: "update.update_backup",
},
blocking=True,
)
state = hass.states.get("update.update_backup")
assert state
assert state.state == STATE_OFF
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert "Creating backup before installing update" not in caplog.text
assert "Installed latest update" in caplog.text
# Specific version, do create a backup this time
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{
UpdateServiceArgument.BACKUP: True,
UpdateServiceArgument.VERSION: "0.9.8",
TargetKey.ENTITY_ID: "update.update_backup",
},
blocking=True,
)
# This entity support backing up before install the update
state = hass.states.get("update.update_backup")
assert state
assert state.state == STATE_ON
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "0.9.8"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert "Creating backup before installing update" in caplog.text
assert "Installed update with version: 0.9.8" in caplog.text
@pytest.mark.parametrize(
("entity_id", "expected_display_precision", "expected_update_percentage"),
[
("update.update_already_in_progress", 0, 50),
("update.update_already_in_progress_float", 2, 0.25),
],
)
async def test_entity_already_in_progress(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
caplog: pytest.LogCaptureFixture,
entity_id: str,
expected_display_precision: int,
expected_update_percentage: float,
) -> None:
"""Test update install already in progress."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
assert (
state.attributes[UpdateEntityStateAttribute.DISPLAY_PRECISION]
== expected_display_precision
)
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.IN_PROGRESS] is True
assert (
state.attributes[UpdateEntityStateAttribute.UPDATE_PERCENTAGE]
== expected_update_percentage
)
with pytest.raises(
HomeAssistantError,
match="Update installation already in progress for",
):
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: entity_id},
blocking=True,
)
# Check update percentage is suppressed when in_progress is False
entity = next(
entity for entity in mock_update_entities if entity.entity_id == entity_id
)
entity._attr_in_progress = False
entity.async_write_ha_state()
state = hass.states.get(entity_id)
assert state.attributes[UpdateEntityStateAttribute.IN_PROGRESS] is False
assert state.attributes[UpdateEntityStateAttribute.UPDATE_PERCENTAGE] is None
async def test_entity_without_progress_support(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test update entity without progress support.
In that case, progress is still handled by Home Assistant.
"""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
events = []
async_track_state_change_event(
hass,
"update.update_available",
# pylint: disable-next=unnecessary-lambda
callback(lambda event: events.append(event)),
)
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.update_available"},
blocking=True,
)
await hass.async_block_till_done()
assert len(events) == 2
assert (
events[0]
.data.get("old_state")
.attributes[UpdateEntityStateAttribute.IN_PROGRESS]
is False
)
assert (
events[0]
.data.get("old_state")
.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION]
== "1.0.0"
)
assert (
events[0]
.data.get("new_state")
.attributes[UpdateEntityStateAttribute.IN_PROGRESS]
is True
)
assert (
events[0]
.data.get("new_state")
.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION]
== "1.0.0"
)
assert (
events[1]
.data.get("old_state")
.attributes[UpdateEntityStateAttribute.IN_PROGRESS]
is True
)
assert (
events[1]
.data.get("old_state")
.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION]
== "1.0.0"
)
assert (
events[1]
.data.get("new_state")
.attributes[UpdateEntityStateAttribute.IN_PROGRESS]
is False
)
assert (
events[1]
.data.get("new_state")
.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION]
== "1.0.1"
)
async def test_entity_without_progress_support_raising(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test update entity without progress support that raises during install.
In that case, progress is still handled by Home Assistant.
"""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
events = []
async_track_state_change_event(
hass,
"update.update_available",
# pylint: disable-next=unnecessary-lambda
callback(lambda event: events.append(event)),
)
with (
patch(
"homeassistant.components.update.UpdateEntity.async_install",
side_effect=RuntimeError,
),
pytest.raises(RuntimeError),
):
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.update_available"},
blocking=True,
)
await hass.async_block_till_done()
assert len(events) == 2
assert (
events[0]
.data.get("old_state")
.attributes[UpdateEntityStateAttribute.IN_PROGRESS]
is False
)
assert (
events[0]
.data.get("old_state")
.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION]
== "1.0.0"
)
assert (
events[0]
.data.get("new_state")
.attributes[UpdateEntityStateAttribute.IN_PROGRESS]
is True
)
assert (
events[0]
.data.get("new_state")
.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION]
== "1.0.0"
)
assert (
events[1]
.data.get("old_state")
.attributes[UpdateEntityStateAttribute.IN_PROGRESS]
is True
)
assert (
events[1]
.data.get("old_state")
.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION]
== "1.0.0"
)
assert (
events[1]
.data.get("new_state")
.attributes[UpdateEntityStateAttribute.IN_PROGRESS]
is False
)
assert (
events[1]
.data.get("new_state")
.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION]
== "1.0.0"
)
def _restart_update_entity(**values: Any) -> MockUpdateEntity:
"""Return an installable update entity for the restart tests."""
return MockUpdateEntity(
name="Update",
unique_id="update",
installed_version="1.0.0",
latest_version="1.0.1",
supported_features=UpdateEntityFeature.INSTALL,
**values,
)
def _restart_update_entity_with_description(
restart_required: bool,
) -> MockUpdateEntity:
"""Return an update entity that sets the flag through its description."""
entity = _restart_update_entity()
entity.entity_description = UpdateEntityDescription(
key="update", restart_required=restart_required
)
return entity
@pytest.mark.parametrize(
("entity", "restart_sources"),
[
pytest.param(_restart_update_entity(), set(), id="not_set"),
pytest.param(
_restart_update_entity(restart_required=True),
{TEST_DOMAIN},
id="attribute",
),
pytest.param(
_restart_update_entity(restart_required=False),
set(),
id="attribute_false",
),
pytest.param(
_restart_update_entity_with_description(True),
{TEST_DOMAIN},
id="description",
),
pytest.param(
_restart_update_entity_with_description(False),
set(),
id="description_false",
),
],
)
async def test_restart_required(
hass: HomeAssistant, entity: MockUpdateEntity, restart_sources: set[str]
) -> None:
"""Test a finished install flags Home Assistant for a restart."""
setup_test_component_platform(hass, DOMAIN, [entity])
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.update"},
blocking=True,
)
assert hass.states.get("update.update").attributes[
UpdateEntityStateAttribute.INSTALLED_VERSION
] == ("1.0.1")
assert (
system_state.async_get(hass).home_assistant_restart_sources == restart_sources
)
async def test_restart_required_install_failed(hass: HomeAssistant) -> None:
"""Test a failed install does not flag Home Assistant for a restart."""
setup_test_component_platform(
hass, DOMAIN, [_restart_update_entity(restart_required=True)]
)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
with (
patch(
"homeassistant.components.update.UpdateEntity.async_install",
side_effect=RuntimeError,
),
pytest.raises(RuntimeError),
):
await hass.services.async_call(
DOMAIN,
UpdateService.INSTALL,
{TargetKey.ENTITY_ID: "update.update"},
blocking=True,
)
assert not system_state.async_get(hass).home_assistant_restart_required
async def test_restore_state(
hass: HomeAssistant, mock_update_entities: list[MockUpdateEntity]
) -> None:
"""Test we restore skipped version state."""
mock_restore_cache(
hass,
(
State(
"update.update_available",
STATE_ON, # Incorrect, but helps checking if it is ignored
{
UpdateEntityStateAttribute.SKIPPED_VERSION: "1.0.1",
},
),
),
)
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
state = hass.states.get("update.update_available")
assert state
assert state.state == STATE_OFF
assert state.attributes[UpdateEntityStateAttribute.INSTALLED_VERSION] == "1.0.0"
assert state.attributes[UpdateEntityStateAttribute.LATEST_VERSION] == "1.0.1"
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] == "1.0.1"
async def test_release_notes(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test getting the release notes over the websocket connection."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await hass.async_block_till_done()
await client.send_json(
{
"id": 1,
"type": "update/release_notes",
"entity_id": "update.update_with_release_notes",
}
)
result = await client.receive_json()
assert result["result"] == {"release_notes": "Release notes", "messages": []}
DO_NOT_INTERRUPT_MESSAGE = {
"severity": "warning",
"message": (
"Do not restart, remove power from, or otherwise interrupt the device "
"while the update is in progress."
),
}
REVIEW_DOCS_MESSAGE = UpdateReleaseNotesMessage(
translation_domain=TEST_DOMAIN,
translation_key="review_docs",
severity=UpdateReleaseNotesMessageSeverity.ERROR,
translation_placeholders={"docs_url": "https://example.com/update"},
)
INTEGRATION_RELEASE_NOTES_TRANSLATIONS = {
"component.test.entity.update.release_notes_messages.review_docs": (
"Review {docs_url} before starting the update."
),
}
async def _async_get_translations_with_integration(
hass: HomeAssistant,
language: str,
category: str,
integrations: Iterable[str] | None = None,
) -> dict[str, str]:
"""Return translations including the test integration's update messages."""
translations = await async_get_translations(hass, language, category, integrations)
return translations | INTEGRATION_RELEASE_NOTES_TRANSLATIONS
@pytest.mark.parametrize(
("latest_version", "release_notes_messages", "release_notes", "expected"),
[
pytest.param(
"1.0.1",
(RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,),
"Release notes",
{"release_notes": "Release notes", "messages": [DO_NOT_INTERRUPT_MESSAGE]},
id="shared_message",
),
pytest.param(
"1.0.1",
(REVIEW_DOCS_MESSAGE,),
"Release notes",
{
"release_notes": "Release notes",
"messages": [
{
"severity": "error",
"message": (
"Review https://example.com/update before starting "
"the update."
),
}
],
},
id="integration_message_with_placeholders",
),
pytest.param(
"1.0.1",
(RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,),
None,
{"release_notes": None, "messages": [DO_NOT_INTERRUPT_MESSAGE]},
id="no_release_notes",
),
pytest.param(
"1.0.0",
(RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,),
"Release notes",
{"release_notes": "Release notes", "messages": []},
id="no_update_available",
),
pytest.param(
"1.0.0",
(RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,),
None,
{"release_notes": None, "messages": []},
id="no_update_available_no_release_notes",
),
pytest.param(
None,
(RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,),
"Release notes",
{"release_notes": "Release notes", "messages": []},
id="unknown_latest_version",
),
],
)
async def test_release_notes_with_messages(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
latest_version: str | None,
release_notes_messages: tuple[UpdateReleaseNotesMessage, ...],
release_notes: str | None,
expected: dict[str, Any],
) -> None:
"""Test release notes messages are returned with the release notes."""
entity = MockUpdateEntity(
name="Update with release notes messages",
unique_id="with_release_notes_messages",
installed_version="1.0.0",
latest_version=latest_version,
supported_features=UpdateEntityFeature.RELEASE_NOTES,
release_notes_messages=release_notes_messages,
)
setup_test_component_platform(hass, DOMAIN, [entity])
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
with (
patch.object(entity, "release_notes", return_value=release_notes),
patch(
"homeassistant.components.update.async_get_translations",
side_effect=_async_get_translations_with_integration,
),
):
await client.send_json(
{
"id": 1,
"type": "update/release_notes",
"entity_id": "update.update_with_release_notes_messages",
}
)
result = await client.receive_json()
assert result["result"] == expected
async def test_release_notes_with_messages_skipped_version(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test release notes messages are returned for a skipped version."""
entity = MockUpdateEntity(
name="Update with skipped version",
unique_id="with_skipped_version",
installed_version="1.0.0",
latest_version="1.0.1",
supported_features=UpdateEntityFeature.RELEASE_NOTES,
release_notes_messages=(RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,),
)
setup_test_component_platform(hass, DOMAIN, [entity])
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
await hass.services.async_call(
DOMAIN,
UpdateService.SKIP,
{TargetKey.ENTITY_ID: "update.update_with_skipped_version"},
blocking=True,
)
state = hass.states.get("update.update_with_skipped_version")
assert state
assert state.state == STATE_OFF
assert state.attributes[UpdateEntityStateAttribute.SKIPPED_VERSION] == "1.0.1"
client = await hass_ws_client(hass)
await client.send_json(
{
"id": 1,
"type": "update/release_notes",
"entity_id": "update.update_with_skipped_version",
}
)
result = await client.receive_json()
assert result["result"] == {
"release_notes": "Release notes",
"messages": [DO_NOT_INTERRUPT_MESSAGE],
}
async def test_release_notes_message_missing_translation(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test release notes messages without a translation are skipped."""
entity = MockUpdateEntity(
name="Update with missing release notes message",
unique_id="with_missing_release_notes_message",
installed_version="1.0.0",
latest_version="1.0.1",
supported_features=UpdateEntityFeature.RELEASE_NOTES,
release_notes_messages=(
UpdateReleaseNotesMessage(
translation_domain=TEST_DOMAIN, translation_key="missing"
),
),
)
setup_test_component_platform(hass, DOMAIN, [entity])
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json(
{
"id": 1,
"type": "update/release_notes",
"entity_id": "update.update_with_missing_release_notes_message",
}
)
result = await client.receive_json()
assert result["result"] == {"release_notes": "Release notes", "messages": []}
assert "Missing translation for release notes message missing of test" in (
caplog.text
)
@pytest.mark.parametrize(
("message_language", "expected_language"),
[
pytest.param({"language": "de"}, "de", id="frontend_language"),
pytest.param({}, "en", id="default_language"),
],
)
async def test_release_notes_messages_language(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
message_language: dict[str, str],
expected_language: str,
) -> None:
"""Test release notes messages are translated in the requested language."""
entity = MockUpdateEntity(
name="Update with release notes messages",
unique_id="with_release_notes_messages",
installed_version="1.0.0",
latest_version="1.0.1",
supported_features=UpdateEntityFeature.RELEASE_NOTES,
release_notes_messages=(
RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,
REVIEW_DOCS_MESSAGE,
),
)
setup_test_component_platform(hass, DOMAIN, [entity])
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
with patch(
"homeassistant.components.update.async_get_translations",
wraps=async_get_translations,
) as mock_get_translations:
await client.send_json(
{
"id": 1,
"type": "update/release_notes",
"entity_id": "update.update_with_release_notes_messages",
**message_language,
}
)
result = await client.receive_json()
assert result["success"]
assert [call.args[1] for call in mock_get_translations.call_args_list] == [
expected_language,
expected_language,
]
@pytest.mark.parametrize(
("entity_values", "entity_description", "expected"),
[
pytest.param(
{},
UpdateEntityDescription(
key="update",
release_notes_messages=(REVIEW_DOCS_MESSAGE,),
),
(REVIEW_DOCS_MESSAGE,),
id="entity_description",
),
pytest.param(
{"release_notes_messages": (RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,)},
UpdateEntityDescription(
key="update",
release_notes_messages=(REVIEW_DOCS_MESSAGE,),
),
(RELEASE_NOTES_MESSAGE_DO_NOT_INTERRUPT,),
id="attribute_overrides_entity_description",
),
],
)
def test_release_notes_messages_property(
entity_values: dict[str, Any],
entity_description: UpdateEntityDescription,
expected: tuple[UpdateReleaseNotesMessage, ...],
) -> None:
"""Test the release notes messages property."""
entity = MockUpdateEntity(**entity_values)
entity.entity_description = entity_description
assert entity.release_notes_messages == expected
async def test_release_notes_entity_not_found(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test getting the release notes for not found entity."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await hass.async_block_till_done()
await client.send_json(
{
"id": 1,
"type": "update/release_notes",
"entity_id": "update.entity_not_found",
}
)
result = await client.receive_json()
assert result["error"]["code"] == "not_found"
assert result["error"]["message"] == "Entity not found"
async def test_release_notes_entity_does_not_support_release_notes(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test getting the release notes for entity that does not support release notes."""
setup_test_component_platform(hass, DOMAIN, mock_update_entities)
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await hass.async_block_till_done()
await client.send_json(
{
"id": 1,
"type": "update/release_notes",
"entity_id": "update.update_available",
}
)
result = await client.receive_json()
assert result["error"]["code"] == "not_supported"
assert result["error"]["message"] == "Entity does not support release notes"
async def test_release_notes_entity_unavailable(
hass: HomeAssistant,
mock_update_entities: list[MockUpdateEntity],
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test getting the release notes for entity that is unavailable."""
entity = MockUpdateEntity(
name="Update unavailable",
unique_id="unavailable",
installed_version="1.0.0",
latest_version="1.0.1",
available=False,
supported_features=UpdateEntityFeature.RELEASE_NOTES,
)
setup_test_component_platform(hass, DOMAIN, [entity])
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await hass.async_block_till_done()
await client.send_json(
{
"id": 1,
"type": "update/release_notes",
"entity_id": "update.update_unavailable",
}
)
result = await client.receive_json()
assert result["error"]["code"] == "home_assistant_error"
assert result["error"]["message"] == "Entity is not available"
class MockFlow(ConfigFlow):
"""Test flow."""
@pytest.fixture(autouse=True)
def config_flow_fixture(hass: HomeAssistant) -> Generator[None]:
"""Mock config flow."""
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
with mock_config_flow(TEST_DOMAIN, MockFlow):
yield
async def test_name(hass: HomeAssistant) -> None:
"""Test update name."""
async def async_setup_entry_init(
hass: HomeAssistant, config_entry: ConfigEntry
) -> None:
"""Set up test config entry."""
await hass.config_entries.async_forward_entry_setups(
config_entry, [Platform.UPDATE]
)
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
mock_integration(
hass,
MockModule(
TEST_DOMAIN,
async_setup_entry=async_setup_entry_init,
),
)
# Unnamed update entity without device class -> no name
entity1 = UpdateEntity()
entity1.entity_id = "update.test1"
# Unnamed update entity with device class but has_entity_name False -> no name
entity2 = UpdateEntity()
entity2.entity_id = "update.test2"
entity2._attr_device_class = UpdateDeviceClass.FIRMWARE
# Unnamed update entity with device class and has_entity_name True -> named
entity3 = UpdateEntity()
entity3.entity_id = "update.test3"
entity3._attr_device_class = UpdateDeviceClass.FIRMWARE
entity3._attr_has_entity_name = True
# Unnamed update entity with device class and has_entity_name True -> named
entity4 = UpdateEntity()
entity4.entity_id = "update.test4"
entity4.entity_description = UpdateEntityDescription(
"test",
UpdateDeviceClass.FIRMWARE,
has_entity_name=True,
)
async def async_setup_entry_platform(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up test update platform via config entry."""
async_add_entities([entity1, entity2, entity3, entity4])
mock_platform(
hass,
f"{TEST_DOMAIN}.{DOMAIN}",
MockPlatform(async_setup_entry=async_setup_entry_platform),
)
config_entry = MockConfigEntry(domain=TEST_DOMAIN)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(entity1.entity_id)
assert state
assert "device_class" not in state.attributes
assert "friendly_name" not in state.attributes
state = hass.states.get(entity2.entity_id)
assert state
assert state.attributes.get("device_class") == "firmware"
assert "friendly_name" not in state.attributes
expected = {
"device_class": "firmware",
"friendly_name": "Firmware",
}
state = hass.states.get(entity3.entity_id)
assert state
assert expected.items() <= state.attributes.items()
state = hass.states.get(entity4.entity_id)
assert state
assert expected.items() <= state.attributes.items()
async def test_custom_version_is_newer(hass: HomeAssistant) -> None:
"""Test UpdateEntity with overridden version_is_newer method."""
class MockUpdateEntity(UpdateEntity):
def version_is_newer(self, latest_version: str, installed_version: str) -> bool:
"""Return True if latest_version is newer than installed_version."""
return AwesomeVersion(
latest_version,
find_first_match=True,
ensure_strategy=[AwesomeVersionStrategy.SEMVER],
) > AwesomeVersion(
installed_version,
find_first_match=True,
ensure_strategy=[AwesomeVersionStrategy.SEMVER],
)
update = MockUpdateEntity()
update.hass = hass
update.platform = MockEntityPlatform(hass)
STABLE = "20230913-111730/v1.14.0-gcb84623"
BETA = "20231107-162609/v1.14.1-rc1-g0617c15"
# Set current installed version to STABLE
update._attr_installed_version = STABLE
update._attr_latest_version = BETA
assert update.installed_version == STABLE
assert update.latest_version == BETA
assert update.state == STATE_ON
# Set current installed version to BETA
update._attr_installed_version = BETA
update._attr_latest_version = STABLE
assert update.installed_version == BETA
assert update.latest_version == STABLE
assert update.state == STATE_OFF
@pytest.mark.parametrize(
("installed_version", "latest_version", "expected"),
[
pytest.param(None, "1.0.1", False, id="unknown-installed-version"),
pytest.param("1.0.0", None, False, id="unknown-latest-version"),
pytest.param("1.0.0", "1.0.0", False, id="same-version"),
pytest.param("1.0.0", "1.0.1", True, id="newer-version"),
pytest.param("1.0.0", "0.9.0", False, id="older-version"),
pytest.param("1.0.0", "awesome_update", True, id="incomparable-version"),
pytest.param("latest", "1.1.0", True, id="installed-special-latest"),
pytest.param("dev", "1.1.0", True, id="installed-special-dev"),
pytest.param("beta", "1.1.0", True, id="installed-special-beta"),
pytest.param("stable", "1.1.0", True, id="installed-special-stable"),
pytest.param("1.0.0", "latest", True, id="latest-special"),
pytest.param("latest", "latest", False, id="same-special-version"),
],
)
def test_has_update(
installed_version: str | None,
latest_version: str | None,
expected: bool,
) -> None:
"""Test the default update availability check."""
update = UpdateEntity()
update._attr_installed_version = installed_version
update._attr_latest_version = latest_version
assert update.has_update is expected
@pytest.mark.parametrize(
("update_available", "expected_state"),
[
pytest.param(True, STATE_ON, id="available"),
pytest.param(False, STATE_OFF, id="unavailable"),
],
)
def test_custom_has_update(update_available: bool, expected_state: str) -> None:
"""Test UpdateEntity with an overridden has_update property."""
class MockUpdateEntity(UpdateEntity):
@property
def has_update(self) -> bool:
"""Return whether an update is available."""
return update_available
def version_is_newer(self, latest_version: str, installed_version: str) -> bool:
"""Fail if version comparison is used."""
raise AssertionError
update = MockUpdateEntity()
update._attr_installed_version = "1.0.0"
update._attr_latest_version = "1.0.1"
assert update.state == expected_state
def test_custom_version_is_newer_incomparable() -> None:
"""Test an incomparable version from an overridden comparison method."""
class MockUpdateEntity(UpdateEntity):
def version_is_newer(self, latest_version: str, installed_version: str) -> bool:
"""Compare versions."""
return AwesomeVersion(latest_version) > AwesomeVersion(installed_version)
update = MockUpdateEntity()
update._attr_installed_version = "1.0.0"
update._attr_latest_version = "awesome_update"
assert update.has_update is True
assert update.state == STATE_ON
@pytest.mark.parametrize(
("installed_version", "latest_version", "expected_state"),
[
pytest.param(None, "1.0.1", None, id="unknown-installed-version"),
pytest.param("1.0.0", None, None, id="unknown-latest-version"),
pytest.param("1.0.0", "1.0.0", STATE_OFF, id="same-version"),
],
)
def test_custom_has_update_state_precedence(
installed_version: str | None,
latest_version: str | None,
expected_state: str | None,
) -> None:
"""Test version state checks take precedence over custom availability."""
class MockUpdateEntity(UpdateEntity):
@property
def has_update(self) -> bool:
"""Fail if update availability is checked."""
raise AssertionError
update = MockUpdateEntity()
update._attr_installed_version = installed_version
update._attr_latest_version = latest_version
assert update.state is expected_state
@pytest.mark.parametrize(
("supported_features", "extra_expected_attributes"),
[
(
UpdateEntityFeature(0),
[
{},
{},
{},
{},
{},
{},
{},
],
),
(
UpdateEntityFeature.PROGRESS,
[
{UpdateEntityStateAttribute.IN_PROGRESS: False},
{UpdateEntityStateAttribute.IN_PROGRESS: False},
{
UpdateEntityStateAttribute.IN_PROGRESS: True,
UpdateEntityStateAttribute.UPDATE_PERCENTAGE: 0,
},
{UpdateEntityStateAttribute.IN_PROGRESS: True},
{
UpdateEntityStateAttribute.IN_PROGRESS: True,
UpdateEntityStateAttribute.UPDATE_PERCENTAGE: 1,
},
{
UpdateEntityStateAttribute.IN_PROGRESS: True,
UpdateEntityStateAttribute.UPDATE_PERCENTAGE: 10,
},
{
UpdateEntityStateAttribute.IN_PROGRESS: True,
UpdateEntityStateAttribute.UPDATE_PERCENTAGE: 100,
},
],
),
],
)
async def test_update_percentage_backwards_compatibility(
hass: HomeAssistant,
supported_features: UpdateEntityFeature,
extra_expected_attributes: list[dict],
) -> None:
"""Test deriving update percentage from deprecated in_progress."""
update = MockUpdateEntity()
update._attr_installed_version = "1.0.0"
update._attr_latest_version = "1.0.1"
update._attr_name = "legacy"
update._attr_release_summary = "Summary"
update._attr_release_url = "https://example.com"
update._attr_supported_features = supported_features
update._attr_title = "Title"
setup_test_component_platform(hass, DOMAIN, [update])
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}})
await hass.async_block_till_done()
expected_attributes = {
UpdateEntityStateAttribute.AUTO_UPDATE: False,
UpdateEntityStateAttribute.DISPLAY_PRECISION: 0,
EntityStateAttribute.ENTITY_PICTURE: "/api/brands/integration/test/icon.png",
EntityStateAttribute.FRIENDLY_NAME: "legacy",
UpdateEntityStateAttribute.INSTALLED_VERSION: "1.0.0",
UpdateEntityStateAttribute.IN_PROGRESS: False,
UpdateEntityStateAttribute.LATEST_VERSION: "1.0.1",
UpdateEntityStateAttribute.RELEASE_SUMMARY: "Summary",
UpdateEntityStateAttribute.RELEASE_URL: "https://example.com",
UpdateEntityStateAttribute.SKIPPED_VERSION: None,
EntityStateAttribute.SUPPORTED_FEATURES: supported_features,
UpdateEntityStateAttribute.TITLE: "Title",
UpdateEntityStateAttribute.UPDATE_PERCENTAGE: None,
}
state = hass.states.get("update.legacy")
assert state is not None
assert state.state == STATE_ON
assert state.attributes == expected_attributes | extra_expected_attributes[0]
in_progress_list = [False, 0, True, 1, 10, 100]
for i, in_progress in enumerate(in_progress_list):
update._attr_in_progress = in_progress
update.async_write_ha_state()
state = hass.states.get("update.legacy")
assert state.state == STATE_ON
assert (
state.attributes == expected_attributes | extra_expected_attributes[i + 1]
)