sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
home-assistant/core:homeassistant/components/teltonika/config_flow.py
"""Config flow for the Teltonika integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from teltasync import Teltasync, TeltonikaAuthenticationError, TeltonikaConnectionError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_VERIFY_SSL from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo from .const import DOMAIN from .util import get_url_variants _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): str, vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, vol.Optional(CONF_VERIFY_SSL, default=False): bool, } ) class CannotConnect(HomeAssistantError): """Error to indicate we cannot connect.""" class InvalidAuth(HomeAssistantError): """Error to indicate there is invalid auth.""" async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]: """Validate the user input allows us to connect. Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user. """ session = async_get_clientsession(hass) host = data[CONF_HOST] last_error: Exception | None = None for base_url in get_url_variants(host): client = Teltasync( base_url=f"{base_url}/api", username=data[CONF_USERNAME], password=data[CONF_PASSWORD], session=session, verify_ssl=data.get(CONF_VERIFY_SSL, True), ) try: device_info = await client.get_device_info() auth_valid = await client.validate_credentials() except TeltonikaConnectionError as err: _LOGGER.debug( "Failed to connect to Teltonika device at %s: %s", base_url, err ) last_error = err continue except TeltonikaAuthenticationError as err: _LOGGER.error("Authentication failed: %s", err) raise InvalidAuth from err finally: await client.close() if not auth_valid: raise InvalidAuth return { "title": device_info.device_name, "device_id": device_info.device_identifier, "host": base_url, } _LOGGER.error("Cannot connect to device after trying all schemas") raise CannotConnect from last_error class TeltonikaConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Teltonika.""" VERSION = 1 MINOR_VERSION = 1 _discovered_host: str | None = None async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: try: info = await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: # Set unique ID to prevent duplicates await self.async_set_unique_id(info["device_id"]) self._abort_if_unique_id_configured() data_to_store = dict(user_input) if "host" in info: data_to_store[CONF_HOST] = info["host"] return self.async_create_entry( title=info["title"], data=data_to_store, ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle reauth when authentication fails.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reauth confirmation.""" errors: dict[str, str] = {} reauth_entry = self._get_reauth_entry() if user_input is not None: data = { CONF_HOST: reauth_entry.data[CONF_HOST], CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], CONF_VERIFY_SSL: reauth_entry.data.get(CONF_VERIFY_SSL, False), } try: # Validate new credentials against the configured host info = await validate_input(self.hass, data) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception during reauth") errors["base"] = "unknown" else: # Verify reauth is for the same device await self.async_set_unique_id(info["device_id"]) self._abort_if_unique_id_mismatch(reason="wrong_account") return self.async_update_reload_and_abort( reauth_entry, data_updates=user_input, ) reauth_schema = vol.Schema( { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, } ) suggested = {**reauth_entry.data, **(user_input or {})} return self.async_show_form( step_id="reauth_confirm", data_schema=self.add_suggested_values_to_schema(reauth_schema, suggested), errors=errors, description_placeholders={ "name": reauth_entry.title, "host": reauth_entry.data[CONF_HOST], }, ) async def async_step_dhcp( self, discovery_info: DhcpServiceInfo ) -> ConfigFlowResult: """Handle DHCP discovery.""" host = discovery_info.ip # Store discovered host for later use self._discovered_host = host # Try to get device info without authentication to get device identifier and name session = async_get_clientsession(self.hass) for base_url in get_url_variants(host): client = Teltasync( base_url=f"{base_url}/api", username="", # No credentials yet password="", session=session, verify_ssl=False, # Teltonika devices use self-signed certs by default ) try: # Get device info from unauthorized endpoint device_info = await client.get_device_info() device_name = device_info.device_name device_id = device_info.device_identifier break except TeltonikaConnectionError: # Connection failed, try next URL variant continue finally: await client.close() else: # No URL variant worked, device not reachable, don't autodiscover return self.async_abort(reason="cannot_connect") # Set unique ID and check for existing conf await self.async_set_unique_id(device_id) self._abort_if_unique_id_configured(updates={CONF_HOST: host}) # Store discovery info for the user step self.context["title_placeholders"] = { "name": device_name, "host": host, } # Proceed to confirmation step to get credentials return await self.async_step_dhcp_confirm() async def async_step_dhcp_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm DHCP discovery and get credentials.""" errors: dict[str, str] = {} if user_input is not None: # Get the host from the discovery host = getattr(self, "_discovered_host", "") try: # Validate credentials with discovered host data = { CONF_HOST: host, CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], CONF_VERIFY_SSL: False, } info = await validate_input(self.hass, data) # Update unique ID to device identifier if we didn't get it during discovery await self.async_set_unique_id( info["device_id"], raise_on_progress=False ) self._abort_if_unique_id_configured() return self.async_create_entry( title=info["title"], data={ CONF_HOST: info["host"], CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], CONF_VERIFY_SSL: False, }, ) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception during DHCP confirm") errors["base"] = "unknown" return self.async_show_form( step_id="dhcp_confirm", data_schema=vol.Schema( { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, } ), errors=errors, description_placeholders=self.context.get("title_placeholders", {}), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/teltonika/config_flow.py", "license": "Apache License 2.0", "lines": 242, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/teltonika/coordinator.py
"""DataUpdateCoordinator for Teltonika.""" from __future__ import annotations from datetime import timedelta import logging from typing import TYPE_CHECKING, Any from aiohttp import ClientResponseError, ContentTypeError from teltasync import Teltasync, TeltonikaAuthenticationError, TeltonikaConnectionError from teltasync.error_codes import TeltonikaErrorCode from teltasync.modems import Modems from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN if TYPE_CHECKING: from . import TeltonikaConfigEntry _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(seconds=30) AUTH_ERROR_CODES = frozenset( { TeltonikaErrorCode.UNAUTHORIZED_ACCESS, TeltonikaErrorCode.LOGIN_FAILED, TeltonikaErrorCode.INVALID_JWT_TOKEN, } ) class TeltonikaDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): """Class to manage fetching Teltonika data.""" device_info: DeviceInfo def __init__( self, hass: HomeAssistant, client: Teltasync, config_entry: TeltonikaConfigEntry, base_url: str, ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, name="Teltonika", update_interval=SCAN_INTERVAL, config_entry=config_entry, ) self.client = client self.base_url = base_url async def _async_setup(self) -> None: """Set up the coordinator - authenticate and fetch device info.""" try: await self.client.get_device_info() system_info_response = await self.client.get_system_info() except TeltonikaAuthenticationError as err: raise ConfigEntryAuthFailed(f"Authentication failed: {err}") from err except (ClientResponseError, ContentTypeError) as err: if (isinstance(err, ClientResponseError) and err.status in (401, 403)) or ( isinstance(err, ContentTypeError) and err.status == 403 ): raise ConfigEntryAuthFailed(f"Authentication failed: {err}") from err raise ConfigEntryNotReady(f"Failed to connect to device: {err}") from err except TeltonikaConnectionError as err: raise ConfigEntryNotReady(f"Failed to connect to device: {err}") from err # Store device info for use by entities self.device_info = DeviceInfo( identifiers={(DOMAIN, system_info_response.mnf_info.serial)}, name=system_info_response.static.device_name, manufacturer="Teltonika", model=system_info_response.static.model, sw_version=system_info_response.static.fw_version, serial_number=system_info_response.mnf_info.serial, configuration_url=self.base_url, ) async def _async_update_data(self) -> dict[str, Any]: """Fetch data from Teltonika device.""" modems = Modems(self.client.auth) try: # Get modems data using the teltasync library modems_response = await modems.get_status() except TeltonikaAuthenticationError as err: raise ConfigEntryAuthFailed(f"Authentication failed: {err}") from err except (ClientResponseError, ContentTypeError) as err: if (isinstance(err, ClientResponseError) and err.status in (401, 403)) or ( isinstance(err, ContentTypeError) and err.status == 403 ): raise ConfigEntryAuthFailed(f"Authentication failed: {err}") from err raise UpdateFailed(f"Error communicating with device: {err}") from err except TeltonikaConnectionError as err: raise UpdateFailed(f"Error communicating with device: {err}") from err if not modems_response.success: if modems_response.errors and any( error.code in AUTH_ERROR_CODES for error in modems_response.errors ): raise ConfigEntryAuthFailed( "Authentication failed: unauthorized access" ) error_message = ( modems_response.errors[0].error if modems_response.errors else "Unknown API error" ) raise UpdateFailed(f"Error communicating with device: {error_message}") # Return only modems which are online modem_data: dict[str, Any] = {} if modems_response.data: modem_data.update( { modem.id: modem for modem in modems_response.data if Modems.is_online(modem) } ) return modem_data
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/teltonika/coordinator.py", "license": "Apache License 2.0", "lines": 110, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/teltonika/sensor.py
"""Teltonika sensor platform.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass import logging from teltasync.modems import ModemStatus from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import ( SIGNAL_STRENGTH_DECIBELS, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, UnitOfTemperature, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import TeltonikaConfigEntry, TeltonikaDataUpdateCoordinator _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class TeltonikaSensorEntityDescription(SensorEntityDescription): """Describes Teltonika sensor entity.""" value_fn: Callable[[ModemStatus], StateType] SENSOR_DESCRIPTIONS: tuple[TeltonikaSensorEntityDescription, ...] = ( TeltonikaSensorEntityDescription( key="rssi", translation_key="rssi", device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, suggested_display_precision=0, value_fn=lambda modem: modem.rssi, ), TeltonikaSensorEntityDescription( key="rsrp", translation_key="rsrp", device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, suggested_display_precision=0, value_fn=lambda modem: modem.rsrp, ), TeltonikaSensorEntityDescription( key="rsrq", translation_key="rsrq", device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, suggested_display_precision=0, value_fn=lambda modem: modem.rsrq, ), TeltonikaSensorEntityDescription( key="sinr", translation_key="sinr", device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, suggested_display_precision=0, value_fn=lambda modem: modem.sinr, ), TeltonikaSensorEntityDescription( key="temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, suggested_display_precision=0, value_fn=lambda modem: modem.temperature, ), TeltonikaSensorEntityDescription( key="operator", translation_key="operator", value_fn=lambda modem: modem.operator, ), TeltonikaSensorEntityDescription( key="connection_type", translation_key="connection_type", value_fn=lambda modem: modem.conntype, ), TeltonikaSensorEntityDescription( key="band", translation_key="band", value_fn=lambda modem: modem.band, ), ) async def async_setup_entry( hass: HomeAssistant, entry: TeltonikaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Teltonika sensor platform.""" coordinator = entry.runtime_data # Track known modems to detect new ones known_modems: set[str] = set() @callback def _async_add_new_modems() -> None: """Add sensors for newly discovered modems.""" current_modems = set(coordinator.data.keys()) new_modems = current_modems - known_modems if new_modems: entities = [ TeltonikaSensorEntity( coordinator, coordinator.device_info, description, modem_id, coordinator.data[modem_id], ) for modem_id in new_modems for description in SENSOR_DESCRIPTIONS ] async_add_entities(entities) known_modems.update(new_modems) # Add sensors for initial modems _async_add_new_modems() # Listen for new modems entry.async_on_unload(coordinator.async_add_listener(_async_add_new_modems)) class TeltonikaSensorEntity( CoordinatorEntity[TeltonikaDataUpdateCoordinator], SensorEntity ): """Teltonika sensor entity.""" _attr_has_entity_name = True entity_description: TeltonikaSensorEntityDescription def __init__( self, coordinator: TeltonikaDataUpdateCoordinator, device_info: DeviceInfo, description: TeltonikaSensorEntityDescription, modem_id: str, modem: ModemStatus, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description self._modem_id = modem_id self._attr_device_info = device_info # Create unique ID using entry unique identifier, modem ID, and sensor type assert coordinator.config_entry is not None entry_unique_id = ( coordinator.config_entry.unique_id or coordinator.config_entry.entry_id ) self._attr_unique_id = f"{entry_unique_id}_{modem_id}_{description.key}" # Use translation key for proper naming modem_name = modem.name or f"Modem {modem_id}" self._modem_name = modem_name self._attr_translation_key = description.translation_key self._attr_translation_placeholders = {"modem_name": modem_name} @property def available(self) -> bool: """Return if entity is available.""" return super().available and self._modem_id in self.coordinator.data @property def native_value(self) -> StateType: """Handle updated data from the coordinator.""" return self.entity_description.value_fn(self.coordinator.data[self._modem_id])
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/teltonika/sensor.py", "license": "Apache License 2.0", "lines": 160, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/teltonika/util.py
"""Utility helpers for the Teltonika integration.""" from __future__ import annotations from yarl import URL def normalize_url(host: str) -> str: """Normalize host input to a base URL without path. Returns just the scheme://host part, without /api. Ensures the URL has a scheme (defaults to HTTPS). """ host_input = host.strip().rstrip("/") # Parse or construct URL if host_input.startswith(("http://", "https://")): url = URL(host_input) else: # handle as scheme-relative URL and add HTTPS scheme by default url = URL(f"//{host_input}").with_scheme("https") # Return base URL without path, only including scheme, host and port return str(url.origin()) def get_url_variants(host: str) -> list[str]: """Get URL variants to try during setup (HTTPS first, then HTTP fallback).""" normalized = normalize_url(host) url = URL(normalized) # If user specified a scheme, only try that if host.strip().startswith(("http://", "https://")): return [normalized] # Otherwise try HTTPS first, then HTTP https_url = str(url.with_scheme("https")) http_url = str(url.with_scheme("http")) return [https_url, http_url]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/teltonika/util.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/teltonika/test_config_flow.py
"""Test the Teltonika config flow.""" from unittest.mock import AsyncMock, MagicMock import pytest from teltasync import TeltonikaAuthenticationError, TeltonikaConnectionError from homeassistant import config_entries from homeassistant.components.teltonika.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME, CONF_VERIFY_SSL from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo from tests.common import MockConfigEntry async def test_form_user_flow( hass: HomeAssistant, mock_teltasync: MagicMock, mock_setup_entry: AsyncMock ) -> None: """Test we get the form and can create an entry.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: "192.168.1.1", CONF_USERNAME: "admin", CONF_PASSWORD: "password", CONF_VERIFY_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "RUTX50 Test" assert result["data"] == { CONF_HOST: "https://192.168.1.1", CONF_USERNAME: "admin", CONF_PASSWORD: "password", CONF_VERIFY_SSL: False, } assert result["result"].unique_id == "1234567890" @pytest.mark.parametrize( ("exception", "error_key"), [ (TeltonikaAuthenticationError("Invalid credentials"), "invalid_auth"), (TeltonikaConnectionError("Connection failed"), "cannot_connect"), (ValueError("Unexpected error"), "unknown"), ], ids=["invalid_auth", "cannot_connect", "unexpected_exception"], ) async def test_form_error_with_recovery( hass: HomeAssistant, mock_teltasync_client: MagicMock, mock_setup_entry: AsyncMock, exception: Exception, error_key: str, ) -> None: """Test we handle errors in config form and can recover.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) # First attempt with error mock_teltasync_client.get_device_info.side_effect = exception result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: "192.168.1.1", CONF_USERNAME: "admin", CONF_PASSWORD: "password", CONF_VERIFY_SSL: False, }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": error_key} # Recover with working connection device_info = MagicMock() device_info.device_name = "RUTX50 Test" device_info.device_identifier = "1234567890" mock_teltasync_client.get_device_info.side_effect = None mock_teltasync_client.get_device_info.return_value = device_info mock_teltasync_client.validate_credentials.return_value = True result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: "192.168.1.1", CONF_USERNAME: "admin", CONF_PASSWORD: "password", CONF_VERIFY_SSL: False, }, ) await hass.async_block_till_done() assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "RUTX50 Test" assert result["data"][CONF_HOST] == "https://192.168.1.1" assert result["result"].unique_id == "1234567890" async def test_form_duplicate_entry( hass: HomeAssistant, mock_teltasync: MagicMock, mock_config_entry: MockConfigEntry ) -> None: """Test duplicate config entry is handled.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: "192.168.1.1", CONF_USERNAME: "admin", CONF_PASSWORD: "password", CONF_VERIFY_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" @pytest.mark.parametrize( ("host_input", "expected_base_url", "expected_host"), [ ("192.168.1.1", "https://192.168.1.1/api", "https://192.168.1.1"), ("http://192.168.1.1", "http://192.168.1.1/api", "http://192.168.1.1"), ("https://192.168.1.1", "https://192.168.1.1/api", "https://192.168.1.1"), ("https://192.168.1.1/api", "https://192.168.1.1/api", "https://192.168.1.1"), ("device.local", "https://device.local/api", "https://device.local"), ], ) async def test_host_url_construction( hass: HomeAssistant, mock_teltasync: MagicMock, mock_teltasync_client: MagicMock, mock_setup_entry: AsyncMock, host_input: str, expected_base_url: str, expected_host: str, ) -> None: """Test that host URLs are constructed correctly.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: host_input, CONF_USERNAME: "admin", CONF_PASSWORD: "password", CONF_VERIFY_SSL: False, }, ) # Verify Teltasync was called with correct base URL assert mock_teltasync_client.get_device_info.call_count == 1 call_args = mock_teltasync.call_args_list[0] assert call_args.kwargs["base_url"] == expected_base_url assert call_args.kwargs["verify_ssl"] is False # Verify the result is a created entry with normalized host assert result["type"] is FlowResultType.CREATE_ENTRY assert result["result"].data[CONF_HOST] == expected_host async def test_form_user_flow_http_fallback( hass: HomeAssistant, mock_teltasync_client: MagicMock, mock_setup_entry: AsyncMock ) -> None: """Test we fall back to HTTP when HTTPS fails.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) # First call (HTTPS) fails https_client = MagicMock() https_client.get_device_info.side_effect = TeltonikaConnectionError( "HTTPS unavailable" ) https_client.close = AsyncMock() # Second call (HTTP) succeeds device_info = MagicMock() device_info.device_name = "RUTX50 Test" device_info.device_identifier = "TESTFALLBACK" http_client = MagicMock() http_client.get_device_info = AsyncMock(return_value=device_info) http_client.validate_credentials = AsyncMock(return_value=True) http_client.close = AsyncMock() mock_teltasync_client.get_device_info.side_effect = [ TeltonikaConnectionError("HTTPS unavailable"), mock_teltasync_client.get_device_info.return_value, ] result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: "192.168.1.1", CONF_USERNAME: "admin", CONF_PASSWORD: "password", CONF_VERIFY_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"][CONF_HOST] == "http://192.168.1.1" assert mock_teltasync_client.get_device_info.call_count == 2 # HTTPS client should be closed before falling back assert mock_teltasync_client.close.call_count == 2 async def test_dhcp_discovery( hass: HomeAssistant, mock_teltasync_client: MagicMock, mock_setup_entry: AsyncMock ) -> None: """Test DHCP discovery flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.1.50", macaddress="209727112233", hostname="teltonika", ), ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "dhcp_confirm" assert "name" in result["description_placeholders"] assert "host" in result["description_placeholders"] # Configure device info for the actual setup device_info = MagicMock() device_info.device_name = "RUTX50 Discovered" device_info.device_identifier = "DISCOVERED123" mock_teltasync_client.get_device_info.return_value = device_info result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_USERNAME: "admin", CONF_PASSWORD: "password", }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "RUTX50 Discovered" assert result["data"][CONF_HOST] == "https://192.168.1.50" assert result["data"][CONF_USERNAME] == "admin" assert result["data"][CONF_PASSWORD] == "password" assert result["result"].unique_id == "DISCOVERED123" async def test_dhcp_discovery_already_configured( hass: HomeAssistant, mock_teltasync: MagicMock, mock_config_entry: MockConfigEntry ) -> None: """Test DHCP discovery when device is already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.1.50", # Different IP macaddress="209727112233", hostname="teltonika", ), ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" # Verify IP was updated assert mock_config_entry.data[CONF_HOST] == "192.168.1.50" async def test_dhcp_discovery_cannot_connect( hass: HomeAssistant, mock_teltasync_client: MagicMock ) -> None: """Test DHCP discovery when device is not reachable.""" # Simulate device not reachable via API mock_teltasync_client.get_device_info.side_effect = TeltonikaConnectionError( "Connection failed" ) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.1.50", macaddress="209727112233", hostname="teltonika", ), ) # Should abort if device is not reachable assert result["type"] is FlowResultType.ABORT assert result["reason"] == "cannot_connect" @pytest.mark.parametrize( ("exception", "error_key"), [ (TeltonikaAuthenticationError("Invalid credentials"), "invalid_auth"), (TeltonikaConnectionError("Connection failed"), "cannot_connect"), (ValueError("Unexpected error"), "unknown"), ], ids=["invalid_auth", "cannot_connect", "unexpected_exception"], ) async def test_dhcp_confirm_error_with_recovery( hass: HomeAssistant, mock_teltasync_client: MagicMock, mock_setup_entry: AsyncMock, exception: Exception, error_key: str, ) -> None: """Test DHCP confirmation handles errors and can recover.""" # Start the DHCP flow result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.1.50", macaddress="209727112233", hostname="teltonika", ), ) # First attempt with error mock_teltasync_client.get_device_info.side_effect = exception result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_USERNAME: "admin", CONF_PASSWORD: "password", }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": error_key} assert result["step_id"] == "dhcp_confirm" # Recover with working connection device_info = MagicMock() device_info.device_name = "RUTX50 Discovered" device_info.device_identifier = "DISCOVERED123" mock_teltasync_client.get_device_info.side_effect = None mock_teltasync_client.get_device_info.return_value = device_info mock_teltasync_client.validate_credentials.return_value = True result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_USERNAME: "admin", CONF_PASSWORD: "password", }, ) await hass.async_block_till_done() assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "RUTX50 Discovered" assert result["data"][CONF_HOST] == "https://192.168.1.50" assert result["result"].unique_id == "DISCOVERED123" async def test_validate_credentials_false( hass: HomeAssistant, mock_teltasync_client: MagicMock ) -> None: """Test config flow when validate_credentials returns False.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) device_info = MagicMock() device_info.device_name = "Test Device" device_info.device_identifier = "TEST123" mock_teltasync_client.get_device_info.return_value = device_info mock_teltasync_client.validate_credentials.return_value = False result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: "192.168.1.1", CONF_USERNAME: "admin", CONF_PASSWORD: "password", CONF_VERIFY_SSL: False, }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "invalid_auth"} async def test_reauth_flow_success( hass: HomeAssistant, mock_teltasync_client: MagicMock, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test successful reauth flow.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_USERNAME: "admin", CONF_PASSWORD: "new_password", }, ) await hass.async_block_till_done() assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data[CONF_USERNAME] == "admin" assert mock_config_entry.data[CONF_PASSWORD] == "new_password" assert mock_config_entry.data[CONF_HOST] == "192.168.1.1" @pytest.mark.parametrize( ("side_effect", "expected_error"), [ (TeltonikaAuthenticationError("Invalid credentials"), "invalid_auth"), (TeltonikaConnectionError("Connection failed"), "cannot_connect"), (ValueError("Unexpected error"), "unknown"), ], ids=["invalid_auth", "cannot_connect", "unexpected_exception"], ) async def test_reauth_flow_errors_with_recovery( hass: HomeAssistant, mock_teltasync_client: MagicMock, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, side_effect: Exception, expected_error: str, ) -> None: """Test reauth flow error handling with successful recovery.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) mock_teltasync_client.get_device_info.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_USERNAME: "admin", CONF_PASSWORD: "bad_password", }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": expected_error} assert result["step_id"] == "reauth_confirm" mock_teltasync_client.get_device_info.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_USERNAME: "admin", CONF_PASSWORD: "new_password", }, ) await hass.async_block_till_done() assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data[CONF_USERNAME] == "admin" assert mock_config_entry.data[CONF_PASSWORD] == "new_password" assert mock_config_entry.data[CONF_HOST] == "192.168.1.1" async def test_reauth_flow_wrong_account( hass: HomeAssistant, mock_teltasync_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reauth flow aborts when device serial doesn't match.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) device_info = MagicMock() device_info.device_name = "RUTX50 Different" device_info.device_identifier = "DIFFERENT1234567890" mock_teltasync_client.get_device_info = AsyncMock(return_value=device_info) result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_USERNAME: "admin", CONF_PASSWORD: "password", }, ) await hass.async_block_till_done() assert result["type"] is FlowResultType.ABORT assert result["reason"] == "wrong_account"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/teltonika/test_config_flow.py", "license": "Apache License 2.0", "lines": 437, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/teltonika/test_init.py
"""Test the Teltonika integration.""" from unittest.mock import MagicMock from aiohttp import ClientResponseError, ContentTypeError import pytest from syrupy.assertion import SnapshotAssertion from teltasync import TeltonikaAuthenticationError, TeltonikaConnectionError from homeassistant.components.teltonika.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from tests.common import MockConfigEntry async def test_load_unload_config_entry( hass: HomeAssistant, init_integration: MockConfigEntry, ) -> None: """Test loading and unloading the integration.""" assert init_integration.state is ConfigEntryState.LOADED await hass.config_entries.async_unload(init_integration.entry_id) await hass.async_block_till_done() assert init_integration.state is ConfigEntryState.NOT_LOADED @pytest.mark.parametrize( ("exception", "expected_state"), [ ( TeltonikaConnectionError("Connection failed"), ConfigEntryState.SETUP_RETRY, ), ( ContentTypeError( request_info=MagicMock(), history=(), status=403, message="Attempt to decode JSON with unexpected mimetype: text/html", headers={}, ), ConfigEntryState.SETUP_ERROR, ), ( ClientResponseError( request_info=MagicMock(), history=(), status=401, message="Unauthorized", headers={}, ), ConfigEntryState.SETUP_ERROR, ), ( ClientResponseError( request_info=MagicMock(), history=(), status=403, message="Forbidden", headers={}, ), ConfigEntryState.SETUP_ERROR, ), ( TeltonikaAuthenticationError("Invalid credentials"), ConfigEntryState.SETUP_ERROR, ), ], ids=[ "connection_error", "content_type_403", "response_401", "response_403", "auth_error", ], ) async def test_setup_errors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_teltasync: MagicMock, exception: Exception, expected_state: ConfigEntryState, ) -> None: """Test various setup errors result in appropriate config entry states.""" mock_teltasync.return_value.get_device_info.side_effect = exception mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is expected_state async def test_device_registry_creation( hass: HomeAssistant, init_integration: MockConfigEntry, device_registry: dr.DeviceRegistry, snapshot: SnapshotAssertion, ) -> None: """Test device registry creation.""" device = device_registry.async_get_device(identifiers={(DOMAIN, "1234567890")}) assert device is not None assert device == snapshot
{ "repo_id": "home-assistant/core", "file_path": "tests/components/teltonika/test_init.py", "license": "Apache License 2.0", "lines": 93, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/teltonika/test_sensor.py
"""Test Teltonika sensor platform.""" from datetime import timedelta from unittest.mock import AsyncMock, MagicMock from aiohttp import ClientResponseError from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from teltasync import TeltonikaAuthenticationError, TeltonikaConnectionError from teltasync.error_codes import TeltonikaErrorCode from homeassistant.components.teltonika.const import DOMAIN from homeassistant.config_entries import SOURCE_REAUTH from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform async def test_sensors( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, init_integration: MockConfigEntry, ) -> None: """Test sensor entities match snapshot.""" await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id) async def test_sensor_modem_removed( hass: HomeAssistant, entity_registry: er.EntityRegistry, init_integration: MockConfigEntry, mock_modems: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test sensor becomes unavailable when modem is removed.""" # Get initial sensor state state = hass.states.get("sensor.rutx50_test_internal_modem_rssi") assert state is not None # Update coordinator with empty modem data mock_response = MagicMock() mock_response.data = [] # No modems mock_modems.get_status.return_value = mock_response freezer.tick(timedelta(seconds=31)) async_fire_time_changed(hass) await hass.async_block_till_done() # Check that entity is marked as unavailable state = hass.states.get("sensor.rutx50_test_internal_modem_rssi") assert state is not None # When modem is removed, entity should be marked as unavailable # Verify through entity registry that entity exists but is unavailable entity_entry = entity_registry.async_get("sensor.rutx50_test_internal_modem_rssi") assert entity_entry is not None # State should show unavailable when modem is removed assert state.state == "unavailable" async def test_sensor_update_failure_and_recovery( hass: HomeAssistant, mock_modems: AsyncMock, init_integration: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test sensor becomes unavailable on update failure and recovers.""" # Get initial sensor state, here it should be available state = hass.states.get("sensor.rutx50_test_internal_modem_rssi") assert state is not None assert state.state == "-63" mock_modems.get_status.side_effect = TeltonikaConnectionError("Connection lost") freezer.tick(timedelta(seconds=30)) async_fire_time_changed(hass) await hass.async_block_till_done() # Sensor should now be unavailable state = hass.states.get("sensor.rutx50_test_internal_modem_rssi") assert state is not None assert state.state == "unavailable" # Simulate recovery mock_modems.get_status.side_effect = None freezer.tick(timedelta(seconds=30)) async_fire_time_changed(hass) await hass.async_block_till_done() # Sensor should be available again with correct data state = hass.states.get("sensor.rutx50_test_internal_modem_rssi") assert state is not None assert state.state == "-63" @pytest.mark.parametrize( ("side_effect", "expect_reauth"), [ (TeltonikaAuthenticationError("Invalid credentials"), True), ( ClientResponseError( request_info=MagicMock(), history=(), status=401, message="Unauthorized", headers={}, ), True, ), ( ClientResponseError( request_info=MagicMock(), history=(), status=500, message="Server error", headers={}, ), False, ), ], ids=["auth_exception", "http_auth_error", "http_non_auth_error"], ) async def test_sensor_update_exception_paths( hass: HomeAssistant, mock_modems: AsyncMock, init_integration: MockConfigEntry, freezer: FrozenDateTimeFactory, side_effect: Exception, expect_reauth: bool, ) -> None: """Test auth and non-auth exceptions during updates.""" mock_modems.get_status.side_effect = side_effect freezer.tick(timedelta(seconds=31)) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get("sensor.rutx50_test_internal_modem_rssi") assert state is not None assert state.state == "unavailable" has_reauth = any( flow["handler"] == DOMAIN and flow["context"]["source"] == SOURCE_REAUTH for flow in hass.config_entries.flow.async_progress() ) assert has_reauth is expect_reauth @pytest.mark.parametrize( ("error_code", "expect_reauth"), [ (TeltonikaErrorCode.UNAUTHORIZED_ACCESS, True), (999, False), ], ids=["api_auth_error", "api_non_auth_error"], ) async def test_sensor_update_unsuccessful_response_paths( hass: HomeAssistant, mock_modems: AsyncMock, init_integration: MockConfigEntry, freezer: FrozenDateTimeFactory, error_code: int, expect_reauth: bool, ) -> None: """Test unsuccessful API response handling.""" mock_modems.get_status.side_effect = None mock_modems.get_status.return_value = MagicMock( success=False, data=None, errors=[MagicMock(code=error_code, error="API error")], ) freezer.tick(timedelta(seconds=31)) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get("sensor.rutx50_test_internal_modem_rssi") assert state is not None assert state.state == "unavailable" has_reauth = any( flow["handler"] == DOMAIN and flow["context"]["source"] == SOURCE_REAUTH for flow in hass.config_entries.flow.async_progress() ) assert has_reauth is expect_reauth
{ "repo_id": "home-assistant/core", "file_path": "tests/components/teltonika/test_sensor.py", "license": "Apache License 2.0", "lines": 159, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/teltonika/test_util.py
"""Test Teltonika utility helpers.""" from homeassistant.components.teltonika.util import get_url_variants, normalize_url def test_normalize_url_adds_https_scheme() -> None: """Test normalize_url adds HTTPS scheme for bare hostnames.""" assert normalize_url("teltonika") == "https://teltonika" def test_normalize_url_preserves_scheme() -> None: """Test normalize_url preserves explicitly provided scheme.""" assert normalize_url("http://teltonika") == "http://teltonika" assert normalize_url("https://teltonika") == "https://teltonika" def test_normalize_url_strips_path() -> None: """Test normalize_url removes any path component.""" assert normalize_url("https://teltonika/api") == "https://teltonika" assert normalize_url("http://teltonika/other/path") == "http://teltonika" def test_get_url_variants_with_https_scheme() -> None: """Test get_url_variants with explicit HTTPS scheme returns only HTTPS.""" assert get_url_variants("https://teltonika") == ["https://teltonika"] def test_get_url_variants_with_http_scheme() -> None: """Test get_url_variants with explicit HTTP scheme returns only HTTP.""" assert get_url_variants("http://teltonika") == ["http://teltonika"] def test_get_url_variants_without_scheme() -> None: """Test get_url_variants without scheme returns both HTTPS and HTTP.""" assert get_url_variants("teltonika") == [ "https://teltonika", "http://teltonika", ]
{ "repo_id": "home-assistant/core", "file_path": "tests/components/teltonika/test_util.py", "license": "Apache License 2.0", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/onedrive_for_business/coordinator.py
"""Coordinator for OneDrive for Business.""" from __future__ import annotations from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import timedelta import logging from time import time from onedrive_personal_sdk import OneDriveClient from onedrive_personal_sdk.const import DriveState from onedrive_personal_sdk.exceptions import AuthenticationError, OneDriveException from onedrive_personal_sdk.models.items import Drive from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers import issue_registry as ir from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN SCAN_INTERVAL = timedelta(minutes=5) _LOGGER = logging.getLogger(__name__) @dataclass class OneDriveRuntimeData: """Runtime data for the OneDrive integration.""" client: OneDriveClient token_function: Callable[[], Awaitable[str]] coordinator: OneDriveForBusinessUpdateCoordinator type OneDriveConfigEntry = ConfigEntry[OneDriveRuntimeData] class OneDriveForBusinessUpdateCoordinator(DataUpdateCoordinator[Drive]): """Class to handle fetching data from the Graph API centrally.""" config_entry: OneDriveConfigEntry def __init__( self, hass: HomeAssistant, entry: OneDriveConfigEntry, client: OneDriveClient ) -> None: """Initialize coordinator.""" super().__init__( hass, _LOGGER, config_entry=entry, name=DOMAIN, update_interval=SCAN_INTERVAL, ) self._client = client async def _async_update_data(self) -> Drive: """Fetch data from API endpoint.""" expires_at = self.config_entry.data["token"]["expires_at"] _LOGGER.debug( "Token expiry: %s (in %s seconds)", expires_at, expires_at - time(), ) try: drive = await self._client.get_drive() except AuthenticationError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="authentication_failed" ) from err except OneDriveException as err: _LOGGER.debug("Failed to fetch drive data: %s", err, exc_info=True) raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_failed" ) from err # create an issue if the drive is almost full if drive.quota and (state := drive.quota.state) in ( DriveState.CRITICAL, DriveState.EXCEEDED, ): key = "drive_full" if state is DriveState.EXCEEDED else "drive_almost_full" ir.async_create_issue( self.hass, DOMAIN, key, is_fixable=False, severity=( ir.IssueSeverity.ERROR if state is DriveState.EXCEEDED else ir.IssueSeverity.WARNING ), translation_key=key, translation_placeholders={ "total": f"{drive.quota.total / (1024**3):.2f}", "used": f"{drive.quota.used / (1024**3):.2f}", }, ) return drive
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/onedrive_for_business/coordinator.py", "license": "Apache License 2.0", "lines": 83, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/onedrive_for_business/sensor.py
"""Sensors for OneDrive for Business.""" from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING from onedrive_personal_sdk.const import DriveState from onedrive_personal_sdk.models.items import DriveQuota from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, ) from homeassistant.const import EntityCategory, UnitOfInformation from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import OneDriveConfigEntry, OneDriveForBusinessUpdateCoordinator PARALLEL_UPDATES = 0 @dataclass(kw_only=True, frozen=True) class OneDriveForBusinessSensorEntityDescription(SensorEntityDescription): """Describes OneDrive sensor entity.""" value_fn: Callable[[DriveQuota], StateType] DRIVE_STATE_ENTITIES: tuple[OneDriveForBusinessSensorEntityDescription, ...] = ( OneDriveForBusinessSensorEntityDescription( key="total_size", value_fn=lambda quota: quota.total, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES, suggested_display_precision=0, device_class=SensorDeviceClass.DATA_SIZE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), OneDriveForBusinessSensorEntityDescription( key="used_size", value_fn=lambda quota: quota.used, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES, suggested_display_precision=2, device_class=SensorDeviceClass.DATA_SIZE, entity_category=EntityCategory.DIAGNOSTIC, ), OneDriveForBusinessSensorEntityDescription( key="remaining_size", value_fn=lambda quota: quota.remaining, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES, suggested_display_precision=2, device_class=SensorDeviceClass.DATA_SIZE, entity_category=EntityCategory.DIAGNOSTIC, ), OneDriveForBusinessSensorEntityDescription( key="drive_state", value_fn=lambda quota: quota.state.value, options=[state.value for state in DriveState], device_class=SensorDeviceClass.ENUM, entity_category=EntityCategory.DIAGNOSTIC, ), ) async def async_setup_entry( hass: HomeAssistant, entry: OneDriveConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up OneDrive for Business sensors based on a config entry.""" coordinator = entry.runtime_data.coordinator async_add_entities( OneDriveDriveStateSensor(coordinator, description) for description in DRIVE_STATE_ENTITIES ) class OneDriveDriveStateSensor( CoordinatorEntity[OneDriveForBusinessUpdateCoordinator], SensorEntity ): """Define a OneDrive for Business sensor.""" entity_description: OneDriveForBusinessSensorEntityDescription _attr_has_entity_name = True def __init__( self, coordinator: OneDriveForBusinessUpdateCoordinator, description: OneDriveForBusinessSensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description self._attr_translation_key = description.key self._attr_unique_id = f"{coordinator.data.id}_{description.key}" self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, name=coordinator.data.name or coordinator.config_entry.title, identifiers={(DOMAIN, coordinator.data.id)}, manufacturer="Microsoft", model=f"OneDrive {coordinator.data.drive_type.value.capitalize()}", ) @property def native_value(self) -> StateType: """Return the state of the sensor.""" if TYPE_CHECKING: assert self.coordinator.data.quota return self.entity_description.value_fn(self.coordinator.data.quota) @property def available(self) -> bool: """Availability of the sensor.""" return super().available and self.coordinator.data.quota is not None
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/onedrive_for_business/sensor.py", "license": "Apache License 2.0", "lines": 105, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/onedrive_for_business/test_sensor.py
"""Tests for OneDrive for Business sensors.""" from datetime import timedelta from typing import Any from unittest.mock import MagicMock from freezegun.api import FrozenDateTimeFactory from onedrive_personal_sdk.const import DriveType from onedrive_personal_sdk.exceptions import HttpRequestException from onedrive_personal_sdk.models.items import Drive import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_sensors( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test the OneDrive for Business sensors.""" await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.parametrize( ("attr", "side_effect"), [ ("side_effect", HttpRequestException(503, "Service Unavailable")), ("return_value", Drive(id="id", name="name", drive_type=DriveType.PERSONAL)), ], ) async def test_update_failure( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_onedrive_client: MagicMock, freezer: FrozenDateTimeFactory, attr: str, side_effect: Any, ) -> None: """Ensure sensors are going unavailable on update failure.""" await setup_integration(hass, mock_config_entry) state = hass.states.get("sensor.my_drive_remaining_storage") assert state.state == "0.75" setattr(mock_onedrive_client.get_drive, attr, side_effect) freezer.tick(timedelta(minutes=10)) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get("sensor.my_drive_remaining_storage") assert state.state == STATE_UNAVAILABLE
{ "repo_id": "home-assistant/core", "file_path": "tests/components/onedrive_for_business/test_sensor.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/indevolt/config_flow.py
"""Config flow for Indevolt integration.""" import logging from typing import Any from aiohttp import ClientError from indevolt_api import IndevoltAPI import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST, CONF_MODEL from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import CONF_GENERATION, CONF_SERIAL_NUMBER, DEFAULT_PORT, DOMAIN _LOGGER = logging.getLogger(__name__) class IndevoltConfigFlow(ConfigFlow, domain=DOMAIN): """Configuration flow for Indevolt integration.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial user configuration step.""" errors: dict[str, str] = {} # Attempt to setup from user input if user_input is not None: errors, device_data = await self._async_validate_input(user_input) if not errors and device_data: await self.async_set_unique_id(device_data[CONF_SERIAL_NUMBER]) # Handle initial setup self._abort_if_unique_id_configured() return self.async_create_entry( title=f"INDEVOLT {device_data[CONF_MODEL]}", data={ CONF_HOST: user_input[CONF_HOST], **device_data, }, ) # Retrieve user input return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Required(CONF_HOST): str}), errors=errors, ) async def _async_validate_input( self, user_input: dict[str, Any] ) -> tuple[dict[str, str], dict[str, Any] | None]: """Validate user input and return errors dict and device data.""" errors = {} device_data = None try: device_data = await self._async_get_device_data(user_input[CONF_HOST]) except TimeoutError: errors["base"] = "timeout" except ConnectionError, ClientError: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unknown error occurred while verifying device") errors["base"] = "unknown" return errors, device_data async def _async_get_device_data(self, host: str) -> dict[str, Any]: """Get device data (type, serial number, generation) from API.""" api = IndevoltAPI(host, DEFAULT_PORT, async_get_clientsession(self.hass)) config_data = await api.get_config() device_data = config_data["device"] return { CONF_SERIAL_NUMBER: device_data["sn"], CONF_GENERATION: device_data["generation"], CONF_MODEL: device_data["type"], }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/indevolt/config_flow.py", "license": "Apache License 2.0", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/indevolt/coordinator.py
"""Home Assistant integration for Indevolt device.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from aiohttp import ClientError from indevolt_api import IndevoltAPI, TimeOutException from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_MODEL from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ( CONF_GENERATION, CONF_SERIAL_NUMBER, DEFAULT_PORT, DOMAIN, SENSOR_KEYS, ) _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = 30 type IndevoltConfigEntry = ConfigEntry[IndevoltCoordinator] class IndevoltCoordinator(DataUpdateCoordinator[dict[str, Any]]): """Coordinator for fetching and pushing data to indevolt devices.""" config_entry: IndevoltConfigEntry firmware_version: str | None def __init__(self, hass: HomeAssistant, entry: IndevoltConfigEntry) -> None: """Initialize the indevolt coordinator.""" super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=SCAN_INTERVAL), config_entry=entry, ) # Initialize Indevolt API self.api = IndevoltAPI( host=entry.data[CONF_HOST], port=DEFAULT_PORT, session=async_get_clientsession(hass), ) self.serial_number = entry.data[CONF_SERIAL_NUMBER] self.device_model = entry.data[CONF_MODEL] self.generation = entry.data[CONF_GENERATION] async def _async_setup(self) -> None: """Fetch device info once on boot.""" try: config_data = await self.api.get_config() except TimeOutException as err: raise ConfigEntryNotReady( f"Device config retrieval timed out: {err}" ) from err # Cache device information device_data = config_data.get("device", {}) self.firmware_version = device_data.get("fw") async def _async_update_data(self) -> dict[str, Any]: """Fetch raw JSON data from the device.""" sensor_keys = SENSOR_KEYS[self.generation] try: return await self.api.fetch_data(sensor_keys) except TimeOutException as err: raise UpdateFailed(f"Device update timed out: {err}") from err async def async_push_data(self, sensor_key: str, value: Any) -> bool: """Push/write data values to given key on the device.""" try: return await self.api.set_data(sensor_key, value) except TimeOutException as err: raise HomeAssistantError(f"Device push timed out: {err}") from err except (ClientError, ConnectionError, OSError) as err: raise HomeAssistantError(f"Device push failed: {err}") from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/indevolt/coordinator.py", "license": "Apache License 2.0", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/indevolt/entity.py
"""Base entity for Indevolt integration.""" from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import IndevoltCoordinator class IndevoltEntity(CoordinatorEntity[IndevoltCoordinator]): """Base Indevolt entity with up-to-date device info.""" _attr_has_entity_name = True @property def serial_number(self) -> str: """Return the device serial number.""" return self.coordinator.serial_number @property def device_info(self) -> DeviceInfo: """Return device information for registry.""" coordinator = self.coordinator return DeviceInfo( identifiers={(DOMAIN, coordinator.serial_number)}, manufacturer="INDEVOLT", serial_number=coordinator.serial_number, model=coordinator.device_model, sw_version=coordinator.firmware_version, hw_version=str(coordinator.generation), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/indevolt/entity.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/indevolt/sensor.py
"""Sensor platform for Indevolt integration.""" from dataclasses import dataclass, field from typing import Final from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import ( PERCENTAGE, EntityCategory, UnitOfElectricCurrent, UnitOfElectricPotential, UnitOfEnergy, UnitOfFrequency, UnitOfPower, UnitOfTemperature, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import IndevoltConfigEntry from .coordinator import IndevoltCoordinator from .entity import IndevoltEntity PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class IndevoltSensorEntityDescription(SensorEntityDescription): """Custom entity description class for Indevolt sensors.""" state_mapping: dict[str | int, str] = field(default_factory=dict) generation: list[int] = field(default_factory=lambda: [1, 2]) SENSORS: Final = ( # System Operating Information IndevoltSensorEntityDescription( key="606", translation_key="mode", state_mapping={"1000": "main", "1001": "sub", "1002": "standalone"}, device_class=SensorDeviceClass.ENUM, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="7101", translation_key="energy_mode", state_mapping={ 0: "outdoor_portable", 1: "self_consumed_prioritized", 4: "real_time_control", 5: "charge_discharge_schedule", }, device_class=SensorDeviceClass.ENUM, ), IndevoltSensorEntityDescription( key="142", generation=[2], translation_key="rated_capacity", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="6105", generation=[1], translation_key="rated_capacity", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="2101", translation_key="ac_input_power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), IndevoltSensorEntityDescription( key="2108", translation_key="ac_output_power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), IndevoltSensorEntityDescription( key="667", generation=[2], translation_key="bypass_power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), # Electrical Energy Information IndevoltSensorEntityDescription( key="2107", translation_key="total_ac_input_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="2104", generation=[2], translation_key="total_ac_output_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="2105", generation=[2], translation_key="off_grid_output_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="11034", generation=[2], translation_key="bypass_input_energy", native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="6004", generation=[2], translation_key="battery_daily_charging_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="6005", generation=[2], translation_key="battery_daily_discharging_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="6006", generation=[2], translation_key="battery_total_charging_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="6007", generation=[2], translation_key="battery_total_discharging_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), # Electricity Meter Status IndevoltSensorEntityDescription( key="11016", generation=[2], translation_key="meter_power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), IndevoltSensorEntityDescription( key="21028", generation=[1], translation_key="meter_power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), # Grid information IndevoltSensorEntityDescription( key="2600", generation=[2], translation_key="grid_voltage", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="2612", generation=[2], translation_key="grid_frequency", native_unit_of_measurement=UnitOfFrequency.HERTZ, device_class=SensorDeviceClass.FREQUENCY, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), # Battery Pack Operating Parameters IndevoltSensorEntityDescription( key="6000", translation_key="battery_power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), IndevoltSensorEntityDescription( key="6001", translation_key="battery_charge_discharge_state", state_mapping={1000: "static", 1001: "charging", 1002: "discharging"}, device_class=SensorDeviceClass.ENUM, ), IndevoltSensorEntityDescription( key="6002", translation_key="battery_soc", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, state_class=SensorStateClass.MEASUREMENT, ), # PV Operating Parameters IndevoltSensorEntityDescription( key="1501", translation_key="dc_output_power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, ), IndevoltSensorEntityDescription( key="1502", translation_key="daily_production", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="1505", generation=[1], translation_key="cumulative_production", native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, ), IndevoltSensorEntityDescription( key="1632", generation=[2], translation_key="dc_input_current_1", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1600", generation=[2], translation_key="dc_input_voltage_1", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1664", translation_key="dc_input_power_1", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1633", generation=[2], translation_key="dc_input_current_2", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1601", generation=[2], translation_key="dc_input_voltage_2", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1665", translation_key="dc_input_power_2", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1634", generation=[2], translation_key="dc_input_current_3", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1602", generation=[2], translation_key="dc_input_voltage_3", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1666", generation=[2], translation_key="dc_input_power_3", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1635", generation=[2], translation_key="dc_input_current_4", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1603", generation=[2], translation_key="dc_input_voltage_4", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="1667", generation=[2], translation_key="dc_input_power_4", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, entity_registry_enabled_default=False, ), # Battery Pack Serial Numbers IndevoltSensorEntityDescription( key="9008", generation=[2], translation_key="main_serial_number", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9032", generation=[2], translation_key="battery_pack_1_serial_number", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9051", generation=[2], translation_key="battery_pack_2_serial_number", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9070", generation=[2], translation_key="battery_pack_3_serial_number", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9165", generation=[2], translation_key="battery_pack_4_serial_number", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9218", generation=[2], translation_key="battery_pack_5_serial_number", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), # Battery Pack SOC IndevoltSensorEntityDescription( key="9000", generation=[2], translation_key="main_soc", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9016", generation=[2], translation_key="battery_pack_1_soc", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9035", generation=[2], translation_key="battery_pack_2_soc", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9054", generation=[2], translation_key="battery_pack_3_soc", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9149", generation=[2], translation_key="battery_pack_4_soc", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9202", generation=[2], translation_key="battery_pack_5_soc", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), # Battery Pack Temperature IndevoltSensorEntityDescription( key="9012", generation=[2], translation_key="main_temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9030", generation=[2], translation_key="battery_pack_1_temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9049", generation=[2], translation_key="battery_pack_2_temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9068", generation=[2], translation_key="battery_pack_3_temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9163", generation=[2], translation_key="battery_pack_4_temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9216", generation=[2], translation_key="battery_pack_5_temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), # Battery Pack Voltage IndevoltSensorEntityDescription( key="9004", generation=[2], translation_key="main_voltage", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9020", generation=[2], translation_key="battery_pack_1_voltage", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9039", generation=[2], translation_key="battery_pack_2_voltage", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9058", generation=[2], translation_key="battery_pack_3_voltage", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9153", generation=[2], translation_key="battery_pack_4_voltage", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="9206", generation=[2], translation_key="battery_pack_5_voltage", native_unit_of_measurement=UnitOfElectricPotential.VOLT, device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), # Battery Pack Current IndevoltSensorEntityDescription( key="9013", generation=[2], translation_key="main_current", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="19173", generation=[2], translation_key="battery_pack_1_current", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="19174", generation=[2], translation_key="battery_pack_2_current", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="19175", generation=[2], translation_key="battery_pack_3_current", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="19176", generation=[2], translation_key="battery_pack_4_current", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), IndevoltSensorEntityDescription( key="19177", generation=[2], translation_key="battery_pack_5_current", native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), ) # Sensors per battery pack (SN, SOC, Temperature, Voltage, Current) BATTERY_PACK_SENSOR_KEYS = [ ("9032", "9016", "9030", "9020", "19173"), # Battery Pack 1 ("9051", "9035", "9049", "9039", "19174"), # Battery Pack 2 ("9070", "9054", "9068", "9058", "19175"), # Battery Pack 3 ("9165", "9149", "9163", "9153", "19176"), # Battery Pack 4 ("9218", "9202", "9216", "9206", "19177"), # Battery Pack 5 ] async def async_setup_entry( hass: HomeAssistant, entry: IndevoltConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the sensor platform for Indevolt.""" coordinator = entry.runtime_data device_gen = coordinator.generation excluded_keys: set[str] = set() for pack_keys in BATTERY_PACK_SENSOR_KEYS: sn_key = pack_keys[0] if not coordinator.data.get(sn_key): excluded_keys.update(pack_keys) # Sensor initialization async_add_entities( IndevoltSensorEntity(coordinator, description) for description in SENSORS if device_gen in description.generation and description.key not in excluded_keys ) class IndevoltSensorEntity(IndevoltEntity, SensorEntity): """Represents a sensor entity for Indevolt devices.""" entity_description: IndevoltSensorEntityDescription def __init__( self, coordinator: IndevoltCoordinator, description: IndevoltSensorEntityDescription, ) -> None: """Initialize the Indevolt sensor entity.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{self.serial_number}_{description.key}" # Sort options (prevent randomization) for ENUM values if description.device_class == SensorDeviceClass.ENUM: self._attr_options = sorted(set(description.state_mapping.values())) @property def native_value(self) -> str | int | float | None: """Return the current value of the sensor in its native unit.""" raw_value = self.coordinator.data.get(self.entity_description.key) if raw_value is None: return None # Return descriptions for ENUM values if self.entity_description.device_class == SensorDeviceClass.ENUM: return self.entity_description.state_mapping.get(raw_value) return raw_value
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/indevolt/sensor.py", "license": "Apache License 2.0", "lines": 680, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/indevolt/test_config_flow.py
"""Tests the Indevolt config flow.""" from unittest.mock import AsyncMock from aiohttp import ClientError import pytest from homeassistant.components.indevolt.const import ( CONF_GENERATION, CONF_SERIAL_NUMBER, DOMAIN, ) from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_HOST, CONF_MODEL from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from .conftest import TEST_DEVICE_SN_GEN2, TEST_HOST from tests.common import MockConfigEntry async def test_user_flow_success( hass: HomeAssistant, mock_indevolt: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Test successful user-initiated config flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {"host": TEST_HOST} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "INDEVOLT CMS-SF2000" assert result["data"] == { CONF_HOST: TEST_HOST, CONF_SERIAL_NUMBER: TEST_DEVICE_SN_GEN2, CONF_MODEL: "CMS-SF2000", CONF_GENERATION: 2, } assert result["result"].unique_id == TEST_DEVICE_SN_GEN2 @pytest.mark.parametrize( ("exception", "expected_error"), [ (TimeoutError, "timeout"), (ConnectionError, "cannot_connect"), (ClientError, "cannot_connect"), (Exception("Some unknown error"), "unknown"), ], ) async def test_user_flow_error( hass: HomeAssistant, mock_indevolt: AsyncMock, mock_setup_entry: AsyncMock, exception: Exception, expected_error: str, ) -> None: """Test connection errors in user flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) # Configure mock to raise exception mock_indevolt.get_config.side_effect = exception result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: TEST_HOST} ) assert result["type"] is FlowResultType.FORM assert result["errors"]["base"] == expected_error # Test recovery by patching the library to work mock_indevolt.get_config.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: TEST_HOST} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "INDEVOLT CMS-SF2000" async def test_user_flow_duplicate_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_indevolt: AsyncMock ) -> None: """Test duplicate entry aborts the flow.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) # Test duplicate entry creation result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: TEST_HOST} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/indevolt/test_config_flow.py", "license": "Apache License 2.0", "lines": 84, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/indevolt/test_init.py
"""Tests for the Indevolt integration initialization and services.""" from unittest.mock import AsyncMock from indevolt_api import TimeOutException import pytest from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from . import setup_integration from tests.common import MockConfigEntry @pytest.mark.parametrize("generation", [2], indirect=True) async def test_load_unload( hass: HomeAssistant, mock_indevolt: AsyncMock, mock_config_entry: MockConfigEntry ) -> None: """Test setting up and removing a config entry.""" await setup_integration(hass, mock_config_entry) # Verify the config entry is successfully loaded assert mock_config_entry.state is ConfigEntryState.LOADED # Unload the integration await hass.config_entries.async_unload(mock_config_entry.entry_id) await hass.async_block_till_done() # Verify the config entry is properly unloaded assert mock_config_entry.state is ConfigEntryState.NOT_LOADED @pytest.mark.parametrize("generation", [2], indirect=True) async def test_load_failure( hass: HomeAssistant, mock_indevolt: AsyncMock, mock_config_entry: MockConfigEntry ) -> None: """Test setup failure when coordinator update fails.""" # Simulate timeout error during coordinator initialization mock_indevolt.get_config.side_effect = TimeOutException mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Verify the config entry enters retry state due to failure assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
{ "repo_id": "home-assistant/core", "file_path": "tests/components/indevolt/test_init.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/indevolt/test_sensor.py
"""Tests for the Indevolt sensor platform.""" from datetime import timedelta from unittest.mock import AsyncMock, patch from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.indevolt.coordinator import SCAN_INTERVAL from homeassistant.const import STATE_UNAVAILABLE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.mark.usefixtures("entity_registry_enabled_by_default") @pytest.mark.parametrize("generation", [2, 1], indirect=True) async def test_sensor( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_indevolt: AsyncMock, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, ) -> None: """Test sensor registration for sensors.""" with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.SENSOR]): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.parametrize("generation", [2], indirect=True) async def test_sensor_availability( hass: HomeAssistant, mock_indevolt: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test sensor availability / non-availability.""" with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.SENSOR]): await setup_integration(hass, mock_config_entry) assert (state := hass.states.get("sensor.cms_sf2000_battery_soc")) assert state.state == "92" mock_indevolt.fetch_data.side_effect = ConnectionError freezer.tick(delta=timedelta(seconds=SCAN_INTERVAL)) async_fire_time_changed(hass) await hass.async_block_till_done() assert (state := hass.states.get("sensor.cms_sf2000_battery_soc")) assert state.state == STATE_UNAVAILABLE # In individual tests, you can override the mock behavior async def test_battery_pack_filtering( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_indevolt: AsyncMock, entity_registry: er.EntityRegistry, ) -> None: """Test that battery pack sensors are filtered based on SN availability.""" # Mock battery pack data - only first two packs have SNs mock_indevolt.fetch_data.return_value = { "9032": "BAT001", "9051": "BAT002", "9070": None, "9165": "", "9218": None, } mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Get all sensor entities entity_entries = er.async_entries_for_config_entry( entity_registry, mock_config_entry.entry_id ) # Verify sensors for packs 1 and 2 exist (with SNs) pack1_sensors = [ e for e in entity_entries if any(key in e.unique_id for key in ("9032", "9016", "9030", "9020", "19173")) ] pack2_sensors = [ e for e in entity_entries if any(key in e.unique_id for key in ("9051", "9035", "9049", "9039", "19174")) ] assert len(pack1_sensors) == 5 assert len(pack2_sensors) == 5 # Verify sensors for packs 3, 4, and 5 don't exist (no SNs) pack3_sensors = [ e for e in entity_entries if any(key in e.unique_id for key in ("9070", "9054", "9068", "9058", "19175")) ] pack4_sensors = [ e for e in entity_entries if any(key in e.unique_id for key in ("9165", "9149", "9163", "9153", "19176")) ] pack5_sensors = [ e for e in entity_entries if any(key in e.unique_id for key in ("9218", "9202", "9216", "9206", "19177")) ] assert len(pack3_sensors) == 0 assert len(pack4_sensors) == 0 assert len(pack5_sensors) == 0 async def test_battery_pack_filtering_fetch_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_indevolt: AsyncMock, entity_registry: er.EntityRegistry, caplog: pytest.LogCaptureFixture, ) -> None: """Test battery pack filtering when fetch fails.""" # Mock fetch_data to raise error on battery pack SN fetch mock_indevolt.fetch_data.side_effect = HomeAssistantError("Timeout") mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Get all sensor entities entity_entries = er.async_entries_for_config_entry( entity_registry, mock_config_entry.entry_id ) # Verify sensors (no sensors) battery_pack_keys = [ "9032", "9051", "9070", "9165", "9218", "9016", "9035", "9054", "9149", "9202", ] battery_sensors = [ e for e in entity_entries if any(key in e.unique_id for key in battery_pack_keys) ] assert len(battery_sensors) == 0
{ "repo_id": "home-assistant/core", "file_path": "tests/components/indevolt/test_sensor.py", "license": "Apache License 2.0", "lines": 135, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/satel_integra/client.py
"""Satel Integra client.""" from collections.abc import Callable from satel_integra.satel_integra import AsyncSatel from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_PORT, EVENT_HOMEASSISTANT_STOP from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryNotReady from .const import ( CONF_OUTPUT_NUMBER, CONF_PARTITION_NUMBER, CONF_SWITCHABLE_OUTPUT_NUMBER, CONF_ZONE_NUMBER, SUBENTRY_TYPE_OUTPUT, SUBENTRY_TYPE_PARTITION, SUBENTRY_TYPE_SWITCHABLE_OUTPUT, SUBENTRY_TYPE_ZONE, ) class SatelClient: """Client to connect to Satel Integra.""" controller: AsyncSatel def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize the client wrapper.""" self.hass = hass self.config_entry = entry host = entry.data[CONF_HOST] port = entry.data[CONF_PORT] # Make sure we initialize the Satel controller with the configured entries to monitor partitions = [ subentry.data[CONF_PARTITION_NUMBER] for subentry in entry.subentries.values() if subentry.subentry_type == SUBENTRY_TYPE_PARTITION ] zones = [ subentry.data[CONF_ZONE_NUMBER] for subentry in entry.subentries.values() if subentry.subentry_type == SUBENTRY_TYPE_ZONE ] outputs = [ subentry.data[CONF_OUTPUT_NUMBER] for subentry in entry.subentries.values() if subentry.subentry_type == SUBENTRY_TYPE_OUTPUT ] switchable_outputs = [ subentry.data[CONF_SWITCHABLE_OUTPUT_NUMBER] for subentry in entry.subentries.values() if subentry.subentry_type == SUBENTRY_TYPE_SWITCHABLE_OUTPUT ] monitored_outputs = outputs + switchable_outputs self.controller = AsyncSatel( host, port, hass.loop, zones, monitored_outputs, partitions ) entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.close) ) async def async_connect( self, zones_update_callback: Callable[[dict[str, dict[int, int]]], None], outputs_update_callback: Callable[[dict[str, dict[int, int]]], None], partitions_update_callback: Callable[[], None], ) -> None: """Start controller connection.""" result = await self.controller.connect() if not result: raise ConfigEntryNotReady("Controller failed to connect") self.config_entry.async_create_background_task( self.hass, self.controller.keep_alive(), f"satel_integra.{self.config_entry.entry_id}.keep_alive", eager_start=False, ) self.config_entry.async_create_background_task( self.hass, self.controller.monitor_status( partitions_update_callback, zones_update_callback, outputs_update_callback, ), f"satel_integra.{self.config_entry.entry_id}.monitor_status", eager_start=False, ) @callback def close(self, *args, **kwargs) -> None: """Close the connection.""" self.controller.close()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/satel_integra/client.py", "license": "Apache License 2.0", "lines": 84, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/satel_integra/coordinator.py
"""Coordinator for Satel Integra.""" from __future__ import annotations from dataclasses import dataclass import logging from satel_integra.satel_integra import AlarmState from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.debounce import Debouncer from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from .client import SatelClient from .const import ZONES _LOGGER = logging.getLogger(__name__) PARTITION_UPDATE_DEBOUNCE_DELAY = 0.15 @dataclass class SatelIntegraData: """Data for the satel_integra integration.""" client: SatelClient coordinator_zones: SatelIntegraZonesCoordinator coordinator_outputs: SatelIntegraOutputsCoordinator coordinator_partitions: SatelIntegraPartitionsCoordinator type SatelConfigEntry = ConfigEntry[SatelIntegraData] class SatelIntegraBaseCoordinator[_DataT](DataUpdateCoordinator[_DataT]): """DataUpdateCoordinator base class for Satel Integra.""" config_entry: SatelConfigEntry def __init__( self, hass: HomeAssistant, entry: SatelConfigEntry, client: SatelClient ) -> None: """Initialize the base coordinator.""" self.client = client super().__init__( hass, _LOGGER, config_entry=entry, name=f"{entry.entry_id} {self.__class__.__name__}", ) class SatelIntegraZonesCoordinator(SatelIntegraBaseCoordinator[dict[int, bool]]): """DataUpdateCoordinator to handle zone updates.""" def __init__( self, hass: HomeAssistant, entry: SatelConfigEntry, client: SatelClient ) -> None: """Initialize the coordinator.""" super().__init__(hass, entry, client) self.data = {} @callback def zones_update_callback(self, status: dict[str, dict[int, int]]) -> None: """Update zone objects as per notification from the alarm.""" _LOGGER.debug("Zones callback, status: %s", status) update_data = {zone: value == 1 for zone, value in status[ZONES].items()} self.async_set_updated_data(update_data) class SatelIntegraOutputsCoordinator(SatelIntegraBaseCoordinator[dict[int, bool]]): """DataUpdateCoordinator to handle output updates.""" def __init__( self, hass: HomeAssistant, entry: SatelConfigEntry, client: SatelClient ) -> None: """Initialize the coordinator.""" super().__init__(hass, entry, client) self.data = {} @callback def outputs_update_callback(self, status: dict[str, dict[int, int]]) -> None: """Update output objects as per notification from the alarm.""" _LOGGER.debug("Outputs callback, status: %s", status) update_data = { output: value == 1 for output, value in status["outputs"].items() } self.async_set_updated_data(update_data) class SatelIntegraPartitionsCoordinator( SatelIntegraBaseCoordinator[dict[AlarmState, list[int]]] ): """DataUpdateCoordinator to handle partition state updates.""" def __init__( self, hass: HomeAssistant, entry: SatelConfigEntry, client: SatelClient ) -> None: """Initialize the coordinator.""" super().__init__(hass, entry, client) self.data = {} self._debouncer = Debouncer( hass=self.hass, logger=_LOGGER, cooldown=PARTITION_UPDATE_DEBOUNCE_DELAY, immediate=False, function=callback( lambda: self.async_set_updated_data( self.client.controller.partition_states ) ), ) @callback def partitions_update_callback(self) -> None: """Update partition objects as per notification from the alarm.""" _LOGGER.debug("Sending request to update panel state") self._debouncer.async_schedule_call()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/satel_integra/coordinator.py", "license": "Apache License 2.0", "lines": 91, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/watts/diagnostics.py
"""Diagnostics support for Watts Vision +.""" from __future__ import annotations import dataclasses from datetime import datetime from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import CONF_ACCESS_TOKEN from homeassistant.core import HomeAssistant from . import WattsVisionConfigEntry TO_REDACT = ("refresh_token", "id_token", "profile_info", "unique_id") async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: WattsVisionConfigEntry, ) -> dict[str, Any]: """Return diagnostics for a config entry.""" runtime_data = entry.runtime_data hub_coordinator = runtime_data.hub_coordinator device_coordinators = runtime_data.device_coordinators now = datetime.now() return async_redact_data( { "entry": entry.as_dict(), "hub_coordinator": { "last_update_success": hub_coordinator.last_update_success, "last_exception": ( str(hub_coordinator.last_exception) if hub_coordinator.last_exception else None ), "last_discovery": ( hub_coordinator.last_discovery.isoformat() if hub_coordinator.last_discovery else None ), "total_devices": len(hub_coordinator.data), "supported_devices": len(device_coordinators), }, "hub_data": { device_id: dataclasses.asdict(device) for device_id, device in hub_coordinator.data.items() }, "devices": { device_id: { "device": dataclasses.asdict(coordinator.data.device), "last_update_success": coordinator.last_update_success, "fast_polling_active": ( coordinator.fast_polling_until is not None and coordinator.fast_polling_until > now ), "fast_polling_until": ( coordinator.fast_polling_until.isoformat() if coordinator.fast_polling_until is not None and coordinator.fast_polling_until > now else None ), } for device_id, coordinator in device_coordinators.items() }, }, {CONF_ACCESS_TOKEN, *TO_REDACT}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/watts/diagnostics.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/watts/test_diagnostics.py
"""Tests for the diagnostics data provided by the Watts Vision + integration.""" from unittest.mock import AsyncMock import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.core import HomeAssistant from . import setup_integration from tests.common import MockConfigEntry from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.typing import ClientSessionGenerator @pytest.mark.freeze_time("2026-01-01T12:00:00") async def test_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_config_entry: MockConfigEntry, mock_watts_client: AsyncMock, snapshot: SnapshotAssertion, ) -> None: """Test diagnostics.""" await setup_integration(hass, mock_config_entry) assert ( await get_diagnostics_for_config_entry(hass, hass_client, mock_config_entry) == snapshot )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/watts/test_diagnostics.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/hypontech/config_flow.py
"""Config flow for the Hypontech Cloud integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from hyponcloud import AuthenticationError, HyponCloud import voluptuous as vol from homeassistant.config_entries import SOURCE_USER, ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, } ) class HypontechConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Hypontech Cloud.""" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: session = async_get_clientsession(self.hass) hypon = HyponCloud( user_input[CONF_USERNAME], user_input[CONF_PASSWORD], session ) try: await hypon.connect() admin_info = await hypon.get_admin_info() except AuthenticationError: errors["base"] = "invalid_auth" except TimeoutError, ConnectionError: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: await self.async_set_unique_id(admin_info.id) if self.source == SOURCE_USER: self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_USERNAME], data=user_input, ) self._abort_if_unique_id_mismatch(reason="wrong_account") return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates={ CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], }, ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle reauthentication.""" return await self.async_step_user()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hypontech/config_flow.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hypontech/coordinator.py
"""The coordinator for Hypontech Cloud integration.""" from __future__ import annotations from dataclasses import dataclass from datetime import timedelta from hyponcloud import HyponCloud, OverviewData, PlantData, RequestError from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN, LOGGER @dataclass class HypontechCoordinatorData: """Store coordinator data.""" overview: OverviewData plants: dict[str, PlantData] type HypontechConfigEntry = ConfigEntry[HypontechDataCoordinator] class HypontechDataCoordinator(DataUpdateCoordinator[HypontechCoordinatorData]): """Coordinator used for all sensors.""" config_entry: HypontechConfigEntry def __init__( self, hass: HomeAssistant, config_entry: HypontechConfigEntry, api: HyponCloud, account_id: str, ) -> None: """Initialize my coordinator.""" super().__init__( hass, LOGGER, config_entry=config_entry, name="Hypontech Data", update_interval=timedelta(seconds=60), ) self.api = api self.account_id = account_id async def _async_update_data(self) -> HypontechCoordinatorData: try: overview = await self.api.get_overview() plants = await self.api.get_list() except RequestError as ex: raise UpdateFailed( translation_domain=DOMAIN, translation_key="connection_error" ) from ex return HypontechCoordinatorData( overview=overview, plants={plant.plant_id: plant for plant in plants}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hypontech/coordinator.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hypontech/entity.py
"""Base entity for the Hypontech Cloud integration.""" from __future__ import annotations from hyponcloud import PlantData from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import HypontechDataCoordinator class HypontechEntity(CoordinatorEntity[HypontechDataCoordinator]): """Base entity for Hypontech Cloud.""" _attr_has_entity_name = True def __init__(self, coordinator: HypontechDataCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, coordinator.account_id)}, name="Overview", manufacturer="Hypontech", ) class HypontechPlantEntity(CoordinatorEntity[HypontechDataCoordinator]): """Base entity for Hypontech Cloud plant.""" _attr_has_entity_name = True def __init__(self, coordinator: HypontechDataCoordinator, plant_id: str) -> None: """Initialize the entity.""" super().__init__(coordinator) self.plant_id = plant_id plant = coordinator.data.plants[plant_id] self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, plant_id)}, name=plant.plant_name, manufacturer="Hypontech", ) @property def plant(self) -> PlantData: """Return the plant data.""" return self.coordinator.data.plants[self.plant_id] @property def available(self) -> bool: """Return if entity is available.""" return super().available and self.plant_id in self.coordinator.data.plants
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hypontech/entity.py", "license": "Apache License 2.0", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hypontech/sensor.py
"""The read-only sensors for Hypontech integration.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from hyponcloud import OverviewData, PlantData from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import UnitOfEnergy, UnitOfPower from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import HypontechConfigEntry, HypontechDataCoordinator from .entity import HypontechEntity, HypontechPlantEntity @dataclass(frozen=True, kw_only=True) class HypontechSensorDescription(SensorEntityDescription): """Describes Hypontech overview sensor entity.""" value_fn: Callable[[OverviewData], float | None] @dataclass(frozen=True, kw_only=True) class HypontechPlantSensorDescription(SensorEntityDescription): """Describes Hypontech plant sensor entity.""" value_fn: Callable[[PlantData], float | None] OVERVIEW_SENSORS: tuple[HypontechSensorDescription, ...] = ( HypontechSensorDescription( key="pv_power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda c: c.power, ), HypontechSensorDescription( key="lifetime_energy", translation_key="lifetime_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, value_fn=lambda c: c.e_total, ), HypontechSensorDescription( key="today_energy", translation_key="today_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, value_fn=lambda c: c.e_today, ), ) PLANT_SENSORS: tuple[HypontechPlantSensorDescription, ...] = ( HypontechPlantSensorDescription( key="pv_power", native_unit_of_measurement=UnitOfPower.WATT, device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda c: c.power, ), HypontechPlantSensorDescription( key="lifetime_energy", translation_key="lifetime_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, value_fn=lambda c: c.e_total, ), HypontechPlantSensorDescription( key="today_energy", translation_key="today_energy", native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, value_fn=lambda c: c.e_today, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: HypontechConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the sensor platform.""" coordinator = config_entry.runtime_data entities: list[SensorEntity] = [ HypontechOverviewSensor(coordinator, desc) for desc in OVERVIEW_SENSORS ] entities.extend( HypontechPlantSensor(coordinator, plant_id, desc) for plant_id in coordinator.data.plants for desc in PLANT_SENSORS ) async_add_entities(entities) class HypontechOverviewSensor(HypontechEntity, SensorEntity): """Class describing Hypontech overview sensor entities.""" entity_description: HypontechSensorDescription def __init__( self, coordinator: HypontechDataCoordinator, description: HypontechSensorDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.account_id}_{description.key}" @property def native_value(self) -> float | None: """Return the state of the sensor.""" return self.entity_description.value_fn(self.coordinator.data.overview) class HypontechPlantSensor(HypontechPlantEntity, SensorEntity): """Class describing Hypontech plant sensor entities.""" entity_description: HypontechPlantSensorDescription def __init__( self, coordinator: HypontechDataCoordinator, plant_id: str, description: HypontechPlantSensorDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator, plant_id) self.entity_description = description self._attr_unique_id = f"{plant_id}_{description.key}" @property def native_value(self) -> float | None: """Return the state of the sensor.""" return self.entity_description.value_fn(self.plant)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hypontech/sensor.py", "license": "Apache License 2.0", "lines": 123, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/hypontech/test_config_flow.py
"""Test the Hypontech Cloud config flow.""" from unittest.mock import AsyncMock from hyponcloud import AuthenticationError import pytest from homeassistant.components.hypontech.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry TEST_USER_INPUT = { CONF_USERNAME: "test@example.com", CONF_PASSWORD: "test-password", } async def test_user_flow( hass: HomeAssistant, mock_hyponcloud: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Test a successful user flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], TEST_USER_INPUT ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "test@example.com" assert result["data"] == TEST_USER_INPUT assert result["result"].unique_id == "2123456789123456789" assert len(mock_setup_entry.mock_calls) == 1 @pytest.mark.parametrize( ("side_effect", "error_message"), [ (AuthenticationError, "invalid_auth"), (ConnectionError, "cannot_connect"), (TimeoutError, "cannot_connect"), (Exception, "unknown"), ], ) @pytest.mark.usefixtures("mock_setup_entry") async def test_form_errors( hass: HomeAssistant, mock_hyponcloud: AsyncMock, side_effect: Exception, error_message: str, ) -> None: """Test we handle errors.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) mock_hyponcloud.connect.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], TEST_USER_INPUT ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": error_message} mock_hyponcloud.connect.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], TEST_USER_INPUT, ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_duplicate_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hyponcloud: AsyncMock ) -> None: """Test that duplicate entries are prevented based on account ID.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], TEST_USER_INPUT ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_reauth_flow( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hyponcloud: AsyncMock ) -> None: """Test reauthentication flow.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {**TEST_USER_INPUT, CONF_PASSWORD: "password"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data[CONF_PASSWORD] == "password" @pytest.mark.parametrize( ("side_effect", "error_message"), [ (AuthenticationError, "invalid_auth"), (ConnectionError, "cannot_connect"), (TimeoutError, "cannot_connect"), (Exception, "unknown"), ], ) async def test_reauth_flow_errors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hyponcloud: AsyncMock, side_effect: Exception, error_message: str, ) -> None: """Test reauthentication flow with errors.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" mock_hyponcloud.connect.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], {**TEST_USER_INPUT, CONF_PASSWORD: "new-password"}, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": error_message} mock_hyponcloud.connect.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {**TEST_USER_INPUT, CONF_PASSWORD: "new-password"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" async def test_reauth_flow_wrong_account( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hyponcloud: AsyncMock ) -> None: """Test reauthentication flow with wrong account.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" mock_hyponcloud.get_admin_info.return_value.id = "different_account_id_456" result = await hass.config_entries.flow.async_configure( result["flow_id"], {**TEST_USER_INPUT, CONF_USERNAME: "different@example.com"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "wrong_account"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/hypontech/test_config_flow.py", "license": "Apache License 2.0", "lines": 141, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/hypontech/test_init.py
"""Test the Hypontech Cloud init.""" from unittest.mock import AsyncMock from hyponcloud import AuthenticationError, RequestError import pytest from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from . import setup_integration from tests.common import MockConfigEntry @pytest.mark.parametrize( ("side_effect", "expected_state"), [ (TimeoutError, ConfigEntryState.SETUP_RETRY), (AuthenticationError, ConfigEntryState.SETUP_ERROR), (RequestError, ConfigEntryState.SETUP_RETRY), ], ) async def test_setup_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hyponcloud: AsyncMock, side_effect: Exception, expected_state: ConfigEntryState, ) -> None: """Test setup entry with timeout error.""" mock_hyponcloud.connect.side_effect = side_effect await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is expected_state async def test_setup_and_unload_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hyponcloud: AsyncMock, ) -> None: """Test setup and unload of config entry.""" await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED await hass.config_entries.async_unload(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
{ "repo_id": "home-assistant/core", "file_path": "tests/components/hypontech/test_init.py", "license": "Apache License 2.0", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/hypontech/test_sensor.py
"""Tests for Hypontech sensors.""" from unittest.mock import AsyncMock, patch from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, snapshot_platform async def test_sensors( hass: HomeAssistant, mock_hyponcloud: AsyncMock, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, ) -> None: """Test the Hypontech sensors.""" with patch("homeassistant.components.hypontech._PLATFORMS", [Platform.SENSOR]): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/hypontech/test_sensor.py", "license": "Apache License 2.0", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/advantage_air/coordinator.py
"""Coordinator for the Advantage Air integration.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from advantage_air import ApiError, advantage_air from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.debounce import Debouncer from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN ADVANTAGE_AIR_SYNC_INTERVAL = 15 REQUEST_REFRESH_DELAY = 0.5 _LOGGER = logging.getLogger(__name__) type AdvantageAirDataConfigEntry = ConfigEntry[AdvantageAirCoordinator] class AdvantageAirCoordinator(DataUpdateCoordinator[dict[str, Any]]): """Advantage Air coordinator.""" config_entry: AdvantageAirDataConfigEntry def __init__( self, hass: HomeAssistant, config_entry: AdvantageAirDataConfigEntry, api: advantage_air, ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name="Advantage Air", update_interval=timedelta(seconds=ADVANTAGE_AIR_SYNC_INTERVAL), request_refresh_debouncer=Debouncer( hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False ), ) self.api = api async def _async_update_data(self) -> dict[str, Any]: """Fetch data from the API.""" try: return await self.api.async_get() except ApiError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_failed", translation_placeholders={"error": str(err)}, ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/advantage_air/coordinator.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/switchbot/select.py
"""Select platform for SwitchBot.""" from __future__ import annotations from datetime import timedelta import logging import switchbot from switchbot.devices.device import SwitchbotOperationError from homeassistant.components.select import SelectEntity from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import SwitchbotConfigEntry, SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity, exception_handler _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(days=7) TIME_FORMAT_12H = "12h" TIME_FORMAT_24H = "24h" TIME_FORMAT_OPTIONS = [TIME_FORMAT_12H, TIME_FORMAT_24H] async def async_setup_entry( hass: HomeAssistant, entry: SwitchbotConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up SwitchBot select platform.""" coordinator = entry.runtime_data if isinstance(coordinator.device, switchbot.SwitchbotMeterProCO2): async_add_entities([SwitchBotMeterProCO2TimeFormatSelect(coordinator)], True) class SwitchBotMeterProCO2TimeFormatSelect(SwitchbotEntity, SelectEntity): """Select entity to set time display format on Meter Pro CO2.""" _attr_should_poll = True _attr_entity_registry_enabled_default = False _device: switchbot.SwitchbotMeterProCO2 _attr_entity_category = EntityCategory.CONFIG _attr_translation_key = "time_format" _attr_options = TIME_FORMAT_OPTIONS def __init__(self, coordinator: SwitchbotDataUpdateCoordinator) -> None: """Initialize the select entity.""" super().__init__(coordinator) self._attr_unique_id = f"{coordinator.base_unique_id}_time_format" @exception_handler async def async_select_option(self, option: str) -> None: """Change the time display format.""" _LOGGER.debug("Setting time format to %s for %s", option, self._address) is_12h_mode = option == TIME_FORMAT_12H await self._device.set_time_display_format(is_12h_mode) self._attr_current_option = option self.async_write_ha_state() async def async_update(self) -> None: """Fetch the latest time format from the device.""" try: device_time = await self._device.get_datetime() except SwitchbotOperationError: _LOGGER.debug( "Failed to update time format for %s", self._address, exc_info=True ) return self._attr_current_option = ( TIME_FORMAT_12H if device_time["12h_mode"] else TIME_FORMAT_24H )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/switchbot/select.py", "license": "Apache License 2.0", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/switchbot/test_select.py
"""Tests for the switchbot select platform.""" from collections.abc import Callable from unittest.mock import AsyncMock, patch import pytest from homeassistant.components.select import ( ATTR_OPTION, DOMAIN as SELECT_DOMAIN, SERVICE_SELECT_OPTION, ) from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from . import DOMAIN, WOMETERTHPC_SERVICE_INFO from tests.common import MockConfigEntry from tests.components.bluetooth import inject_bluetooth_service_info @pytest.mark.parametrize( ("mode", "expected_state"), [ (False, "24h"), (True, "12h"), ], ) @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_time_format_select_initial_state( hass: HomeAssistant, mock_entry_factory: Callable[[str], MockConfigEntry], mode: bool, expected_state: str, ) -> None: """Test the time format select entity initial state.""" await async_setup_component(hass, DOMAIN, {}) inject_bluetooth_service_info(hass, WOMETERTHPC_SERVICE_INFO) entry = mock_entry_factory("hygrometer_co2") entry.add_to_hass(hass) with patch( "switchbot.SwitchbotMeterProCO2.get_datetime", return_value={ "12h_mode": mode, "year": 2025, "month": 1, "day": 9, "hour": 12, "minute": 0, "second": 0, }, ): assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() state = hass.states.get("select.test_name_time_format") assert state is not None assert state.state == expected_state @pytest.mark.usefixtures("entity_registry_enabled_by_default") @pytest.mark.parametrize( ("origin_mode", "expected_state"), [ (False, "24h"), (True, "12h"), ], ) async def test_set_time_format( hass: HomeAssistant, mock_entry_factory: Callable[[str], MockConfigEntry], origin_mode: bool, expected_state: str, ) -> None: """Test changing time format to 12h.""" await async_setup_component(hass, DOMAIN, {}) inject_bluetooth_service_info(hass, WOMETERTHPC_SERVICE_INFO) entry = mock_entry_factory("hygrometer_co2") entry.add_to_hass(hass) mock_get_datetime = AsyncMock( return_value={ "12h_mode": origin_mode, "year": 2025, "month": 1, "day": 9, "hour": 12, "minute": 0, "second": 0, } ) mock_set_time_display_format = AsyncMock(return_value=True) with ( patch( "switchbot.SwitchbotMeterProCO2.get_datetime", mock_get_datetime, ), patch( "switchbot.SwitchbotMeterProCO2.set_time_display_format", mock_set_time_display_format, ), ): assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.test_name_time_format", ATTR_OPTION: expected_state, }, blocking=True, ) mock_set_time_display_format.assert_awaited_once_with(origin_mode) state = hass.states.get("select.test_name_time_format") assert state is not None assert state.state == expected_state
{ "repo_id": "home-assistant/core", "file_path": "tests/components/switchbot/test_select.py", "license": "Apache License 2.0", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/tplink_omada/test_update.py
"""Tests for TP-Link Omada update entities.""" from datetime import timedelta from unittest.mock import AsyncMock, MagicMock, patch from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from tplink_omada_client.devices import OmadaListDevice from tplink_omada_client.exceptions import OmadaClientException, RequestFailed from homeassistant.components.tplink_omada.coordinator import POLL_DEVICES from homeassistant.components.update import ( ATTR_IN_PROGRESS, DOMAIN as UPDATE_DOMAIN, SERVICE_INSTALL, ) from homeassistant.const import ATTR_ENTITY_ID, STATE_ON, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from tests.common import ( MockConfigEntry, async_fire_time_changed, async_load_json_array_fixture, snapshot_platform, ) from tests.typing import WebSocketGenerator POLL_INTERVAL = timedelta(seconds=POLL_DEVICES) async def _rebuild_device_list_with_update( hass: HomeAssistant, mac: str, **overrides ) -> list[OmadaListDevice]: """Rebuild device list from fixture with specified overrides for a device.""" devices_data = await async_load_json_array_fixture( hass, "devices.json", "tplink_omada" ) for device_data in devices_data: if device_data["mac"] == mac: device_data.update(overrides) return [OmadaListDevice(d) for d in devices_data] @pytest.fixture async def init_integration( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_omada_client: MagicMock, ) -> MockConfigEntry: """Set up the TP-Link Omada integration for testing.""" mock_config_entry.add_to_hass(hass) with patch("homeassistant.components.tplink_omada.PLATFORMS", [Platform.UPDATE]): assert await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() return mock_config_entry async def test_entities( hass: HomeAssistant, entity_registry: er.EntityRegistry, init_integration: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test the creation of the TP-Link Omada update entities.""" await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id) async def test_firmware_download_in_progress( hass: HomeAssistant, init_integration: MockConfigEntry, mock_omada_site_client: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test update entity when firmware download is in progress.""" entity_id = "update.test_poe_switch_firmware" freezer.tick(POLL_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() # Rebuild device list with fwDownload set to True for the switch updated_devices = await _rebuild_device_list_with_update( hass, "54-AF-97-00-00-01", fwDownload=True ) mock_omada_site_client.get_devices.return_value = updated_devices # Trigger coordinator update freezer.tick(POLL_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() # Verify update entity shows in progress entity = hass.states.get(entity_id) assert entity is not None assert entity.attributes.get(ATTR_IN_PROGRESS) is True async def test_install_firmware_success( hass: HomeAssistant, init_integration: MockConfigEntry, mock_omada_site_client: MagicMock, ) -> None: """Test successful firmware installation.""" entity_id = "update.test_poe_switch_firmware" # Verify update is available entity = hass.states.get(entity_id) assert entity is not None assert entity.state == STATE_ON # Call install service await hass.services.async_call( UPDATE_DOMAIN, SERVICE_INSTALL, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() # Verify start_firmware_upgrade was called with the correct device mock_omada_site_client.start_firmware_upgrade.assert_awaited_once() await_args = mock_omada_site_client.start_firmware_upgrade.await_args[0] assert await_args[0].mac == "54-AF-97-00-00-01" @pytest.mark.parametrize( ("exception_type", "error_message"), [ ( RequestFailed(500, "Update rejected"), "Firmware update request rejected", ), ( OmadaClientException("Connection error"), "Unable to send Firmware update request. Check the controller is online.", ), ], ) async def test_install_firmware_exceptions( hass: HomeAssistant, init_integration: MockConfigEntry, mock_omada_site_client: MagicMock, exception_type: Exception, error_message: str, ) -> None: """Test firmware installation exception handling.""" entity_id = "update.test_poe_switch_firmware" # Mock exception mock_omada_site_client.start_firmware_upgrade = AsyncMock( side_effect=exception_type ) # Call install service and expect error with pytest.raises( HomeAssistantError, match=error_message, ): await hass.services.async_call( UPDATE_DOMAIN, SERVICE_INSTALL, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) @pytest.mark.parametrize( ("entity_name", "expected_notes"), [ ("test_router", None), ("test_poe_switch", "Bug fixes and performance improvements"), ], ) async def test_release_notes( hass: HomeAssistant, init_integration: MockConfigEntry, hass_ws_client: WebSocketGenerator, entity_name: str, expected_notes: str | None, ) -> None: """Test that release notes are available via websocket.""" entity_id = f"update.{entity_name}_firmware" # Get release notes via websocket client = await hass_ws_client(hass) await hass.async_block_till_done() await client.send_json( { "id": 1, "type": "update/release_notes", "entity_id": entity_id, } ) result = await client.receive_json() assert expected_notes == result["result"]
{ "repo_id": "home-assistant/core", "file_path": "tests/components/tplink_omada/test_update.py", "license": "Apache License 2.0", "lines": 169, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/daikin/test_zone_climate.py
"""Tests for Daikin zone climate entities.""" from __future__ import annotations from unittest.mock import AsyncMock import pytest from homeassistant.components.climate import ( ATTR_HVAC_ACTION, ATTR_HVAC_MODE, ATTR_HVAC_MODES, ATTR_MAX_TEMP, ATTR_MIN_TEMP, DOMAIN as CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, SERVICE_SET_TEMPERATURE, HVACAction, HVACMode, ) from homeassistant.components.daikin.const import DOMAIN, KEY_MAC from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_TEMPERATURE, CONF_HOST, STATE_UNAVAILABLE, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_component import async_update_entity from .conftest import ZoneDevice, configure_zone_device from tests.common import MockConfigEntry HOST = "127.0.0.1" async def _async_setup_daikin( hass: HomeAssistant, zone_device: ZoneDevice ) -> MockConfigEntry: """Set up a Daikin config entry with a mocked library device.""" config_entry = MockConfigEntry( domain=DOMAIN, unique_id=zone_device.mac, data={CONF_HOST: HOST, KEY_MAC: zone_device.mac}, ) config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return config_entry def _zone_entity_id( entity_registry: er.EntityRegistry, zone_device: ZoneDevice, zone_id: int ) -> str | None: """Return the entity id for a zone climate unique id.""" return entity_registry.async_get_entity_id( CLIMATE_DOMAIN, DOMAIN, f"{zone_device.mac}-zone{zone_id}-temperature", ) async def _async_set_zone_temperature( hass: HomeAssistant, entity_id: str, temperature: float ) -> None: """Call `climate.set_temperature` for a zone climate.""" await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, { ATTR_ENTITY_ID: entity_id, ATTR_TEMPERATURE: temperature, }, blocking=True, ) async def test_setup_entry_adds_zone_climates( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Configured zones create zone climate entities.""" configure_zone_device( zone_device, zones=[["-", "0", 0], ["Living", "1", 22], ["Office", "1", 21]] ) await _async_setup_daikin(hass, zone_device) assert _zone_entity_id(entity_registry, zone_device, 0) is None assert _zone_entity_id(entity_registry, zone_device, 1) is not None assert _zone_entity_id(entity_registry, zone_device, 2) is not None async def test_setup_entry_skips_zone_climates_without_support( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Missing zone temperature lists skip zone climate entities.""" configure_zone_device(zone_device, zones=[["Living", "1", 22]]) zone_device.values["lztemp_h"] = "" zone_device.values["lztemp_c"] = "" await _async_setup_daikin(hass, zone_device) assert _zone_entity_id(entity_registry, zone_device, 0) is None async def test_setup_entry_handles_missing_zone_temperature_key( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Missing zone temperature keys do not break climate setup.""" configure_zone_device(zone_device, zones=[["Living", "1", 22]]) zone_device.values.pop("lztemp_h") await _async_setup_daikin(hass, zone_device) assert _zone_entity_id(entity_registry, zone_device, 0) is None main_entity_id = entity_registry.async_get_entity_id( CLIMATE_DOMAIN, DOMAIN, zone_device.mac, ) assert main_entity_id is not None assert hass.states.get(main_entity_id) is not None @pytest.mark.parametrize( ("mode", "expected_zone_key"), [("hot", "lztemp_h"), ("cool", "lztemp_c")], ) async def test_zone_climate_sets_temperature_for_active_mode( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, mode: str, expected_zone_key: str, ) -> None: """Setting temperature updates the active mode zone value.""" configure_zone_device( zone_device, zones=[["Living", "1", 22], ["Office", "1", 21]], mode=mode, ) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None await _async_set_zone_temperature(hass, entity_id, 23) zone_device.set_zone.assert_awaited_once_with(0, expected_zone_key, "23") async def test_zone_climate_rejects_out_of_range_temperature( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Service validation rejects values outside the allowed range.""" configure_zone_device( zone_device, zones=[["Living", "1", 22]], target_temperature=22, ) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None with pytest.raises(ServiceValidationError) as err: await _async_set_zone_temperature(hass, entity_id, 30) assert err.value.translation_key == "temp_out_of_range" async def test_zone_climate_unavailable_without_target_temperature( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Zones are unavailable if system target temperature is missing.""" configure_zone_device( zone_device, zones=[["Living", "1", 22]], target_temperature=None, ) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE async def test_zone_climate_zone_inactive_after_setup( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Inactive zones raise a translated error during service calls.""" configure_zone_device(zone_device, zones=[["Living", "1", 22]]) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None zone_device.zones[0][0] = "-" with pytest.raises(HomeAssistantError) as err: await _async_set_zone_temperature(hass, entity_id, 21) assert err.value.translation_key == "zone_inactive" async def test_zone_climate_zone_missing_after_setup( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Missing zones raise a translated error during service calls.""" configure_zone_device( zone_device, zones=[["Living", "1", 22], ["Office", "1", 22]], ) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 1) assert entity_id is not None zone_device.zones = [["Living", "1", 22]] with pytest.raises(HomeAssistantError) as err: await _async_set_zone_temperature(hass, entity_id, 21) assert err.value.translation_key == "zone_missing" async def test_zone_climate_parameters_unavailable( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Missing zone parameter lists make the zone entity unavailable.""" configure_zone_device(zone_device, zones=[["Living", "1", 22]]) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None zone_device.values["lztemp_h"] = "" zone_device.values["lztemp_c"] = "" await async_update_entity(hass, entity_id) state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE async def test_zone_climate_hvac_modes_read_only( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Changing HVAC mode through a zone climate is blocked.""" configure_zone_device(zone_device, zones=[["Living", "1", 22]]) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None with pytest.raises(HomeAssistantError) as err: await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, { ATTR_ENTITY_ID: entity_id, ATTR_HVAC_MODE: HVACMode.HEAT, }, blocking=True, ) assert err.value.translation_key == "zone_hvac_read_only" async def test_zone_climate_set_temperature_requires_heat_or_cool( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Setting temperature in unsupported modes raises a translated error.""" configure_zone_device( zone_device, zones=[["Living", "1", 22]], mode="auto", ) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None with pytest.raises(HomeAssistantError) as err: await _async_set_zone_temperature(hass, entity_id, 21) assert err.value.translation_key == "zone_hvac_mode_unsupported" async def test_zone_climate_properties( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Zone climate exposes expected state attributes.""" configure_zone_device( zone_device, zones=[["Living", "1", 22]], target_temperature=24, mode="cool", heating_values="20", cooling_values="18", ) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None state = hass.states.get(entity_id) assert state is not None assert state.state == HVACMode.COOL assert state.attributes[ATTR_HVAC_ACTION] == HVACAction.COOLING assert state.attributes[ATTR_TEMPERATURE] == 18.0 assert state.attributes[ATTR_MIN_TEMP] == 22.0 assert state.attributes[ATTR_MAX_TEMP] == 26.0 assert state.attributes[ATTR_HVAC_MODES] == [HVACMode.COOL] assert state.attributes["zone_id"] == 0 async def test_zone_climate_target_temperature_inactive_mode( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """In non-heating/cooling modes, zone target temperature is None.""" configure_zone_device( zone_device, zones=[["Living", "1", 22]], mode="auto", heating_values="bad", cooling_values="19", ) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None state = hass.states.get(entity_id) assert state is not None assert state.state == HVACMode.HEAT_COOL assert state.attributes[ATTR_TEMPERATURE] is None async def test_zone_climate_set_zone_failed( hass: HomeAssistant, entity_registry: er.EntityRegistry, zone_device: ZoneDevice, ) -> None: """Service call surfaces backend zone update errors.""" configure_zone_device(zone_device, zones=[["Living", "1", 22]]) await _async_setup_daikin(hass, zone_device) entity_id = _zone_entity_id(entity_registry, zone_device, 0) assert entity_id is not None zone_device.set_zone = AsyncMock(side_effect=NotImplementedError) with pytest.raises(HomeAssistantError) as err: await _async_set_zone_temperature(hass, entity_id, 21) assert err.value.translation_key == "zone_set_failed"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/daikin/test_zone_climate.py", "license": "Apache License 2.0", "lines": 307, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/mta/config_flow.py
"""Config flow for MTA New York City Transit integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from pymta import LINE_TO_FEED, BusFeed, MTAFeedError, SubwayFeed import voluptuous as vol from homeassistant.config_entries import ( SOURCE_REAUTH, ConfigEntry, ConfigFlow, ConfigFlowResult, ConfigSubentryFlow, SubentryFlowResult, ) from homeassistant.const import CONF_API_KEY from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.selector import ( SelectOptionDict, SelectSelector, SelectSelectorConfig, SelectSelectorMode, TextSelector, TextSelectorConfig, TextSelectorType, ) from .const import ( CONF_LINE, CONF_ROUTE, CONF_STOP_ID, CONF_STOP_NAME, DOMAIN, SUBENTRY_TYPE_BUS, SUBENTRY_TYPE_SUBWAY, ) _LOGGER = logging.getLogger(__name__) class MTAConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for MTA.""" VERSION = 1 MINOR_VERSION = 1 @classmethod @callback def async_get_supported_subentry_types( cls, config_entry: ConfigEntry ) -> dict[str, type[ConfigSubentryFlow]]: """Return subentries supported by this handler.""" return { SUBENTRY_TYPE_SUBWAY: SubwaySubentryFlowHandler, SUBENTRY_TYPE_BUS: BusSubentryFlowHandler, } async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: api_key = user_input.get(CONF_API_KEY) self._async_abort_entries_match({CONF_API_KEY: api_key}) if api_key: # Test the API key by trying to fetch bus data session = async_get_clientsession(self.hass) bus_feed = BusFeed(api_key=api_key, session=session) try: # Try to get stops for a known route to validate the key await bus_feed.get_stops(route_id="M15") except MTAFeedError: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected error validating API key") errors["base"] = "unknown" if not errors: if self.source == SOURCE_REAUTH: return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates={CONF_API_KEY: api_key or None}, ) return self.async_create_entry( title="MTA", data={CONF_API_KEY: api_key or None}, ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Optional(CONF_API_KEY): TextSelector( TextSelectorConfig(type=TextSelectorType.PASSWORD) ), } ), errors=errors, ) async def async_step_reauth( self, _entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle reauth when user wants to add or update API key.""" return await self.async_step_user() class SubwaySubentryFlowHandler(ConfigSubentryFlow): """Handle subway stop subentry flow.""" def __init__(self) -> None: """Initialize the subentry flow.""" self.data: dict[str, Any] = {} self.stops: dict[str, str] = {} async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Handle the line selection step.""" if user_input is not None: self.data[CONF_LINE] = user_input[CONF_LINE] return await self.async_step_stop() lines = sorted(LINE_TO_FEED.keys()) line_options = [SelectOptionDict(value=line, label=line) for line in lines] return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_LINE): SelectSelector( SelectSelectorConfig( options=line_options, mode=SelectSelectorMode.DROPDOWN, ) ), } ), ) async def async_step_stop( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Handle the stop selection step.""" errors: dict[str, str] = {} if user_input is not None: stop_id = user_input[CONF_STOP_ID] self.data[CONF_STOP_ID] = stop_id stop_name = self.stops.get(stop_id, stop_id) self.data[CONF_STOP_NAME] = stop_name unique_id = f"{self.data[CONF_LINE]}_{stop_id}" # Check for duplicate subentries across all entries for entry in self.hass.config_entries.async_entries(DOMAIN): for subentry in entry.subentries.values(): if subentry.unique_id == unique_id: return self.async_abort(reason="already_configured") # Test connection to real-time GTFS-RT feed try: await self._async_test_connection() except MTAFeedError: errors["base"] = "cannot_connect" else: title = f"{self.data[CONF_LINE]} - {stop_name}" return self.async_create_entry( title=title, data=self.data, unique_id=unique_id, ) try: self.stops = await self._async_get_stops(self.data[CONF_LINE]) except MTAFeedError: _LOGGER.debug("Error fetching stops for line %s", self.data[CONF_LINE]) return self.async_abort(reason="cannot_connect") if not self.stops: _LOGGER.error("No stops found for line %s", self.data[CONF_LINE]) return self.async_abort(reason="no_stops") stop_options = [ SelectOptionDict(value=stop_id, label=stop_name) for stop_id, stop_name in sorted(self.stops.items(), key=lambda x: x[1]) ] return self.async_show_form( step_id="stop", data_schema=vol.Schema( { vol.Required(CONF_STOP_ID): SelectSelector( SelectSelectorConfig( options=stop_options, mode=SelectSelectorMode.DROPDOWN, ) ), } ), errors=errors, description_placeholders={"line": self.data[CONF_LINE]}, ) async def _async_get_stops(self, line: str) -> dict[str, str]: """Get stops for a line from the library.""" feed_id = SubwayFeed.get_feed_id_for_route(line) session = async_get_clientsession(self.hass) subway_feed = SubwayFeed(feed_id=feed_id, session=session) stops_list = await subway_feed.get_stops(route_id=line) stops = {} for stop in stops_list: stop_id = stop["stop_id"] stop_name = stop["stop_name"] # Add direction label (stop_id always ends in N or S) direction = stop_id[-1] stops[stop_id] = f"{stop_name} ({direction} direction)" return stops async def _async_test_connection(self) -> None: """Test connection to MTA feed.""" feed_id = SubwayFeed.get_feed_id_for_route(self.data[CONF_LINE]) session = async_get_clientsession(self.hass) subway_feed = SubwayFeed(feed_id=feed_id, session=session) await subway_feed.get_arrivals( route_id=self.data[CONF_LINE], stop_id=self.data[CONF_STOP_ID], max_arrivals=1, ) class BusSubentryFlowHandler(ConfigSubentryFlow): """Handle bus stop subentry flow.""" def __init__(self) -> None: """Initialize the subentry flow.""" self.data: dict[str, Any] = {} self.stops: dict[str, str] = {} def _get_api_key(self) -> str: """Get API key from parent entry.""" return self._get_entry().data.get(CONF_API_KEY) or "" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Handle the route input step.""" errors: dict[str, str] = {} if user_input is not None: route = user_input[CONF_ROUTE].upper().strip() self.data[CONF_ROUTE] = route # Validate route by fetching stops try: self.stops = await self._async_get_stops(route) if not self.stops: errors["base"] = "invalid_route" else: return await self.async_step_stop() except MTAFeedError: _LOGGER.debug("Error fetching stops for route %s", route) errors["base"] = "invalid_route" return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_ROUTE): TextSelector(), } ), errors=errors, ) async def async_step_stop( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Handle the stop selection step.""" errors: dict[str, str] = {} if user_input is not None: stop_id = user_input[CONF_STOP_ID] self.data[CONF_STOP_ID] = stop_id stop_name = self.stops.get(stop_id, stop_id) self.data[CONF_STOP_NAME] = stop_name unique_id = f"bus_{self.data[CONF_ROUTE]}_{stop_id}" # Check for duplicate subentries across all entries for entry in self.hass.config_entries.async_entries(DOMAIN): for subentry in entry.subentries.values(): if subentry.unique_id == unique_id: return self.async_abort(reason="already_configured") # Test connection to real-time feed try: await self._async_test_connection() except MTAFeedError: errors["base"] = "cannot_connect" else: title = f"{self.data[CONF_ROUTE]} - {stop_name}" return self.async_create_entry( title=title, data=self.data, unique_id=unique_id, ) stop_options = [ SelectOptionDict(value=stop_id, label=stop_name) for stop_id, stop_name in sorted(self.stops.items(), key=lambda x: x[1]) ] return self.async_show_form( step_id="stop", data_schema=vol.Schema( { vol.Required(CONF_STOP_ID): SelectSelector( SelectSelectorConfig( options=stop_options, mode=SelectSelectorMode.DROPDOWN, ) ), } ), errors=errors, description_placeholders={"route": self.data[CONF_ROUTE]}, ) async def _async_get_stops(self, route: str) -> dict[str, str]: """Get stops for a bus route from the library.""" session = async_get_clientsession(self.hass) api_key = self._get_api_key() bus_feed = BusFeed(api_key=api_key, session=session) stops_list = await bus_feed.get_stops(route_id=route) stops = {} for stop in stops_list: stop_id = stop["stop_id"] stop_name = stop["stop_name"] # Add direction if available (e.g., "to South Ferry") if direction := stop.get("direction_name"): stops[stop_id] = f"{stop_name} (to {direction})" else: stops[stop_id] = stop_name return stops async def _async_test_connection(self) -> None: """Test connection to MTA bus feed.""" session = async_get_clientsession(self.hass) api_key = self._get_api_key() bus_feed = BusFeed(api_key=api_key, session=session) await bus_feed.get_arrivals( route_id=self.data[CONF_ROUTE], stop_id=self.data[CONF_STOP_ID], max_arrivals=1, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/mta/config_flow.py", "license": "Apache License 2.0", "lines": 313, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/mta/const.py
"""Constants for the MTA New York City Transit integration.""" from datetime import timedelta DOMAIN = "mta" CONF_LINE = "line" CONF_STOP_ID = "stop_id" CONF_STOP_NAME = "stop_name" CONF_ROUTE = "route" SUBENTRY_TYPE_SUBWAY = "subway" SUBENTRY_TYPE_BUS = "bus" UPDATE_INTERVAL = timedelta(seconds=30)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/mta/const.py", "license": "Apache License 2.0", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/mta/coordinator.py
"""Data update coordinator for MTA New York City Transit.""" from __future__ import annotations from dataclasses import dataclass from datetime import datetime import logging from pymta import BusFeed, MTAFeedError, SubwayFeed from homeassistant.config_entries import ConfigEntry, ConfigSubentry from homeassistant.const import CONF_API_KEY from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt as dt_util from .const import ( CONF_LINE, CONF_ROUTE, CONF_STOP_ID, DOMAIN, SUBENTRY_TYPE_BUS, UPDATE_INTERVAL, ) _LOGGER = logging.getLogger(__name__) @dataclass class MTAArrival: """Represents a single transit arrival.""" arrival_time: datetime minutes_until: int route_id: str destination: str @dataclass class MTAData: """Data for MTA arrivals.""" arrivals: list[MTAArrival] type MTAConfigEntry = ConfigEntry[dict[str, MTADataUpdateCoordinator]] class MTADataUpdateCoordinator(DataUpdateCoordinator[MTAData]): """Class to manage fetching MTA data.""" config_entry: MTAConfigEntry def __init__( self, hass: HomeAssistant, config_entry: MTAConfigEntry, subentry: ConfigSubentry, ) -> None: """Initialize.""" self.subentry = subentry self.stop_id = subentry.data[CONF_STOP_ID] session = async_get_clientsession(hass) if subentry.subentry_type == SUBENTRY_TYPE_BUS: api_key = config_entry.data.get(CONF_API_KEY) or "" self.feed: BusFeed | SubwayFeed = BusFeed(api_key=api_key, session=session) self.route_id = subentry.data[CONF_ROUTE] else: # Subway feed line = subentry.data[CONF_LINE] feed_id = SubwayFeed.get_feed_id_for_route(line) self.feed = SubwayFeed(feed_id=feed_id, session=session) self.route_id = line super().__init__( hass, _LOGGER, config_entry=config_entry, name=f"{DOMAIN}_{subentry.subentry_id}", update_interval=UPDATE_INTERVAL, ) async def _async_update_data(self) -> MTAData: """Fetch data from MTA.""" _LOGGER.debug( "Fetching data for route=%s, stop=%s", self.route_id, self.stop_id, ) try: library_arrivals = await self.feed.get_arrivals( route_id=self.route_id, stop_id=self.stop_id, max_arrivals=3, ) except MTAFeedError as err: raise UpdateFailed(f"Error fetching MTA data: {err}") from err now = dt_util.now() arrivals: list[MTAArrival] = [] for library_arrival in library_arrivals: # Convert UTC arrival time to local time arrival_time = dt_util.as_local(library_arrival.arrival_time) minutes_until = int((arrival_time - now).total_seconds() / 60) _LOGGER.debug( "Stop %s: arrival_time=%s, minutes_until=%d, route=%s", library_arrival.stop_id, arrival_time, minutes_until, library_arrival.route_id, ) arrivals.append( MTAArrival( arrival_time=arrival_time, minutes_until=minutes_until, route_id=library_arrival.route_id, destination=library_arrival.destination, ) ) _LOGGER.debug("Returning %d arrivals", len(arrivals)) return MTAData(arrivals=arrivals)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/mta/coordinator.py", "license": "Apache License 2.0", "lines": 101, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/mta/sensor.py
"""Sensor platform for MTA New York City Transit.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from datetime import datetime from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, ) from homeassistant.config_entries import ConfigSubentry from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import CONF_LINE, CONF_ROUTE, CONF_STOP_NAME, DOMAIN, SUBENTRY_TYPE_BUS from .coordinator import MTAArrival, MTAConfigEntry, MTADataUpdateCoordinator PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class MTASensorEntityDescription(SensorEntityDescription): """Describes an MTA sensor entity.""" arrival_index: int value_fn: Callable[[MTAArrival], datetime | str] SENSOR_DESCRIPTIONS: tuple[MTASensorEntityDescription, ...] = ( MTASensorEntityDescription( key="next_arrival", translation_key="next_arrival", device_class=SensorDeviceClass.TIMESTAMP, arrival_index=0, value_fn=lambda arrival: arrival.arrival_time, ), MTASensorEntityDescription( key="next_arrival_route", translation_key="next_arrival_route", arrival_index=0, value_fn=lambda arrival: arrival.route_id, ), MTASensorEntityDescription( key="next_arrival_destination", translation_key="next_arrival_destination", arrival_index=0, value_fn=lambda arrival: arrival.destination, ), MTASensorEntityDescription( key="second_arrival", translation_key="second_arrival", device_class=SensorDeviceClass.TIMESTAMP, arrival_index=1, value_fn=lambda arrival: arrival.arrival_time, ), MTASensorEntityDescription( key="second_arrival_route", translation_key="second_arrival_route", arrival_index=1, value_fn=lambda arrival: arrival.route_id, ), MTASensorEntityDescription( key="second_arrival_destination", translation_key="second_arrival_destination", arrival_index=1, value_fn=lambda arrival: arrival.destination, ), MTASensorEntityDescription( key="third_arrival", translation_key="third_arrival", device_class=SensorDeviceClass.TIMESTAMP, arrival_index=2, value_fn=lambda arrival: arrival.arrival_time, ), MTASensorEntityDescription( key="third_arrival_route", translation_key="third_arrival_route", arrival_index=2, value_fn=lambda arrival: arrival.route_id, ), MTASensorEntityDescription( key="third_arrival_destination", translation_key="third_arrival_destination", arrival_index=2, value_fn=lambda arrival: arrival.destination, ), ) async def async_setup_entry( hass: HomeAssistant, entry: MTAConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up MTA sensor based on a config entry.""" for subentry_id, coordinator in entry.runtime_data.items(): subentry = entry.subentries[subentry_id] async_add_entities( ( MTASensor(coordinator, subentry, description) for description in SENSOR_DESCRIPTIONS ), config_subentry_id=subentry_id, ) class MTASensor(CoordinatorEntity[MTADataUpdateCoordinator], SensorEntity): """Sensor for MTA transit arrivals.""" _attr_has_entity_name = True entity_description: MTASensorEntityDescription def __init__( self, coordinator: MTADataUpdateCoordinator, subentry: ConfigSubentry, description: MTASensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description is_bus = subentry.subentry_type == SUBENTRY_TYPE_BUS if is_bus: route = subentry.data[CONF_ROUTE] model = "Bus" else: route = subentry.data[CONF_LINE] model = "Subway" stop_name = subentry.data.get(CONF_STOP_NAME, subentry.subentry_id) unique_id = subentry.unique_id or subentry.subentry_id self._attr_unique_id = f"{unique_id}-{description.key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, unique_id)}, name=f"{route} - {stop_name}", manufacturer="MTA", model=model, entry_type=DeviceEntryType.SERVICE, ) @property def native_value(self) -> datetime | str | None: """Return the state of the sensor.""" arrivals = self.coordinator.data.arrivals if len(arrivals) <= self.entity_description.arrival_index: return None return self.entity_description.value_fn( arrivals[self.entity_description.arrival_index] )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/mta/sensor.py", "license": "Apache License 2.0", "lines": 136, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/mta/test_config_flow.py
"""Test the MTA config flow.""" from unittest.mock import AsyncMock, MagicMock from pymta import MTAFeedError import pytest from homeassistant.components.mta.const import ( CONF_LINE, CONF_ROUTE, CONF_STOP_ID, CONF_STOP_NAME, DOMAIN, SUBENTRY_TYPE_BUS, SUBENTRY_TYPE_SUBWAY, ) from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_API_KEY from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry async def test_main_entry_flow_without_token( hass: HomeAssistant, mock_setup_entry: AsyncMock, ) -> None: """Test the main config flow without API key.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "MTA" assert result["data"] == {CONF_API_KEY: None} assert len(mock_setup_entry.mock_calls) == 1 async def test_main_entry_flow_with_token( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_bus_feed: MagicMock, ) -> None: """Test the main config flow with API key.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: "test_api_key"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "MTA" assert result["data"] == {CONF_API_KEY: "test_api_key"} assert len(mock_setup_entry.mock_calls) == 1 async def test_main_entry_already_configured( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test we abort if MTA is already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_reauth_flow( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bus_feed: MagicMock, ) -> None: """Test the reauth flow.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: "new_api_key"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data[CONF_API_KEY] == "new_api_key" @pytest.mark.parametrize( ("side_effect", "expected_error"), [ (MTAFeedError("Connection error"), "cannot_connect"), (RuntimeError("Unexpected error"), "unknown"), ], ) async def test_reauth_flow_errors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bus_feed: MagicMock, side_effect: Exception, expected_error: str, ) -> None: """Test the reauth flow with connection error.""" mock_config_entry.add_to_hass(hass) mock_bus_feed.return_value.get_stops.side_effect = side_effect result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: "bad_api_key"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": expected_error} mock_bus_feed.return_value.get_stops.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: "api_key"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" # Subway subentry tests async def test_subway_subentry_flow( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_subway_feed: MagicMock, ) -> None: """Test the subway subentry flow.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, SUBENTRY_TYPE_SUBWAY), context={"source": SOURCE_USER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_LINE: "1"} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "stop" result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "127N"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "1 - Times Sq - 42 St (N direction)" assert result["data"] == { CONF_LINE: "1", CONF_STOP_ID: "127N", CONF_STOP_NAME: "Times Sq - 42 St (N direction)", } async def test_subway_subentry_already_configured( hass: HomeAssistant, mock_config_entry_with_subway_subentry: MockConfigEntry, mock_subway_feed: MagicMock, ) -> None: """Test subway subentry already configured.""" mock_config_entry_with_subway_subentry.add_to_hass(hass) await hass.config_entries.async_setup( mock_config_entry_with_subway_subentry.entry_id ) await hass.async_block_till_done() result = await hass.config_entries.subentries.async_init( (mock_config_entry_with_subway_subentry.entry_id, SUBENTRY_TYPE_SUBWAY), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_LINE: "1"} ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "127N"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_subway_subentry_connection_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_subway_feed: MagicMock, ) -> None: """Test subway subentry flow with connection error.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() mock_subway_feed.return_value.get_arrivals.side_effect = MTAFeedError( "Connection error" ) result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, SUBENTRY_TYPE_SUBWAY), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_LINE: "1"} ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "127N"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "cannot_connect"} async def test_subway_subentry_cannot_get_stops( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_subway_feed: MagicMock, ) -> None: """Test subway subentry flow when cannot get stops.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() mock_subway_feed.return_value.get_stops.side_effect = MTAFeedError("Feed error") result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, SUBENTRY_TYPE_SUBWAY), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_LINE: "1"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "cannot_connect" async def test_subway_subentry_no_stops_found( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_subway_feed: MagicMock, ) -> None: """Test subway subentry flow when no stops are found.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() mock_subway_feed.return_value.get_stops.return_value = [] result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, SUBENTRY_TYPE_SUBWAY), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_LINE: "1"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_stops" # Bus subentry tests async def test_bus_subentry_flow( hass: HomeAssistant, mock_config_entry_with_api_key: MockConfigEntry, mock_bus_feed: MagicMock, ) -> None: """Test the bus subentry flow.""" mock_config_entry_with_api_key.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry_with_api_key.entry_id) await hass.async_block_till_done() result = await hass.config_entries.subentries.async_init( (mock_config_entry_with_api_key.entry_id, SUBENTRY_TYPE_BUS), context={"source": SOURCE_USER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_ROUTE: "M15"} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "stop" result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "400561"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "M15 - 1 Av/E 79 St" assert result["data"] == { CONF_ROUTE: "M15", CONF_STOP_ID: "400561", CONF_STOP_NAME: "1 Av/E 79 St", } async def test_bus_subentry_flow_without_token( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bus_feed: MagicMock, ) -> None: """Test the bus subentry flow without API token (space workaround).""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, SUBENTRY_TYPE_BUS), context={"source": SOURCE_USER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_ROUTE: "M15"} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "stop" result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "400561"} ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_bus_subentry_already_configured( hass: HomeAssistant, mock_config_entry_with_bus_subentry: MockConfigEntry, mock_bus_feed: MagicMock, ) -> None: """Test bus subentry already configured.""" mock_config_entry_with_bus_subentry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry_with_bus_subentry.entry_id) await hass.async_block_till_done() result = await hass.config_entries.subentries.async_init( (mock_config_entry_with_bus_subentry.entry_id, SUBENTRY_TYPE_BUS), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_ROUTE: "M15"} ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "400561"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_bus_subentry_invalid_route( hass: HomeAssistant, mock_config_entry_with_api_key: MockConfigEntry, mock_bus_feed: MagicMock, ) -> None: """Test bus subentry flow with invalid route.""" mock_config_entry_with_api_key.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry_with_api_key.entry_id) await hass.async_block_till_done() mock_bus_feed.return_value.get_stops.return_value = [] result = await hass.config_entries.subentries.async_init( (mock_config_entry_with_api_key.entry_id, SUBENTRY_TYPE_BUS), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_ROUTE: "INVALID"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "invalid_route"} async def test_bus_subentry_route_fetch_error( hass: HomeAssistant, mock_config_entry_with_api_key: MockConfigEntry, mock_bus_feed: MagicMock, ) -> None: """Test bus subentry flow when route fetch fails (treated as invalid route).""" mock_config_entry_with_api_key.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry_with_api_key.entry_id) await hass.async_block_till_done() mock_bus_feed.return_value.get_stops.side_effect = MTAFeedError("Connection error") result = await hass.config_entries.subentries.async_init( (mock_config_entry_with_api_key.entry_id, SUBENTRY_TYPE_BUS), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_ROUTE: "M15"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "invalid_route"} mock_bus_feed.return_value.get_stops.side_effect = None result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_ROUTE: "M15"} ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "400561"} ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_bus_subentry_connection_test_error( hass: HomeAssistant, mock_config_entry_with_api_key: MockConfigEntry, mock_bus_feed: MagicMock, ) -> None: """Test bus subentry flow when connection test fails after route validation.""" mock_config_entry_with_api_key.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry_with_api_key.entry_id) await hass.async_block_till_done() # get_stops succeeds but get_arrivals fails mock_bus_feed.return_value.get_arrivals.side_effect = MTAFeedError( "Connection error" ) result = await hass.config_entries.subentries.async_init( (mock_config_entry_with_api_key.entry_id, SUBENTRY_TYPE_BUS), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_ROUTE: "M15"} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "stop" result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "400561"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "cannot_connect"} mock_bus_feed.return_value.get_arrivals.side_effect = None result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "400561"} ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_bus_subentry_with_direction( hass: HomeAssistant, mock_config_entry_with_api_key: MockConfigEntry, mock_bus_feed_with_direction: MagicMock, ) -> None: """Test bus subentry flow shows direction for stops.""" mock_config_entry_with_api_key.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry_with_api_key.entry_id) await hass.async_block_till_done() result = await hass.config_entries.subentries.async_init( (mock_config_entry_with_api_key.entry_id, SUBENTRY_TYPE_BUS), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_ROUTE: "M15"} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "stop" # Select a stop with direction info result = await hass.config_entries.subentries.async_configure( result["flow_id"], {CONF_STOP_ID: "400561"} ) assert result["type"] is FlowResultType.CREATE_ENTRY # Stop name should include direction assert result["title"] == "M15 - 1 Av/E 79 St (to South Ferry)" assert result["data"][CONF_STOP_NAME] == "1 Av/E 79 St (to South Ferry)"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/mta/test_config_flow.py", "license": "Apache License 2.0", "lines": 408, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/mta/test_init.py
"""Test the MTA New York City Transit init.""" from types import MappingProxyType from unittest.mock import MagicMock from pymta import MTAFeedError import pytest from homeassistant.components.mta.const import ( CONF_LINE, CONF_STOP_ID, CONF_STOP_NAME, DOMAIN, ) from homeassistant.config_entries import ConfigEntryState, ConfigSubentry from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry async def test_setup_entry_no_subentries( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test setting up an entry without subentries.""" mock_config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.LOADED assert DOMAIN in hass.config_entries.async_domains() async def test_setup_entry_with_subway_subentry( hass: HomeAssistant, mock_config_entry_with_subway_subentry: MockConfigEntry, mock_subway_feed: MagicMock, ) -> None: """Test setting up an entry with a subway subentry.""" mock_config_entry_with_subway_subentry.add_to_hass(hass) assert await hass.config_entries.async_setup( mock_config_entry_with_subway_subentry.entry_id ) await hass.async_block_till_done() assert mock_config_entry_with_subway_subentry.state is ConfigEntryState.LOADED assert DOMAIN in hass.config_entries.async_domains() # Verify coordinator was created for the subentry assert len(mock_config_entry_with_subway_subentry.runtime_data) == 1 async def test_setup_entry_with_bus_subentry( hass: HomeAssistant, mock_config_entry_with_bus_subentry: MockConfigEntry, mock_bus_feed: MagicMock, ) -> None: """Test setting up an entry with a bus subentry.""" mock_config_entry_with_bus_subentry.add_to_hass(hass) assert await hass.config_entries.async_setup( mock_config_entry_with_bus_subentry.entry_id ) await hass.async_block_till_done() assert mock_config_entry_with_bus_subentry.state is ConfigEntryState.LOADED assert DOMAIN in hass.config_entries.async_domains() # Verify coordinator was created for the subentry assert len(mock_config_entry_with_bus_subentry.runtime_data) == 1 async def test_unload_entry( hass: HomeAssistant, mock_config_entry_with_subway_subentry: MockConfigEntry, mock_subway_feed: MagicMock, ) -> None: """Test unloading an entry.""" mock_config_entry_with_subway_subentry.add_to_hass(hass) assert await hass.config_entries.async_setup( mock_config_entry_with_subway_subentry.entry_id ) await hass.async_block_till_done() assert mock_config_entry_with_subway_subentry.state is ConfigEntryState.LOADED assert await hass.config_entries.async_unload( mock_config_entry_with_subway_subentry.entry_id ) await hass.async_block_till_done() assert mock_config_entry_with_subway_subentry.state is ConfigEntryState.NOT_LOADED async def test_setup_entry_with_unknown_subentry_type( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test that unknown subentry types are skipped.""" # Add a subentry with an unknown type unknown_subentry = ConfigSubentry( data=MappingProxyType( { CONF_LINE: "1", CONF_STOP_ID: "127N", CONF_STOP_NAME: "Times Sq - 42 St", } ), subentry_id="01JUNKNOWN000000000000001", subentry_type="unknown_type", # Unknown subentry type title="Unknown Subentry", unique_id="unknown_1", ) mock_config_entry.subentries = {unknown_subentry.subentry_id: unknown_subentry} mock_config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.LOADED # No coordinators should be created for unknown subentry type assert len(mock_config_entry.runtime_data) == 0 async def test_setup_entry_coordinator_fetch_error( hass: HomeAssistant, mock_config_entry_with_subway_subentry: MockConfigEntry, mock_subway_feed: MagicMock, ) -> None: """Test that coordinator raises ConfigEntryNotReady on fetch error.""" mock_subway_feed.return_value.get_arrivals.side_effect = MTAFeedError("API error") mock_config_entry_with_subway_subentry.add_to_hass(hass) assert not await hass.config_entries.async_setup( mock_config_entry_with_subway_subentry.entry_id ) await hass.async_block_till_done() assert mock_config_entry_with_subway_subentry.state is ConfigEntryState.SETUP_RETRY @pytest.mark.freeze_time("2023-10-21") async def test_sensor_no_arrivals( hass: HomeAssistant, mock_config_entry_with_subway_subentry: MockConfigEntry, mock_subway_feed: MagicMock, entity_registry: er.EntityRegistry, ) -> None: """Test sensor values when there are no arrivals.""" await hass.config.async_set_time_zone("UTC") # Return empty arrivals list mock_subway_feed.return_value.get_arrivals.return_value = [] mock_config_entry_with_subway_subentry.add_to_hass(hass) await hass.config_entries.async_setup( mock_config_entry_with_subway_subentry.entry_id ) await hass.async_block_till_done() # All arrival sensors should have state "unknown" (native_value is None) state = hass.states.get("sensor.1_times_sq_42_st_n_direction_next_arrival") assert state is not None assert state.state == "unknown" state = hass.states.get("sensor.1_times_sq_42_st_n_direction_second_arrival") assert state is not None assert state.state == "unknown" state = hass.states.get("sensor.1_times_sq_42_st_n_direction_third_arrival") assert state is not None assert state.state == "unknown"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/mta/test_init.py", "license": "Apache License 2.0", "lines": 137, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/mta/test_sensor.py
"""Test the MTA sensor platform.""" from unittest.mock import MagicMock import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform @pytest.mark.freeze_time("2023-10-21") @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_subway_sensor( hass: HomeAssistant, mock_config_entry_with_subway_subentry: MockConfigEntry, mock_subway_feed: MagicMock, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test the subway sensor entities.""" await hass.config.async_set_time_zone("UTC") mock_config_entry_with_subway_subentry.add_to_hass(hass) await hass.config_entries.async_setup( mock_config_entry_with_subway_subentry.entry_id ) await hass.async_block_till_done() await snapshot_platform( hass, entity_registry, snapshot, mock_config_entry_with_subway_subentry.entry_id ) @pytest.mark.freeze_time("2023-10-21") @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_bus_sensor( hass: HomeAssistant, mock_config_entry_with_bus_subentry: MockConfigEntry, mock_bus_feed: MagicMock, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test the bus sensor entities.""" await hass.config.async_set_time_zone("UTC") mock_config_entry_with_bus_subentry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry_with_bus_subentry.entry_id) await hass.async_block_till_done() await snapshot_platform( hass, entity_registry, snapshot, mock_config_entry_with_bus_subentry.entry_id )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/mta/test_sensor.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/matter/test_entity.py
"""Test Matter entity behavior.""" from __future__ import annotations import pytest from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @pytest.mark.usefixtures("matter_node") @pytest.mark.parametrize( ("node_fixture", "entity_id", "expected_translation_key", "expected_name"), [ ("mock_onoff_light", "light.mock_onoff_light", "light", "Mock OnOff Light"), ("mock_door_lock", "lock.mock_door_lock", "lock", "Mock Door Lock"), ("mock_thermostat", "climate.mock_thermostat", "thermostat", "Mock Thermostat"), ("mock_valve", "valve.mock_valve", "valve", "Mock Valve"), ("mock_fan", "fan.mocked_fan_switch", "fan", "Mocked Fan Switch"), ("eve_energy_plug", "switch.eve_energy_plug", "switch", "Eve Energy Plug"), ("mock_vacuum_cleaner", "vacuum.mock_vacuum", "vacuum", "Mock Vacuum"), ( "silabs_water_heater", "water_heater.water_heater", "water_heater", "Water Heater", ), ], ) async def test_single_endpoint_platform_translation_key( hass: HomeAssistant, entity_registry: er.EntityRegistry, entity_id: str, expected_translation_key: str, expected_name: str, ) -> None: """Test single-endpoint entities on platforms with _platform_translation_key. The translation key must always be present for state_attributes translations and icon translations. When there is no endpoint postfix, the entity name should be suppressed (None) so only the device name is displayed. """ entry = entity_registry.async_get(entity_id) assert entry is not None assert entry.translation_key == expected_translation_key # No original_name means the entity name is suppressed, # so only the device name is shown assert entry.original_name is None state = hass.states.get(entity_id) assert state is not None # The friendly name should be just the device name (no entity name appended) assert state.name == expected_name @pytest.mark.usefixtures("matter_node") @pytest.mark.parametrize("node_fixture", ["inovelli_vtm31"]) async def test_multi_endpoint_entity_translation_key( hass: HomeAssistant, entity_registry: er.EntityRegistry, ) -> None: """Test that multi-endpoint entities have a translation key and a name postfix. When a device has the same primary attribute on multiple endpoints, the entity name gets postfixed with the endpoint ID. The translation key must still always be set for translations. """ # Endpoint 1 entry_1 = entity_registry.async_get("light.inovelli_light_1") assert entry_1 is not None assert entry_1.translation_key == "light" assert entry_1.original_name == "Light (1)" state_1 = hass.states.get("light.inovelli_light_1") assert state_1 is not None assert state_1.name == "Inovelli Light (1)" # Endpoint 6 entry_6 = entity_registry.async_get("light.inovelli_light_6") assert entry_6 is not None assert entry_6.translation_key == "light" assert entry_6.original_name == "Light (6)" state_6 = hass.states.get("light.inovelli_light_6") assert state_6 is not None assert state_6.name == "Inovelli Light (6)" @pytest.mark.usefixtures("matter_node") @pytest.mark.parametrize("node_fixture", ["eve_energy_20ecn4101"]) async def test_label_modified_entity_translation_key( hass: HomeAssistant, entity_registry: er.EntityRegistry, ) -> None: """Test that label-modified entities have a translation key and a label postfix. When a device uses Matter labels to differentiate endpoints, the entity name gets the label as a postfix. The translation key must still always be set for translations. """ # Top outlet entry_top = entity_registry.async_get("switch.eve_energy_20ecn4101_switch_top") assert entry_top is not None assert entry_top.translation_key == "switch" assert entry_top.original_name == "Switch (top)" state_top = hass.states.get("switch.eve_energy_20ecn4101_switch_top") assert state_top is not None assert state_top.name == "Eve Energy 20ECN4101 Switch (top)" # Bottom outlet entry_bottom = entity_registry.async_get( "switch.eve_energy_20ecn4101_switch_bottom" ) assert entry_bottom is not None assert entry_bottom.translation_key == "switch" assert entry_bottom.original_name == "Switch (bottom)" state_bottom = hass.states.get("switch.eve_energy_20ecn4101_switch_bottom") assert state_bottom is not None assert state_bottom.name == "Eve Energy 20ECN4101 Switch (bottom)" @pytest.mark.usefixtures("matter_node") @pytest.mark.parametrize("node_fixture", ["eve_thermo_v4"]) async def test_description_translation_key_not_overridden( hass: HomeAssistant, entity_registry: er.EntityRegistry, ) -> None: """Test that a description-level translation key is not overridden. When an entity description already sets translation_key (e.g. "child_lock"), the _platform_translation_key logic should not override it. The entity keeps its description-level translation key and name. """ entry = entity_registry.async_get("switch.eve_thermo_20ebp1701_child_lock") assert entry is not None # The description-level translation key should be preserved, not overridden # by _platform_translation_key ("switch") assert entry.translation_key == "child_lock" assert entry.original_name == "Child lock" state = hass.states.get("switch.eve_thermo_20ebp1701_child_lock") assert state is not None assert state.name == "Eve Thermo 20EBP1701 Child lock" @pytest.mark.usefixtures("matter_node") @pytest.mark.parametrize("node_fixture", ["air_quality_sensor"]) async def test_entity_name_from_description_translation_key( hass: HomeAssistant, entity_registry: er.EntityRegistry, ) -> None: """Test entity name derived from an explicit description translation key. Sensor entities do not set _platform_translation_key on the platform class. When the entity description sets translation_key explicitly, the entity name is derived from that translation key. """ entry = entity_registry.async_get( "sensor.lightfi_aq1_air_quality_sensor_air_quality" ) assert entry is not None assert entry.translation_key == "air_quality" assert entry.original_name == "Air quality" state = hass.states.get("sensor.lightfi_aq1_air_quality_sensor_air_quality") assert state is not None assert state.name == "lightfi-aq1-air-quality-sensor Air quality" @pytest.mark.usefixtures("matter_node") @pytest.mark.parametrize("node_fixture", ["mock_temperature_sensor"]) async def test_entity_name_from_device_class( hass: HomeAssistant, entity_registry: er.EntityRegistry, ) -> None: """Test entity name derived from device class when no translation key is set. Sensor entities do not set _platform_translation_key on the platform class. When the entity description also has no translation_key, the entity name is derived from the device class instead. """ entry = entity_registry.async_get("sensor.mock_temperature_sensor_temperature") assert entry is not None assert entry.translation_key is None # Name is derived from the device class assert entry.original_name == "Temperature" state = hass.states.get("sensor.mock_temperature_sensor_temperature") assert state is not None assert state.name == "Mock Temperature Sensor Temperature"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/matter/test_entity.py", "license": "Apache License 2.0", "lines": 161, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fritz/test_coordinator.py
"""Tests for Fritz!Tools coordinator.""" from __future__ import annotations from copy import deepcopy from unittest.mock import MagicMock, patch from fritzconnection.lib.fritztools import ArgumentNamespace import pytest from homeassistant.components.fritz.const import ( CONF_FEATURE_DEVICE_TRACKING, DEFAULT_CONF_FEATURE_DEVICE_TRACKING, DEFAULT_SSL, DOMAIN, ) from homeassistant.components.fritz.coordinator import AvmWrapper, ClassSetupMissing from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from .const import MOCK_MESH_MASTER_MAC, MOCK_STATUS_DEVICE_INFO_DATA, MOCK_USER_DATA from tests.common import MockConfigEntry @pytest.mark.parametrize( "attr", [ "unique_id", "model", "current_firmware", "mac", ], ) async def test_fritzboxtools_class_no_setup( hass: HomeAssistant, attr: str, ) -> None: """Test accessing FritzBoxTools class properties before setup.""" entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA) entry.add_to_hass(hass) coordinator = AvmWrapper( hass=hass, config_entry=entry, host=MOCK_USER_DATA[CONF_HOST], port=MOCK_USER_DATA[CONF_PORT], username=MOCK_USER_DATA[CONF_USERNAME], password=MOCK_USER_DATA[CONF_PASSWORD], use_tls=MOCK_USER_DATA.get(CONF_SSL, DEFAULT_SSL), device_discovery_enabled=MOCK_USER_DATA.get( CONF_FEATURE_DEVICE_TRACKING, DEFAULT_CONF_FEATURE_DEVICE_TRACKING ), ) with pytest.raises(ClassSetupMissing): getattr(coordinator, attr) async def test_clear_connection_cache( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, fc_class_mock, fh_class_mock, fs_class_mock, ) -> None: """Test clearing the connection cache.""" entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA) entry.add_to_hass(hass) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done(wait_background_tasks=True) assert entry.state is ConfigEntryState.LOADED caplog.clear() fc_class_mock.return_value.clear_cache() assert "Cleared FritzConnection call action cache" in caplog.text async def test_no_connection( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, fc_class_mock, fh_class_mock, fs_class_mock, ) -> None: """Test no connection established.""" entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA) entry.add_to_hass(hass) with patch( "homeassistant.components.fritz.coordinator.FritzConnectionCached", return_value=None, ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done(wait_background_tasks=True) assert ( f"Unable to establish a connection with {MOCK_USER_DATA[CONF_HOST]}" in caplog.text ) async def test_no_software_version( hass: HomeAssistant, device_registry: dr.DeviceRegistry, fc_class_mock, fh_class_mock, fs_class_mock, ) -> None: """Test software version non normalized.""" entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA) entry.add_to_hass(hass) device_info = deepcopy(MOCK_STATUS_DEVICE_INFO_DATA) device_info["NewSoftwareVersion"] = "string_version_not_number" fs_class_mock.get_device_info = MagicMock( return_value=ArgumentNamespace(device_info) ) assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done(wait_background_tasks=True) assert entry.state is ConfigEntryState.LOADED device = device_registry.async_get_device( identifiers={(DOMAIN, MOCK_MESH_MASTER_MAC)} ) assert device assert device.sw_version == "string_version_not_number"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fritz/test_coordinator.py", "license": "Apache License 2.0", "lines": 114, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/liebherr/switch.py
"""Switch platform for Liebherr integration.""" from __future__ import annotations from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import TYPE_CHECKING, Any from pyliebherrhomeapi import ToggleControl, ZonePosition from pyliebherrhomeapi.const import ( CONTROL_NIGHT_MODE, CONTROL_PARTY_MODE, CONTROL_SUPER_COOL, CONTROL_SUPER_FROST, ) from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .coordinator import LiebherrConfigEntry, LiebherrCoordinator from .entity import ZONE_POSITION_MAP, LiebherrEntity PARALLEL_UPDATES = 1 @dataclass(frozen=True, kw_only=True) class LiebherrSwitchEntityDescription(SwitchEntityDescription): """Base description for Liebherr switch entities.""" control_name: str @dataclass(frozen=True, kw_only=True) class LiebherrZoneSwitchEntityDescription(LiebherrSwitchEntityDescription): """Describes a Liebherr zone-based switch entity.""" set_fn: Callable[[LiebherrCoordinator, int, bool], Awaitable[None]] @dataclass(frozen=True, kw_only=True) class LiebherrDeviceSwitchEntityDescription(LiebherrSwitchEntityDescription): """Describes a Liebherr device-wide switch entity.""" set_fn: Callable[[LiebherrCoordinator, bool], Awaitable[None]] ZONE_SWITCH_TYPES: dict[str, LiebherrZoneSwitchEntityDescription] = { CONTROL_SUPER_COOL: LiebherrZoneSwitchEntityDescription( key="super_cool", translation_key="super_cool", control_name=CONTROL_SUPER_COOL, set_fn=lambda coordinator, zone_id, value: coordinator.client.set_super_cool( device_id=coordinator.device_id, zone_id=zone_id, value=value, ), ), CONTROL_SUPER_FROST: LiebherrZoneSwitchEntityDescription( key="super_frost", translation_key="super_frost", control_name=CONTROL_SUPER_FROST, set_fn=lambda coordinator, zone_id, value: coordinator.client.set_super_frost( device_id=coordinator.device_id, zone_id=zone_id, value=value, ), ), } DEVICE_SWITCH_TYPES: dict[str, LiebherrDeviceSwitchEntityDescription] = { CONTROL_PARTY_MODE: LiebherrDeviceSwitchEntityDescription( key="party_mode", translation_key="party_mode", control_name=CONTROL_PARTY_MODE, set_fn=lambda coordinator, value: coordinator.client.set_party_mode( device_id=coordinator.device_id, value=value, ), ), CONTROL_NIGHT_MODE: LiebherrDeviceSwitchEntityDescription( key="night_mode", translation_key="night_mode", control_name=CONTROL_NIGHT_MODE, set_fn=lambda coordinator, value: coordinator.client.set_night_mode( device_id=coordinator.device_id, value=value, ), ), } def _create_switch_entities( coordinators: list[LiebherrCoordinator], ) -> list[LiebherrDeviceSwitch | LiebherrZoneSwitch]: """Create switch entities for the given coordinators.""" entities: list[LiebherrDeviceSwitch | LiebherrZoneSwitch] = [] for coordinator in coordinators: has_multiple_zones = len(coordinator.data.get_temperature_controls()) > 1 for control in coordinator.data.controls: if not isinstance(control, ToggleControl): continue # Zone-based switches (SuperCool, SuperFrost) if control.zone_id is not None and ( desc := ZONE_SWITCH_TYPES.get(control.name) ): entities.append( LiebherrZoneSwitch( coordinator=coordinator, description=desc, zone_id=control.zone_id, has_multiple_zones=has_multiple_zones, ) ) # Device-wide switches (PartyMode, NightMode) elif device_desc := DEVICE_SWITCH_TYPES.get(control.name): entities.append( LiebherrDeviceSwitch( coordinator=coordinator, description=device_desc, ) ) return entities async def async_setup_entry( hass: HomeAssistant, entry: LiebherrConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Liebherr switch entities.""" async_add_entities( _create_switch_entities(list(entry.runtime_data.coordinators.values())) ) @callback def _async_new_device(coordinators: list[LiebherrCoordinator]) -> None: """Add switch entities for new devices.""" async_add_entities(_create_switch_entities(coordinators)) entry.async_on_unload( async_dispatcher_connect( hass, f"{DOMAIN}_new_device_{entry.entry_id}", _async_new_device ) ) class LiebherrDeviceSwitch(LiebherrEntity, SwitchEntity): """Representation of a device-wide Liebherr switch.""" entity_description: LiebherrSwitchEntityDescription _zone_id: int | None = None def __init__( self, coordinator: LiebherrCoordinator, description: LiebherrSwitchEntityDescription, ) -> None: """Initialize the device switch entity.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.device_id}_{description.key}" @property def _toggle_control(self) -> ToggleControl | None: """Get the toggle control for this entity.""" for control in self.coordinator.data.controls: if ( isinstance(control, ToggleControl) and control.name == self.entity_description.control_name and (self._zone_id is None or control.zone_id == self._zone_id) ): return control return None @property def is_on(self) -> bool | None: """Return true if the switch is on.""" if TYPE_CHECKING: assert self._toggle_control is not None return self._toggle_control.value @property def available(self) -> bool: """Return if entity is available.""" return super().available and self._toggle_control is not None async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self._async_set_value(True) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self._async_set_value(False) async def _async_call_set_fn(self, value: bool) -> None: """Call the set function for this switch.""" if TYPE_CHECKING: assert isinstance( self.entity_description, LiebherrDeviceSwitchEntityDescription ) await self.entity_description.set_fn(self.coordinator, value) async def _async_set_value(self, value: bool) -> None: """Set the switch value.""" await self._async_send_command(self._async_call_set_fn(value)) class LiebherrZoneSwitch(LiebherrDeviceSwitch): """Representation of a zone-based Liebherr switch.""" entity_description: LiebherrZoneSwitchEntityDescription _zone_id: int def __init__( self, coordinator: LiebherrCoordinator, description: LiebherrZoneSwitchEntityDescription, zone_id: int, has_multiple_zones: bool, ) -> None: """Initialize the zone switch entity.""" super().__init__(coordinator, description) self._zone_id = zone_id self._attr_unique_id = f"{coordinator.device_id}_{description.key}_{zone_id}" # Add zone suffix only for multi-zone devices if has_multiple_zones: temp_controls = coordinator.data.get_temperature_controls() if ( (tc := temp_controls.get(zone_id)) and isinstance(tc.zone_position, ZonePosition) and (zone_key := ZONE_POSITION_MAP.get(tc.zone_position)) ): self._attr_translation_key = f"{description.translation_key}_{zone_key}" async def _async_call_set_fn(self, value: bool) -> None: """Call the set function for this zone switch.""" await self.entity_description.set_fn(self.coordinator, self._zone_id, value)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/liebherr/switch.py", "license": "Apache License 2.0", "lines": 200, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/liebherr/test_switch.py
"""Test the Liebherr switch platform.""" import copy from datetime import timedelta from typing import Any from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory from pyliebherrhomeapi import ( Device, DeviceState, DeviceType, TemperatureControl, TemperatureUnit, ToggleControl, ZonePosition, ) from pyliebherrhomeapi.exceptions import LiebherrConnectionError import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_UNAVAILABLE, Platform, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from .conftest import MOCK_DEVICE from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.fixture def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return [Platform.SWITCH] @pytest.fixture(autouse=True) def enable_all_entities(entity_registry_enabled_by_default: None) -> None: """Make sure all entities are enabled.""" @pytest.mark.usefixtures("init_integration") async def test_switches( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test all switch entities with multi-zone device.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.parametrize( ("entity_id", "service", "method", "kwargs"), [ ( "switch.test_fridge_top_zone_supercool", SERVICE_TURN_ON, "set_super_cool", {"device_id": "test_device_id", "zone_id": 1, "value": True}, ), ( "switch.test_fridge_top_zone_supercool", SERVICE_TURN_OFF, "set_super_cool", {"device_id": "test_device_id", "zone_id": 1, "value": False}, ), ( "switch.test_fridge_bottom_zone_superfrost", SERVICE_TURN_ON, "set_super_frost", {"device_id": "test_device_id", "zone_id": 2, "value": True}, ), ( "switch.test_fridge_partymode", SERVICE_TURN_ON, "set_party_mode", {"device_id": "test_device_id", "value": True}, ), ( "switch.test_fridge_nightmode", SERVICE_TURN_OFF, "set_night_mode", {"device_id": "test_device_id", "value": False}, ), ], ) @pytest.mark.usefixtures("init_integration") async def test_switch_service_calls( hass: HomeAssistant, mock_liebherr_client: MagicMock, entity_id: str, service: str, method: str, kwargs: dict[str, Any], ) -> None: """Test switch turn on/off service calls.""" initial_call_count = mock_liebherr_client.get_device_state.call_count await hass.services.async_call( SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) getattr(mock_liebherr_client, method).assert_called_once_with(**kwargs) # Verify coordinator refresh was triggered assert mock_liebherr_client.get_device_state.call_count > initial_call_count @pytest.mark.parametrize( ("entity_id", "method"), [ ("switch.test_fridge_top_zone_supercool", "set_super_cool"), ("switch.test_fridge_partymode", "set_party_mode"), ], ) @pytest.mark.usefixtures("init_integration") async def test_switch_failure( hass: HomeAssistant, mock_liebherr_client: MagicMock, entity_id: str, method: str, ) -> None: """Test switch fails gracefully on connection error.""" getattr(mock_liebherr_client, method).side_effect = LiebherrConnectionError( "Connection failed" ) with pytest.raises( HomeAssistantError, match="An error occurred while communicating with the device", ): await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) @pytest.mark.usefixtures("init_integration") async def test_switch_when_control_missing( hass: HomeAssistant, mock_liebherr_client: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test switch entity behavior when toggle control is removed.""" entity_id = "switch.test_fridge_top_zone_supercool" state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_OFF # Device stops reporting toggle controls mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: DeviceState( device=MOCK_DEVICE, controls=[] ) freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE async def test_single_zone_switch( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, platforms: list[Platform], ) -> None: """Test single zone device uses name without zone suffix.""" device = Device( device_id="single_zone_id", nickname="Single Zone Fridge", device_type=DeviceType.FRIDGE, device_name="K2601", ) mock_liebherr_client.get_devices.return_value = [device] single_zone_state = DeviceState( device=device, controls=[ TemperatureControl( zone_id=1, zone_position=ZonePosition.TOP, name="Fridge", type="fridge", value=4, target=4, min=2, max=8, unit=TemperatureUnit.CELSIUS, ), ToggleControl( name="supercool", type="ToggleControl", zone_id=1, zone_position=ZonePosition.TOP, value=False, ), ], ) mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: copy.deepcopy( single_zone_state ) mock_config_entry.add_to_hass(hass) with patch("homeassistant.components.liebherr.PLATFORMS", platforms): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/liebherr/test_switch.py", "license": "Apache License 2.0", "lines": 199, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/velux/switch.py
"""Support for Velux switches.""" from __future__ import annotations from typing import Any from pyvlx import OnOffSwitch from homeassistant.components.switch import SwitchEntity from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import VeluxConfigEntry from .entity import VeluxEntity, wrap_pyvlx_call_exceptions PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, config_entry: VeluxConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up switch(es) for Velux platform.""" pyvlx = config_entry.runtime_data async_add_entities( VeluxOnOffSwitch(node, config_entry.entry_id) for node in pyvlx.nodes if isinstance(node, OnOffSwitch) ) class VeluxOnOffSwitch(VeluxEntity, SwitchEntity): """Representation of a Velux on/off switch.""" _attr_name = None node: OnOffSwitch @property def is_on(self) -> bool: """Return true if switch is on.""" return self.node.is_on() @wrap_pyvlx_call_exceptions async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self.node.set_on() @wrap_pyvlx_call_exceptions async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self.node.set_off()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/velux/switch.py", "license": "Apache License 2.0", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/velux/test_switch.py
"""Test Velux switch entities.""" from unittest.mock import AsyncMock import pytest from pyvlx import PyVLXException from homeassistant.components.switch import ( DOMAIN as SWITCH_DOMAIN, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.const import STATE_OFF, STATE_ON, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import device_registry as dr, entity_registry as er from . import update_callback_entity from tests.common import MockConfigEntry, SnapshotAssertion, snapshot_platform # Apply setup_integration fixture to all tests in this module pytestmark = pytest.mark.usefixtures("setup_integration") @pytest.fixture def platform() -> Platform: """Fixture to specify platform to test.""" return Platform.SWITCH @pytest.mark.parametrize("mock_pyvlx", ["mock_onoff_switch"], indirect=True) async def test_switch_setup( hass: HomeAssistant, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, mock_pyvlx: AsyncMock, snapshot: SnapshotAssertion, ) -> None: """Snapshot the entity and validate registry metadata for switch entities.""" await snapshot_platform( hass, entity_registry, snapshot, mock_config_entry.entry_id, ) async def test_switch_device_association( hass: HomeAssistant, entity_registry: er.EntityRegistry, device_registry: dr.DeviceRegistry, mock_onoff_switch: AsyncMock, ) -> None: """Test switch device association.""" test_entity_id = f"switch.{mock_onoff_switch.name.lower().replace(' ', '_')}" entity_entry = entity_registry.async_get(test_entity_id) assert entity_entry is not None assert entity_entry.device_id is not None device_entry = device_registry.async_get(entity_entry.device_id) assert device_entry is not None assert ("velux", mock_onoff_switch.serial_number) in device_entry.identifiers assert device_entry.name == mock_onoff_switch.name async def test_switch_is_on(hass: HomeAssistant, mock_onoff_switch: AsyncMock) -> None: """Test switch on state.""" entity_id = f"switch.{mock_onoff_switch.name.lower().replace(' ', '_')}" # Initial state is off state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_OFF # Simulate switching on mock_onoff_switch.is_on.return_value = True mock_onoff_switch.is_off.return_value = False await update_callback_entity(hass, mock_onoff_switch) state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_ON async def test_switch_turn_on_off( hass: HomeAssistant, mock_onoff_switch: AsyncMock ) -> None: """Test turning switch on.""" entity_id = f"switch.{mock_onoff_switch.name.lower().replace(' ', '_')}" await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {"entity_id": entity_id}, blocking=True, ) mock_onoff_switch.set_on.assert_awaited_once() await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {"entity_id": entity_id}, blocking=True, ) mock_onoff_switch.set_off.assert_awaited_once() @pytest.mark.parametrize("mock_pyvlx", ["mock_onoff_switch"], indirect=True) async def test_switch_error_handling( hass: HomeAssistant, mock_onoff_switch: AsyncMock ) -> None: """Test error handling when turning switching fails.""" entity_id = f"switch.{mock_onoff_switch.name.lower().replace(' ', '_')}" mock_onoff_switch.set_on.side_effect = PyVLXException("Connection lost") mock_onoff_switch.set_off.side_effect = PyVLXException("Connection lost") with pytest.raises(HomeAssistantError): await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {"entity_id": entity_id}, blocking=True, ) with pytest.raises(HomeAssistantError): await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {"entity_id": entity_id}, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/velux/test_switch.py", "license": "Apache License 2.0", "lines": 106, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/onedrive_for_business/application_credentials.py
"""Application credentials platform for the OneDrive for Business integration.""" from __future__ import annotations from collections.abc import Generator from contextlib import contextmanager from contextvars import ContextVar from homeassistant.components.application_credentials import AuthorizationServer from homeassistant.core import HomeAssistant from .const import CONF_TENANT_ID, DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN _tenant_id_context: ContextVar[str] = ContextVar(f"{DOMAIN}_{CONF_TENANT_ID}") @contextmanager def tenant_id_context(tenant_id: str) -> Generator[None]: """Context manager for setting the active tenant ID.""" token = _tenant_id_context.set(tenant_id) try: yield finally: _tenant_id_context.reset(token) async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer: """Return authorization server.""" tenant_id = _tenant_id_context.get() return AuthorizationServer( authorize_url=OAUTH2_AUTHORIZE.format(tenant_id=tenant_id), token_url=OAUTH2_TOKEN.format(tenant_id=tenant_id), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/onedrive_for_business/application_credentials.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/onedrive_for_business/backup.py
"""Support for OneDrive backup.""" from __future__ import annotations from collections.abc import AsyncIterator, Callable, Coroutine from functools import wraps import logging from time import time from typing import Any, Concatenate from aiohttp import ClientTimeout from onedrive_personal_sdk.clients.large_file_upload import LargeFileUploadClient from onedrive_personal_sdk.exceptions import ( AuthenticationError, HashMismatchError, OneDriveException, ) from onedrive_personal_sdk.models.upload import FileInfo from homeassistant.components.backup import ( AgentBackup, BackupAgent, BackupAgentError, BackupNotFound, suggested_filename, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.json import json_dumps from homeassistant.util.json import json_loads_object from . import OneDriveConfigEntry from .const import CONF_FOLDER_ID, DATA_BACKUP_AGENT_LISTENERS, DOMAIN _LOGGER = logging.getLogger(__name__) MAX_CHUNK_SIZE = 60 * 1024 * 1024 # largest chunk possible, must be <= 60 MiB TARGET_CHUNKS = 20 TIMEOUT = ClientTimeout(connect=10, total=43200) # 12 hours CACHE_TTL = 300 async def async_get_backup_agents( hass: HomeAssistant, ) -> list[BackupAgent]: """Return a list of backup agents.""" entries: list[OneDriveConfigEntry] = hass.config_entries.async_loaded_entries( DOMAIN ) return [OneDriveBackupAgent(hass, entry) for entry in entries] @callback def async_register_backup_agents_listener( hass: HomeAssistant, *, listener: Callable[[], None], **kwargs: Any, ) -> Callable[[], None]: """Register a listener to be called when agents are added or removed.""" hass.data.setdefault(DATA_BACKUP_AGENT_LISTENERS, []).append(listener) @callback def remove_listener() -> None: """Remove the listener.""" hass.data[DATA_BACKUP_AGENT_LISTENERS].remove(listener) if not hass.data[DATA_BACKUP_AGENT_LISTENERS]: del hass.data[DATA_BACKUP_AGENT_LISTENERS] return remove_listener def handle_backup_errors[_R, **P]( func: Callable[Concatenate[OneDriveBackupAgent, P], Coroutine[Any, Any, _R]], ) -> Callable[Concatenate[OneDriveBackupAgent, P], Coroutine[Any, Any, _R]]: """Handle backup errors.""" @wraps(func) async def wrapper( self: OneDriveBackupAgent, *args: P.args, **kwargs: P.kwargs ) -> _R: try: return await func(self, *args, **kwargs) except AuthenticationError as err: self._entry.async_start_reauth(self._hass) raise BackupAgentError("Authentication error") from err except OneDriveException as err: _LOGGER.error( "Error during backup in %s:, message %s", func.__name__, err, ) _LOGGER.debug("Full error: %s", err, exc_info=True) raise BackupAgentError("Backup operation failed") from err except TimeoutError as err: _LOGGER.error( "Error during backup in %s: Timeout", func.__name__, ) raise BackupAgentError("Backup operation timed out") from err return wrapper def suggested_filenames(backup: AgentBackup) -> tuple[str, str]: """Return the suggested filenames for the backup and metadata.""" base_name = suggested_filename(backup).rsplit(".", 1)[0] return f"{base_name}.tar", f"{base_name}.metadata.json" class OneDriveBackupAgent(BackupAgent): """OneDrive backup agent.""" domain = DOMAIN def __init__(self, hass: HomeAssistant, entry: OneDriveConfigEntry) -> None: """Initialize the OneDrive backup agent.""" super().__init__() self._hass = hass self._entry = entry self._client = entry.runtime_data.client self._token_function = entry.runtime_data.token_function self._folder_id = entry.data[CONF_FOLDER_ID] self.name = entry.title assert entry.unique_id self.unique_id = entry.unique_id self._cache_backup_metadata: dict[str, AgentBackup] = {} self._cache_expiration = time() @handle_backup_errors async def async_download_backup( self, backup_id: str, **kwargs: Any ) -> AsyncIterator[bytes]: """Download a backup file.""" backup = await self._find_backup_by_id(backup_id) backup_filename, _ = suggested_filenames(backup) stream = await self._client.download_drive_item( f"{self._folder_id}:/{backup_filename}:", timeout=TIMEOUT ) return stream.iter_chunked(1024) @handle_backup_errors async def async_upload_backup( self, *, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], backup: AgentBackup, **kwargs: Any, ) -> None: """Upload a backup.""" backup_filename, metadata_filename = suggested_filenames(backup) file = FileInfo( backup_filename, backup.size, self._folder_id, await open_stream(), ) # determine chunk based on target chunks upload_chunk_size = backup.size / TARGET_CHUNKS # find the nearest multiple of 320KB upload_chunk_size = round(upload_chunk_size / (320 * 1024)) * (320 * 1024) # limit to max chunk size upload_chunk_size = min(upload_chunk_size, MAX_CHUNK_SIZE) # ensure minimum chunk size of 320KB upload_chunk_size = max(upload_chunk_size, 320 * 1024) try: await LargeFileUploadClient.upload( self._token_function, file, upload_chunk_size=upload_chunk_size, session=async_get_clientsession(self._hass), smart_chunk_size=True, ) except HashMismatchError as err: raise BackupAgentError( "Hash validation failed, backup file might be corrupt" ) from err _LOGGER.debug("Uploaded backup to %s", backup_filename) # Store metadata in separate metadata file (just backup.as_dict(), no extra fields) metadata_content = json_dumps(backup.as_dict()) try: await self._client.upload_file( self._folder_id, metadata_filename, metadata_content, ) except OneDriveException: # Clean up the backup file if metadata upload fails _LOGGER.debug( "Uploading metadata failed, deleting backup file %s", backup_filename ) await self._client.delete_drive_item( f"{self._folder_id}:/{backup_filename}:" ) raise _LOGGER.debug("Uploaded metadata file %s", metadata_filename) self._cache_expiration = time() @handle_backup_errors async def async_delete_backup( self, backup_id: str, **kwargs: Any, ) -> None: """Delete a backup file.""" backup = await self._find_backup_by_id(backup_id) backup_filename, metadata_filename = suggested_filenames(backup) await self._client.delete_drive_item(f"{self._folder_id}:/{backup_filename}:") await self._client.delete_drive_item(f"{self._folder_id}:/{metadata_filename}:") _LOGGER.debug("Deleted backup %s", backup_filename) self._cache_expiration = time() @handle_backup_errors async def async_list_backups(self, **kwargs: Any) -> list[AgentBackup]: """List backups.""" return list((await self._list_cached_metadata_files()).values()) @handle_backup_errors async def async_get_backup(self, backup_id: str, **kwargs: Any) -> AgentBackup: """Return a backup.""" return await self._find_backup_by_id(backup_id) async def _list_cached_metadata_files(self) -> dict[str, AgentBackup]: """List metadata files with a cache.""" if time() <= self._cache_expiration: return self._cache_backup_metadata async def _download_metadata(item_id: str) -> AgentBackup | None: """Download metadata file.""" try: metadata_stream = await self._client.download_drive_item(item_id) except OneDriveException as err: _LOGGER.warning("Error downloading metadata for %s: %s", item_id, err) return None return AgentBackup.from_dict( json_loads_object(await metadata_stream.read()) ) items = await self._client.list_drive_items(self._folder_id) # Build a set of backup filenames to check for orphaned metadata backup_filenames = { item.name for item in items if item.name and item.name.endswith(".tar") } metadata_files: dict[str, AgentBackup] = {} for item in items: if item.name and item.name.endswith(".metadata.json"): # Check if corresponding backup file exists backup_filename = f"{item.name[: -len('.metadata.json')]}.tar" if backup_filename not in backup_filenames: _LOGGER.warning( "Backup file %s not found for metadata %s", backup_filename, item.name, ) continue if metadata := await _download_metadata(item.id): metadata_files[metadata.backup_id] = metadata self._cache_backup_metadata = metadata_files self._cache_expiration = time() + CACHE_TTL return self._cache_backup_metadata async def _find_backup_by_id(self, backup_id: str) -> AgentBackup: """Find a backup by its backup ID on remote.""" metadata_files = await self._list_cached_metadata_files() if backup := metadata_files.get(backup_id): return backup raise BackupNotFound(f"Backup {backup_id} not found")
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/onedrive_for_business/backup.py", "license": "Apache License 2.0", "lines": 235, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/onedrive_for_business/config_flow.py
"""Config flow for OneDrive for Business.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any, cast from onedrive_personal_sdk.clients.client import OneDriveClient from onedrive_personal_sdk.exceptions import OneDriveException from onedrive_personal_sdk.models.items import Drive import voluptuous as vol from homeassistant.config_entries import ( SOURCE_REAUTH, SOURCE_RECONFIGURE, ConfigFlowResult, ) from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.config_entry_oauth2_flow import AbstractOAuth2FlowHandler from .application_credentials import tenant_id_context from .const import ( CONF_FOLDER_ID, CONF_FOLDER_PATH, CONF_TENANT_ID, DOMAIN, OAUTH_SCOPES, ) FOLDER_NAME_SCHEMA = vol.Schema({vol.Required(CONF_FOLDER_PATH): str}) class OneDriveForBusinessConfigFlow(AbstractOAuth2FlowHandler, domain=DOMAIN): """Config flow to handle OneDrive OAuth2 authentication.""" DOMAIN = DOMAIN client: OneDriveClient drive: Drive @property def logger(self) -> logging.Logger: """Return logger.""" return logging.getLogger(__name__) @property def extra_authorize_data(self) -> dict[str, Any]: """Extra data that needs to be appended to the authorize url.""" return {"scope": " ".join(OAUTH_SCOPES)} def __init__(self) -> None: """Initialize the OneDrive config flow.""" super().__init__() self._data: dict[str, Any] = {} async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" return await self.async_step_pick_tenant() async def async_step_pick_tenant( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Select the tenant id.""" if user_input is not None: self._data[CONF_TENANT_ID] = user_input[CONF_TENANT_ID] # Continue with OAuth flow using tenant context with tenant_id_context(user_input[CONF_TENANT_ID]): return await self.async_step_pick_implementation() return self.async_show_form( step_id="pick_tenant", data_schema=vol.Schema( { vol.Required(CONF_TENANT_ID): str, } ), description_placeholders={ "entra_url": "https://entra.microsoft.com/", "redirect_url": "https://my.home-assistant.io/redirect/oauth", }, ) async def async_step_pick_implementation( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the pick implementation step with tenant context.""" with tenant_id_context(self._data[CONF_TENANT_ID]): return await super().async_step_pick_implementation(user_input) async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult: """Handle the initial step.""" async def get_access_token() -> str: return cast(str, data[CONF_TOKEN][CONF_ACCESS_TOKEN]) self.client = OneDriveClient( get_access_token, async_get_clientsession(self.hass) ) try: self.drive = await self.client.get_drive() except OneDriveException: self.logger.exception("Failed to connect to OneDrive") return self.async_abort(reason="connection_error") except Exception: self.logger.exception("Unknown error") return self.async_abort(reason="unknown") await self.async_set_unique_id(self.drive.id) if self.source == SOURCE_REAUTH: self._abort_if_unique_id_mismatch(reason="wrong_drive") return self.async_update_reload_and_abort( entry=self._get_reauth_entry(), data_updates=data, ) if self.source == SOURCE_RECONFIGURE: self._abort_if_unique_id_mismatch(reason="wrong_drive") else: self._abort_if_unique_id_configured() self._data.update(data) if self.source == SOURCE_RECONFIGURE: return await self.async_step_reconfigure_folder() return await self.async_step_select_folder() async def async_step_select_folder( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Step to ask for the folder name.""" errors: dict[str, str] = {} if user_input is not None: try: path = str(user_input[CONF_FOLDER_PATH]).lstrip("/") folder = await self.client.create_folder("root", path) except OneDriveException: self.logger.debug("Failed to create folder", exc_info=True) errors["base"] = "folder_creation_error" if not errors: title = ( f"{self.drive.owner.user.display_name}'s OneDrive ({self.drive.owner.user.email})" if self.drive.owner and self.drive.owner.user and self.drive.owner.user.display_name and self.drive.owner.user.email else "OneDrive" ) return self.async_create_entry( title=title, data={ **self._data, CONF_FOLDER_ID: folder.id, CONF_FOLDER_PATH: user_input[CONF_FOLDER_PATH], }, ) return self.async_show_form( step_id="select_folder", data_schema=FOLDER_NAME_SCHEMA, errors=errors, ) async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Reconfigure the entry.""" self._data[CONF_TENANT_ID] = self._get_reconfigure_entry().data[CONF_TENANT_ID] with tenant_id_context(self._data[CONF_TENANT_ID]): return await self.async_step_pick_implementation() async def async_step_reconfigure_folder( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Step to ask for new folder path during reconfiguration.""" errors: dict[str, str] = {} reconfigure_entry = self._get_reconfigure_entry() if user_input is not None: path = str(user_input[CONF_FOLDER_PATH]).lstrip("/") try: folder = await self.client.create_folder("root", path) except OneDriveException: self.logger.debug("Failed to create folder", exc_info=True) errors["base"] = "folder_creation_error" if not errors: return self.async_update_reload_and_abort( reconfigure_entry, data={ **self._data, CONF_FOLDER_ID: folder.id, CONF_FOLDER_PATH: user_input[CONF_FOLDER_PATH], }, ) return self.async_show_form( step_id="reconfigure_folder", data_schema=self.add_suggested_values_to_schema( FOLDER_NAME_SCHEMA, {CONF_FOLDER_PATH: reconfigure_entry.data[CONF_FOLDER_PATH]}, ), errors=errors, ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Perform reauth upon an API authentication error.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm reauth dialog.""" if user_input is None: return self.async_show_form(step_id="reauth_confirm") self._data[CONF_TENANT_ID] = self._get_reauth_entry().data[CONF_TENANT_ID] with tenant_id_context(self._data[CONF_TENANT_ID]): return await self.async_step_pick_implementation()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/onedrive_for_business/config_flow.py", "license": "Apache License 2.0", "lines": 190, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/onedrive_for_business/const.py
"""Constants for the OneDrive for Business integration.""" from collections.abc import Callable from typing import Final from homeassistant.util.hass_dict import HassKey DOMAIN: Final = "onedrive_for_business" CONF_FOLDER_PATH: Final = "folder_path" CONF_FOLDER_ID: Final = "folder_id" CONF_TENANT_ID: Final = "tenant_id" OAUTH2_AUTHORIZE: Final = ( "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize" ) OAUTH2_TOKEN: Final = "https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token" OAUTH_SCOPES: Final = [ "Files.ReadWrite.All", "offline_access", "openid", ] DATA_BACKUP_AGENT_LISTENERS: HassKey[list[Callable[[], None]]] = HassKey( f"{DOMAIN}.backup_agent_listeners" )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/onedrive_for_business/const.py", "license": "Apache License 2.0", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/onedrive_for_business/const.py
"""Consts for OneDrive tests.""" from onedrive_personal_sdk.models.items import IdentitySet, User CLIENT_ID = "1234" CLIENT_SECRET = "5678" TENANT_ID = "test_tenant_id" BACKUP_METADATA = { "addons": [], "backup_id": "23e64aec", "date": "2024-11-22T11:48:48.727189+01:00", "database_included": True, "extra_metadata": {}, "folders": [], "homeassistant_included": True, "homeassistant_version": "2024.12.0.dev0", "name": "Core 2024.12.0.dev0", "protected": False, "size": 34519040, } INSTANCE_ID = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0" IDENTITY_SET = IdentitySet( user=User( display_name="John Doe", id="id", email="john@doe.com", ) )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/onedrive_for_business/const.py", "license": "Apache License 2.0", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/onedrive_for_business/test_backup.py
"""Test the backups for OneDrive for Business.""" from __future__ import annotations from collections.abc import AsyncGenerator from io import StringIO from unittest.mock import Mock, patch from onedrive_personal_sdk.exceptions import ( AuthenticationError, HashMismatchError, OneDriveException, ) from onedrive_personal_sdk.models.items import File import pytest from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, AgentBackup from homeassistant.components.onedrive_for_business.backup import ( async_register_backup_agents_listener, ) from homeassistant.components.onedrive_for_business.const import ( DATA_BACKUP_AGENT_LISTENERS, DOMAIN, ) from homeassistant.config_entries import SOURCE_REAUTH from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from . import setup_integration from .const import BACKUP_METADATA from tests.common import AsyncMock, MockConfigEntry from tests.typing import ClientSessionGenerator, MagicMock, WebSocketGenerator @pytest.fixture(autouse=True) async def setup_backup_integration( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> AsyncGenerator[None]: """Set up onedrive integration.""" with ( patch("homeassistant.components.backup.is_hassio", return_value=False), patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0), ): assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) await setup_integration(hass, mock_config_entry) await hass.async_block_till_done() yield async def test_agents_info( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_config_entry: MockConfigEntry, ) -> None: """Test backup agent info.""" client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/agents/info"}) response = await client.receive_json() assert response["success"] assert response["result"] == { "agents": [ {"agent_id": "backup.local", "name": "local"}, { "agent_id": f"{DOMAIN}.{mock_config_entry.unique_id}", "name": mock_config_entry.title, }, ], } async def test_agents_list_backups( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, ) -> None: """Test agent list backups.""" client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/info"}) response = await client.receive_json() assert response["success"] assert response["result"]["agent_errors"] == {} assert response["result"]["backups"] == [ { "addons": [], "agents": { "onedrive_for_business.mock_drive_id": { "protected": False, "size": 34519040, } }, "backup_id": "23e64aec", "database_included": True, "date": "2024-11-22T11:48:48.727189+01:00", "extra_metadata": {}, "failed_addons": [], "failed_agent_ids": [], "failed_folders": [], "folders": [], "homeassistant_included": True, "homeassistant_version": "2024.12.0.dev0", "name": "Core 2024.12.0.dev0", "with_automatic_settings": None, } ] async def test_agents_list_backups_with_download_failure( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_onedrive_client: MagicMock, ) -> None: """Test agent list backups still works if one of the items fails to download.""" mock_onedrive_client.download_drive_item.side_effect = OneDriveException("test") client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/info"}) response = await client.receive_json() assert response["success"] assert response["result"]["agent_errors"] == {} assert response["result"]["backups"] == [] async def test_agents_get_backup( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_config_entry: MockConfigEntry, ) -> None: """Test agent get backup.""" backup_id = BACKUP_METADATA["backup_id"] client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/details", "backup_id": backup_id}) response = await client.receive_json() assert response["success"] assert response["result"]["agent_errors"] == {} assert response["result"]["backup"] == { "addons": [], "agents": { f"{DOMAIN}.{mock_config_entry.unique_id}": { "protected": False, "size": 34519040, } }, "backup_id": "23e64aec", "database_included": True, "date": "2024-11-22T11:48:48.727189+01:00", "extra_metadata": {}, "failed_addons": [], "failed_agent_ids": [], "failed_folders": [], "folders": [], "homeassistant_included": True, "homeassistant_version": "2024.12.0.dev0", "name": "Core 2024.12.0.dev0", "with_automatic_settings": None, } async def test_agents_get_backup_missing_file( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_config_entry: MockConfigEntry, mock_onedrive_client: MagicMock, mock_metadata_file: File, caplog: pytest.LogCaptureFixture, ) -> None: """Test what happens when only metadata exists.""" mock_onedrive_client.list_drive_items.return_value = [mock_metadata_file] backup_id = BACKUP_METADATA["backup_id"] client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/details", "backup_id": backup_id}) response = await client.receive_json() assert response["success"] assert response["result"]["agent_errors"] == {} assert response["result"]["backup"] is None assert ( "Backup file 23e64aec.tar not found for metadata 23e64aec.metadata.json" in caplog.text ) async def test_agents_delete( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_onedrive_client: MagicMock, ) -> None: """Test agent delete backup.""" client = await hass_ws_client(hass) await client.send_json_auto_id( { "type": "backup/delete", "backup_id": BACKUP_METADATA["backup_id"], } ) response = await client.receive_json() assert response["success"] assert response["result"] == {"agent_errors": {}} assert mock_onedrive_client.delete_drive_item.call_count == 2 async def test_agents_upload( hass_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture, mock_onedrive_client: MagicMock, mock_large_file_upload_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test agent upload backup.""" client = await hass_client() test_backup = AgentBackup.from_dict(BACKUP_METADATA) with ( patch( "homeassistant.components.backup.manager.BackupManager.async_get_backup", ) as fetch_backup, patch( "homeassistant.components.backup.manager.read_backup", return_value=test_backup, ), patch("pathlib.Path.open") as mocked_open, ): mocked_open.return_value.read = Mock(side_effect=[b"test", b""]) fetch_backup.return_value = test_backup resp = await client.post( f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.unique_id}", data={"file": StringIO("test")}, ) assert resp.status == 201 assert f"Uploading backup {test_backup.backup_id}" in caplog.text mock_large_file_upload_client.assert_called_once() async def test_agents_upload_corrupt_upload( hass_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture, mock_onedrive_client: MagicMock, mock_large_file_upload_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test hash validation fails.""" mock_large_file_upload_client.side_effect = HashMismatchError("test") client = await hass_client() test_backup = AgentBackup.from_dict(BACKUP_METADATA) with ( patch( "homeassistant.components.backup.manager.BackupManager.async_get_backup", ) as fetch_backup, patch( "homeassistant.components.backup.manager.read_backup", return_value=test_backup, ), patch("pathlib.Path.open") as mocked_open, ): mocked_open.return_value.read = Mock(side_effect=[b"test", b""]) fetch_backup.return_value = test_backup resp = await client.post( f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.unique_id}", data={"file": StringIO("test")}, ) assert resp.status == 201 assert f"Uploading backup {test_backup.backup_id}" in caplog.text mock_large_file_upload_client.assert_called_once() assert mock_onedrive_client.update_drive_item.call_count == 0 assert "Hash validation failed, backup file might be corrupt" in caplog.text async def test_agents_upload_metadata_upload_failed( hass_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture, mock_onedrive_client: MagicMock, mock_large_file_upload_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test metadata upload fails.""" client = await hass_client() test_backup = AgentBackup.from_dict(BACKUP_METADATA) mock_onedrive_client.upload_file.side_effect = OneDriveException("test") with ( patch( "homeassistant.components.backup.manager.BackupManager.async_get_backup", ) as fetch_backup, patch( "homeassistant.components.backup.manager.read_backup", return_value=test_backup, ), patch("pathlib.Path.open") as mocked_open, ): mocked_open.return_value.read = Mock(side_effect=[b"test", b""]) fetch_backup.return_value = test_backup resp = await client.post( f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.unique_id}", data={"file": StringIO("test")}, ) assert resp.status == 201 assert f"Uploading backup {test_backup.backup_id}" in caplog.text mock_large_file_upload_client.assert_called_once() mock_onedrive_client.delete_drive_item.assert_called_once() assert mock_onedrive_client.update_drive_item.call_count == 0 async def test_agents_download( hass_client: ClientSessionGenerator, mock_onedrive_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test agent download backup.""" client = await hass_client() backup_id = BACKUP_METADATA["backup_id"] resp = await client.get( f"/api/backup/download/{backup_id}?agent_id={DOMAIN}.{mock_config_entry.unique_id}" ) assert resp.status == 200 assert await resp.content.read() == b"backup data" async def test_error_on_agents_download( hass_client: ClientSessionGenerator, mock_onedrive_client: MagicMock, mock_config_entry: MockConfigEntry, mock_backup_file: File, mock_metadata_file: File, ) -> None: """Test we get not found on an not existing backup on download.""" client = await hass_client() backup_id = BACKUP_METADATA["backup_id"] mock_onedrive_client.list_drive_items.side_effect = [ [mock_backup_file, mock_metadata_file], [], ] with patch("homeassistant.components.onedrive_for_business.backup.CACHE_TTL", -1): resp = await client.get( f"/api/backup/download/{backup_id}?agent_id={DOMAIN}.{mock_config_entry.unique_id}" ) assert resp.status == 404 @pytest.mark.parametrize( ("side_effect", "error"), [ ( OneDriveException(), "Backup operation failed", ), (TimeoutError(), "Backup operation timed out"), ], ) async def test_delete_error( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_onedrive_client: MagicMock, mock_config_entry: MockConfigEntry, side_effect: Exception, error: str, ) -> None: """Test error during delete.""" mock_onedrive_client.delete_drive_item.side_effect = AsyncMock( side_effect=side_effect ) client = await hass_ws_client(hass) await client.send_json_auto_id( { "type": "backup/delete", "backup_id": BACKUP_METADATA["backup_id"], } ) response = await client.receive_json() assert response["success"] assert response["result"] == { "agent_errors": {f"{DOMAIN}.{mock_config_entry.unique_id}": error} } async def test_agents_delete_not_found_does_not_throw( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_onedrive_client: MagicMock, ) -> None: """Test agent delete backup.""" mock_onedrive_client.list_drive_items.return_value = [] client = await hass_ws_client(hass) await client.send_json_auto_id( { "type": "backup/delete", "backup_id": BACKUP_METADATA["backup_id"], } ) response = await client.receive_json() assert response["success"] assert response["result"] == {"agent_errors": {}} async def test_agents_backup_not_found( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_onedrive_client: MagicMock, ) -> None: """Test backup not found.""" mock_onedrive_client.list_drive_items.return_value = [] backup_id = BACKUP_METADATA["backup_id"] client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/details", "backup_id": backup_id}) response = await client.receive_json() assert response["success"] assert response["result"]["backup"] is None async def test_reauth_on_403( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_onedrive_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test we re-authenticate on 403.""" mock_onedrive_client.list_drive_items.side_effect = AuthenticationError( 403, "Auth failed" ) backup_id = BACKUP_METADATA["backup_id"] client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/details", "backup_id": backup_id}) response = await client.receive_json() assert response["success"] assert response["result"]["agent_errors"] == { f"{DOMAIN}.{mock_config_entry.unique_id}": "Authentication error" } await hass.async_block_till_done() flows = hass.config_entries.flow.async_progress() assert len(flows) == 1 flow = flows[0] assert flow["step_id"] == "reauth_confirm" assert flow["handler"] == DOMAIN assert "context" in flow assert flow["context"]["source"] == SOURCE_REAUTH assert flow["context"]["entry_id"] == mock_config_entry.entry_id async def test_listeners_get_cleaned_up(hass: HomeAssistant) -> None: """Test listener gets cleaned up.""" listener = MagicMock() remove_listener = async_register_backup_agents_listener(hass, listener=listener) # make sure it's the last listener hass.data[DATA_BACKUP_AGENT_LISTENERS] = [listener] remove_listener() assert hass.data.get(DATA_BACKUP_AGENT_LISTENERS) is None
{ "repo_id": "home-assistant/core", "file_path": "tests/components/onedrive_for_business/test_backup.py", "license": "Apache License 2.0", "lines": 401, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/onedrive_for_business/test_config_flow.py
"""Test the OneDrive config flow.""" from http import HTTPStatus from unittest.mock import AsyncMock, MagicMock from onedrive_personal_sdk.exceptions import OneDriveException from onedrive_personal_sdk.models.items import Drive, IdentitySet import pytest from homeassistant import config_entries from homeassistant.components.onedrive_for_business.const import ( CONF_FOLDER_ID, CONF_FOLDER_PATH, CONF_TENANT_ID, DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN, ) from homeassistant.config_entries import ConfigFlowResult from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers import config_entry_oauth2_flow from . import setup_integration from .const import CLIENT_ID, TENANT_ID from tests.common import MockConfigEntry from tests.test_util.aiohttp import AiohttpClientMocker from tests.typing import ClientSessionGenerator async def _do_get_token( hass: HomeAssistant, result: ConfigFlowResult, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, ) -> None: state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) scope = "Files.ReadWrite.All+offline_access+openid" authorize_url = OAUTH2_AUTHORIZE.format(tenant_id=TENANT_ID) token_url = OAUTH2_TOKEN.format(tenant_id=TENANT_ID) assert result["url"] == ( f"{authorize_url}?response_type=code&client_id={CLIENT_ID}" "&redirect_uri=https://example.com/auth/external/callback" f"&state={state}&scope={scope}" ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == HTTPStatus.OK assert resp.headers["content-type"] == "text/html; charset=utf-8" aioclient_mock.post( token_url, json={ "refresh_token": "mock-refresh-token", "access_token": "mock-access-token", "type": "Bearer", "expires_in": 60, }, ) @pytest.mark.usefixtures("current_request_with_host") async def test_full_flow( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_setup_entry: AsyncMock, mock_onedrive_client_init: MagicMock, ) -> None: """Check full flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "pick_tenant" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_TENANT_ID: TENANT_ID} ) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) result = await hass.config_entries.flow.async_configure(result["flow_id"]) # Ensure the token callback is set up correctly token_callback = mock_onedrive_client_init.call_args[0][0] assert await token_callback() == "mock-access-token" assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_FOLDER_PATH: "myFolder"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert len(mock_setup_entry.mock_calls) == 1 assert result["title"] == "John Doe's OneDrive (john@doe.com)" assert result["result"].unique_id == "mock_drive_id" assert result["data"][CONF_TOKEN][CONF_ACCESS_TOKEN] == "mock-access-token" assert result["data"][CONF_TOKEN]["refresh_token"] == "mock-refresh-token" assert result["data"][CONF_FOLDER_PATH] == "myFolder" assert result["data"][CONF_FOLDER_ID] == "my_folder_id" @pytest.mark.usefixtures("current_request_with_host") async def test_full_flow_with_owner_not_found( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_setup_entry: AsyncMock, mock_onedrive_client: MagicMock, mock_drive: Drive, ) -> None: """Ensure we get a default title if the drive's owner can't be read.""" mock_drive.owner = IdentitySet(user=None) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "pick_tenant" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_TENANT_ID: TENANT_ID} ) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_FOLDER_PATH: "myFolder"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert len(mock_setup_entry.mock_calls) == 1 assert result["title"] == "OneDrive" assert result["result"].unique_id == "mock_drive_id" assert result["data"][CONF_TOKEN][CONF_ACCESS_TOKEN] == "mock-access-token" assert result["data"][CONF_TOKEN]["refresh_token"] == "mock-refresh-token" assert result["data"][CONF_FOLDER_PATH] == "myFolder" assert result["data"][CONF_FOLDER_ID] == "my_folder_id" mock_onedrive_client.reset_mock() @pytest.mark.usefixtures("current_request_with_host") async def test_error_during_folder_creation( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_setup_entry: AsyncMock, mock_onedrive_client: MagicMock, ) -> None: """Ensure we can create the backup folder.""" mock_onedrive_client.create_folder.side_effect = OneDriveException() result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "pick_tenant" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_TENANT_ID: TENANT_ID} ) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_FOLDER_PATH: "myFolder"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "folder_creation_error"} mock_onedrive_client.create_folder.side_effect = None # clear error and try again result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_FOLDER_PATH: "myFolder"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "John Doe's OneDrive (john@doe.com)" assert result["result"].unique_id == "mock_drive_id" assert result["data"][CONF_TOKEN][CONF_ACCESS_TOKEN] == "mock-access-token" assert result["data"][CONF_TOKEN]["refresh_token"] == "mock-refresh-token" assert result["data"][CONF_FOLDER_PATH] == "myFolder" assert result["data"][CONF_FOLDER_ID] == "my_folder_id" @pytest.mark.usefixtures("current_request_with_host") @pytest.mark.parametrize( ("exception", "error"), [ (Exception, "unknown"), (OneDriveException, "connection_error"), ], ) async def test_flow_errors( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_onedrive_client: MagicMock, exception: Exception, error: str, ) -> None: """Test errors during flow.""" mock_onedrive_client.get_drive.side_effect = exception result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "pick_tenant" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_TENANT_ID: TENANT_ID} ) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.ABORT assert result["reason"] == error @pytest.mark.usefixtures("current_request_with_host") async def test_already_configured( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test already configured account.""" await setup_integration(hass, mock_config_entry) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "pick_tenant" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_TENANT_ID: TENANT_ID} ) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" @pytest.mark.usefixtures("current_request_with_host") async def test_reconfigure_flow( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_onedrive_client: MagicMock, mock_config_entry: MockConfigEntry, mock_setup_entry: AsyncMock, ) -> None: """Test reconfigure flow.""" await setup_integration(hass, mock_config_entry) result = await mock_config_entry.start_reconfigure_flow(hass) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reconfigure_folder" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_FOLDER_PATH: "new/folder/path"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reconfigure_successful" assert mock_config_entry.data[CONF_FOLDER_PATH] == "new/folder/path" assert mock_config_entry.data[CONF_FOLDER_ID] == "my_folder_id" assert mock_config_entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN] == "mock-access-token" assert mock_config_entry.data[CONF_TOKEN]["refresh_token"] == "mock-refresh-token" @pytest.mark.usefixtures("current_request_with_host") async def test_reconfigure_flow_error( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_onedrive_client: MagicMock, mock_config_entry: MockConfigEntry, mock_setup_entry: AsyncMock, ) -> None: """Test reconfigure flow errors.""" mock_config_entry.add_to_hass(hass) await hass.async_block_till_done() result = await mock_config_entry.start_reconfigure_flow(hass) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reconfigure_folder" mock_onedrive_client.create_folder.side_effect = OneDriveException() result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_FOLDER_PATH: "new/folder/path"} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reconfigure_folder" assert result["errors"] == {"base": "folder_creation_error"} # clear side effect and try again mock_onedrive_client.create_folder.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_FOLDER_PATH: "new/folder/path"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reconfigure_successful" assert mock_config_entry.data[CONF_FOLDER_PATH] == "new/folder/path" assert mock_config_entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN] == "mock-access-token" assert mock_config_entry.data[CONF_TOKEN]["refresh_token"] == "mock-refresh-token" @pytest.mark.usefixtures("current_request_with_host") async def test_reconfigure_flow_wrong_drive( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, mock_drive: Drive, ) -> None: """Test that the reconfigure flow fails on a different drive id.""" mock_drive.id = "other_drive_id" mock_config_entry.add_to_hass(hass) await hass.async_block_till_done() result = await mock_config_entry.start_reconfigure_flow(hass) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) @pytest.mark.usefixtures("current_request_with_host") async def test_reauth_flow( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test that the reauth flow works.""" await setup_integration(hass, mock_config_entry) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN] == "mock-access-token" assert mock_config_entry.data[CONF_TOKEN]["refresh_token"] == "mock-refresh-token" assert mock_config_entry.data[CONF_FOLDER_PATH] == "backups/home_assistant" assert mock_config_entry.data[CONF_FOLDER_ID] == "my_folder_id" assert mock_config_entry.data[CONF_TENANT_ID] == TENANT_ID @pytest.mark.usefixtures("current_request_with_host") async def test_reauth_flow_id_changed( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, mock_drive: Drive, ) -> None: """Test that the reauth flow fails on a different drive id.""" await setup_integration(hass, mock_config_entry) mock_drive.id = "other_drive_id" result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) await _do_get_token(hass, result, hass_client_no_auth, aioclient_mock) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "wrong_drive" assert mock_config_entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN] == "mock-access-token" assert mock_config_entry.data[CONF_TOKEN]["refresh_token"] == "mock-refresh-token" assert mock_config_entry.data[CONF_FOLDER_PATH] == "backups/home_assistant" assert mock_config_entry.data[CONF_FOLDER_ID] == "my_folder_id" assert mock_config_entry.data[CONF_TENANT_ID] == TENANT_ID
{ "repo_id": "home-assistant/core", "file_path": "tests/components/onedrive_for_business/test_config_flow.py", "license": "Apache License 2.0", "lines": 341, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/onedrive_for_business/test_init.py
"""Test the OneDrive setup.""" from copy import copy from unittest.mock import MagicMock, patch from onedrive_personal_sdk.exceptions import ( AuthenticationError, NotFoundError, OneDriveException, ) from onedrive_personal_sdk.models.items import Folder import pytest from homeassistant.components.onedrive_for_business.const import ( CONF_FOLDER_ID, CONF_FOLDER_PATH, ) from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers.config_entry_oauth2_flow import ( ImplementationUnavailableError, ) from . import setup_integration from tests.common import MockConfigEntry async def test_load_unload_config_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_onedrive_client_init: MagicMock, mock_onedrive_client: MagicMock, ) -> None: """Test loading and unloading the integration.""" await setup_integration(hass, mock_config_entry) # Ensure the token callback is set up correctly token_callback = mock_onedrive_client_init.call_args[0][0] assert await token_callback() == "mock-access-token" # make sure metadata migration is not called assert mock_onedrive_client.upload_file.call_count == 0 assert mock_onedrive_client.update_drive_item.call_count == 0 assert mock_config_entry.state is ConfigEntryState.LOADED await hass.config_entries.async_unload(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.NOT_LOADED @pytest.mark.parametrize( ("side_effect", "state"), [ (AuthenticationError(403, "Auth failed"), ConfigEntryState.SETUP_ERROR), (OneDriveException(), ConfigEntryState.SETUP_RETRY), ], ) async def test_approot_errors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_onedrive_client: MagicMock, side_effect: Exception, state: ConfigEntryState, ) -> None: """Test errors during approot retrieval.""" mock_onedrive_client.get_drive_item.side_effect = side_effect await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is state async def test_get_integration_folder_creation( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_onedrive_client: MagicMock, mock_folder: Folder, ) -> None: """Test faulty integration folder creation.""" folder_name = copy(mock_config_entry.data[CONF_FOLDER_PATH]) mock_onedrive_client.get_drive_item.side_effect = NotFoundError(404, "Not found") await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED mock_onedrive_client.create_folder.assert_called_once_with( parent_id="root", name=folder_name, ) # ensure the folder id and name are updated assert mock_config_entry.data[CONF_FOLDER_ID] == mock_folder.id assert mock_config_entry.data[CONF_FOLDER_PATH] == folder_name async def test_get_integration_folder_creation_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_onedrive_client: MagicMock, caplog: pytest.LogCaptureFixture, ) -> None: """Test faulty integration folder creation error.""" mock_onedrive_client.get_drive_item.side_effect = NotFoundError(404, "Not found") mock_onedrive_client.create_folder.side_effect = OneDriveException() await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY assert "Failed to get backups/home_assistant folder" in caplog.text async def test_oauth_implementation_not_available( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test that unavailable OAuth implementation raises ConfigEntryNotReady.""" mock_config_entry.add_to_hass(hass) with patch( "homeassistant.components.onedrive_for_business.async_get_config_entry_implementation", side_effect=ImplementationUnavailableError, ): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
{ "repo_id": "home-assistant/core", "file_path": "tests/components/onedrive_for_business/test_init.py", "license": "Apache License 2.0", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/evohome/services.py
"""Service handlers for the Evohome integration.""" from __future__ import annotations from datetime import timedelta from typing import Any, Final from evohomeasync2.const import SZ_CAN_BE_TEMPORARY, SZ_SYSTEM_MODE, SZ_TIMING_MODE from evohomeasync2.schemas.const import ( S2_DURATION as SZ_DURATION, S2_PERIOD as SZ_PERIOD, SystemMode as EvoSystemMode, ) import voluptuous as vol from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN from homeassistant.const import ATTR_MODE from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.helpers import config_validation as cv, service from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.service import verify_domain_control from .const import ATTR_DURATION, ATTR_PERIOD, ATTR_SETPOINT, DOMAIN, EvoService from .coordinator import EvoDataUpdateCoordinator # system mode schemas are built dynamically when the services are registered # because supported modes can vary for edge-case systems # Zone service schemas (registered as entity services) CLEAR_ZONE_OVERRIDE_SCHEMA: Final[dict[str | vol.Marker, Any]] = {} SET_ZONE_OVERRIDE_SCHEMA: Final[dict[str | vol.Marker, Any]] = { vol.Required(ATTR_SETPOINT): vol.All( vol.Coerce(float), vol.Range(min=4.0, max=35.0) ), vol.Optional(ATTR_DURATION): vol.All( cv.time_period, vol.Range(min=timedelta(days=0), max=timedelta(days=1)), ), } def _register_zone_entity_services(hass: HomeAssistant) -> None: """Register entity-level services for zones.""" service.async_register_platform_entity_service( hass, DOMAIN, EvoService.CLEAR_ZONE_OVERRIDE, entity_domain=CLIMATE_DOMAIN, schema=CLEAR_ZONE_OVERRIDE_SCHEMA, func="async_clear_zone_override", ) service.async_register_platform_entity_service( hass, DOMAIN, EvoService.SET_ZONE_OVERRIDE, entity_domain=CLIMATE_DOMAIN, schema=SET_ZONE_OVERRIDE_SCHEMA, func="async_set_zone_override", ) @callback def setup_service_functions( hass: HomeAssistant, coordinator: EvoDataUpdateCoordinator ) -> None: """Set up the service handlers for the system/zone operating modes. Not all Honeywell TCC-compatible systems support all operating modes. In addition, each mode will require any of four distinct service schemas. This has to be enumerated before registering the appropriate handlers. """ @verify_domain_control(DOMAIN) async def force_refresh(call: ServiceCall) -> None: """Obtain the latest state data via the vendor's RESTful API.""" await coordinator.async_refresh() @verify_domain_control(DOMAIN) async def set_system_mode(call: ServiceCall) -> None: """Set the system mode.""" assert coordinator.tcs is not None # mypy payload = { "unique_id": coordinator.tcs.id, "service": call.service, "data": call.data, } async_dispatcher_send(hass, DOMAIN, payload) assert coordinator.tcs is not None # mypy hass.services.async_register(DOMAIN, EvoService.REFRESH_SYSTEM, force_refresh) # Enumerate which operating modes are supported by this system modes = list(coordinator.tcs.allowed_system_modes) # Not all systems support "AutoWithReset": register this handler only if required if any( m[SZ_SYSTEM_MODE] for m in modes if m[SZ_SYSTEM_MODE] == EvoSystemMode.AUTO_WITH_RESET ): hass.services.async_register(DOMAIN, EvoService.RESET_SYSTEM, set_system_mode) system_mode_schemas = [] modes = [m for m in modes if m[SZ_SYSTEM_MODE] != EvoSystemMode.AUTO_WITH_RESET] # Permanent-only modes will use this schema perm_modes = [m[SZ_SYSTEM_MODE] for m in modes if not m[SZ_CAN_BE_TEMPORARY]] if perm_modes: # any of: "Auto", "HeatingOff": permanent only schema = vol.Schema({vol.Required(ATTR_MODE): vol.In(perm_modes)}) system_mode_schemas.append(schema) modes = [m for m in modes if m[SZ_CAN_BE_TEMPORARY]] # These modes are set for a number of hours (or indefinitely): use this schema temp_modes = [m[SZ_SYSTEM_MODE] for m in modes if m[SZ_TIMING_MODE] == SZ_DURATION] if temp_modes: # any of: "AutoWithEco", permanent or for 0-24 hours schema = vol.Schema( { vol.Required(ATTR_MODE): vol.In(temp_modes), vol.Optional(ATTR_DURATION): vol.All( cv.time_period, vol.Range(min=timedelta(hours=0), max=timedelta(hours=24)), ), } ) system_mode_schemas.append(schema) # These modes are set for a number of days (or indefinitely): use this schema temp_modes = [m[SZ_SYSTEM_MODE] for m in modes if m[SZ_TIMING_MODE] == SZ_PERIOD] if temp_modes: # any of: "Away", "Custom", "DayOff", permanent or for 1-99 days schema = vol.Schema( { vol.Required(ATTR_MODE): vol.In(temp_modes), vol.Optional(ATTR_PERIOD): vol.All( cv.time_period, vol.Range(min=timedelta(days=1), max=timedelta(days=99)), ), } ) system_mode_schemas.append(schema) if system_mode_schemas: hass.services.async_register( DOMAIN, EvoService.SET_SYSTEM_MODE, set_system_mode, schema=vol.Schema(vol.Any(*system_mode_schemas)), ) _register_zone_entity_services(hass)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/evohome/services.py", "license": "Apache License 2.0", "lines": 126, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/knx/storage/time_server.py
"""Time server controller for KNX integration.""" from __future__ import annotations from typing import Any, TypedDict import voluptuous as vol from xknx import XKNX from ..expose import KnxExposeTime, create_time_server_exposures from .entity_store_validation import validate_config_store_data from .knx_selector import GASelector class KNXTimeServerStoreModel(TypedDict, total=False): """Represent KNX time server configuration store data.""" time: dict[str, Any] | None date: dict[str, Any] | None datetime: dict[str, Any] | None TIME_SERVER_CONFIG_SCHEMA = vol.Schema( { vol.Optional("time"): GASelector( state=False, passive=False, valid_dpt="10.001" ), vol.Optional("date"): GASelector( state=False, passive=False, valid_dpt="11.001" ), vol.Optional("datetime"): GASelector( state=False, passive=False, valid_dpt="19.001" ), } ) def validate_time_server_data(time_server_data: dict) -> KNXTimeServerStoreModel: """Validate time server data. Return validated data or raise EntityStoreValidationException. """ return validate_config_store_data(TIME_SERVER_CONFIG_SCHEMA, time_server_data) # type: ignore[return-value] class TimeServerController: """Controller class for UI time exposures.""" def __init__(self) -> None: """Initialize time server controller.""" self.time_exposes: list[KnxExposeTime] = [] def stop(self) -> None: """Shutdown time server controller.""" for expose in self.time_exposes: expose.async_remove() self.time_exposes.clear() def start(self, xknx: XKNX, config: KNXTimeServerStoreModel) -> None: """Update time server configuration.""" if self.time_exposes: self.stop() self.time_exposes = create_time_server_exposures(xknx, config)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/knx/storage/time_server.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/knx/test_time_server.py
"""Test KNX time server.""" import pytest from homeassistant.core import HomeAssistant from .conftest import KNXTestKit from tests.typing import WebSocketGenerator # Freeze time: 2026-1-29 11:02:03 UTC -> Europe/Vienna (UTC+1) = 12:02:03 Thursday FREEZE_TIME = "2026-1-29 11:02:03" # KNX Time DPT 10.001: Day of week + time # 0x8C = 0b10001100 = Thursday (100) + 12 hours (01100) # 0x02 = 2 minutes # 0x03 = 3 seconds RAW_TIME = (0x8C, 0x02, 0x03) # KNX Date DPT 11.001 # 0x1D = 29th day # 0x01 = January (month 1) # 0x1A = 26 (2026 - 2000) RAW_DATE = (0x1D, 0x01, 0x1A) # KNX DateTime DPT 19.001: Year, Month, Day, Hour+DoW, Minutes, Seconds, Flags, Quality # 0x7E = 126 (offset from 1900) # 0x01 = January # 0x1D = 29th day # 0x8C = Thursday + 12 hours # 0x02 = 2 minutes # 0x03 = 3 seconds # 0x20 = ignore working day flag, no DST # 0xC0 = external sync, reliable source RAW_DATETIME = (0x7E, 0x01, 0x1D, 0x8C, 0x02, 0x03, 0x20, 0xC0) @pytest.mark.freeze_time(FREEZE_TIME) @pytest.mark.parametrize( ("config", "expected_telegrams"), [ ( {"time": {"write": "1/1/1"}}, {"1/1/1": RAW_TIME}, ), ( {"date": {"write": "2/2/2"}}, {"2/2/2": RAW_DATE}, ), ( {"datetime": {"write": "3/3/3"}}, {"3/3/3": RAW_DATETIME}, ), ( {"time": {"write": "1/1/1"}, "date": {"write": "2/2/2"}}, { "1/1/1": RAW_TIME, "2/2/2": RAW_DATE, }, ), ( {"date": {"write": "2/2/2"}, "datetime": {"write": "3/3/3"}}, { "2/2/2": RAW_DATE, "3/3/3": RAW_DATETIME, }, ), ], ) async def test_time_server_write_format( hass: HomeAssistant, knx: KNXTestKit, hass_ws_client: WebSocketGenerator, config: dict, expected_telegrams: dict[str, tuple], ) -> None: """Test time server writes each format when configured.""" await hass.config.async_set_time_zone("Europe/Vienna") await knx.setup_integration({}) client = await hass_ws_client(hass) # Get initial empty configuration await client.send_json_auto_id({"type": "knx/get_time_server_config"}) res = await client.receive_json() assert res["success"], res assert res["result"] == {} # Update time server config to enable format await client.send_json_auto_id( {"type": "knx/update_time_server_config", "config": config} ) res = await client.receive_json() assert res["success"], res # Verify telegrams are written for address, expected_value in expected_telegrams.items(): await knx.assert_write(address, expected_value) # Verify read responses work for address, expected_value in expected_telegrams.items(): await knx.receive_read(address) await knx.assert_response(address, expected_value) @pytest.mark.freeze_time(FREEZE_TIME) async def test_time_server_load_from_config_store( hass: HomeAssistant, knx: KNXTestKit, hass_ws_client: WebSocketGenerator ) -> None: """Test time server is loaded correctly from config store.""" await hass.config.async_set_time_zone("Europe/Vienna") await knx.setup_integration( {}, config_store_fixture="config_store_time_server.json" ) # Verify all three formats are written on startup await knx.assert_write("1/1/1", RAW_TIME, ignore_order=True) await knx.assert_write("2/2/2", RAW_DATE, ignore_order=True) await knx.assert_write("3/3/3", RAW_DATETIME, ignore_order=True) client = await hass_ws_client(hass) # Verify configuration was loaded await client.send_json_auto_id({"type": "knx/get_time_server_config"}) res = await client.receive_json() assert res["success"], res assert res["result"] == { "time": {"write": "1/1/1"}, "date": {"write": "2/2/2"}, "datetime": {"write": "3/3/3"}, } @pytest.mark.parametrize( "invalid_config", [ {"invalid": 1}, {"time": {"state": "1/2/3"}}, {"time": {"write": "not_an_address"}}, {"date": {"passive": ["1/2/3"]}}, {"datetime": {}}, {"time": {"write": "1/2/3"}, "invalid_key": "value"}, ], ) async def test_time_server_invalid_config( hass: HomeAssistant, knx: KNXTestKit, hass_ws_client: WebSocketGenerator, invalid_config: dict, ) -> None: """Test invalid time server configuration is rejected.""" await knx.setup_integration({}) client = await hass_ws_client(hass) # Try to update with invalid configuration await client.send_json_auto_id( {"type": "knx/update_time_server_config", "config": invalid_config} ) res = await client.receive_json() assert res["success"] # uses custom error handling assert not res["result"]["success"] assert "errors" in res["result"]
{ "repo_id": "home-assistant/core", "file_path": "tests/components/knx/test_time_server.py", "license": "Apache License 2.0", "lines": 139, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/switchbot_cloud/image.py
"""Support for the Switchbot Image.""" import datetime from switchbot_api import Device, Remote, SwitchBotAPI from switchbot_api.utils import get_file_stream_from_cloud from homeassistant.components.image import ImageEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import SwitchbotCloudData, SwitchBotCoordinator from .const import DOMAIN from .entity import SwitchBotCloudEntity async def async_setup_entry( hass: HomeAssistant, config: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up SwitchBot Cloud entry.""" data: SwitchbotCloudData = hass.data[DOMAIN][config.entry_id] async_add_entities( _async_make_entity(data.api, device, coordinator) for device, coordinator in data.devices.images ) class SwitchBotCloudImage(SwitchBotCloudEntity, ImageEntity): """Base Class for SwitchBot Image.""" _attr_translation_key = "display" def __init__( self, api: SwitchBotAPI, device: Device | Remote, coordinator: SwitchBotCoordinator, ) -> None: """Initialize the image entity.""" super().__init__(api, device, coordinator) ImageEntity.__init__(self, self.coordinator.hass) self._image_content = b"" async def async_image(self) -> bytes | None: """Async image.""" if ( not isinstance(self._attr_image_url, str) or len(self._attr_image_url.strip()) == 0 ): self._image_content = b"" return None self._image_content = await get_file_stream_from_cloud(self._attr_image_url, 5) return self._image_content def _set_attributes(self) -> None: """Set attributes from coordinator data.""" if self.coordinator.data is None: return self._attr_image_last_updated = datetime.datetime.now() self._attr_image_url = self.coordinator.data.get("imageUrl") @callback def _async_make_entity( api: SwitchBotAPI, device: Device | Remote, coordinator: SwitchBotCoordinator ) -> SwitchBotCloudImage: """Make a SwitchBotCloudImage.""" return SwitchBotCloudImage(api, device, coordinator)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/switchbot_cloud/image.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/switchbot_cloud/test_image.py
"""Test for the switchbot_cloud image.""" from unittest.mock import AsyncMock, patch from switchbot_api import Device from homeassistant.components.switchbot_cloud import DOMAIN from homeassistant.components.switchbot_cloud.image import SwitchBotCloudImage from homeassistant.config_entries import ConfigEntryState from homeassistant.const import STATE_UNKNOWN from homeassistant.core import HomeAssistant from . import configure_integration async def test_coordinator_data_is_none( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test coordinator data is none.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="ai-art-frame-id-1", deviceName="ai-art-frame-1", deviceType="AI Art Frame", hubDeviceId="test-hub-id", ), ] mock_get_status.side_effect = [None, None] entry = await configure_integration(hass) assert entry.state is ConfigEntryState.LOADED entity_id = "image.ai_art_frame_1_display" state = hass.states.get(entity_id) assert state.state is STATE_UNKNOWN async def test_async_image( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test coordinator data is none.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="ai-art-frame-id-1", deviceName="ai-art-frame-1", deviceType="AI Art Frame", hubDeviceId="test-hub-id", ), ] mock_get_status.side_effect = [ { "deviceId": "B0E9FEA5D7F0", "deviceType": "AI Art Frame", "hubDeviceId": "B0E9FEA5D7F0", "battery": 0, "displayMode": 1, "imageUrl": "https://p3.itc.cn/images01/20231215/2f2db37e221c4ad3af575254c7769ca1.jpeg", "version": "V0.0-0.5", } ] entry = await configure_integration(hass) assert entry.state is ConfigEntryState.LOADED cloud_data = hass.data[DOMAIN][entry.entry_id] device, coordinator = cloud_data.devices.images[0] image_entity = SwitchBotCloudImage(cloud_data.api, device, coordinator) # 1. load before refresh await image_entity.async_image() assert image_entity._image_content == b"" # 2. load after refresh with patch( "homeassistant.components.switchbot_cloud.image.get_file_stream_from_cloud", new_callable=AsyncMock, ) as mock_get: mock_get.return_value = b"this is a bytes" image_entity._attr_image_url = ( "https://p3.itc.cn/images01/20231215/2f2db37e221c4ad3af575254c7769ca1.jpeg" ) await image_entity.async_image() assert image_entity._image_content == mock_get.return_value
{ "repo_id": "home-assistant/core", "file_path": "tests/components/switchbot_cloud/test_image.py", "license": "Apache License 2.0", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/idrive_e2/backup.py
"""Backup platform for the IDrive e2 integration.""" from collections.abc import AsyncIterator, Callable, Coroutine import functools import json import logging from time import time from typing import Any, cast from aiobotocore.client import AioBaseClient as S3Client from botocore.exceptions import BotoCoreError from homeassistant.components.backup import ( AgentBackup, BackupAgent, BackupAgentError, BackupNotFound, suggested_filename, ) from homeassistant.core import HomeAssistant, callback from . import IDriveE2ConfigEntry from .const import CONF_BUCKET, DATA_BACKUP_AGENT_LISTENERS, DOMAIN _LOGGER = logging.getLogger(__name__) CACHE_TTL = 300 # S3 part size requirements: 5 MiB to 5 GiB per part # https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html # We set the threshold to 20 MiB to avoid too many parts. # Note that each part is allocated in the memory. MULTIPART_MIN_PART_SIZE_BYTES = 20 * 2**20 def handle_boto_errors[T]( func: Callable[..., Coroutine[Any, Any, T]], ) -> Callable[..., Coroutine[Any, Any, T]]: """Handle BotoCoreError exceptions by converting them to BackupAgentError.""" @functools.wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> T: """Catch BotoCoreError and raise BackupAgentError.""" try: return await func(*args, **kwargs) except BotoCoreError as err: error_msg = f"Failed during {func.__name__}" raise BackupAgentError(error_msg) from err return wrapper async def async_get_backup_agents( hass: HomeAssistant, ) -> list[BackupAgent]: """Return a list of backup agents.""" entries: list[IDriveE2ConfigEntry] = hass.config_entries.async_loaded_entries( DOMAIN ) return [IDriveE2BackupAgent(hass, entry) for entry in entries] @callback def async_register_backup_agents_listener( hass: HomeAssistant, *, listener: Callable[[], None], **kwargs: Any, ) -> Callable[[], None]: """Register a listener to be called when agents are added or removed. :return: A function to unregister the listener. """ hass.data.setdefault(DATA_BACKUP_AGENT_LISTENERS, []).append(listener) @callback def remove_listener() -> None: """Remove the listener.""" hass.data[DATA_BACKUP_AGENT_LISTENERS].remove(listener) if not hass.data[DATA_BACKUP_AGENT_LISTENERS]: del hass.data[DATA_BACKUP_AGENT_LISTENERS] return remove_listener def suggested_filenames(backup: AgentBackup) -> tuple[str, str]: """Return the suggested filenames for the backup and metadata files.""" base_name = suggested_filename(backup).rsplit(".", 1)[0] return f"{base_name}.tar", f"{base_name}.metadata.json" class IDriveE2BackupAgent(BackupAgent): """Backup agent for the IDrive e2 integration.""" domain = DOMAIN def __init__(self, hass: HomeAssistant, entry: IDriveE2ConfigEntry) -> None: """Initialize the IDrive e2 agent.""" super().__init__() self._client: S3Client = entry.runtime_data self._bucket: str = entry.data[CONF_BUCKET] self.name = entry.title self.unique_id = entry.entry_id self._backup_cache: dict[str, AgentBackup] = {} self._cache_expiration = time() @handle_boto_errors async def async_download_backup( self, backup_id: str, **kwargs: Any, ) -> AsyncIterator[bytes]: """Download a backup file. :param backup_id: The ID of the backup that was returned in async_list_backups. :return: An async iterator that yields bytes. """ backup = await self._find_backup_by_id(backup_id) tar_filename, _ = suggested_filenames(backup) response = await cast(Any, self._client).get_object( Bucket=self._bucket, Key=tar_filename ) return response["Body"].iter_chunks() async def async_upload_backup( self, *, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], backup: AgentBackup, **kwargs: Any, ) -> None: """Upload a backup. :param open_stream: A function returning an async iterator that yields bytes. :param backup: Metadata about the backup that should be uploaded. """ tar_filename, metadata_filename = suggested_filenames(backup) try: if backup.size < MULTIPART_MIN_PART_SIZE_BYTES: await self._upload_simple(tar_filename, open_stream) else: await self._upload_multipart(tar_filename, open_stream) # Upload the metadata file metadata_content = json.dumps(backup.as_dict()) await cast(Any, self._client).put_object( Bucket=self._bucket, Key=metadata_filename, Body=metadata_content, ) except BotoCoreError as err: raise BackupAgentError("Failed to upload backup") from err else: # Reset cache after successful upload self._cache_expiration = time() async def _upload_simple( self, tar_filename: str, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], ) -> None: """Upload a small file using simple upload. :param tar_filename: The target filename for the backup. :param open_stream: A function returning an async iterator that yields bytes. """ _LOGGER.debug("Starting simple upload for %s", tar_filename) stream = await open_stream() file_data = bytearray() async for chunk in stream: file_data.extend(chunk) await cast(Any, self._client).put_object( Bucket=self._bucket, Key=tar_filename, Body=bytes(file_data), ) async def _upload_multipart( self, tar_filename: str, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], ) -> None: """Upload a large file using multipart upload. :param tar_filename: The target filename for the backup. :param open_stream: A function returning an async iterator that yields bytes. """ _LOGGER.debug("Starting multipart upload for %s", tar_filename) multipart_upload = await cast(Any, self._client).create_multipart_upload( Bucket=self._bucket, Key=tar_filename, ) upload_id = multipart_upload["UploadId"] try: parts: list[dict[str, Any]] = [] part_number = 1 buffer = bytearray() # bytes buffer to store the data offset = 0 # start index of unread data inside buffer stream = await open_stream() async for chunk in stream: buffer.extend(chunk) # Upload parts of exactly MULTIPART_MIN_PART_SIZE_BYTES to ensure # all non-trailing parts have the same size (defensive implementation) view = memoryview(buffer) try: while len(buffer) - offset >= MULTIPART_MIN_PART_SIZE_BYTES: start = offset end = offset + MULTIPART_MIN_PART_SIZE_BYTES part_data = view[start:end] offset = end _LOGGER.debug( "Uploading part number %d, size %d", part_number, len(part_data), ) part = await cast(Any, self._client).upload_part( Bucket=self._bucket, Key=tar_filename, PartNumber=part_number, UploadId=upload_id, Body=part_data.tobytes(), ) parts.append({"PartNumber": part_number, "ETag": part["ETag"]}) part_number += 1 finally: view.release() # Compact the buffer if the consumed offset has grown large enough. This # avoids unnecessary memory copies when compacting after every part upload. if offset and offset >= MULTIPART_MIN_PART_SIZE_BYTES: buffer = bytearray(buffer[offset:]) offset = 0 # Upload the final buffer as the last part (no minimum size requirement) # Offset should be 0 after the last compaction, but we use it as the start # index to be defensive in case the buffer was not compacted. if offset < len(buffer): remaining_data = memoryview(buffer)[offset:] _LOGGER.debug( "Uploading final part number %d, size %d", part_number, len(remaining_data), ) part = await cast(Any, self._client).upload_part( Bucket=self._bucket, Key=tar_filename, PartNumber=part_number, UploadId=upload_id, Body=remaining_data.tobytes(), ) parts.append({"PartNumber": part_number, "ETag": part["ETag"]}) await cast(Any, self._client).complete_multipart_upload( Bucket=self._bucket, Key=tar_filename, UploadId=upload_id, MultipartUpload={"Parts": parts}, ) except BotoCoreError: try: await cast(Any, self._client).abort_multipart_upload( Bucket=self._bucket, Key=tar_filename, UploadId=upload_id, ) except BotoCoreError: _LOGGER.exception("Failed to abort multipart upload") raise @handle_boto_errors async def async_delete_backup( self, backup_id: str, **kwargs: Any, ) -> None: """Delete a backup file. :param backup_id: The ID of the backup that was returned in async_list_backups. """ backup = await self._find_backup_by_id(backup_id) tar_filename, metadata_filename = suggested_filenames(backup) # Delete both the backup file and its metadata file await cast(Any, self._client).delete_objects( Bucket=self._bucket, Delete={ "Objects": [ {"Key": tar_filename}, {"Key": metadata_filename}, ] }, ) # Reset cache after successful deletion self._cache_expiration = time() @handle_boto_errors async def async_list_backups(self, **kwargs: Any) -> list[AgentBackup]: """List backups.""" backups = await self._list_backups() return list(backups.values()) @handle_boto_errors async def async_get_backup( self, backup_id: str, **kwargs: Any, ) -> AgentBackup: """Return a backup.""" return await self._find_backup_by_id(backup_id) async def _find_backup_by_id(self, backup_id: str) -> AgentBackup: """Find a backup by its backup ID.""" backups = await self._list_backups() if backup := backups.get(backup_id): return backup raise BackupNotFound(f"Backup {backup_id} not found") async def _list_backups(self) -> dict[str, AgentBackup]: """List backups, using a cache if possible.""" if time() <= self._cache_expiration: return self._backup_cache backups = {} paginator = self._client.get_paginator("list_objects_v2") metadata_files: list[dict[str, Any]] = [] async for page in paginator.paginate(Bucket=self._bucket): metadata_files.extend( obj for obj in page.get("Contents", []) if obj["Key"].endswith(".metadata.json") ) for metadata_file in metadata_files: try: # Download and parse metadata file metadata_response = await cast(Any, self._client).get_object( Bucket=self._bucket, Key=metadata_file["Key"] ) metadata_content = await metadata_response["Body"].read() metadata_json = json.loads(metadata_content) except (BotoCoreError, json.JSONDecodeError) as err: _LOGGER.warning( "Failed to process metadata file %s: %s", metadata_file["Key"], err, ) continue backup = AgentBackup.from_dict(metadata_json) backups[backup.backup_id] = backup self._backup_cache = backups self._cache_expiration = time() + CACHE_TTL return self._backup_cache
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/idrive_e2/backup.py", "license": "Apache License 2.0", "lines": 307, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/idrive_e2/config_flow.py
"""IDrive e2 config flow.""" from __future__ import annotations import logging from typing import Any, cast from aiobotocore.session import AioSession from botocore.exceptions import ClientError, ConnectionError from idrive_e2 import CannotConnect, IDriveE2Client, InvalidAuth import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.selector import ( SelectSelector, SelectSelectorConfig, SelectSelectorMode, TextSelector, TextSelectorConfig, TextSelectorType, ) from .const import ( CONF_ACCESS_KEY_ID, CONF_BUCKET, CONF_ENDPOINT_URL, CONF_SECRET_ACCESS_KEY, DOMAIN, ) _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_ACCESS_KEY_ID): cv.string, vol.Required(CONF_SECRET_ACCESS_KEY): TextSelector( config=TextSelectorConfig(type=TextSelectorType.PASSWORD) ), } ) async def _list_buckets( endpoint_url: str, access_key: str, secret_key: str ) -> list[str]: """List S3 buckets.""" session = AioSession() async with session.create_client( "s3", endpoint_url=endpoint_url, aws_access_key_id=access_key, aws_secret_access_key=secret_key, ) as client: result = await cast(Any, client).list_buckets() return [bucket["Name"] for bucket in result.get("Buckets", []) if "Name" in bucket] class IDriveE2ConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for IDrive e2.""" _data: dict[str, str] _buckets: list[str] async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """First step: prompt for access_key and secret_access_key, then fetch region endpoint and buckets.""" errors: dict[str, str] = {} if user_input is not None: session = async_get_clientsession(self.hass) client = IDriveE2Client(session) try: endpoint = await client.get_region_endpoint( user_input[CONF_ACCESS_KEY_ID] ) # Get the list of buckets belonging to the provided credentials buckets = await _list_buckets( endpoint, user_input[CONF_ACCESS_KEY_ID], user_input[CONF_SECRET_ACCESS_KEY], ) except InvalidAuth, ClientError: errors["base"] = "invalid_credentials" except CannotConnect, ConnectionError: errors["base"] = "cannot_connect" except ValueError: errors["base"] = "invalid_endpoint_url" else: # Check if any buckets were found if not buckets: errors["base"] = "no_buckets" if not errors: # Store validated data for the next step self._data = { CONF_ACCESS_KEY_ID: user_input[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: user_input[CONF_SECRET_ACCESS_KEY], CONF_ENDPOINT_URL: endpoint, } self._buckets = buckets return await self.async_step_bucket() return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( STEP_USER_DATA_SCHEMA, user_input ), errors=errors, ) async def async_step_bucket( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Second step: list preloaded buckets and let user select from dropdown.""" if user_input is not None: # Check if the entry already exists to avoid duplicates self._async_abort_entries_match( { CONF_BUCKET: user_input[CONF_BUCKET], CONF_ENDPOINT_URL: self._data[CONF_ENDPOINT_URL], } ) return self.async_create_entry( title=user_input[CONF_BUCKET], data={**self._data, CONF_BUCKET: user_input[CONF_BUCKET]}, ) # Show the bucket selection form with a dropdown selector return self.async_show_form( step_id="bucket", data_schema=vol.Schema( { vol.Required(CONF_BUCKET): SelectSelector( config=SelectSelectorConfig( options=self._buckets, mode=SelectSelectorMode.DROPDOWN ) ) } ), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/idrive_e2/config_flow.py", "license": "Apache License 2.0", "lines": 125, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/idrive_e2/const.py
"""Constants for the IDrive e2 integration.""" from collections.abc import Callable from typing import Final from homeassistant.util.hass_dict import HassKey DOMAIN: Final = "idrive_e2" CONF_ACCESS_KEY_ID = "access_key_id" CONF_SECRET_ACCESS_KEY = "secret_access_key" CONF_ENDPOINT_URL = "endpoint_url" CONF_BUCKET = "bucket" DATA_BACKUP_AGENT_LISTENERS: HassKey[list[Callable[[], None]]] = HassKey( f"{DOMAIN}.backup_agent_listeners" )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/idrive_e2/const.py", "license": "Apache License 2.0", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/idrive_e2/const.py
"""Consts for IDrive e2 tests.""" from homeassistant.components.idrive_e2.const import ( CONF_ACCESS_KEY_ID, CONF_BUCKET, CONF_ENDPOINT_URL, CONF_SECRET_ACCESS_KEY, ) USER_INPUT = { CONF_ACCESS_KEY_ID: "TestTestTestTestTest", CONF_SECRET_ACCESS_KEY: "TestTestTestTestTestTestTestTestTestTest", CONF_ENDPOINT_URL: "https://c7h8.fra201.idrivee2-98.com", CONF_BUCKET: "test", }
{ "repo_id": "home-assistant/core", "file_path": "tests/components/idrive_e2/const.py", "license": "Apache License 2.0", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/idrive_e2/test_backup.py
"""Test the IDrive e2 backup platform.""" from collections.abc import AsyncGenerator from io import StringIO import json from time import time from unittest.mock import AsyncMock, Mock, patch from botocore.exceptions import ConnectTimeoutError import pytest from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, AgentBackup from homeassistant.components.idrive_e2.backup import ( MULTIPART_MIN_PART_SIZE_BYTES, BotoCoreError, IDriveE2BackupAgent, async_register_backup_agents_listener, suggested_filenames, ) from homeassistant.components.idrive_e2.const import ( CONF_ENDPOINT_URL, DATA_BACKUP_AGENT_LISTENERS, DOMAIN, ) from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from . import setup_integration from .const import USER_INPUT from tests.common import MockConfigEntry from tests.typing import ClientSessionGenerator, MagicMock, WebSocketGenerator @pytest.fixture(autouse=True) async def setup_backup_integration( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> AsyncGenerator[None]: """Set up IDrive e2 integration.""" with ( patch("homeassistant.components.backup.is_hassio", return_value=False), patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0), ): assert await async_setup_component(hass, BACKUP_DOMAIN, {}) await setup_integration(hass, mock_config_entry) await hass.async_block_till_done() yield async def test_suggested_filenames() -> None: """Test the suggested_filenames function.""" backup = AgentBackup( backup_id="a1b2c3", date="2021-01-01T01:02:03+00:00", addons=[], database_included=False, extra_metadata={}, folders=[], homeassistant_included=False, homeassistant_version=None, name="my_pretty_backup", protected=False, size=0, ) tar_filename, metadata_filename = suggested_filenames(backup) assert tar_filename == "my_pretty_backup_2021-01-01_01.02_03000000.tar" assert ( metadata_filename == "my_pretty_backup_2021-01-01_01.02_03000000.metadata.json" ) async def test_agents_info( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_config_entry: MockConfigEntry, ) -> None: """Test backup agent info.""" client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/agents/info"}) response = await client.receive_json() assert response["success"] assert response["result"] == { "agents": [ {"agent_id": "backup.local", "name": "local"}, { "agent_id": f"{DOMAIN}.{mock_config_entry.entry_id}", "name": mock_config_entry.title, }, ], } async def test_agents_list_backups( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_config_entry: MockConfigEntry, agent_backup: AgentBackup, ) -> None: """Test agent list backups.""" client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/info"}) response = await client.receive_json() assert response["success"] assert response["result"]["agent_errors"] == {} assert response["result"]["backups"] == [ { "addons": agent_backup.addons, "agents": { f"{DOMAIN}.{mock_config_entry.entry_id}": { "protected": agent_backup.protected, "size": agent_backup.size, } }, "backup_id": agent_backup.backup_id, "database_included": agent_backup.database_included, "date": agent_backup.date, "extra_metadata": agent_backup.extra_metadata, "failed_addons": [], "failed_agent_ids": [], "failed_folders": [], "folders": agent_backup.folders, "homeassistant_included": agent_backup.homeassistant_included, "homeassistant_version": agent_backup.homeassistant_version, "name": agent_backup.name, "with_automatic_settings": None, } ] async def test_agents_get_backup( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_config_entry: MockConfigEntry, agent_backup: AgentBackup, ) -> None: """Test agent get backup.""" client = await hass_ws_client(hass) await client.send_json_auto_id( {"type": "backup/details", "backup_id": agent_backup.backup_id} ) response = await client.receive_json() assert response["success"] assert response["result"]["agent_errors"] == {} assert response["result"]["backup"] == { "addons": agent_backup.addons, "agents": { f"{DOMAIN}.{mock_config_entry.entry_id}": { "protected": agent_backup.protected, "size": agent_backup.size, } }, "backup_id": agent_backup.backup_id, "database_included": agent_backup.database_included, "date": agent_backup.date, "extra_metadata": agent_backup.extra_metadata, "failed_addons": [], "failed_agent_ids": [], "failed_folders": [], "folders": agent_backup.folders, "homeassistant_included": agent_backup.homeassistant_included, "homeassistant_version": agent_backup.homeassistant_version, "name": agent_backup.name, "with_automatic_settings": None, } async def test_agents_get_backup_does_not_throw_on_not_found( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_client: MagicMock, ) -> None: """Test agent get backup does not throw on a backup not found.""" mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [ {"Contents": []} ] client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "backup/details", "backup_id": "random"}) response = await client.receive_json() assert response["success"] assert response["result"]["agent_errors"] == {} assert response["result"]["backup"] is None async def test_agents_list_backups_with_corrupted_metadata( hass: HomeAssistant, mock_client: MagicMock, mock_config_entry: MockConfigEntry, caplog: pytest.LogCaptureFixture, agent_backup: AgentBackup, ) -> None: """Test listing backups when one metadata file is corrupted.""" # Create agent agent = IDriveE2BackupAgent(hass, mock_config_entry) # Set up mock responses for both valid and corrupted metadata files mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [ { "Contents": [ { "Key": "valid_backup.metadata.json", "LastModified": "2023-01-01T00:00:00+00:00", }, { "Key": "corrupted_backup.metadata.json", "LastModified": "2023-01-01T00:00:00+00:00", }, ] } ] # Mock responses for get_object calls valid_metadata = json.dumps(agent_backup.as_dict()) corrupted_metadata = "{invalid json content" async def mock_get_object(**kwargs): """Mock get_object with different responses based on the key.""" key = kwargs.get("Key", "") if "valid_backup" in key: mock_body = AsyncMock() mock_body.read.return_value = valid_metadata.encode() return {"Body": mock_body} # Corrupted metadata mock_body = AsyncMock() mock_body.read.return_value = corrupted_metadata.encode() return {"Body": mock_body} mock_client.get_object.side_effect = mock_get_object backups = await agent.async_list_backups() assert len(backups) == 1 assert backups[0].backup_id == agent_backup.backup_id assert "Failed to process metadata file" in caplog.text async def test_agents_delete( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_client: MagicMock, ) -> None: """Test agent delete backup.""" client = await hass_ws_client(hass) await client.send_json_auto_id( { "type": "backup/delete", "backup_id": "23e64aec", } ) response = await client.receive_json() assert response["success"] assert response["result"] == {"agent_errors": {}} # Should delete both the tar and the metadata file assert mock_client.delete_objects.call_count == 1 kwargs = mock_client.delete_objects.call_args.kwargs assert "Delete" in kwargs and "Objects" in kwargs["Delete"] assert len(kwargs["Delete"]["Objects"]) == 2 async def test_agents_delete_not_throwing_on_not_found( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_client: MagicMock, ) -> None: """Test agent delete backup does not throw on a backup not found.""" mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [ {"Contents": []} ] client = await hass_ws_client(hass) await client.send_json_auto_id( { "type": "backup/delete", "backup_id": "random", } ) response = await client.receive_json() assert response["success"] assert response["result"] == {"agent_errors": {}} assert mock_client.delete_objects.call_count == 0 async def test_agents_upload( hass_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture, mock_client: MagicMock, mock_config_entry: MockConfigEntry, agent_backup: AgentBackup, ) -> None: """Test agent upload backup.""" client = await hass_client() with ( patch( "homeassistant.components.backup.manager.BackupManager.async_get_backup", return_value=agent_backup, ), patch( "homeassistant.components.backup.manager.read_backup", return_value=agent_backup, ), patch("pathlib.Path.open") as mocked_open, ): # we must emit at least two chunks # the "appendix" chunk triggers the upload of the final buffer part mocked_open.return_value.read = Mock( side_effect=[ b"a" * agent_backup.size, b"appendix", b"", ] ) resp = await client.post( f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.entry_id}", data={"file": StringIO("test")}, ) assert resp.status == 201 assert f"Uploading backup {agent_backup.backup_id}" in caplog.text if agent_backup.size < MULTIPART_MIN_PART_SIZE_BYTES: # single part + metadata both as regular upload (no multiparts) assert mock_client.create_multipart_upload.await_count == 0 assert mock_client.put_object.await_count == 2 else: assert "Uploading final part" in caplog.text # 2 parts as multipart + metadata as regular upload assert mock_client.create_multipart_upload.await_count == 1 assert mock_client.upload_part.await_count == 2 assert mock_client.complete_multipart_upload.await_count == 1 assert mock_client.put_object.await_count == 1 async def test_agents_upload_network_failure( hass_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture, mock_client: MagicMock, mock_config_entry: MockConfigEntry, agent_backup: AgentBackup, ) -> None: """Test agent upload backup with network failure.""" client = await hass_client() with ( patch( "homeassistant.components.backup.manager.BackupManager.async_get_backup", return_value=agent_backup, ), patch( "homeassistant.components.backup.manager.read_backup", return_value=agent_backup, ), patch("pathlib.Path.open") as mocked_open, ): mocked_open.return_value.read = Mock(side_effect=[b"test", b""]) # simulate network failure mock_client.put_object.side_effect = mock_client.upload_part.side_effect = ( mock_client.abort_multipart_upload.side_effect ) = ConnectTimeoutError(endpoint_url=USER_INPUT[CONF_ENDPOINT_URL]) resp = await client.post( f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.entry_id}", data={"file": StringIO("test")}, ) assert resp.status == 201 assert "Upload failed for idrive_e2" in caplog.text async def test_multipart_upload_consistent_part_sizes( hass: HomeAssistant, mock_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test that multipart upload uses consistent part sizes. Defensive implementation to ensure that even if the input stream yields varying chunk sizes, the multipart upload will still create parts of the same correct size. This test verifies that varying chunk sizes still result in consistent part sizes. """ agent = IDriveE2BackupAgent(hass, mock_config_entry) # simulate varying chunk data sizes # total data: 12 + 12 + 10 + 12 + 5 = 51 MiB chunk_sizes = [12, 12, 10, 12, 5] # in units of 1 MiB mib = 2**20 async def mock_stream(): for size in chunk_sizes: yield b"x" * (size * mib) async def open_stream(): return mock_stream() # Record the sizes of each uploaded part uploaded_part_sizes: list[int] = [] async def record_upload_part(**kwargs): body = kwargs.get("Body", b"") uploaded_part_sizes.append(len(body)) return {"ETag": f"etag-{len(uploaded_part_sizes)}"} mock_client.upload_part.side_effect = record_upload_part await agent._upload_multipart("test.tar", open_stream) # Verify that all non-trailing parts have the same size assert len(uploaded_part_sizes) >= 2, "Expected at least 2 parts" non_trailing_parts = uploaded_part_sizes[:-1] assert all(size == MULTIPART_MIN_PART_SIZE_BYTES for size in non_trailing_parts), ( f"All non-trailing parts should be {MULTIPART_MIN_PART_SIZE_BYTES} bytes, got {non_trailing_parts}" ) # Verify the trailing part contains the remainder total_data = sum(chunk_sizes) * mib expected_trailing = total_data % MULTIPART_MIN_PART_SIZE_BYTES if expected_trailing == 0: expected_trailing = MULTIPART_MIN_PART_SIZE_BYTES assert uploaded_part_sizes[-1] == expected_trailing async def test_agents_download( hass_client: ClientSessionGenerator, mock_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test agent download backup.""" client = await hass_client() backup_id = "23e64aec" resp = await client.get( f"/api/backup/download/{backup_id}?agent_id={DOMAIN}.{mock_config_entry.entry_id}" ) assert resp.status == 200 assert await resp.content.read() == b"backup data" assert mock_client.get_object.call_count == 2 # One for metadata, one for tar file async def test_error_during_delete( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, mock_client: MagicMock, mock_config_entry: MockConfigEntry, agent_backup: AgentBackup, ) -> None: """Test the error wrapper.""" mock_client.delete_objects.side_effect = BotoCoreError client = await hass_ws_client(hass) await client.send_json_auto_id( { "type": "backup/delete", "backup_id": agent_backup.backup_id, } ) response = await client.receive_json() assert response["success"] assert response["result"] == { "agent_errors": { f"{DOMAIN}.{mock_config_entry.entry_id}": "Failed during async_delete_backup" } } async def test_cache_expiration( hass: HomeAssistant, mock_client: MagicMock, agent_backup: AgentBackup, ) -> None: """Test that the cache expires correctly.""" # Mock the entry mock_entry = MockConfigEntry( domain=DOMAIN, data={"bucket": "test-bucket"}, unique_id="test-unique-id", title="Test IDrive e2", ) mock_entry.runtime_data = mock_client # Create agent agent = IDriveE2BackupAgent(hass, mock_entry) # Mock metadata response metadata_content = json.dumps(agent_backup.as_dict()) mock_body = AsyncMock() mock_body.read.return_value = metadata_content.encode() mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [ { "Contents": [ { "Key": "test.metadata.json", "LastModified": "2023-01-01T00:00:00+00:00", } ] } ] mock_client.get_object.return_value = {"Body": mock_body} # First call should query IDrive e2 await agent.async_list_backups() assert mock_client.get_paginator.call_count == 1 assert mock_client.get_object.call_count == 1 # Second call should use cache await agent.async_list_backups() assert mock_client.get_paginator.call_count == 1 assert mock_client.get_object.call_count == 1 # Set cache to expire agent._cache_expiration = time() - 1 # Third call should query IDrive e2 again await agent.async_list_backups() assert mock_client.get_paginator.call_count == 2 assert mock_client.get_object.call_count == 2 async def test_listeners_get_cleaned_up(hass: HomeAssistant) -> None: """Test listener gets cleaned up.""" listener = MagicMock() remove_listener = async_register_backup_agents_listener(hass, listener=listener) hass.data[DATA_BACKUP_AGENT_LISTENERS] = [ listener ] # make sure it's the last listener remove_listener() assert DATA_BACKUP_AGENT_LISTENERS not in hass.data async def test_list_backups_with_pagination( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test listing backups when paginating through multiple pages.""" # Create agent agent = IDriveE2BackupAgent(hass, mock_config_entry) # Create two different backups backup1 = AgentBackup( backup_id="backup1", date="2023-01-01T00:00:00+00:00", addons=[], database_included=False, extra_metadata={}, folders=[], homeassistant_included=False, homeassistant_version=None, name="Backup 1", protected=False, size=0, ) backup2 = AgentBackup( backup_id="backup2", date="2023-01-02T00:00:00+00:00", addons=[], database_included=False, extra_metadata={}, folders=[], homeassistant_included=False, homeassistant_version=None, name="Backup 2", protected=False, size=0, ) # Setup two pages of results page1 = { "Contents": [ { "Key": "backup1.metadata.json", "LastModified": "2023-01-01T00:00:00+00:00", }, {"Key": "backup1.tar", "LastModified": "2023-01-01T00:00:00+00:00"}, ] } page2 = { "Contents": [ { "Key": "backup2.metadata.json", "LastModified": "2023-01-02T00:00:00+00:00", }, {"Key": "backup2.tar", "LastModified": "2023-01-02T00:00:00+00:00"}, ] } # Setup mock client mock_client = mock_config_entry.runtime_data mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [ page1, page2, ] # Mock get_object responses based on the key async def mock_get_object(**kwargs): """Mock get_object with different responses based on the key.""" key = kwargs.get("Key", "") if "backup1" in key: mock_body = AsyncMock() mock_body.read.return_value = json.dumps(backup1.as_dict()).encode() return {"Body": mock_body} # backup2 mock_body = AsyncMock() mock_body.read.return_value = json.dumps(backup2.as_dict()).encode() return {"Body": mock_body} mock_client.get_object.side_effect = mock_get_object # List backups and verify we got both backups = await agent.async_list_backups() assert len(backups) == 2 backup_ids = {backup.backup_id for backup in backups} assert backup_ids == {"backup1", "backup2"}
{ "repo_id": "home-assistant/core", "file_path": "tests/components/idrive_e2/test_backup.py", "license": "Apache License 2.0", "lines": 536, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/idrive_e2/test_config_flow.py
"""Test the IDrive e2 config flow.""" from __future__ import annotations from collections.abc import Generator from unittest.mock import AsyncMock, patch from botocore.exceptions import EndpointConnectionError from idrive_e2 import CannotConnect, InvalidAuth import pytest import voluptuous as vol from homeassistant.components.idrive_e2 import ClientError from homeassistant.components.idrive_e2.config_flow import CONF_ACCESS_KEY_ID from homeassistant.components.idrive_e2.const import ( CONF_BUCKET, CONF_ENDPOINT_URL, CONF_SECRET_ACCESS_KEY, DOMAIN, ) from homeassistant.config_entries import SOURCE_USER from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers.selector import SelectSelector from .const import USER_INPUT from tests.common import MockConfigEntry @pytest.fixture def mock_idrive_client() -> Generator[AsyncMock]: """Patch IDriveE2Client to return a mocked client.""" mock_client = AsyncMock() mock_client.get_region_endpoint.return_value = USER_INPUT[CONF_ENDPOINT_URL] with patch( "homeassistant.components.idrive_e2.config_flow.IDriveE2Client", return_value=mock_client, ): yield mock_client async def test_flow( hass: HomeAssistant, mock_idrive_client: AsyncMock, mock_client: AsyncMock, ) -> None: """Test config flow success path.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ACCESS_KEY_ID: USER_INPUT[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: USER_INPUT[CONF_SECRET_ACCESS_KEY], }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "bucket" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_BUCKET: USER_INPUT[CONF_BUCKET]}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "test" assert result["data"] == USER_INPUT @pytest.mark.parametrize( ("exception", "errors"), [ ( ClientError( {"Error": {"Code": "403", "Message": "Forbidden"}}, "list_buckets" ), {"base": "invalid_credentials"}, ), (ValueError(), {"base": "invalid_endpoint_url"}), ( EndpointConnectionError(endpoint_url="http://example.com"), {"base": "cannot_connect"}, ), ], ) async def test_flow_list_buckets_errors( hass: HomeAssistant, mock_idrive_client: AsyncMock, mock_client: AsyncMock, exception: Exception, errors: dict[str, str], ) -> None: """Test errors when listing buckets.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) flow_id = result["flow_id"] assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" # First attempt: fail mock_client.list_buckets.side_effect = exception result = await hass.config_entries.flow.async_configure( flow_id, { CONF_ACCESS_KEY_ID: USER_INPUT[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: USER_INPUT[CONF_SECRET_ACCESS_KEY], }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == errors # Second attempt: fix and finish to CREATE_ENTRY mock_client.list_buckets.side_effect = None result = await hass.config_entries.flow.async_configure( flow_id, { CONF_ACCESS_KEY_ID: USER_INPUT[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: USER_INPUT[CONF_SECRET_ACCESS_KEY], }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "bucket" result = await hass.config_entries.flow.async_configure( flow_id, {CONF_BUCKET: USER_INPUT[CONF_BUCKET]}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "test" assert result["data"] == USER_INPUT async def test_flow_no_buckets( hass: HomeAssistant, mock_idrive_client: AsyncMock, mock_client: AsyncMock, ) -> None: """Test we show an error when no buckets are returned.""" # Start flow result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) flow_id = result["flow_id"] assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" # First attempt: empty bucket list -> error mock_client.list_buckets.return_value = {"Buckets": []} result = await hass.config_entries.flow.async_configure( flow_id, { CONF_ACCESS_KEY_ID: USER_INPUT[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: USER_INPUT[CONF_SECRET_ACCESS_KEY], }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": "no_buckets"} # Second attempt: fix and finish to CREATE_ENTRY mock_client.list_buckets.return_value = { "Buckets": [{"Name": USER_INPUT[CONF_BUCKET]}] } result = await hass.config_entries.flow.async_configure( flow_id, { CONF_ACCESS_KEY_ID: USER_INPUT[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: USER_INPUT[CONF_SECRET_ACCESS_KEY], }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "bucket" result = await hass.config_entries.flow.async_configure( flow_id, {CONF_BUCKET: USER_INPUT[CONF_BUCKET]}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "test" assert result["data"] == USER_INPUT async def test_flow_bucket_step_options_from_s3_list_buckets( hass: HomeAssistant, mock_idrive_client: AsyncMock, mock_client: AsyncMock, ) -> None: """Test bucket step shows dropdown options coming from S3 list_buckets().""" # Start flow result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) flow_id = result["flow_id"] assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" # S3 list_buckets returns our test payload mock_client.list_buckets.return_value = { "Buckets": [{"Name": "bucket1"}, {"Name": "bucket2"}] } # Submit credentials result = await hass.config_entries.flow.async_configure( flow_id, { CONF_ACCESS_KEY_ID: USER_INPUT[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: USER_INPUT[CONF_SECRET_ACCESS_KEY], }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "bucket" # Extract dropdown options from selector in schema schema = result["data_schema"].schema selector = schema[vol.Required(CONF_BUCKET)] assert isinstance(selector, SelectSelector) cfg = selector.config options = cfg["options"] if isinstance(cfg, dict) else cfg.options assert options == ["bucket1", "bucket2"] # Continue to finish to CREATE_ENTRY result = await hass.config_entries.flow.async_configure( flow_id, {CONF_BUCKET: "bucket1"}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "bucket1" assert result["data"][CONF_BUCKET] == "bucket1" @pytest.mark.parametrize( ("exception", "expected_error"), [ (InvalidAuth("Invalid credentials"), "invalid_credentials"), (CannotConnect("cannot connect"), "cannot_connect"), ], ) async def test_flow_get_region_endpoint_error( hass: HomeAssistant, mock_idrive_client: AsyncMock, mock_client: AsyncMock, exception: Exception, expected_error: str, ) -> None: """Test user step error mapping when resolving region endpoint via client.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) flow_id = result["flow_id"] assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" # First attempt: fail endpoint resolution mock_idrive_client.get_region_endpoint.side_effect = exception result = await hass.config_entries.flow.async_configure( flow_id, { CONF_ACCESS_KEY_ID: USER_INPUT[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: USER_INPUT[CONF_SECRET_ACCESS_KEY], }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": expected_error} # Second attempt: fix and finish to CREATE_ENTRY mock_idrive_client.get_region_endpoint.side_effect = None mock_idrive_client.get_region_endpoint.return_value = USER_INPUT[CONF_ENDPOINT_URL] result = await hass.config_entries.flow.async_configure( flow_id, { CONF_ACCESS_KEY_ID: USER_INPUT[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: USER_INPUT[CONF_SECRET_ACCESS_KEY], }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "bucket" result = await hass.config_entries.flow.async_configure( flow_id, {CONF_BUCKET: USER_INPUT[CONF_BUCKET]}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"] == USER_INPUT async def test_abort_if_already_configured( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_idrive_client: AsyncMock, mock_client: AsyncMock, ) -> None: """Test we abort if the account is already configured.""" # Existing entry that should cause abort when selecting the same bucket + endpoint MockConfigEntry( domain=mock_config_entry.domain, title=mock_config_entry.title, data={ **mock_config_entry.data, CONF_BUCKET: USER_INPUT[CONF_BUCKET], CONF_ENDPOINT_URL: USER_INPUT[CONF_ENDPOINT_URL], }, unique_id="existing", ).add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ACCESS_KEY_ID: USER_INPUT[CONF_ACCESS_KEY_ID], CONF_SECRET_ACCESS_KEY: USER_INPUT[CONF_SECRET_ACCESS_KEY], }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "bucket" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_BUCKET: USER_INPUT[CONF_BUCKET]}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/idrive_e2/test_config_flow.py", "license": "Apache License 2.0", "lines": 293, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/idrive_e2/test_init.py
"""Test the IDrive e2 storage integration.""" from unittest.mock import AsyncMock, patch from botocore.exceptions import ( ClientError, EndpointConnectionError, ParamValidationError, ) import pytest from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from . import setup_integration from tests.common import MockConfigEntry async def test_async_setup_entry_does_not_mask_when_close_fails( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: AsyncMock, ) -> None: """Test close failures do not mask the original setup exception.""" mock_config_entry.add_to_hass(hass) # Force setup to fail after the client has been created mock_client.head_bucket.side_effect = ClientError( {"Error": {"Code": "403", "Message": "Forbidden"}}, "HeadBucket" ) # Also force close() to fail mock_client.close.side_effect = RuntimeError("boom") assert await hass.config_entries.async_setup(mock_config_entry.entry_id) is False assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR mock_client.close.assert_awaited_once() async def test_load_unload_config_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test loading and unloading the integration.""" await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED await hass.config_entries.async_unload(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.NOT_LOADED @pytest.mark.parametrize( ("exception", "state"), [ ( ParamValidationError(report="Invalid bucket name"), ConfigEntryState.SETUP_ERROR, ), (ValueError(), ConfigEntryState.SETUP_ERROR), ( EndpointConnectionError(endpoint_url="https://example.com"), ConfigEntryState.SETUP_RETRY, ), ], ) async def test_setup_entry_create_client_errors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, exception: Exception, state: ConfigEntryState, ) -> None: """Test various setup errors.""" with patch( "homeassistant.components.idrive_e2.AioSession.create_client", side_effect=exception, ): await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is state @pytest.mark.parametrize( ("error_response"), [ {"Error": {"Code": "InvalidAccessKeyId"}}, {"Error": {"Code": "404", "Message": "Not Found"}}, ], ids=["invalid_access_key", "bucket_not_found"], ) async def test_setup_entry_head_bucket_errors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: AsyncMock, error_response: dict, ) -> None: """Test setup_entry errors when calling head_bucket.""" mock_client.head_bucket.side_effect = ClientError( error_response=error_response, operation_name="head_bucket", ) await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
{ "repo_id": "home-assistant/core", "file_path": "tests/components/idrive_e2/test_init.py", "license": "Apache License 2.0", "lines": 86, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/cloudflare/coordinator.py
"""Contains the Coordinator for updating the IP addresses of your Cloudflare DNS records.""" from __future__ import annotations import asyncio from datetime import timedelta from logging import getLogger import socket import pycfdns from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_API_TOKEN, CONF_ZONE from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util.location import async_detect_location_info from homeassistant.util.network import is_ipv4_address from .const import CONF_RECORDS, DEFAULT_UPDATE_INTERVAL _LOGGER = getLogger(__name__) type CloudflareConfigEntry = ConfigEntry[CloudflareCoordinator] class CloudflareCoordinator(DataUpdateCoordinator[None]): """Coordinates records updates.""" config_entry: CloudflareConfigEntry client: pycfdns.Client zone: pycfdns.ZoneModel def __init__( self, hass: HomeAssistant, config_entry: CloudflareConfigEntry ) -> None: """Initialize an coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=config_entry.title, update_interval=timedelta(minutes=DEFAULT_UPDATE_INTERVAL), ) async def _async_setup(self) -> None: """Set up the coordinator.""" self.client = pycfdns.Client( api_token=self.config_entry.data[CONF_API_TOKEN], client_session=async_get_clientsession(self.hass), ) try: self.zone = next( zone for zone in await self.client.list_zones() if zone["name"] == self.config_entry.data[CONF_ZONE] ) except pycfdns.AuthenticationException as e: raise ConfigEntryAuthFailed from e except pycfdns.ComunicationException as e: raise UpdateFailed("Error communicating with API") from e async def _async_update_data(self) -> None: """Update records.""" _LOGGER.debug("Starting update for zone %s", self.zone["name"]) try: records = await self.client.list_dns_records( zone_id=self.zone["id"], type="A" ) _LOGGER.debug("Records: %s", records) target_records: list[str] = self.config_entry.data[CONF_RECORDS] location_info = await async_detect_location_info( async_get_clientsession(self.hass, family=socket.AF_INET) ) if not location_info or not is_ipv4_address(location_info.ip): raise UpdateFailed("Could not get external IPv4 address") filtered_records = [ record for record in records if record["name"] in target_records and record["content"] != location_info.ip ] if len(filtered_records) == 0: _LOGGER.debug("All target records are up to date") return await asyncio.gather( *[ self.client.update_dns_record( zone_id=self.zone["id"], record_id=record["id"], record_content=location_info.ip, record_name=record["name"], record_type=record["type"], record_proxied=record["proxied"], ) for record in filtered_records ] ) _LOGGER.debug("Update for zone %s is complete", self.zone["name"]) except ( pycfdns.AuthenticationException, pycfdns.ComunicationException, ) as e: raise UpdateFailed( f"Error updating zone {self.config_entry.data[CONF_ZONE]}" ) from e
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/cloudflare/coordinator.py", "license": "Apache License 2.0", "lines": 94, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/splunk/config_flow.py
"""Config flow for Splunk integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from hass_splunk import hass_splunk import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PORT, CONF_SSL, CONF_TOKEN, CONF_VERIFY_SSL, ) from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DEFAULT_HOST, DEFAULT_PORT, DOMAIN _LOGGER = logging.getLogger(__name__) class SplunkConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Splunk.""" VERSION = 1 MINOR_VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" # Single instance integration - manifest enforces only one entry errors: dict[str, str] = {} if user_input is not None: errors = await self._async_validate_input(user_input) if not errors: host = user_input[CONF_HOST] port = user_input[CONF_PORT] return self.async_create_entry( title=f"{host}:{port}", data=user_input, ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_TOKEN): str, vol.Required(CONF_HOST): str, vol.Optional(CONF_PORT, default=DEFAULT_PORT): int, vol.Optional(CONF_SSL, default=False): bool, vol.Optional(CONF_VERIFY_SSL, default=True): bool, vol.Optional(CONF_NAME): str, } ), errors=errors, ) async def async_step_import( self, import_config: dict[str, Any] ) -> ConfigFlowResult: """Handle import from YAML configuration.""" # Single instance integration - manifest prevents duplicates # Validate the imported configuration errors = await self._async_validate_input(import_config) if errors: # Map error keys to abort reasons for issue creation error_key = errors.get("base", "unknown") _LOGGER.error("Failed to import Splunk configuration from YAML: %s", errors) return self.async_abort(reason=error_key) host = import_config.get(CONF_HOST, DEFAULT_HOST) port = import_config.get(CONF_PORT, DEFAULT_PORT) return self.async_create_entry( title=f"{host}:{port}", data=import_config, ) async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration of the Splunk integration.""" errors: dict[str, str] = {} if user_input is not None: errors = await self._async_validate_input(user_input) if not errors: return self.async_update_reload_and_abort( self._get_reconfigure_entry(), data_updates=user_input, title=f"{user_input[CONF_HOST]}:{user_input[CONF_PORT]}", ) return self.async_show_form( step_id="reconfigure", data_schema=self.add_suggested_values_to_schema( vol.Schema( { vol.Required(CONF_TOKEN): str, vol.Required(CONF_HOST): str, vol.Optional(CONF_PORT, default=DEFAULT_PORT): int, vol.Optional(CONF_SSL, default=False): bool, vol.Optional(CONF_VERIFY_SSL, default=True): bool, vol.Optional(CONF_NAME): str, } ), self._get_reconfigure_entry().data, ), errors=errors, ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle reauth upon an API authentication error.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm reauth dialog.""" errors: dict[str, str] = {} if user_input is not None: reauth_entry = self._get_reauth_entry() # Test the new token with existing config test_config = {**reauth_entry.data, CONF_TOKEN: user_input[CONF_TOKEN]} errors = await self._async_validate_input(test_config) if not errors: return self.async_update_reload_and_abort( reauth_entry, data_updates={CONF_TOKEN: user_input[CONF_TOKEN]}, ) return self.async_show_form( step_id="reauth_confirm", data_schema=vol.Schema({vol.Required(CONF_TOKEN): str}), errors=errors, ) async def _async_validate_input(self, user_input: dict[str, Any]) -> dict[str, str]: """Validate user input and return errors if any.""" errors: dict[str, str] = {} event_collector = hass_splunk( session=async_get_clientsession(self.hass), host=user_input.get(CONF_HOST, DEFAULT_HOST), port=user_input.get(CONF_PORT, DEFAULT_PORT), token=user_input[CONF_TOKEN], use_ssl=user_input.get(CONF_SSL, False), verify_ssl=user_input.get(CONF_VERIFY_SSL, True), ) try: # First check connectivity connectivity_ok = await event_collector.check( connectivity=True, token=False, busy=False ) if not connectivity_ok: errors["base"] = "cannot_connect" return errors # Then check token validity token_ok = await event_collector.check( connectivity=False, token=True, busy=False ) if not token_ok: errors["base"] = "invalid_auth" return errors except Exception: _LOGGER.exception("Unexpected error validating Splunk connection") errors["base"] = "unknown" return errors
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/splunk/config_flow.py", "license": "Apache License 2.0", "lines": 155, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/splunk/const.py
"""Constants for the Splunk integration.""" DOMAIN = "splunk" CONF_FILTER = "filter" DEFAULT_HOST = "localhost" DEFAULT_PORT = 8088 DEFAULT_SSL = False DEFAULT_NAME = "HASS"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/splunk/const.py", "license": "Apache License 2.0", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/splunk/test_config_flow.py
"""Test the Splunk config flow.""" from unittest.mock import AsyncMock import pytest from homeassistant.components.splunk.const import DEFAULT_HOST, DEFAULT_PORT, DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PORT, CONF_SSL, CONF_TOKEN, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry pytestmark = pytest.mark.usefixtures("mock_setup_entry") async def test_user_flow_success( hass: HomeAssistant, mock_hass_splunk: AsyncMock ) -> None: """Test successful user flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_TOKEN: "test-token-123", CONF_HOST: "splunk.example.com", CONF_PORT: 8088, CONF_SSL: True, CONF_NAME: "Test Splunk", }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "splunk.example.com:8088" assert result["data"] == { CONF_TOKEN: "test-token-123", CONF_HOST: "splunk.example.com", CONF_PORT: 8088, CONF_SSL: True, CONF_VERIFY_SSL: True, CONF_NAME: "Test Splunk", } # Verify that check was called twice (connectivity and token) assert mock_hass_splunk.check.call_count == 2 @pytest.mark.parametrize( ("side_effect", "error"), [ ([False, True], "cannot_connect"), ([True, False], "invalid_auth"), (Exception("Unexpected error"), "unknown"), ], ) async def test_user_flow_error_and_recovery( hass: HomeAssistant, mock_hass_splunk: AsyncMock, side_effect: list[bool] | Exception, error: str, ) -> None: """Test user flow errors and recovery.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) mock_hass_splunk.check.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_TOKEN: "test-token-123", CONF_HOST: "splunk.example.com", CONF_PORT: 8088, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": error} # Test recovery by resetting mock and completing successfully mock_hass_splunk.check.side_effect = None mock_hass_splunk.check.return_value = True result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_TOKEN: "test-token-123", CONF_HOST: "splunk.example.com", CONF_PORT: 8088, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_user_flow_already_configured( hass: HomeAssistant, mock_hass_splunk: AsyncMock, mock_config_entry: MockConfigEntry ) -> None: """Test user flow when entry is already configured (single instance).""" mock_config_entry.add_to_hass(hass) # With single_config_entry in manifest, flow should abort immediately result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "single_instance_allowed" async def test_import_flow_success( hass: HomeAssistant, mock_hass_splunk: AsyncMock ) -> None: """Test successful import flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_TOKEN: "test-token-123", CONF_HOST: "splunk.example.com", CONF_PORT: 8088, CONF_SSL: False, CONF_NAME: "Imported Splunk", }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "splunk.example.com:8088" assert result["data"] == { CONF_TOKEN: "test-token-123", CONF_HOST: "splunk.example.com", CONF_PORT: 8088, CONF_SSL: False, CONF_NAME: "Imported Splunk", } @pytest.mark.parametrize( ("side_effect", "reason"), [ ([False, True], "cannot_connect"), ([True, False], "invalid_auth"), (Exception("Unexpected error"), "unknown"), ], ) async def test_import_flow_error_and_recovery( hass: HomeAssistant, mock_hass_splunk: AsyncMock, side_effect: list[bool] | Exception, reason: str, ) -> None: """Test import flow errors and recovery.""" mock_hass_splunk.check.side_effect = side_effect result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_TOKEN: "test-token-123", CONF_HOST: "splunk.example.com", CONF_PORT: 8088, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == reason # Test recovery by resetting mock and importing again mock_hass_splunk.check.side_effect = None mock_hass_splunk.check.return_value = True result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_TOKEN: "test-token-123", CONF_HOST: "splunk.example.com", CONF_PORT: 8088, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_import_flow_already_configured( hass: HomeAssistant, mock_hass_splunk: AsyncMock, mock_config_entry: MockConfigEntry ) -> None: """Test import flow when entry is already configured (single instance).""" mock_config_entry.add_to_hass(hass) # With single_config_entry in manifest, import should abort immediately result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_TOKEN: "test-token-123", CONF_HOST: DEFAULT_HOST, CONF_PORT: DEFAULT_PORT, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "single_instance_allowed" async def test_reconfigure_flow_success( hass: HomeAssistant, mock_hass_splunk: AsyncMock, mock_config_entry: MockConfigEntry ) -> None: """Test successful reconfigure flow.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reconfigure_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reconfigure" result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_TOKEN: "new-token-456", CONF_HOST: "new-splunk.example.com", CONF_PORT: 9088, CONF_SSL: True, CONF_VERIFY_SSL: False, CONF_NAME: "Updated Splunk", }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reconfigure_successful" assert mock_config_entry.data[CONF_HOST] == "new-splunk.example.com" assert mock_config_entry.data[CONF_PORT] == 9088 assert mock_config_entry.data[CONF_TOKEN] == "new-token-456" assert mock_config_entry.data[CONF_SSL] is True assert mock_config_entry.data[CONF_VERIFY_SSL] is False assert mock_config_entry.data[CONF_NAME] == "Updated Splunk" assert mock_config_entry.title == "new-splunk.example.com:9088" @pytest.mark.parametrize( ("side_effect", "error"), [ ([False, True], "cannot_connect"), ([True, False], "invalid_auth"), (Exception("Unexpected error"), "unknown"), ], ) async def test_reconfigure_flow_error_and_recovery( hass: HomeAssistant, mock_hass_splunk: AsyncMock, mock_config_entry: MockConfigEntry, side_effect: list[bool] | Exception, error: str, ) -> None: """Test reconfigure flow errors and recovery.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reconfigure_flow(hass) mock_hass_splunk.check.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_TOKEN: "test-token-123", CONF_HOST: "new-splunk.example.com", CONF_PORT: 8088, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reconfigure" assert result["errors"] == {"base": error} # Test recovery mock_hass_splunk.check.side_effect = None mock_hass_splunk.check.return_value = True result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_TOKEN: "test-token-123", CONF_HOST: "new-splunk.example.com", CONF_PORT: 8088, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reconfigure_successful" async def test_reauth_flow_success( hass: HomeAssistant, mock_hass_splunk: AsyncMock, mock_config_entry: MockConfigEntry ) -> None: """Test successful reauth flow.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_TOKEN: "new-token-456"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data[CONF_TOKEN] == "new-token-456" async def test_reauth_flow_invalid_auth( hass: HomeAssistant, mock_hass_splunk: AsyncMock, mock_config_entry: MockConfigEntry ) -> None: """Test reauth flow with invalid token and recovery.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) # Mock token check failure mock_hass_splunk.check.side_effect = [True, False] result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_TOKEN: "invalid-token"}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" assert result["errors"] == {"base": "invalid_auth"} # Now test that we can recover from the error mock_hass_splunk.check.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_TOKEN: "new-valid-token"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data[CONF_TOKEN] == "new-valid-token"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/splunk/test_config_flow.py", "license": "Apache License 2.0", "lines": 300, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/compit/number.py
"""Number platform for Compit integration.""" from dataclasses import dataclass from compit_inext_api.consts import CompitParameter from homeassistant.components.number import ( NumberDeviceClass, NumberEntity, NumberEntityDescription, NumberMode, ) from homeassistant.const import EntityCategory, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MANUFACTURER_NAME from .coordinator import CompitConfigEntry, CompitDataUpdateCoordinator PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class CompitDeviceDescription: """Class to describe a Compit device.""" name: str """Name of the device.""" parameters: list[NumberEntityDescription] """Parameters of the device.""" DESCRIPTIONS: dict[CompitParameter, NumberEntityDescription] = { CompitParameter.TARGET_TEMPERATURE_COMFORT: NumberEntityDescription( key=CompitParameter.TARGET_TEMPERATURE_COMFORT.value, translation_key="target_temperature_comfort", native_min_value=0, native_max_value=40, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.TARGET_TEMPERATURE_ECO_WINTER: NumberEntityDescription( key=CompitParameter.TARGET_TEMPERATURE_ECO_WINTER.value, translation_key="target_temperature_eco_winter", native_min_value=0, native_max_value=40, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.TARGET_TEMPERATURE_ECO_COOLING: NumberEntityDescription( key=CompitParameter.TARGET_TEMPERATURE_ECO_COOLING.value, translation_key="target_temperature_eco_cooling", native_min_value=0, native_max_value=40, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.TARGET_TEMPERATURE_OUT_OF_HOME: NumberEntityDescription( key=CompitParameter.TARGET_TEMPERATURE_OUT_OF_HOME.value, translation_key="target_temperature_out_of_home", native_min_value=0, native_max_value=40, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.TARGET_TEMPERATURE_ECO: NumberEntityDescription( key=CompitParameter.TARGET_TEMPERATURE_ECO.value, translation_key="target_temperature_eco", native_min_value=0, native_max_value=40, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.TARGET_TEMPERATURE_HOLIDAY: NumberEntityDescription( key=CompitParameter.TARGET_TEMPERATURE_HOLIDAY.value, translation_key="target_temperature_holiday", native_min_value=0, native_max_value=40, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.TARGET_TEMPERATURE_CONST: NumberEntityDescription( key=CompitParameter.TARGET_TEMPERATURE_CONST.value, translation_key="target_temperature_const", native_min_value=0, native_max_value=95, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.HEATING_TARGET_TEMPERATURE_CONST: NumberEntityDescription( key=CompitParameter.HEATING_TARGET_TEMPERATURE_CONST.value, translation_key="heating_target_temperature_const", native_min_value=0, native_max_value=95, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.MIXER_TARGET_TEMPERATURE: NumberEntityDescription( key=CompitParameter.MIXER_TARGET_TEMPERATURE.value, translation_key="mixer_target_temperature", native_min_value=0, native_max_value=90, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.MIXER1_TARGET_TEMPERATURE: NumberEntityDescription( key=CompitParameter.MIXER1_TARGET_TEMPERATURE.value, translation_key="mixer_target_temperature_zone", native_min_value=0, native_max_value=95, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, translation_placeholders={"zone": "1"}, ), CompitParameter.MIXER2_TARGET_TEMPERATURE: NumberEntityDescription( key=CompitParameter.MIXER2_TARGET_TEMPERATURE.value, translation_key="mixer_target_temperature_zone", native_min_value=0, native_max_value=95, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, translation_placeholders={"zone": "2"}, ), CompitParameter.BOILER_TARGET_TEMPERATURE: NumberEntityDescription( key=CompitParameter.BOILER_TARGET_TEMPERATURE.value, translation_key="boiler_target_temperature", native_min_value=0, native_max_value=95, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), CompitParameter.BOILER_TARGET_TEMPERATURE_CONST: NumberEntityDescription( key=CompitParameter.BOILER_TARGET_TEMPERATURE_CONST.value, translation_key="boiler_target_temperature_const", native_min_value=0, native_max_value=90, native_step=0.1, native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=NumberDeviceClass.TEMPERATURE, mode=NumberMode.SLIDER, entity_category=EntityCategory.CONFIG, ), } DEVICE_DEFINITIONS: dict[int, CompitDeviceDescription] = { 7: CompitDeviceDescription( name="Nano One", parameters=[ DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_COMFORT], DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_ECO], DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_HOLIDAY], ], ), 12: CompitDeviceDescription( name="Nano Color", parameters=[ DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_COMFORT], DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_ECO_WINTER], DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_ECO_COOLING], DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_OUT_OF_HOME], ], ), 223: CompitDeviceDescription( name="Nano Color 2", parameters=[ DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_COMFORT], DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_ECO_WINTER], DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_ECO_COOLING], DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_OUT_OF_HOME], ], ), 3: CompitDeviceDescription( name="R810", parameters=[ DESCRIPTIONS[CompitParameter.TARGET_TEMPERATURE_CONST], ], ), 34: CompitDeviceDescription( name="r470", parameters=[ DESCRIPTIONS[CompitParameter.HEATING_TARGET_TEMPERATURE_CONST], ], ), 221: CompitDeviceDescription( name="R350.M", parameters=[ DESCRIPTIONS[CompitParameter.MIXER_TARGET_TEMPERATURE], ], ), 91: CompitDeviceDescription( name="R770RS / R771RS", parameters=[ DESCRIPTIONS[CompitParameter.MIXER1_TARGET_TEMPERATURE], DESCRIPTIONS[CompitParameter.MIXER2_TARGET_TEMPERATURE], ], ), 212: CompitDeviceDescription( name="BioMax742", parameters=[ DESCRIPTIONS[CompitParameter.BOILER_TARGET_TEMPERATURE], ], ), 210: CompitDeviceDescription( name="EL750", parameters=[ DESCRIPTIONS[CompitParameter.BOILER_TARGET_TEMPERATURE], ], ), 36: CompitDeviceDescription( name="BioMax742", parameters=[ DESCRIPTIONS[CompitParameter.BOILER_TARGET_TEMPERATURE_CONST], ], ), 75: CompitDeviceDescription( name="BioMax772", parameters=[ DESCRIPTIONS[CompitParameter.BOILER_TARGET_TEMPERATURE_CONST], ], ), 201: CompitDeviceDescription( name="BioMax775", parameters=[ DESCRIPTIONS[CompitParameter.BOILER_TARGET_TEMPERATURE_CONST], ], ), } async def async_setup_entry( hass: HomeAssistant, entry: CompitConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Compit number entities from a config entry.""" coordinator = entry.runtime_data async_add_entities( CompitNumber( coordinator, device_id, device_definition.name, entity_description, ) for device_id, device in coordinator.connector.all_devices.items() if (device_definition := DEVICE_DEFINITIONS.get(device.definition.code)) for entity_description in device_definition.parameters ) class CompitNumber(CoordinatorEntity[CompitDataUpdateCoordinator], NumberEntity): """Representation of a Compit number entity.""" _attr_has_entity_name = True def __init__( self, coordinator: CompitDataUpdateCoordinator, device_id: int, device_name: str, entity_description: NumberEntityDescription, ) -> None: """Initialize the number entity.""" super().__init__(coordinator) self.device_id = device_id self.entity_description = entity_description self._attr_unique_id = f"{device_id}_{entity_description.key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, str(device_id))}, name=device_name, manufacturer=MANUFACTURER_NAME, model=device_name, ) @property def available(self) -> bool: """Return if entity is available.""" return ( super().available and self.coordinator.connector.get_device(self.device_id) is not None ) @property def native_value(self) -> float | None: """Return the current value.""" value = self.coordinator.connector.get_current_value( self.device_id, CompitParameter(self.entity_description.key) ) if value is None or isinstance(value, str): return None return value async def async_set_native_value(self, value: float) -> None: """Set new value.""" await self.coordinator.connector.set_device_parameter( self.device_id, CompitParameter(self.entity_description.key), value ) self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/compit/number.py", "license": "Apache License 2.0", "lines": 315, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/compit/test_number.py
"""Tests for the Compit number platform.""" from typing import Any from unittest.mock import MagicMock from compit_inext_api.consts import CompitParameter import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration, snapshot_compit_entities from tests.common import MockConfigEntry async def test_number_entities_snapshot( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, mock_connector: MagicMock, snapshot: SnapshotAssertion, ) -> None: """Snapshot test for number entities creation, unique IDs, and device info.""" await setup_integration(hass, mock_config_entry) snapshot_compit_entities(hass, entity_registry, snapshot, Platform.NUMBER) @pytest.mark.parametrize( "mock_return_value", [ None, "invalid", ], ) async def test_number_unknown_device_parameters( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock, mock_return_value: Any, ) -> None: """Test that number entity shows unknown when get_parameter_value returns invalid values.""" mock_connector.get_current_value.side_effect = lambda device_id, parameter_code: ( mock_return_value ) await setup_integration(hass, mock_config_entry) state = hass.states.get("number.nano_color_2_target_comfort_temperature") assert state is not None assert state.state == "unknown" async def test_number_get_value( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock, ) -> None: """Test getting a number value.""" mock_connector.get_current_value.side_effect = lambda device_id, parameter_code: ( 22.0 ) await setup_integration(hass, mock_config_entry) state = hass.states.get("number.nano_color_2_target_comfort_temperature") assert state is not None assert state.state == "22.0" async def test_set_number_value( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock, ) -> None: """Test setting a number value.""" await setup_integration(hass, mock_config_entry) state = hass.states.get("number.nano_color_2_target_comfort_temperature") assert state is not None await hass.services.async_call( "number", "set_value", {ATTR_ENTITY_ID: state.entity_id, "value": 23}, blocking=True, ) mock_connector.set_device_parameter.assert_called_once_with( 2, CompitParameter.TARGET_TEMPERATURE_COMFORT, 23 )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/compit/test_number.py", "license": "Apache License 2.0", "lines": 73, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/actron_air/test_climate.py
"""Tests for the Actron Air climate platform.""" from unittest.mock import MagicMock, patch from actron_neo_api import ActronAirAPIError import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.climate import ( ATTR_FAN_MODE, ATTR_HVAC_MODE, DOMAIN as CLIMATE_DOMAIN, SERVICE_SET_FAN_MODE, SERVICE_SET_HVAC_MODE, SERVICE_SET_TEMPERATURE, HVACMode, ) from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, snapshot_platform async def test_climate_entities( hass: HomeAssistant, mock_actron_api: MagicMock, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, mock_zone: MagicMock, ) -> None: """Test climate entities.""" status = mock_actron_api.state_manager.get_status.return_value status.remote_zone_info = [mock_zone] status.zones = {1: mock_zone} with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.CLIMATE]): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_system_set_temperature( hass: HomeAssistant, mock_actron_api: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setting temperature for system climate entity.""" with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.CLIMATE]): await setup_integration(hass, mock_config_entry) status = mock_actron_api.state_manager.get_status.return_value await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, {ATTR_ENTITY_ID: "climate.test_system", ATTR_TEMPERATURE: 22.5}, blocking=True, ) status.user_aircon_settings.set_temperature.assert_awaited_once_with( temperature=22.5 ) async def test_system_set_temperature_api_error( hass: HomeAssistant, mock_actron_api: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test API error when setting temperature for system climate entity.""" with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.CLIMATE]): await setup_integration(hass, mock_config_entry) status = mock_actron_api.state_manager.get_status.return_value status.user_aircon_settings.set_temperature.side_effect = ActronAirAPIError( "Test error" ) with pytest.raises(HomeAssistantError, match="Test error"): await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, {ATTR_ENTITY_ID: "climate.test_system", ATTR_TEMPERATURE: 22.5}, blocking=True, ) async def test_system_set_fan_mode( hass: HomeAssistant, mock_actron_api: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setting fan mode for system climate entity.""" with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.CLIMATE]): await setup_integration(hass, mock_config_entry) status = mock_actron_api.state_manager.get_status.return_value await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_FAN_MODE, {ATTR_ENTITY_ID: "climate.test_system", ATTR_FAN_MODE: "low"}, blocking=True, ) status.user_aircon_settings.set_fan_mode.assert_awaited_once_with("LOW") async def test_system_set_fan_mode_api_error( hass: HomeAssistant, mock_actron_api: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test API error when setting fan mode for system climate entity.""" with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.CLIMATE]): await setup_integration(hass, mock_config_entry) status = mock_actron_api.state_manager.get_status.return_value status.user_aircon_settings.set_fan_mode.side_effect = ActronAirAPIError( "Test error" ) with pytest.raises(HomeAssistantError, match="Test error"): await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_FAN_MODE, {ATTR_ENTITY_ID: "climate.test_system", ATTR_FAN_MODE: "high"}, blocking=True, ) async def test_system_set_hvac_mode( hass: HomeAssistant, mock_actron_api: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setting HVAC mode for system climate entity.""" with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.CLIMATE]): await setup_integration(hass, mock_config_entry) status = mock_actron_api.state_manager.get_status.return_value await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, {ATTR_ENTITY_ID: "climate.test_system", ATTR_HVAC_MODE: HVACMode.COOL}, blocking=True, ) status.ac_system.set_system_mode.assert_awaited_once_with("COOL") async def test_system_set_hvac_mode_api_error( hass: HomeAssistant, mock_actron_api: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test API error when setting HVAC mode for system climate entity.""" with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.CLIMATE]): await setup_integration(hass, mock_config_entry) status = mock_actron_api.state_manager.get_status.return_value status.ac_system.set_system_mode.side_effect = ActronAirAPIError("Test error") with pytest.raises(HomeAssistantError, match="Test error"): await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, {ATTR_ENTITY_ID: "climate.test_system", ATTR_HVAC_MODE: HVACMode.HEAT}, blocking=True, ) async def test_zone_set_temperature( hass: HomeAssistant, init_integration_with_zone: None, mock_zone: MagicMock, ) -> None: """Test setting temperature for zone climate entity.""" await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, {ATTR_ENTITY_ID: "climate.living_room", ATTR_TEMPERATURE: 23.0}, blocking=True, ) mock_zone.set_temperature.assert_awaited_once_with(temperature=23.0) async def test_zone_set_temperature_api_error( hass: HomeAssistant, init_integration_with_zone: None, mock_zone: MagicMock, ) -> None: """Test API error when setting temperature for zone climate entity.""" mock_zone.set_temperature.side_effect = ActronAirAPIError("Test error") with pytest.raises(HomeAssistantError, match="Test error"): await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, {ATTR_ENTITY_ID: "climate.living_room", ATTR_TEMPERATURE: 23.0}, blocking=True, ) async def test_zone_set_hvac_mode_on( hass: HomeAssistant, init_integration_with_zone: None, mock_zone: MagicMock, ) -> None: """Test setting HVAC mode to on for zone climate entity.""" mock_zone.is_active = False mock_zone.hvac_mode = "OFF" await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, {ATTR_ENTITY_ID: "climate.living_room", ATTR_HVAC_MODE: HVACMode.COOL}, blocking=True, ) mock_zone.enable.assert_awaited_once_with(True) async def test_zone_set_hvac_mode_off( hass: HomeAssistant, init_integration_with_zone: None, mock_zone: MagicMock, ) -> None: """Test setting HVAC mode to off for zone climate entity.""" await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, {ATTR_ENTITY_ID: "climate.living_room", ATTR_HVAC_MODE: HVACMode.OFF}, blocking=True, ) mock_zone.enable.assert_awaited_once_with(False) async def test_zone_set_hvac_mode_api_error( hass: HomeAssistant, init_integration_with_zone: None, mock_zone: MagicMock, ) -> None: """Test API error when setting HVAC mode for zone climate entity.""" mock_zone.enable.side_effect = ActronAirAPIError("Test error") with pytest.raises(HomeAssistantError, match="Test error"): await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, {ATTR_ENTITY_ID: "climate.living_room", ATTR_HVAC_MODE: HVACMode.OFF}, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/actron_air/test_climate.py", "license": "Apache License 2.0", "lines": 209, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/google_travel_time/schemas.py
"""Schemas for the Google Travel Time integration.""" import voluptuous as vol from homeassistant.const import ATTR_CONFIG_ENTRY_ID, CONF_LANGUAGE, CONF_MODE from homeassistant.helpers.selector import ( ConfigEntrySelector, SelectSelector, SelectSelectorConfig, SelectSelectorMode, TextSelector, TimeSelector, ) from .const import ( ALL_LANGUAGES, AVOID_OPTIONS, CONF_ARRIVAL_TIME, CONF_AVOID, CONF_DEPARTURE_TIME, CONF_DESTINATION, CONF_ORIGIN, CONF_TIME_TYPE, CONF_TRAFFIC_MODEL, CONF_TRANSIT_MODE, CONF_TRANSIT_ROUTING_PREFERENCE, CONF_UNITS, DOMAIN, TIME_TYPES, TRAFFIC_MODELS, TRANSIT_PREFS, TRANSPORT_TYPES, TRAVEL_MODES_WITHOUT_TRANSIT, UNITS, UNITS_METRIC, ) LANGUAGE_SELECTOR = SelectSelector( SelectSelectorConfig( options=sorted(ALL_LANGUAGES), mode=SelectSelectorMode.DROPDOWN, translation_key=CONF_LANGUAGE, ) ) AVOID_SELECTOR = SelectSelector( SelectSelectorConfig( options=AVOID_OPTIONS, sort=True, mode=SelectSelectorMode.DROPDOWN, translation_key=CONF_AVOID, ) ) TRAFFIC_MODEL_SELECTOR = SelectSelector( SelectSelectorConfig( options=TRAFFIC_MODELS, sort=True, mode=SelectSelectorMode.DROPDOWN, translation_key=CONF_TRAFFIC_MODEL, ) ) TRANSIT_MODE_SELECTOR = SelectSelector( SelectSelectorConfig( options=TRANSPORT_TYPES, sort=True, mode=SelectSelectorMode.DROPDOWN, translation_key=CONF_TRANSIT_MODE, ) ) TRANSIT_ROUTING_PREFERENCE_SELECTOR = SelectSelector( SelectSelectorConfig( options=TRANSIT_PREFS, sort=True, mode=SelectSelectorMode.DROPDOWN, translation_key=CONF_TRANSIT_ROUTING_PREFERENCE, ) ) UNITS_SELECTOR = SelectSelector( SelectSelectorConfig( options=UNITS, sort=True, mode=SelectSelectorMode.DROPDOWN, translation_key=CONF_UNITS, ) ) TIME_TYPE_SELECTOR = SelectSelector( SelectSelectorConfig( options=TIME_TYPES, sort=True, mode=SelectSelectorMode.DROPDOWN, translation_key=CONF_TIME_TYPE, ) ) _SERVICE_BASE_SCHEMA = vol.Schema( { vol.Required(ATTR_CONFIG_ENTRY_ID): ConfigEntrySelector( {"integration": DOMAIN} ), vol.Required(CONF_ORIGIN): TextSelector(), vol.Required(CONF_DESTINATION): TextSelector(), vol.Optional(CONF_UNITS, default=UNITS_METRIC): UNITS_SELECTOR, vol.Optional(CONF_LANGUAGE): LANGUAGE_SELECTOR, } ) SERVICE_GET_TRAVEL_TIMES_SCHEMA = _SERVICE_BASE_SCHEMA.extend( { vol.Optional(CONF_MODE, default="driving"): SelectSelector( SelectSelectorConfig( options=TRAVEL_MODES_WITHOUT_TRANSIT, sort=True, mode=SelectSelectorMode.DROPDOWN, translation_key=CONF_MODE, ) ), vol.Optional(CONF_AVOID): AVOID_SELECTOR, vol.Optional(CONF_TRAFFIC_MODEL): TRAFFIC_MODEL_SELECTOR, vol.Optional(CONF_DEPARTURE_TIME): TimeSelector(), } ) SERVICE_GET_TRANSIT_TIMES_SCHEMA = _SERVICE_BASE_SCHEMA.extend( { vol.Optional(CONF_TRANSIT_MODE): TRANSIT_MODE_SELECTOR, vol.Optional( CONF_TRANSIT_ROUTING_PREFERENCE ): TRANSIT_ROUTING_PREFERENCE_SELECTOR, vol.Exclusive(CONF_DEPARTURE_TIME, "time"): TimeSelector(), vol.Exclusive(CONF_ARRIVAL_TIME, "time"): TimeSelector(), } )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_travel_time/schemas.py", "license": "Apache License 2.0", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/google_travel_time/services.py
"""Services for the Google Travel Time integration.""" from typing import cast from google.api_core.client_options import ClientOptions from google.api_core.exceptions import GoogleAPIError, PermissionDenied from google.maps.routing_v2 import RoutesAsyncClient from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_CONFIG_ENTRY_ID, CONF_API_KEY, CONF_LANGUAGE, CONF_MODE, ) from homeassistant.core import ( HomeAssistant, ServiceCall, ServiceResponse, SupportsResponse, callback, ) from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.service import async_get_config_entry from .const import ( CONF_ARRIVAL_TIME, CONF_AVOID, CONF_DEPARTURE_TIME, CONF_DESTINATION, CONF_ORIGIN, CONF_TRAFFIC_MODEL, CONF_TRANSIT_MODE, CONF_TRANSIT_ROUTING_PREFERENCE, CONF_UNITS, DOMAIN, TRAVEL_MODES_TO_GOOGLE_SDK_ENUM, ) from .helpers import ( async_compute_routes, create_routes_api_disabled_issue, delete_routes_api_disabled_issue, ) from .schemas import SERVICE_GET_TRANSIT_TIMES_SCHEMA, SERVICE_GET_TRAVEL_TIMES_SCHEMA SERVICE_GET_TRAVEL_TIMES = "get_travel_times" SERVICE_GET_TRANSIT_TIMES = "get_transit_times" def _build_routes_response(response) -> list[dict]: """Build the routes response from the API response.""" if response is None or not response.routes: return [] return [ { "duration": route.duration.seconds, "duration_text": route.localized_values.duration.text, "static_duration_text": route.localized_values.static_duration.text, "distance_meters": route.distance_meters, "distance_text": route.localized_values.distance.text, } for route in response.routes ] def _raise_service_error( hass: HomeAssistant, entry: ConfigEntry, exc: Exception ) -> None: """Raise a HomeAssistantError based on the exception.""" if isinstance(exc, PermissionDenied): create_routes_api_disabled_issue(hass, entry) raise HomeAssistantError( translation_domain=DOMAIN, translation_key="permission_denied", ) from exc if isinstance(exc, GoogleAPIError): raise HomeAssistantError( translation_domain=DOMAIN, translation_key="api_error", translation_placeholders={"error": str(exc)}, ) from exc raise exc @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services for the Google Travel Time integration.""" async def async_get_travel_times_service(service: ServiceCall) -> ServiceResponse: """Handle the service call to get travel times (non-transit modes).""" entry = async_get_config_entry( service.hass, DOMAIN, service.data[ATTR_CONFIG_ENTRY_ID] ) api_key = entry.data[CONF_API_KEY] travel_mode = TRAVEL_MODES_TO_GOOGLE_SDK_ENUM[service.data[CONF_MODE]] client_options = ClientOptions(api_key=api_key) client = RoutesAsyncClient(client_options=client_options) try: response = await async_compute_routes( client=client, origin=service.data[CONF_ORIGIN], destination=service.data[CONF_DESTINATION], hass=hass, travel_mode=travel_mode, units=service.data[CONF_UNITS], language=service.data.get(CONF_LANGUAGE), avoid=service.data.get(CONF_AVOID), traffic_model=service.data.get(CONF_TRAFFIC_MODEL), departure_time=service.data.get(CONF_DEPARTURE_TIME), ) except Exception as ex: # noqa: BLE001 _raise_service_error(hass, entry, ex) delete_routes_api_disabled_issue(hass, entry) return cast(ServiceResponse, {"routes": _build_routes_response(response)}) async def async_get_transit_times_service(service: ServiceCall) -> ServiceResponse: """Handle the service call to get transit times.""" entry = async_get_config_entry( service.hass, DOMAIN, service.data[ATTR_CONFIG_ENTRY_ID] ) api_key = entry.data[CONF_API_KEY] client_options = ClientOptions(api_key=api_key) client = RoutesAsyncClient(client_options=client_options) try: response = await async_compute_routes( client=client, origin=service.data[CONF_ORIGIN], destination=service.data[CONF_DESTINATION], hass=hass, travel_mode=TRAVEL_MODES_TO_GOOGLE_SDK_ENUM["transit"], units=service.data[CONF_UNITS], language=service.data.get(CONF_LANGUAGE), transit_mode=service.data.get(CONF_TRANSIT_MODE), transit_routing_preference=service.data.get( CONF_TRANSIT_ROUTING_PREFERENCE ), departure_time=service.data.get(CONF_DEPARTURE_TIME), arrival_time=service.data.get(CONF_ARRIVAL_TIME), ) except Exception as ex: # noqa: BLE001 _raise_service_error(hass, entry, ex) delete_routes_api_disabled_issue(hass, entry) return cast(ServiceResponse, {"routes": _build_routes_response(response)}) hass.services.async_register( DOMAIN, SERVICE_GET_TRAVEL_TIMES, async_get_travel_times_service, SERVICE_GET_TRAVEL_TIMES_SCHEMA, supports_response=SupportsResponse.ONLY, ) hass.services.async_register( DOMAIN, SERVICE_GET_TRANSIT_TIMES, async_get_transit_times_service, SERVICE_GET_TRANSIT_TIMES_SCHEMA, supports_response=SupportsResponse.ONLY, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_travel_time/services.py", "license": "Apache License 2.0", "lines": 144, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/google_travel_time/test_services.py
"""Tests for Google Maps Travel Time services.""" from unittest.mock import AsyncMock from google.api_core.exceptions import GoogleAPIError, PermissionDenied import pytest from homeassistant.components.google_travel_time.const import DOMAIN from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from .const import DEFAULT_OPTIONS, MOCK_CONFIG from tests.common import MockConfigEntry @pytest.mark.parametrize( ("data", "options"), [(MOCK_CONFIG, DEFAULT_OPTIONS)], ) async def test_service_get_travel_times( hass: HomeAssistant, routes_mock: AsyncMock, mock_config: MockConfigEntry, ) -> None: """Test service get_travel_times.""" response_data = await hass.services.async_call( DOMAIN, "get_travel_times", { "config_entry_id": mock_config.entry_id, "origin": "location1", "destination": "location2", "mode": "driving", "units": "metric", }, blocking=True, return_response=True, ) assert response_data == { "routes": [ { "duration": 1620, "duration_text": "27 mins", "static_duration_text": "26 mins", "distance_meters": 21300, "distance_text": "21.3 km", } ] } @pytest.mark.parametrize( ("data", "options"), [(MOCK_CONFIG, DEFAULT_OPTIONS)], ) async def test_service_get_travel_times_with_all_options( hass: HomeAssistant, routes_mock: AsyncMock, mock_config: MockConfigEntry, ) -> None: """Test service get_travel_times with all optional parameters.""" response_data = await hass.services.async_call( DOMAIN, "get_travel_times", { "config_entry_id": mock_config.entry_id, "origin": "location1", "destination": "location2", "mode": "driving", "units": "imperial", "language": "en", "avoid": "tolls", "traffic_model": "best_guess", "departure_time": "08:00:00", }, blocking=True, return_response=True, ) assert "routes" in response_data assert len(response_data["routes"]) == 1 @pytest.mark.parametrize( ("data", "options"), [(MOCK_CONFIG, DEFAULT_OPTIONS)], ) async def test_service_get_travel_times_empty_response( hass: HomeAssistant, routes_mock: AsyncMock, mock_config: MockConfigEntry, ) -> None: """Test service get_travel_times with empty response.""" routes_mock.compute_routes.return_value = None response_data = await hass.services.async_call( DOMAIN, "get_travel_times", { "config_entry_id": mock_config.entry_id, "origin": "location1", "destination": "location2", "mode": "driving", "units": "metric", }, blocking=True, return_response=True, ) assert response_data == {"routes": []} @pytest.mark.parametrize( ("data", "options"), [(MOCK_CONFIG, DEFAULT_OPTIONS)], ) @pytest.mark.parametrize( ("exception", "error_message"), [ ( PermissionDenied("test"), "The Routes API is not enabled for this API key", ), (GoogleAPIError("test"), "Google API error"), ], ) async def test_service_get_travel_times_errors( hass: HomeAssistant, routes_mock: AsyncMock, mock_config: MockConfigEntry, exception: Exception, error_message: str, ) -> None: """Test service get_travel_times error handling.""" routes_mock.compute_routes.side_effect = exception with pytest.raises( HomeAssistantError, match=error_message, ): await hass.services.async_call( DOMAIN, "get_travel_times", { "config_entry_id": mock_config.entry_id, "origin": "location1", "destination": "location2", "mode": "driving", "units": "metric", }, blocking=True, return_response=True, ) @pytest.mark.parametrize( ("data", "options"), [(MOCK_CONFIG, DEFAULT_OPTIONS)], ) async def test_service_get_transit_times( hass: HomeAssistant, routes_mock: AsyncMock, mock_config: MockConfigEntry, ) -> None: """Test service get_transit_times.""" response_data = await hass.services.async_call( DOMAIN, "get_transit_times", { "config_entry_id": mock_config.entry_id, "origin": "location1", "destination": "location2", "units": "metric", }, blocking=True, return_response=True, ) assert response_data == { "routes": [ { "duration": 1620, "duration_text": "27 mins", "static_duration_text": "26 mins", "distance_meters": 21300, "distance_text": "21.3 km", } ] } @pytest.mark.parametrize( ("data", "options"), [(MOCK_CONFIG, DEFAULT_OPTIONS)], ) async def test_service_get_transit_times_with_all_options( hass: HomeAssistant, routes_mock: AsyncMock, mock_config: MockConfigEntry, ) -> None: """Test service get_transit_times with all optional parameters.""" response_data = await hass.services.async_call( DOMAIN, "get_transit_times", { "config_entry_id": mock_config.entry_id, "origin": "location1", "destination": "location2", "units": "imperial", "language": "en", "transit_mode": "bus", "transit_routing_preference": "fewer_transfers", "departure_time": "08:00:00", }, blocking=True, return_response=True, ) assert "routes" in response_data assert len(response_data["routes"]) == 1 @pytest.mark.parametrize( ("data", "options"), [(MOCK_CONFIG, DEFAULT_OPTIONS)], ) @pytest.mark.parametrize( ("exception", "error_message"), [ ( PermissionDenied("test"), "The Routes API is not enabled for this API key", ), (GoogleAPIError("test"), "Google API error"), ], ) async def test_service_get_transit_times_errors( hass: HomeAssistant, routes_mock: AsyncMock, mock_config: MockConfigEntry, exception: Exception, error_message: str, ) -> None: """Test service get_transit_times error handling.""" routes_mock.compute_routes.side_effect = exception with pytest.raises( HomeAssistantError, match=error_message, ): await hass.services.async_call( DOMAIN, "get_transit_times", { "config_entry_id": mock_config.entry_id, "origin": "location1", "destination": "location2", "units": "metric", }, blocking=True, return_response=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/google_travel_time/test_services.py", "license": "Apache License 2.0", "lines": 237, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/homevolt/diagnostics.py
"""Diagnostics support for Homevolt.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import CONF_HOST, CONF_PASSWORD from homeassistant.core import HomeAssistant from .coordinator import HomevoltConfigEntry TO_REDACT = {CONF_HOST, CONF_PASSWORD} async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: HomevoltConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator = entry.runtime_data client = coordinator.data result: dict[str, Any] = { "config": async_redact_data(entry.data, TO_REDACT), "coordinator": { "last_update_success": coordinator.last_update_success, "last_exception": ( str(coordinator.last_exception) if coordinator.last_exception else None ), }, } if client is None: return result result["device"] = { "unique_id": client.unique_id, } result["sensors"] = { key: {"value": sensor.value, "type": sensor.type} for key, sensor in client.sensors.items() } result["ems"] = { device_id: { "name": metadata.name, "model": metadata.model, "sensors": { key: sensor.value for key, sensor in client.sensors.items() if sensor.device_identifier == device_id }, } for device_id, metadata in client.device_metadata.items() } return result
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homevolt/diagnostics.py", "license": "Apache License 2.0", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/homevolt/test_diagnostics.py
"""Tests for Homevolt diagnostics.""" from __future__ import annotations from syrupy.assertion import SnapshotAssertion from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.typing import ClientSessionGenerator async def test_config_entry_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, init_integration: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test config entry diagnostics.""" diagnostics = await get_diagnostics_for_config_entry( hass, hass_client, init_integration ) assert diagnostics == snapshot
{ "repo_id": "home-assistant/core", "file_path": "tests/components/homevolt/test_diagnostics.py", "license": "Apache License 2.0", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/compit/water_heater.py
"""Water heater platform for Compit integration.""" from dataclasses import dataclass from typing import Any from compit_inext_api.consts import CompitParameter from propcache.api import cached_property from homeassistant.components.water_heater import ( STATE_ECO, STATE_OFF, STATE_ON, STATE_PERFORMANCE, WaterHeaterEntity, WaterHeaterEntityDescription, WaterHeaterEntityFeature, ) from homeassistant.const import ATTR_TEMPERATURE, PRECISION_WHOLE, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MANUFACTURER_NAME from .coordinator import CompitConfigEntry, CompitDataUpdateCoordinator PARALLEL_UPDATES = 0 STATE_SCHEDULE = "schedule" COMPIT_STATE_TO_HA = { STATE_OFF: STATE_OFF, STATE_ON: STATE_PERFORMANCE, STATE_SCHEDULE: STATE_ECO, } HA_STATE_TO_COMPIT = {value: key for key, value in COMPIT_STATE_TO_HA.items()} @dataclass(frozen=True, kw_only=True) class CompitWaterHeaterEntityDescription(WaterHeaterEntityDescription): """Class to describe a Compit water heater device.""" min_temp: float max_temp: float supported_features: WaterHeaterEntityFeature supports_current_temperature: bool = True DEVICE_DEFINITIONS: dict[int, CompitWaterHeaterEntityDescription] = { 34: CompitWaterHeaterEntityDescription( key="r470", min_temp=0.0, max_temp=75.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 91: CompitWaterHeaterEntityDescription( key="R770RS / R771RS", min_temp=30.0, max_temp=80.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 92: CompitWaterHeaterEntityDescription( key="r490", min_temp=30.0, max_temp=80.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 215: CompitWaterHeaterEntityDescription( key="R480", min_temp=30.0, max_temp=80.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 222: CompitWaterHeaterEntityDescription( key="R377B", min_temp=30.0, max_temp=75.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 224: CompitWaterHeaterEntityDescription( key="R 900", min_temp=0.0, max_temp=70.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 36: CompitWaterHeaterEntityDescription( key="BioMax742", min_temp=0.0, max_temp=75.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 75: CompitWaterHeaterEntityDescription( key="BioMax772", min_temp=0.0, max_temp=75.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 201: CompitWaterHeaterEntityDescription( key="BioMax775", min_temp=0.0, max_temp=75.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 210: CompitWaterHeaterEntityDescription( key="EL750", min_temp=30.0, max_temp=80.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE | WaterHeaterEntityFeature.ON_OFF | WaterHeaterEntityFeature.OPERATION_MODE, ), 44: CompitWaterHeaterEntityDescription( key="SolarComp 951", min_temp=0.0, max_temp=85.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE, supports_current_temperature=False, ), 45: CompitWaterHeaterEntityDescription( key="SolarComp971", min_temp=0.0, max_temp=75.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE, supports_current_temperature=False, ), 99: CompitWaterHeaterEntityDescription( key="SolarComp971C", min_temp=0.0, max_temp=75.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE, supports_current_temperature=False, ), 53: CompitWaterHeaterEntityDescription( key="R350.CWU", min_temp=0.0, max_temp=80.0, supported_features=WaterHeaterEntityFeature.TARGET_TEMPERATURE, ), } async def async_setup_entry( hass: HomeAssistant, entry: CompitConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Compit water heater entities from a config entry.""" coordinator = entry.runtime_data async_add_entities( CompitWaterHeater(coordinator, device_id, entity_description) for device_id, device in coordinator.connector.all_devices.items() if (entity_description := DEVICE_DEFINITIONS.get(device.definition.code)) ) class CompitWaterHeater( CoordinatorEntity[CompitDataUpdateCoordinator], WaterHeaterEntity ): """Representation of a Compit Water Heater.""" _attr_target_temperature_step = PRECISION_WHOLE _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_has_entity_name = True _attr_name = None entity_description: CompitWaterHeaterEntityDescription def __init__( self, coordinator: CompitDataUpdateCoordinator, device_id: int, entity_description: CompitWaterHeaterEntityDescription, ) -> None: """Initialize the water heater.""" super().__init__(coordinator) self.device_id = device_id self.entity_description = entity_description self._attr_unique_id = f"{device_id}_{entity_description.key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, str(device_id))}, name=entity_description.key, manufacturer=MANUFACTURER_NAME, model=entity_description.key, ) @property def available(self) -> bool: """Return if entity is available.""" return ( super().available and self.coordinator.connector.get_device(self.device_id) is not None ) @cached_property def min_temp(self) -> float: """Return the minimum temperature.""" return self.entity_description.min_temp @cached_property def max_temp(self) -> float: """Return the maximum temperature.""" return self.entity_description.max_temp @cached_property def supported_features(self) -> WaterHeaterEntityFeature: """Return the supported features.""" return self.entity_description.supported_features @cached_property def operation_list(self) -> list[str] | None: """Return the list of available operation modes.""" if ( self.entity_description.supported_features & WaterHeaterEntityFeature.OPERATION_MODE ): return [STATE_OFF, STATE_PERFORMANCE, STATE_ECO] return None @property def target_temperature(self) -> float | None: """Return the set target temperature.""" value = self.coordinator.connector.get_current_value( self.device_id, CompitParameter.DHW_TARGET_TEMPERATURE ) if isinstance(value, float): return value return None @property def current_temperature(self) -> float | None: """Return the current temperature.""" if self.entity_description.supports_current_temperature is False: return None value = self.coordinator.connector.get_current_value( self.device_id, CompitParameter.DHW_CURRENT_TEMPERATURE ) if isinstance(value, float): return value return None async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return self._attr_target_temperature = temperature await self.coordinator.connector.set_device_parameter( self.device_id, CompitParameter.DHW_TARGET_TEMPERATURE, float(temperature), ) self.async_write_ha_state() async def async_turn_on(self, **kwargs: Any) -> None: """Turn the water heater on.""" await self.coordinator.connector.select_device_option( self.device_id, CompitParameter.DHW_ON_OFF, HA_STATE_TO_COMPIT[STATE_PERFORMANCE], ) self.async_write_ha_state() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the water heater off.""" await self.coordinator.connector.select_device_option( self.device_id, CompitParameter.DHW_ON_OFF, HA_STATE_TO_COMPIT[STATE_OFF], ) self.async_write_ha_state() async def async_set_operation_mode(self, operation_mode: str) -> None: """Set new operation mode.""" await self.coordinator.connector.select_device_option( self.device_id, CompitParameter.DHW_ON_OFF, HA_STATE_TO_COMPIT[operation_mode], ) self.async_write_ha_state() @property def current_operation(self) -> str | None: """Return the current operation mode.""" on_off = self.coordinator.connector.get_current_option( self.device_id, CompitParameter.DHW_ON_OFF ) if on_off is None: return None return COMPIT_STATE_TO_HA.get(on_off)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/compit/water_heater.py", "license": "Apache License 2.0", "lines": 276, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/compit/test_water_heater.py
"""Tests for the Compit water heater platform.""" from typing import Any from unittest.mock import MagicMock from compit_inext_api.consts import CompitParameter import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.water_heater import ATTR_TEMPERATURE from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration, snapshot_compit_entities from tests.common import MockConfigEntry async def test_water_heater_entities_snapshot( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, mock_connector: MagicMock, snapshot: SnapshotAssertion, ) -> None: """Snapshot test for water heater entities creation, unique IDs, and device info.""" await setup_integration(hass, mock_config_entry) snapshot_compit_entities(hass, entity_registry, snapshot, Platform.WATER_HEATER) @pytest.mark.parametrize( "mock_return_value", [ None, "invalid", ], ) async def test_water_heater_unknown_temperature( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock, mock_return_value: Any, ) -> None: """Test that water heater shows unknown temperature when get_current_value returns invalid values.""" mock_connector.get_current_value.side_effect = lambda device_id, parameter_code: ( mock_return_value ) await setup_integration(hass, mock_config_entry) state = hass.states.get("water_heater.r_900") assert state is not None assert state.attributes.get("temperature") is None assert state.attributes.get("current_temperature") is None async def test_water_heater_set_temperature( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock ) -> None: """Test setting water heater temperature.""" await setup_integration(hass, mock_config_entry) await hass.services.async_call( "water_heater", "set_temperature", { ATTR_ENTITY_ID: "water_heater.r_900", ATTR_TEMPERATURE: 60.0, }, blocking=True, ) mock_connector.set_device_parameter.assert_called_once() assert ( mock_connector.get_current_value(1, CompitParameter.DHW_TARGET_TEMPERATURE) == 60.0 ) async def test_water_heater_turn_on( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock ) -> None: """Test turning water heater on.""" await mock_connector.select_device_option(1, CompitParameter.DHW_ON_OFF, "off") await setup_integration(hass, mock_config_entry) await hass.services.async_call( "water_heater", "turn_on", {ATTR_ENTITY_ID: "water_heater.r_900"}, blocking=True, ) assert mock_connector.get_current_option(1, CompitParameter.DHW_ON_OFF) == "on" async def test_water_heater_turn_off( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock ) -> None: """Test turning water heater off.""" await mock_connector.select_device_option(1, CompitParameter.DHW_ON_OFF, "on") await setup_integration(hass, mock_config_entry) await hass.services.async_call( "water_heater", "turn_off", {ATTR_ENTITY_ID: "water_heater.r_900"}, blocking=True, ) assert mock_connector.get_current_option(1, CompitParameter.DHW_ON_OFF) == "off" async def test_water_heater_current_operation( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock ) -> None: """Test water heater current operation state.""" await setup_integration(hass, mock_config_entry) state = hass.states.get("water_heater.r_900") assert state is not None assert state.state == "performance" await hass.services.async_call( "water_heater", "set_operation_mode", {ATTR_ENTITY_ID: "water_heater.r_900", "operation_mode": "eco"}, blocking=True, ) await hass.async_block_till_done() state = hass.states.get("water_heater.r_900") assert state.state == "eco" assert ( mock_connector.get_current_option(1, CompitParameter.DHW_ON_OFF) == "schedule" )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/compit/test_water_heater.py", "license": "Apache License 2.0", "lines": 109, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/mobile_app/analytics.py
"""Analytics platform.""" from homeassistant.components.analytics import AnalyticsInput, AnalyticsModifications from homeassistant.core import HomeAssistant async def async_modify_analytics( hass: HomeAssistant, analytics_input: AnalyticsInput ) -> AnalyticsModifications: """Modify the analytics.""" return AnalyticsModifications(remove=True)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/mobile_app/analytics.py", "license": "Apache License 2.0", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/mobile_app/test_analytics.py
"""Tests for analytics platform.""" from homeassistant.components.analytics import async_devices_payload from homeassistant.components.mobile_app import DOMAIN from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry async def test_analytics( hass: HomeAssistant, device_registry: dr.DeviceRegistry ) -> None: """Test the analytics platform.""" await async_setup_component(hass, "analytics", {}) config_entry = MockConfigEntry(domain=DOMAIN, data={}) config_entry.add_to_hass(hass) device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, identifiers={(DOMAIN, "test")}, manufacturer="Test Manufacturer", ) result = await async_devices_payload(hass) assert DOMAIN not in result["integrations"]
{ "repo_id": "home-assistant/core", "file_path": "tests/components/mobile_app/test_analytics.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/ntfy/services.py
"""Service registration for ntfy integration.""" from datetime import timedelta from typing import Any from aiontfy import BroadcastAction, CopyAction, HttpAction, ViewAction import voluptuous as vol from yarl import URL from homeassistant.components.notify import ( ATTR_MESSAGE, ATTR_TITLE, DOMAIN as NOTIFY_DOMAIN, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from homeassistant.helpers.selector import MediaSelector from .const import DOMAIN SERVICE_PUBLISH = "publish" SERVICE_CLEAR = "clear" SERVICE_DELETE = "delete" ATTR_ATTACH = "attach" ATTR_CALL = "call" ATTR_CLICK = "click" ATTR_DELAY = "delay" ATTR_EMAIL = "email" ATTR_ICON = "icon" ATTR_MARKDOWN = "markdown" ATTR_PRIORITY = "priority" ATTR_TAGS = "tags" ATTR_SEQUENCE_ID = "sequence_id" ATTR_ATTACH_FILE = "attach_file" ATTR_FILENAME = "filename" GRP_ATTACHMENT = "attachment" MSG_ATTACHMENT = "Only one attachment source is allowed: URL or local file" ATTR_ACTIONS = "actions" ATTR_ACTION = "action" ATTR_VIEW = "view" ATTR_BROADCAST = "broadcast" ATTR_HTTP = "http" ATTR_LABEL = "label" ATTR_URL = "url" ATTR_CLEAR = "clear" ATTR_INTENT = "intent" ATTR_EXTRAS = "extras" ATTR_METHOD = "method" ATTR_HEADERS = "headers" ATTR_BODY = "body" ATTR_VALUE = "value" ATTR_COPY = "copy" ACTIONS_MAP = { ATTR_VIEW: ViewAction, ATTR_BROADCAST: BroadcastAction, ATTR_HTTP: HttpAction, ATTR_COPY: CopyAction, } MAX_ACTIONS_ALLOWED = 3 # ntfy only supports up to 3 actions per notification def validate_filename(params: dict[str, Any]) -> dict[str, Any]: """Validate filename.""" if ATTR_FILENAME in params and not ( ATTR_ATTACH_FILE in params or ATTR_ATTACH in params ): raise vol.Invalid("Filename only allowed when attachment is provided") return params ACTION_SCHEMA = vol.Schema( { vol.Required(ATTR_LABEL): cv.string, vol.Optional(ATTR_CLEAR, default=False): cv.boolean, } ) VIEW_SCHEMA = ACTION_SCHEMA.extend( { vol.Required(ATTR_ACTION): vol.Equal("view"), vol.Required(ATTR_URL): vol.All(vol.Url(), vol.Coerce(URL)), } ) BROADCAST_SCHEMA = ACTION_SCHEMA.extend( { vol.Required(ATTR_ACTION): vol.Equal("broadcast"), vol.Optional(ATTR_INTENT): cv.string, vol.Optional(ATTR_EXTRAS): dict[str, str], } ) HTTP_SCHEMA = VIEW_SCHEMA.extend( { vol.Required(ATTR_ACTION): vol.Equal("http"), vol.Optional(ATTR_METHOD): cv.string, vol.Optional(ATTR_HEADERS): dict[str, str], vol.Optional(ATTR_BODY): cv.string, } ) COPY_SCHEMA = ACTION_SCHEMA.extend( { vol.Required(ATTR_ACTION): vol.Equal("copy"), vol.Required(ATTR_VALUE): cv.string, } ) SERVICE_PUBLISH_SCHEMA = vol.All( cv.make_entity_service_schema( { vol.Optional(ATTR_TITLE): cv.string, vol.Optional(ATTR_MESSAGE): cv.string, vol.Optional(ATTR_MARKDOWN): cv.boolean, vol.Optional(ATTR_TAGS): vol.All(cv.ensure_list, [str]), vol.Optional(ATTR_PRIORITY): vol.All(vol.Coerce(int), vol.Range(1, 5)), vol.Optional(ATTR_CLICK): vol.All(vol.Url(), vol.Coerce(URL)), vol.Optional(ATTR_DELAY): vol.All( cv.time_period, vol.Range(min=timedelta(seconds=10), max=timedelta(days=3)), ), vol.Optional(ATTR_EMAIL): vol.Email(), vol.Optional(ATTR_CALL): cv.string, vol.Optional(ATTR_ICON): vol.All(vol.Url(), vol.Coerce(URL)), vol.Optional(ATTR_SEQUENCE_ID): cv.string, vol.Exclusive(ATTR_ATTACH, GRP_ATTACHMENT, MSG_ATTACHMENT): vol.All( vol.Url(), vol.Coerce(URL) ), vol.Exclusive( ATTR_ATTACH_FILE, GRP_ATTACHMENT, MSG_ATTACHMENT ): MediaSelector({"accept": ["*/*"]}), vol.Optional(ATTR_FILENAME): cv.string, vol.Optional(ATTR_ACTIONS): vol.All( cv.ensure_list, vol.Length( max=MAX_ACTIONS_ALLOWED, msg="Too many actions defined. A maximum of 3 is supported", ), [vol.Any(VIEW_SCHEMA, BROADCAST_SCHEMA, HTTP_SCHEMA, COPY_SCHEMA)], ), } ), validate_filename, ) SERVICE_CLEAR_DELETE_SCHEMA = cv.make_entity_service_schema( { vol.Required(ATTR_SEQUENCE_ID): cv.string, } ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services for ntfy integration.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_PUBLISH, entity_domain=NOTIFY_DOMAIN, schema=SERVICE_PUBLISH_SCHEMA, description_placeholders={ "markdown_guide_url": "https://www.markdownguide.org/basic-syntax/", "emoji_reference_url": "https://docs.ntfy.sh/emojis/", }, func="publish", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_CLEAR, entity_domain=NOTIFY_DOMAIN, schema=SERVICE_CLEAR_DELETE_SCHEMA, func="clear", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_DELETE, entity_domain=NOTIFY_DOMAIN, schema=SERVICE_CLEAR_DELETE_SCHEMA, func="delete", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/ntfy/services.py", "license": "Apache License 2.0", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/jvc_projector/switch.py
"""Switch platform for the jvc_projector integration.""" from __future__ import annotations from dataclasses import dataclass from typing import Any, Final from jvcprojector import Command, command as cmd from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import JVCConfigEntry, JvcProjectorDataUpdateCoordinator from .entity import JvcProjectorEntity @dataclass(frozen=True, kw_only=True) class JvcProjectorSwitchDescription(SwitchEntityDescription): """Describes JVC Projector switch entities.""" command: type[Command] SWITCHES: Final[tuple[JvcProjectorSwitchDescription, ...]] = ( JvcProjectorSwitchDescription( key="low_latency_mode", command=cmd.LowLatencyMode, entity_registry_enabled_default=False, ), JvcProjectorSwitchDescription( key="eshift", command=cmd.EShift, entity_registry_enabled_default=False, ), ) async def async_setup_entry( hass: HomeAssistant, entry: JVCConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the JVC Projector switch platform from a config entry.""" coordinator = entry.runtime_data async_add_entities( JvcProjectorSwitchEntity(coordinator, description) for description in SWITCHES if coordinator.supports(description.command) ) class JvcProjectorSwitchEntity(JvcProjectorEntity, SwitchEntity): """JVC Projector class for switch entities.""" def __init__( self, coordinator: JvcProjectorDataUpdateCoordinator, description: JvcProjectorSwitchDescription, ) -> None: """Initialize the entity.""" super().__init__(coordinator, description.command) self.command: type[Command] = description.command self.entity_description = description self._attr_translation_key = description.key self._attr_unique_id = f"{self._attr_unique_id}_{description.key}" @property def is_on(self) -> bool: """Return True if the entity is on.""" return self.coordinator.data.get(self.command.name) == STATE_ON async def async_turn_on(self, **kwargs: Any) -> None: """Turn the entity on.""" await self.coordinator.device.set(self.command, STATE_ON) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the entity off.""" await self.coordinator.device.set(self.command, STATE_OFF)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/jvc_projector/switch.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/jvc_projector/test_switch.py
"""Tests for JVC Projector switch platform.""" from collections.abc import Generator from unittest.mock import AsyncMock, MagicMock, patch from jvcprojector import command as cmd import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.switch import ( DOMAIN as SWITCH_DOMAIN, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform ESHIFT_ENTITY_ID = "switch.jvc_projector_e_shift" LOW_LATENCY_ENTITY_ID = "switch.jvc_projector_low_latency_mode" @pytest.fixture(autouse=True) def platform() -> Generator[AsyncMock]: """Fixture for platform.""" with patch("homeassistant.components.jvc_projector.PLATFORMS", [Platform.SWITCH]): yield @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_entities( hass: HomeAssistant, mock_device: MagicMock, mock_integration: MockConfigEntry, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test entities.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_switch_entities( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_device: MagicMock, mock_integration: MockConfigEntry, ) -> None: """Test switch entities.""" await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: ESHIFT_ENTITY_ID}, blocking=True, ) mock_device.set.assert_any_call(cmd.EShift, "off") await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: ESHIFT_ENTITY_ID}, blocking=True, ) mock_device.set.assert_any_call(cmd.EShift, "on")
{ "repo_id": "home-assistant/core", "file_path": "tests/components/jvc_projector/test_switch.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:script/hassfest/core_files.py
"""Validate .core_files.yaml base_platforms alignment with entity platforms.""" import re from homeassistant.util.yaml import load_yaml_dict from .model import Config, Integration # Non-entity-platform components that belong in base_platforms EXTRA_BASE_PLATFORMS = {"diagnostics"} _COMPONENT_RE = re.compile(r"homeassistant/components/([^/]+)/\*\*") def validate(integrations: dict[str, Integration], config: Config) -> None: """Validate that base_platforms in .core_files.yaml matches entity platforms.""" if config.specific_integrations: return core_files_path = config.root / ".core_files.yaml" core_files = load_yaml_dict(str(core_files_path)) base_platform_entries = { match.group(1) for entry in core_files["base_platforms"] if (match := _COMPONENT_RE.match(entry)) } entity_platforms = { integration.domain for integration in integrations.values() if integration.manifest.get("integration_type") == "entity" and integration.domain != "tag" } expected = entity_platforms | EXTRA_BASE_PLATFORMS for domain in sorted(expected - base_platform_entries): config.add_error( "core_files", f"Entity platform '{domain}' is missing from " "base_platforms in .core_files.yaml", ) for domain in sorted(base_platform_entries - expected): config.add_error( "core_files", f"'{domain}' in base_platforms in .core_files.yaml " "is not an entity platform or in EXTRA_BASE_PLATFORMS", )
{ "repo_id": "home-assistant/core", "file_path": "script/hassfest/core_files.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/hassfest/test_core_files.py
"""Tests for hassfest core_files validation.""" from pathlib import Path from unittest.mock import patch from script.hassfest.core_files import EXTRA_BASE_PLATFORMS, validate from script.hassfest.model import Config, Integration def _create_integration( config: Config, domain: str, integration_type: str = "hub" ) -> Integration: """Create a minimal Integration with the given type.""" integration = Integration(config.core_integrations_path / domain, _config=config) integration._manifest = { "domain": domain, "name": domain, "integration_type": integration_type, } return integration def _create_core_files_yaml(base_platforms: list[str]) -> dict: """Build a minimal .core_files.yaml dict.""" return { "base_platforms": [f"homeassistant/components/{p}/**" for p in base_platforms], } def test_skip_specific_integrations() -> None: """Test that validation is skipped for specific integrations.""" config = Config( root=Path(".").absolute(), specific_integrations=[Path("some/path")], action="validate", requirements=False, ) # Should not raise or add errors — it just returns early validate({}, config) assert not config.errors def test_valid_alignment(config: Config) -> None: """Test no errors when base_platforms matches entity platforms.""" integrations = { "sensor": _create_integration(config, "sensor", "entity"), "light": _create_integration(config, "light", "entity"), "tag": _create_integration(config, "tag", "entity"), # excluded "mqtt": _create_integration(config, "mqtt", "hub"), } core_files = _create_core_files_yaml(["sensor", "light", *EXTRA_BASE_PLATFORMS]) with patch("script.hassfest.core_files.load_yaml_dict", return_value=core_files): validate(integrations, config) assert not config.errors def test_missing_entity_platform(config: Config) -> None: """Test error when an entity platform is missing from base_platforms.""" integrations = { "sensor": _create_integration(config, "sensor", "entity"), "light": _create_integration(config, "light", "entity"), } # light is missing from base_platforms core_files = _create_core_files_yaml(["sensor", *EXTRA_BASE_PLATFORMS]) with patch("script.hassfest.core_files.load_yaml_dict", return_value=core_files): validate(integrations, config) assert len(config.errors) == 1 assert ( config.errors[0].error == "Entity platform 'light' is missing from base_platforms in .core_files.yaml" ) def test_unexpected_entry(config: Config) -> None: """Test error when base_platforms contains a non-entity-platform entry.""" integrations = { "sensor": _create_integration(config, "sensor", "entity"), } core_files = _create_core_files_yaml( ["sensor", "unknown_thing", *EXTRA_BASE_PLATFORMS] ) with patch("script.hassfest.core_files.load_yaml_dict", return_value=core_files): validate(integrations, config) assert len(config.errors) == 1 assert ( config.errors[0].error == "'unknown_thing' in base_platforms in .core_files.yaml is not an entity platform or in EXTRA_BASE_PLATFORMS" )
{ "repo_id": "home-assistant/core", "file_path": "tests/hassfest/test_core_files.py", "license": "Apache License 2.0", "lines": 74, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/homevolt/config_flow.py
"""Config flow for the Homevolt integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from homevolt import Homevolt, HomevoltAuthenticationError, HomevoltConnectionError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST, CONF_PASSWORD from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from .const import DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): str, } ) STEP_CREDENTIALS_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_PASSWORD): str, } ) class HomevoltConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Homevolt.""" VERSION = 1 MINOR_VERSION = 1 def __init__(self) -> None: """Initialize the config flow.""" self._host: str | None = None self._need_password: bool = False async def check_status(self, client: Homevolt) -> dict[str, str]: """Check connection status and return errors if any.""" errors: dict[str, str] = {} try: await client.update_info() except HomevoltAuthenticationError: errors["base"] = "invalid_auth" except HomevoltConnectionError: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Error occurred while connecting to the Homevolt battery") errors["base"] = "unknown" return errors async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: host = user_input[CONF_HOST] password = None websession = async_get_clientsession(self.hass) client = Homevolt(host, password, websession=websession) errors = await self.check_status(client) if errors.get("base") == "invalid_auth": self._host = host return await self.async_step_credentials() if not errors: device_id = client.unique_id await self.async_set_unique_id(device_id) self._abort_if_unique_id_configured() return self.async_create_entry( title="Homevolt", data={ CONF_HOST: host, CONF_PASSWORD: None, }, ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle reauth on authentication failure.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reauth confirmation with new credentials.""" reauth_entry = self._get_reauth_entry() host = reauth_entry.data[CONF_HOST] errors: dict[str, str] = {} if user_input is not None: password = user_input[CONF_PASSWORD] websession = async_get_clientsession(self.hass) client = Homevolt(host, password, websession=websession) errors = await self.check_status(client) if not errors: device_id = client.unique_id await self.async_set_unique_id(device_id) self._abort_if_unique_id_mismatch(reason="wrong_account") return self.async_update_reload_and_abort( reauth_entry, unique_id=device_id, data_updates={CONF_HOST: host, CONF_PASSWORD: password}, ) return self.async_show_form( step_id="reauth_confirm", data_schema=STEP_CREDENTIALS_DATA_SCHEMA, errors=errors, description_placeholders={"host": host}, ) async def async_step_credentials( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the credentials step.""" errors: dict[str, str] = {} assert self._host is not None if user_input is not None: password = user_input[CONF_PASSWORD] websession = async_get_clientsession(self.hass) client = Homevolt(self._host, password, websession=websession) errors = await self.check_status(client) if not errors: device_id = client.unique_id await self.async_set_unique_id(device_id) self._abort_if_unique_id_configured() return self.async_create_entry( title="Homevolt", data={ CONF_HOST: self._host, CONF_PASSWORD: password, }, ) return self.async_show_form( step_id="credentials", data_schema=STEP_CREDENTIALS_DATA_SCHEMA, errors=errors, description_placeholders={"host": self._host}, ) async def async_step_zeroconf( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle zeroconf discovery.""" self._host = discovery_info.host self._async_abort_entries_match({CONF_HOST: self._host}) websession = async_get_clientsession(self.hass) client = Homevolt(self._host, None, websession=websession) errors = await self.check_status(client) if errors.get("base") == "invalid_auth": self._need_password = True elif errors: return self.async_abort(reason=errors["base"]) else: await self.async_set_unique_id(client.unique_id) self._abort_if_unique_id_configured( updates={CONF_HOST: self._host}, ) return await self.async_step_zeroconf_confirm() async def async_step_zeroconf_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm zeroconf discovery.""" assert self._host is not None errors: dict[str, str] = {} if user_input is None: if self._need_password: return self.async_show_form( step_id="zeroconf_confirm", data_schema=STEP_CREDENTIALS_DATA_SCHEMA, errors=errors, description_placeholders={"host": self._host}, ) self._set_confirm_only() return self.async_show_form( step_id="zeroconf_confirm", description_placeholders={"host": self._host}, ) password: str | None = None if self._need_password: password = user_input[CONF_PASSWORD] websession = async_get_clientsession(self.hass) client = Homevolt(self._host, password, websession=websession) errors = await self.check_status(client) if errors: return self.async_show_form( step_id="zeroconf_confirm", data_schema=STEP_CREDENTIALS_DATA_SCHEMA, errors=errors, description_placeholders={"host": self._host}, ) await self.async_set_unique_id(client.unique_id) self._abort_if_unique_id_configured(updates={CONF_HOST: self._host}) return self.async_create_entry( title="Homevolt", data={CONF_HOST: self._host, CONF_PASSWORD: password}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homevolt/config_flow.py", "license": "Apache License 2.0", "lines": 189, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/homevolt/const.py
"""Constants for the Homevolt integration.""" from __future__ import annotations from datetime import timedelta DOMAIN = "homevolt" MANUFACTURER = "Homevolt" SCAN_INTERVAL = timedelta(seconds=15)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homevolt/const.py", "license": "Apache License 2.0", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/homevolt/coordinator.py
"""Data update coordinator for Homevolt integration.""" from __future__ import annotations import logging from homevolt import ( Homevolt, HomevoltAuthenticationError, HomevoltConnectionError, HomevoltError, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN, SCAN_INTERVAL type HomevoltConfigEntry = ConfigEntry[HomevoltDataUpdateCoordinator] _LOGGER = logging.getLogger(__name__) class HomevoltDataUpdateCoordinator(DataUpdateCoordinator[Homevolt]): """Class to manage fetching Homevolt data.""" config_entry: HomevoltConfigEntry def __init__( self, hass: HomeAssistant, entry: HomevoltConfigEntry, client: Homevolt, ) -> None: """Initialize the Homevolt coordinator.""" self.client = client super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, config_entry=entry, ) async def _async_update_data(self) -> Homevolt: """Fetch data from the Homevolt API.""" try: await self.client.update_info() except HomevoltAuthenticationError as err: raise ConfigEntryAuthFailed from err except (HomevoltConnectionError, HomevoltError) as err: raise UpdateFailed(f"Error communicating with device: {err}") from err return self.client
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homevolt/coordinator.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/homevolt/sensor.py
"""Support for Homevolt sensors.""" from __future__ import annotations import logging from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import ( PERCENTAGE, SIGNAL_STRENGTH_DECIBELS, EntityCategory, UnitOfElectricCurrent, UnitOfElectricPotential, UnitOfEnergy, UnitOfFrequency, UnitOfPower, UnitOfTemperature, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from .coordinator import HomevoltConfigEntry, HomevoltDataUpdateCoordinator from .entity import HomevoltEntity PARALLEL_UPDATES = 0 # Coordinator-based updates _LOGGER = logging.getLogger(__name__) SENSORS: tuple[SensorEntityDescription, ...] = ( SensorEntityDescription( key="available_charging_energy", translation_key="available_charging_energy", device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL, native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, ), SensorEntityDescription( key="available_charging_power", translation_key="available_charging_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, ), SensorEntityDescription( key="available_discharge_energy", translation_key="available_discharge_energy", device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL, native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, ), SensorEntityDescription( key="available_discharge_power", translation_key="available_discharge_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, ), SensorEntityDescription( key="rssi", translation_key="rssi", device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), SensorEntityDescription( key="average_rssi", translation_key="average_rssi", device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), SensorEntityDescription( key="charge_cycles", state_class=SensorStateClass.TOTAL_INCREASING, native_unit_of_measurement="cycles", entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="energy_exported", translation_key="energy_exported", device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, ), SensorEntityDescription( key="energy_imported", translation_key="energy_imported", device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, ), SensorEntityDescription( key="frequency", device_class=SensorDeviceClass.FREQUENCY, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfFrequency.HERTZ, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="l1_current", translation_key="l1_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, ), SensorEntityDescription( key="l1_l2_voltage", translation_key="l1_l2_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, ), SensorEntityDescription( key="l1_power", translation_key="l1_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, entity_registry_enabled_default=False, ), SensorEntityDescription( key="l1_voltage", translation_key="l1_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, entity_registry_enabled_default=False, ), SensorEntityDescription( key="l2_current", translation_key="l2_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, ), SensorEntityDescription( key="l2_l3_voltage", translation_key="l2_l3_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, ), SensorEntityDescription( key="l2_power", translation_key="l2_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, entity_registry_enabled_default=False, ), SensorEntityDescription( key="l2_voltage", translation_key="l2_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, entity_registry_enabled_default=False, ), SensorEntityDescription( key="l3_current", translation_key="l3_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, ), SensorEntityDescription( key="l3_l1_voltage", translation_key="l3_l1_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, ), SensorEntityDescription( key="l3_power", translation_key="l3_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, entity_registry_enabled_default=False, ), SensorEntityDescription( key="l3_voltage", translation_key="l3_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, entity_registry_enabled_default=False, ), SensorEntityDescription( key="power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, entity_registry_enabled_default=False, ), SensorEntityDescription( key="schedule_id", translation_key="schedule_id", entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="schedule_max_discharge", translation_key="schedule_max_discharge", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="schedule_max_power", translation_key="schedule_max_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="schedule_power_setpoint", translation_key="schedule_power_setpoint", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="schedule_type", translation_key="schedule_type", device_class=SensorDeviceClass.ENUM, options=[ "idle", "inverter_charge", "inverter_discharge", "grid_charge", "grid_discharge", "grid_charge_discharge", "frequency_reserve", "solar_charge", "solar_charge_discharge", "full_solar_export", ], entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="state_of_charge", device_class=SensorDeviceClass.BATTERY, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, ), SensorEntityDescription( key="system_temperature", translation_key="system_temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="tmax", translation_key="tmax", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="tmin", translation_key="tmin", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, entity_category=EntityCategory.DIAGNOSTIC, ), ) async def async_setup_entry( hass: HomeAssistant, entry: HomevoltConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Homevolt sensor.""" coordinator = entry.runtime_data entities: list[HomevoltSensor] = [] sensors_by_key = {sensor.key: sensor for sensor in SENSORS} for sensor_key, sensor in coordinator.data.sensors.items(): if (description := sensors_by_key.get(sensor.type)) is None: _LOGGER.warning("Unsupported sensor '%s' found during setup", sensor) continue entities.append( HomevoltSensor( description, coordinator, sensor_key, ) ) async_add_entities(entities) class HomevoltSensor(HomevoltEntity, SensorEntity): """Representation of a Homevolt sensor.""" entity_description: SensorEntityDescription def __init__( self, description: SensorEntityDescription, coordinator: HomevoltDataUpdateCoordinator, sensor_key: str, ) -> None: """Initialize the sensor.""" sensor_data = coordinator.data.sensors[sensor_key] super().__init__(coordinator, sensor_data.device_identifier) self.entity_description = description self._attr_unique_id = f"{coordinator.data.unique_id}_{sensor_key}" self._sensor_key = sensor_key @property def available(self) -> bool: """Return if entity is available.""" return super().available and self._sensor_key in self.coordinator.data.sensors @property def native_value(self) -> StateType: """Return the native value of the sensor.""" return self.coordinator.data.sensors[self._sensor_key].value
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homevolt/sensor.py", "license": "Apache License 2.0", "lines": 320, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/homevolt/test_config_flow.py
"""Tests for the Homevolt config flow.""" from __future__ import annotations from ipaddress import IPv4Address from unittest.mock import AsyncMock, MagicMock from homevolt import HomevoltAuthenticationError, HomevoltConnectionError import pytest from homeassistant.components.homevolt.const import DOMAIN from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF from homeassistant.const import CONF_HOST, CONF_PASSWORD from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from tests.common import MockConfigEntry DISCOVERY_INFO = ZeroconfServiceInfo( ip_address=IPv4Address("192.168.1.123"), ip_addresses=[IPv4Address("192.168.1.123")], port=80, hostname="homevolt.local.", type="_http._tcp.local.", name="homevolt._http._tcp.local.", properties={}, ) async def test_full_flow_success( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock ) -> None: """Test a complete successful user flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} user_input = { CONF_HOST: "192.168.1.100", } result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Homevolt" assert result["data"] == {CONF_HOST: "192.168.1.100", CONF_PASSWORD: None} assert result["result"].unique_id == "40580137858664" assert len(mock_setup_entry.mock_calls) == 1 async def test_flow_auth_error_then_password_success( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock ) -> None: """Test flow when authentication is required.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} user_input = { CONF_HOST: "192.168.1.100", } mock_homevolt_client.update_info.side_effect = HomevoltAuthenticationError result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "credentials" assert result["errors"] == {} # Now provide password - should succeed mock_homevolt_client.update_info.side_effect = None password_input = { CONF_PASSWORD: "test-password", } result = await hass.config_entries.flow.async_configure( result["flow_id"], password_input ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Homevolt" assert result["data"] == { CONF_HOST: "192.168.1.100", CONF_PASSWORD: "test-password", } assert result["result"].unique_id == "40580137858664" assert len(mock_setup_entry.mock_calls) == 1 @pytest.mark.parametrize( ("exception", "expected_error"), [ (HomevoltConnectionError, "cannot_connect"), (Exception, "unknown"), ], ) async def test_step_user_errors( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock, exception: Exception, expected_error: str, ) -> None: """Test error cases for the user step with recovery.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} user_input = { CONF_HOST: "192.168.1.100", } mock_homevolt_client.update_info.side_effect = exception result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": expected_error} mock_homevolt_client.update_info.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Homevolt" assert result["data"] == {CONF_HOST: "192.168.1.100", CONF_PASSWORD: None} assert result["result"].unique_id == "40580137858664" assert len(mock_setup_entry.mock_calls) == 1 async def test_duplicate_entry( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test that a duplicate device_id aborts the flow.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} user_input = { CONF_HOST: "192.168.1.200", } result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_credentials_step_invalid_password( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock ) -> None: """Test invalid password in credentials step shows error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) user_input = { CONF_HOST: "192.168.1.100", } mock_homevolt_client.update_info.side_effect = HomevoltAuthenticationError result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "credentials" # Provide wrong password - should show error password_input = { CONF_PASSWORD: "wrong-password", } result = await hass.config_entries.flow.async_configure( result["flow_id"], password_input ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "credentials" assert result["errors"] == {"base": "invalid_auth"} mock_homevolt_client.update_info.side_effect = None password_input = { CONF_PASSWORD: "correct-password", } result = await hass.config_entries.flow.async_configure( result["flow_id"], password_input ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Homevolt" assert result["data"] == { CONF_HOST: "192.168.1.100", CONF_PASSWORD: "correct-password", } assert result["result"].unique_id == "40580137858664" assert len(mock_setup_entry.mock_calls) == 1 async def test_reauth_success( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test successful reauthentication flow.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" assert result["description_placeholders"] == { "host": "127.0.0.1", "name": "Homevolt", } result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PASSWORD: "new-password"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.unique_id == "40580137858664" assert mock_config_entry.data == { CONF_HOST: "127.0.0.1", CONF_PASSWORD: "new-password", } @pytest.mark.parametrize( ("exception", "expected_error"), [ (HomevoltAuthenticationError, "invalid_auth"), (HomevoltConnectionError, "cannot_connect"), (Exception, "unknown"), ], ) async def test_reauth_flow_errors( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock, mock_config_entry: MockConfigEntry, exception: Exception, expected_error: str, ) -> None: """Test reauthentication flow with errors and recovery.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" mock_homevolt_client.update_info.side_effect = exception result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PASSWORD: "wrong-password"}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" assert result["errors"] == {"base": expected_error} mock_homevolt_client.update_info.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PASSWORD: "correct-password"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data == { CONF_HOST: "127.0.0.1", CONF_PASSWORD: "correct-password", } async def test_zeroconf_confirm_flow_success( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock ) -> None: """Test zeroconf flow shows confirm step before creating entry.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "zeroconf_confirm" assert result["description_placeholders"] == {"host": "192.168.1.123"} result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Homevolt" assert result["data"] == {CONF_HOST: "192.168.1.123", CONF_PASSWORD: None} assert result["result"].unique_id == "40580137858664" assert len(mock_setup_entry.mock_calls) == 1 async def test_zeroconf_duplicate_aborts( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test zeroconf flow aborts when unique id is already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" assert mock_config_entry.data[CONF_HOST] == "192.168.1.123" async def test_zeroconf_confirm_with_password_success( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock, monkeypatch: pytest.MonkeyPatch, ) -> None: """Test zeroconf confirm collects password and creates entry when auth is required.""" mock_homevolt_client.update_info.side_effect = HomevoltAuthenticationError result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "zeroconf_confirm" assert result["description_placeholders"] == {"host": "192.168.1.123"} mock_homevolt_client.update_info.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PASSWORD: "test-password"}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Homevolt" assert result["data"] == { CONF_HOST: "192.168.1.123", CONF_PASSWORD: "test-password", } assert result["result"].unique_id == "40580137858664" assert len(mock_setup_entry.mock_calls) == 1 async def test_zeroconf_confirm_with_password_invalid_then_success( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock, monkeypatch: pytest.MonkeyPatch, ) -> None: """Test zeroconf confirm shows error on invalid password, then succeeds.""" mock_homevolt_client.update_info.side_effect = HomevoltAuthenticationError result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "zeroconf_confirm" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PASSWORD: "wrong-password"}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "zeroconf_confirm" assert result["errors"] == {"base": "invalid_auth"} mock_homevolt_client.update_info.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PASSWORD: "correct-password"}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Homevolt" assert result["data"] == { CONF_HOST: "192.168.1.123", CONF_PASSWORD: "correct-password", } assert result["result"].unique_id == "40580137858664" assert len(mock_setup_entry.mock_calls) == 1 @pytest.mark.parametrize( ("exception", "expected_reason"), [ (HomevoltConnectionError, "cannot_connect"), (Exception("Unexpected error"), "unknown"), ], ids=["connection_error", "unknown_error"], ) async def test_zeroconf_error_aborts( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_homevolt_client: MagicMock, exception: Exception, expected_reason: str, ) -> None: """Test zeroconf flow aborts on error during discovery.""" mock_homevolt_client.update_info.side_effect = exception result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == expected_reason
{ "repo_id": "home-assistant/core", "file_path": "tests/components/homevolt/test_config_flow.py", "license": "Apache License 2.0", "lines": 372, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/homevolt/test_init.py
"""Test the Homevolt init module.""" from __future__ import annotations from unittest.mock import MagicMock from homevolt import HomevoltAuthenticationError, HomevoltConnectionError import pytest from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry async def test_load_unload_entry( hass: HomeAssistant, mock_homevolt_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test load and unload entry.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) assert mock_config_entry.state is ConfigEntryState.LOADED await hass.config_entries.async_unload(mock_config_entry.entry_id) assert mock_config_entry.state is ConfigEntryState.NOT_LOADED mock_homevolt_client.close_connection.assert_called_once() @pytest.mark.parametrize( ("side_effect", "expected_state"), [ ( HomevoltConnectionError("Connection failed"), ConfigEntryState.SETUP_RETRY, ), ( HomevoltAuthenticationError("Authentication failed"), ConfigEntryState.SETUP_ERROR, ), ], ) async def test_config_entry_setup_failure( hass: HomeAssistant, mock_homevolt_client: MagicMock, mock_config_entry: MockConfigEntry, side_effect: Exception, expected_state: ConfigEntryState, ) -> None: """Test the Homevolt configuration entry setup failures.""" mock_homevolt_client.update_info.side_effect = side_effect mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) assert mock_config_entry.state is expected_state
{ "repo_id": "home-assistant/core", "file_path": "tests/components/homevolt/test_init.py", "license": "Apache License 2.0", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/homevolt/test_sensor.py
"""Tests for the Homevolt sensor platform.""" from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.homevolt.const import DOMAIN, SCAN_INTERVAL from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform pytestmark = pytest.mark.usefixtures( "entity_registry_enabled_by_default", "init_integration" ) async def test_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, device_registry: dr.DeviceRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test the sensor entities.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) device_entry = device_registry.async_get_device( identifiers={(DOMAIN, "40580137858664_ems_40580137858664")} ) assert device_entry entity_entries = er.async_entries_for_config_entry( entity_registry, mock_config_entry.entry_id ) for entity_entry in entity_entries: assert entity_entry.device_id == device_entry.id async def test_sensor_exposes_values_from_coordinator( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, mock_homevolt_client, freezer: FrozenDateTimeFactory, ) -> None: """Ensure sensor entities are created and expose values from the coordinator.""" unique_id = "40580137858664_l1_voltage" entity_id = entity_registry.async_get_entity_id("sensor", DOMAIN, unique_id) assert entity_id is not None state = hass.states.get(entity_id) assert state is not None assert float(state.state) == 234.0 mock_homevolt_client.sensors["l1_voltage"].value = 240.1 freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state is not None assert float(state.state) == 240.1
{ "repo_id": "home-assistant/core", "file_path": "tests/components/homevolt/test_sensor.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/solarlog/models.py
"""The SolarLog integration models.""" from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING if TYPE_CHECKING: from solarlog_cli.solarlog_connector import SolarLogConnector from .coordinator import ( SolarLogBasicDataCoordinator, SolarLogDeviceDataCoordinator, SolarLogLongtimeDataCoordinator, ) @dataclass class SolarlogIntegrationData: """Data for the solarlog integration.""" api: SolarLogConnector basic_data_coordinator: SolarLogBasicDataCoordinator device_data_coordinator: SolarLogDeviceDataCoordinator | None = None longtime_data_coordinator: SolarLogLongtimeDataCoordinator | None = None
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/solarlog/models.py", "license": "Apache License 2.0", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/openai_conversation/tts.py
"""Text to speech support for OpenAI.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import TYPE_CHECKING, Any from openai import OpenAIError from propcache.api import cached_property from homeassistant.components.tts import ( ATTR_PREFERRED_FORMAT, ATTR_VOICE, TextToSpeechEntity, TtsAudioType, Voice, ) from homeassistant.config_entries import ConfigSubentry from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import CONF_CHAT_MODEL, CONF_PROMPT, CONF_TTS_SPEED, RECOMMENDED_TTS_SPEED from .entity import OpenAIBaseLLMEntity if TYPE_CHECKING: from . import OpenAIConfigEntry _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: OpenAIConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up TTS entities.""" for subentry in config_entry.subentries.values(): if subentry.subentry_type != "tts": continue async_add_entities( [OpenAITTSEntity(config_entry, subentry)], config_subentry_id=subentry.subentry_id, ) class OpenAITTSEntity(TextToSpeechEntity, OpenAIBaseLLMEntity): """OpenAI TTS entity.""" _attr_supported_options = [ATTR_VOICE, ATTR_PREFERRED_FORMAT] # https://platform.openai.com/docs/guides/text-to-speech#supported-languages # The model may also generate the audio in different languages but with lower quality _attr_supported_languages = [ "af-ZA", # Afrikaans "ar-SA", # Arabic "hy-AM", # Armenian "az-AZ", # Azerbaijani "be-BY", # Belarusian "bs-BA", # Bosnian "bg-BG", # Bulgarian "ca-ES", # Catalan "zh-CN", # Chinese (Mandarin) "hr-HR", # Croatian "cs-CZ", # Czech "da-DK", # Danish "nl-NL", # Dutch "en-US", # English "et-EE", # Estonian "fi-FI", # Finnish "fr-FR", # French "gl-ES", # Galician "de-DE", # German "el-GR", # Greek "he-IL", # Hebrew "hi-IN", # Hindi "hu-HU", # Hungarian "is-IS", # Icelandic "id-ID", # Indonesian "it-IT", # Italian "ja-JP", # Japanese "kn-IN", # Kannada "kk-KZ", # Kazakh "ko-KR", # Korean "lv-LV", # Latvian "lt-LT", # Lithuanian "mk-MK", # Macedonian "ms-MY", # Malay "mr-IN", # Marathi "mi-NZ", # Maori "ne-NP", # Nepali "no-NO", # Norwegian "fa-IR", # Persian "pl-PL", # Polish "pt-PT", # Portuguese "ro-RO", # Romanian "ru-RU", # Russian "sr-RS", # Serbian "sk-SK", # Slovak "sl-SI", # Slovenian "es-ES", # Spanish "sw-KE", # Swahili "sv-SE", # Swedish "fil-PH", # Tagalog (Filipino) "ta-IN", # Tamil "th-TH", # Thai "tr-TR", # Turkish "uk-UA", # Ukrainian "ur-PK", # Urdu "vi-VN", # Vietnamese "cy-GB", # Welsh ] # Unused, but required by base class. # The models detect the input language automatically. _attr_default_language = "en-US" # https://platform.openai.com/docs/guides/text-to-speech#voice-options _supported_voices = [ Voice(voice.lower(), voice) for voice in ( "Marin", "Cedar", "Alloy", "Ash", "Ballad", "Coral", "Echo", "Fable", "Nova", "Onyx", "Sage", "Shimmer", "Verse", ) ] _supported_formats = ["mp3", "opus", "aac", "flac", "wav", "pcm"] _attr_has_entity_name = False def __init__(self, entry: OpenAIConfigEntry, subentry: ConfigSubentry) -> None: """Initialize the entity.""" super().__init__(entry, subentry) self._attr_name = subentry.title @callback def async_get_supported_voices(self, language: str) -> list[Voice]: """Return a list of supported voices for a language.""" return self._supported_voices @cached_property def default_options(self) -> Mapping[str, Any]: """Return a mapping with the default options.""" return { ATTR_VOICE: self._supported_voices[0].voice_id, ATTR_PREFERRED_FORMAT: "mp3", } async def async_get_tts_audio( self, message: str, language: str, options: dict[str, Any] ) -> TtsAudioType: """Load tts audio file from the engine.""" options = {**self.subentry.data, **options} client = self.entry.runtime_data response_format = options[ATTR_PREFERRED_FORMAT] if response_format not in self._supported_formats: # common aliases if response_format == "ogg": response_format = "opus" elif response_format == "raw": response_format = "pcm" else: response_format = self.default_options[ATTR_PREFERRED_FORMAT] try: async with client.audio.speech.with_streaming_response.create( model=options[CONF_CHAT_MODEL], voice=options[ATTR_VOICE], input=message, instructions=str(options.get(CONF_PROMPT)), speed=options.get(CONF_TTS_SPEED, RECOMMENDED_TTS_SPEED), response_format=response_format, ) as response: response_data = bytearray() async for chunk in response.iter_bytes(): response_data.extend(chunk) except OpenAIError as exc: _LOGGER.exception("Error during TTS") raise HomeAssistantError(exc) from exc return response_format, bytes(response_data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openai_conversation/tts.py", "license": "Apache License 2.0", "lines": 170, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/openai_conversation/test_tts.py
"""Test TTS platform of OpenAI Conversation integration.""" from http import HTTPStatus from pathlib import Path from typing import Any from unittest.mock import MagicMock import httpx from openai import RateLimitError import pytest from homeassistant.components import tts from homeassistant.components.media_player import ( ATTR_MEDIA_CONTENT_ID, DOMAIN as MP_DOMAIN, SERVICE_PLAY_MEDIA, ) from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.core_config import async_process_ha_core_config from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, async_mock_service from tests.components.tts.common import retrieve_media from tests.typing import ClientSessionGenerator @pytest.fixture(autouse=True) def tts_mutagen_mock_fixture_autouse(tts_mutagen_mock: MagicMock) -> None: """Mock writing tags.""" @pytest.fixture(autouse=True) def mock_tts_cache_dir_autouse(mock_tts_cache_dir: Path) -> None: """Mock the TTS cache dir with empty dir.""" @pytest.fixture async def calls(hass: HomeAssistant) -> list[ServiceCall]: """Mock media player calls.""" return async_mock_service(hass, MP_DOMAIN, SERVICE_PLAY_MEDIA) @pytest.fixture(autouse=True) async def setup_internal_url(hass: HomeAssistant) -> None: """Set up internal url.""" await async_process_ha_core_config( hass, {"internal_url": "http://example.local:8123"} ) @pytest.mark.parametrize( "service_data", [ { ATTR_ENTITY_ID: "tts.openai_tts", tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something", tts.ATTR_MESSAGE: "There is a person at the front door.", tts.ATTR_OPTIONS: {}, }, { ATTR_ENTITY_ID: "tts.openai_tts", tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something", tts.ATTR_MESSAGE: "There is a person at the front door.", tts.ATTR_OPTIONS: {tts.ATTR_VOICE: "voice2"}, }, ], ) @pytest.mark.usefixtures("mock_init_component") async def test_tts( hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_config_entry: MockConfigEntry, mock_create_speech: MagicMock, entity_registry: er.EntityRegistry, calls: list[ServiceCall], service_data: dict[str, Any], ) -> None: """Test text to speech generation.""" entity_id = "tts.openai_tts" # Ensure entity is linked to the subentry entity_entry = entity_registry.async_get(entity_id) tts_entry = next( iter( entry for entry in mock_config_entry.subentries.values() if entry.subentry_type == "tts" ) ) assert entity_entry is not None assert entity_entry.config_entry_id == mock_config_entry.entry_id assert entity_entry.config_subentry_id == tts_entry.subentry_id # Mock the OpenAI response stream mock_create_speech.return_value = [b"mock aud", b"io data"] await hass.services.async_call( tts.DOMAIN, "speak", service_data, blocking=True, ) assert len(calls) == 1 assert ( await retrieve_media(hass, hass_client, calls[0].data[ATTR_MEDIA_CONTENT_ID]) == HTTPStatus.OK ) voice_id = service_data[tts.ATTR_OPTIONS].get(tts.ATTR_VOICE, "marin") mock_create_speech.assert_called_once_with( model="gpt-4o-mini-tts", voice=voice_id, input="There is a person at the front door.", instructions="", speed=1.0, response_format="mp3", ) @pytest.mark.usefixtures("mock_init_component") async def test_tts_error( hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_config_entry: MockConfigEntry, mock_create_speech: MagicMock, entity_registry: er.EntityRegistry, calls: list[ServiceCall], ) -> None: """Test exception handling during text to speech generation.""" # Mock the OpenAI response stream mock_create_speech.side_effect = RateLimitError( response=httpx.Response(status_code=429, request=""), body=None, message=None, ) service_data = { ATTR_ENTITY_ID: "tts.openai_tts", tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something", tts.ATTR_MESSAGE: "There is a person at the front door.", tts.ATTR_OPTIONS: {tts.ATTR_VOICE: "voice1"}, } await hass.services.async_call( tts.DOMAIN, "speak", service_data, blocking=True, ) assert len(calls) == 1 assert ( await retrieve_media(hass, hass_client, calls[0].data[ATTR_MEDIA_CONTENT_ID]) == HTTPStatus.INTERNAL_SERVER_ERROR ) mock_create_speech.assert_called_once_with( model="gpt-4o-mini-tts", voice="voice1", input="There is a person at the front door.", instructions="", speed=1.0, response_format="mp3", )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/openai_conversation/test_tts.py", "license": "Apache License 2.0", "lines": 141, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/nrgkick/switch.py
"""Switch platform for NRGkick.""" from __future__ import annotations from typing import Any from nrgkick_api.const import CONTROL_KEY_CHARGE_PAUSE from homeassistant.components.switch import SwitchEntity from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import NRGkickConfigEntry, NRGkickData, NRGkickDataUpdateCoordinator from .entity import NRGkickEntity PARALLEL_UPDATES = 0 CHARGING_ENABLED_KEY = "charging_enabled" def _is_charging_enabled(data: NRGkickData) -> bool: """Return True if charging is enabled (not paused).""" return bool(data.control.get(CONTROL_KEY_CHARGE_PAUSE) == 0) async def async_setup_entry( _hass: HomeAssistant, entry: NRGkickConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up NRGkick switches based on a config entry.""" coordinator = entry.runtime_data async_add_entities([NRGkickChargingEnabledSwitch(coordinator)]) class NRGkickChargingEnabledSwitch(NRGkickEntity, SwitchEntity): """Representation of the NRGkick charging enabled switch.""" _attr_translation_key = CHARGING_ENABLED_KEY def __init__(self, coordinator: NRGkickDataUpdateCoordinator) -> None: """Initialize the switch.""" super().__init__(coordinator, CHARGING_ENABLED_KEY) @property def is_on(self) -> bool: """Return the state of the switch.""" data = self.coordinator.data assert data is not None return _is_charging_enabled(data) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the entity on (enable charging).""" await self._async_call_api(self.coordinator.api.set_charge_pause(False)) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the entity off (pause charging).""" await self._async_call_api(self.coordinator.api.set_charge_pause(True))
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nrgkick/switch.py", "license": "Apache License 2.0", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/nrgkick/test_switch.py
"""Tests for the NRGkick switch platform.""" from __future__ import annotations from unittest.mock import AsyncMock, call from nrgkick_api import NRGkickCommandRejectedError from nrgkick_api.const import CONTROL_KEY_CHARGE_PAUSE import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, Platform, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, snapshot_platform pytestmark = pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_switch_entities( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_nrgkick_api: AsyncMock, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test switch entities.""" await setup_integration(hass, mock_config_entry, platforms=[Platform.SWITCH]) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_charge_switch_service_calls_update_state( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_nrgkick_api: AsyncMock, ) -> None: """Test the charge switch calls the API and updates state.""" await setup_integration(hass, mock_config_entry, platforms=[Platform.SWITCH]) entity_id = "switch.nrgkick_test_charging_enabled" assert (state := hass.states.get(entity_id)) assert state.state == "on" # Pause charging # Simulate the device reporting the new paused state after the command. control_data = mock_nrgkick_api.get_control.return_value.copy() control_data[CONTROL_KEY_CHARGE_PAUSE] = 1 mock_nrgkick_api.get_control.return_value = control_data await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) assert (state := hass.states.get(entity_id)) assert state.state == "off" # Resume charging # Simulate the device reporting the resumed state after the command. control_data = mock_nrgkick_api.get_control.return_value.copy() control_data[CONTROL_KEY_CHARGE_PAUSE] = 0 mock_nrgkick_api.get_control.return_value = control_data await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) assert (state := hass.states.get(entity_id)) assert state.state == "on" assert mock_nrgkick_api.set_charge_pause.await_args_list == [ call(True), call(False), ] async def test_charge_switch_rejected_by_device( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_nrgkick_api: AsyncMock, ) -> None: """Test the switch surfaces device rejection messages and keeps state.""" await setup_integration(hass, mock_config_entry, platforms=[Platform.SWITCH]) entity_id = "switch.nrgkick_test_charging_enabled" # Device refuses the command and the library raises an exception. mock_nrgkick_api.set_charge_pause.side_effect = NRGkickCommandRejectedError( "Charging pause is blocked by solar-charging" ) with pytest.raises(HomeAssistantError) as err: await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) assert err.value.translation_key == "command_rejected" assert err.value.translation_placeholders == { "reason": "Charging pause is blocked by solar-charging" } # State should reflect actual device control data (still not paused). assert (state := hass.states.get(entity_id)) assert state.state == "on"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/nrgkick/test_switch.py", "license": "Apache License 2.0", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test