diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 805e3ac4dbd8c5..a059710d3d751a 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -8,7 +8,7 @@ repos: - id: ruff-format files: ^((homeassistant|pylint|script|tests)/.+)?[^/]+\.(py|pyi)$ - repo: https://github.com/codespell-project/codespell - rev: v2.3.0 + rev: v2.4.1 hooks: - id: codespell args: diff --git a/homeassistant/components/apple_tv/config_flow.py b/homeassistant/components/apple_tv/config_flow.py index 5c317755d05fbd..76c4681a30d6f0 100644 --- a/homeassistant/components/apple_tv/config_flow.py +++ b/homeassistant/components/apple_tv/config_flow.py @@ -134,7 +134,7 @@ def device_identifier(self) -> str | None: unique_id for said entry. When a new (zeroconf) service or device is discovered, the identifier is first used to look up if it belongs to an existing config entry. If that's the case, the unique_id from that entry is - re-used, otherwise the newly discovered identifier is used instead. + reused, otherwise the newly discovered identifier is used instead. """ assert self.atv all_identifiers = set(self.atv.all_identifiers) diff --git a/homeassistant/components/backup/__init__.py b/homeassistant/components/backup/__init__.py index 86e5b95d196490..f97805b19234f9 100644 --- a/homeassistant/components/backup/__init__.py +++ b/homeassistant/components/backup/__init__.py @@ -26,6 +26,8 @@ BackupReaderWriterError, CoreBackupReaderWriter, CreateBackupEvent, + CreateBackupStage, + CreateBackupState, IdleEvent, IncorrectPasswordError, ManagerBackup, @@ -49,6 +51,8 @@ "BackupReaderWriter", "BackupReaderWriterError", "CreateBackupEvent", + "CreateBackupStage", + "CreateBackupState", "Folder", "IdleEvent", "IncorrectPasswordError", diff --git a/homeassistant/components/backup/util.py b/homeassistant/components/backup/util.py index fbb13b4721abe5..b920c66a9b8568 100644 --- a/homeassistant/components/backup/util.py +++ b/homeassistant/components/backup/util.py @@ -4,6 +4,7 @@ import asyncio from collections.abc import AsyncIterator, Callable, Coroutine +from concurrent.futures import CancelledError, Future import copy from dataclasses import dataclass, replace from io import BytesIO @@ -12,6 +13,7 @@ from pathlib import Path, PurePath from queue import SimpleQueue import tarfile +import threading from typing import IO, Any, Self, cast import aiohttp @@ -22,7 +24,6 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.util import dt as dt_util from homeassistant.util.json import JsonObjectType, json_loads_object -from homeassistant.util.thread import ThreadWithException from .const import BUF_SIZE, LOGGER from .models import AddonInfo, AgentBackup, Folder @@ -167,23 +168,38 @@ class AsyncIteratorReader: def __init__(self, hass: HomeAssistant, stream: AsyncIterator[bytes]) -> None: """Initialize the wrapper.""" + self._aborted = False self._hass = hass self._stream = stream self._buffer: bytes | None = None + self._next_future: Future[bytes | None] | None = None self._pos: int = 0 async def _next(self) -> bytes | None: """Get the next chunk from the iterator.""" return await anext(self._stream, None) + def abort(self) -> None: + """Abort the reader.""" + self._aborted = True + if self._next_future is not None: + self._next_future.cancel() + def read(self, n: int = -1, /) -> bytes: """Read data from the iterator.""" result = bytearray() while n < 0 or len(result) < n: if not self._buffer: - self._buffer = asyncio.run_coroutine_threadsafe( + self._next_future = asyncio.run_coroutine_threadsafe( self._next(), self._hass.loop - ).result() + ) + if self._aborted: + self._next_future.cancel() + raise AbortCipher + try: + self._buffer = self._next_future.result() + except CancelledError as err: + raise AbortCipher from err self._pos = 0 if not self._buffer: # The stream is exhausted @@ -205,9 +221,11 @@ class AsyncIteratorWriter: def __init__(self, hass: HomeAssistant) -> None: """Initialize the wrapper.""" + self._aborted = False self._hass = hass self._pos: int = 0 self._queue: asyncio.Queue[bytes | None] = asyncio.Queue(maxsize=1) + self._write_future: Future[bytes | None] | None = None def __aiter__(self) -> Self: """Return the iterator.""" @@ -219,13 +237,28 @@ async def __anext__(self) -> bytes: return data raise StopAsyncIteration + def abort(self) -> None: + """Abort the writer.""" + self._aborted = True + if self._write_future is not None: + self._write_future.cancel() + def tell(self) -> int: """Return the current position in the iterator.""" return self._pos def write(self, s: bytes, /) -> int: """Write data to the iterator.""" - asyncio.run_coroutine_threadsafe(self._queue.put(s), self._hass.loop).result() + self._write_future = asyncio.run_coroutine_threadsafe( + self._queue.put(s), self._hass.loop + ) + if self._aborted: + self._write_future.cancel() + raise AbortCipher + try: + self._write_future.result() + except CancelledError as err: + raise AbortCipher from err self._pos += len(s) return len(s) @@ -415,7 +448,9 @@ def _encrypt_backup( class _CipherWorkerStatus: done: asyncio.Event error: Exception | None = None - thread: ThreadWithException + reader: AsyncIteratorReader + thread: threading.Thread + writer: AsyncIteratorWriter class _CipherBackupStreamer: @@ -468,11 +503,13 @@ def on_done(error: Exception | None) -> None: stream = await self._open_stream() reader = AsyncIteratorReader(self._hass, stream) writer = AsyncIteratorWriter(self._hass) - worker = ThreadWithException( + worker = threading.Thread( target=self._cipher_func, args=[reader, writer, self._password, on_done, self.size(), self._nonces], ) - worker_status = _CipherWorkerStatus(done=asyncio.Event(), thread=worker) + worker_status = _CipherWorkerStatus( + done=asyncio.Event(), reader=reader, thread=worker, writer=writer + ) self._workers.append(worker_status) worker.start() return writer @@ -480,9 +517,8 @@ def on_done(error: Exception | None) -> None: async def wait(self) -> None: """Wait for the worker threads to finish.""" for worker in self._workers: - if not worker.thread.is_alive(): - continue - worker.thread.raise_exc(AbortCipher) + worker.reader.abort() + worker.writer.abort() await asyncio.gather(*(worker.done.wait() for worker in self._workers)) diff --git a/homeassistant/components/bluesound/strings.json b/homeassistant/components/bluesound/strings.json index c85014fedc36a3..b50c01a11bf49d 100644 --- a/homeassistant/components/bluesound/strings.json +++ b/homeassistant/components/bluesound/strings.json @@ -28,7 +28,7 @@ "services": { "join": { "name": "Join", - "description": "Group player together.", + "description": "Groups players together under a single master speaker.", "fields": { "master": { "name": "Master", @@ -36,23 +36,23 @@ }, "entity_id": { "name": "Entity", - "description": "Name of entity that will coordinate the grouping. Platform dependent." + "description": "Name of entity that will group to master speaker. Platform dependent." } } }, "unjoin": { "name": "Unjoin", - "description": "Unjoin the player from a group.", + "description": "Separates a player from a group.", "fields": { "entity_id": { "name": "Entity", - "description": "Name of entity that will be unjoined from their group. Platform dependent." + "description": "Name of entity that will be separated from their group. Platform dependent." } } }, "set_sleep_timer": { "name": "Set sleep timer", - "description": "Set a Bluesound timer. It will increase timer in steps: 15, 30, 45, 60, 90, 0.", + "description": "Sets a Bluesound timer that will turn off the speaker. It will increase in steps: 15, 30, 45, 60, 90, 0.", "fields": { "entity_id": { "name": "Entity", @@ -62,7 +62,7 @@ }, "clear_sleep_timer": { "name": "Clear sleep timer", - "description": "Clear a Bluesound timer.", + "description": "Clears a Bluesound timer.", "fields": { "entity_id": { "name": "Entity", diff --git a/homeassistant/components/dwd_weather_warnings/sensor.py b/homeassistant/components/dwd_weather_warnings/sensor.py index c6aa5727b74d78..0aaf1f2a8018f9 100644 --- a/homeassistant/components/dwd_weather_warnings/sensor.py +++ b/homeassistant/components/dwd_weather_warnings/sensor.py @@ -3,7 +3,7 @@ Data is fetched from DWD: https://rcccm.dwd.de/DE/wetter/warnungen_aktuell/objekt_einbindung/objekteinbindung.html -Warnungen vor extremem Unwetter (Stufe 4) # codespell:ignore vor +Warnungen vor extremem Unwetter (Stufe 4) # codespell:ignore vor,extremem Unwetterwarnungen (Stufe 3) Warnungen vor markantem Wetter (Stufe 2) # codespell:ignore vor Wetterwarnungen (Stufe 1) diff --git a/homeassistant/components/frontier_silicon/media_player.py b/homeassistant/components/frontier_silicon/media_player.py index 8407e0a869d227..52998e03703d93 100644 --- a/homeassistant/components/frontier_silicon/media_player.py +++ b/homeassistant/components/frontier_silicon/media_player.py @@ -244,7 +244,7 @@ async def async_volume_up(self) -> None: """Send volume up command.""" volume = await self.fs_device.get_volume() volume = int(volume or 0) + 1 - await self.fs_device.set_volume(min(volume, self._max_volume)) + await self.fs_device.set_volume(min(volume, self._max_volume or 1)) async def async_volume_down(self) -> None: """Send volume down command.""" diff --git a/homeassistant/components/hassio/backup.py b/homeassistant/components/hassio/backup.py index 4aad984cc54ecc..43451e96b372ef 100644 --- a/homeassistant/components/hassio/backup.py +++ b/homeassistant/components/hassio/backup.py @@ -30,6 +30,8 @@ BackupReaderWriter, BackupReaderWriterError, CreateBackupEvent, + CreateBackupStage, + CreateBackupState, Folder, IdleEvent, IncorrectPasswordError, @@ -47,6 +49,7 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.util import dt as dt_util +from homeassistant.util.enum import try_parse_enum from .const import DOMAIN, EVENT_SUPERVISOR_EVENT from .handler import get_supervisor_client @@ -336,6 +339,7 @@ async def async_create_backup( self._async_wait_for_backup( backup, locations, + on_progress=on_progress, remove_after_upload=locations == [LOCATION_CLOUD_BACKUP], ), name="backup_manager_create_backup", @@ -349,6 +353,7 @@ async def _async_wait_for_backup( backup: supervisor_backups.NewBackup, locations: list[str | None], *, + on_progress: Callable[[CreateBackupEvent], None], remove_after_upload: bool, ) -> WrittenBackup: """Wait for a backup to complete.""" @@ -360,6 +365,14 @@ async def _async_wait_for_backup( def on_job_progress(data: Mapping[str, Any]) -> None: """Handle backup progress.""" nonlocal backup_id + if not (stage := try_parse_enum(CreateBackupStage, data.get("stage"))): + _LOGGER.debug("Unknown create stage: %s", data.get("stage")) + else: + on_progress( + CreateBackupEvent( + reason=None, stage=stage, state=CreateBackupState.IN_PROGRESS + ) + ) if data.get("done") is True: backup_id = data.get("reference") create_errors.extend(data.get("errors", [])) diff --git a/homeassistant/components/hue/v1/light.py b/homeassistant/components/hue/v1/light.py index e9669d226f0a0a..33b99a7895b4e4 100644 --- a/homeassistant/components/hue/v1/light.py +++ b/homeassistant/components/hue/v1/light.py @@ -408,7 +408,7 @@ def color_mode(self) -> str: if self._fixed_color_mode: return self._fixed_color_mode - # The light supports both hs/xy and white with adjustabe color_temperature + # The light supports both hs/xy and white with adjustable color_temperature mode = self._color_mode if mode in ("xy", "hs"): return ColorMode.HS diff --git a/homeassistant/components/isy994/sensor.py b/homeassistant/components/isy994/sensor.py index 789075e5c57a14..58ba3171bc84fa 100644 --- a/homeassistant/components/isy994/sensor.py +++ b/homeassistant/components/isy994/sensor.py @@ -73,7 +73,7 @@ "CV": SensorDeviceClass.VOLTAGE, "DEWPT": SensorDeviceClass.TEMPERATURE, "DISTANC": SensorDeviceClass.DISTANCE, - "ETO": SensorDeviceClass.PRECIPITATION_INTENSITY, + "ETO": SensorDeviceClass.PRECIPITATION_INTENSITY, # codespell:ignore eto "FATM": SensorDeviceClass.WEIGHT, "FREQ": SensorDeviceClass.FREQUENCY, "MUSCLEM": SensorDeviceClass.WEIGHT, diff --git a/homeassistant/components/mqtt/light/schema_json.py b/homeassistant/components/mqtt/light/schema_json.py index 43b0cbf77b3c98..14e21e61d48e3d 100644 --- a/homeassistant/components/mqtt/light/schema_json.py +++ b/homeassistant/components/mqtt/light/schema_json.py @@ -2,7 +2,6 @@ from __future__ import annotations -from collections.abc import Callable from contextlib import suppress import logging from typing import TYPE_CHECKING, Any, cast @@ -24,7 +23,6 @@ ATTR_XY_COLOR, DEFAULT_MAX_KELVIN, DEFAULT_MIN_KELVIN, - DOMAIN as LIGHT_DOMAIN, ENTITY_ID_FORMAT, FLASH_LONG, FLASH_SHORT, @@ -34,7 +32,6 @@ LightEntityFeature, brightness_supported, color_supported, - filter_supported_color_modes, valid_supported_color_modes, ) from homeassistant.const import ( @@ -48,15 +45,13 @@ CONF_XY, STATE_ON, ) -from homeassistant.core import async_get_hass, callback +from homeassistant.core import callback from homeassistant.helpers import config_validation as cv -from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue from homeassistant.helpers.json import json_dumps from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType, VolSchemaType from homeassistant.util import color as color_util from homeassistant.util.json import json_loads_object -from homeassistant.util.yaml import dump as yaml_dump from .. import subscription from ..config import DEFAULT_QOS, DEFAULT_RETAIN, MQTT_RW_SCHEMA @@ -68,7 +63,6 @@ CONF_QOS, CONF_RETAIN, CONF_STATE_TOPIC, - DOMAIN as MQTT_DOMAIN, ) from ..entity import MqttEntity from ..models import ReceiveMessage @@ -86,15 +80,10 @@ DOMAIN = "mqtt_json" DEFAULT_BRIGHTNESS = False -DEFAULT_COLOR_MODE = False -DEFAULT_COLOR_TEMP = False DEFAULT_EFFECT = False DEFAULT_FLASH_TIME_LONG = 10 DEFAULT_FLASH_TIME_SHORT = 2 DEFAULT_NAME = "MQTT JSON Light" -DEFAULT_RGB = False -DEFAULT_XY = False -DEFAULT_HS = False DEFAULT_BRIGHTNESS_SCALE = 255 DEFAULT_WHITE_SCALE = 255 @@ -110,89 +99,6 @@ CONF_MIN_MIREDS = "min_mireds" -def valid_color_configuration( - setup_from_yaml: bool, -) -> Callable[[dict[str, Any]], dict[str, Any]]: - """Test color_mode is not combined with deprecated config.""" - - def _valid_color_configuration(config: ConfigType) -> ConfigType: - deprecated = {CONF_COLOR_TEMP, CONF_HS, CONF_RGB, CONF_XY} - deprecated_flags_used = any(config.get(key) for key in deprecated) - if config.get(CONF_SUPPORTED_COLOR_MODES): - if deprecated_flags_used: - raise vol.Invalid( - "supported_color_modes must not " - f"be combined with any of {deprecated}" - ) - elif deprecated_flags_used: - deprecated_flags = ", ".join(key for key in deprecated if key in config) - _LOGGER.warning( - "Deprecated flags [%s] used in MQTT JSON light config " - "for handling color mode, please use `supported_color_modes` instead. " - "Got: %s. This will stop working in Home Assistant Core 2025.3", - deprecated_flags, - config, - ) - if not setup_from_yaml: - return config - issue_id = hex(hash(frozenset(config))) - yaml_config_str = yaml_dump(config) - learn_more_url = ( - "https://www.home-assistant.io/integrations/" - f"{LIGHT_DOMAIN}.mqtt/#json-schema" - ) - hass = async_get_hass() - async_create_issue( - hass, - MQTT_DOMAIN, - issue_id, - issue_domain=LIGHT_DOMAIN, - is_fixable=False, - severity=IssueSeverity.WARNING, - learn_more_url=learn_more_url, - translation_placeholders={ - "deprecated_flags": deprecated_flags, - "config": yaml_config_str, - }, - translation_key="deprecated_color_handling", - ) - - if CONF_COLOR_MODE in config: - _LOGGER.warning( - "Deprecated flag `color_mode` used in MQTT JSON light config " - ", the `color_mode` flag is not used anymore and should be removed. " - "Got: %s. This will stop working in Home Assistant Core 2025.3", - config, - ) - if not setup_from_yaml: - return config - issue_id = hex(hash(frozenset(config))) - yaml_config_str = yaml_dump(config) - learn_more_url = ( - "https://www.home-assistant.io/integrations/" - f"{LIGHT_DOMAIN}.mqtt/#json-schema" - ) - hass = async_get_hass() - async_create_issue( - hass, - MQTT_DOMAIN, - issue_id, - breaks_in_ha_version="2025.3.0", - issue_domain=LIGHT_DOMAIN, - is_fixable=False, - severity=IssueSeverity.WARNING, - learn_more_url=learn_more_url, - translation_placeholders={ - "config": yaml_config_str, - }, - translation_key="deprecated_color_mode_flag", - ) - - return config - - return _valid_color_configuration - - _PLATFORM_SCHEMA_BASE = ( MQTT_RW_SCHEMA.extend( { @@ -200,12 +106,6 @@ def _valid_color_configuration(config: ConfigType) -> ConfigType: vol.Optional( CONF_BRIGHTNESS_SCALE, default=DEFAULT_BRIGHTNESS_SCALE ): vol.All(vol.Coerce(int), vol.Range(min=1)), - # CONF_COLOR_MODE was deprecated with HA Core 2024.4 and will be - # removed with HA Core 2025.3 - vol.Optional(CONF_COLOR_MODE): cv.boolean, - # CONF_COLOR_TEMP was deprecated with HA Core 2024.4 and will be - # removed with HA Core 2025.3 - vol.Optional(CONF_COLOR_TEMP, default=DEFAULT_COLOR_TEMP): cv.boolean, vol.Optional(CONF_COLOR_TEMP_KELVIN, default=False): cv.boolean, vol.Optional(CONF_EFFECT, default=DEFAULT_EFFECT): cv.boolean, vol.Optional(CONF_EFFECT_LIST): vol.All(cv.ensure_list, [cv.string]), @@ -215,9 +115,6 @@ def _valid_color_configuration(config: ConfigType) -> ConfigType: vol.Optional( CONF_FLASH_TIME_SHORT, default=DEFAULT_FLASH_TIME_SHORT ): cv.positive_int, - # CONF_HS was deprecated with HA Core 2024.4 and will be - # removed with HA Core 2025.3 - vol.Optional(CONF_HS, default=DEFAULT_HS): cv.boolean, vol.Optional(CONF_MAX_MIREDS): cv.positive_int, vol.Optional(CONF_MIN_MIREDS): cv.positive_int, vol.Optional(CONF_MAX_KELVIN): cv.positive_int, @@ -227,9 +124,6 @@ def _valid_color_configuration(config: ConfigType) -> ConfigType: vol.Coerce(int), vol.In([0, 1, 2]) ), vol.Optional(CONF_RETAIN, default=DEFAULT_RETAIN): cv.boolean, - # CONF_RGB was deprecated with HA Core 2024.4 and will be - # removed with HA Core 2025.3 - vol.Optional(CONF_RGB, default=DEFAULT_RGB): cv.boolean, vol.Optional(CONF_STATE_TOPIC): valid_subscribe_topic, vol.Optional(CONF_SUPPORTED_COLOR_MODES): vol.All( cv.ensure_list, @@ -240,22 +134,29 @@ def _valid_color_configuration(config: ConfigType) -> ConfigType: vol.Optional(CONF_WHITE_SCALE, default=DEFAULT_WHITE_SCALE): vol.All( vol.Coerce(int), vol.Range(min=1) ), - # CONF_XY was deprecated with HA Core 2024.4 and will be - # removed with HA Core 2025.3 - vol.Optional(CONF_XY, default=DEFAULT_XY): cv.boolean, }, ) .extend(MQTT_ENTITY_COMMON_SCHEMA.schema) .extend(MQTT_LIGHT_SCHEMA_SCHEMA.schema) ) +# Support for legacy color_mode handling was removed with HA Core 2025.3 +# The removed attributes can be removed from the schema's from HA Core 2026.3 DISCOVERY_SCHEMA_JSON = vol.All( - valid_color_configuration(False), + cv.removed(CONF_COLOR_MODE, raise_if_present=False), + cv.removed(CONF_COLOR_TEMP, raise_if_present=False), + cv.removed(CONF_HS, raise_if_present=False), + cv.removed(CONF_RGB, raise_if_present=False), + cv.removed(CONF_XY, raise_if_present=False), _PLATFORM_SCHEMA_BASE.extend({}, extra=vol.REMOVE_EXTRA), ) PLATFORM_SCHEMA_MODERN_JSON = vol.All( - valid_color_configuration(True), + cv.removed(CONF_COLOR_MODE), + cv.removed(CONF_COLOR_TEMP), + cv.removed(CONF_HS), + cv.removed(CONF_RGB), + cv.removed(CONF_XY), _PLATFORM_SCHEMA_BASE, ) @@ -272,8 +173,6 @@ class MqttLightJson(MqttEntity, LightEntity, RestoreEntity): _topic: dict[str, str | None] _optimistic: bool - _deprecated_color_handling: bool = False - @staticmethod def config_schema() -> VolSchemaType: """Return the config schema.""" @@ -318,122 +217,65 @@ def _setup_from_config(self, config: ConfigType) -> None: self._attr_color_mode = next(iter(self.supported_color_modes)) else: self._attr_color_mode = ColorMode.UNKNOWN - else: - self._deprecated_color_handling = True - color_modes = {ColorMode.ONOFF} - if config[CONF_BRIGHTNESS]: - color_modes.add(ColorMode.BRIGHTNESS) - if config[CONF_COLOR_TEMP]: - color_modes.add(ColorMode.COLOR_TEMP) - if config[CONF_HS] or config[CONF_RGB] or config[CONF_XY]: - color_modes.add(ColorMode.HS) - self._attr_supported_color_modes = filter_supported_color_modes(color_modes) - if self.supported_color_modes and len(self.supported_color_modes) == 1: - self._fixed_color_mode = next(iter(self.supported_color_modes)) def _update_color(self, values: dict[str, Any]) -> None: - if self._deprecated_color_handling: - # Deprecated color handling - try: - red = int(values["color"]["r"]) - green = int(values["color"]["g"]) - blue = int(values["color"]["b"]) - self._attr_hs_color = color_util.color_RGB_to_hs(red, green, blue) - except KeyError: - pass - except ValueError: - _LOGGER.warning( - "Invalid RGB color value '%s' received for entity %s", - values, - self.entity_id, - ) - return - - try: - x_color = float(values["color"]["x"]) - y_color = float(values["color"]["y"]) - self._attr_hs_color = color_util.color_xy_to_hs(x_color, y_color) - except KeyError: - pass - except ValueError: - _LOGGER.warning( - "Invalid XY color value '%s' received for entity %s", - values, - self.entity_id, + color_mode: str = values["color_mode"] + if not self._supports_color_mode(color_mode): + _LOGGER.warning( + "Invalid color mode '%s' received for entity %s", + color_mode, + self.entity_id, + ) + return + try: + if color_mode == ColorMode.COLOR_TEMP: + self._attr_color_temp_kelvin = ( + values["color_temp"] + if self._color_temp_kelvin + else color_util.color_temperature_mired_to_kelvin( + values["color_temp"] + ) ) - return - - try: + self._attr_color_mode = ColorMode.COLOR_TEMP + elif color_mode == ColorMode.HS: hue = float(values["color"]["h"]) saturation = float(values["color"]["s"]) + self._attr_color_mode = ColorMode.HS self._attr_hs_color = (hue, saturation) - except KeyError: - pass - except ValueError: - _LOGGER.warning( - "Invalid HS color value '%s' received for entity %s", - values, - self.entity_id, - ) - return - else: - color_mode: str = values["color_mode"] - if not self._supports_color_mode(color_mode): - _LOGGER.warning( - "Invalid color mode '%s' received for entity %s", - color_mode, - self.entity_id, - ) - return - try: - if color_mode == ColorMode.COLOR_TEMP: - self._attr_color_temp_kelvin = ( - values["color_temp"] - if self._color_temp_kelvin - else color_util.color_temperature_mired_to_kelvin( - values["color_temp"] - ) - ) - self._attr_color_mode = ColorMode.COLOR_TEMP - elif color_mode == ColorMode.HS: - hue = float(values["color"]["h"]) - saturation = float(values["color"]["s"]) - self._attr_color_mode = ColorMode.HS - self._attr_hs_color = (hue, saturation) - elif color_mode == ColorMode.RGB: - r = int(values["color"]["r"]) - g = int(values["color"]["g"]) - b = int(values["color"]["b"]) - self._attr_color_mode = ColorMode.RGB - self._attr_rgb_color = (r, g, b) - elif color_mode == ColorMode.RGBW: - r = int(values["color"]["r"]) - g = int(values["color"]["g"]) - b = int(values["color"]["b"]) - w = int(values["color"]["w"]) - self._attr_color_mode = ColorMode.RGBW - self._attr_rgbw_color = (r, g, b, w) - elif color_mode == ColorMode.RGBWW: - r = int(values["color"]["r"]) - g = int(values["color"]["g"]) - b = int(values["color"]["b"]) - c = int(values["color"]["c"]) - w = int(values["color"]["w"]) - self._attr_color_mode = ColorMode.RGBWW - self._attr_rgbww_color = (r, g, b, c, w) - elif color_mode == ColorMode.WHITE: - self._attr_color_mode = ColorMode.WHITE - elif color_mode == ColorMode.XY: - x = float(values["color"]["x"]) - y = float(values["color"]["y"]) - self._attr_color_mode = ColorMode.XY - self._attr_xy_color = (x, y) - except (KeyError, ValueError): - _LOGGER.warning( - "Invalid or incomplete color value '%s' received for entity %s", - values, - self.entity_id, - ) + elif color_mode == ColorMode.RGB: + r = int(values["color"]["r"]) + g = int(values["color"]["g"]) + b = int(values["color"]["b"]) + self._attr_color_mode = ColorMode.RGB + self._attr_rgb_color = (r, g, b) + elif color_mode == ColorMode.RGBW: + r = int(values["color"]["r"]) + g = int(values["color"]["g"]) + b = int(values["color"]["b"]) + w = int(values["color"]["w"]) + self._attr_color_mode = ColorMode.RGBW + self._attr_rgbw_color = (r, g, b, w) + elif color_mode == ColorMode.RGBWW: + r = int(values["color"]["r"]) + g = int(values["color"]["g"]) + b = int(values["color"]["b"]) + c = int(values["color"]["c"]) + w = int(values["color"]["w"]) + self._attr_color_mode = ColorMode.RGBWW + self._attr_rgbww_color = (r, g, b, c, w) + elif color_mode == ColorMode.WHITE: + self._attr_color_mode = ColorMode.WHITE + elif color_mode == ColorMode.XY: + x = float(values["color"]["x"]) + y = float(values["color"]["y"]) + self._attr_color_mode = ColorMode.XY + self._attr_xy_color = (x, y) + except (KeyError, TypeError, ValueError): + _LOGGER.warning( + "Invalid or incomplete color value '%s' received for entity %s", + values, + self.entity_id, + ) @callback def _state_received(self, msg: ReceiveMessage) -> None: @@ -447,18 +289,7 @@ def _state_received(self, msg: ReceiveMessage) -> None: elif values["state"] is None: self._attr_is_on = None - if ( - self._deprecated_color_handling - and color_supported(self.supported_color_modes) - and "color" in values - ): - # Deprecated color handling - if values["color"] is None: - self._attr_hs_color = None - else: - self._update_color(values) - - if not self._deprecated_color_handling and "color_mode" in values: + if color_supported(self.supported_color_modes) and "color_mode" in values: self._update_color(values) if brightness_supported(self.supported_color_modes): @@ -484,35 +315,6 @@ def _state_received(self, msg: ReceiveMessage) -> None: self.entity_id, ) - if ( - self._deprecated_color_handling - and self.supported_color_modes - and ColorMode.COLOR_TEMP in self.supported_color_modes - ): - # Deprecated color handling - try: - if values["color_temp"] is None: - self._attr_color_temp_kelvin = None - else: - self._attr_color_temp_kelvin = ( - values["color_temp"] # type: ignore[assignment] - if self._color_temp_kelvin - else color_util.color_temperature_mired_to_kelvin( - values["color_temp"] # type: ignore[arg-type] - ) - ) - except KeyError: - pass - except (TypeError, ValueError): - _LOGGER.warning( - "Invalid color temp value '%s' received for entity %s", - values["color_temp"], - self.entity_id, - ) - # Allow to switch back to color_temp - if "color" not in values: - self._attr_hs_color = None - if self.supported_features and LightEntityFeature.EFFECT: with suppress(KeyError): self._attr_effect = cast(str, values["effect"]) @@ -565,19 +367,6 @@ async def _subscribe_topics(self) -> None: ) self._attr_xy_color = last_attributes.get(ATTR_XY_COLOR, self.xy_color) - @property - def color_mode(self) -> ColorMode | str | None: - """Return current color mode.""" - if not self._deprecated_color_handling: - return self._attr_color_mode - if self._fixed_color_mode: - # Legacy light with support for a single color mode - return self._fixed_color_mode - # Legacy light with support for ct + hs, prioritize hs - if self.hs_color is not None: - return ColorMode.HS - return ColorMode.COLOR_TEMP - def _set_flash_and_transition(self, message: dict[str, Any], **kwargs: Any) -> None: if ATTR_TRANSITION in kwargs: message["transition"] = kwargs[ATTR_TRANSITION] @@ -604,17 +393,15 @@ def _scale_rgbxx(self, rgbxx: tuple[int, ...], kwargs: Any) -> tuple[int, ...]: def _supports_color_mode(self, color_mode: ColorMode | str) -> bool: """Return True if the light natively supports a color mode.""" return ( - not self._deprecated_color_handling - and self.supported_color_modes is not None + self.supported_color_modes is not None and color_mode in self.supported_color_modes ) - async def async_turn_on(self, **kwargs: Any) -> None: # noqa: C901 + async def async_turn_on(self, **kwargs: Any) -> None: """Turn the device on. This method is a coroutine. """ - brightness: int should_update = False hs_color: tuple[float, float] message: dict[str, Any] = {"state": "ON"} @@ -623,39 +410,6 @@ async def async_turn_on(self, **kwargs: Any) -> None: # noqa: C901 rgbcw: tuple[int, ...] xy_color: tuple[float, float] - if ATTR_HS_COLOR in kwargs and ( - self._config[CONF_HS] or self._config[CONF_RGB] or self._config[CONF_XY] - ): - # Legacy color handling - hs_color = kwargs[ATTR_HS_COLOR] - message["color"] = {} - if self._config[CONF_RGB]: - # If brightness is supported, we don't want to scale the - # RGB values given using the brightness. - if self._config[CONF_BRIGHTNESS]: - brightness = 255 - else: - # We pop the brightness, to omit it from the payload - brightness = kwargs.pop(ATTR_BRIGHTNESS, 255) - rgb = color_util.color_hsv_to_RGB( - hs_color[0], hs_color[1], brightness / 255 * 100 - ) - message["color"]["r"] = rgb[0] - message["color"]["g"] = rgb[1] - message["color"]["b"] = rgb[2] - if self._config[CONF_XY]: - xy_color = color_util.color_hs_to_xy(*kwargs[ATTR_HS_COLOR]) - message["color"]["x"] = xy_color[0] - message["color"]["y"] = xy_color[1] - if self._config[CONF_HS]: - message["color"]["h"] = hs_color[0] - message["color"]["s"] = hs_color[1] - - if self._optimistic: - self._attr_color_temp_kelvin = None - self._attr_hs_color = kwargs[ATTR_HS_COLOR] - should_update = True - if ATTR_HS_COLOR in kwargs and self._supports_color_mode(ColorMode.HS): hs_color = kwargs[ATTR_HS_COLOR] message["color"] = {"h": hs_color[0], "s": hs_color[1]} diff --git a/homeassistant/components/mqtt/strings.json b/homeassistant/components/mqtt/strings.json index 3815b6adbd5c22..bf0bd594ea4997 100644 --- a/homeassistant/components/mqtt/strings.json +++ b/homeassistant/components/mqtt/strings.json @@ -1,13 +1,5 @@ { "issues": { - "deprecated_color_handling": { - "title": "Deprecated color handling used for MQTT light", - "description": "An MQTT light config (with `json` schema) found in `configuration.yaml` uses deprecated color handling flags.\n\nConfiguration found:\n```yaml\n{config}\n```\nDeprecated flags: **{deprecated_flags}**.\n\nUse the `supported_color_modes` option instead and [reload](/developer-tools/yaml) the manually configured MQTT items or restart Home Assistant to fix this issue." - }, - "deprecated_color_mode_flag": { - "title": "Deprecated color_mode option flag used for MQTT light", - "description": "An MQTT light config (with `json` schema) found in `configuration.yaml` uses a deprecated `color_mode` flag.\n\nConfiguration found:\n```yaml\n{config}\n```\n\nRemove the option from your config and [reload](/developer-tools/yaml) the manually configured MQTT items or restart Home Assistant to fix this issue." - }, "invalid_platform_config": { "title": "Invalid config found for mqtt {domain} item", "description": "Home Assistant detected an invalid config for a manually configured item.\n\nPlatform domain: **{domain}**\nConfiguration file: **{config_file}**\nNear line: **{line}**\nConfiguration found:\n```yaml\n{config}\n```\nError: **{error}**.\n\nMake sure the configuration is valid and [reload](/developer-tools/yaml) the manually configured MQTT items or restart Home Assistant to fix this issue." diff --git a/homeassistant/components/onedrive/manifest.json b/homeassistant/components/onedrive/manifest.json index 263c73a9f69cff..cd44298384a7bf 100644 --- a/homeassistant/components/onedrive/manifest.json +++ b/homeassistant/components/onedrive/manifest.json @@ -9,5 +9,5 @@ "iot_class": "cloud_polling", "loggers": ["onedrive_personal_sdk"], "quality_scale": "bronze", - "requirements": ["onedrive-personal-sdk==0.0.2"] + "requirements": ["onedrive-personal-sdk==0.0.3"] } diff --git a/homeassistant/components/overkiz/manifest.json b/homeassistant/components/overkiz/manifest.json index eda39821d5c1bc..c25accd87f356d 100644 --- a/homeassistant/components/overkiz/manifest.json +++ b/homeassistant/components/overkiz/manifest.json @@ -13,7 +13,7 @@ "integration_type": "hub", "iot_class": "local_polling", "loggers": ["boto3", "botocore", "pyhumps", "pyoverkiz", "s3transfer"], - "requirements": ["pyoverkiz==1.15.5"], + "requirements": ["pyoverkiz==1.16.0"], "zeroconf": [ { "type": "_kizbox._tcp.local.", diff --git a/homeassistant/components/rflink/light.py b/homeassistant/components/rflink/light.py index 2a5b1ccf8d7f04..af8d2c76844368 100644 --- a/homeassistant/components/rflink/light.py +++ b/homeassistant/components/rflink/light.py @@ -101,7 +101,7 @@ def entity_class_for_type(entity_type): entity_device_mapping = { # sends only 'dim' commands not compatible with on/off switches TYPE_DIMMABLE: DimmableRflinkLight, - # sends only 'on/off' commands not advices with dimmers and signal + # sends only 'on/off' commands not advised with dimmers and signal # repetition TYPE_SWITCHABLE: RflinkLight, # sends 'dim' and 'on' command to support both dimmers and on/off diff --git a/homeassistant/components/tuya/sensor.py b/homeassistant/components/tuya/sensor.py index f766c744998a8b..756564c6a0366c 100644 --- a/homeassistant/components/tuya/sensor.py +++ b/homeassistant/components/tuya/sensor.py @@ -45,7 +45,7 @@ class TuyaSensorEntityDescription(SensorEntityDescription): subkey: str | None = None -# Commonly used battery sensors, that are re-used in the sensors down below. +# Commonly used battery sensors, that are reused in the sensors down below. BATTERY_SENSORS: tuple[TuyaSensorEntityDescription, ...] = ( TuyaSensorEntityDescription( key=DPCode.BATTERY_PERCENTAGE, diff --git a/homeassistant/components/vesync/humidifier.py b/homeassistant/components/vesync/humidifier.py index 40ea015f4d8483..5afe73606735d5 100644 --- a/homeassistant/components/vesync/humidifier.py +++ b/homeassistant/components/vesync/humidifier.py @@ -157,11 +157,15 @@ def set_mode(self, mode: str) -> None: """Set the mode of the device.""" if mode not in self.available_modes: raise HomeAssistantError( - "{mode} is not one of the valid available modes: {self.available_modes}" + f"{mode} is not one of the valid available modes: {self.available_modes}" ) if not self.device.set_humidity_mode(self._get_vs_mode(mode)): raise HomeAssistantError(f"An error occurred while setting mode {mode}.") + if mode == MODE_SLEEP: + # We successfully changed the mode. Consider it a success even if display operation fails. + self.device.set_display(False) + # Changing mode while humidifier is off actually turns it on, as per the app. But # the library does not seem to update the device_status. It is also possible that # other attributes get updated. Scheduling a forced refresh to get device status. diff --git a/homeassistant/helpers/debounce.py b/homeassistant/helpers/debounce.py index 83555b56dcbe7e..c46c6806d5d029 100644 --- a/homeassistant/helpers/debounce.py +++ b/homeassistant/helpers/debounce.py @@ -146,6 +146,10 @@ def async_shutdown(self) -> None: """Cancel any scheduled call, and prevent new runs.""" self._shutdown_requested = True self.async_cancel() + # Release hard references to parent function + # https://github.com/home-assistant/core/issues/137237 + self._function = None + self._job = None @callback def async_cancel(self) -> None: diff --git a/pylint/plugins/hass_enforce_class_module.py b/pylint/plugins/hass_enforce_class_module.py index 09fe61b68c6fa4..cc7b33d9946841 100644 --- a/pylint/plugins/hass_enforce_class_module.py +++ b/pylint/plugins/hass_enforce_class_module.py @@ -140,7 +140,7 @@ def visit_classdef(self, node: nodes.ClassDef) -> None: for ancestor in top_level_ancestors: if ancestor.name in _BASE_ENTITY_MODULES and not any( - anc.name in _MODULE_CLASSES for anc in ancestors + parent.name in _MODULE_CLASSES for parent in ancestors ): self.add_message( "hass-enforce-class-module", diff --git a/requirements_all.txt b/requirements_all.txt index 35b314c671b857..a2f7671778f3cb 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1556,7 +1556,7 @@ omnilogic==0.4.5 ondilo==0.5.0 # homeassistant.components.onedrive -onedrive-personal-sdk==0.0.2 +onedrive-personal-sdk==0.0.3 # homeassistant.components.onvif onvif-zeep-async==3.2.5 @@ -2190,7 +2190,7 @@ pyotgw==2.2.2 pyotp==2.8.0 # homeassistant.components.overkiz -pyoverkiz==1.15.5 +pyoverkiz==1.16.0 # homeassistant.components.onewire pyownet==0.10.0.post1 diff --git a/requirements_test.txt b/requirements_test.txt index 6f944b07b29357..0718ce8a9a1c1e 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -19,7 +19,7 @@ pylint==3.3.4 pylint-per-file-ignores==1.4.0 pipdeptree==2.25.0 pytest-asyncio==0.25.3 -pytest-aiohttp==1.0.5 +pytest-aiohttp==1.1.0 pytest-cov==6.0.0 pytest-freezer==0.4.9 pytest-github-actions-annotate-failures==0.3.0 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index 4c01bce2fe3ce1..6b2886465ed566 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -1304,7 +1304,7 @@ omnilogic==0.4.5 ondilo==0.5.0 # homeassistant.components.onedrive -onedrive-personal-sdk==0.0.2 +onedrive-personal-sdk==0.0.3 # homeassistant.components.onvif onvif-zeep-async==3.2.5 @@ -1786,7 +1786,7 @@ pyotgw==2.2.2 pyotp==2.8.0 # homeassistant.components.overkiz -pyoverkiz==1.15.5 +pyoverkiz==1.16.0 # homeassistant.components.onewire pyownet==0.10.0.post1 diff --git a/requirements_test_pre_commit.txt b/requirements_test_pre_commit.txt index 4dd3bc4601094f..1cf3d91defac59 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 +codespell==2.4.1 ruff==0.9.1 yamllint==1.35.1 diff --git a/script/hassfest/quality_scale_validation/runtime_data.py b/script/hassfest/quality_scale_validation/runtime_data.py index cfc4c5224de01b..3562d89796732b 100644 --- a/script/hassfest/quality_scale_validation/runtime_data.py +++ b/script/hassfest/quality_scale_validation/runtime_data.py @@ -10,7 +10,7 @@ from script.hassfest import ast_parse_module from script.hassfest.model import Config, Integration -_ANNOTATION_MATCH = re.compile(r"^[A-Za-z]+ConfigEntry$") +_ANNOTATION_MATCH = re.compile(r"^[A-Za-z][A-Za-z0-9]+ConfigEntry$") _FUNCTIONS: dict[str, dict[str, int]] = { "__init__": { # based on ComponentProtocol "async_migrate_entry": 2, diff --git a/tests/components/backup/test_util.py b/tests/components/backup/test_util.py index 3bcb53f7c8657e..3b188ff8226eca 100644 --- a/tests/components/backup/test_util.py +++ b/tests/components/backup/test_util.py @@ -2,6 +2,7 @@ from __future__ import annotations +import asyncio from collections.abc import AsyncIterator import dataclasses import tarfile @@ -189,6 +190,73 @@ async def open_backup() -> AsyncIterator[bytes]: assert decrypted_output == decrypted_backup_data + expected_padding +async def test_decrypted_backup_streamer_interrupt_stuck_reader( + hass: HomeAssistant, +) -> None: + """Test the decrypted backup streamer.""" + encrypted_backup_path = get_fixture_path("test_backups/c0cb53bd.tar", DOMAIN) + backup = AgentBackup( + addons=["addon_1", "addon_2"], + backup_id="1234", + date="2024-12-02T07:23:58.261875-05:00", + database_included=False, + extra_metadata={}, + folders=[], + homeassistant_included=True, + homeassistant_version="2024.12.0.dev0", + name="test", + protected=True, + size=encrypted_backup_path.stat().st_size, + ) + + stuck = asyncio.Event() + + async def send_backup() -> AsyncIterator[bytes]: + f = encrypted_backup_path.open("rb") + while chunk := f.read(1024): + await stuck.wait() + yield chunk + + async def open_backup() -> AsyncIterator[bytes]: + return send_backup() + + decryptor = DecryptedBackupStreamer(hass, backup, open_backup, "hunter2") + await decryptor.open_stream() + await decryptor.wait() + + +async def test_decrypted_backup_streamer_interrupt_stuck_writer( + hass: HomeAssistant, +) -> None: + """Test the decrypted backup streamer.""" + encrypted_backup_path = get_fixture_path("test_backups/c0cb53bd.tar", DOMAIN) + backup = AgentBackup( + addons=["addon_1", "addon_2"], + backup_id="1234", + date="2024-12-02T07:23:58.261875-05:00", + database_included=False, + extra_metadata={}, + folders=[], + homeassistant_included=True, + homeassistant_version="2024.12.0.dev0", + name="test", + protected=True, + size=encrypted_backup_path.stat().st_size, + ) + + async def send_backup() -> AsyncIterator[bytes]: + f = encrypted_backup_path.open("rb") + while chunk := f.read(1024): + yield chunk + + async def open_backup() -> AsyncIterator[bytes]: + return send_backup() + + decryptor = DecryptedBackupStreamer(hass, backup, open_backup, "hunter2") + await decryptor.open_stream() + await decryptor.wait() + + async def test_decrypted_backup_streamer_wrong_password(hass: HomeAssistant) -> None: """Test the decrypted backup streamer with wrong password.""" encrypted_backup_path = get_fixture_path("test_backups/c0cb53bd.tar", DOMAIN) @@ -279,6 +347,77 @@ async def open_backup() -> AsyncIterator[bytes]: assert encrypted_output == encrypted_backup_data + expected_padding +async def test_encrypted_backup_streamer_interrupt_stuck_reader( + hass: HomeAssistant, +) -> None: + """Test the encrypted backup streamer.""" + decrypted_backup_path = get_fixture_path( + "test_backups/c0cb53bd.tar.decrypted", DOMAIN + ) + backup = AgentBackup( + addons=["addon_1", "addon_2"], + backup_id="1234", + date="2024-12-02T07:23:58.261875-05:00", + database_included=False, + extra_metadata={}, + folders=[], + homeassistant_included=True, + homeassistant_version="2024.12.0.dev0", + name="test", + protected=False, + size=decrypted_backup_path.stat().st_size, + ) + + stuck = asyncio.Event() + + async def send_backup() -> AsyncIterator[bytes]: + f = decrypted_backup_path.open("rb") + while chunk := f.read(1024): + await stuck.wait() + yield chunk + + async def open_backup() -> AsyncIterator[bytes]: + return send_backup() + + decryptor = EncryptedBackupStreamer(hass, backup, open_backup, "hunter2") + await decryptor.open_stream() + await decryptor.wait() + + +async def test_encrypted_backup_streamer_interrupt_stuck_writer( + hass: HomeAssistant, +) -> None: + """Test the encrypted backup streamer.""" + decrypted_backup_path = get_fixture_path( + "test_backups/c0cb53bd.tar.decrypted", DOMAIN + ) + backup = AgentBackup( + addons=["addon_1", "addon_2"], + backup_id="1234", + date="2024-12-02T07:23:58.261875-05:00", + database_included=False, + extra_metadata={}, + folders=[], + homeassistant_included=True, + homeassistant_version="2024.12.0.dev0", + name="test", + protected=True, + size=decrypted_backup_path.stat().st_size, + ) + + async def send_backup() -> AsyncIterator[bytes]: + f = decrypted_backup_path.open("rb") + while chunk := f.read(1024): + yield chunk + + async def open_backup() -> AsyncIterator[bytes]: + return send_backup() + + decryptor = EncryptedBackupStreamer(hass, backup, open_backup, "hunter2") + await decryptor.open_stream() + await decryptor.wait() + + async def test_encrypted_backup_streamer_random_nonce(hass: HomeAssistant) -> None: """Test the encrypted backup streamer.""" decrypted_backup_path = get_fixture_path( diff --git a/tests/components/bluetooth_le_tracker/test_device_tracker.py b/tests/components/bluetooth_le_tracker/test_device_tracker.py index da90980640bb8e..738cae90c227c2 100644 --- a/tests/components/bluetooth_le_tracker/test_device_tracker.py +++ b/tests/components/bluetooth_le_tracker/test_device_tracker.py @@ -215,7 +215,7 @@ async def test_see_device_if_time_updated(hass: HomeAssistant) -> None: @pytest.mark.usefixtures("mock_bluetooth", "mock_device_tracker_conf") async def test_preserve_new_tracked_device_name(hass: HomeAssistant) -> None: - """Test preserving tracked device name across new seens.""" + """Test preserving tracked device name across new seens.""" # codespell:ignore seens address = "DE:AD:BE:EF:13:37" name = "Mock device name" diff --git a/tests/components/enphase_envoy/test_config_flow.py b/tests/components/enphase_envoy/test_config_flow.py index a3da14b3835088..efbe6da9b13b2f 100644 --- a/tests/components/enphase_envoy/test_config_flow.py +++ b/tests/components/enphase_envoy/test_config_flow.py @@ -439,7 +439,7 @@ async def test_zero_conf_old_blank_entry( mock_setup_entry: AsyncMock, mock_envoy: AsyncMock, ) -> None: - """Test re-using old blank entry.""" + """Test reusing old blank entry.""" entry = MockConfigEntry( domain=DOMAIN, data={ @@ -478,7 +478,7 @@ async def test_zero_conf_old_blank_entry_standard_title( mock_setup_entry: AsyncMock, mock_envoy: AsyncMock, ) -> None: - """Test re-using old blank entry was Envoy as title.""" + """Test reusing old blank entry was Envoy as title.""" entry = MockConfigEntry( domain=DOMAIN, data={ @@ -519,7 +519,7 @@ async def test_zero_conf_old_blank_entry_user_title( mock_setup_entry: AsyncMock, mock_envoy: AsyncMock, ) -> None: - """Test re-using old blank entry with user title.""" + """Test reusing old blank entry with user title.""" entry = MockConfigEntry( domain=DOMAIN, data={ diff --git a/tests/components/hassio/test_backup.py b/tests/components/hassio/test_backup.py index ab3335e00dc6e7..023a19a223f70d 100644 --- a/tests/components/hassio/test_backup.py +++ b/tests/components/hassio/test_backup.py @@ -1002,6 +1002,113 @@ async def test_reader_writer_create( assert response["event"] == {"manager_state": "idle"} +@pytest.mark.usefixtures("hassio_client", "setup_integration") +async def test_reader_writer_create_report_progress( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + freezer: FrozenDateTimeFactory, + supervisor_client: AsyncMock, +) -> None: + """Test generating a backup.""" + client = await hass_ws_client(hass) + freezer.move_to("2025-01-30 13:42:12.345678") + supervisor_client.backups.partial_backup.return_value.job_id = TEST_JOB_ID + supervisor_client.backups.backup_info.return_value = TEST_BACKUP_DETAILS + supervisor_client.jobs.get_job.return_value = TEST_JOB_NOT_DONE + + await client.send_json_auto_id({"type": "backup/subscribe_events"}) + response = await client.receive_json() + assert response["event"] == {"manager_state": "idle"} + response = await client.receive_json() + assert response["success"] + + await client.send_json_auto_id( + {"type": "backup/generate", "agent_ids": ["hassio.local"], "name": "Test"} + ) + response = await client.receive_json() + assert response["event"] == { + "manager_state": "create_backup", + "reason": None, + "stage": None, + "state": "in_progress", + } + + response = await client.receive_json() + assert response["success"] + assert response["result"] == {"backup_job_id": TEST_JOB_ID} + + supervisor_client.backups.partial_backup.assert_called_once_with( + DEFAULT_BACKUP_OPTIONS + ) + + supervisor_event_base = {"uuid": TEST_JOB_ID, "reference": "test_slug"} + supervisor_events = [ + supervisor_event_base | {"done": False, "stage": "addon_repositories"}, + supervisor_event_base | {"done": False, "stage": None}, # Will be skipped + supervisor_event_base | {"done": False, "stage": "unknown"}, # Will be skipped + supervisor_event_base | {"done": False, "stage": "home_assistant"}, + supervisor_event_base | {"done": False, "stage": "addons"}, + supervisor_event_base | {"done": True, "stage": "finishing_file"}, + ] + expected_manager_events = [ + "addon_repositories", + "home_assistant", + "addons", + "finishing_file", + ] + + for supervisor_event in supervisor_events: + await client.send_json_auto_id( + { + "type": "supervisor/event", + "data": {"event": "job", "data": supervisor_event}, + } + ) + + acks = 0 + events = [] + for _ in range(len(supervisor_events) + len(expected_manager_events)): + response = await client.receive_json() + if "event" in response: + events.append(response) + continue + assert response["success"] + acks += 1 + + assert acks == len(supervisor_events) + assert len(events) == len(expected_manager_events) + + for i, event in enumerate(events): + assert event["event"] == { + "manager_state": "create_backup", + "reason": None, + "stage": expected_manager_events[i], + "state": "in_progress", + } + + response = await client.receive_json() + assert response["event"] == { + "manager_state": "create_backup", + "reason": None, + "stage": "upload_to_agents", + "state": "in_progress", + } + + response = await client.receive_json() + assert response["event"] == { + "manager_state": "create_backup", + "reason": None, + "stage": None, + "state": "completed", + } + + supervisor_client.backups.download_backup.assert_not_called() + supervisor_client.backups.remove_backup.assert_not_called() + + response = await client.receive_json() + assert response["event"] == {"manager_state": "idle"} + + @pytest.mark.usefixtures("hassio_client", "setup_integration") async def test_reader_writer_create_job_done( hass: HomeAssistant, diff --git a/tests/components/hue/test_light_v2.py b/tests/components/hue/test_light_v2.py index 2b978ffc33fdfc..c831d40d261447 100644 --- a/tests/components/hue/test_light_v2.py +++ b/tests/components/hue/test_light_v2.py @@ -392,7 +392,7 @@ async def test_light_availability( assert test_light is not None assert test_light.state == "on" - # Change availability by modififying the zigbee_connectivity status + # Change availability by modifying the zigbee_connectivity status for status in ("connectivity_issue", "disconnected", "connected"): mock_bridge_v2.api.emit_event( "update", diff --git a/tests/components/mqtt/test_light_json.py b/tests/components/mqtt/test_light_json.py index 512e409143834e..7ddd04a09a619c 100644 --- a/tests/components/mqtt/test_light_json.py +++ b/tests/components/mqtt/test_light_json.py @@ -100,7 +100,6 @@ STATE_UNKNOWN, ) from homeassistant.core import HomeAssistant, State -from homeassistant.helpers.json import json_dumps from homeassistant.util.json import json_loads from .test_common import ( @@ -195,172 +194,6 @@ async def test_fail_setup_if_no_command_topic( assert "required key not provided" in caplog.text -@pytest.mark.parametrize( - "hass_config", - [ - help_custom_config(light.DOMAIN, COLOR_MODES_CONFIG, ({"color_temp": True},)), - help_custom_config(light.DOMAIN, COLOR_MODES_CONFIG, ({"hs": True},)), - help_custom_config(light.DOMAIN, COLOR_MODES_CONFIG, ({"rgb": True},)), - help_custom_config(light.DOMAIN, COLOR_MODES_CONFIG, ({"xy": True},)), - ], -) -async def test_fail_setup_if_color_mode_deprecated( - mqtt_mock_entry: MqttMockHAClientGenerator, - caplog: pytest.LogCaptureFixture, -) -> None: - """Test if setup fails if color mode is combined with deprecated config keys.""" - assert await mqtt_mock_entry() - assert "supported_color_modes must not be combined with any of" in caplog.text - - -@pytest.mark.parametrize( - ("hass_config", "color_modes"), - [ - ( - help_custom_config(light.DOMAIN, DEFAULT_CONFIG, ({"color_temp": True},)), - ("color_temp",), - ), - (help_custom_config(light.DOMAIN, DEFAULT_CONFIG, ({"hs": True},)), ("hs",)), - (help_custom_config(light.DOMAIN, DEFAULT_CONFIG, ({"rgb": True},)), ("rgb",)), - (help_custom_config(light.DOMAIN, DEFAULT_CONFIG, ({"xy": True},)), ("xy",)), - ( - help_custom_config( - light.DOMAIN, DEFAULT_CONFIG, ({"color_temp": True, "rgb": True},) - ), - ("color_temp, rgb", "rgb, color_temp"), - ), - ], - ids=["color_temp", "hs", "rgb", "xy", "color_temp, rgb"], -) -async def test_warning_if_color_mode_flags_are_used( - mqtt_mock_entry: MqttMockHAClientGenerator, - caplog: pytest.LogCaptureFixture, - color_modes: tuple[str, ...], -) -> None: - """Test warnings deprecated config keys without supported color modes defined.""" - with patch( - "homeassistant.components.mqtt.light.schema_json.async_create_issue" - ) as mock_async_create_issue: - assert await mqtt_mock_entry() - assert any( - ( - f"Deprecated flags [{color_modes_case}] used in MQTT JSON light config " - "for handling color mode, please use `supported_color_modes` instead." - in caplog.text - ) - for color_modes_case in color_modes - ) - mock_async_create_issue.assert_called_once() - - -@pytest.mark.parametrize( - ("config", "color_modes"), - [ - ( - help_custom_config(light.DOMAIN, DEFAULT_CONFIG, ({"color_temp": True},)), - ("color_temp",), - ), - (help_custom_config(light.DOMAIN, DEFAULT_CONFIG, ({"hs": True},)), ("hs",)), - (help_custom_config(light.DOMAIN, DEFAULT_CONFIG, ({"rgb": True},)), ("rgb",)), - (help_custom_config(light.DOMAIN, DEFAULT_CONFIG, ({"xy": True},)), ("xy",)), - ( - help_custom_config( - light.DOMAIN, DEFAULT_CONFIG, ({"color_temp": True, "rgb": True},) - ), - ("color_temp, rgb", "rgb, color_temp"), - ), - ], - ids=["color_temp", "hs", "rgb", "xy", "color_temp, rgb"], -) -async def test_warning_on_discovery_if_color_mode_flags_are_used( - hass: HomeAssistant, - mqtt_mock_entry: MqttMockHAClientGenerator, - caplog: pytest.LogCaptureFixture, - config: dict[str, Any], - color_modes: tuple[str, ...], -) -> None: - """Test warnings deprecated config keys with discovery.""" - with patch( - "homeassistant.components.mqtt.light.schema_json.async_create_issue" - ) as mock_async_create_issue: - assert await mqtt_mock_entry() - - config_payload = json_dumps(config[mqtt.DOMAIN][light.DOMAIN][0]) - async_fire_mqtt_message( - hass, - "homeassistant/light/bla/config", - config_payload, - ) - await hass.async_block_till_done() - assert any( - ( - f"Deprecated flags [{color_modes_case}] used in MQTT JSON light config " - "for handling color mode, please " - "use `supported_color_modes` instead" in caplog.text - ) - for color_modes_case in color_modes - ) - mock_async_create_issue.assert_not_called() - - -@pytest.mark.parametrize( - "hass_config", - [ - help_custom_config( - light.DOMAIN, - DEFAULT_CONFIG, - ({"color_mode": True, "supported_color_modes": ["color_temp"]},), - ), - ], - ids=["color_temp"], -) -async def test_warning_if_color_mode_option_flag_is_used( - mqtt_mock_entry: MqttMockHAClientGenerator, - caplog: pytest.LogCaptureFixture, -) -> None: - """Test warning deprecated color_mode option flag is used.""" - with patch( - "homeassistant.components.mqtt.light.schema_json.async_create_issue" - ) as mock_async_create_issue: - assert await mqtt_mock_entry() - assert "Deprecated flag `color_mode` used in MQTT JSON light config" in caplog.text - mock_async_create_issue.assert_called_once() - - -@pytest.mark.parametrize( - "config", - [ - help_custom_config( - light.DOMAIN, - DEFAULT_CONFIG, - ({"color_mode": True, "supported_color_modes": ["color_temp"]},), - ), - ], - ids=["color_temp"], -) -async def test_warning_on_discovery_if_color_mode_option_flag_is_used( - hass: HomeAssistant, - mqtt_mock_entry: MqttMockHAClientGenerator, - caplog: pytest.LogCaptureFixture, - config: dict[str, Any], -) -> None: - """Test warning deprecated color_mode option flag is used.""" - with patch( - "homeassistant.components.mqtt.light.schema_json.async_create_issue" - ) as mock_async_create_issue: - assert await mqtt_mock_entry() - - config_payload = json_dumps(config[mqtt.DOMAIN][light.DOMAIN][0]) - async_fire_mqtt_message( - hass, - "homeassistant/light/bla/config", - config_payload, - ) - await hass.async_block_till_done() - assert "Deprecated flag `color_mode` used in MQTT JSON light config" in caplog.text - mock_async_create_issue.assert_not_called() - - @pytest.mark.parametrize( ("hass_config", "error"), [ @@ -400,82 +233,6 @@ async def test_fail_setup_if_color_modes_invalid( assert error in caplog.text -@pytest.mark.parametrize( - ("hass_config", "kelvin", "color_temp_payload_value"), - [ - ( - { - mqtt.DOMAIN: { - light.DOMAIN: { - "schema": "json", - "name": "test", - "command_topic": "test_light/set", - "state_topic": "test_light", - "color_mode": True, - "color_temp_kelvin": False, - "supported_color_modes": "color_temp", - } - } - }, - 5208, - 192, - ), - ( - { - mqtt.DOMAIN: { - light.DOMAIN: { - "schema": "json", - "name": "test", - "command_topic": "test_light/set", - "state_topic": "test_light", - "color_mode": True, - "color_temp_kelvin": True, - "supported_color_modes": "color_temp", - } - } - }, - 5208, - 5208, - ), - ], - ids=["mireds", "kelvin"], -) -async def test_single_color_mode( - hass: HomeAssistant, - mqtt_mock_entry: MqttMockHAClientGenerator, - kelvin: int, - color_temp_payload_value: int, -) -> None: - """Test setup with single color_mode.""" - await mqtt_mock_entry() - state = hass.states.get("light.test") - assert state.state == STATE_UNKNOWN - - await common.async_turn_on( - hass, "light.test", brightness=50, color_temp_kelvin=kelvin - ) - - payload = { - "state": "ON", - "brightness": 50, - "color_mode": "color_temp", - "color_temp": color_temp_payload_value, - } - async_fire_mqtt_message( - hass, - "test_light", - json_dumps(payload), - ) - color_modes = [light.ColorMode.COLOR_TEMP] - state = hass.states.get("light.test") - assert state.state == STATE_ON - - assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes - assert state.attributes.get(light.ATTR_COLOR_TEMP_KELVIN) == 5208 - assert state.attributes.get(light.ATTR_BRIGHTNESS) == 50 - assert state.attributes.get(light.ATTR_COLOR_MODE) == color_modes[0] - - @pytest.mark.parametrize("hass_config", [COLOR_MODES_CONFIG]) async def test_turn_on_with_unknown_color_mode_optimistic( hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator @@ -550,34 +307,6 @@ async def test_controlling_state_with_unknown_color_mode( assert state.attributes.get(light.ATTR_COLOR_MODE) == light.ColorMode.COLOR_TEMP -@pytest.mark.parametrize( - "hass_config", - [ - { - mqtt.DOMAIN: { - light.DOMAIN: { - "schema": "json", - "name": "test", - "command_topic": "test_light_rgb/set", - "rgb": True, - } - } - } - ], -) -async def test_legacy_rgb_light( - hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator -) -> None: - """Test legacy RGB light flags expected features and color modes.""" - await mqtt_mock_entry() - - state = hass.states.get("light.test") - color_modes = [light.ColorMode.HS] - assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes - expected_features = light.SUPPORT_FLASH | light.SUPPORT_TRANSITION - assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == expected_features - - @pytest.mark.parametrize( "hass_config", [ @@ -642,203 +371,9 @@ async def test_no_color_brightness_color_temp_if_no_topics( "name": "test", "state_topic": "test_light_rgb", "command_topic": "test_light_rgb/set", - "brightness": True, - "color_temp": True, - "effect": True, - "rgb": True, - "xy": True, - "hs": True, - "qos": "0", - } - } - } - ], -) -async def test_controlling_state_via_topic( - hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator -) -> None: - """Test the controlling of the state via topic.""" - await mqtt_mock_entry() - - state = hass.states.get("light.test") - assert state.state == STATE_UNKNOWN - color_modes = [light.ColorMode.COLOR_TEMP, light.ColorMode.HS] - assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes - expected_features = ( - light.SUPPORT_EFFECT | light.SUPPORT_FLASH | light.SUPPORT_TRANSITION - ) - assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == expected_features - assert state.attributes.get("rgb_color") is None - assert state.attributes.get("brightness") is None - assert state.attributes.get("color_temp_kelvin") is None - assert state.attributes.get("effect") is None - assert state.attributes.get("xy_color") is None - assert state.attributes.get("hs_color") is None - assert not state.attributes.get(ATTR_ASSUMED_STATE) - - # Turn on the light - async_fire_mqtt_message( - hass, - "test_light_rgb", - '{"state":"ON",' - '"color":{"r":255,"g":255,"b":255},' - '"brightness":255,' - '"color_temp":155,' - '"effect":"colorloop"}', - ) - - state = hass.states.get("light.test") - assert state.state == STATE_ON - assert state.attributes.get("rgb_color") == (255, 255, 255) - assert state.attributes.get("brightness") == 255 - assert state.attributes.get("color_temp_kelvin") is None # rgb color has priority - assert state.attributes.get("effect") == "colorloop" - assert state.attributes.get("xy_color") == (0.323, 0.329) - assert state.attributes.get("hs_color") == (0.0, 0.0) - - # Turn on the light - async_fire_mqtt_message( - hass, - "test_light_rgb", - '{"state":"ON",' - '"brightness":255,' - '"color":null,' - '"color_temp":155,' - '"effect":"colorloop"}', - ) - - state = hass.states.get("light.test") - assert state.state == STATE_ON - assert state.attributes.get("rgb_color") == ( - 255, - 253, - 249, - ) # temp converted to color - assert state.attributes.get("brightness") == 255 - assert state.attributes.get("color_temp_kelvin") == 6451 - assert state.attributes.get("effect") == "colorloop" - assert state.attributes.get("xy_color") == (0.328, 0.333) # temp converted to color - assert state.attributes.get("hs_color") == (44.098, 2.43) # temp converted to color - - # Turn the light off - async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"OFF"}') - - state = hass.states.get("light.test") - assert state.state == STATE_OFF - - async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "brightness":100}') - - light_state = hass.states.get("light.test") - - assert light_state.attributes["brightness"] == 100 - - async_fire_mqtt_message( - hass, "test_light_rgb", '{"state":"ON", "color":{"r":125,"g":125,"b":125}}' - ) - - light_state = hass.states.get("light.test") - assert light_state.attributes.get("rgb_color") == (255, 255, 255) - - async_fire_mqtt_message( - hass, "test_light_rgb", '{"state":"ON", "color":{"x":0.135,"y":0.135}}' - ) - - light_state = hass.states.get("light.test") - assert light_state.attributes.get("xy_color") == (0.141, 0.141) - - async_fire_mqtt_message( - hass, "test_light_rgb", '{"state":"ON", "color":{"h":180,"s":50}}' - ) - - light_state = hass.states.get("light.test") - assert light_state.attributes.get("hs_color") == (180.0, 50.0) - - async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "color":null}') - - light_state = hass.states.get("light.test") - assert "hs_color" in light_state.attributes # Color temp approximation - - async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "color_temp":155}') - - light_state = hass.states.get("light.test") - assert light_state.attributes.get("color_temp_kelvin") == 6451 # 155 mired - - async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "color_temp":null}') - - light_state = hass.states.get("light.test") - assert light_state.attributes.get("color_temp_kelvin") is None - - async_fire_mqtt_message( - hass, "test_light_rgb", '{"state":"ON", "effect":"colorloop"}' - ) - - light_state = hass.states.get("light.test") - assert light_state.attributes.get("effect") == "colorloop" - - async_fire_mqtt_message( - hass, - "test_light_rgb", - '{"state":"ON",' - '"color":{"r":255,"g":255,"b":255},' - '"brightness":128,' - '"color_temp":155,' - '"effect":"colorloop"}', - ) - light_state = hass.states.get("light.test") - assert light_state.state == STATE_ON - assert light_state.attributes.get("brightness") == 128 - - async_fire_mqtt_message( - hass, - "test_light_rgb", - '{"state":"OFF","brightness":0}', - ) - light_state = hass.states.get("light.test") - assert light_state.state == STATE_OFF - assert light_state.attributes.get("brightness") is None - - # Simulate the lights color temp has been changed - # while it was switched off - async_fire_mqtt_message( - hass, - "test_light_rgb", - '{"state":"OFF","color_temp":201}', - ) - light_state = hass.states.get("light.test") - assert light_state.state == STATE_OFF - # Color temp attribute is not exposed while the lamp is off - assert light_state.attributes.get("color_temp_kelvin") is None - - # test previous zero brightness received was ignored and brightness is restored - # see if the latest color_temp value received is restored - async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON"}') - light_state = hass.states.get("light.test") - assert light_state.attributes.get("brightness") == 128 - assert light_state.attributes.get("color_temp_kelvin") == 4975 # 201 mired - - # A `0` brightness value is ignored when a light is turned on - async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON","brightness":0}') - light_state = hass.states.get("light.test") - assert light_state.attributes.get("brightness") == 128 - - -@pytest.mark.parametrize( - "hass_config", - [ - { - mqtt.DOMAIN: { - light.DOMAIN: { - "schema": "json", - "name": "test", - "state_topic": "test_light_rgb", - "command_topic": "test_light_rgb/set", - "brightness": True, - "color_temp": True, "color_temp_kelvin": True, "effect": True, - "rgb": True, - "xy": True, - "hs": True, + "supported_color_modes": ["color_temp", "hs"], "qos": "0", } } @@ -856,9 +391,11 @@ async def test_controlling_state_color_temp_kelvin( color_modes = [light.ColorMode.COLOR_TEMP, light.ColorMode.HS] assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes expected_features = ( - light.SUPPORT_EFFECT | light.SUPPORT_FLASH | light.SUPPORT_TRANSITION + light.LightEntityFeature.EFFECT + | light.LightEntityFeature.FLASH + | light.LightEntityFeature.TRANSITION ) - assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == expected_features + assert state.attributes.get(ATTR_SUPPORTED_FEATURES) is expected_features assert state.attributes.get("rgb_color") is None assert state.attributes.get("brightness") is None assert state.attributes.get("color_temp_kelvin") is None @@ -872,7 +409,8 @@ async def test_controlling_state_color_temp_kelvin( hass, "test_light_rgb", '{"state":"ON",' - '"color":{"r":255,"g":255,"b":255},' + '"color":{"h": 44.098, "s": 2.43},' + '"color_mode": "hs",' '"brightness":255,' '"color_temp":155,' '"effect":"colorloop"}', @@ -880,12 +418,12 @@ async def test_controlling_state_color_temp_kelvin( state = hass.states.get("light.test") assert state.state == STATE_ON - assert state.attributes.get("rgb_color") == (255, 255, 255) + assert state.attributes.get("rgb_color") == (255, 253, 249) assert state.attributes.get("brightness") == 255 assert state.attributes.get("color_temp_kelvin") is None # rgb color has priority assert state.attributes.get("effect") == "colorloop" - assert state.attributes.get("xy_color") == (0.323, 0.329) - assert state.attributes.get("hs_color") == (0.0, 0.0) + assert state.attributes.get("xy_color") == (0.328, 0.333) + assert state.attributes.get("hs_color") == (44.098, 2.43) # Turn on the light async_fire_mqtt_message( @@ -894,6 +432,7 @@ async def test_controlling_state_color_temp_kelvin( '{"state":"ON",' '"brightness":255,' '"color":null,' + '"color_mode":"color_temp",' '"color_temp":6451,' # Kelvin '"effect":"colorloop"}', ) @@ -920,7 +459,7 @@ async def test_controlling_state_color_temp_kelvin( ) ], ) -async def test_controlling_state_via_topic2( +async def test_controlling_state_via_topic( hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator, caplog: pytest.LogCaptureFixture, @@ -981,6 +520,11 @@ async def test_controlling_state_via_topic2( state = hass.states.get("light.test") assert state.attributes["brightness"] == 100 + # Zero brightness value is ignored + async_fire_mqtt_message(hass, "test_light_rgb", '{"state":"ON", "brightness":0}') + state = hass.states.get("light.test") + assert state.attributes["brightness"] == 100 + # RGB color async_fire_mqtt_message( hass, @@ -1083,242 +627,6 @@ async def test_controlling_state_via_topic2( { mqtt.DOMAIN: { light.DOMAIN: { - "schema": "json", - "name": "test", - "command_topic": "test_light_rgb/set", - "state_topic": "test_light_rgb/set", - "rgb": True, - "color_temp": True, - "brightness": True, - } - } - } - ], -) -async def test_controlling_the_state_with_legacy_color_handling( - hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator -) -> None: - """Test state updates for lights with a legacy color handling.""" - supported_color_modes = ["color_temp", "hs"] - await mqtt_mock_entry() - - state = hass.states.get("light.test") - assert state.state == STATE_UNKNOWN - expected_features = light.SUPPORT_FLASH | light.SUPPORT_TRANSITION - assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == expected_features - assert state.attributes.get("brightness") is None - assert state.attributes.get("color_mode") is None - assert state.attributes.get("color_temp_kelvin") is None - assert state.attributes.get("effect") is None - assert state.attributes.get("hs_color") is None - assert state.attributes.get("rgb_color") is None - assert state.attributes.get("rgbw_color") is None - assert state.attributes.get("rgbww_color") is None - assert state.attributes.get("supported_color_modes") == supported_color_modes - assert state.attributes.get("xy_color") is None - assert not state.attributes.get(ATTR_ASSUMED_STATE) - - for _ in range(2): - # Returned state after the light was turned on - # Receiving legacy color mode: rgb. - async_fire_mqtt_message( - hass, - "test_light_rgb/set", - '{ "state": "ON", "brightness": 255, "level": 100, "hue": 16,' - '"saturation": 100, "color": { "r": 255, "g": 67, "b": 0 }, ' - '"bulb_mode": "color", "color_mode": "rgb" }', - ) - - state = hass.states.get("light.test") - assert state.state == STATE_ON - assert state.attributes.get("brightness") == 255 - assert state.attributes.get("color_mode") == "hs" - assert state.attributes.get("color_temp_kelvin") is None - assert state.attributes.get("effect") is None - assert state.attributes.get("hs_color") == (15.765, 100.0) - assert state.attributes.get("rgb_color") == (255, 67, 0) - assert state.attributes.get("rgbw_color") is None - assert state.attributes.get("rgbww_color") is None - assert state.attributes.get("xy_color") == (0.674, 0.322) - - # Returned state after the lights color mode was changed - # Receiving legacy color mode: color_temp - async_fire_mqtt_message( - hass, - "test_light_rgb/set", - '{ "state": "ON", "brightness": 255, "level": 100, ' - '"kelvin": 92, "color_temp": 353, "bulb_mode": "white", ' - '"color_mode": "color_temp" }', - ) - - state = hass.states.get("light.test") - assert state.state == STATE_ON - assert state.attributes.get("brightness") == 255 - assert state.attributes.get("color_mode") == "color_temp" - assert state.attributes.get("color_temp_kelvin") == 2832 - assert state.attributes.get("effect") is None - assert state.attributes.get("hs_color") == (28.125, 61.661) - assert state.attributes.get("rgb_color") == (255, 171, 98) - assert state.attributes.get("rgbw_color") is None - assert state.attributes.get("rgbww_color") is None - assert state.attributes.get("xy_color") == (0.512, 0.385) - - -@pytest.mark.parametrize( - "hass_config", - [ - { - mqtt.DOMAIN: { - light.DOMAIN: { - "schema": "json", - "name": "test", - "command_topic": "test_light_rgb/set", - "brightness": True, - "color_temp": True, - "effect": True, - "hs": True, - "rgb": True, - "xy": True, - "qos": 2, - } - } - } - ], -) -async def test_sending_mqtt_commands_and_optimistic( - hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator -) -> None: - """Test the sending of command in optimistic mode.""" - fake_state = State( - "light.test", - "on", - { - "brightness": 95, - "hs_color": [100, 100], - "effect": "random", - "color_temp_kelvin": 10000, - }, - ) - mock_restore_cache(hass, (fake_state,)) - - mqtt_mock = await mqtt_mock_entry() - - state = hass.states.get("light.test") - assert state.state == STATE_ON - assert state.attributes.get("brightness") == 95 - assert state.attributes.get("hs_color") == (100, 100) - assert state.attributes.get("effect") == "random" - assert state.attributes.get("color_temp_kelvin") is None # hs_color has priority - color_modes = [light.ColorMode.COLOR_TEMP, light.ColorMode.HS] - assert state.attributes.get(light.ATTR_SUPPORTED_COLOR_MODES) == color_modes - expected_features = ( - light.SUPPORT_EFFECT | light.SUPPORT_FLASH | light.SUPPORT_TRANSITION - ) - assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == expected_features - assert state.attributes.get(ATTR_ASSUMED_STATE) - - await common.async_turn_on(hass, "light.test") - - mqtt_mock.async_publish.assert_called_once_with( - "test_light_rgb/set", '{"state":"ON"}', 2, False - ) - mqtt_mock.async_publish.reset_mock() - state = hass.states.get("light.test") - assert state.state == STATE_ON - - await common.async_turn_on(hass, "light.test", color_temp_kelvin=11111) - - mqtt_mock.async_publish.assert_called_once_with( - "test_light_rgb/set", - JsonValidator('{"state": "ON", "color_temp": 90}'), - 2, - False, - ) - mqtt_mock.async_publish.reset_mock() - state = hass.states.get("light.test") - assert state.state == STATE_ON - assert state.attributes.get("color_mode") == light.ColorMode.COLOR_TEMP - assert state.attributes.get("color_temp_kelvin") == 11111 - - await common.async_turn_off(hass, "light.test") - - mqtt_mock.async_publish.assert_called_once_with( - "test_light_rgb/set", '{"state":"OFF"}', 2, False - ) - mqtt_mock.async_publish.reset_mock() - state = hass.states.get("light.test") - assert state.state == STATE_OFF - - mqtt_mock.reset_mock() - await common.async_turn_on( - hass, "light.test", brightness=50, xy_color=(0.123, 0.123) - ) - mqtt_mock.async_publish.assert_called_once_with( - "test_light_rgb/set", - JsonValidator( - '{"state": "ON", "color": {"r": 0, "g": 124, "b": 255,' - ' "x": 0.14, "y": 0.133, "h": 210.824, "s": 100.0},' - ' "brightness": 50}' - ), - 2, - False, - ) - mqtt_mock.async_publish.reset_mock() - state = hass.states.get("light.test") - assert state.attributes.get("color_mode") == light.ColorMode.HS - assert state.attributes["brightness"] == 50 - assert state.attributes["hs_color"] == (210.824, 100.0) - assert state.attributes["rgb_color"] == (0, 124, 255) - assert state.attributes["xy_color"] == (0.14, 0.133) - - await common.async_turn_on(hass, "light.test", brightness=50, hs_color=(359, 78)) - mqtt_mock.async_publish.assert_called_once_with( - "test_light_rgb/set", - JsonValidator( - '{"state": "ON", "color": {"r": 255, "g": 56, "b": 59,' - ' "x": 0.654, "y": 0.301, "h": 359.0, "s": 78.0},' - ' "brightness": 50}' - ), - 2, - False, - ) - mqtt_mock.async_publish.reset_mock() - state = hass.states.get("light.test") - assert state.state == STATE_ON - assert state.attributes.get("color_mode") == light.ColorMode.HS - assert state.attributes["brightness"] == 50 - assert state.attributes["hs_color"] == (359.0, 78.0) - assert state.attributes["rgb_color"] == (255, 56, 59) - assert state.attributes["xy_color"] == (0.654, 0.301) - - await common.async_turn_on(hass, "light.test", rgb_color=(255, 128, 0)) - mqtt_mock.async_publish.assert_called_once_with( - "test_light_rgb/set", - JsonValidator( - '{"state": "ON", "color": {"r": 255, "g": 128, "b": 0,' - ' "x": 0.611, "y": 0.375, "h": 30.118, "s": 100.0}}' - ), - 2, - False, - ) - mqtt_mock.async_publish.reset_mock() - state = hass.states.get("light.test") - assert state.state == STATE_ON - assert state.attributes.get("color_mode") == light.ColorMode.HS - assert state.attributes["brightness"] == 50 - assert state.attributes["hs_color"] == (30.118, 100) - assert state.attributes["rgb_color"] == (255, 128, 0) - assert state.attributes["xy_color"] == (0.611, 0.375) - - -@pytest.mark.parametrize( - "hass_config", - [ - { - mqtt.DOMAIN: { - light.DOMAIN: { - "brightness": True, - "color_mode": True, "command_topic": "test_light_rgb/set", "effect": True, "name": "test", @@ -1338,7 +646,7 @@ async def test_sending_mqtt_commands_and_optimistic( } ], ) -async def test_sending_mqtt_commands_and_optimistic2( +async def test_sending_mqtt_commands_and_optimistic( hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator ) -> None: """Test the sending of command in optimistic mode for a light supporting color mode.""" @@ -1560,8 +868,7 @@ async def test_sending_mqtt_commands_and_optimistic2( "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", - "brightness": True, - "hs": True, + "supported_color_modes": ["hs"], } } } @@ -1623,7 +930,7 @@ async def test_sending_hs_color( "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", - "rgb": True, + "supported_color_modes": ["rgb"], } } } @@ -1678,7 +985,6 @@ async def test_sending_rgb_color_no_brightness( { mqtt.DOMAIN: { light.DOMAIN: { - "color_mode": True, "command_topic": "test_light_rgb/set", "name": "test", "schema": "json", @@ -1761,8 +1067,8 @@ async def test_sending_rgb_color_no_brightness2( "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", + "supported_color_modes": ["rgb"], "brightness": True, - "rgb": True, } } } @@ -1829,9 +1135,9 @@ async def test_sending_rgb_color_with_brightness( "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", + "supported_color_modes": ["rgb"], "brightness": True, "brightness_scale": 100, - "rgb": True, } } } @@ -1899,9 +1205,7 @@ async def test_sending_rgb_color_with_scaled_brightness( "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", - "brightness": True, "brightness_scale": 100, - "color_mode": True, "supported_color_modes": ["hs", "white"], "white_scale": 50, } @@ -1946,8 +1250,7 @@ async def test_sending_scaled_white( "schema": "json", "name": "test", "command_topic": "test_light_rgb/set", - "brightness": True, - "xy": True, + "supported_color_modes": ["xy"], } } } @@ -1973,7 +1276,7 @@ async def test_sending_xy_color( call( "test_light_rgb/set", JsonValidator( - '{"state": "ON", "color": {"x": 0.14, "y": 0.133},' + '{"state": "ON", "color": {"x": 0.123, "y": 0.123},' ' "brightness": 50}' ), 0, @@ -2190,7 +1493,7 @@ async def test_transition( "name": "test", "state_topic": "test_light_bright_scale", "command_topic": "test_light_bright_scale/set", - "brightness": True, + "supported_color_modes": ["brightness"], "brightness_scale": 99, } } @@ -2255,7 +1558,6 @@ async def test_brightness_scale( "command_topic": "test_light_bright_scale/set", "brightness": True, "brightness_scale": 99, - "color_mode": True, "supported_color_modes": ["hs", "white"], "white_scale": 50, } @@ -2315,8 +1617,7 @@ async def test_white_scale( "state_topic": "test_light_rgb", "command_topic": "test_light_rgb/set", "brightness": True, - "color_temp": True, - "rgb": True, + "supported_color_modes": ["hs", "color_temp"], "qos": "0", } } @@ -2349,62 +1650,64 @@ async def test_invalid_values( '{"state":"ON",' '"color":{"r":255,"g":255,"b":255},' '"brightness": 255,' + '"color_mode": "color_temp",' '"color_temp": 100,' '"effect": "rainbow"}', ) state = hass.states.get("light.test") assert state.state == STATE_ON - assert state.attributes.get("rgb_color") == (255, 255, 255) + # Color converttrd from color_temp to rgb + assert state.attributes.get("rgb_color") == (202, 218, 255) assert state.attributes.get("brightness") == 255 - assert state.attributes.get("color_temp_kelvin") is None + assert state.attributes.get("color_temp_kelvin") == 10000 # Empty color value async_fire_mqtt_message( hass, "test_light_rgb", - '{"state":"ON", "color":{}}', + '{"state":"ON", "color":{}, "color_mode": "rgb"}', ) # Color should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON - assert state.attributes.get("rgb_color") == (255, 255, 255) + assert state.attributes.get("rgb_color") == (202, 218, 255) # Bad HS color values async_fire_mqtt_message( hass, "test_light_rgb", - '{"state":"ON", "color":{"h":"bad","s":"val"}}', + '{"state":"ON", "color":{"h":"bad","s":"val"}, "color_mode": "hs"}', ) # Color should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON - assert state.attributes.get("rgb_color") == (255, 255, 255) + assert state.attributes.get("rgb_color") == (202, 218, 255) # Bad RGB color values async_fire_mqtt_message( hass, "test_light_rgb", - '{"state":"ON", "color":{"r":"bad","g":"val","b":"test"}}', + '{"state":"ON", "color":{"r":"bad","g":"val","b":"test"}, "color_mode": "rgb"}', ) # Color should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON - assert state.attributes.get("rgb_color") == (255, 255, 255) + assert state.attributes.get("rgb_color") == (202, 218, 255) # Bad XY color values async_fire_mqtt_message( hass, "test_light_rgb", - '{"state":"ON", "color":{"x":"bad","y":"val"}}', + '{"state":"ON", "color":{"x":"bad","y":"val"}, "color_mode": "xy"}', ) # Color should not have changed state = hass.states.get("light.test") assert state.state == STATE_ON - assert state.attributes.get("rgb_color") == (255, 255, 255) + assert state.attributes.get("rgb_color") == (202, 218, 255) # Bad brightness values async_fire_mqtt_message( @@ -2418,7 +1721,9 @@ async def test_invalid_values( # Unset color and set a valid color temperature async_fire_mqtt_message( - hass, "test_light_rgb", '{"state":"ON", "color": null, "color_temp": 100}' + hass, + "test_light_rgb", + '{"state":"ON", "color": null, "color_temp": 100, "color_mode": "color_temp"}', ) state = hass.states.get("light.test") assert state.state == STATE_ON @@ -2426,11 +1731,14 @@ async def test_invalid_values( # Bad color temperature async_fire_mqtt_message( - hass, "test_light_rgb", '{"state":"ON", "color_temp": "badValue"}' + hass, + "test_light_rgb", + '{"state":"ON", "color_temp": "badValue", "color_mode": "color_temp"}', ) assert ( - "Invalid color temp value 'badValue' received for entity light.test" - in caplog.text + "Invalid or incomplete color value '{'state': 'ON', 'color_temp': " + "'badValue', 'color_mode': 'color_temp'}' " + "received for entity light.test" in caplog.text ) # Color temperature should not have changed @@ -2927,7 +2235,6 @@ async def test_setup_manual_entity_from_yaml( DEFAULT_CONFIG, ( { - "color_mode": True, "effect": True, "supported_color_modes": [ "color_temp", diff --git a/tests/components/mqtt/test_util.py b/tests/components/mqtt/test_util.py index df91764b0fb2c3..f751096bca2d8c 100644 --- a/tests/components/mqtt/test_util.py +++ b/tests/components/mqtt/test_util.py @@ -52,7 +52,7 @@ async def test_canceling_debouncer_on_shutdown( assert not mock_debouncer.is_set() mqtt_client_mock.subscribe.assert_not_called() - # Note thet the broker connection will not be disconnected gracefully + # Note that the broker connection will not be disconnected gracefully await hass.async_block_till_done() async_fire_time_changed(hass, utcnow() + timedelta(seconds=5)) await asyncio.sleep(0) diff --git a/tests/components/unifiprotect/test_camera.py b/tests/components/unifiprotect/test_camera.py index 12b92beedd016a..975e93edf097b8 100644 --- a/tests/components/unifiprotect/test_camera.py +++ b/tests/components/unifiprotect/test_camera.py @@ -174,7 +174,7 @@ def validate_common_camera_state( entity_id: str, features: int = CameraEntityFeature.STREAM, ): - """Validate state that is common to all camera entity, regradless of type.""" + """Validate state that is common to all camera entity, regardless of type.""" entity_state = hass.states.get(entity_id) assert entity_state assert entity_state.attributes[ATTR_ATTRIBUTION] == DEFAULT_ATTRIBUTION diff --git a/tests/components/vesync/test_humidifier.py b/tests/components/vesync/test_humidifier.py index b93c97baab635e..d5057c449513eb 100644 --- a/tests/components/vesync/test_humidifier.py +++ b/tests/components/vesync/test_humidifier.py @@ -10,9 +10,16 @@ ATTR_HUMIDITY, ATTR_MODE, DOMAIN as HUMIDIFIER_DOMAIN, + MODE_AUTO, + MODE_SLEEP, SERVICE_SET_HUMIDITY, SERVICE_SET_MODE, ) +from homeassistant.components.vesync.const import ( + VS_HUMIDIFIER_MODE_AUTO, + VS_HUMIDIFIER_MODE_MANUAL, + VS_HUMIDIFIER_MODE_SLEEP, +) from homeassistant.config_entries import ConfigEntry, ConfigEntryState from homeassistant.const import ( ATTR_ENTITY_ID, @@ -222,7 +229,7 @@ async def test_set_mode( await hass.services.async_call( HUMIDIFIER_DOMAIN, SERVICE_SET_MODE, - {ATTR_ENTITY_ID: ENTITY_HUMIDIFIER, ATTR_MODE: "auto"}, + {ATTR_ENTITY_ID: ENTITY_HUMIDIFIER, ATTR_MODE: MODE_AUTO}, blocking=True, ) await hass.async_block_till_done() @@ -285,3 +292,38 @@ async def test_valid_mist_modes( await hass.async_block_till_done() assert "Unknown mode 'auto'" not in caplog.text assert "Unknown mode 'manual'" not in caplog.text + + +async def test_set_mode_sleep_turns_display_off( + hass: HomeAssistant, + config_entry: ConfigEntry, + humidifier, + manager, +) -> None: + """Test update of display for sleep mode.""" + + # First define valid mist modes + humidifier.mist_modes = [ + VS_HUMIDIFIER_MODE_AUTO, + VS_HUMIDIFIER_MODE_MANUAL, + VS_HUMIDIFIER_MODE_SLEEP, + ] + + with patch( + "homeassistant.components.vesync.async_generate_device_list", + return_value=[humidifier], + ): + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + with ( + patch.object(humidifier, "set_humidity_mode", return_value=True), + patch.object(humidifier, "set_display") as display_mock, + ): + await hass.services.async_call( + HUMIDIFIER_DOMAIN, + SERVICE_SET_MODE, + {ATTR_ENTITY_ID: ENTITY_HUMIDIFIER, ATTR_MODE: MODE_SLEEP}, + blocking=True, + ) + display_mock.assert_called_once_with(False) diff --git a/tests/helpers/test_debounce.py b/tests/helpers/test_debounce.py index 6fa758aec6eb84..b2dd8943e78387 100644 --- a/tests/helpers/test_debounce.py +++ b/tests/helpers/test_debounce.py @@ -4,6 +4,7 @@ from datetime import timedelta import logging from unittest.mock import AsyncMock, Mock +import weakref import pytest @@ -529,3 +530,37 @@ async def _func() -> None: async_fire_time_changed(hass, utcnow() + timedelta(seconds=1)) await hass.async_block_till_done(wait_background_tasks=False) assert len(calls) == 2 + + +async def test_shutdown_releases_parent_class(hass: HomeAssistant) -> None: + """Test shutdown releases parent class. + + See https://github.com/home-assistant/core/issues/137237 + """ + calls = [] + + class SomeClass: + def run_func(self) -> None: + calls.append(None) + + my_class = SomeClass() + my_class_weak_ref = weakref.ref(my_class) + + debouncer = debounce.Debouncer( + hass, + _LOGGER, + cooldown=0.01, + immediate=True, + function=my_class.run_func, + ) + + # Debouncer keeps a reference to the function, prevening GC + del my_class + await debouncer.async_call() + await hass.async_block_till_done() + assert len(calls) == 1 + assert my_class_weak_ref() is not None + + # Debouncer shutdown releases the class + debouncer.async_shutdown() + assert my_class_weak_ref() is None diff --git a/tests/util/test_async.py b/tests/util/test_async.py index cfa78228f0c9e6..e2310e6acd5b2c 100644 --- a/tests/util/test_async.py +++ b/tests/util/test_async.py @@ -134,8 +134,10 @@ async def _eager_task(): async def test_create_eager_task_from_thread(hass: HomeAssistant) -> None: """Test we report trying to create an eager task from a thread.""" + coro = asyncio.sleep(0) + def create_task(): - hasync.create_eager_task(asyncio.sleep(0)) + hasync.create_eager_task(coro) with pytest.raises( RuntimeError, @@ -145,14 +147,19 @@ def create_task(): ): await hass.async_add_executor_job(create_task) + # Avoid `RuntimeWarning: coroutine 'sleep' was never awaited` + await coro + async def test_create_eager_task_from_thread_in_integration( hass: HomeAssistant, caplog: pytest.LogCaptureFixture ) -> None: """Test we report trying to create an eager task from a thread.""" + coro = asyncio.sleep(0) + def create_task(): - hasync.create_eager_task(asyncio.sleep(0)) + hasync.create_eager_task(coro) frames = extract_stack_to_frame( [ @@ -200,6 +207,9 @@ def create_task(): "self.light.is_on" ) in caplog.text + # Avoid `RuntimeWarning: coroutine 'sleep' was never awaited` + await coro + async def test_get_scheduled_timer_handles(hass: HomeAssistant) -> None: """Test get_scheduled_timer_handles returns all scheduled timer handles."""