From ad362b1d4cd8c25be3af348f75926b1d670e3d19 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 22 Aug 2024 00:48:25 -0500 Subject: [PATCH 01/31] Bump dbus-fast to 2.23.0 (#124384) --- homeassistant/components/bluetooth/manifest.json | 2 +- homeassistant/package_constraints.txt | 2 +- requirements_all.txt | 2 +- requirements_test_all.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/bluetooth/manifest.json b/homeassistant/components/bluetooth/manifest.json index 0dbe1475b8d03..07ea970de3d25 100644 --- a/homeassistant/components/bluetooth/manifest.json +++ b/homeassistant/components/bluetooth/manifest.json @@ -19,7 +19,7 @@ "bluetooth-adapters==0.19.4", "bluetooth-auto-recovery==1.4.2", "bluetooth-data-tools==1.19.4", - "dbus-fast==2.22.1", + "dbus-fast==2.23.0", "habluetooth==3.3.2" ] } diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index 31100828978c6..b6bcd1dac6bbb 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -23,7 +23,7 @@ cached_ipaddress==0.3.0 certifi>=2021.5.30 ciso8601==2.3.1 cryptography==43.0.0 -dbus-fast==2.22.1 +dbus-fast==2.23.0 fnv-hash-fast==0.5.0 ha-av==10.1.1 ha-ffmpeg==3.2.0 diff --git a/requirements_all.txt b/requirements_all.txt index 4820889dfabb1..17ab928a92b92 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -703,7 +703,7 @@ datadog==0.15.0 datapoint==0.9.9 # homeassistant.components.bluetooth -dbus-fast==2.22.1 +dbus-fast==2.23.0 # homeassistant.components.debugpy debugpy==1.8.1 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index 6f1e23f9d1060..765352c89ff50 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -599,7 +599,7 @@ datadog==0.15.0 datapoint==0.9.9 # homeassistant.components.bluetooth -dbus-fast==2.22.1 +dbus-fast==2.23.0 # homeassistant.components.debugpy debugpy==1.8.1 From 266cd623a5e822ab29118419621472681976ccd5 Mon Sep 17 00:00:00 2001 From: G Johansson Date: Thu, 22 Aug 2024 07:59:21 +0200 Subject: [PATCH 02/31] Bump python-holidays to 0.55 (#124314) --- homeassistant/components/holiday/manifest.json | 2 +- homeassistant/components/workday/binary_sensor.py | 4 ++-- homeassistant/components/workday/manifest.json | 2 +- requirements_all.txt | 2 +- requirements_test_all.txt | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/holiday/manifest.json b/homeassistant/components/holiday/manifest.json index 0a714815ae3e5..0a3064450d46e 100644 --- a/homeassistant/components/holiday/manifest.json +++ b/homeassistant/components/holiday/manifest.json @@ -5,5 +5,5 @@ "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/holiday", "iot_class": "local_polling", - "requirements": ["holidays==0.54", "babel==2.15.0"] + "requirements": ["holidays==0.55", "babel==2.15.0"] } diff --git a/homeassistant/components/workday/binary_sensor.py b/homeassistant/components/workday/binary_sensor.py index 4635b2209a696..33c2e249024a6 100644 --- a/homeassistant/components/workday/binary_sensor.py +++ b/homeassistant/components/workday/binary_sensor.py @@ -92,7 +92,7 @@ def _get_obj_holidays( subdiv=province, years=year, language=language, - categories=set_categories, # type: ignore[arg-type] + categories=set_categories, ) if (supported_languages := obj_holidays.supported_languages) and language == "en": for lang in supported_languages: @@ -102,7 +102,7 @@ def _get_obj_holidays( subdiv=province, years=year, language=lang, - categories=set_categories, # type: ignore[arg-type] + categories=set_categories, ) LOGGER.debug("Changing language from %s to %s", language, lang) return obj_holidays diff --git a/homeassistant/components/workday/manifest.json b/homeassistant/components/workday/manifest.json index 133c82454bc79..fafa870d00ab1 100644 --- a/homeassistant/components/workday/manifest.json +++ b/homeassistant/components/workday/manifest.json @@ -7,5 +7,5 @@ "iot_class": "local_polling", "loggers": ["holidays"], "quality_scale": "internal", - "requirements": ["holidays==0.54"] + "requirements": ["holidays==0.55"] } diff --git a/requirements_all.txt b/requirements_all.txt index 17ab928a92b92..f0df486d1c610 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1099,7 +1099,7 @@ hole==0.8.0 # homeassistant.components.holiday # homeassistant.components.workday -holidays==0.54 +holidays==0.55 # homeassistant.components.frontend home-assistant-frontend==20240809.0 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index 765352c89ff50..67f19ae081e81 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -922,7 +922,7 @@ hole==0.8.0 # homeassistant.components.holiday # homeassistant.components.workday -holidays==0.54 +holidays==0.55 # homeassistant.components.frontend home-assistant-frontend==20240809.0 From 2ff326b563f34068dcf79247cf4bee282ff747b0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 22 Aug 2024 08:55:16 +0200 Subject: [PATCH 03/31] Bump github/codeql-action from 3.26.2 to 3.26.4 (#124390) --- .github/workflows/codeql.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 45c2b31d772f9..e9824f42b9109 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -24,11 +24,11 @@ jobs: uses: actions/checkout@v4.1.7 - name: Initialize CodeQL - uses: github/codeql-action/init@v3.26.2 + uses: github/codeql-action/init@v3.26.4 with: languages: python - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3.26.2 + uses: github/codeql-action/analyze@v3.26.4 with: category: "/language:python" From 60f9fbf800cd346a18782cf6e6b413acc07fc49d Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 22 Aug 2024 08:55:43 +0200 Subject: [PATCH 04/31] Bump home-assistant/builder from 2024.08.1 to 2024.08.2 (#124341) --- .github/workflows/builder.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/builder.yml b/.github/workflows/builder.yml index 7f3c0b0e66e27..e1f95c5c0a9bc 100644 --- a/.github/workflows/builder.yml +++ b/.github/workflows/builder.yml @@ -197,7 +197,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Build base image - uses: home-assistant/builder@2024.08.1 + uses: home-assistant/builder@2024.08.2 with: args: | $BUILD_ARGS \ @@ -263,7 +263,7 @@ jobs: password: ${{ secrets.GITHUB_TOKEN }} - name: Build base image - uses: home-assistant/builder@2024.08.1 + uses: home-assistant/builder@2024.08.2 with: args: | $BUILD_ARGS \ From 9b9e98a26e25ad6aa9f1ceee9215043476cfd548 Mon Sep 17 00:00:00 2001 From: spongebobberts <133538584+spongebobberts@users.noreply.github.com> Date: Thu, 22 Aug 2024 03:05:13 -0400 Subject: [PATCH 05/31] Fix typo in Alexa resources docstring (#124388) Fixed typo in Alexa resources docstring --- homeassistant/components/alexa/resources.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/alexa/resources.py b/homeassistant/components/alexa/resources.py index 7782716798ae9..4541801d31f7e 100644 --- a/homeassistant/components/alexa/resources.py +++ b/homeassistant/components/alexa/resources.py @@ -283,7 +283,7 @@ class AlexaPresetResource(AlexaCapabilityResource): """Implements Alexa PresetResources. Use presetResources with RangeController to provide a set of - friendlyNamesfor each RangeController preset. + friendlyNames for each RangeController preset. https://developer.amazon.com/docs/device-apis/resources-and-assets.html#presetresources """ From 61114d83285e815742c8ae2e47e5765f9d83d744 Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Thu, 22 Aug 2024 09:07:45 +0200 Subject: [PATCH 06/31] Install and start Mosquitto MQTT broker add on from MQTT config flow (#124106) * Opt in to install Mosquitto broker add-on in MQTT config flow * rephrase * Tests with supervisor and running add-on * Complete tests for success flows * Also set up entry in success flow * Use realistic names for addon and broker * Finetuning and fail test cases * Spelling * Improve translation strings * Update addon docstr Co-authored-by: Erik Montnemery * Raise AddonError if add-on does not start * Only show the option to use the add-on * Simplify flow, rework and cleanup * Revert unrelated cleanup, process suggestion * Move ADDON_SLUG const to addon module * Move fixture to component level * Move back supervisor fixture * Move addon_setup_time_fixture and superfixe to config flow model tests * Refactor hassio fixture * Rename helpers as they are no fixtures, remove fixture from their names --------- Co-authored-by: Erik Montnemery --- homeassistant/components/mqtt/addon.py | 22 + homeassistant/components/mqtt/config_flow.py | 185 +++++++- homeassistant/components/mqtt/const.py | 3 + homeassistant/components/mqtt/strings.json | 17 + tests/components/conftest.py | 91 +++- tests/components/hassio/common.py | 125 +++++ tests/components/mqtt/test_config_flow.py | 451 ++++++++++++++++++- 7 files changed, 876 insertions(+), 18 deletions(-) create mode 100644 homeassistant/components/mqtt/addon.py create mode 100644 tests/components/hassio/common.py diff --git a/homeassistant/components/mqtt/addon.py b/homeassistant/components/mqtt/addon.py new file mode 100644 index 0000000000000..3ac6748033f11 --- /dev/null +++ b/homeassistant/components/mqtt/addon.py @@ -0,0 +1,22 @@ +"""Provide MQTT add-on management. + +Currently only supports the official mosquitto add-on. +""" + +from __future__ import annotations + +from homeassistant.components.hassio import AddonManager +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers.singleton import singleton + +from .const import DOMAIN, LOGGER + +ADDON_SLUG = "core_mosquitto" +DATA_ADDON_MANAGER = f"{DOMAIN}_addon_manager" + + +@singleton(DATA_ADDON_MANAGER) +@callback +def get_addon_manager(hass: HomeAssistant) -> AddonManager: + """Get the add-on manager.""" + return AddonManager(hass, LOGGER, "Mosquitto Mqtt Broker", ADDON_SLUG) diff --git a/homeassistant/components/mqtt/config_flow.py b/homeassistant/components/mqtt/config_flow.py index 17dfc6512b307..a27e34c364c5d 100644 --- a/homeassistant/components/mqtt/config_flow.py +++ b/homeassistant/components/mqtt/config_flow.py @@ -2,8 +2,10 @@ from __future__ import annotations +import asyncio from collections import OrderedDict from collections.abc import Callable, Mapping +import logging import queue from ssl import PROTOCOL_TLS_CLIENT, SSLContext, SSLError from types import MappingProxyType @@ -14,7 +16,12 @@ import voluptuous as vol from homeassistant.components.file_upload import process_uploaded_file -from homeassistant.components.hassio import HassioServiceInfo +from homeassistant.components.hassio import HassioServiceInfo, is_hassio +from homeassistant.components.hassio.addon_manager import ( + AddonError, + AddonManager, + AddonState, +) from homeassistant.config_entries import ( ConfigEntry, ConfigFlow, @@ -32,6 +39,7 @@ CONF_USERNAME, ) from homeassistant.core import callback +from homeassistant.data_entry_flow import AbortFlow from homeassistant.helpers import config_validation as cv from homeassistant.helpers.json import json_dumps from homeassistant.helpers.selector import ( @@ -51,6 +59,7 @@ ) from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads +from .addon import get_addon_manager from .client import MqttClientSetup from .const import ( ATTR_PAYLOAD, @@ -91,6 +100,11 @@ valid_publish_topic, ) +_LOGGER = logging.getLogger(__name__) + +ADDON_SETUP_TIMEOUT = 5 +ADDON_SETUP_TIMEOUT_ROUNDS = 5 + MQTT_TIMEOUT = 5 ADVANCED_OPTIONS = "advanced_options" @@ -197,6 +211,12 @@ class FlowHandler(ConfigFlow, domain=DOMAIN): entry: ConfigEntry | None _hassio_discovery: dict[str, Any] | None = None + _addon_manager: AddonManager + + def __init__(self) -> None: + """Set up flow instance.""" + self.install_task: asyncio.Task | None = None + self.start_task: asyncio.Task | None = None @staticmethod @callback @@ -206,6 +226,118 @@ def async_get_options_flow( """Get the options flow for this handler.""" return MQTTOptionsFlowHandler(config_entry) + async def _async_install_addon(self) -> None: + """Install the Mosquitto Mqtt broker add-on.""" + addon_manager: AddonManager = get_addon_manager(self.hass) + await addon_manager.async_schedule_install_addon() + + async def async_step_install_failed( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Add-on installation failed.""" + return self.async_abort( + reason="addon_install_failed", + description_placeholders={"addon": self._addon_manager.addon_name}, + ) + + async def async_step_install_addon( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Install Mosquitto Broker add-on.""" + if self.install_task is None: + self.install_task = self.hass.async_create_task(self._async_install_addon()) + + if not self.install_task.done(): + return self.async_show_progress( + step_id="install_addon", + progress_action="install_addon", + progress_task=self.install_task, + ) + + try: + await self.install_task + except AddonError as err: + _LOGGER.error(err) + return self.async_show_progress_done(next_step_id="install_failed") + finally: + self.install_task = None + + return self.async_show_progress_done(next_step_id="start_addon") + + async def async_step_start_failed( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Add-on start failed.""" + return self.async_abort( + reason="addon_start_failed", + description_placeholders={"addon": self._addon_manager.addon_name}, + ) + + async def async_step_start_addon( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Start Mosquitto Broker add-on.""" + if not self.start_task: + self.start_task = self.hass.async_create_task(self._async_start_addon()) + if not self.start_task.done(): + return self.async_show_progress( + step_id="start_addon", + progress_action="start_addon", + progress_task=self.start_task, + ) + try: + await self.start_task + except AddonError as err: + _LOGGER.error(err) + return self.async_show_progress_done(next_step_id="start_failed") + finally: + self.start_task = None + + return self.async_show_progress_done(next_step_id="setup_entry_from_discovery") + + async def _async_get_config_and_try(self) -> dict[str, Any] | None: + """Get the MQTT add-on discovery info and try the connection.""" + if self._hassio_discovery is not None: + return self._hassio_discovery + addon_manager: AddonManager = get_addon_manager(self.hass) + try: + addon_discovery_config = ( + await addon_manager.async_get_addon_discovery_info() + ) + config: dict[str, Any] = { + CONF_BROKER: addon_discovery_config[CONF_HOST], + CONF_PORT: addon_discovery_config[CONF_PORT], + CONF_USERNAME: addon_discovery_config.get(CONF_USERNAME), + CONF_PASSWORD: addon_discovery_config.get(CONF_PASSWORD), + CONF_DISCOVERY: DEFAULT_DISCOVERY, + } + except AddonError: + # We do not have discovery information yet + return None + if await self.hass.async_add_executor_job( + try_connection, + config, + ): + self._hassio_discovery = config + return config + return None + + async def _async_start_addon(self) -> None: + """Start the Mosquitto Broker add-on.""" + addon_manager: AddonManager = get_addon_manager(self.hass) + await addon_manager.async_schedule_start_addon() + + # Sleep some seconds to let the add-on start properly before connecting. + for _ in range(ADDON_SETUP_TIMEOUT_ROUNDS): + await asyncio.sleep(ADDON_SETUP_TIMEOUT) + # Finish setup using discovery info to test the connection + if await self._async_get_config_and_try(): + break + else: + raise AddonError( + f"Failed to correctly start {addon_manager.addon_name} add-on" + ) + async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: @@ -213,8 +345,57 @@ async def async_step_user( if self._async_current_entries(): return self.async_abort(reason="single_instance_allowed") + if is_hassio(self.hass): + # Offer to set up broker add-on if supervisor is available + self._addon_manager = get_addon_manager(self.hass) + return self.async_show_menu( + step_id="user", + menu_options=["addon", "broker"], + description_placeholders={"addon": self._addon_manager.addon_name}, + ) + + # Start up a flow for manual setup return await self.async_step_broker() + async def async_step_setup_entry_from_discovery( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Set up mqtt entry from discovery info.""" + if (config := await self._async_get_config_and_try()) is not None: + return self.async_create_entry( + title=self._addon_manager.addon_name, + data=config, + ) + + raise AbortFlow( + "addon_connection_failed", + description_placeholders={"addon": self._addon_manager.addon_name}, + ) + + async def async_step_addon( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Install and start MQTT broker add-on.""" + addon_manager = self._addon_manager + + try: + addon_info = await addon_manager.async_get_addon_info() + except AddonError as err: + raise AbortFlow( + "addon_info_failed", + description_placeholders={"addon": self._addon_manager.addon_name}, + ) from err + + if addon_info.state == AddonState.RUNNING: + # Finish setup using discovery info + return await self.async_step_setup_entry_from_discovery() + + if addon_info.state == AddonState.NOT_RUNNING: + return await self.async_step_start_addon() + + # Install the add-on and start it + return await self.async_step_install_addon() + async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: @@ -293,7 +474,7 @@ async def async_step_broker( async def async_step_hassio( self, discovery_info: HassioServiceInfo ) -> ConfigFlowResult: - """Receive a Hass.io discovery.""" + """Receive a Hass.io discovery or process setup after addon install.""" await self._async_handle_discovery_without_unique_id() self._hassio_discovery = discovery_info.config diff --git a/homeassistant/components/mqtt/const.py b/homeassistant/components/mqtt/const.py index 9a8e6ae22df66..3bf9cf218f27b 100644 --- a/homeassistant/components/mqtt/const.py +++ b/homeassistant/components/mqtt/const.py @@ -1,5 +1,7 @@ """Constants used by multiple MQTT modules.""" +import logging + import jinja2 from homeassistant.const import CONF_PAYLOAD, Platform @@ -148,6 +150,7 @@ } DOMAIN = "mqtt" +LOGGER = logging.getLogger(__package__) MQTT_CONNECTION_STATE = "mqtt_connection_state" diff --git a/homeassistant/components/mqtt/strings.json b/homeassistant/components/mqtt/strings.json index c786d7e08a157..1550d6c8b626d 100644 --- a/homeassistant/components/mqtt/strings.json +++ b/homeassistant/components/mqtt/strings.json @@ -23,6 +23,13 @@ }, "config": { "step": { + "user": { + "description": "Please choose how you want to connect to the MQTT broker:", + "menu_options": { + "addon": "Use the official {addon} add-on.", + "broker": "Manually enter the MQTT broker connection details" + } + }, "broker": { "description": "Please enter the connection information of your MQTT broker.", "data": { @@ -63,6 +70,12 @@ "ws_path": "The WebSocket path to be used for the connection to your MQTT broker." } }, + "install_addon": { + "title": "Installing add-on" + }, + "start_addon": { + "title": "Starting add-on" + }, "hassio_confirm": { "title": "MQTT Broker via Home Assistant add-on", "description": "Do you want to configure Home Assistant to connect to the MQTT broker provided by the add-on {addon}?", @@ -87,6 +100,10 @@ } }, "abort": { + "addon_info_failed": "Failed get info for the {addon} add-on.", + "addon_install_failed": "Failed to install the {addon} add-on.", + "addon_start_failed": "Failed to start the {addon} add-on.", + "addon_connection_failed": "Failed to connect to the {addon} add-on. Check the add-on status and try again later.", "already_configured": "[%key:common::config_flow::abort::already_configured_service%]", "reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]", "single_instance_allowed": "[%key:common::config_flow::abort::single_instance_allowed%]" diff --git a/tests/components/conftest.py b/tests/components/conftest.py index 7d15bde88c007..26da794e03b59 100644 --- a/tests/components/conftest.py +++ b/tests/components/conftest.py @@ -6,7 +6,7 @@ from importlib.util import find_spec from pathlib import Path from typing import TYPE_CHECKING, Any -from unittest.mock import MagicMock, patch +from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -180,3 +180,92 @@ def mock_legacy_device_tracker_setup() -> Callable[[HomeAssistant, MockScanner], from .device_tracker.common import mock_legacy_device_tracker_setup return mock_legacy_device_tracker_setup + + +@pytest.fixture(name="discovery_info") +def discovery_info_fixture() -> Any: + """Return the discovery info from the supervisor.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_discovery_info + + return mock_discovery_info() + + +@pytest.fixture(name="get_addon_discovery_info") +def get_addon_discovery_info_fixture(discovery_info: Any) -> Generator[AsyncMock]: + """Mock get add-on discovery info.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_get_addon_discovery_info + + yield from mock_get_addon_discovery_info(discovery_info) + + +@pytest.fixture(name="addon_store_info") +def addon_store_info_fixture() -> Generator[AsyncMock]: + """Mock Supervisor add-on store info.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_addon_store_info + + yield from mock_addon_store_info() + + +@pytest.fixture(name="addon_info") +def addon_info_fixture() -> Generator[AsyncMock]: + """Mock Supervisor add-on info.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_addon_info + + yield from mock_addon_info() + + +@pytest.fixture(name="addon_not_installed") +def addon_not_installed_fixture( + addon_store_info: AsyncMock, addon_info: AsyncMock +) -> AsyncMock: + """Mock add-on not installed.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_addon_not_installed + + return mock_addon_not_installed(addon_store_info, addon_info) + + +@pytest.fixture(name="addon_installed") +def addon_installed_fixture( + addon_store_info: AsyncMock, addon_info: AsyncMock +) -> AsyncMock: + """Mock add-on already installed but not running.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_addon_installed + + return mock_addon_installed(addon_store_info, addon_info) + + +@pytest.fixture(name="addon_running") +def addon_running_fixture( + addon_store_info: AsyncMock, addon_info: AsyncMock +) -> AsyncMock: + """Mock add-on already running.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_addon_running + + return mock_addon_running(addon_store_info, addon_info) + + +@pytest.fixture(name="install_addon") +def install_addon_fixture( + addon_store_info: AsyncMock, addon_info: AsyncMock +) -> Generator[AsyncMock]: + """Mock install add-on.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_install_addon + + yield from mock_install_addon(addon_store_info, addon_info) + + +@pytest.fixture(name="start_addon") +def start_addon_fixture() -> Generator[AsyncMock]: + """Mock start add-on.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_start_addon + + yield from mock_start_addon() diff --git a/tests/components/hassio/common.py b/tests/components/hassio/common.py new file mode 100644 index 0000000000000..f9a77628bbe42 --- /dev/null +++ b/tests/components/hassio/common.py @@ -0,0 +1,125 @@ +"""Provide common test tools for hassio.""" + +from __future__ import annotations + +from collections.abc import Generator +from typing import Any +from unittest.mock import DEFAULT, AsyncMock, patch + +from homeassistant.core import HomeAssistant + + +def mock_discovery_info() -> Any: + """Return the discovery info from the supervisor.""" + return DEFAULT + + +def mock_get_addon_discovery_info(discovery_info: Any) -> Generator[AsyncMock]: + """Mock get add-on discovery info.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_get_addon_discovery_info", + return_value=discovery_info, + ) as get_addon_discovery_info: + yield get_addon_discovery_info + + +def mock_addon_store_info() -> Generator[AsyncMock]: + """Mock Supervisor add-on store info.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_get_addon_store_info" + ) as addon_store_info: + addon_store_info.return_value = { + "available": False, + "installed": None, + "state": None, + "version": "1.0.0", + } + yield addon_store_info + + +def mock_addon_info() -> Generator[AsyncMock]: + """Mock Supervisor add-on info.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_get_addon_info", + ) as addon_info: + addon_info.return_value = { + "available": False, + "hostname": None, + "options": {}, + "state": None, + "update_available": False, + "version": None, + } + yield addon_info + + +def mock_addon_not_installed( + addon_store_info: AsyncMock, addon_info: AsyncMock +) -> AsyncMock: + """Mock add-on not installed.""" + addon_store_info.return_value["available"] = True + return addon_info + + +def mock_addon_installed( + addon_store_info: AsyncMock, addon_info: AsyncMock +) -> AsyncMock: + """Mock add-on already installed but not running.""" + addon_store_info.return_value = { + "available": True, + "installed": "1.0.0", + "state": "stopped", + "version": "1.0.0", + } + addon_info.return_value["available"] = True + addon_info.return_value["hostname"] = "core-matter-server" + addon_info.return_value["state"] = "stopped" + addon_info.return_value["version"] = "1.0.0" + return addon_info + + +def mock_addon_running(addon_store_info: AsyncMock, addon_info: AsyncMock) -> AsyncMock: + """Mock add-on already running.""" + addon_store_info.return_value = { + "available": True, + "installed": "1.0.0", + "state": "started", + "version": "1.0.0", + } + addon_info.return_value["available"] = True + addon_info.return_value["hostname"] = "core-mosquitto" + addon_info.return_value["state"] = "started" + addon_info.return_value["version"] = "1.0.0" + return addon_info + + +def mock_install_addon( + addon_store_info: AsyncMock, addon_info: AsyncMock +) -> Generator[AsyncMock]: + """Mock install add-on.""" + + async def install_addon_side_effect(hass: HomeAssistant, slug: str) -> None: + """Mock install add-on.""" + addon_store_info.return_value = { + "available": True, + "installed": "1.0.0", + "state": "stopped", + "version": "1.0.0", + } + addon_info.return_value["available"] = True + addon_info.return_value["state"] = "stopped" + addon_info.return_value["version"] = "1.0.0" + + with patch( + "homeassistant.components.hassio.addon_manager.async_install_addon" + ) as install_addon: + install_addon.side_effect = install_addon_side_effect + yield install_addon + + +def mock_start_addon() -> Generator[AsyncMock]: + """Mock start add-on.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_start_addon" + ) as start_addon: + yield start_addon diff --git a/tests/components/mqtt/test_config_flow.py b/tests/components/mqtt/test_config_flow.py index 2b4cb20ccf94f..8e29658e0171a 100644 --- a/tests/components/mqtt/test_config_flow.py +++ b/tests/components/mqtt/test_config_flow.py @@ -14,6 +14,8 @@ from homeassistant import config_entries from homeassistant.components import mqtt from homeassistant.components.hassio import HassioServiceInfo +from homeassistant.components.hassio.addon_manager import AddonError +from homeassistant.components.hassio.handler import HassioAPIError from homeassistant.components.mqtt.config_flow import PWD_NOT_CHANGED from homeassistant.const import ( CONF_CLIENT_ID, @@ -28,6 +30,15 @@ from tests.common import MockConfigEntry from tests.typing import MqttMockHAClientGenerator, MqttMockPahoClient +ADD_ON_DISCOVERY_INFO = { + "addon": "Mosquitto Mqtt Broker", + "host": "core-mosquitto", + "port": 1883, + "username": "mock-user", + "password": "mock-pass", + "protocol": "3.1.1", + "ssl": False, +} MOCK_CLIENT_CERT = b"## mock client certificate file ##" MOCK_CLIENT_KEY = b"## mock key file ##" @@ -186,6 +197,29 @@ def _mock_process_uploaded_file( yield mock_upload +@pytest.fixture(name="supervisor") +def supervisor_fixture() -> Generator[MagicMock]: + """Mock Supervisor.""" + with patch( + "homeassistant.components.mqtt.config_flow.is_hassio", return_value=True + ) as is_hassio: + yield is_hassio + + +@pytest.fixture(name="addon_setup_time", autouse=True) +def addon_setup_time_fixture() -> Generator[int]: + """Mock add-on setup sleep time.""" + with patch( + "homeassistant.components.mqtt.config_flow.ADDON_SETUP_TIMEOUT", new=0 + ) as addon_setup_time: + yield addon_setup_time + + +@pytest.fixture(autouse=True) +def mock_get_addon_discovery_info(get_addon_discovery_info: AsyncMock) -> None: + """Mock get add-on discovery info.""" + + @pytest.mark.usefixtures("mqtt_client_mock") async def test_user_connection_works( hass: HomeAssistant, @@ -216,6 +250,47 @@ async def test_user_connection_works( assert len(mock_finish_setup.mock_calls) == 1 +@pytest.mark.usefixtures("mqtt_client_mock", "supervisor") +async def test_user_connection_works_with_supervisor( + hass: HomeAssistant, + mock_try_connection: MagicMock, + mock_finish_setup: MagicMock, +) -> None: + """Test we can finish a config flow with a supervised install.""" + mock_try_connection.return_value = True + + result = await hass.config_entries.flow.async_init( + "mqtt", context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + assert result["menu_options"] == ["addon", "broker"] + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "broker"}, + ) + + # Assert a manual setup flow + assert result["type"] is FlowResultType.FORM + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"broker": "127.0.0.1"} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].data == { + "broker": "127.0.0.1", + "port": 1883, + "discovery": True, + } + # Check we tried the connection + assert len(mock_try_connection.mock_calls) == 1 + # Check config entry got setup + assert len(mock_finish_setup.mock_calls) == 1 + await hass.async_block_till_done(wait_background_tasks=True) + + @pytest.mark.usefixtures("mqtt_client_mock") async def test_user_v5_connection_works( hass: HomeAssistant, @@ -382,16 +457,8 @@ async def test_hassio_confirm( result = await hass.config_entries.flow.async_init( "mqtt", data=HassioServiceInfo( - config={ - "addon": "Mock Addon", - "host": "mock-broker", - "port": 1883, - "username": "mock-user", - "password": "mock-pass", - "protocol": "3.1.1", # Set by the addon's discovery, ignored by HA - "ssl": False, # Set by the addon's discovery, ignored by HA - }, - name="Mock Addon", + config=ADD_ON_DISCOVERY_INFO.copy(), + name="Mosquitto Mqtt Broker", slug="mosquitto", uuid="1234", ), @@ -399,7 +466,7 @@ async def test_hassio_confirm( ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "hassio_confirm" - assert result["description_placeholders"] == {"addon": "Mock Addon"} + assert result["description_placeholders"] == {"addon": "Mosquitto Mqtt Broker"} mock_try_connection_success.reset_mock() result = await hass.config_entries.flow.async_configure( @@ -408,7 +475,7 @@ async def test_hassio_confirm( assert result["type"] is FlowResultType.CREATE_ENTRY assert result["result"].data == { - "broker": "mock-broker", + "broker": "core-mosquitto", "port": 1883, "username": "mock-user", "password": "mock-pass", @@ -426,14 +493,12 @@ async def test_hassio_cannot_connect( mock_finish_setup: MagicMock, ) -> None: """Test a config flow is aborted when a connection was not successful.""" - mock_try_connection.return_value = True - result = await hass.config_entries.flow.async_init( "mqtt", data=HassioServiceInfo( config={ "addon": "Mock Addon", - "host": "mock-broker", + "host": "core-mosquitto", "port": 1883, "username": "mock-user", "password": "mock-pass", @@ -463,6 +528,362 @@ async def test_hassio_cannot_connect( assert len(mock_finish_setup.mock_calls) == 0 +@pytest.mark.usefixtures( + "mqtt_client_mock", "supervisor", "addon_info", "addon_running" +) +@pytest.mark.parametrize("discovery_info", [{"config": ADD_ON_DISCOVERY_INFO.copy()}]) +async def test_addon_flow_with_supervisor_addon_running( + hass: HomeAssistant, + mock_try_connection_success: MagicMock, + mock_finish_setup: MagicMock, +) -> None: + """Test we perform an auto config flow with a supervised install. + + Case: The Mosquitto add-on is already installed, and running. + """ + # show menu + result = await hass.config_entries.flow.async_init( + "mqtt", context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + assert result["menu_options"] == ["addon", "broker"] + assert result["step_id"] == "user" + + # select install via add-on + mock_try_connection_success.reset_mock() + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "addon"}, + ) + await hass.async_block_till_done(wait_background_tasks=True) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].data == { + "broker": "core-mosquitto", + "port": 1883, + "username": "mock-user", + "password": "mock-pass", + "discovery": True, + } + # Check we tried the connection + assert len(mock_try_connection_success.mock_calls) + # Check config entry got setup + assert len(mock_finish_setup.mock_calls) == 1 + + +@pytest.mark.usefixtures( + "mqtt_client_mock", "supervisor", "addon_info", "addon_installed", "start_addon" +) +@pytest.mark.parametrize("discovery_info", [{"config": ADD_ON_DISCOVERY_INFO.copy()}]) +async def test_addon_flow_with_supervisor_addon_installed( + hass: HomeAssistant, + mock_try_connection_success: MagicMock, + mock_finish_setup: MagicMock, +) -> None: + """Test we perform an auto config flow with a supervised install. + + Case: The Mosquitto add-on is installed, but not running. + """ + # show menu + result = await hass.config_entries.flow.async_init( + "mqtt", context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + assert result["menu_options"] == ["addon", "broker"] + assert result["step_id"] == "user" + + # select install via add-on + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "addon"}, + ) + + # add-on installed but not started, so we wait for start-up + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["progress_action"] == "start_addon" + assert result["step_id"] == "start_addon" + await hass.async_block_till_done() + await hass.async_block_till_done(wait_background_tasks=True) + mock_try_connection_success.reset_mock() + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "start_addon"}, + ) + + # add-on is running, so entry can be installed + await hass.async_block_till_done(wait_background_tasks=True) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].data == { + "broker": "core-mosquitto", + "port": 1883, + "username": "mock-user", + "password": "mock-pass", + "discovery": True, + } + # Check we tried the connection + assert len(mock_try_connection_success.mock_calls) + # Check config entry got setup + assert len(mock_finish_setup.mock_calls) == 1 + + +@pytest.mark.usefixtures( + "mqtt_client_mock", "supervisor", "addon_info", "addon_running" +) +@pytest.mark.parametrize("discovery_info", [{"config": ADD_ON_DISCOVERY_INFO.copy()}]) +async def test_addon_flow_with_supervisor_addon_running_connection_fails( + hass: HomeAssistant, + mock_try_connection: MagicMock, +) -> None: + """Test we perform an auto config flow with a supervised install. + + Case: The Mosquitto add-on is already installed, and running. + """ + # show menu + result = await hass.config_entries.flow.async_init( + "mqtt", context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + assert result["menu_options"] == ["addon", "broker"] + assert result["step_id"] == "user" + + # select install via add-on but the connection fails and the flow will be aborted. + mock_try_connection.return_value = False + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "addon"}, + ) + await hass.async_block_till_done(wait_background_tasks=True) + assert result["type"] is FlowResultType.ABORT + + +@pytest.mark.usefixtures( + "mqtt_client_mock", + "supervisor", + "addon_info", + "addon_installed", +) +async def test_addon_not_running_api_error( + hass: HomeAssistant, + start_addon: AsyncMock, +) -> None: + """Test we perform an auto config flow with a supervised install. + + Case: The Mosquitto add-on start fails on a API error. + """ + start_addon.side_effect = HassioAPIError() + + result = await hass.config_entries.flow.async_init( + "mqtt", context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + assert result["menu_options"] == ["addon", "broker"] + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "addon"}, + ) + # add-on not installed, so we wait for install + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["progress_action"] == "start_addon" + assert result["step_id"] == "start_addon" + await hass.async_block_till_done() + await hass.async_block_till_done(wait_background_tasks=True) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "install_addon"}, + ) + + # add-on start-up failed + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "addon_start_failed" + + +@pytest.mark.usefixtures( + "mqtt_client_mock", + "supervisor", + "start_addon", + "addon_installed", +) +async def test_addon_discovery_info_error( + hass: HomeAssistant, + addon_info: AsyncMock, + get_addon_discovery_info: AsyncMock, +) -> None: + """Test we perform an auto config flow with a supervised install. + + Case: The Mosquitto add-on start on a discovery error. + """ + get_addon_discovery_info.side_effect = AddonError + + result = await hass.config_entries.flow.async_init( + "mqtt", context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + assert result["menu_options"] == ["addon", "broker"] + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "addon"}, + ) + # Addon will retry + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["progress_action"] == "start_addon" + assert result["step_id"] == "start_addon" + await hass.async_block_till_done() + await hass.async_block_till_done(wait_background_tasks=True) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "start_addon"}, + ) + + # add-on start-up failed + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "addon_start_failed" + + +@pytest.mark.usefixtures( + "mqtt_client_mock", + "supervisor", + "start_addon", + "addon_installed", +) +async def test_addon_info_error( + hass: HomeAssistant, + addon_info: AsyncMock, +) -> None: + """Test we perform an auto config flow with a supervised install. + + Case: The Mosquitto add-on info could not be retrieved. + """ + addon_info.side_effect = AddonError() + + result = await hass.config_entries.flow.async_init( + "mqtt", context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + assert result["menu_options"] == ["addon", "broker"] + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "addon"}, + ) + + # add-on info failed + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "addon_info_failed" + + +@pytest.mark.usefixtures( + "mqtt_client_mock", + "supervisor", + "addon_info", + "addon_not_installed", + "install_addon", + "start_addon", +) +@pytest.mark.parametrize("discovery_info", [{"config": ADD_ON_DISCOVERY_INFO.copy()}]) +async def test_addon_flow_with_supervisor_addon_not_installed( + hass: HomeAssistant, + mock_try_connection_success: MagicMock, + mock_finish_setup: MagicMock, +) -> None: + """Test we perform an auto config flow with a supervised install. + + Case: The Mosquitto add-on is not yet installed nor running. + """ + result = await hass.config_entries.flow.async_init( + "mqtt", context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + assert result["menu_options"] == ["addon", "broker"] + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "addon"}, + ) + # add-on not installed, so we wait for install + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["progress_action"] == "install_addon" + assert result["step_id"] == "install_addon" + await hass.async_block_till_done() + await hass.async_block_till_done(wait_background_tasks=True) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "install_addon"}, + ) + + # add-on installed but not started, so we wait for start-up + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["progress_action"] == "start_addon" + assert result["step_id"] == "start_addon" + await hass.async_block_till_done() + await hass.async_block_till_done(wait_background_tasks=True) + mock_try_connection_success.reset_mock() + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "start_addon"}, + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].data == { + "broker": "core-mosquitto", + "port": 1883, + "username": "mock-user", + "password": "mock-pass", + "discovery": True, + } + # Check we tried the connection + assert len(mock_try_connection_success.mock_calls) + # Check config entry got setup + assert len(mock_finish_setup.mock_calls) == 1 + + +@pytest.mark.usefixtures( + "mqtt_client_mock", + "supervisor", + "addon_info", + "addon_not_installed", + "start_addon", +) +async def test_addon_not_installed_failures( + hass: HomeAssistant, + install_addon: AsyncMock, +) -> None: + """Test we perform an auto config flow with a supervised install. + + Case: The Mosquitto add-on install fails. + """ + install_addon.side_effect = HassioAPIError() + + result = await hass.config_entries.flow.async_init( + "mqtt", context={"source": config_entries.SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + assert result["menu_options"] == ["addon", "broker"] + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "addon"}, + ) + # add-on not installed, so we wait for install + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["progress_action"] == "install_addon" + assert result["step_id"] == "install_addon" + await hass.async_block_till_done() + await hass.async_block_till_done(wait_background_tasks=True) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": "install_addon"}, + ) + + # add-on install failed + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "addon_install_failed" + + async def test_option_flow( hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator, From 0c8ed18ca5ded9746bb7d820974494d07b9406a1 Mon Sep 17 00:00:00 2001 From: G Johansson Date: Thu, 22 Aug 2024 09:38:27 +0200 Subject: [PATCH 07/31] Use setup_test_component_platform in Climate tests (#123941) * Use setup_test_component_platform in Climate tests * Rename mock integration helper * Change name to register_test_integration * Change name in tests * Fix ruff format --- tests/components/climate/conftest.py | 50 +++- tests/components/climate/test_init.py | 362 +++++--------------------- 2 files changed, 110 insertions(+), 302 deletions(-) diff --git a/tests/components/climate/conftest.py b/tests/components/climate/conftest.py index fd4368c42191f..4ade8606e77ce 100644 --- a/tests/components/climate/conftest.py +++ b/tests/components/climate/conftest.py @@ -4,10 +4,18 @@ import pytest -from homeassistant.config_entries import ConfigFlow +from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN +from homeassistant.config_entries import ConfigEntry, ConfigFlow +from homeassistant.const import Platform from homeassistant.core import HomeAssistant -from tests.common import mock_config_flow, mock_platform +from tests.common import ( + MockConfigEntry, + MockModule, + mock_config_flow, + mock_integration, + mock_platform, +) class MockFlow(ConfigFlow): @@ -21,3 +29,41 @@ def config_flow_fixture(hass: HomeAssistant) -> Generator[None]: with mock_config_flow("test", MockFlow): yield + + +@pytest.fixture +def register_test_integration( + hass: HomeAssistant, config_flow_fixture: None +) -> Generator: + """Provide a mocked integration for tests.""" + + config_entry = MockConfigEntry(domain="test") + config_entry.add_to_hass(hass) + + async def help_async_setup_entry_init( + hass: HomeAssistant, config_entry: ConfigEntry + ) -> bool: + """Set up test config entry.""" + await hass.config_entries.async_forward_entry_setups( + config_entry, [CLIMATE_DOMAIN] + ) + return True + + async def help_async_unload_entry( + hass: HomeAssistant, config_entry: ConfigEntry + ) -> bool: + """Unload test config emntry.""" + return await hass.config_entries.async_unload_platforms( + config_entry, [Platform.CLIMATE] + ) + + mock_integration( + hass, + MockModule( + "test", + async_setup_entry=help_async_setup_entry_init, + async_unload_entry=help_async_unload_entry, + ), + ) + + return config_entry diff --git a/tests/components/climate/test_init.py b/tests/components/climate/test_init.py index f306551e5400e..256ecf92b1de4 100644 --- a/tests/components/climate/test_init.py +++ b/tests/components/climate/test_init.py @@ -56,6 +56,7 @@ import_and_test_deprecated_constant_enum, mock_integration, mock_platform, + setup_test_component_platform, ) @@ -237,42 +238,15 @@ def test_deprecated_current_constants( async def test_preset_mode_validation( - hass: HomeAssistant, config_flow_fixture: None + hass: HomeAssistant, register_test_integration: MockConfigEntry ) -> None: """Test mode validation for fan, swing and preset.""" + climate_entity = MockClimateEntity(name="test", entity_id="climate.test") - async def async_setup_entry_init( - hass: HomeAssistant, config_entry: ConfigEntry - ) -> bool: - """Set up test config entry.""" - await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN]) - return True - - async def async_setup_entry_climate_platform( - hass: HomeAssistant, - config_entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - ) -> None: - """Set up test climate platform via config entry.""" - async_add_entities([MockClimateEntity(name="test", entity_id="climate.test")]) - - mock_integration( - hass, - MockModule( - "test", - async_setup_entry=async_setup_entry_init, - ), - built_in=False, + setup_test_component_platform( + hass, DOMAIN, entities=[climate_entity], from_config_entry=True ) - mock_platform( - hass, - "test.climate", - MockPlatform(async_setup_entry=async_setup_entry_climate_platform), - ) - - config_entry = MockConfigEntry(domain="test") - config_entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.config_entries.async_setup(register_test_integration.entry_id) await hass.async_block_till_done() state = hass.states.get("climate.test") @@ -402,7 +376,9 @@ def supported_features(self) -> int: async def test_warning_not_implemented_turn_on_off_feature( - hass: HomeAssistant, caplog: pytest.LogCaptureFixture, config_flow_fixture: None + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + register_test_integration: MockConfigEntry, ) -> None: """Test adding feature flag and warn if missing when methods are set.""" @@ -419,43 +395,15 @@ def turn_off(self) -> None: """Turn off.""" called.append("turn_off") - async def async_setup_entry_init( - hass: HomeAssistant, config_entry: ConfigEntry - ) -> bool: - """Set up test config entry.""" - await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN]) - return True - - async def async_setup_entry_climate_platform( - hass: HomeAssistant, - config_entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - ) -> None: - """Set up test climate platform via config entry.""" - async_add_entities( - [MockClimateEntityTest(name="test", entity_id="climate.test")] - ) - - mock_integration( - hass, - MockModule( - "test", - async_setup_entry=async_setup_entry_init, - ), - built_in=False, - ) - mock_platform( - hass, - "test.climate", - MockPlatform(async_setup_entry=async_setup_entry_climate_platform), - ) + climate_entity = MockClimateEntityTest(name="test", entity_id="climate.test") with patch.object( MockClimateEntityTest, "__module__", "tests.custom_components.climate.test_init" ): - config_entry = MockConfigEntry(domain="test") - config_entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(config_entry.entry_id) + setup_test_component_platform( + hass, DOMAIN, entities=[climate_entity], from_config_entry=True + ) + await hass.config_entries.async_setup(register_test_integration.entry_id) await hass.async_block_till_done() state = hass.states.get("climate.test") @@ -499,7 +447,9 @@ async def async_setup_entry_climate_platform( async def test_implicit_warning_not_implemented_turn_on_off_feature( - hass: HomeAssistant, caplog: pytest.LogCaptureFixture, config_flow_fixture: None + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + register_test_integration: MockConfigEntry, ) -> None: """Test adding feature flag and warn if missing when methods are not set. @@ -527,43 +477,15 @@ def hvac_modes(self) -> list[HVACMode]: """ return [HVACMode.OFF, HVACMode.HEAT] - async def async_setup_entry_init( - hass: HomeAssistant, config_entry: ConfigEntry - ) -> bool: - """Set up test config entry.""" - await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN]) - return True - - async def async_setup_entry_climate_platform( - hass: HomeAssistant, - config_entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - ) -> None: - """Set up test climate platform via config entry.""" - async_add_entities( - [MockClimateEntityTest(name="test", entity_id="climate.test")] - ) - - mock_integration( - hass, - MockModule( - "test", - async_setup_entry=async_setup_entry_init, - ), - built_in=False, - ) - mock_platform( - hass, - "test.climate", - MockPlatform(async_setup_entry=async_setup_entry_climate_platform), - ) + climate_entity = MockClimateEntityTest(name="test", entity_id="climate.test") with patch.object( MockClimateEntityTest, "__module__", "tests.custom_components.climate.test_init" ): - config_entry = MockConfigEntry(domain="test") - config_entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(config_entry.entry_id) + setup_test_component_platform( + hass, DOMAIN, entities=[climate_entity], from_config_entry=True + ) + await hass.config_entries.async_setup(register_test_integration.entry_id) await hass.async_block_till_done() state = hass.states.get("climate.test") @@ -579,7 +501,9 @@ async def async_setup_entry_climate_platform( async def test_no_warning_implemented_turn_on_off_feature( - hass: HomeAssistant, caplog: pytest.LogCaptureFixture, config_flow_fixture: None + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + register_test_integration: MockConfigEntry, ) -> None: """Test no warning when feature flags are set.""" @@ -594,43 +518,15 @@ class MockClimateEntityTest(MockClimateEntity): | ClimateEntityFeature.TURN_ON ) - async def async_setup_entry_init( - hass: HomeAssistant, config_entry: ConfigEntry - ) -> bool: - """Set up test config entry.""" - await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN]) - return True - - async def async_setup_entry_climate_platform( - hass: HomeAssistant, - config_entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - ) -> None: - """Set up test climate platform via config entry.""" - async_add_entities( - [MockClimateEntityTest(name="test", entity_id="climate.test")] - ) - - mock_integration( - hass, - MockModule( - "test", - async_setup_entry=async_setup_entry_init, - ), - built_in=False, - ) - mock_platform( - hass, - "test.climate", - MockPlatform(async_setup_entry=async_setup_entry_climate_platform), - ) + climate_entity = MockClimateEntityTest(name="test", entity_id="climate.test") with patch.object( MockClimateEntityTest, "__module__", "tests.custom_components.climate.test_init" ): - config_entry = MockConfigEntry(domain="test") - config_entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(config_entry.entry_id) + setup_test_component_platform( + hass, DOMAIN, entities=[climate_entity], from_config_entry=True + ) + await hass.config_entries.async_setup(register_test_integration.entry_id) await hass.async_block_till_done() state = hass.states.get("climate.test") @@ -651,7 +547,9 @@ async def async_setup_entry_climate_platform( async def test_no_warning_integration_has_migrated( - hass: HomeAssistant, caplog: pytest.LogCaptureFixture, config_flow_fixture: None + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + register_test_integration: MockConfigEntry, ) -> None: """Test no warning when integration migrated using `_enable_turn_on_off_backwards_compatibility`.""" @@ -665,43 +563,15 @@ class MockClimateEntityTest(MockClimateEntity): | ClimateEntityFeature.SWING_MODE ) - async def async_setup_entry_init( - hass: HomeAssistant, config_entry: ConfigEntry - ) -> bool: - """Set up test config entry.""" - await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN]) - return True - - async def async_setup_entry_climate_platform( - hass: HomeAssistant, - config_entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - ) -> None: - """Set up test climate platform via config entry.""" - async_add_entities( - [MockClimateEntityTest(name="test", entity_id="climate.test")] - ) - - mock_integration( - hass, - MockModule( - "test", - async_setup_entry=async_setup_entry_init, - ), - built_in=False, - ) - mock_platform( - hass, - "test.climate", - MockPlatform(async_setup_entry=async_setup_entry_climate_platform), - ) + climate_entity = MockClimateEntityTest(name="test", entity_id="climate.test") with patch.object( MockClimateEntityTest, "__module__", "tests.custom_components.climate.test_init" ): - config_entry = MockConfigEntry(domain="test") - config_entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(config_entry.entry_id) + setup_test_component_platform( + hass, DOMAIN, entities=[climate_entity], from_config_entry=True + ) + await hass.config_entries.async_setup(register_test_integration.entry_id) await hass.async_block_till_done() state = hass.states.get("climate.test") @@ -722,7 +592,9 @@ async def async_setup_entry_climate_platform( async def test_no_warning_integration_implement_feature_flags( - hass: HomeAssistant, caplog: pytest.LogCaptureFixture, config_flow_fixture: None + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + register_test_integration: MockConfigEntry, ) -> None: """Test no warning when integration uses the correct feature flags.""" @@ -737,43 +609,15 @@ class MockClimateEntityTest(MockClimateEntity): | ClimateEntityFeature.TURN_ON ) - async def async_setup_entry_init( - hass: HomeAssistant, config_entry: ConfigEntry - ) -> bool: - """Set up test config entry.""" - await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN]) - return True - - async def async_setup_entry_climate_platform( - hass: HomeAssistant, - config_entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - ) -> None: - """Set up test climate platform via config entry.""" - async_add_entities( - [MockClimateEntityTest(name="test", entity_id="climate.test")] - ) - - mock_integration( - hass, - MockModule( - "test", - async_setup_entry=async_setup_entry_init, - ), - built_in=False, - ) - mock_platform( - hass, - "test.climate", - MockPlatform(async_setup_entry=async_setup_entry_climate_platform), - ) + climate_entity = MockClimateEntityTest(name="test", entity_id="climate.test") with patch.object( MockClimateEntityTest, "__module__", "tests.custom_components.climate.test_init" ): - config_entry = MockConfigEntry(domain="test") - config_entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(config_entry.entry_id) + setup_test_component_platform( + hass, DOMAIN, entities=[climate_entity], from_config_entry=True + ) + await hass.config_entries.async_setup(register_test_integration.entry_id) await hass.async_block_till_done() state = hass.states.get("climate.test") @@ -1022,7 +866,7 @@ async def async_setup_entry_climate_platform( async def test_no_issue_aux_property_deprecated_for_core( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, - config_flow_fixture: None, + register_test_integration: MockConfigEntry, manifest_extra: dict[str, str], translation_key: str, translation_placeholders_extra: dict[str, str], @@ -1061,39 +905,10 @@ async def async_turn_aux_heat_off(self) -> None: entity_id="climate.testing", ) - async def async_setup_entry_init( - hass: HomeAssistant, config_entry: ConfigEntry - ) -> bool: - """Set up test config entry.""" - await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN]) - return True - - async def async_setup_entry_climate_platform( - hass: HomeAssistant, - config_entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - ) -> None: - """Set up test weather platform via config entry.""" - async_add_entities([climate_entity]) - - mock_integration( - hass, - MockModule( - "test", - async_setup_entry=async_setup_entry_init, - partial_manifest=manifest_extra, - ), - built_in=False, + setup_test_component_platform( + hass, DOMAIN, entities=[climate_entity], from_config_entry=True ) - mock_platform( - hass, - "test.climate", - MockPlatform(async_setup_entry=async_setup_entry_climate_platform), - ) - - config_entry = MockConfigEntry(domain="test") - config_entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.config_entries.async_setup(register_test_integration.entry_id) await hass.async_block_till_done() assert climate_entity.state == HVACMode.HEAT @@ -1111,7 +926,7 @@ async def async_setup_entry_climate_platform( async def test_no_issue_no_aux_property( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, - config_flow_fixture: None, + register_test_integration: MockConfigEntry, issue_registry: ir.IssueRegistry, ) -> None: """Test the issue is raised on deprecated auxiliary heater attributes.""" @@ -1121,38 +936,10 @@ async def test_no_issue_no_aux_property( entity_id="climate.testing", ) - async def async_setup_entry_init( - hass: HomeAssistant, config_entry: ConfigEntry - ) -> bool: - """Set up test config entry.""" - await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN]) - return True - - async def async_setup_entry_climate_platform( - hass: HomeAssistant, - config_entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - ) -> None: - """Set up test weather platform via config entry.""" - async_add_entities([climate_entity]) - - mock_integration( - hass, - MockModule( - "test", - async_setup_entry=async_setup_entry_init, - ), - built_in=False, - ) - mock_platform( - hass, - "test.climate", - MockPlatform(async_setup_entry=async_setup_entry_climate_platform), + setup_test_component_platform( + hass, DOMAIN, entities=[climate_entity], from_config_entry=True ) - - config_entry = MockConfigEntry(domain="test") - config_entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(config_entry.entry_id) + assert await hass.config_entries.async_setup(register_test_integration.entry_id) await hass.async_block_till_done() assert climate_entity.state == HVACMode.HEAT @@ -1167,7 +954,7 @@ async def async_setup_entry_climate_platform( async def test_temperature_validation( - hass: HomeAssistant, config_flow_fixture: None + hass: HomeAssistant, register_test_integration: MockConfigEntry ) -> None: """Test validation for temperatures.""" @@ -1194,40 +981,15 @@ def set_temperature(self, **kwargs: Any) -> None: self._attr_target_temperature_high = kwargs[ATTR_TARGET_TEMP_HIGH] self._attr_target_temperature_low = kwargs[ATTR_TARGET_TEMP_LOW] - async def async_setup_entry_init( - hass: HomeAssistant, config_entry: ConfigEntry - ) -> bool: - """Set up test config entry.""" - await hass.config_entries.async_forward_entry_setups(config_entry, [DOMAIN]) - return True - - async def async_setup_entry_climate_platform( - hass: HomeAssistant, - config_entry: ConfigEntry, - async_add_entities: AddEntitiesCallback, - ) -> None: - """Set up test climate platform via config entry.""" - async_add_entities( - [MockClimateEntityTemp(name="test", entity_id="climate.test")] - ) - - mock_integration( - hass, - MockModule( - "test", - async_setup_entry=async_setup_entry_init, - ), - built_in=False, - ) - mock_platform( - hass, - "test.climate", - MockPlatform(async_setup_entry=async_setup_entry_climate_platform), + test_climate = MockClimateEntityTemp( + name="Test", + unique_id="unique_climate_test", ) - config_entry = MockConfigEntry(domain="test") - config_entry.add_to_hass(hass) - assert await hass.config_entries.async_setup(config_entry.entry_id) + setup_test_component_platform( + hass, DOMAIN, entities=[test_climate], from_config_entry=True + ) + await hass.config_entries.async_setup(register_test_integration.entry_id) await hass.async_block_till_done() state = hass.states.get("climate.test") From b541d214ed8859a95cfce115610289f5675d0a4e Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Thu, 22 Aug 2024 11:03:35 +0200 Subject: [PATCH 08/31] Fix lingering mqtt unload entry test (#124392) --- tests/components/mqtt/test_device_trigger.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/components/mqtt/test_device_trigger.py b/tests/components/mqtt/test_device_trigger.py index 10322dd90468a..1acfe8dd9f5a9 100644 --- a/tests/components/mqtt/test_device_trigger.py +++ b/tests/components/mqtt/test_device_trigger.py @@ -18,7 +18,7 @@ from .test_common import help_test_unload_config_entry from tests.common import async_fire_mqtt_message, async_get_device_automations -from tests.typing import MqttMockHAClient, MqttMockHAClientGenerator, WebSocketGenerator +from tests.typing import MqttMockHAClientGenerator, WebSocketGenerator @pytest.fixture(autouse=True, name="stub_blueprint_populate") @@ -1672,11 +1672,11 @@ async def test_trigger_debug_info( assert debug_info_data["triggers"][0]["discovery_data"]["payload"] == config2 +@pytest.mark.usefixtures("mqtt_mock") async def test_unload_entry( hass: HomeAssistant, service_calls: list[ServiceCall], device_registry: dr.DeviceRegistry, - mqtt_mock: MqttMockHAClient, ) -> None: """Test unloading the MQTT entry.""" @@ -1738,3 +1738,4 @@ async def test_unload_entry( async_fire_mqtt_message(hass, "foobar/triggers/button1", "short_press") await hass.async_block_till_done() assert len(service_calls) == 2 + await hass.async_block_till_done(wait_background_tasks=True) From 480e748b04942bf582ab19a3a7dde2423d83bbc2 Mon Sep 17 00:00:00 2001 From: TimL Date: Thu, 22 Aug 2024 20:04:03 +1000 Subject: [PATCH 09/31] Bump pysmlight to 0.0.13 (#124398) Better handle socket uptime disconnected Raise auth error on get/post requests that fail --- homeassistant/components/smlight/manifest.json | 2 +- requirements_all.txt | 2 +- requirements_test_all.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/smlight/manifest.json b/homeassistant/components/smlight/manifest.json index 0dbd25e90bd55..72d915666e520 100644 --- a/homeassistant/components/smlight/manifest.json +++ b/homeassistant/components/smlight/manifest.json @@ -6,7 +6,7 @@ "documentation": "https://www.home-assistant.io/integrations/smlight", "integration_type": "device", "iot_class": "local_polling", - "requirements": ["pysmlight==0.0.12"], + "requirements": ["pysmlight==0.0.13"], "zeroconf": [ { "type": "_slzb-06._tcp.local." diff --git a/requirements_all.txt b/requirements_all.txt index f0df486d1c610..78215689479cc 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2214,7 +2214,7 @@ pysmartthings==0.7.8 pysml==0.0.12 # homeassistant.components.smlight -pysmlight==0.0.12 +pysmlight==0.0.13 # homeassistant.components.snmp pysnmp==6.2.5 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index 67f19ae081e81..afbbfb396ac50 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -1768,7 +1768,7 @@ pysmartthings==0.7.8 pysml==0.0.12 # homeassistant.components.smlight -pysmlight==0.0.12 +pysmlight==0.0.13 # homeassistant.components.snmp pysnmp==6.2.5 From ab6d0e32776ea402dc8cce9a7c8580097c1d4f2f Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Thu, 22 Aug 2024 12:08:24 +0200 Subject: [PATCH 10/31] Handle !include without arguments in configuration.yaml (#124399) * Prevent !include without arguments in configuration.yaml from crashing core * Add test --- homeassistant/util/yaml/loader.py | 18 ++++++++++++++++++ tests/util/yaml/test_init.py | 20 ++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/homeassistant/util/yaml/loader.py b/homeassistant/util/yaml/loader.py index ff9b7cb360193..4b7236d70223b 100644 --- a/homeassistant/util/yaml/loader.py +++ b/homeassistant/util/yaml/loader.py @@ -348,6 +348,20 @@ def _add_reference_to_node_class( return obj +def _raise_if_no_value[NodeT: yaml.nodes.Node, _R]( + func: Callable[[LoaderType, NodeT], _R], +) -> Callable[[LoaderType, NodeT], _R]: + def wrapper(loader: LoaderType, node: NodeT) -> _R: + if not node.value: + raise HomeAssistantError( + f"{node.start_mark}: {node.tag} needs an argument." + ) + return func(loader, node) + + return wrapper + + +@_raise_if_no_value def _include_yaml(loader: LoaderType, node: yaml.nodes.Node) -> JSON_TYPE: """Load another YAML file and embed it using the !include tag. @@ -382,6 +396,7 @@ def _find_files(directory: str, pattern: str) -> Iterator[str]: yield filename +@_raise_if_no_value def _include_dir_named_yaml(loader: LoaderType, node: yaml.nodes.Node) -> NodeDictClass: """Load multiple files from directory as a dictionary.""" mapping = NodeDictClass() @@ -399,6 +414,7 @@ def _include_dir_named_yaml(loader: LoaderType, node: yaml.nodes.Node) -> NodeDi return _add_reference_to_node_class(mapping, loader, node) +@_raise_if_no_value def _include_dir_merge_named_yaml( loader: LoaderType, node: yaml.nodes.Node ) -> NodeDictClass: @@ -414,6 +430,7 @@ def _include_dir_merge_named_yaml( return _add_reference_to_node_class(mapping, loader, node) +@_raise_if_no_value def _include_dir_list_yaml( loader: LoaderType, node: yaml.nodes.Node ) -> list[JSON_TYPE]: @@ -427,6 +444,7 @@ def _include_dir_list_yaml( ] +@_raise_if_no_value def _include_dir_merge_list_yaml( loader: LoaderType, node: yaml.nodes.Node ) -> JSON_TYPE: diff --git a/tests/util/yaml/test_init.py b/tests/util/yaml/test_init.py index ece65504ed65c..793ba3183ada0 100644 --- a/tests/util/yaml/test_init.py +++ b/tests/util/yaml/test_init.py @@ -726,3 +726,23 @@ def test_load_yaml_dict_fail() -> None: """Test item without a key.""" with pytest.raises(yaml_loader.YamlTypeError): yaml_loader.load_yaml_dict(YAML_CONFIG_FILE) + + +@pytest.mark.parametrize( + "tag", + [ + "!include", + "!include_dir_named", + "!include_dir_merge_named", + "!include_dir_list", + "!include_dir_merge_list", + ], +) +@pytest.mark.usefixtures("try_both_loaders") +def test_include_without_parameter(tag: str) -> None: + """Test include extensions without parameters.""" + with ( + io.StringIO(f"key: {tag}") as file, + pytest.raises(HomeAssistantError, match=f"{tag} needs an argument"), + ): + yaml_loader.parse_yaml(file) From 4e3bd55c737807e77f6ac853026a67136458d7e0 Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Thu, 22 Aug 2024 12:11:07 +0200 Subject: [PATCH 11/31] Revert UnitOfReactivePower change from iotawatt (#124393) Revert "Change POWER_VOLT_AMPERE_REACTIVE to UnitOfReactivePower (#117153)" This reverts commit 3e53cc175f78d8224f539e08dc6978c6cee3b41f. --- homeassistant/components/iotawatt/const.py | 1 + homeassistant/components/iotawatt/sensor.py | 5 ++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/iotawatt/const.py b/homeassistant/components/iotawatt/const.py index 278030d4f103c..de008388f6220 100644 --- a/homeassistant/components/iotawatt/const.py +++ b/homeassistant/components/iotawatt/const.py @@ -7,6 +7,7 @@ import httpx DOMAIN = "iotawatt" +VOLT_AMPERE_REACTIVE = "VAR" VOLT_AMPERE_REACTIVE_HOURS = "VARh" CONNECTION_ERRORS = (KeyError, json.JSONDecodeError, httpx.HTTPError) diff --git a/homeassistant/components/iotawatt/sensor.py b/homeassistant/components/iotawatt/sensor.py index e0328ea9d58ef..c9af588c1606a 100644 --- a/homeassistant/components/iotawatt/sensor.py +++ b/homeassistant/components/iotawatt/sensor.py @@ -23,7 +23,6 @@ UnitOfEnergy, UnitOfFrequency, UnitOfPower, - UnitOfReactivePower, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er @@ -32,7 +31,7 @@ from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.util import dt as dt_util -from .const import DOMAIN, VOLT_AMPERE_REACTIVE_HOURS +from .const import DOMAIN, VOLT_AMPERE_REACTIVE, VOLT_AMPERE_REACTIVE_HOURS from .coordinator import IotawattUpdater _LOGGER = logging.getLogger(__name__) @@ -90,7 +89,7 @@ class IotaWattSensorEntityDescription(SensorEntityDescription): ), "VAR": IotaWattSensorEntityDescription( key="VAR", - native_unit_of_measurement=UnitOfReactivePower.VOLT_AMPERE_REACTIVE, + native_unit_of_measurement=VOLT_AMPERE_REACTIVE, state_class=SensorStateClass.MEASUREMENT, icon="mdi:flash", entity_registry_enabled_default=False, From 403db6277fce9332e5978e9de74af040bbc94fb2 Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Thu, 22 Aug 2024 14:50:45 +0200 Subject: [PATCH 12/31] Improve type hints in lcn tests (#124415) --- tests/components/lcn/test_config_flow.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/tests/components/lcn/test_config_flow.py b/tests/components/lcn/test_config_flow.py index e4cb4c588e999..d002c5fe62528 100644 --- a/tests/components/lcn/test_config_flow.py +++ b/tests/components/lcn/test_config_flow.py @@ -129,7 +129,7 @@ async def test_show_form(hass: HomeAssistant) -> None: assert result["step_id"] == "user" -async def test_step_user(hass): +async def test_step_user(hass: HomeAssistant) -> None: """Test for user step.""" with ( patch("pypck.connection.PchkConnectionManager.async_connect"), @@ -150,7 +150,9 @@ async def test_step_user(hass): } -async def test_step_user_existing_host(hass, entry): +async def test_step_user_existing_host( + hass: HomeAssistant, entry: MockConfigEntry +) -> None: """Test for user defined host already exists.""" entry.add_to_hass(hass) @@ -172,7 +174,9 @@ async def test_step_user_existing_host(hass, entry): (TimeoutError, {CONF_BASE: "connection_refused"}), ], ) -async def test_step_user_error(hass, error, errors): +async def test_step_user_error( + hass: HomeAssistant, error: type[Exception], errors: dict[str, str] +) -> None: """Test for error in user step is handled correctly.""" with patch( "pypck.connection.PchkConnectionManager.async_connect", side_effect=error @@ -187,7 +191,7 @@ async def test_step_user_error(hass, error, errors): assert result["errors"] == errors -async def test_step_reconfigure(hass, entry): +async def test_step_reconfigure(hass: HomeAssistant, entry: MockConfigEntry) -> None: """Test for reconfigure step.""" entry.add_to_hass(hass) old_entry_data = entry.data.copy() @@ -222,7 +226,12 @@ async def test_step_reconfigure(hass, entry): (TimeoutError, {CONF_BASE: "connection_refused"}), ], ) -async def test_step_reconfigure_error(hass, entry, error, errors): +async def test_step_reconfigure_error( + hass: HomeAssistant, + entry: MockConfigEntry, + error: type[Exception], + errors: dict[str, str], +) -> None: """Test for error in reconfigure step is handled correctly.""" entry.add_to_hass(hass) with patch( @@ -242,7 +251,7 @@ async def test_step_reconfigure_error(hass, entry, error, errors): assert result["errors"] == errors -async def test_validate_connection(): +async def test_validate_connection() -> None: """Test the connection validation.""" data = CONNECTION_DATA.copy() From 1bc0ec201ad311af0726431f7e105b4e91ec9f93 Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Thu, 22 Aug 2024 15:13:00 +0200 Subject: [PATCH 13/31] Drop ignore-missing-annotations from pylint tests (#120302) --- .github/workflows/ci.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 0f0850ade1af3..f6ffa439d9b32 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -716,14 +716,14 @@ jobs: run: | . venv/bin/activate python --version - pylint --ignore-missing-annotations=y tests + pylint tests - name: Run pylint (partially) if: needs.info.outputs.test_full_suite == 'false' shell: bash run: | . venv/bin/activate python --version - pylint --ignore-missing-annotations=y tests/components/${{ needs.info.outputs.tests_glob }} + pylint tests/components/${{ needs.info.outputs.tests_glob }} mypy: name: Check mypy From df8256735672abbe09d79b72787d55b96d5e14ba Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 22 Aug 2024 08:14:45 -0500 Subject: [PATCH 14/31] Fix shelly available check when device is not initialized (#124182) * Fix shelly available check when device is not initialized available needs to check for device.initialized or if the device is sleepy as calls to status will raise NotInitialized which results in many unretrieved exceptions while writing state fixes ``` 2024-08-18 09:33:03.757 ERROR (MainThread) [homeassistant] Error doing job: Task exception was never retrieved (None) Traceback (most recent call last): File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 258, in _handle_refresh_interval await self._async_refresh(log_failures=True, scheduled=True) File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 453, in _async_refresh self.async_update_listeners() File "/usr/src/homeassistant/homeassistant/helpers/update_coordinator.py", line 168, in async_update_listeners update_callback() File "/config/custom_components/shelly/entity.py", line 374, in _update_callback self.async_write_ha_state() File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1005, in async_write_ha_state self._async_write_ha_state() File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1130, in _async_write_ha_state self.__async_calculate_state() File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1067, in __async_calculate_state state = self._stringify_state(available) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 1011, in _stringify_state if (state := self.state) is None: ^^^^^^^^^^ File "/usr/src/homeassistant/homeassistant/components/binary_sensor/__init__.py", line 293, in state if (is_on := self.is_on) is None: ^^^^^^^^^^ File "/config/custom_components/shelly/binary_sensor.py", line 331, in is_on return bool(self.attribute_value) ^^^^^^^^^^^^^^^^^^^^ File "/config/custom_components/shelly/entity.py", line 545, in attribute_value self._last_value = self.sub_status ^^^^^^^^^^^^^^^ File "/config/custom_components/shelly/entity.py", line 534, in sub_status return self.status[self.entity_description.sub_key] ^^^^^^^^^^^ File "/config/custom_components/shelly/entity.py", line 364, in status return cast(dict, self.coordinator.device.status[self.key]) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.12/site-packages/aioshelly/rpc_device/device.py", line 390, in status raise NotInitialized aioshelly.exceptions.NotInitialized ``` * tweak * cover * fix * cover * fixes --- .../components/shelly/coordinator.py | 3 ++ homeassistant/components/shelly/entity.py | 8 +++++ tests/components/shelly/test_sensor.py | 34 ++++++++++++++++++- 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/shelly/coordinator.py b/homeassistant/components/shelly/coordinator.py index 2710565f9601c..6286e5157271f 100644 --- a/homeassistant/components/shelly/coordinator.py +++ b/homeassistant/components/shelly/coordinator.py @@ -682,6 +682,7 @@ def _async_handle_update( self.entry.async_create_background_task( self.hass, self._async_connected(), "rpc device init", eager_start=True ) + # Make sure entities are marked available self.async_set_updated_data(None) elif update_type is RpcUpdateType.DISCONNECTED: self.entry.async_create_background_task( @@ -690,6 +691,8 @@ def _async_handle_update( "rpc device disconnected", eager_start=True, ) + # Make sure entities are marked as unavailable + self.async_set_updated_data(None) elif update_type is RpcUpdateType.STATUS: self.async_set_updated_data(None) if self.sleep_period: diff --git a/homeassistant/components/shelly/entity.py b/homeassistant/components/shelly/entity.py index 5bf8a4113778e..980a39feaba91 100644 --- a/homeassistant/components/shelly/entity.py +++ b/homeassistant/components/shelly/entity.py @@ -358,6 +358,14 @@ def __init__(self, coordinator: ShellyRpcCoordinator, key: str) -> None: self._attr_unique_id = f"{coordinator.mac}-{key}" self._attr_name = get_rpc_entity_name(coordinator.device, key) + @property + def available(self) -> bool: + """Check if device is available and initialized or sleepy.""" + coordinator = self.coordinator + return super().available and ( + coordinator.device.initialized or bool(coordinator.sleep_period) + ) + @property def status(self) -> dict: """Device status by entity key.""" diff --git a/tests/components/shelly/test_sensor.py b/tests/components/shelly/test_sensor.py index 843270107e0a0..7aa4218341f56 100644 --- a/tests/components/shelly/test_sensor.py +++ b/tests/components/shelly/test_sensor.py @@ -47,7 +47,7 @@ register_entity, ) -from tests.common import mock_restore_cache_with_extra_data +from tests.common import async_fire_time_changed, mock_restore_cache_with_extra_data RELAY_BLOCK_ID = 0 SENSOR_BLOCK_ID = 3 @@ -1279,3 +1279,35 @@ async def test_rpc_rgbw_sensors( entry = entity_registry.async_get(entity_id) assert entry assert entry.unique_id == f"123456789ABC-{light_type}:0-temperature_{light_type}" + + +async def test_rpc_device_sensor_goes_unavailable_on_disconnect( + hass: HomeAssistant, + mock_rpc_device: Mock, + monkeypatch: pytest.MonkeyPatch, + freezer: FrozenDateTimeFactory, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test RPC device with sensor goes unavailable on disconnect.""" + await init_integration(hass, 2) + temp_sensor_state = hass.states.get("sensor.test_name_temperature") + assert temp_sensor_state is not None + assert temp_sensor_state.state != STATE_UNAVAILABLE + monkeypatch.setattr(mock_rpc_device, "connected", False) + monkeypatch.setattr(mock_rpc_device, "initialized", False) + mock_rpc_device.mock_disconnected() + await hass.async_block_till_done() + temp_sensor_state = hass.states.get("sensor.test_name_temperature") + assert temp_sensor_state.state == STATE_UNAVAILABLE + + freezer.tick(60) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert "NotInitialized" not in caplog.text + + monkeypatch.setattr(mock_rpc_device, "connected", True) + monkeypatch.setattr(mock_rpc_device, "initialized", True) + mock_rpc_device.mock_initialized() + await hass.async_block_till_done() + temp_sensor_state = hass.states.get("sensor.test_name_temperature") + assert temp_sensor_state.state != STATE_UNAVAILABLE From c541cb5cbaf1ddb59e977436ffdc9e8a3a492364 Mon Sep 17 00:00:00 2001 From: Jakob Schlyter Date: Thu, 22 Aug 2024 15:36:11 +0200 Subject: [PATCH 15/31] Automatically generate Amazon Polly list of voices and regions (#119198) * Automatically generate list of voices and regions. Requires AWS credentials. * add missing commit * replace pydantic with dataclass * dictionary values are strings or list of strings * also generated set of supported engines * use sets for amazon polly parameters * move default for readability --- .../components/amazon_polly/const.py | 121 ++-------------- homeassistant/components/amazon_polly/tts.py | 8 +- homeassistant/generated/amazon_polly.py | 137 ++++++++++++++++++ script/amazon_polly.py | 70 +++++++++ 4 files changed, 221 insertions(+), 115 deletions(-) create mode 100644 homeassistant/generated/amazon_polly.py create mode 100644 script/amazon_polly.py diff --git a/homeassistant/components/amazon_polly/const.py b/homeassistant/components/amazon_polly/const.py index bb196544fc3d4..40b1bba3ddddd 100644 --- a/homeassistant/components/amazon_polly/const.py +++ b/homeassistant/components/amazon_polly/const.py @@ -8,128 +8,23 @@ CONF_ACCESS_KEY_ID: Final = "aws_access_key_id" CONF_SECRET_ACCESS_KEY: Final = "aws_secret_access_key" -DEFAULT_REGION: Final = "us-east-1" -SUPPORTED_REGIONS: Final[list[str]] = [ - "us-east-1", - "us-east-2", - "us-west-1", - "us-west-2", - "ca-central-1", - "eu-west-1", - "eu-central-1", - "eu-west-2", - "eu-west-3", - "ap-southeast-1", - "ap-southeast-2", - "ap-northeast-2", - "ap-northeast-1", - "ap-south-1", - "sa-east-1", -] - CONF_ENGINE: Final = "engine" CONF_VOICE: Final = "voice" CONF_OUTPUT_FORMAT: Final = "output_format" CONF_SAMPLE_RATE: Final = "sample_rate" CONF_TEXT_TYPE: Final = "text_type" -SUPPORTED_VOICES: Final[list[str]] = [ - "Aditi", # Hindi - "Amy", # English (British) - "Aria", # English (New Zealand), Neural - "Arlet", # Catalan, Neural - "Arthur", # English, Neural - "Astrid", # Swedish - "Ayanda", # English (South African), Neural - "Bianca", # Italian - "Brian", # English (British) - "Camila", # Portuguese, Brazilian - "Carla", # Italian - "Carmen", # Romanian - "Celine", # French - "Chantal", # French Canadian - "Conchita", # Spanish (European) - "Cristiano", # Portuguese (European) - "Daniel", # German, Neural - "Dora", # Icelandic - "Elin", # Swedish, Neural - "Emma", # English - "Enrique", # Spanish (European) - "Ewa", # Polish - "Filiz", # Turkish - "Gabrielle", # French (Canadian) - "Geraint", # English Welsh - "Giorgio", # Italian - "Gwyneth", # Welsh - "Hala", # Arabic (Gulf), Neural - "Hannah", # German (Austrian), Neural - "Hans", # German - "Hiujin", # Chinese (Cantonese), Neural - "Ida", # Norwegian, Neural - "Ines", # Portuguese, European # codespell:ignore ines - "Ivy", # English - "Jacek", # Polish - "Jan", # Polish - "Joanna", # English - "Joey", # English - "Justin", # English - "Kajal", # English (Indian)/Hindi (Bilingual ), Neural - "Karl", # Icelandic - "Kendra", # English - "Kevin", # English, Neural - "Kimberly", # English - "Laura", # Dutch, Neural - "Lea", # French - "Liam", # Canadian French, Neural - "Liv", # Norwegian - "Lotte", # Dutch - "Lucia", # Spanish European - "Lupe", # Spanish US - "Mads", # Danish - "Maja", # Polish - "Marlene", # German - "Mathieu", # French - "Matthew", # English - "Maxim", # Russian - "Mia", # Spanish Mexican - "Miguel", # Spanish US - "Mizuki", # Japanese - "Naja", # Danish - "Nicole", # English Australian - "Ola", # Polish, Neural - "Olivia", # Female, Australian, Neural - "Penelope", # Spanish US - "Pedro", # Spanish US, Neural - "Raveena", # English, Indian - "Ricardo", # Portuguese (Brazilian) - "Ruben", # Dutch - "Russell", # English (Australian) - "Ruth", # English, Neural - "Salli", # English - "Seoyeon", # Korean - "Stephen", # English, Neural - "Suvi", # Finnish - "Takumi", # Japanese - "Tatyana", # Russian - "Vicki", # German - "Vitoria", # Portuguese, Brazilian - "Zeina", # Arabic - "Zhiyu", # Chinese -] - -SUPPORTED_OUTPUT_FORMATS: Final[list[str]] = ["mp3", "ogg_vorbis", "pcm"] +SUPPORTED_OUTPUT_FORMATS: Final[set[str]] = {"mp3", "ogg_vorbis", "pcm"} -SUPPORTED_ENGINES: Final[list[str]] = ["neural", "standard"] +SUPPORTED_SAMPLE_RATES: Final[set[str]] = {"8000", "16000", "22050", "24000"} -SUPPORTED_SAMPLE_RATES: Final[list[str]] = ["8000", "16000", "22050", "24000"] - -SUPPORTED_SAMPLE_RATES_MAP: Final[dict[str, list[str]]] = { - "mp3": ["8000", "16000", "22050", "24000"], - "ogg_vorbis": ["8000", "16000", "22050"], - "pcm": ["8000", "16000"], +SUPPORTED_SAMPLE_RATES_MAP: Final[dict[str, set[str]]] = { + "mp3": {"8000", "16000", "22050", "24000"}, + "ogg_vorbis": {"8000", "16000", "22050"}, + "pcm": {"8000", "16000"}, } -SUPPORTED_TEXT_TYPES: Final[list[str]] = ["text", "ssml"] +SUPPORTED_TEXT_TYPES: Final[set[str]] = {"text", "ssml"} CONTENT_TYPE_EXTENSIONS: Final[dict[str, str]] = { "audio/mpeg": "mp3", @@ -137,6 +32,8 @@ "audio/pcm": "pcm", } +DEFAULT_REGION: Final = "us-east-1" + DEFAULT_ENGINE: Final = "standard" DEFAULT_VOICE: Final = "Joanna" DEFAULT_OUTPUT_FORMAT: Final = "mp3" diff --git a/homeassistant/components/amazon_polly/tts.py b/homeassistant/components/amazon_polly/tts.py index d5cb7092fe3bc..1fc972fa3a118 100644 --- a/homeassistant/components/amazon_polly/tts.py +++ b/homeassistant/components/amazon_polly/tts.py @@ -16,6 +16,11 @@ ) from homeassistant.const import ATTR_CREDENTIALS, CONF_PROFILE_NAME from homeassistant.core import HomeAssistant +from homeassistant.generated.amazon_polly import ( + SUPPORTED_ENGINES, + SUPPORTED_REGIONS, + SUPPORTED_VOICES, +) import homeassistant.helpers.config_validation as cv from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType @@ -38,13 +43,10 @@ DEFAULT_SAMPLE_RATES, DEFAULT_TEXT_TYPE, DEFAULT_VOICE, - SUPPORTED_ENGINES, SUPPORTED_OUTPUT_FORMATS, - SUPPORTED_REGIONS, SUPPORTED_SAMPLE_RATES, SUPPORTED_SAMPLE_RATES_MAP, SUPPORTED_TEXT_TYPES, - SUPPORTED_VOICES, ) _LOGGER: Final = logging.getLogger(__name__) diff --git a/homeassistant/generated/amazon_polly.py b/homeassistant/generated/amazon_polly.py new file mode 100644 index 0000000000000..1d870bf6c92f7 --- /dev/null +++ b/homeassistant/generated/amazon_polly.py @@ -0,0 +1,137 @@ +"""Automatically generated file. + +To update, run python3 -m script.amazon_polly +""" + +from __future__ import annotations + +from typing import Final + +SUPPORTED_ENGINES: Final[set[str]] = { + "generative", + "long-form", + "neural", + "standard", +} + +SUPPORTED_REGIONS: Final[set[str]] = { + "af-south-1", + "ap-east-1", + "ap-northeast-1", + "ap-northeast-2", + "ap-northeast-3", + "ap-south-1", + "ap-southeast-1", + "ap-southeast-2", + "ca-central-1", + "eu-central-1", + "eu-north-1", + "eu-west-1", + "eu-west-2", + "eu-west-3", + "me-south-1", + "sa-east-1", + "us-east-1", + "us-east-2", + "us-west-1", + "us-west-2", +} + +SUPPORTED_VOICES: Final[set[str]] = { + "Aditi", + "Adriano", + "Amy", + "Andres", + "Aria", + "Arlet", + "Arthur", + "Astrid", + "Ayanda", + "Bianca", + "Brian", + "Burcu", + "Camila", + "Carla", + "Carmen", + "Celine", + "Chantal", + "Conchita", + "Cristiano", + "Daniel", + "Danielle", + "Dora", + "Elin", + "Emma", + "Enrique", + "Ewa", + "Filiz", + "Gabrielle", + "Geraint", + "Giorgio", + "Gregory", + "Gwyneth", + "Hala", + "Hannah", + "Hans", + "Hiujin", + "Ida", + "Ines", + "Isabelle", + "Ivy", + "Jacek", + "Jan", + "Joanna", + "Joey", + "Justin", + "Kajal", + "Karl", + "Kazuha", + "Kendra", + "Kevin", + "Kimberly", + "Laura", + "Lea", + "Liam", + "Lisa", + "Liv", + "Lotte", + "Lucia", + "Lupe", + "Mads", + "Maja", + "Marlene", + "Mathieu", + "Matthew", + "Maxim", + "Mia", + "Miguel", + "Mizuki", + "Naja", + "Niamh", + "Nicole", + "Ola", + "Olivia", + "Pedro", + "Penelope", + "Raveena", + "Remi", + "Ricardo", + "Ruben", + "Russell", + "Ruth", + "Salli", + "Seoyeon", + "Sergio", + "Sofie", + "Stephen", + "Suvi", + "Takumi", + "Tatyana", + "Thiago", + "Tomoko", + "Vicki", + "Vitoria", + "Zayd", + "Zeina", + "Zhiyu", +} diff --git a/script/amazon_polly.py b/script/amazon_polly.py new file mode 100644 index 0000000000000..fcb0a4b7987e2 --- /dev/null +++ b/script/amazon_polly.py @@ -0,0 +1,70 @@ +"""Helper script to update supported languages for Amazone Polly text-to-speech (TTS). + +N.B. This script requires AWS credentials. +""" + +from dataclasses import dataclass +from pathlib import Path +from typing import Self + +import boto3 + +from .hassfest.serializer import format_python_namespace + + +@dataclass(frozen=True) +class AmazonPollyVoice: + """Amazon Polly Voice.""" + + id: str + name: str + gender: str + language_name: str + language_code: str + supported_engines: set[str] + additional_language_codes: set[str] + + @classmethod + def validate(cls, model: dict[str, str | list[str]]) -> Self: + """Validate data model.""" + return cls( + id=model["Id"], + name=model["Name"], + gender=model["Gender"], + language_name=model["LanguageName"], + language_code=model["LanguageCode"], + supported_engines=set(model["SupportedEngines"]), + additional_language_codes=set(model.get("AdditionalLanguageCodes", [])), + ) + + +def get_all_voices(client: boto3.client) -> list[AmazonPollyVoice]: + """Get list of all supported voices from Amazon Polly.""" + response = client.describe_voices() + return [AmazonPollyVoice.validate(voice) for voice in response["Voices"]] + + +supported_regions = set( + boto3.session.Session().get_available_regions(service_name="polly") +) + +polly_client = boto3.client(service_name="polly", region_name="us-east-1") +voices = get_all_voices(polly_client) +supported_voices = set({v.id for v in voices}) +supported_engines = set().union(*[v.supported_engines for v in voices]) + +Path("homeassistant/generated/amazon_polly.py").write_text( + format_python_namespace( + { + "SUPPORTED_VOICES": supported_voices, + "SUPPORTED_REGIONS": supported_regions, + "SUPPORTED_ENGINES": supported_engines, + }, + annotations={ + "SUPPORTED_VOICES": "Final[set[str]]", + "SUPPORTED_REGIONS": "Final[set[str]]", + "SUPPORTED_ENGINES": "Final[set[str]]", + }, + generator="script.amazon_polly", + ) +) From 4a6f833fca20c7687279aa18c971bc6ae0f9c6e8 Mon Sep 17 00:00:00 2001 From: Penny Wood Date: Thu, 22 Aug 2024 21:39:09 +0800 Subject: [PATCH 16/31] Add supported features for iZone (#124416) * Fix for #123462 * Set outside of constructor --- homeassistant/components/izone/climate.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/homeassistant/components/izone/climate.py b/homeassistant/components/izone/climate.py index 3a1279a9bd43e..617cdc730cc08 100644 --- a/homeassistant/components/izone/climate.py +++ b/homeassistant/components/izone/climate.py @@ -441,6 +441,9 @@ class ZoneDevice(ClimateEntity): _attr_name = None _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_target_temperature_step = 0.5 + _attr_supported_features = ( + ClimateEntityFeature.TURN_OFF | ClimateEntityFeature.TURN_ON + ) def __init__(self, controller: ControllerDevice, zone: Zone) -> None: """Initialise ZoneDevice.""" From 2337c3ff69ad9b1e5d0a79b193c659b20c8f6948 Mon Sep 17 00:00:00 2001 From: Markus Jacobsen Date: Thu, 22 Aug 2024 15:49:42 +0200 Subject: [PATCH 17/31] Improve Bang olufsen test typing and parameter order (#124419) * Add proper media_player typing to tests * Add proper typing to init tests * Add proper typing to config_flow tests * Fix order of parameters of tests * Add more typing Reorder parameters --- tests/components/bang_olufsen/conftest.py | 10 +- .../bang_olufsen/test_config_flow.py | 16 +- tests/components/bang_olufsen/test_init.py | 16 +- .../bang_olufsen/test_media_player.py | 155 +++++++++++------- 4 files changed, 128 insertions(+), 69 deletions(-) diff --git a/tests/components/bang_olufsen/conftest.py b/tests/components/bang_olufsen/conftest.py index 4764798f34d4a..66b40f908990e 100644 --- a/tests/components/bang_olufsen/conftest.py +++ b/tests/components/bang_olufsen/conftest.py @@ -36,7 +36,7 @@ @pytest.fixture -def mock_config_entry(): +def mock_config_entry() -> MockConfigEntry: """Mock config entry.""" return MockConfigEntry( domain=DOMAIN, @@ -47,7 +47,11 @@ def mock_config_entry(): @pytest.fixture -async def mock_media_player(hass: HomeAssistant, mock_config_entry, mock_mozart_client): +async def mock_media_player( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_mozart_client: AsyncMock, +) -> None: """Mock media_player entity.""" mock_config_entry.add_to_hass(hass) @@ -248,7 +252,7 @@ def mock_mozart_client() -> Generator[AsyncMock]: @pytest.fixture -def mock_setup_entry(): +def mock_setup_entry() -> Generator[AsyncMock]: """Mock successful setup entry.""" with patch( "homeassistant.components.bang_olufsen.async_setup_entry", return_value=True diff --git a/tests/components/bang_olufsen/test_config_flow.py b/tests/components/bang_olufsen/test_config_flow.py index e637120a6ae59..5d5f34a79e6cc 100644 --- a/tests/components/bang_olufsen/test_config_flow.py +++ b/tests/components/bang_olufsen/test_config_flow.py @@ -1,6 +1,6 @@ """Test the bang_olufsen config_flow.""" -from unittest.mock import Mock +from unittest.mock import AsyncMock, Mock from aiohttp.client_exceptions import ClientConnectorError from mozart_api.exceptions import ApiException @@ -25,7 +25,7 @@ async def test_config_flow_timeout_error( - hass: HomeAssistant, mock_mozart_client + hass: HomeAssistant, mock_mozart_client: AsyncMock ) -> None: """Test we handle timeout_error.""" mock_mozart_client.get_beolink_self.side_effect = TimeoutError() @@ -42,7 +42,7 @@ async def test_config_flow_timeout_error( async def test_config_flow_client_connector_error( - hass: HomeAssistant, mock_mozart_client + hass: HomeAssistant, mock_mozart_client: AsyncMock ) -> None: """Test we handle client_connector_error.""" mock_mozart_client.get_beolink_self.side_effect = ClientConnectorError( @@ -73,7 +73,7 @@ async def test_config_flow_invalid_ip(hass: HomeAssistant) -> None: async def test_config_flow_api_exception( - hass: HomeAssistant, mock_mozart_client + hass: HomeAssistant, mock_mozart_client: AsyncMock ) -> None: """Test we handle api_exception.""" mock_mozart_client.get_beolink_self.side_effect = ApiException() @@ -89,7 +89,7 @@ async def test_config_flow_api_exception( assert mock_mozart_client.get_beolink_self.call_count == 1 -async def test_config_flow(hass: HomeAssistant, mock_mozart_client) -> None: +async def test_config_flow(hass: HomeAssistant, mock_mozart_client: AsyncMock) -> None: """Test config flow.""" result_init = await hass.config_entries.flow.async_init( @@ -112,7 +112,9 @@ async def test_config_flow(hass: HomeAssistant, mock_mozart_client) -> None: assert mock_mozart_client.get_beolink_self.call_count == 1 -async def test_config_flow_zeroconf(hass: HomeAssistant, mock_mozart_client) -> None: +async def test_config_flow_zeroconf( + hass: HomeAssistant, mock_mozart_client: AsyncMock +) -> None: """Test zeroconf discovery.""" result_zeroconf = await hass.config_entries.flow.async_init( @@ -162,7 +164,7 @@ async def test_config_flow_zeroconf_ipv6(hass: HomeAssistant) -> None: async def test_config_flow_zeroconf_invalid_ip( - hass: HomeAssistant, mock_mozart_client + hass: HomeAssistant, mock_mozart_client: AsyncMock ) -> None: """Test zeroconf discovery with invalid IP address.""" mock_mozart_client.get_beolink_self.side_effect = ClientConnectorError( diff --git a/tests/components/bang_olufsen/test_init.py b/tests/components/bang_olufsen/test_init.py index 11742b846ae8f..3eb98e956beb1 100644 --- a/tests/components/bang_olufsen/test_init.py +++ b/tests/components/bang_olufsen/test_init.py @@ -1,5 +1,7 @@ """Test the bang_olufsen __init__.""" +from unittest.mock import AsyncMock + from aiohttp.client_exceptions import ServerTimeoutError from homeassistant.components.bang_olufsen import DOMAIN @@ -9,12 +11,14 @@ from .const import TEST_MODEL_BALANCE, TEST_NAME, TEST_SERIAL_NUMBER +from tests.common import MockConfigEntry + async def test_setup_entry( hass: HomeAssistant, - mock_config_entry, - mock_mozart_client, device_registry: DeviceRegistry, + mock_config_entry: MockConfigEntry, + mock_mozart_client: AsyncMock, ) -> None: """Test async_setup_entry.""" @@ -41,7 +45,9 @@ async def test_setup_entry( async def test_setup_entry_failed( - hass: HomeAssistant, mock_config_entry, mock_mozart_client + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_mozart_client: AsyncMock, ) -> None: """Test failed async_setup_entry.""" @@ -66,7 +72,9 @@ async def test_setup_entry_failed( async def test_unload_entry( - hass: HomeAssistant, mock_config_entry, mock_mozart_client + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_mozart_client: AsyncMock, ) -> None: """Test unload_entry.""" diff --git a/tests/components/bang_olufsen/test_media_player.py b/tests/components/bang_olufsen/test_media_player.py index 37f375bdb397b..e169c023d1da1 100644 --- a/tests/components/bang_olufsen/test_media_player.py +++ b/tests/components/bang_olufsen/test_media_player.py @@ -1,10 +1,11 @@ """Test the Bang & Olufsen media_player entity.""" +from collections.abc import Callable from contextlib import nullcontext as does_not_raise import logging -from unittest.mock import patch +from unittest.mock import AsyncMock, patch -from mozart_api.models import PlaybackContentMetadata +from mozart_api.models import PlaybackContentMetadata, RenderingState, Source import pytest from homeassistant.components.bang_olufsen.const import ( @@ -75,7 +76,7 @@ async def test_initialization( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, mock_config_entry: MockConfigEntry, - mock_mozart_client, + mock_mozart_client: AsyncMock, ) -> None: """Test the integration is initialized properly in _initialize, async_added_to_hass and __init__.""" @@ -131,7 +132,9 @@ async def test_async_update_sources_outdated_api( async def test_async_update_playback_metadata( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test _async_update_playback_metadata.""" @@ -170,8 +173,8 @@ async def test_async_update_playback_metadata( async def test_async_update_playback_error( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, - mock_mozart_client, - mock_config_entry, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test _async_update_playback_error.""" @@ -192,7 +195,9 @@ async def test_async_update_playback_error( async def test_async_update_playback_progress( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test _async_update_playback_progress.""" @@ -218,7 +223,9 @@ async def test_async_update_playback_progress( async def test_async_update_playback_state( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test _async_update_playback_state.""" @@ -293,14 +300,14 @@ async def test_async_update_playback_state( ], ) async def test_async_update_source_change( - reported_source, - real_source, - content_type, - progress, - metadata, hass: HomeAssistant, - mock_mozart_client, - mock_config_entry, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, + reported_source: Source, + real_source: Source, + content_type: MediaType, + progress: int, + metadata: PlaybackContentMetadata, ) -> None: """Test _async_update_source_change.""" @@ -338,7 +345,9 @@ async def test_async_update_source_change( async def test_async_turn_off( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_turn_off.""" @@ -366,7 +375,9 @@ async def test_async_turn_off( async def test_async_set_volume_level( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_set_volume_level and _async_update_volume by proxy.""" @@ -404,7 +415,9 @@ async def test_async_set_volume_level( async def test_async_mute_volume( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_mute_volume.""" @@ -452,11 +465,11 @@ async def test_async_mute_volume( ], ) async def test_async_media_play_pause( - initial_state, - command, hass: HomeAssistant, - mock_mozart_client, - mock_config_entry, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, + initial_state: RenderingState, + command: str, ) -> None: """Test async_media_play_pause.""" @@ -484,7 +497,9 @@ async def test_async_media_play_pause( async def test_async_media_stop( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_media_stop.""" @@ -513,7 +528,9 @@ async def test_async_media_stop( async def test_async_media_next_track( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_media_next_track.""" @@ -540,12 +557,12 @@ async def test_async_media_next_track( ], ) async def test_async_media_seek( - source, - expected_result, - seek_called_times, hass: HomeAssistant, - mock_mozart_client, - mock_config_entry, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, + source: Source, + expected_result: Callable, + seek_called_times: int, ) -> None: """Test async_media_seek.""" @@ -575,7 +592,9 @@ async def test_async_media_seek( async def test_async_media_previous_track( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_media_previous_track.""" @@ -593,7 +612,9 @@ async def test_async_media_previous_track( async def test_async_clear_playlist( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_clear_playlist.""" @@ -622,13 +643,13 @@ async def test_async_clear_playlist( ], ) async def test_async_select_source( - source, - expected_result, - audio_source_call, - video_source_call, hass: HomeAssistant, - mock_mozart_client, - mock_config_entry, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, + source: str, + expected_result: Callable, + audio_source_call: int, + video_source_call: int, ) -> None: """Test async_select_source with an invalid source.""" @@ -651,7 +672,9 @@ async def test_async_select_source( async def test_async_play_media_invalid_type( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media only accepts valid media types.""" @@ -676,7 +699,9 @@ async def test_async_play_media_invalid_type( async def test_async_play_media_url( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media URL.""" @@ -701,7 +726,9 @@ async def test_async_play_media_url( async def test_async_play_media_overlay_absolute_volume_uri( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media overlay with Home Assistant local URI and absolute volume.""" @@ -734,8 +761,8 @@ async def test_async_play_media_overlay_absolute_volume_uri( async def test_async_play_media_overlay_invalid_offset_volume_tts( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, - mock_mozart_client, - mock_config_entry, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media with Home Assistant invalid offset volume and B&O tts.""" @@ -765,7 +792,9 @@ async def test_async_play_media_overlay_invalid_offset_volume_tts( async def test_async_play_media_overlay_offset_volume_tts( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media with Home Assistant invalid offset volume and B&O tts.""" @@ -798,7 +827,9 @@ async def test_async_play_media_overlay_offset_volume_tts( async def test_async_play_media_tts( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media with Home Assistant tts.""" @@ -822,7 +853,9 @@ async def test_async_play_media_tts( async def test_async_play_media_radio( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media with B&O radio.""" @@ -846,7 +879,9 @@ async def test_async_play_media_radio( async def test_async_play_media_favourite( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media with B&O favourite.""" @@ -868,7 +903,9 @@ async def test_async_play_media_favourite( async def test_async_play_media_deezer_flow( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media with Deezer flow.""" @@ -894,7 +931,9 @@ async def test_async_play_media_deezer_flow( async def test_async_play_media_deezer_playlist( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media with Deezer playlist.""" @@ -919,7 +958,9 @@ async def test_async_play_media_deezer_playlist( async def test_async_play_media_deezer_track( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media with Deezer track.""" @@ -943,7 +984,9 @@ async def test_async_play_media_deezer_track( async def test_async_play_media_invalid_deezer( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media with an invalid/no Deezer login.""" @@ -972,7 +1015,9 @@ async def test_async_play_media_invalid_deezer( async def test_async_play_media_url_m3u( - hass: HomeAssistant, mock_mozart_client, mock_config_entry + hass: HomeAssistant, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, ) -> None: """Test async_play_media URL with the m3u extension.""" @@ -1041,12 +1086,12 @@ async def test_async_play_media_url_m3u( ], ) async def test_async_browse_media( - child, - present, hass: HomeAssistant, - mock_mozart_client, - mock_config_entry, hass_ws_client: WebSocketGenerator, + mock_mozart_client: AsyncMock, + mock_config_entry: MockConfigEntry, + child: dict[str, str | bool | None], + present: bool, ) -> None: """Test async_browse_media with audio and video source.""" From 404a7bab185e553735ed78198f7081cc6919a477 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Thu, 22 Aug 2024 16:06:41 +0200 Subject: [PATCH 18/31] Wrap OSError in loader.load_yaml (#124406) --- homeassistant/util/yaml/loader.py | 10 +++++++++- tests/util/yaml/test_init.py | 21 +++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/homeassistant/util/yaml/loader.py b/homeassistant/util/yaml/loader.py index 4b7236d70223b..a56cf126f7978 100644 --- a/homeassistant/util/yaml/loader.py +++ b/homeassistant/util/yaml/loader.py @@ -221,13 +221,21 @@ def __report_deprecated() -> None: def load_yaml( fname: str | os.PathLike[str], secrets: Secrets | None = None ) -> JSON_TYPE | None: - """Load a YAML file.""" + """Load a YAML file. + + If opening the file raises an OSError it will be wrapped in a HomeAssistantError, + except for FileNotFoundError which will be re-raised. + """ try: with open(fname, encoding="utf-8") as conf_file: return parse_yaml(conf_file, secrets) except UnicodeDecodeError as exc: _LOGGER.error("Unable to read file %s: %s", fname, exc) raise HomeAssistantError(exc) from exc + except FileNotFoundError: + raise + except OSError as exc: + raise HomeAssistantError(exc) from exc def load_yaml_dict( diff --git a/tests/util/yaml/test_init.py b/tests/util/yaml/test_init.py index 793ba3183ada0..dbd7f1d2e99b1 100644 --- a/tests/util/yaml/test_init.py +++ b/tests/util/yaml/test_init.py @@ -746,3 +746,24 @@ def test_include_without_parameter(tag: str) -> None: pytest.raises(HomeAssistantError, match=f"{tag} needs an argument"), ): yaml_loader.parse_yaml(file) + + +@pytest.mark.parametrize( + ("open_exception", "load_yaml_exception"), + [ + (FileNotFoundError, OSError), + (NotADirectoryError, HomeAssistantError), + (PermissionError, HomeAssistantError), + ], +) +@pytest.mark.usefixtures("try_both_loaders") +def test_load_yaml_wrap_oserror( + open_exception: Exception, + load_yaml_exception: Exception, +) -> None: + """Test load_yaml wraps OSError in HomeAssistantError.""" + with ( + patch("homeassistant.util.yaml.loader.open", side_effect=open_exception), + pytest.raises(load_yaml_exception), + ): + yaml_loader.load_yaml("bla") From 890c6e97fd837f318d8fa9359bce37c28cd554c9 Mon Sep 17 00:00:00 2001 From: Markus Jacobsen Date: Thu, 22 Aug 2024 16:31:15 +0200 Subject: [PATCH 19/31] Add Bang & Olufsen websocket testing (#123075) * Add websocket.py testing Convert media_player testing dispatch events to the proper websocket events * Fix WebSocket testing by using callbacks * Add typing * Add caplog checking Check dispatch events directly Check event bus directly Avoid using internals * Fix event and / dispatch callbacks not necessarily being checked * Remove unnecessary caplog log level handling --- tests/components/bang_olufsen/conftest.py | 3 + .../bang_olufsen/test_media_player.py | 166 ++++++++++-------- .../components/bang_olufsen/test_websocket.py | 163 +++++++++++++++++ 3 files changed, 257 insertions(+), 75 deletions(-) create mode 100644 tests/components/bang_olufsen/test_websocket.py diff --git a/tests/components/bang_olufsen/conftest.py b/tests/components/bang_olufsen/conftest.py index 66b40f908990e..dd6c4a73469c0 100644 --- a/tests/components/bang_olufsen/conftest.py +++ b/tests/components/bang_olufsen/conftest.py @@ -245,8 +245,11 @@ def mock_mozart_client() -> Generator[AsyncMock]: # Non-REST API client methods client.check_device_connection = AsyncMock() client.close_api_client = AsyncMock() + + # WebSocket listener client.connect_notifications = AsyncMock() client.disconnect_notifications = Mock() + client.websocket_connected = False yield client diff --git a/tests/components/bang_olufsen/test_media_player.py b/tests/components/bang_olufsen/test_media_player.py index e169c023d1da1..3dd3c43f5a574 100644 --- a/tests/components/bang_olufsen/test_media_player.py +++ b/tests/components/bang_olufsen/test_media_player.py @@ -5,14 +5,18 @@ import logging from unittest.mock import AsyncMock, patch -from mozart_api.models import PlaybackContentMetadata, RenderingState, Source +from mozart_api.models import ( + PlaybackContentMetadata, + RenderingState, + Source, + WebsocketNotificationTag, +) import pytest from homeassistant.components.bang_olufsen.const import ( BANG_OLUFSEN_STATES, DOMAIN, BangOlufsenSource, - WebsocketNotification, ) from homeassistant.components.media_player import ( ATTR_INPUT_SOURCE, @@ -38,7 +42,6 @@ from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError -from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.setup import async_setup_component from .const import ( @@ -59,7 +62,6 @@ TEST_PLAYBACK_STATE_TURN_OFF, TEST_RADIO_STATION, TEST_SEEK_POSITION_HOME_ASSISTANT_FORMAT, - TEST_SERIAL_NUMBER, TEST_SOURCES, TEST_VIDEO_SOURCES, TEST_VOLUME, @@ -131,6 +133,29 @@ async def test_async_update_sources_outdated_api( ) +async def test_async_update_sources_remote( + hass: HomeAssistant, mock_mozart_client, mock_config_entry: MockConfigEntry +) -> None: + """Test _async_update_sources is called when there are new video sources.""" + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + + notification_callback = mock_mozart_client.get_notification_notifications.call_args[ + 0 + ][0] + + # This is not an ideal check, but I couldn't get anything else to work + assert mock_mozart_client.get_available_sources.call_count == 1 + assert mock_mozart_client.get_remote_menu.call_count == 1 + + # Send the remote menu Websocket event + notification_callback(WebsocketNotificationTag(value="remoteMenuChanged")) + + assert mock_mozart_client.get_available_sources.call_count == 2 + assert mock_mozart_client.get_remote_menu.call_count == 2 + + async def test_async_update_playback_metadata( hass: HomeAssistant, mock_mozart_client: AsyncMock, @@ -141,6 +166,10 @@ async def test_async_update_playback_metadata( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) + playback_metadata_callback = ( + mock_mozart_client.get_playback_metadata_notifications.call_args[0][0] + ) + states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert ATTR_MEDIA_DURATION not in states.attributes assert ATTR_MEDIA_TITLE not in states.attributes @@ -150,11 +179,7 @@ async def test_async_update_playback_metadata( assert ATTR_MEDIA_CHANNEL not in states.attributes # Send the WebSocket event dispatch - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.PLAYBACK_METADATA}", - TEST_PLAYBACK_METADATA, - ) + playback_metadata_callback(TEST_PLAYBACK_METADATA) states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert ( @@ -181,13 +206,13 @@ async def test_async_update_playback_error( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) - # The async_dispatcher_send function seems to swallow exceptions, making pytest.raises unusable - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.PLAYBACK_ERROR}", - TEST_PLAYBACK_ERROR, + playback_error_callback = ( + mock_mozart_client.get_playback_error_notifications.call_args[0][0] ) + # The async_dispatcher_send function seems to swallow exceptions, making pytest.raises unusable + playback_error_callback(TEST_PLAYBACK_ERROR) + assert ( "Exception in _async_update_playback_error when dispatching '11111111_playback_error': (PlaybackError(error='Test error', item=None),)" in caplog.text @@ -204,16 +229,16 @@ async def test_async_update_playback_progress( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) + playback_progress_callback = ( + mock_mozart_client.get_playback_progress_notifications.call_args[0][0] + ) + states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert ATTR_MEDIA_POSITION not in states.attributes old_updated_at = states.attributes[ATTR_MEDIA_POSITION_UPDATED_AT] assert old_updated_at - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.PLAYBACK_PROGRESS}", - TEST_PLAYBACK_PROGRESS, - ) + playback_progress_callback(TEST_PLAYBACK_PROGRESS) states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert states.attributes[ATTR_MEDIA_POSITION] == TEST_PLAYBACK_PROGRESS.progress @@ -232,14 +257,14 @@ async def test_async_update_playback_state( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) + playback_state_callback = ( + mock_mozart_client.get_playback_state_notifications.call_args[0][0] + ) + states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert states.state == MediaPlayerState.PLAYING - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.PLAYBACK_STATE}", - TEST_PLAYBACK_STATE_PAUSED, - ) + playback_state_callback(TEST_PLAYBACK_STATE_PAUSED) states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert states.state == TEST_PLAYBACK_STATE_PAUSED.value @@ -314,29 +339,26 @@ async def test_async_update_source_change( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) + playback_progress_callback = ( + mock_mozart_client.get_playback_progress_notifications.call_args[0][0] + ) + playback_metadata_callback = ( + mock_mozart_client.get_playback_metadata_notifications.call_args[0][0] + ) + source_change_callback = ( + mock_mozart_client.get_source_change_notifications.call_args[0][0] + ) + states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert ATTR_INPUT_SOURCE not in states.attributes assert states.attributes[ATTR_MEDIA_CONTENT_TYPE] == MediaType.MUSIC # Simulate progress attribute being available - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.PLAYBACK_PROGRESS}", - TEST_PLAYBACK_PROGRESS, - ) + playback_progress_callback(TEST_PLAYBACK_PROGRESS) # Simulate metadata - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.PLAYBACK_METADATA}", - metadata, - ) - - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.SOURCE_CHANGE}", - reported_source, - ) + playback_metadata_callback(metadata) + source_change_callback(reported_source) states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert states.attributes[ATTR_INPUT_SOURCE] == real_source.name @@ -354,6 +376,10 @@ async def test_async_turn_off( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) + playback_state_callback = ( + mock_mozart_client.get_playback_state_notifications.call_args[0][0] + ) + await hass.services.async_call( "media_player", "turn_off", @@ -361,11 +387,7 @@ async def test_async_turn_off( blocking=True, ) - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.PLAYBACK_STATE}", - TEST_PLAYBACK_STATE_TURN_OFF, - ) + playback_state_callback(TEST_PLAYBACK_STATE_TURN_OFF) states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert states.state == BANG_OLUFSEN_STATES[TEST_PLAYBACK_STATE_TURN_OFF.value] @@ -384,6 +406,8 @@ async def test_async_set_volume_level( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) + volume_callback = mock_mozart_client.get_volume_notifications.call_args[0][0] + states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert ATTR_MEDIA_VOLUME_LEVEL not in states.attributes @@ -398,11 +422,7 @@ async def test_async_set_volume_level( ) # The service call will trigger a WebSocket notification - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.VOLUME}", - TEST_VOLUME, - ) + volume_callback(TEST_VOLUME) states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert ( @@ -424,6 +444,8 @@ async def test_async_mute_volume( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) + volume_callback = mock_mozart_client.get_volume_notifications.call_args[0][0] + states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert ATTR_MEDIA_VOLUME_MUTED not in states.attributes @@ -438,11 +460,7 @@ async def test_async_mute_volume( ) # The service call will trigger a WebSocket notification - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.VOLUME}", - TEST_VOLUME_MUTED, - ) + volume_callback(TEST_VOLUME_MUTED) states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert ( @@ -476,13 +494,13 @@ async def test_async_media_play_pause( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) - # Set the initial state - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.PLAYBACK_STATE}", - initial_state, + playback_state_callback = ( + mock_mozart_client.get_playback_state_notifications.call_args[0][0] ) + # Set the initial state + playback_state_callback(initial_state) + states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert states.state == BANG_OLUFSEN_STATES[initial_state.value] @@ -506,13 +524,13 @@ async def test_async_media_stop( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) - # Set the state to playing - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.PLAYBACK_STATE}", - TEST_PLAYBACK_STATE_PLAYING, + playback_state_callback = ( + mock_mozart_client.get_playback_state_notifications.call_args[0][0] ) + # Set the state to playing + playback_state_callback(TEST_PLAYBACK_STATE_PLAYING) + states = hass.states.get(TEST_MEDIA_PLAYER_ENTITY_ID) assert states.state == BANG_OLUFSEN_STATES[TEST_PLAYBACK_STATE_PLAYING.value] @@ -569,13 +587,13 @@ async def test_async_media_seek( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) - # Set the source - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.SOURCE_CHANGE}", - source, + source_change_callback = ( + mock_mozart_client.get_source_change_notifications.call_args[0][0] ) + # Set the source + source_change_callback(source) + # Check results with expected_result: await hass.services.async_call( @@ -801,12 +819,10 @@ async def test_async_play_media_overlay_offset_volume_tts( mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) + volume_callback = mock_mozart_client.get_volume_notifications.call_args[0][0] + # Set the volume to enable offset - async_dispatcher_send( - hass, - f"{TEST_SERIAL_NUMBER}_{WebsocketNotification.VOLUME}", - TEST_VOLUME, - ) + volume_callback(TEST_VOLUME) await hass.services.async_call( "media_player", diff --git a/tests/components/bang_olufsen/test_websocket.py b/tests/components/bang_olufsen/test_websocket.py new file mode 100644 index 0000000000000..209550faee5a9 --- /dev/null +++ b/tests/components/bang_olufsen/test_websocket.py @@ -0,0 +1,163 @@ +"""Test the Bang & Olufsen WebSocket listener.""" + +import logging +from unittest.mock import AsyncMock, Mock + +from mozart_api.models import SoftwareUpdateState +import pytest + +from homeassistant.components.bang_olufsen.const import ( + BANG_OLUFSEN_WEBSOCKET_EVENT, + CONNECTION_STATUS, + DOMAIN, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers.device_registry import DeviceRegistry +from homeassistant.helpers.dispatcher import async_dispatcher_connect + +from .const import TEST_NAME + +from tests.common import MockConfigEntry + + +async def test_connection( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + mock_config_entry: MockConfigEntry, + mock_mozart_client: AsyncMock, +) -> None: + """Test on_connection and on_connection_lost logs and calls correctly.""" + + mock_mozart_client.websocket_connected = True + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + + connection_callback = mock_mozart_client.get_on_connection.call_args[0][0] + + caplog.set_level(logging.DEBUG) + + mock_connection_callback = Mock() + + async_dispatcher_connect( + hass, + f"{mock_config_entry.unique_id}_{CONNECTION_STATUS}", + mock_connection_callback, + ) + + # Call the WebSocket connection status method + connection_callback() + await hass.async_block_till_done() + + mock_connection_callback.assert_called_once_with(True) + assert f"Connected to the {TEST_NAME} notification channel" in caplog.text + + +async def test_connection_lost( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + mock_config_entry: MockConfigEntry, + mock_mozart_client: AsyncMock, +) -> None: + """Test on_connection_lost logs and calls correctly.""" + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + + connection_lost_callback = mock_mozart_client.get_on_connection_lost.call_args[0][0] + + mock_connection_lost_callback = Mock() + + async_dispatcher_connect( + hass, + f"{mock_config_entry.unique_id}_{CONNECTION_STATUS}", + mock_connection_lost_callback, + ) + + connection_lost_callback() + await hass.async_block_till_done() + + mock_connection_lost_callback.assert_called_once_with(False) + assert f"Lost connection to the {TEST_NAME}" in caplog.text + + +async def test_on_software_update_state( + hass: HomeAssistant, + device_registry: DeviceRegistry, + mock_config_entry: MockConfigEntry, + mock_mozart_client: AsyncMock, +) -> None: + """Test software version is updated through on_software_update_state.""" + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + + software_update_state_callback = ( + mock_mozart_client.get_software_update_state_notifications.call_args[0][0] + ) + + # Trigger the notification + await software_update_state_callback(SoftwareUpdateState()) + + await hass.async_block_till_done() + + device = device_registry.async_get_device( + identifiers={(DOMAIN, mock_config_entry.unique_id)} + ) + assert device.sw_version == "1.0.0" + + +async def test_on_all_notifications_raw( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + device_registry: DeviceRegistry, + mock_config_entry: MockConfigEntry, + mock_mozart_client: AsyncMock, +) -> None: + """Test on_all_notifications_raw logs and fires as expected.""" + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + + all_notifications_raw_callback = ( + mock_mozart_client.get_all_notifications_raw.call_args[0][0] + ) + + raw_notification = { + "eventData": { + "default": {"level": 40}, + "level": {"level": 40}, + "maximum": {"level": 100}, + "muted": {"muted": False}, + }, + "eventType": "WebSocketEventVolume", + } + raw_notification_full = raw_notification + + # Get device ID for the modified notification that is sent as an event and in the log + device = device_registry.async_get_device( + identifiers={(DOMAIN, mock_config_entry.unique_id)} + ) + raw_notification_full.update( + { + "device_id": device.id, + "serial_number": mock_config_entry.unique_id, + } + ) + + caplog.set_level(logging.DEBUG) + + mock_event_callback = Mock() + + # Listen to BANG_OLUFSEN_WEBSOCKET_EVENT events + hass.bus.async_listen(BANG_OLUFSEN_WEBSOCKET_EVENT, mock_event_callback) + + # Trigger the notification + all_notifications_raw_callback(raw_notification) + await hass.async_block_till_done() + + assert str(raw_notification_full) in caplog.text + + mocked_call = mock_event_callback.call_args[0][0].as_dict() + assert mocked_call["event_type"] == BANG_OLUFSEN_WEBSOCKET_EVENT + assert mocked_call["data"] == raw_notification_full From 6f66f37fc7a35436af40ac7598294620e57a73be Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 22 Aug 2024 09:47:22 -0500 Subject: [PATCH 20/31] Shutdown database engine before waiting for executor shutdown (#117339) * Close database connection before stopping the executor related issue #117004 * Close database connection before waiting for database executor to finish related issue #117004 * fix test * fix * drop unused arg * Revert "drop unused arg" This reverts commit 8a9fe6a24a614d7fda2058248f653fa400a5a252. * docstring * comment --- homeassistant/components/recorder/core.py | 17 +++++++++-------- homeassistant/util/executor.py | 14 +++++++++++--- tests/components/recorder/test_init.py | 19 +++++++++---------- 3 files changed, 29 insertions(+), 21 deletions(-) diff --git a/homeassistant/components/recorder/core.py b/homeassistant/components/recorder/core.py index 31c36be9c888c..c57274317e3fe 100644 --- a/homeassistant/components/recorder/core.py +++ b/homeassistant/components/recorder/core.py @@ -367,13 +367,6 @@ def async_add_executor_job[_T]( """Add an executor job from within the event loop.""" return self.hass.loop.run_in_executor(self._db_executor, target, *args) - def _stop_executor(self) -> None: - """Stop the executor.""" - if self._db_executor is None: - return - self._db_executor.shutdown() - self._db_executor = None - @callback def _async_check_queue(self, *_: Any) -> None: """Periodic check of the queue size to ensure we do not exhaust memory. @@ -1501,5 +1494,13 @@ def _shutdown(self) -> None: try: self._end_session() finally: - self._stop_executor() + if self._db_executor: + # We shutdown the executor without forcefully + # joining the threads until after we have tried + # to cleanly close the connection. + self._db_executor.shutdown(join_threads_or_timeout=False) self._close_connection() + if self._db_executor: + # After the connection is closed, we can join the threads + # or forcefully shutdown the threads if they take too long. + self._db_executor.join_threads_or_timeout() diff --git a/homeassistant/util/executor.py b/homeassistant/util/executor.py index 47b6d08a197cf..5f0fdd5c273fe 100644 --- a/homeassistant/util/executor.py +++ b/homeassistant/util/executor.py @@ -63,10 +63,18 @@ def join_or_interrupt_threads( class InterruptibleThreadPoolExecutor(ThreadPoolExecutor): """A ThreadPoolExecutor instance that will not deadlock on shutdown.""" - def shutdown(self, *args: Any, **kwargs: Any) -> None: - """Shutdown with interrupt support added.""" + def shutdown( + self, *args: Any, join_threads_or_timeout: bool = True, **kwargs: Any + ) -> None: + """Shutdown with interrupt support added. + + By default shutdown will wait for threads to finish up + to the timeout before forcefully stopping them. This can + be disabled by setting `join_threads_or_timeout` to False. + """ super().shutdown(wait=False, cancel_futures=True) - self.join_threads_or_timeout() + if join_threads_or_timeout: + self.join_threads_or_timeout() def join_threads_or_timeout(self) -> None: """Join threads or timeout.""" diff --git a/tests/components/recorder/test_init.py b/tests/components/recorder/test_init.py index 72d47515edd6e..3bbc78e21cec6 100644 --- a/tests/components/recorder/test_init.py +++ b/tests/components/recorder/test_init.py @@ -166,11 +166,10 @@ async def test_shutdown_before_startup_finishes( await hass.async_block_till_done() await hass.async_stop() - def _run_information_with_session(): - instance.recorder_and_worker_thread_ids.add(threading.get_ident()) - return run_information_with_session(session) - - run_info = await instance.async_add_executor_job(_run_information_with_session) + # The database executor is shutdown so we must run the + # query in the main thread for testing + instance.recorder_and_worker_thread_ids.add(threading.get_ident()) + run_info = run_information_with_session(session) assert run_info.run_id == 1 assert run_info.start is not None @@ -216,8 +215,7 @@ async def test_shutdown_closes_connections( instance = recorder.get_instance(hass) await instance.async_db_ready await hass.async_block_till_done() - pool = instance.engine.pool - pool.shutdown = Mock() + pool = instance.engine def _ensure_connected(): with session_scope(hass=hass, read_only=True) as session: @@ -225,10 +223,11 @@ def _ensure_connected(): await instance.async_add_executor_job(_ensure_connected) - hass.bus.async_fire(EVENT_HOMEASSISTANT_FINAL_WRITE) - await hass.async_block_till_done() + with patch.object(pool, "dispose", wraps=pool.dispose) as dispose: + hass.bus.async_fire(EVENT_HOMEASSISTANT_FINAL_WRITE) + await hass.async_block_till_done() - assert len(pool.shutdown.mock_calls) == 1 + assert len(dispose.mock_calls) == 1 with pytest.raises(RuntimeError): assert instance.get_session() From 5d64155bb670d890e38cecc735fd05cc22c84eba Mon Sep 17 00:00:00 2001 From: Petro31 <35082313+Petro31@users.noreply.github.com> Date: Thu, 22 Aug 2024 13:11:08 -0400 Subject: [PATCH 21/31] Add zip to template engine (#122460) * add zip to template engine * fix doc strings --- homeassistant/helpers/template.py | 1 + tests/helpers/test_template.py | 45 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 7742418c5a7dd..e090e0de2d1e3 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -2844,6 +2844,7 @@ def __init__( self.globals["iif"] = iif self.globals["bool"] = forgiving_boolean self.globals["version"] = version + self.globals["zip"] = zip self.tests["is_number"] = is_number self.tests["list"] = _is_list self.tests["set"] = _is_set diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 3123c01f50026..0676ae21ab73b 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -6236,3 +6236,48 @@ async def test_template_thread_safety_checks(hass: HomeAssistant) -> None: await hass.async_add_executor_job(template_obj.async_render_to_info) assert template_obj.async_render_to_info().result() == 23 + + +@pytest.mark.parametrize( + ("cola", "colb", "expected"), + [ + ([1, 2], [3, 4], [(1, 3), (2, 4)]), + ([1, 2], [3, 4, 5], [(1, 3), (2, 4)]), + ([1, 2, 3, 4], [3, 4], [(1, 3), (2, 4)]), + ], +) +def test_zip(hass: HomeAssistant, cola, colb, expected) -> None: + """Test zip.""" + assert ( + template.Template("{{ zip(cola, colb) | list }}", hass).async_render( + {"cola": cola, "colb": colb} + ) + == expected + ) + assert ( + template.Template( + "[{% for a, b in zip(cola, colb) %}({{a}}, {{b}}), {% endfor %}]", hass + ).async_render({"cola": cola, "colb": colb}) + == expected + ) + + +@pytest.mark.parametrize( + ("col", "expected"), + [ + ([(1, 3), (2, 4)], [(1, 2), (3, 4)]), + (["ax", "by", "cz"], [("a", "b", "c"), ("x", "y", "z")]), + ], +) +def test_unzip(hass: HomeAssistant, col, expected) -> None: + """Test unzipping using zip.""" + assert ( + template.Template("{{ zip(*col) | list }}", hass).async_render({"col": col}) + == expected + ) + assert ( + template.Template( + "{% set a, b = zip(*col) %}[{{a}}, {{b}}]", hass + ).async_render({"col": col}) + == expected + ) From 3a928990818086442cdc27e8b752f08b4f81dc2a Mon Sep 17 00:00:00 2001 From: Michael Arthur Date: Fri, 23 Aug 2024 05:13:54 +1200 Subject: [PATCH 22/31] Add LawnMowerActivity.RETURNING to Lawn Mower (#124261) * Add returning activity state * update tests * update tests * set can return to returning state * update MQTT tests * update mqtt back to docked * fix up other tests that I broke again * re-add mower_can_dock --- .../components/kitchen_sink/lawn_mower.py | 14 +++++++++++--- homeassistant/components/lawn_mower/const.py | 3 +++ .../components/lawn_mower/strings.json | 3 ++- .../snapshots/test_lawn_mower.ambr | 12 ++++++++++++ .../components/kitchen_sink/test_lawn_mower.py | 6 ++++++ tests/components/mqtt/test_lawn_mower.py | 18 +++++++++++++++++- 6 files changed, 51 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/kitchen_sink/lawn_mower.py b/homeassistant/components/kitchen_sink/lawn_mower.py index 50ec70f675937..51814fb262dde 100644 --- a/homeassistant/components/kitchen_sink/lawn_mower.py +++ b/homeassistant/components/kitchen_sink/lawn_mower.py @@ -30,18 +30,26 @@ async def async_setup_platform( ), DemoLawnMower( "kitchen_sink_mower_002", + "Mower can return", + LawnMowerActivity.RETURNING, + LawnMowerEntityFeature.DOCK + | LawnMowerEntityFeature.PAUSE + | LawnMowerEntityFeature.START_MOWING, + ), + DemoLawnMower( + "kitchen_sink_mower_003", "Mower can dock", LawnMowerActivity.MOWING, LawnMowerEntityFeature.DOCK | LawnMowerEntityFeature.START_MOWING, ), DemoLawnMower( - "kitchen_sink_mower_003", + "kitchen_sink_mower_004", "Mower can pause", LawnMowerActivity.DOCKED, LawnMowerEntityFeature.PAUSE | LawnMowerEntityFeature.START_MOWING, ), DemoLawnMower( - "kitchen_sink_mower_004", + "kitchen_sink_mower_005", "Mower can do all", LawnMowerActivity.DOCKED, LawnMowerEntityFeature.DOCK @@ -49,7 +57,7 @@ async def async_setup_platform( | LawnMowerEntityFeature.START_MOWING, ), DemoLawnMower( - "kitchen_sink_mower_005", + "kitchen_sink_mower_006", "Mower is paused", LawnMowerActivity.PAUSED, LawnMowerEntityFeature.DOCK diff --git a/homeassistant/components/lawn_mower/const.py b/homeassistant/components/lawn_mower/const.py index e060abe642340..231be83ed887c 100644 --- a/homeassistant/components/lawn_mower/const.py +++ b/homeassistant/components/lawn_mower/const.py @@ -18,6 +18,9 @@ class LawnMowerActivity(StrEnum): DOCKED = "docked" """Device is docked.""" + RETURNING = "returning" + """Device is returning.""" + class LawnMowerEntityFeature(IntFlag): """Supported features of the lawn mower entity.""" diff --git a/homeassistant/components/lawn_mower/strings.json b/homeassistant/components/lawn_mower/strings.json index 15ed50ca6c5cd..ebaea4ffd6a43 100644 --- a/homeassistant/components/lawn_mower/strings.json +++ b/homeassistant/components/lawn_mower/strings.json @@ -7,7 +7,8 @@ "error": "Error", "paused": "[%key:common::state::paused%]", "mowing": "Mowing", - "docked": "Docked" + "docked": "Docked", + "returning": "Returning" } } }, diff --git a/tests/components/kitchen_sink/snapshots/test_lawn_mower.ambr b/tests/components/kitchen_sink/snapshots/test_lawn_mower.ambr index 4189de18ce4e8..e3e413c5a44c7 100644 --- a/tests/components/kitchen_sink/snapshots/test_lawn_mower.ambr +++ b/tests/components/kitchen_sink/snapshots/test_lawn_mower.ambr @@ -49,6 +49,18 @@ 'last_updated': , 'state': 'docked', }), + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Mower can return', + 'supported_features': , + }), + 'context': , + 'entity_id': 'lawn_mower.mower_can_return', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'returning', + }), StateSnapshot({ 'attributes': ReadOnlyDict({ 'friendly_name': 'Mower is paused', diff --git a/tests/components/kitchen_sink/test_lawn_mower.py b/tests/components/kitchen_sink/test_lawn_mower.py index 48914ab5a4632..e1ba201a7226a 100644 --- a/tests/components/kitchen_sink/test_lawn_mower.py +++ b/tests/components/kitchen_sink/test_lawn_mower.py @@ -72,6 +72,12 @@ async def test_states(hass: HomeAssistant, snapshot: SnapshotAssertion) -> None: LawnMowerActivity.MOWING, LawnMowerActivity.DOCKED, ), + ( + "lawn_mower.mower_can_return", + SERVICE_DOCK, + LawnMowerActivity.RETURNING, + LawnMowerActivity.DOCKED, + ), ], ) async def test_mower( diff --git a/tests/components/mqtt/test_lawn_mower.py b/tests/components/mqtt/test_lawn_mower.py index 4906f6cfda329..101a45787ef4e 100644 --- a/tests/components/mqtt/test_lawn_mower.py +++ b/tests/components/mqtt/test_lawn_mower.py @@ -103,6 +103,13 @@ async def test_run_lawn_mower_setup_and_state_updates( state = hass.states.get("lawn_mower.test_lawn_mower") assert state.state == "mowing" + async_fire_mqtt_message(hass, "test/lawn_mower_stat", "returning") + + await hass.async_block_till_done() + + state = hass.states.get("lawn_mower.test_lawn_mower") + assert state.state == "returning" + async_fire_mqtt_message(hass, "test/lawn_mower_stat", "docked") await hass.async_block_till_done() @@ -198,6 +205,13 @@ async def test_value_template( state = hass.states.get("lawn_mower.test_lawn_mower") assert state.state == "paused" + async_fire_mqtt_message(hass, "test/lawn_mower_stat", '{"val":"returning"}') + + await hass.async_block_till_done() + + state = hass.states.get("lawn_mower.test_lawn_mower") + assert state.state == "returning" + async_fire_mqtt_message(hass, "test/lawn_mower_stat", '{"val": null}') await hass.async_block_till_done() @@ -702,7 +716,8 @@ async def test_mqtt_payload_not_a_valid_activity_warning( assert ( "Invalid activity for lawn_mower.test_lawn_mower: 'painting' " - "(valid activities: ['error', 'paused', 'mowing', 'docked'])" in caplog.text + "(valid activities: ['error', 'paused', 'mowing', 'docked', 'returning'])" + in caplog.text ) @@ -774,6 +789,7 @@ async def test_reloadable( [ ("activity_state_topic", "paused", None, "paused"), ("activity_state_topic", "docked", None, "docked"), + ("activity_state_topic", "returning", None, "returning"), ("activity_state_topic", "mowing", None, "mowing"), ], ) From 7887bcba89d5843f7b93be4b647d7a1654e59951 Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Thu, 22 Aug 2024 19:16:08 +0200 Subject: [PATCH 23/31] Allow to set options for an MQTT enum sensor (#123248) * Add options attribute support for MQTT sensor * Add comment --- homeassistant/components/mqtt/const.py | 1 + homeassistant/components/mqtt/select.py | 9 +- homeassistant/components/mqtt/sensor.py | 39 +++++++-- tests/components/mqtt/test_sensor.py | 105 ++++++++++++++++++++++++ 4 files changed, 146 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/mqtt/const.py b/homeassistant/components/mqtt/const.py index 3bf9cf218f27b..1e1011cc38121 100644 --- a/homeassistant/components/mqtt/const.py +++ b/homeassistant/components/mqtt/const.py @@ -39,6 +39,7 @@ CONF_JSON_ATTRS_TOPIC = "json_attributes_topic" CONF_JSON_ATTRS_TEMPLATE = "json_attributes_template" CONF_KEEPALIVE = "keepalive" +CONF_OPTIONS = "options" CONF_ORIGIN = "origin" CONF_QOS = ATTR_QOS CONF_RETAIN = ATTR_RETAIN diff --git a/homeassistant/components/mqtt/select.py b/homeassistant/components/mqtt/select.py index 5cc7a586c712e..e301892dee23f 100644 --- a/homeassistant/components/mqtt/select.py +++ b/homeassistant/components/mqtt/select.py @@ -19,7 +19,12 @@ from . import subscription from .config import MQTT_RW_SCHEMA -from .const import CONF_COMMAND_TEMPLATE, CONF_COMMAND_TOPIC, CONF_STATE_TOPIC +from .const import ( + CONF_COMMAND_TEMPLATE, + CONF_COMMAND_TOPIC, + CONF_OPTIONS, + CONF_STATE_TOPIC, +) from .mixins import MqttEntity, async_setup_entity_entry_helper from .models import ( MqttCommandTemplate, @@ -32,8 +37,6 @@ _LOGGER = logging.getLogger(__name__) -CONF_OPTIONS = "options" - DEFAULT_NAME = "MQTT Select" MQTT_SELECT_ATTRIBUTES_BLOCKED = frozenset( diff --git a/homeassistant/components/mqtt/sensor.py b/homeassistant/components/mqtt/sensor.py index e983f1b66f391..d689b6bb76738 100644 --- a/homeassistant/components/mqtt/sensor.py +++ b/homeassistant/components/mqtt/sensor.py @@ -38,7 +38,7 @@ from . import subscription from .config import MQTT_RO_SCHEMA -from .const import CONF_STATE_TOPIC, PAYLOAD_NONE +from .const import CONF_OPTIONS, CONF_STATE_TOPIC, PAYLOAD_NONE from .mixins import MqttAvailabilityMixin, MqttEntity, async_setup_entity_entry_helper from .models import ( MqttValueTemplate, @@ -72,6 +72,7 @@ vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean, vol.Optional(CONF_LAST_RESET_VALUE_TEMPLATE): cv.template, vol.Optional(CONF_NAME): vol.Any(cv.string, None), + vol.Optional(CONF_OPTIONS): cv.ensure_list, vol.Optional(CONF_SUGGESTED_DISPLAY_PRECISION): cv.positive_int, vol.Optional(CONF_STATE_CLASS): vol.Any(STATE_CLASSES_SCHEMA, None), vol.Optional(CONF_UNIT_OF_MEASUREMENT): vol.Any(cv.string, None), @@ -79,8 +80,8 @@ ).extend(MQTT_ENTITY_COMMON_SCHEMA.schema) -def validate_sensor_state_class_config(config: ConfigType) -> ConfigType: - """Validate the sensor state class config.""" +def validate_sensor_state_and_device_class_config(config: ConfigType) -> ConfigType: + """Validate the sensor options, state and device class config.""" if ( CONF_LAST_RESET_VALUE_TEMPLATE in config and (state_class := config.get(CONF_STATE_CLASS)) != SensorStateClass.TOTAL @@ -90,17 +91,35 @@ def validate_sensor_state_class_config(config: ConfigType) -> ConfigType: f"together with state class `{state_class}`" ) + # Only allow `options` to be set for `enum` sensors + # to limit the possible sensor values + if (options := config.get(CONF_OPTIONS)) is not None: + if not options: + raise vol.Invalid("An empty options list is not allowed") + if config.get(CONF_STATE_CLASS) or config.get(CONF_UNIT_OF_MEASUREMENT): + raise vol.Invalid( + f"Specifying `{CONF_OPTIONS}` is not allowed together with " + f"the `{CONF_STATE_CLASS}` or `{CONF_UNIT_OF_MEASUREMENT}` option" + ) + + if (device_class := config.get(CONF_DEVICE_CLASS)) != SensorDeviceClass.ENUM: + raise vol.Invalid( + f"The option `{CONF_OPTIONS}` can only be used " + f"together with device class `{SensorDeviceClass.ENUM}`, " + f"got `{CONF_DEVICE_CLASS}` '{device_class}'" + ) + return config PLATFORM_SCHEMA_MODERN = vol.All( _PLATFORM_SCHEMA_BASE, - validate_sensor_state_class_config, + validate_sensor_state_and_device_class_config, ) DISCOVERY_SCHEMA = vol.All( _PLATFORM_SCHEMA_BASE.extend({}, extra=vol.REMOVE_EXTRA), - validate_sensor_state_class_config, + validate_sensor_state_and_device_class_config, ) @@ -197,6 +216,7 @@ def _setup_from_config(self, config: ConfigType) -> None: CONF_SUGGESTED_DISPLAY_PRECISION ) self._attr_native_unit_of_measurement = config.get(CONF_UNIT_OF_MEASUREMENT) + self._attr_options = config.get(CONF_OPTIONS) self._attr_state_class = config.get(CONF_STATE_CLASS) self._expire_after = config.get(CONF_EXPIRE_AFTER) @@ -252,6 +272,15 @@ def _update_state(self, msg: ReceiveMessage) -> None: else: self._attr_native_value = payload return + if self.options and payload not in self.options: + _LOGGER.warning( + "Ignoring invalid option received on topic '%s', got '%s', allowed: %s", + msg.topic, + payload, + ", ".join(self.options), + ) + return + if self.device_class in { None, SensorDeviceClass.ENUM, diff --git a/tests/components/mqtt/test_sensor.py b/tests/components/mqtt/test_sensor.py index 4b117aaa4d5eb..a62c36404ca52 100644 --- a/tests/components/mqtt/test_sensor.py +++ b/tests/components/mqtt/test_sensor.py @@ -3,6 +3,7 @@ import copy from datetime import datetime, timedelta import json +import logging from pathlib import Path from typing import Any from unittest.mock import MagicMock, patch @@ -110,6 +111,48 @@ async def test_setting_sensor_value_via_mqtt_message( assert state.attributes.get("unit_of_measurement") == "fav unit" +@pytest.mark.parametrize( + "hass_config", + [ + { + mqtt.DOMAIN: { + sensor.DOMAIN: { + "name": "test", + "state_topic": "test-topic", + "device_class": "enum", + "options": ["red", "green", "blue"], + } + } + }, + ], +) +async def test_setting_enum_sensor_value_via_mqtt_message( + hass: HomeAssistant, + mqtt_mock_entry: MqttMockHAClientGenerator, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test the setting of the value via MQTT of an enum type sensor.""" + await mqtt_mock_entry() + + async_fire_mqtt_message(hass, "test-topic", "red") + state = hass.states.get("sensor.test") + assert state.state == "red" + + async_fire_mqtt_message(hass, "test-topic", "green") + state = hass.states.get("sensor.test") + assert state.state == "green" + + with caplog.at_level(logging.WARNING): + async_fire_mqtt_message(hass, "test-topic", "yellow") + assert ( + "Ignoring invalid option received on topic 'test-topic', " + "got 'yellow', allowed: red, green, blue" in caplog.text + ) + # Assert the state update was filtered out and ignored + state = hass.states.get("sensor.test") + assert state.state == "green" + + @pytest.mark.parametrize( "hass_config", [ @@ -874,6 +917,61 @@ async def test_invalid_state_class( assert "expected SensorStateClass or one of" in caplog.text +@pytest.mark.parametrize( + ("hass_config", "error_logged"), + [ + ( + { + mqtt.DOMAIN: { + sensor.DOMAIN: { + "name": "test", + "state_topic": "test-topic", + "state_class": "measurement", + "options": ["red", "green", "blue"], + } + } + }, + "Specifying `options` is not allowed together with the `state_class` " + "or `unit_of_measurement` option", + ), + ( + { + mqtt.DOMAIN: { + sensor.DOMAIN: { + "name": "test", + "state_topic": "test-topic", + "device_class": "gas", + "options": ["red", "green", "blue"], + } + } + }, + "The option `options` can only be used together with " + "device class `enum`, got `device_class` 'gas'", + ), + ( + { + mqtt.DOMAIN: { + sensor.DOMAIN: { + "name": "test", + "state_topic": "test-topic", + "options": [], + } + } + }, + "An empty options list is not allowed", + ), + ], +) +async def test_invalid_options_config( + mqtt_mock_entry: MqttMockHAClientGenerator, + caplog: pytest.LogCaptureFixture, + error_logged: str, +) -> None: + """Test state_class, deviceclass with sensor options.""" + assert await mqtt_mock_entry() + assert error_logged in caplog.text + + @pytest.mark.parametrize( "hass_config", [ @@ -891,6 +989,13 @@ async def test_invalid_state_class( "state_topic": "test-topic", "state_class": None, }, + { + "name": "Test 4", + "state_topic": "test-topic", + "state_class": None, + "device_class": "enum", + "options": ["red", "green", "blue"], + }, ] } } From e13f8996f25be750c5910388766731843ee3ea20 Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Thu, 22 Aug 2024 20:13:30 +0200 Subject: [PATCH 24/31] Fix Import ReceivePayloadType (#124431) * Fix Import ReceivePayloadType * Do not assert export `ReceivePayloadType` on mqtt integration level as helper should be used. --- homeassistant/components/mqtt/__init__.py | 1 - homeassistant/components/mqtt/climate.py | 2 +- homeassistant/components/mqtt/device_tracker.py | 3 ++- homeassistant/components/mqtt/event.py | 2 +- homeassistant/components/mqtt/fan.py | 2 +- homeassistant/components/mqtt/humidifier.py | 2 +- homeassistant/components/mqtt/lawn_mower.py | 2 +- homeassistant/components/mqtt/light/schema_basic.py | 2 +- homeassistant/components/mqtt/light/schema_template.py | 2 +- homeassistant/components/mqtt/lock.py | 2 +- homeassistant/components/mqtt/number.py | 2 +- homeassistant/components/mqtt/select.py | 2 +- homeassistant/components/mqtt/sensor.py | 8 ++------ homeassistant/components/mqtt/siren.py | 2 +- homeassistant/components/mqtt/tag.py | 2 +- homeassistant/components/mqtt/text.py | 2 +- homeassistant/components/mqtt/trigger.py | 2 +- homeassistant/components/mysensors/gateway.py | 2 +- tests/components/mqtt/test_init.py | 1 - 19 files changed, 19 insertions(+), 24 deletions(-) diff --git a/homeassistant/components/mqtt/__init__.py b/homeassistant/components/mqtt/__init__.py index b2adb7665fc07..86eeca2017c0a 100644 --- a/homeassistant/components/mqtt/__init__.py +++ b/homeassistant/components/mqtt/__init__.py @@ -89,7 +89,6 @@ PayloadSentinel, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, convert_outgoing_mqtt_payload, ) from .subscription import ( # noqa: F401 diff --git a/homeassistant/components/mqtt/climate.py b/homeassistant/components/mqtt/climate.py index 7873b05688988..426bac8e9cad1 100644 --- a/homeassistant/components/mqtt/climate.py +++ b/homeassistant/components/mqtt/climate.py @@ -46,6 +46,7 @@ from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.template import Template from homeassistant.helpers.typing import ConfigType, VolSchemaType from homeassistant.util.unit_conversion import TemperatureConverter @@ -84,7 +85,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA from .util import valid_publish_topic, valid_subscribe_topic diff --git a/homeassistant/components/mqtt/device_tracker.py b/homeassistant/components/mqtt/device_tracker.py index b2aeb4c0fc188..57614106d4ec6 100644 --- a/homeassistant/components/mqtt/device_tracker.py +++ b/homeassistant/components/mqtt/device_tracker.py @@ -27,13 +27,14 @@ from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, VolSchemaType from . import subscription from .config import MQTT_BASE_SCHEMA from .const import CONF_PAYLOAD_RESET, CONF_STATE_TOPIC from .mixins import CONF_JSON_ATTRS_TOPIC, MqttEntity, async_setup_entity_entry_helper -from .models import MqttValueTemplate, ReceiveMessage, ReceivePayloadType +from .models import MqttValueTemplate, ReceiveMessage from .schemas import MQTT_ENTITY_COMMON_SCHEMA from .util import valid_subscribe_topic diff --git a/homeassistant/components/mqtt/event.py b/homeassistant/components/mqtt/event.py index 5e801fda54b01..0dc267f80f964 100644 --- a/homeassistant/components/mqtt/event.py +++ b/homeassistant/components/mqtt/event.py @@ -19,6 +19,7 @@ from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, VolSchemaType from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads_object @@ -32,7 +33,6 @@ MqttValueTemplateException, PayloadSentinel, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA diff --git a/homeassistant/components/mqtt/fan.py b/homeassistant/components/mqtt/fan.py index 1838ce20e4d97..a22dba4ae936c 100644 --- a/homeassistant/components/mqtt/fan.py +++ b/homeassistant/components/mqtt/fan.py @@ -29,6 +29,7 @@ from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.template import Template from homeassistant.helpers.typing import ConfigType, VolSchemaType from homeassistant.util.percentage import ( @@ -52,7 +53,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA from .util import valid_publish_topic, valid_subscribe_topic diff --git a/homeassistant/components/mqtt/humidifier.py b/homeassistant/components/mqtt/humidifier.py index a4510ee5951f3..d55c1d3cebf4e 100644 --- a/homeassistant/components/mqtt/humidifier.py +++ b/homeassistant/components/mqtt/humidifier.py @@ -32,6 +32,7 @@ from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.template import Template from homeassistant.helpers.typing import ConfigType, VolSchemaType @@ -54,7 +55,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA from .util import valid_publish_topic, valid_subscribe_topic diff --git a/homeassistant/components/mqtt/lawn_mower.py b/homeassistant/components/mqtt/lawn_mower.py index a74d278401cce..f4aa248929ef7 100644 --- a/homeassistant/components/mqtt/lawn_mower.py +++ b/homeassistant/components/mqtt/lawn_mower.py @@ -20,6 +20,7 @@ from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, VolSchemaType from . import subscription @@ -31,7 +32,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA from .util import valid_publish_topic, valid_subscribe_topic diff --git a/homeassistant/components/mqtt/light/schema_basic.py b/homeassistant/components/mqtt/light/schema_basic.py index b0ffae4e328f8..1a64b1eecb48d 100644 --- a/homeassistant/components/mqtt/light/schema_basic.py +++ b/homeassistant/components/mqtt/light/schema_basic.py @@ -39,6 +39,7 @@ from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.restore_state import RestoreEntity +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, VolSchemaType import homeassistant.util.color as color_util @@ -57,7 +58,6 @@ PayloadSentinel, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, TemplateVarsType, ) from ..schemas import MQTT_ENTITY_COMMON_SCHEMA diff --git a/homeassistant/components/mqtt/light/schema_template.py b/homeassistant/components/mqtt/light/schema_template.py index c35b0e6ced9b8..a1f4ea2e81a22 100644 --- a/homeassistant/components/mqtt/light/schema_template.py +++ b/homeassistant/components/mqtt/light/schema_template.py @@ -31,6 +31,7 @@ from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.restore_state import RestoreEntity +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, TemplateVarsType, VolSchemaType import homeassistant.util.color as color_util @@ -43,7 +44,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from ..schemas import MQTT_ENTITY_COMMON_SCHEMA from .schema import MQTT_LIGHT_SCHEMA_SCHEMA diff --git a/homeassistant/components/mqtt/lock.py b/homeassistant/components/mqtt/lock.py index 22b0e24b3c666..c72dcd8dc21bf 100644 --- a/homeassistant/components/mqtt/lock.py +++ b/homeassistant/components/mqtt/lock.py @@ -21,6 +21,7 @@ from homeassistant.core import HomeAssistant, callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, TemplateVarsType from . import subscription @@ -39,7 +40,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA diff --git a/homeassistant/components/mqtt/number.py b/homeassistant/components/mqtt/number.py index e8f2cf0cfe404..ce441a2de6ecf 100644 --- a/homeassistant/components/mqtt/number.py +++ b/homeassistant/components/mqtt/number.py @@ -28,6 +28,7 @@ from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, VolSchemaType from . import subscription @@ -44,7 +45,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA diff --git a/homeassistant/components/mqtt/select.py b/homeassistant/components/mqtt/select.py index e301892dee23f..5f9c4a11c2316 100644 --- a/homeassistant/components/mqtt/select.py +++ b/homeassistant/components/mqtt/select.py @@ -15,6 +15,7 @@ from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, VolSchemaType from . import subscription @@ -31,7 +32,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA diff --git a/homeassistant/components/mqtt/sensor.py b/homeassistant/components/mqtt/sensor.py index d689b6bb76738..fc95807b8a5d9 100644 --- a/homeassistant/components/mqtt/sensor.py +++ b/homeassistant/components/mqtt/sensor.py @@ -33,6 +33,7 @@ import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.event import async_call_later +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, VolSchemaType from homeassistant.util import dt as dt_util @@ -40,12 +41,7 @@ from .config import MQTT_RO_SCHEMA from .const import CONF_OPTIONS, CONF_STATE_TOPIC, PAYLOAD_NONE from .mixins import MqttAvailabilityMixin, MqttEntity, async_setup_entity_entry_helper -from .models import ( - MqttValueTemplate, - PayloadSentinel, - ReceiveMessage, - ReceivePayloadType, -) +from .models import MqttValueTemplate, PayloadSentinel, ReceiveMessage from .schemas import MQTT_ENTITY_COMMON_SCHEMA from .util import check_state_too_long diff --git a/homeassistant/components/mqtt/siren.py b/homeassistant/components/mqtt/siren.py index 9f1466dd95d42..e7cf9e270bded 100644 --- a/homeassistant/components/mqtt/siren.py +++ b/homeassistant/components/mqtt/siren.py @@ -31,6 +31,7 @@ import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.json import json_dumps +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.template import Template from homeassistant.helpers.typing import ConfigType, TemplateVarsType, VolSchemaType from homeassistant.util.json import JSON_DECODE_EXCEPTIONS, json_loads_object @@ -51,7 +52,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA diff --git a/homeassistant/components/mqtt/tag.py b/homeassistant/components/mqtt/tag.py index d5f5371c357a5..031c620af4a23 100644 --- a/homeassistant/components/mqtt/tag.py +++ b/homeassistant/components/mqtt/tag.py @@ -13,6 +13,7 @@ from homeassistant.const import CONF_DEVICE, CONF_VALUE_TEMPLATE from homeassistant.core import HassJobType, HomeAssistant, callback import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import subscription @@ -31,7 +32,6 @@ MqttValueTemplate, MqttValueTemplateException, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_DEVICE_INFO_SCHEMA from .subscription import EntitySubscription diff --git a/homeassistant/components/mqtt/text.py b/homeassistant/components/mqtt/text.py index 0b122dec7b5dd..0db711cc4567d 100644 --- a/homeassistant/components/mqtt/text.py +++ b/homeassistant/components/mqtt/text.py @@ -22,6 +22,7 @@ from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.typing import ConfigType, VolSchemaType from . import subscription @@ -33,7 +34,6 @@ MqttValueTemplate, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) from .schemas import MQTT_ENTITY_COMMON_SCHEMA from .util import check_state_too_long diff --git a/homeassistant/components/mqtt/trigger.py b/homeassistant/components/mqtt/trigger.py index 3f7f03d7f1988..b901176cf8805 100644 --- a/homeassistant/components/mqtt/trigger.py +++ b/homeassistant/components/mqtt/trigger.py @@ -18,6 +18,7 @@ callback, ) from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.helpers.template import Template from homeassistant.helpers.trigger import TriggerActionType, TriggerData, TriggerInfo from homeassistant.helpers.typing import ConfigType, TemplateVarsType @@ -31,7 +32,6 @@ PayloadSentinel, PublishPayloadType, ReceiveMessage, - ReceivePayloadType, ) TRIGGER_SCHEMA = cv.TRIGGER_BASE_SCHEMA.extend( diff --git a/homeassistant/components/mysensors/gateway.py b/homeassistant/components/mysensors/gateway.py index 11f27f8a1083e..00c8d5eecfb87 100644 --- a/homeassistant/components/mysensors/gateway.py +++ b/homeassistant/components/mysensors/gateway.py @@ -16,7 +16,6 @@ from homeassistant.components.mqtt import ( DOMAIN as MQTT_DOMAIN, ReceiveMessage as MQTTReceiveMessage, - ReceivePayloadType, async_publish, async_subscribe, ) @@ -24,6 +23,7 @@ from homeassistant.const import CONF_DEVICE, EVENT_HOMEASSISTANT_STOP from homeassistant.core import Event, HomeAssistant, callback import homeassistant.helpers.config_validation as cv +from homeassistant.helpers.service_info.mqtt import ReceivePayloadType from homeassistant.setup import SetupPhases, async_pause_setup from homeassistant.util.unit_system import METRIC_SYSTEM diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index 333960d8ad4f4..5dab5689518ae 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -2458,7 +2458,6 @@ async def test_multi_platform_discovery( "PayloadSentinel", "PublishPayloadType", "ReceiveMessage", - "ReceivePayloadType", "async_prepare_subscribe_topics", "async_publish", "async_subscribe", From 6e5e96b0476329ddbc497cc75f69325d7674b2fe Mon Sep 17 00:00:00 2001 From: Sid <27780930+autinerd@users.noreply.github.com> Date: Thu, 22 Aug 2024 20:51:57 +0200 Subject: [PATCH 25/31] Bump ruff to 0.6.2 (#124433) --- .pre-commit-config.yaml | 2 +- requirements_test_pre_commit.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index f29fd92a880cc..ab5e59139cfd1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.6.1 + rev: v0.6.2 hooks: - id: ruff args: diff --git a/requirements_test_pre_commit.txt b/requirements_test_pre_commit.txt index 6bd2fbbc145bb..0c8d2b3796ba1 100644 --- a/requirements_test_pre_commit.txt +++ b/requirements_test_pre_commit.txt @@ -1,5 +1,5 @@ # Automatically generated from .pre-commit-config.yaml by gen_requirements_all.py, do not edit codespell==2.3.0 -ruff==0.6.1 +ruff==0.6.2 yamllint==1.35.1 From 51dba1eec359a2a6a801c90f095305e0b1f53e7a Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Thu, 22 Aug 2024 20:58:05 +0200 Subject: [PATCH 26/31] Cleanup redundant fixtures and move all other hassio addon fixtures to be shared (#124437) --- tests/components/conftest.py | 65 ++++++++ tests/components/hassio/common.py | 59 ++++++- tests/components/hassio/test_addon_manager.py | 152 +----------------- 3 files changed, 124 insertions(+), 152 deletions(-) diff --git a/tests/components/conftest.py b/tests/components/conftest.py index 26da794e03b59..9f13d52e0e85f 100644 --- a/tests/components/conftest.py +++ b/tests/components/conftest.py @@ -14,6 +14,8 @@ from homeassistant.core import HomeAssistant if TYPE_CHECKING: + from homeassistant.components.hassio.addon_manager import AddonManager + from .conversation import MockAgent from .device_tracker.common import MockScanner from .light.common import MockLight @@ -182,6 +184,15 @@ def mock_legacy_device_tracker_setup() -> Callable[[HomeAssistant, MockScanner], return mock_legacy_device_tracker_setup +@pytest.fixture(name="addon_manager") +def addon_manager_fixture(hass: HomeAssistant) -> AddonManager: + """Return an AddonManager instance.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_addon_manager + + return mock_addon_manager(hass) + + @pytest.fixture(name="discovery_info") def discovery_info_fixture() -> Any: """Return the discovery info from the supervisor.""" @@ -269,3 +280,57 @@ def start_addon_fixture() -> Generator[AsyncMock]: from .hassio.common import mock_start_addon yield from mock_start_addon() + + +@pytest.fixture(name="restart_addon") +def restart_addon_fixture() -> Generator[AsyncMock]: + """Mock restart add-on.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_restart_addon + + yield from mock_restart_addon() + + +@pytest.fixture(name="stop_addon") +def stop_addon_fixture() -> Generator[AsyncMock]: + """Mock stop add-on.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_stop_addon + + yield from mock_stop_addon() + + +@pytest.fixture(name="set_addon_options") +def set_addon_options_fixture() -> Generator[AsyncMock]: + """Mock set add-on options.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_set_addon_options + + yield from mock_set_addon_options() + + +@pytest.fixture(name="uninstall_addon") +def uninstall_addon_fixture() -> Generator[AsyncMock]: + """Mock uninstall add-on.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_uninstall_addon + + yield from mock_uninstall_addon() + + +@pytest.fixture(name="create_backup") +def create_backup_fixture() -> Generator[AsyncMock]: + """Mock create backup.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_create_backup + + yield from mock_create_backup() + + +@pytest.fixture(name="update_addon") +def update_addon_fixture() -> Generator[AsyncMock]: + """Mock update add-on.""" + # pylint: disable-next=import-outside-toplevel + from .hassio.common import mock_update_addon + + yield from mock_update_addon() diff --git a/tests/components/hassio/common.py b/tests/components/hassio/common.py index f9a77628bbe42..f39e65dcb1ef3 100644 --- a/tests/components/hassio/common.py +++ b/tests/components/hassio/common.py @@ -3,11 +3,20 @@ from __future__ import annotations from collections.abc import Generator +import logging from typing import Any from unittest.mock import DEFAULT, AsyncMock, patch +from homeassistant.components.hassio.addon_manager import AddonManager from homeassistant.core import HomeAssistant +LOGGER = logging.getLogger(__name__) + + +def mock_addon_manager(hass: HomeAssistant) -> AddonManager: + """Return an AddonManager instance.""" + return AddonManager(hass, LOGGER, "Test", "test_addon") + def mock_discovery_info() -> Any: """Return the discovery info from the supervisor.""" @@ -72,7 +81,7 @@ def mock_addon_installed( "version": "1.0.0", } addon_info.return_value["available"] = True - addon_info.return_value["hostname"] = "core-matter-server" + addon_info.return_value["hostname"] = "core-test-addon" addon_info.return_value["state"] = "stopped" addon_info.return_value["version"] = "1.0.0" return addon_info @@ -123,3 +132,51 @@ def mock_start_addon() -> Generator[AsyncMock]: "homeassistant.components.hassio.addon_manager.async_start_addon" ) as start_addon: yield start_addon + + +def mock_stop_addon() -> Generator[AsyncMock]: + """Mock stop add-on.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_stop_addon" + ) as stop_addon: + yield stop_addon + + +def mock_restart_addon() -> Generator[AsyncMock]: + """Mock restart add-on.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_restart_addon" + ) as restart_addon: + yield restart_addon + + +def mock_uninstall_addon() -> Generator[AsyncMock]: + """Mock uninstall add-on.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_uninstall_addon" + ) as uninstall_addon: + yield uninstall_addon + + +def mock_set_addon_options() -> Generator[AsyncMock]: + """Mock set add-on options.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_set_addon_options" + ) as set_options: + yield set_options + + +def mock_create_backup() -> Generator[AsyncMock]: + """Mock create backup.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_create_backup" + ) as create_backup: + yield create_backup + + +def mock_update_addon() -> Generator[AsyncMock]: + """Mock update add-on.""" + with patch( + "homeassistant.components.hassio.addon_manager.async_update_addon" + ) as update_addon: + yield update_addon diff --git a/tests/components/hassio/test_addon_manager.py b/tests/components/hassio/test_addon_manager.py index 6a20c6eec885e..af7a3551684c5 100644 --- a/tests/components/hassio/test_addon_manager.py +++ b/tests/components/hassio/test_addon_manager.py @@ -3,10 +3,8 @@ from __future__ import annotations import asyncio -from collections.abc import Generator -import logging from typing import Any -from unittest.mock import AsyncMock, call, patch +from unittest.mock import AsyncMock, call import pytest @@ -19,154 +17,6 @@ from homeassistant.components.hassio.handler import HassioAPIError from homeassistant.core import HomeAssistant -LOGGER = logging.getLogger(__name__) - - -@pytest.fixture(name="addon_manager") -def addon_manager_fixture(hass: HomeAssistant) -> AddonManager: - """Return an AddonManager instance.""" - return AddonManager(hass, LOGGER, "Test", "test_addon") - - -@pytest.fixture(name="addon_not_installed") -def addon_not_installed_fixture( - addon_store_info: AsyncMock, addon_info: AsyncMock -) -> AsyncMock: - """Mock add-on not installed.""" - addon_store_info.return_value["available"] = True - return addon_info - - -@pytest.fixture(name="addon_installed") -def mock_addon_installed( - addon_store_info: AsyncMock, addon_info: AsyncMock -) -> AsyncMock: - """Mock add-on already installed but not running.""" - addon_store_info.return_value = { - "available": True, - "installed": "1.0.0", - "state": "stopped", - "version": "1.0.0", - } - addon_info.return_value["available"] = True - addon_info.return_value["hostname"] = "core-test-addon" - addon_info.return_value["state"] = "stopped" - addon_info.return_value["version"] = "1.0.0" - return addon_info - - -@pytest.fixture(name="get_addon_discovery_info") -def get_addon_discovery_info_fixture() -> Generator[AsyncMock]: - """Mock get add-on discovery info.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_get_addon_discovery_info" - ) as get_addon_discovery_info: - yield get_addon_discovery_info - - -@pytest.fixture(name="addon_store_info") -def addon_store_info_fixture() -> Generator[AsyncMock]: - """Mock Supervisor add-on store info.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_get_addon_store_info" - ) as addon_store_info: - addon_store_info.return_value = { - "available": False, - "installed": None, - "state": None, - "version": "1.0.0", - } - yield addon_store_info - - -@pytest.fixture(name="addon_info") -def addon_info_fixture() -> Generator[AsyncMock]: - """Mock Supervisor add-on info.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_get_addon_info", - ) as addon_info: - addon_info.return_value = { - "available": False, - "hostname": None, - "options": {}, - "state": None, - "update_available": False, - "version": None, - } - yield addon_info - - -@pytest.fixture(name="set_addon_options") -def set_addon_options_fixture() -> Generator[AsyncMock]: - """Mock set add-on options.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_set_addon_options" - ) as set_options: - yield set_options - - -@pytest.fixture(name="install_addon") -def install_addon_fixture() -> Generator[AsyncMock]: - """Mock install add-on.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_install_addon" - ) as install_addon: - yield install_addon - - -@pytest.fixture(name="uninstall_addon") -def uninstall_addon_fixture() -> Generator[AsyncMock]: - """Mock uninstall add-on.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_uninstall_addon" - ) as uninstall_addon: - yield uninstall_addon - - -@pytest.fixture(name="start_addon") -def start_addon_fixture() -> Generator[AsyncMock]: - """Mock start add-on.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_start_addon" - ) as start_addon: - yield start_addon - - -@pytest.fixture(name="restart_addon") -def restart_addon_fixture() -> Generator[AsyncMock]: - """Mock restart add-on.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_restart_addon" - ) as restart_addon: - yield restart_addon - - -@pytest.fixture(name="stop_addon") -def stop_addon_fixture() -> Generator[AsyncMock]: - """Mock stop add-on.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_stop_addon" - ) as stop_addon: - yield stop_addon - - -@pytest.fixture(name="create_backup") -def create_backup_fixture() -> Generator[AsyncMock]: - """Mock create backup.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_create_backup" - ) as create_backup: - yield create_backup - - -@pytest.fixture(name="update_addon") -def mock_update_addon() -> Generator[AsyncMock]: - """Mock update add-on.""" - with patch( - "homeassistant.components.hassio.addon_manager.async_update_addon" - ) as update_addon: - yield update_addon - async def test_not_installed_raises_exception( addon_manager: AddonManager, From 1d35c745bb2390ae52dc683991906ba57d4a5bba Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 22 Aug 2024 14:00:30 -0500 Subject: [PATCH 27/31] Reduce ESPHome entity state write overhead (#124329) --- homeassistant/components/esphome/entity.py | 8 +++----- homeassistant/components/esphome/entry_data.py | 5 ++++- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/esphome/entity.py b/homeassistant/components/esphome/entity.py index 764390c861b51..a484a988ea961 100644 --- a/homeassistant/components/esphome/entity.py +++ b/homeassistant/components/esphome/entity.py @@ -94,7 +94,6 @@ async def platform_async_setup_entry( """ entry_data = entry.runtime_data entry_data.info[info_type] = {} - entry_data.state.setdefault(state_type, {}) platform = entity_platform.async_get_current_platform() on_static_info_update = functools.partial( async_static_info_updated, @@ -188,6 +187,7 @@ def __init__( ) -> None: """Initialize.""" self._entry_data = entry_data + self._states = cast(dict[int, _StateT], entry_data.state[state_type]) assert entry_data.device_info is not None device_info = entry_data.device_info self._device_info = device_info @@ -265,11 +265,9 @@ def _on_static_info_update(self, static_info: EntityInfo) -> None: @callback def _update_state_from_entry_data(self) -> None: """Update state from entry data.""" - state = self._entry_data.state key = self._key - state_type = self._state_type - if has_state := key in state[state_type]: - self._state = cast(_StateT, state[state_type][key]) + if has_state := key in self._states: + self._state = self._states[key] self._has_state = has_state @callback diff --git a/homeassistant/components/esphome/entry_data.py b/homeassistant/components/esphome/entry_data.py index ff6f048eba19f..6fc40612c489f 100644 --- a/homeassistant/components/esphome/entry_data.py +++ b/homeassistant/components/esphome/entry_data.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +from collections import defaultdict from collections.abc import Callable, Iterable from dataclasses import dataclass, field from functools import partial @@ -111,7 +112,9 @@ class RuntimeEntryData: title: str client: APIClient store: ESPHomeStorage - state: dict[type[EntityState], dict[int, EntityState]] = field(default_factory=dict) + state: defaultdict[type[EntityState], dict[int, EntityState]] = field( + default_factory=lambda: defaultdict(dict) + ) # When the disconnect callback is called, we mark all states # as stale so we will always dispatch a state update when the # device reconnects. This is the same format as state_subscriptions. From 281a9f042be23a31d72509f1acd697c837e02db8 Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Thu, 22 Aug 2024 21:01:48 +0200 Subject: [PATCH 28/31] Check minimum amount of integrations for a brand (#124310) --- script/hassfest/brand.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/script/hassfest/brand.py b/script/hassfest/brand.py index fe47d31067a02..6139e12393e87 100644 --- a/script/hassfest/brand.py +++ b/script/hassfest/brand.py @@ -18,6 +18,8 @@ } ) +BRAND_EXCEPTIONS = ["u_tec"] + def _validate_brand( brand: Brand, integrations: dict[str, Integration], config: Config @@ -38,10 +40,14 @@ def _validate_brand( f"Domain '{brand.domain}' does not match file name {brand.path.name}", ) - if not brand.integrations and not brand.iot_standards: + if ( + len(brand.integrations) < 2 + and not brand.iot_standards + and brand.domain not in BRAND_EXCEPTIONS + ): config.add_error( "brand", - f"{brand.path.name}: At least one of integrations or " + f"{brand.path.name}: At least two integrations or " "iot_standards must be non-empty", ) From fc1ed7d7cb39964f39577cf61fa71a91edf50317 Mon Sep 17 00:00:00 2001 From: Raman Gupta <7243222+raman325@users.noreply.github.com> Date: Thu, 22 Aug 2024 15:07:21 -0400 Subject: [PATCH 29/31] Refactor targets for zwave_js services (#115734) * Let labels be used as targets for zwave_js services * add coverage * Fix test bug and switch from targets to fields * Remove label addition * Remove labels from service descriptions * Remove labels from strings * More changes --- homeassistant/components/zwave_js/helpers.py | 26 ++- homeassistant/components/zwave_js/services.py | 64 ++---- .../components/zwave_js/services.yaml | 193 ++++++++++++++++-- .../components/zwave_js/strings.json | 98 +++++++++ 4 files changed, 295 insertions(+), 86 deletions(-) diff --git a/homeassistant/components/zwave_js/helpers.py b/homeassistant/components/zwave_js/helpers.py index 737b8deff34be..5885527e01c33 100644 --- a/homeassistant/components/zwave_js/helpers.py +++ b/homeassistant/components/zwave_js/helpers.py @@ -343,20 +343,18 @@ def async_get_nodes_from_area_id( } ) # Add devices in an area that are Z-Wave JS devices - for device in dr.async_entries_for_area(dev_reg, area_id): - if next( - ( - config_entry_id - for config_entry_id in device.config_entries - if cast( - ConfigEntry, - hass.config_entries.async_get_entry(config_entry_id), - ).domain - == DOMAIN - ), - None, - ): - nodes.add(async_get_node_from_device_id(hass, device.id, dev_reg)) + nodes.update( + async_get_node_from_device_id(hass, device.id, dev_reg) + for device in dr.async_entries_for_area(dev_reg, area_id) + if any( + cast( + ConfigEntry, + hass.config_entries.async_get_entry(config_entry_id), + ).domain + == DOMAIN + for config_entry_id in device.config_entries + ) + ) return nodes diff --git a/homeassistant/components/zwave_js/services.py b/homeassistant/components/zwave_js/services.py index e5c0bd64781aa..969a235bb414e 100644 --- a/homeassistant/components/zwave_js/services.py +++ b/homeassistant/components/zwave_js/services.py @@ -48,6 +48,12 @@ type _NodeOrEndpointType = ZwaveNode | Endpoint +TARGET_VALIDATORS = { + vol.Optional(ATTR_AREA_ID): vol.All(cv.ensure_list, [cv.string]), + vol.Optional(ATTR_DEVICE_ID): vol.All(cv.ensure_list, [cv.string]), + vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, +} + def parameter_name_does_not_need_bitmask( val: dict[str, int | str | list[str]], @@ -261,13 +267,7 @@ def validate_entities(val: dict[str, Any]) -> dict[str, Any]: schema=vol.Schema( vol.All( { - vol.Optional(ATTR_AREA_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_DEVICE_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, + **TARGET_VALIDATORS, vol.Optional(const.ATTR_ENDPOINT, default=0): vol.Coerce(int), vol.Required(const.ATTR_CONFIG_PARAMETER): vol.Any( vol.Coerce(int), cv.string @@ -305,13 +305,7 @@ def validate_entities(val: dict[str, Any]) -> dict[str, Any]: schema=vol.Schema( vol.All( { - vol.Optional(ATTR_AREA_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_DEVICE_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, + **TARGET_VALIDATORS, vol.Optional(const.ATTR_ENDPOINT, default=0): vol.Coerce(int), vol.Required(const.ATTR_CONFIG_PARAMETER): vol.Coerce(int), vol.Required(const.ATTR_CONFIG_VALUE): vol.Any( @@ -356,13 +350,7 @@ def validate_entities(val: dict[str, Any]) -> dict[str, Any]: schema=vol.Schema( vol.All( { - vol.Optional(ATTR_AREA_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_DEVICE_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, + **TARGET_VALIDATORS, vol.Required(const.ATTR_COMMAND_CLASS): vol.Coerce(int), vol.Required(const.ATTR_PROPERTY): vol.Any( vol.Coerce(int), str @@ -391,13 +379,7 @@ def validate_entities(val: dict[str, Any]) -> dict[str, Any]: schema=vol.Schema( vol.All( { - vol.Optional(ATTR_AREA_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_DEVICE_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, + **TARGET_VALIDATORS, vol.Optional(const.ATTR_BROADCAST, default=False): cv.boolean, vol.Required(const.ATTR_COMMAND_CLASS): vol.Coerce(int), vol.Required(const.ATTR_PROPERTY): vol.Any( @@ -428,15 +410,7 @@ def validate_entities(val: dict[str, Any]) -> dict[str, Any]: self.async_ping, schema=vol.Schema( vol.All( - { - vol.Optional(ATTR_AREA_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_DEVICE_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, - }, + TARGET_VALIDATORS, cv.has_at_least_one_key( ATTR_DEVICE_ID, ATTR_ENTITY_ID, ATTR_AREA_ID ), @@ -453,13 +427,7 @@ def validate_entities(val: dict[str, Any]) -> dict[str, Any]: schema=vol.Schema( vol.All( { - vol.Optional(ATTR_AREA_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_DEVICE_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, + **TARGET_VALIDATORS, vol.Required(const.ATTR_COMMAND_CLASS): vol.All( vol.Coerce(int), vol.Coerce(CommandClass) ), @@ -483,13 +451,7 @@ def validate_entities(val: dict[str, Any]) -> dict[str, Any]: schema=vol.Schema( vol.All( { - vol.Optional(ATTR_AREA_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_DEVICE_ID): vol.All( - cv.ensure_list, [cv.string] - ), - vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, + **TARGET_VALIDATORS, vol.Required(const.ATTR_NOTIFICATION_TYPE): vol.All( vol.Coerce(int), vol.Coerce(NotificationType) ), diff --git a/homeassistant/components/zwave_js/services.yaml b/homeassistant/components/zwave_js/services.yaml index 81809e3fbeb74..1e521ddbe2d36 100644 --- a/homeassistant/components/zwave_js/services.yaml +++ b/homeassistant/components/zwave_js/services.yaml @@ -89,10 +89,28 @@ set_lock_configuration: boolean: set_config_parameter: - target: - entity: - integration: zwave_js fields: + area_id: + example: living_room + selector: + area: + device: + - integration: zwave_js + multiple: true + device_id: + example: "8f4219cfa57e23f6f669c4616c2205e2" + selector: + device: + filter: + - integration: zwave_js + multiple: true + entity_id: + example: sensor.living_room_temperature + selector: + entity: + filter: + - integration: zwave_js + multiple: true endpoint: example: 1 default: 0 @@ -127,10 +145,28 @@ set_config_parameter: max: 3 bulk_set_partial_config_parameters: - target: - entity: - integration: zwave_js fields: + area_id: + example: living_room + selector: + area: + device: + - integration: zwave_js + multiple: true + device_id: + example: "8f4219cfa57e23f6f669c4616c2205e2" + selector: + device: + filter: + - integration: zwave_js + multiple: true + entity_id: + example: sensor.living_room_temperature + selector: + entity: + filter: + - integration: zwave_js + multiple: true endpoint: example: 1 default: 0 @@ -169,10 +205,28 @@ refresh_value: boolean: set_value: - target: - entity: - integration: zwave_js fields: + area_id: + example: living_room + selector: + area: + device: + - integration: zwave_js + multiple: true + device_id: + example: "8f4219cfa57e23f6f669c4616c2205e2" + selector: + device: + filter: + - integration: zwave_js + multiple: true + entity_id: + example: sensor.living_room_temperature + selector: + entity: + filter: + - integration: zwave_js + multiple: true command_class: example: 117 required: true @@ -208,10 +262,28 @@ set_value: boolean: multicast_set_value: - target: - entity: - integration: zwave_js fields: + area_id: + example: living_room + selector: + area: + device: + - integration: zwave_js + multiple: true + device_id: + example: "8f4219cfa57e23f6f669c4616c2205e2" + selector: + device: + filter: + - integration: zwave_js + multiple: true + entity_id: + example: sensor.living_room_temperature + selector: + entity: + filter: + - integration: zwave_js + multiple: true broadcast: example: true required: false @@ -248,9 +320,28 @@ multicast_set_value: object: ping: - target: - entity: - integration: zwave_js + fields: + area_id: + example: living_room + selector: + area: + device: + - integration: zwave_js + multiple: true + device_id: + example: "8f4219cfa57e23f6f669c4616c2205e2" + selector: + device: + filter: + - integration: zwave_js + multiple: true + entity_id: + example: sensor.living_room_temperature + selector: + entity: + filter: + - integration: zwave_js + multiple: true reset_meter: target: @@ -258,6 +349,30 @@ reset_meter: domain: sensor integration: zwave_js fields: + area_id: + example: living_room + selector: + area: + entity: + - integration: zwave_js + domain: sensor + multiple: true + device_id: + example: "8f4219cfa57e23f6f669c4616c2205e2" + selector: + device: + entity: + - integration: zwave_js + domain: sensor + multiple: true + entity_id: + example: sensor.living_room_temperature + selector: + entity: + filter: + - integration: zwave_js + domain: sensor + multiple: true meter_type: example: 1 required: false @@ -270,10 +385,28 @@ reset_meter: text: invoke_cc_api: - target: - entity: - integration: zwave_js fields: + area_id: + example: living_room + selector: + area: + device: + - integration: zwave_js + multiple: true + device_id: + example: "8f4219cfa57e23f6f669c4616c2205e2" + selector: + device: + filter: + - integration: zwave_js + multiple: true + entity_id: + example: sensor.living_room_temperature + selector: + entity: + filter: + - integration: zwave_js + multiple: true command_class: example: 132 required: true @@ -296,10 +429,28 @@ invoke_cc_api: object: refresh_notifications: - target: - entity: - integration: zwave_js fields: + area_id: + example: living_room + selector: + area: + device: + - integration: zwave_js + multiple: true + device_id: + example: "8f4219cfa57e23f6f669c4616c2205e2" + selector: + device: + filter: + - integration: zwave_js + multiple: true + entity_id: + example: sensor.living_room_temperature + selector: + entity: + filter: + - integration: zwave_js + multiple: true notification_type: example: 1 required: true diff --git a/homeassistant/components/zwave_js/strings.json b/homeassistant/components/zwave_js/strings.json index 4bba3e0538cf8..ca7d5153e6e0b 100644 --- a/homeassistant/components/zwave_js/strings.json +++ b/homeassistant/components/zwave_js/strings.json @@ -265,10 +265,22 @@ "bulk_set_partial_config_parameters": { "description": "Allows for bulk setting partial parameters. Useful when multiple partial parameters have to be set at the same time.", "fields": { + "area_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::area_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::area_id::name%]" + }, + "device_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::device_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::device_id::name%]" + }, "endpoint": { "description": "[%key:component::zwave_js::services::set_config_parameter::fields::endpoint::description%]", "name": "[%key:component::zwave_js::services::set_config_parameter::fields::endpoint::name%]" }, + "entity_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::entity_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::entity_id::name%]" + }, "parameter": { "description": "[%key:component::zwave_js::services::set_config_parameter::fields::parameter::description%]", "name": "[%key:component::zwave_js::services::set_config_parameter::fields::parameter::name%]" @@ -293,14 +305,26 @@ "invoke_cc_api": { "description": "Calls a Command Class API on a node. Some Command Classes can't be fully controlled via the `set_value` action and require direct calls to the Command Class API.", "fields": { + "area_id": { + "description": "The area(s) to target for this service. If an area is specified, all zwave_js devices and entities in that area will be targeted for this service.", + "name": "Area ID(s)" + }, "command_class": { "description": "The ID of the command class that you want to issue a command to.", "name": "[%key:component::zwave_js::services::set_value::fields::command_class::name%]" }, + "device_id": { + "description": "The device(s) to target for this service.", + "name": "Device ID(s)" + }, "endpoint": { "description": "The endpoint to call the API on. If an endpoint is specified, that endpoint will be targeted for all nodes associated with the target areas, devices, and/or entities. If an endpoint is not specified, the root endpoint (0) will be targeted for nodes associated with target areas and devices, and the endpoint for the primary value of each entity will be targeted.", "name": "[%key:component::zwave_js::services::set_config_parameter::fields::endpoint::name%]" }, + "entity_id": { + "description": "The entity ID(s) to target for this service.", + "name": "Entity ID(s)" + }, "method_name": { "description": "The name of the API method to call. Refer to the Z-Wave JS Command Class API documentation (https://zwave-js.github.io/node-zwave-js/#/api/CCs/index) for available methods.", "name": "Method name" @@ -315,6 +339,10 @@ "multicast_set_value": { "description": "Changes any value that Z-Wave JS recognizes on multiple Z-Wave devices using multicast, so all devices receive the message simultaneously. This action has minimal validation so only use this action if you know what you are doing.", "fields": { + "area_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::area_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::area_id::name%]" + }, "broadcast": { "description": "Whether command should be broadcast to all devices on the network.", "name": "Broadcast?" @@ -323,10 +351,18 @@ "description": "[%key:component::zwave_js::services::set_value::fields::command_class::description%]", "name": "[%key:component::zwave_js::services::set_value::fields::command_class::name%]" }, + "device_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::device_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::device_id::name%]" + }, "endpoint": { "description": "[%key:component::zwave_js::services::set_value::fields::endpoint::description%]", "name": "[%key:component::zwave_js::services::set_config_parameter::fields::endpoint::name%]" }, + "entity_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::entity_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::entity_id::name%]" + }, "options": { "description": "[%key:component::zwave_js::services::set_value::fields::options::description%]", "name": "[%key:component::zwave_js::services::set_value::fields::options::name%]" @@ -348,11 +384,37 @@ }, "ping": { "description": "Forces Z-Wave JS to try to reach a node. This can be used to update the status of the node in Z-Wave JS when you think it doesn't accurately reflect reality, e.g. reviving a failed/dead node or marking the node as asleep.", + "fields": { + "area_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::area_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::area_id::name%]" + }, + "device_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::device_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::device_id::name%]" + }, + "entity_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::entity_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::entity_id::name%]" + } + }, "name": "Ping a node" }, "refresh_notifications": { "description": "Refreshes notifications on a node based on notification type and optionally notification event.", "fields": { + "area_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::area_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::area_id::name%]" + }, + "device_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::device_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::device_id::name%]" + }, + "entity_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::entity_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::entity_id::name%]" + }, "notification_event": { "description": "The Notification Event number as defined in the Z-Wave specs.", "name": "Notification Event" @@ -381,6 +443,18 @@ "reset_meter": { "description": "Resets the meters on a node.", "fields": { + "area_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::area_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::area_id::name%]" + }, + "device_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::device_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::device_id::name%]" + }, + "entity_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::entity_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::entity_id::name%]" + }, "meter_type": { "description": "The type of meter to reset. Not all meters support the ability to pick a meter type to reset.", "name": "Meter type" @@ -395,14 +469,26 @@ "set_config_parameter": { "description": "Changes the configuration parameters of your Z-Wave devices.", "fields": { + "area_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::area_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::area_id::name%]" + }, "bitmask": { "description": "Target a specific bitmask (see the documentation for more information). Cannot be combined with value_size or value_format.", "name": "Bitmask" }, + "device_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::device_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::device_id::name%]" + }, "endpoint": { "description": "The configuration parameter's endpoint.", "name": "Endpoint" }, + "entity_id": { + "description": "[%key:component::zwave_js::services::set_value::fields::entity_id::description%]", + "name": "[%key:component::zwave_js::services::set_value::fields::entity_id::name%]" + }, "parameter": { "description": "The name (or ID) of the configuration parameter you want to configure.", "name": "Parameter" @@ -477,14 +563,26 @@ "set_value": { "description": "Changes any value that Z-Wave JS recognizes on a Z-Wave device. This action has minimal validation so only use this action if you know what you are doing.", "fields": { + "area_id": { + "description": "The area(s) to target for this service. If an area is specified, all zwave_js devices and entities in that area will be targeted for this service.", + "name": "Area ID(s)" + }, "command_class": { "description": "The ID of the command class for the value.", "name": "Command class" }, + "device_id": { + "description": "The device(s) to target for this service.", + "name": "Device ID(s)" + }, "endpoint": { "description": "The endpoint for the value.", "name": "[%key:component::zwave_js::services::set_config_parameter::fields::endpoint::name%]" }, + "entity_id": { + "description": "The entity ID(s) to target for this service.", + "name": "Entity ID(s)" + }, "options": { "description": "Set value options map. Refer to the Z-Wave JS documentation for more information on what options can be set.", "name": "Options" From 2533bde27a87b9eee13378e3dc2bba2435f95323 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 22 Aug 2024 14:46:54 -0500 Subject: [PATCH 30/31] Bump yalexs to 8.1.4 (#124425) changelog: https://github.com/bdraco/yalexs/compare/v8.1.2...v8.1.4 --- homeassistant/components/august/manifest.json | 2 +- requirements_all.txt | 2 +- requirements_test_all.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/august/manifest.json b/homeassistant/components/august/manifest.json index 5d7b253e95253..7e73e55e6ba9d 100644 --- a/homeassistant/components/august/manifest.json +++ b/homeassistant/components/august/manifest.json @@ -28,5 +28,5 @@ "documentation": "https://www.home-assistant.io/integrations/august", "iot_class": "cloud_push", "loggers": ["pubnub", "yalexs"], - "requirements": ["yalexs==8.1.2", "yalexs-ble==2.4.3"] + "requirements": ["yalexs==8.1.4", "yalexs-ble==2.4.3"] } diff --git a/requirements_all.txt b/requirements_all.txt index 78215689479cc..4caea33f8e80a 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2968,7 +2968,7 @@ yalesmartalarmclient==0.4.0 yalexs-ble==2.4.3 # homeassistant.components.august -yalexs==8.1.2 +yalexs==8.1.4 # homeassistant.components.yeelight yeelight==0.7.14 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index afbbfb396ac50..4deb4a075b534 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -2348,7 +2348,7 @@ yalesmartalarmclient==0.4.0 yalexs-ble==2.4.3 # homeassistant.components.august -yalexs==8.1.2 +yalexs==8.1.4 # homeassistant.components.yeelight yeelight==0.7.14 From 61ac4c7af7a3495e985e7ac75cde16346476d97d Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 22 Aug 2024 14:50:15 -0500 Subject: [PATCH 31/31] Use identity checks for ESPHome Enums (#124334) Enums are singletons and should use is to compare. The valve platform was updated but cover and lock were missed. --- homeassistant/components/esphome/cover.py | 4 ++-- homeassistant/components/esphome/lock.py | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/esphome/cover.py b/homeassistant/components/esphome/cover.py index 19ce4cbf55a24..83c749f89ca21 100644 --- a/homeassistant/components/esphome/cover.py +++ b/homeassistant/components/esphome/cover.py @@ -61,13 +61,13 @@ def is_closed(self) -> bool | None: @esphome_state_property def is_opening(self) -> bool: """Return if the cover is opening or not.""" - return self._state.current_operation == CoverOperation.IS_OPENING + return self._state.current_operation is CoverOperation.IS_OPENING @property @esphome_state_property def is_closing(self) -> bool: """Return if the cover is closing or not.""" - return self._state.current_operation == CoverOperation.IS_CLOSING + return self._state.current_operation is CoverOperation.IS_CLOSING @property @esphome_state_property diff --git a/homeassistant/components/esphome/lock.py b/homeassistant/components/esphome/lock.py index 4caa1f6861231..15a402ccb919f 100644 --- a/homeassistant/components/esphome/lock.py +++ b/homeassistant/components/esphome/lock.py @@ -40,25 +40,25 @@ def _on_static_info_update(self, static_info: EntityInfo) -> None: @esphome_state_property def is_locked(self) -> bool | None: """Return true if the lock is locked.""" - return self._state.state == LockState.LOCKED + return self._state.state is LockState.LOCKED @property @esphome_state_property def is_locking(self) -> bool | None: """Return true if the lock is locking.""" - return self._state.state == LockState.LOCKING + return self._state.state is LockState.LOCKING @property @esphome_state_property def is_unlocking(self) -> bool | None: """Return true if the lock is unlocking.""" - return self._state.state == LockState.UNLOCKING + return self._state.state is LockState.UNLOCKING @property @esphome_state_property def is_jammed(self) -> bool | None: """Return true if the lock is jammed (incomplete locking).""" - return self._state.state == LockState.JAMMED + return self._state.state is LockState.JAMMED @convert_api_error_ha_error async def async_lock(self, **kwargs: Any) -> None: