sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
home-assistant/core:homeassistant/components/lock/trigger.py
"""Provides triggers for locks.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import Trigger, make_entity_target_state_trigger from .const import DOMAIN, LockState TRIGGERS: dict[str, type[Trigger]] = { "jammed": make_entity_target_state_trigger(DOMAIN, LockState.JAMMED), "locked": make_entity_target_state_trigger(DOMAIN, LockState.LOCKED), "opened": make_entity_target_state_trigger(DOMAIN, LockState.OPEN), "unlocked": make_entity_target_state_trigger(DOMAIN, LockState.UNLOCKED), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for locks.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/lock/trigger.py", "license": "Apache License 2.0", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/nederlandse_spoorwegen/diagnostics.py
"""Diagnostics support for Nederlandse Spoorwegen.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import CONF_API_KEY from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntry from .const import DOMAIN from .coordinator import NSConfigEntry TO_REDACT = [ CONF_API_KEY, ] async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: NSConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinators_data = {} # Collect data from all coordinators for subentry_id, coordinator in entry.runtime_data.items(): coordinators_data[subentry_id] = { "coordinator_info": { "name": coordinator.name, "departure": coordinator.departure, "destination": coordinator.destination, "via": coordinator.via, "departure_time": coordinator.departure_time, }, "route_data": { "trips_count": len(coordinator.data.trips) if coordinator.data else 0, "has_first_trip": coordinator.data.first_trip is not None if coordinator.data else False, "has_next_trip": coordinator.data.next_trip is not None if coordinator.data else False, } if coordinator.data else None, } return { "entry_data": async_redact_data(entry.data, TO_REDACT), "coordinators": coordinators_data, } async def async_get_device_diagnostics( hass: HomeAssistant, entry: NSConfigEntry, device: DeviceEntry ) -> dict[str, Any]: """Return diagnostics for a route.""" # Find the coordinator for this device coordinator = None subentry_id = None # Each device has an identifier (DOMAIN, subentry_id) for identifier in device.identifiers: if identifier[0] == DOMAIN: subentry_id = identifier[1] coordinator = entry.runtime_data.get(subentry_id) break # Collect detailed diagnostics for this specific route device_data = { "device_info": { "subentry_id": subentry_id, "device_name": device.name, "manufacturer": device.manufacturer, "model": device.model, }, "coordinator_info": { "name": coordinator.name, "departure": coordinator.departure, "destination": coordinator.destination, "via": coordinator.via, "departure_time": coordinator.departure_time, } if coordinator else None, } # Add detailed trip data if available if coordinator and coordinator.data: device_data["trip_details"] = { "trips_count": len(coordinator.data.trips), "has_first_trip": coordinator.data.first_trip is not None, "has_next_trip": coordinator.data.next_trip is not None, } # Add first trip details if available if coordinator.data.first_trip: first_trip = coordinator.data.first_trip device_data["first_trip"] = { "departure_time_planned": str(first_trip.departure_time_planned) if first_trip.departure_time_planned else None, "departure_time_actual": str(first_trip.departure_time_actual) if first_trip.departure_time_actual else None, "arrival_time_planned": str(first_trip.arrival_time_planned) if first_trip.arrival_time_planned else None, "arrival_time_actual": str(first_trip.arrival_time_actual) if first_trip.arrival_time_actual else None, "departure_platform_planned": first_trip.departure_platform_planned, "departure_platform_actual": first_trip.departure_platform_actual, "arrival_platform_planned": first_trip.arrival_platform_planned, "arrival_platform_actual": first_trip.arrival_platform_actual, "status": str(first_trip.status) if first_trip.status else None, "nr_transfers": first_trip.nr_transfers, "going": first_trip.going, } return device_data
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nederlandse_spoorwegen/diagnostics.py", "license": "Apache License 2.0", "lines": 106, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/nintendo_parental_controls/select.py
"""Nintendo Switch Parental Controls select entity definitions.""" from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from enum import StrEnum from typing import Any from pynintendoparental.enum import DeviceTimerMode from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import NintendoParentalControlsConfigEntry, NintendoUpdateCoordinator from .entity import Device, NintendoDevice PARALLEL_UPDATES = 1 class NintendoParentalSelect(StrEnum): """Store keys for Nintendo Parental Controls select entities.""" TIMER_MODE = "timer_mode" @dataclass(kw_only=True, frozen=True) class NintendoParentalControlsSelectEntityDescription(SelectEntityDescription): """Description for Nintendo Parental Controls select entities.""" get_option: Callable[[Device], DeviceTimerMode | None] set_option_fn: Callable[[Device, DeviceTimerMode], Coroutine[Any, Any, None]] options_enum: type[DeviceTimerMode] SELECT_DESCRIPTIONS: tuple[NintendoParentalControlsSelectEntityDescription, ...] = ( NintendoParentalControlsSelectEntityDescription( key=NintendoParentalSelect.TIMER_MODE, translation_key=NintendoParentalSelect.TIMER_MODE, get_option=lambda device: device.timer_mode, set_option_fn=lambda device, option: device.set_timer_mode(option), options_enum=DeviceTimerMode, ), ) async def async_setup_entry( hass: HomeAssistant, entry: NintendoParentalControlsConfigEntry, async_add_devices: AddConfigEntryEntitiesCallback, ) -> None: """Set up the select platform.""" async_add_devices( NintendoParentalSelectEntity( coordinator=entry.runtime_data, device=device, description=description, ) for device in entry.runtime_data.api.devices.values() for description in SELECT_DESCRIPTIONS ) class NintendoParentalSelectEntity(NintendoDevice, SelectEntity): """Nintendo Parental Controls select entity.""" entity_description: NintendoParentalControlsSelectEntityDescription def __init__( self, coordinator: NintendoUpdateCoordinator, device: Device, description: NintendoParentalControlsSelectEntityDescription, ) -> None: """Initialize the select entity.""" super().__init__(coordinator=coordinator, device=device, key=description.key) self.entity_description = description @property def current_option(self) -> str | None: """Return the current selected option.""" option = self.entity_description.get_option(self._device) return option.name.lower() if option else None @property def options(self) -> list[str]: """Return a list of available options.""" return [option.name.lower() for option in self.entity_description.options_enum] async def async_select_option(self, option: str) -> None: """Change the selected option.""" enum_option = self.entity_description.options_enum[option.upper()] await self.entity_description.set_option_fn(self._device, enum_option) await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/select.py", "license": "Apache License 2.0", "lines": 72, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/openrgb/select.py
"""Select platform for OpenRGB integration.""" from __future__ import annotations from homeassistant.components.select import SelectEntity from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import CONNECTION_ERRORS, DOMAIN, UID_SEPARATOR from .coordinator import OpenRGBConfigEntry, OpenRGBCoordinator PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, config_entry: OpenRGBConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the OpenRGB select platform.""" coordinator = config_entry.runtime_data async_add_entities([OpenRGBProfileSelect(coordinator, config_entry)]) class OpenRGBProfileSelect(CoordinatorEntity[OpenRGBCoordinator], SelectEntity): """Representation of an OpenRGB profile select entity.""" _attr_translation_key = "profile" _attr_has_entity_name = True _state_hash: int | None = None _pending_profile: str | None = None def __init__( self, coordinator: OpenRGBCoordinator, entry: OpenRGBConfigEntry ) -> None: """Initialize the select entity.""" super().__init__(coordinator) self._attr_unique_id = UID_SEPARATOR.join([entry.entry_id, "profile"]) self._attr_device_info = { "identifiers": {(DOMAIN, entry.entry_id)}, } self._update_attrs() def _compute_state_hash(self) -> int: """Compute a hash of device states.""" return hash( "\n".join(str(device.data) for device in self.coordinator.client.devices) ) @callback def _update_attrs(self) -> None: """Update the attributes based on the current profile list.""" profiles = self.coordinator.client.profiles self._attr_options = [profile.name for profile in profiles] # If a profile was just applied, set it as current if self._pending_profile is not None: self._attr_current_option = self._pending_profile self._pending_profile = None self._state_hash = self._compute_state_hash() # Only check for state changes if we have a current option to potentially clear elif self._attr_current_option is not None: current_hash = self._compute_state_hash() # If state changed, we can no longer assume current profile if current_hash != self._state_hash: self._attr_current_option = None self._state_hash = None @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" self._update_attrs() super()._handle_coordinator_update() @property def available(self) -> bool: """Return if the select is available.""" return super().available and bool(self._attr_options) async def async_select_option(self, option: str) -> None: """Load the selected profile.""" async with self.coordinator.client_lock: try: await self.hass.async_add_executor_job( self.coordinator.client.load_profile, option ) except CONNECTION_ERRORS as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", translation_placeholders={ "server_address": self.coordinator.server_address, "error": str(err), }, ) from err except ValueError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="openrgb_error", translation_placeholders={ "error": str(err), }, ) from err self._pending_profile = option await self.coordinator.async_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openrgb/select.py", "license": "Apache License 2.0", "lines": 91, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/overseerr/models.py
"""Data models for Overseerr integration.""" from dataclasses import dataclass from python_overseerr import IssueCount, RequestCount @dataclass class OverseerrData: """Data model for Overseerr coordinator.""" requests: RequestCount issues: IssueCount
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/overseerr/models.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:homeassistant/components/pooldose/number.py
"""Number entities for the Seko PoolDose integration.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, cast from homeassistant.components.number import ( NumberDeviceClass, NumberEntity, NumberEntityDescription, ) from homeassistant.const import ( CONCENTRATION_PARTS_PER_MILLION, EntityCategory, UnitOfElectricPotential, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import PooldoseConfigEntry from .entity import PooldoseEntity if TYPE_CHECKING: from .coordinator import PooldoseCoordinator _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 NUMBER_DESCRIPTIONS: tuple[NumberEntityDescription, ...] = ( NumberEntityDescription( key="ph_target", translation_key="ph_target", entity_category=EntityCategory.CONFIG, device_class=NumberDeviceClass.PH, ), NumberEntityDescription( key="orp_target", translation_key="orp_target", entity_category=EntityCategory.CONFIG, device_class=NumberDeviceClass.VOLTAGE, native_unit_of_measurement=UnitOfElectricPotential.MILLIVOLT, ), NumberEntityDescription( key="cl_target", translation_key="cl_target", entity_category=EntityCategory.CONFIG, native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION, ), NumberEntityDescription( key="ofa_ph_lower", translation_key="ofa_ph_lower", entity_category=EntityCategory.CONFIG, device_class=NumberDeviceClass.PH, ), NumberEntityDescription( key="ofa_ph_upper", translation_key="ofa_ph_upper", entity_category=EntityCategory.CONFIG, device_class=NumberDeviceClass.PH, ), NumberEntityDescription( key="ofa_orp_lower", translation_key="ofa_orp_lower", entity_category=EntityCategory.CONFIG, device_class=NumberDeviceClass.VOLTAGE, native_unit_of_measurement=UnitOfElectricPotential.MILLIVOLT, ), NumberEntityDescription( key="ofa_orp_upper", translation_key="ofa_orp_upper", entity_category=EntityCategory.CONFIG, device_class=NumberDeviceClass.VOLTAGE, native_unit_of_measurement=UnitOfElectricPotential.MILLIVOLT, ), NumberEntityDescription( key="ofa_cl_lower", translation_key="ofa_cl_lower", entity_category=EntityCategory.CONFIG, native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION, ), NumberEntityDescription( key="ofa_cl_upper", translation_key="ofa_cl_upper", entity_category=EntityCategory.CONFIG, native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: PooldoseConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up PoolDose number entities from a config entry.""" if TYPE_CHECKING: assert config_entry.unique_id is not None coordinator = config_entry.runtime_data number_data = coordinator.data.get("number", {}) serial_number = config_entry.unique_id async_add_entities( PooldoseNumber(coordinator, serial_number, coordinator.device_info, description) for description in NUMBER_DESCRIPTIONS if description.key in number_data ) class PooldoseNumber(PooldoseEntity, NumberEntity): """Number entity for the Seko PoolDose Python API.""" def __init__( self, coordinator: PooldoseCoordinator, serial_number: str, device_info: Any, description: NumberEntityDescription, ) -> None: """Initialize the number.""" super().__init__(coordinator, serial_number, device_info, description, "number") self._async_update_attrs() def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" self._async_update_attrs() super()._handle_coordinator_update() def _async_update_attrs(self) -> None: """Update number attributes.""" data = cast(dict, self.get_data()) self._attr_native_value = data["value"] self._attr_native_min_value = data["min"] self._attr_native_max_value = data["max"] self._attr_native_step = data["step"] async def async_set_native_value(self, value: float) -> None: """Set new value.""" await self._async_perform_write( self.coordinator.client.set_number, self.entity_description.key, value ) self._attr_native_value = value self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/pooldose/number.py", "license": "Apache License 2.0", "lines": 127, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/pooldose/select.py
"""Select entities for the Seko PoolDose integration.""" from __future__ import annotations from dataclasses import dataclass import logging from typing import TYPE_CHECKING, Any, cast from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.const import EntityCategory, UnitOfVolume, UnitOfVolumeFlowRate from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import PooldoseConfigEntry from .const import UNIT_MAPPING from .entity import PooldoseEntity if TYPE_CHECKING: from .coordinator import PooldoseCoordinator _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 @dataclass(frozen=True, kw_only=True) class PooldoseSelectEntityDescription(SelectEntityDescription): """Describes PoolDose select entity.""" use_unit_conversion: bool = False SELECT_DESCRIPTIONS: tuple[PooldoseSelectEntityDescription, ...] = ( PooldoseSelectEntityDescription( key="water_meter_unit", translation_key="water_meter_unit", entity_category=EntityCategory.CONFIG, entity_registry_enabled_default=False, options=[UnitOfVolume.LITERS, UnitOfVolume.CUBIC_METERS], use_unit_conversion=True, ), PooldoseSelectEntityDescription( key="flow_rate_unit", translation_key="flow_rate_unit", entity_category=EntityCategory.CONFIG, entity_registry_enabled_default=False, options=[ UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR, UnitOfVolumeFlowRate.LITERS_PER_SECOND, ], use_unit_conversion=True, ), PooldoseSelectEntityDescription( key="ph_type_dosing_set", translation_key="ph_type_dosing_set", entity_category=EntityCategory.CONFIG, options=["alcalyne", "acid"], ), PooldoseSelectEntityDescription( key="ph_type_dosing_method", translation_key="ph_type_dosing_method", entity_category=EntityCategory.CONFIG, options=["off", "proportional", "on_off", "timed"], entity_registry_enabled_default=False, ), PooldoseSelectEntityDescription( key="orp_type_dosing_set", translation_key="orp_type_dosing_set", entity_category=EntityCategory.CONFIG, options=["low", "high"], entity_registry_enabled_default=False, ), PooldoseSelectEntityDescription( key="orp_type_dosing_method", translation_key="orp_type_dosing_method", entity_category=EntityCategory.CONFIG, options=["off", "proportional", "on_off", "timed"], entity_registry_enabled_default=False, ), PooldoseSelectEntityDescription( key="cl_type_dosing_set", translation_key="cl_type_dosing_set", entity_category=EntityCategory.CONFIG, options=["low", "high"], entity_registry_enabled_default=False, ), PooldoseSelectEntityDescription( key="cl_type_dosing_method", translation_key="cl_type_dosing_method", entity_category=EntityCategory.CONFIG, options=["off", "proportional", "on_off", "timed"], entity_registry_enabled_default=False, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: PooldoseConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up PoolDose select entities from a config entry.""" if TYPE_CHECKING: assert config_entry.unique_id is not None coordinator = config_entry.runtime_data select_data = coordinator.data["select"] serial_number = config_entry.unique_id async_add_entities( PooldoseSelect(coordinator, serial_number, coordinator.device_info, description) for description in SELECT_DESCRIPTIONS if description.key in select_data ) class PooldoseSelect(PooldoseEntity, SelectEntity): """Select entity for the Seko PoolDose Python API.""" entity_description: PooldoseSelectEntityDescription def __init__( self, coordinator: PooldoseCoordinator, serial_number: str, device_info: Any, description: PooldoseSelectEntityDescription, ) -> None: """Initialize the select.""" super().__init__(coordinator, serial_number, device_info, description, "select") self._async_update_attrs() def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" self._async_update_attrs() super()._handle_coordinator_update() def _async_update_attrs(self) -> None: """Update select attributes.""" data = cast(dict, self.get_data()) api_value = cast(str, data["value"]) # Convert API value to Home Assistant unit if unit conversion is enabled if self.entity_description.use_unit_conversion: # Map API value (e.g., "m3") to HA unit (e.g., "m³") self._attr_current_option = UNIT_MAPPING.get(api_value, api_value) else: self._attr_current_option = api_value async def async_select_option(self, option: str) -> None: """Change the selected option.""" # Convert Home Assistant unit to API value if unit conversion is enabled if self.entity_description.use_unit_conversion: # Invert UNIT_MAPPING to get API value from HA unit reverse_map = {v: k for k, v in UNIT_MAPPING.items()} api_value = reverse_map.get(option, option) else: api_value = option await self._async_perform_write( self.coordinator.client.set_select, self.entity_description.key, api_value ) self._attr_current_option = option self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/pooldose/select.py", "license": "Apache License 2.0", "lines": 139, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/risco/models.py
"""Models for Risco integration.""" from collections.abc import Callable from dataclasses import dataclass, field from typing import Any from pyrisco import RiscoLocal @dataclass class LocalData: """A data class for local data passed to the platforms.""" system: RiscoLocal partition_updates: dict[int, Callable[[], Any]] = field(default_factory=dict)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/risco/models.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/risco/services.py
"""Services for Risco integration.""" from datetime import datetime import voluptuous as vol from homeassistant.const import ATTR_CONFIG_ENTRY_ID, ATTR_TIME, CONF_TYPE from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN, SERVICE_SET_TIME, TYPE_LOCAL from .models import LocalData async def async_setup_services(hass: HomeAssistant) -> None: """Create the Risco Services/Actions.""" async def _set_time(service_call: ServiceCall) -> None: entry = service.async_get_config_entry( service_call.hass, DOMAIN, service_call.data[ATTR_CONFIG_ENTRY_ID] ) time = service_call.data.get(ATTR_TIME) # Validate config entry is local (not cloud) if entry.data.get(CONF_TYPE) != TYPE_LOCAL: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="not_local_entry", ) time_to_send = time if time is None: time_to_send = datetime.now() local_data: LocalData = hass.data[DOMAIN][entry.entry_id] await local_data.system.set_time(time_to_send) hass.services.async_register( domain=DOMAIN, service=SERVICE_SET_TIME, schema=vol.Schema( { vol.Required(ATTR_CONFIG_ENTRY_ID): cv.string, vol.Optional(ATTR_TIME): cv.datetime, } ), service_func=_set_time, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/risco/services.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:homeassistant/components/saunum/binary_sensor.py
"""Binary sensor platform for Saunum Leil Sauna Control Unit integration.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING from pysaunum import SaunumData from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, BinarySensorEntityDescription, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import LeilSaunaConfigEntry from .entity import LeilSaunaEntity if TYPE_CHECKING: from .coordinator import LeilSaunaCoordinator PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class LeilSaunaBinarySensorEntityDescription(BinarySensorEntityDescription): """Describes Leil Sauna binary sensor entity.""" value_fn: Callable[[SaunumData], bool | None] BINARY_SENSORS: tuple[LeilSaunaBinarySensorEntityDescription, ...] = ( LeilSaunaBinarySensorEntityDescription( key="door_open", device_class=BinarySensorDeviceClass.DOOR, value_fn=lambda data: data.door_open, ), LeilSaunaBinarySensorEntityDescription( key="alarm_door_open", translation_key="alarm_door_open", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.alarm_door_open, ), LeilSaunaBinarySensorEntityDescription( key="alarm_door_sensor", translation_key="alarm_door_sensor", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.alarm_door_sensor, ), LeilSaunaBinarySensorEntityDescription( key="alarm_thermal_cutoff", translation_key="alarm_thermal_cutoff", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.alarm_thermal_cutoff, ), LeilSaunaBinarySensorEntityDescription( key="alarm_internal_temp", translation_key="alarm_internal_temp", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.alarm_internal_temp, ), LeilSaunaBinarySensorEntityDescription( key="alarm_temp_sensor_short", translation_key="alarm_temp_sensor_short", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.alarm_temp_sensor_short, ), LeilSaunaBinarySensorEntityDescription( key="alarm_temp_sensor_open", translation_key="alarm_temp_sensor_open", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.alarm_temp_sensor_open, ), ) async def async_setup_entry( hass: HomeAssistant, entry: LeilSaunaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Saunum Leil Sauna binary sensors from a config entry.""" coordinator = entry.runtime_data async_add_entities( LeilSaunaBinarySensorEntity(coordinator, description) for description in BINARY_SENSORS if description.value_fn(coordinator.data) is not None ) class LeilSaunaBinarySensorEntity(LeilSaunaEntity, BinarySensorEntity): """Representation of a Saunum Leil Sauna binary sensor.""" entity_description: LeilSaunaBinarySensorEntityDescription def __init__( self, coordinator: LeilSaunaCoordinator, description: LeilSaunaBinarySensorEntityDescription, ) -> None: """Initialize the binary sensor.""" super().__init__(coordinator) self._attr_unique_id = f"{coordinator.config_entry.entry_id}-{description.key}" self.entity_description = description @property def is_on(self) -> bool | None: """Return the state of the binary sensor.""" return self.entity_description.value_fn(self.coordinator.data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/binary_sensor.py", "license": "Apache License 2.0", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/saunum/sensor.py
"""Sensor platform for Saunum Leil Sauna Control Unit integration.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING from pysaunum import SaunumData from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import EntityCategory, UnitOfTemperature, UnitOfTime from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import LeilSaunaConfigEntry from .entity import LeilSaunaEntity if TYPE_CHECKING: from .coordinator import LeilSaunaCoordinator PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class LeilSaunaSensorEntityDescription(SensorEntityDescription): """Describes Leil Sauna sensor entity.""" value_fn: Callable[[SaunumData], float | int | None] SENSORS: tuple[LeilSaunaSensorEntityDescription, ...] = ( LeilSaunaSensorEntityDescription( key="current_temperature", translation_key="current_temperature", native_unit_of_measurement=UnitOfTemperature.CELSIUS, device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda data: data.current_temperature, ), LeilSaunaSensorEntityDescription( key="heater_elements_active", translation_key="heater_elements_active", state_class=SensorStateClass.MEASUREMENT, value_fn=lambda data: data.heater_elements_active, ), LeilSaunaSensorEntityDescription( key="on_time", translation_key="on_time", native_unit_of_measurement=UnitOfTime.SECONDS, suggested_unit_of_measurement=UnitOfTime.HOURS, device_class=SensorDeviceClass.DURATION, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, state_class=SensorStateClass.TOTAL_INCREASING, value_fn=lambda data: data.on_time, ), ) async def async_setup_entry( hass: HomeAssistant, entry: LeilSaunaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Saunum Leil Sauna sensors from a config entry.""" coordinator = entry.runtime_data async_add_entities( LeilSaunaSensorEntity(coordinator, description) for description in SENSORS if description.value_fn(coordinator.data) is not None ) class LeilSaunaSensorEntity(LeilSaunaEntity, SensorEntity): """Representation of a Saunum Leil Sauna sensor.""" entity_description: LeilSaunaSensorEntityDescription def __init__( self, coordinator: LeilSaunaCoordinator, description: LeilSaunaSensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self._attr_unique_id = f"{coordinator.config_entry.entry_id}-{description.key}" self.entity_description = description @property def native_value(self) -> float | int | None: """Return the value reported by the sensor.""" return self.entity_description.value_fn(self.coordinator.data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/sensor.py", "license": "Apache License 2.0", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/scene/trigger.py
"""Provides triggers for scenes.""" from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant, State from homeassistant.helpers.trigger import ( ENTITY_STATE_TRIGGER_SCHEMA, EntityTriggerBase, Trigger, ) from . import DOMAIN class SceneActivatedTrigger(EntityTriggerBase): """Trigger for scene entity activations.""" _domain = DOMAIN _schema = ENTITY_STATE_TRIGGER_SCHEMA def is_valid_transition(self, from_state: State, to_state: State) -> bool: """Check if the origin state is valid and different from the current state.""" # UNKNOWN is a valid from_state, otherwise the first time the scene is activated # it would not trigger if from_state.state == STATE_UNAVAILABLE: return False return from_state.state != to_state.state def is_valid_state(self, state: State) -> bool: """Check if the new state is not invalid.""" return state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN) TRIGGERS: dict[str, type[Trigger]] = { "activated": SceneActivatedTrigger, } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for scenes.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/scene/trigger.py", "license": "Apache License 2.0", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/shelly/services.py
"""Support for services.""" from typing import TYPE_CHECKING, Any, cast from aioshelly.const import RPC_GENERATIONS from aioshelly.exceptions import DeviceConnectionError, RpcCallError import voluptuous as vol from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ATTR_DEVICE_ID from homeassistant.core import ( HomeAssistant, ServiceCall, ServiceResponse, SupportsResponse, callback, ) from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import config_validation as cv, device_registry as dr from homeassistant.util.json import JsonValueType from .const import ATTR_KEY, ATTR_VALUE, CONF_SLEEP_PERIOD, DOMAIN from .coordinator import ShellyConfigEntry from .utils import get_device_entry_gen SERVICE_GET_KVS_VALUE = "get_kvs_value" SERVICE_SET_KVS_VALUE = "set_kvs_value" SERVICE_GET_KVS_VALUE_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE_ID): cv.string, vol.Required(ATTR_KEY): str, } ) SERVICE_SET_KVS_VALUE_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE_ID): cv.string, vol.Required(ATTR_KEY): str, vol.Required(ATTR_VALUE): vol.Any(str, int, float, bool, dict, list, None), } ) @callback def async_get_config_entry_for_service_call( call: ServiceCall, ) -> ShellyConfigEntry: """Get the config entry related to a service call (by device ID).""" device_registry = dr.async_get(call.hass) device_id = call.data[ATTR_DEVICE_ID] if (device_entry := device_registry.async_get(device_id)) is None: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_device_id", translation_placeholders={"device_id": device_id}, ) for entry_id in device_entry.config_entries: config_entry = call.hass.config_entries.async_get_entry(entry_id) if TYPE_CHECKING: assert config_entry if config_entry.domain != DOMAIN: continue if config_entry.state is not ConfigEntryState.LOADED: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="entry_not_loaded", translation_placeholders={"device": config_entry.title}, ) if get_device_entry_gen(config_entry) not in RPC_GENERATIONS: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="kvs_not_supported", translation_placeholders={"device": config_entry.title}, ) if config_entry.data.get(CONF_SLEEP_PERIOD, 0) > 0: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="kvs_not_supported", translation_placeholders={"device": config_entry.title}, ) return config_entry raise ServiceValidationError( translation_domain=DOMAIN, translation_key="config_entry_not_found", translation_placeholders={"device_id": device_id}, ) async def _async_execute_action( call: ServiceCall, method: str, args: tuple ) -> dict[str, Any]: """Execute action on the device.""" config_entry = async_get_config_entry_for_service_call(call) runtime_data = config_entry.runtime_data if not runtime_data.rpc: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="device_not_initialized", translation_placeholders={"device": config_entry.title}, ) action_method = getattr(runtime_data.rpc.device, method) try: response = await action_method(*args) except RpcCallError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="rpc_call_error", translation_placeholders={"device": config_entry.title}, ) from err except DeviceConnectionError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="device_communication_error", translation_placeholders={"device": config_entry.title}, ) from err else: return cast(dict[str, Any], response) async def async_get_kvs_value(call: ServiceCall) -> ServiceResponse: """Handle the get_kvs_value service call.""" key = call.data[ATTR_KEY] response = await _async_execute_action(call, "kvs_get", (key,)) result: dict[str, JsonValueType] = {} result[ATTR_VALUE] = response[ATTR_VALUE] return result async def async_set_kvs_value(call: ServiceCall) -> None: """Handle the set_kvs_value service call.""" await _async_execute_action( call, "kvs_set", (call.data[ATTR_KEY], call.data[ATTR_VALUE]) ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up the services for Shelly integration.""" for service, method, schema, response in ( ( SERVICE_GET_KVS_VALUE, async_get_kvs_value, SERVICE_GET_KVS_VALUE_SCHEMA, SupportsResponse.ONLY, ), ( SERVICE_SET_KVS_VALUE, async_set_kvs_value, SERVICE_SET_KVS_VALUE_SCHEMA, SupportsResponse.NONE, ), ): hass.services.async_register( DOMAIN, service, method, schema=schema, supports_response=response, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/shelly/services.py", "license": "Apache License 2.0", "lines": 143, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/siren/trigger.py
"""Provides triggers for sirens.""" from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import Trigger, make_entity_target_state_trigger from . import DOMAIN TRIGGERS: dict[str, type[Trigger]] = { "turned_on": make_entity_target_state_trigger(DOMAIN, STATE_ON), "turned_off": make_entity_target_state_trigger(DOMAIN, STATE_OFF), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for sirens.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/siren/trigger.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:homeassistant/components/sunricher_dali/entity.py
"""Base entity for Sunricher DALI integration.""" from __future__ import annotations import logging from PySrDaliGateway import CallbackEventType, DaliObjectBase, Device from homeassistant.core import callback from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) class DaliCenterEntity(Entity): """Base entity for DALI Center objects (devices, scenes, etc.).""" _attr_has_entity_name = True _attr_should_poll = False def __init__(self, dali_object: DaliObjectBase) -> None: """Initialize base entity.""" self._dali_object = dali_object self._attr_unique_id = dali_object.unique_id self._unavailable_logged = False self._attr_available = True async def async_added_to_hass(self) -> None: """Register availability listener.""" self.async_on_remove( self._dali_object.register_listener( CallbackEventType.ONLINE_STATUS, self._handle_availability, ) ) @callback def _handle_availability(self, available: bool) -> None: """Handle availability changes.""" if not available and not self._unavailable_logged: _LOGGER.info("Entity %s became unavailable", self.entity_id) self._unavailable_logged = True elif available and self._unavailable_logged: _LOGGER.info("Entity %s is back online", self.entity_id) self._unavailable_logged = False self._attr_available = available self.schedule_update_ha_state() class DaliDeviceEntity(DaliCenterEntity): """Base entity for DALI Device objects.""" def __init__(self, device: Device) -> None: """Initialize device entity.""" super().__init__(device) self._attr_available = device.status == "online"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/sunricher_dali/entity.py", "license": "Apache License 2.0", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/sunricher_dali/scene.py
"""Support for DALI Center Scene entities.""" import logging from typing import Any from PySrDaliGateway import Scene from homeassistant.components.scene import Scene as SceneEntity from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .entity import DaliCenterEntity from .types import DaliCenterConfigEntry _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: DaliCenterConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up DALI Center scene entities from config entry.""" async_add_entities(DaliCenterScene(scene) for scene in entry.runtime_data.scenes) class DaliCenterScene(DaliCenterEntity, SceneEntity): """Representation of a DALI Center Scene.""" def __init__(self, scene: Scene) -> None: """Initialize the DALI scene.""" super().__init__(scene) self._scene = scene self._attr_name = scene.name self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, scene.gw_sn)}, ) async def async_activate(self, **kwargs: Any) -> None: """Activate the DALI scene.""" await self.hass.async_add_executor_job(self._scene.activate)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/sunricher_dali/scene.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/switch/trigger.py
"""Provides triggers for switch platform.""" from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import Trigger, make_entity_target_state_trigger from .const import DOMAIN TRIGGERS: dict[str, type[Trigger]] = { "turned_on": make_entity_target_state_trigger(DOMAIN, STATE_ON), "turned_off": make_entity_target_state_trigger(DOMAIN, STATE_OFF), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for switch platform.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/switch/trigger.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:homeassistant/components/switchbot/button.py
"""Button support for SwitchBot devices.""" import logging import switchbot from homeassistant.components.button import ButtonEntity from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util import dt as dt_util from .coordinator import SwitchbotConfigEntry, SwitchbotDataUpdateCoordinator from .entity import SwitchbotEntity, exception_handler _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, entry: SwitchbotConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Switchbot button platform.""" coordinator = entry.runtime_data if isinstance(coordinator.device, switchbot.SwitchbotArtFrame): async_add_entities( [ SwitchBotArtFrameNextButton(coordinator, "next_image"), SwitchBotArtFramePrevButton(coordinator, "previous_image"), ] ) if isinstance(coordinator.device, switchbot.SwitchbotMeterProCO2): async_add_entities([SwitchBotMeterProCO2SyncDateTimeButton(coordinator)]) class SwitchBotArtFrameButtonBase(SwitchbotEntity, ButtonEntity): """Base class for Art Frame buttons.""" _device: switchbot.SwitchbotArtFrame def __init__( self, coordinator: SwitchbotDataUpdateCoordinator, translation_key: str ) -> None: """Initialize the button base.""" super().__init__(coordinator) self._attr_unique_id = f"{coordinator.base_unique_id}_{translation_key}" self._attr_translation_key = translation_key class SwitchBotArtFrameNextButton(SwitchBotArtFrameButtonBase): """Representation of a next image button.""" @exception_handler async def async_press(self) -> None: """Handle the button press.""" _LOGGER.debug("Pressing next image button %s", self._address) await self._device.next_image() class SwitchBotArtFramePrevButton(SwitchBotArtFrameButtonBase): """Representation of a previous image button.""" @exception_handler async def async_press(self) -> None: """Handle the button press.""" _LOGGER.debug("Pressing previous image button %s", self._address) await self._device.prev_image() class SwitchBotMeterProCO2SyncDateTimeButton(SwitchbotEntity, ButtonEntity): """Button to sync date and time on Meter Pro CO2 to the current HA instance datetime.""" _device: switchbot.SwitchbotMeterProCO2 _attr_entity_category = EntityCategory.CONFIG _attr_translation_key = "sync_datetime" def __init__(self, coordinator: SwitchbotDataUpdateCoordinator) -> None: """Initialize the sync time button.""" super().__init__(coordinator) self._attr_unique_id = f"{coordinator.base_unique_id}_sync_datetime" @exception_handler async def async_press(self) -> None: """Sync time with Home Assistant.""" now = dt_util.now() # Get UTC offset components utc_offset = now.utcoffset() utc_offset_hours, utc_offset_minutes = 0, 0 if utc_offset is not None: total_seconds = int(utc_offset.total_seconds()) utc_offset_hours = total_seconds // 3600 utc_offset_minutes = abs(total_seconds % 3600) // 60 timestamp = int(now.timestamp()) _LOGGER.debug( "Syncing time for %s: timestamp=%s, utc_offset_hours=%s, utc_offset_minutes=%s", self._address, timestamp, utc_offset_hours, utc_offset_minutes, ) await self._device.set_datetime( timestamp=timestamp, utc_offset_hours=utc_offset_hours, utc_offset_minutes=utc_offset_minutes, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/switchbot/button.py", "license": "Apache License 2.0", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/template/validators.py
"""Template config validation methods.""" from collections.abc import Callable from enum import StrEnum import logging from typing import Any import voluptuous as vol from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity import Entity _LOGGER = logging.getLogger(__name__) # Valid on/off values for booleans. These tuples are pulled # from cv.boolean and are used to produce logger errors for the user. RESULT_ON = ("1", "true", "yes", "on", "enable") RESULT_OFF = ("0", "false", "no", "off", "disable") def log_validation_result_error( entity: Entity, attribute: str, value: Any, expected: tuple[str, ...] | str, ) -> None: """Log a template result error.""" # in some cases, like `preview` entities, the entity_id does not exist. if entity.entity_id is None: message = f"Received invalid {attribute}: {value} for entity {entity.name}, %s" else: message = ( f"Received invalid {entity.entity_id.split('.')[0]} {attribute}" f": {value} for entity {entity.entity_id}, %s" ) _LOGGER.error( message, expected if isinstance(expected, str) else "expected one of " + ", ".join(expected), ) def check_result_for_none(result: Any, **kwargs: Any) -> bool: """Checks the result for none, unknown, unavailable.""" if result is None: return True if kwargs.get("none_on_unknown_unavailable") and isinstance(result, str): return result.lower() in (STATE_UNAVAILABLE, STATE_UNKNOWN) return False def strenum[T: StrEnum]( entity: Entity, attribute: str, state_enum: type[T], state_on: T | None = None, state_off: T | None = None, **kwargs: Any, ) -> Callable[[Any], T | None]: """Converts the template result to an StrEnum. All strings will attempt to convert to the StrEnum If state_on or state_off are provided, boolean values will return the enum that represents each boolean value. Anything that cannot convert will result in None. none_on_unknown_unavailable """ def convert(result: Any) -> T | None: if check_result_for_none(result, **kwargs): return None if isinstance(result, str): value = result.lower().strip() try: return state_enum(value) except ValueError: pass if state_on or state_off: try: bool_value = cv.boolean(result) if state_on and bool_value: return state_on if state_off and not bool_value: return state_off except vol.Invalid: pass expected = tuple(s.value for s in state_enum) if state_on: expected += RESULT_ON if state_off: expected += RESULT_OFF log_validation_result_error( entity, attribute, result, expected, ) return None return convert def boolean( entity: Entity, attribute: str, as_true: tuple[str, ...] | None = None, as_false: tuple[str, ...] | None = None, **kwargs: Any, ) -> Callable[[Any], bool | None]: """Convert the result to a boolean. True/not 0/'1'/'true'/'yes'/'on'/'enable' are considered truthy False/0/'0'/'false'/'no'/'off'/'disable' are considered falsy Additional values provided by as_true are considered truthy Additional values provided by as_false are considered truthy All other values are None """ def convert(result: Any) -> bool | None: if check_result_for_none(result, **kwargs): return None if isinstance(result, bool): return result if isinstance(result, str) and (as_true or as_false): value = result.lower().strip() if as_true and value in as_true: return True if as_false and value in as_false: return False try: return cv.boolean(result) except vol.Invalid: pass items: tuple[str, ...] = RESULT_ON + RESULT_OFF if as_true: items += as_true if as_false: items += as_false log_validation_result_error(entity, attribute, result, items) return None return convert def number( entity: Entity, attribute: str, minimum: float | None = None, maximum: float | None = None, return_type: type[float | int] = float, **kwargs: Any, ) -> Callable[[Any], float | int | None]: """Convert the result to a number (float or int). Any value in the range is converted to a float or int All other values are None """ message = "expected a number" if minimum is not None and maximum is not None: message = f"{message} between {minimum:0.1f} and {maximum:0.1f}" elif minimum is not None and maximum is None: message = f"{message} greater than or equal to {minimum:0.1f}" elif minimum is None and maximum is not None: message = f"{message} less than or equal to {maximum:0.1f}" def convert(result: Any) -> float | int | None: if check_result_for_none(result, **kwargs): return None if (result_type := type(result)) is bool: log_validation_result_error(entity, attribute, result, message) return None if isinstance(result, (float, int)): value = result if return_type is int and result_type is float: value = int(value) elif return_type is float and result_type is int: value = float(value) else: try: value = vol.Coerce(float)(result) if return_type is int: value = int(value) except vol.Invalid: log_validation_result_error(entity, attribute, result, message) return None if minimum is None and maximum is None: return value if ( ( minimum is not None and maximum is not None and minimum <= value <= maximum ) or (minimum is not None and maximum is None and value >= minimum) or (minimum is None and maximum is not None and value <= maximum) ): return value log_validation_result_error(entity, attribute, result, message) return None return convert def list_of_strings( entity: Entity, attribute: str, none_on_empty: bool = False, **kwargs: Any, ) -> Callable[[Any], list[str] | None]: """Convert the result to a list of strings. This ensures the result is a list of strings. All other values that are not lists will result in None. none_on_empty will cause the converter to return None when the list is empty. """ def convert(result: Any) -> list[str] | None: if check_result_for_none(result, **kwargs): return None if not isinstance(result, list): log_validation_result_error( entity, attribute, result, "expected a list of strings", ) return None if none_on_empty and len(result) == 0: return None # Ensure the result are strings. return [str(v) for v in result] return convert def item_in_list[T]( entity: Entity, attribute: str, items: list[Any] | str | None, items_attribute: str | None = None, **kwargs: Any, ) -> Callable[[Any], Any | None]: """Assert the result of the template is an item inside a list. Returns the result if the result is inside the list. All results that are not inside the list will return None. """ def convert(result: Any) -> Any | None: if check_result_for_none(result, **kwargs): return None # items may be mutable based on another template field. Always # perform this check when the items come from an configured # attribute. if isinstance(items, str): _items = getattr(entity, items) else: _items = items if _items is None or (len(_items) == 0): if items_attribute: log_validation_result_error( entity, attribute, result, f"{items_attribute} is empty", ) return None if result not in _items: log_validation_result_error( entity, attribute, result, tuple(str(v) for v in _items), ) return None return result return convert def url( entity: Entity, attribute: str, **kwargs: Any, ) -> Callable[[Any], str | None]: """Convert the result to a string url or None.""" def convert(result: Any) -> str | None: if check_result_for_none(result, **kwargs): return None try: return cv.url(result) except vol.Invalid: log_validation_result_error( entity, attribute, result, "expected a url", ) return None return convert def string( entity: Entity, attribute: str, **kwargs: Any, ) -> Callable[[Any], str | None]: """Convert the result to a string or None.""" def convert(result: Any) -> str | None: if check_result_for_none(result, **kwargs): return None if isinstance(result, str): return result try: return cv.string(result) except vol.Invalid: log_validation_result_error( entity, attribute, result, "expected a string", ) return None return convert
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/template/validators.py", "license": "Apache License 2.0", "lines": 288, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/teslemetry/application_credentials.py
"""Application Credentials platform the Teslemetry integration.""" from homeassistant.components.application_credentials import ( AuthorizationServer, ClientCredential, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_oauth2_flow from .const import AUTHORIZE_URL, TOKEN_URL from .oauth import TeslemetryImplementation async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer: """Return authorization server.""" return AuthorizationServer( authorize_url=AUTHORIZE_URL, token_url=TOKEN_URL, ) async def async_get_auth_implementation( hass: HomeAssistant, auth_domain: str, credential: ClientCredential ) -> config_entry_oauth2_flow.AbstractOAuth2Implementation: """Return auth implementation.""" return TeslemetryImplementation( hass, auth_domain, credential.client_id, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/teslemetry/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/teslemetry/oauth.py
"""Provide oauth implementations for the Teslemetry integration.""" from __future__ import annotations from typing import Any from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_oauth2_flow from .const import AUTHORIZE_URL, TOKEN_URL class TeslemetryImplementation( config_entry_oauth2_flow.LocalOAuth2ImplementationWithPkce ): """Teslemetry OAuth2 implementation.""" def __init__(self, hass: HomeAssistant, domain: str, client_id: str) -> None: """Initialize OAuth2 implementation.""" super().__init__( hass, domain, client_id, AUTHORIZE_URL, TOKEN_URL, ) @property def name(self) -> str: """Name of the implementation.""" return "Teslemetry OAuth2" @property def extra_authorize_data(self) -> dict[str, Any]: """Extra data that needs to be appended to the authorize url.""" data: dict = { "name": self.hass.config.location_name, } data.update(super().extra_authorize_data) return data @property def extra_token_resolve_data(self) -> dict[str, Any]: """Extra data that needs to be appended to the token resolve request.""" data: dict = { "name": self.hass.config.location_name, } data.update(super().extra_token_resolve_data) return data
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/teslemetry/oauth.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/tibber/application_credentials.py
"""Application credentials platform for Tibber.""" from homeassistant.components.application_credentials import AuthorizationServer from homeassistant.core import HomeAssistant AUTHORIZE_URL = "https://thewall.tibber.com/connect/authorize" TOKEN_URL = "https://thewall.tibber.com/connect/token" async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer: """Return authorization server for Tibber Data API.""" return AuthorizationServer( authorize_url=AUTHORIZE_URL, token_url=TOKEN_URL, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/tibber/application_credentials.py", "license": "Apache License 2.0", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/tplink_omada/services.py
"""Services for the TP-Link Omada integration.""" from typing import cast from tplink_omada_client.exceptions import OmadaClientException import voluptuous as vol from homeassistant.config_entries import ConfigEntry, ConfigEntryState from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import config_validation as cv, selector from .const import DOMAIN from .controller import OmadaSiteController SERVICE_RECONNECT_CLIENT = "reconnect_client" ATTR_CONFIG_ENTRY_ID = "config_entry_id" ATTR_MAC = "mac" def _get_controller(call: ServiceCall) -> OmadaSiteController: if call.data.get(ATTR_CONFIG_ENTRY_ID): entry = call.hass.config_entries.async_get_entry( call.data[ATTR_CONFIG_ENTRY_ID] ) if not entry: raise ServiceValidationError("Specified TP-Link Omada controller not found") else: # Assume first loaded entry if none specified (for backward compatibility/99% use case) entries = call.hass.config_entries.async_entries(DOMAIN) if len(entries) == 0: raise ServiceValidationError("No active TP-Link Omada controllers found") entry = entries[0] entry = cast(ConfigEntry[OmadaSiteController], entry) if entry.state is not ConfigEntryState.LOADED: raise ServiceValidationError( "The TP-Link Omada integration is not currently available" ) return entry.runtime_data SCHEMA_RECONNECT_CLIENT = vol.Schema( { vol.Optional(ATTR_CONFIG_ENTRY_ID): selector.ConfigEntrySelector( { "integration": DOMAIN, } ), vol.Required(ATTR_MAC): cv.string, } ) async def _handle_reconnect_client(call: ServiceCall) -> None: """Handle the service action to force reconnection of a network client.""" controller = _get_controller(call) mac: str = call.data[ATTR_MAC] try: await controller.omada_client.reconnect_client(mac) except OmadaClientException as ex: raise HomeAssistantError(f"Failed to reconnect client with MAC {mac}") from ex SERVICES = [ (SERVICE_RECONNECT_CLIENT, SCHEMA_RECONNECT_CLIENT, _handle_reconnect_client) ] @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up the services for the TP-Link Omada integration.""" for service_name, schema, handler in SERVICES: hass.services.async_register(DOMAIN, service_name, handler, schema=schema)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/tplink_omada/services.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/transmission/helpers.py
"""Helper functions for Transmission.""" from typing import Any from transmission_rpc.torrent import Torrent def format_torrent(torrent: Torrent) -> dict[str, Any]: """Format a single torrent.""" value: dict[str, Any] = {} value["id"] = torrent.id value["name"] = torrent.name value["status"] = torrent.status.value value["percent_done"] = f"{torrent.percent_done * 100:.2f}%" value["ratio"] = f"{torrent.ratio:.2f}" value["eta"] = str(torrent.eta) if torrent.eta else None value["added_date"] = torrent.added_date.isoformat() value["done_date"] = torrent.done_date.isoformat() if torrent.done_date else None value["download_dir"] = torrent.download_dir value["labels"] = torrent.labels return value def filter_torrents( torrents: list[Torrent], statuses: list[str] | None = None ) -> list[Torrent]: """Filter torrents based on the statuses provided.""" return [ torrent for torrent in torrents if statuses is None or torrent.status in statuses ] def format_torrents( torrents: list[Torrent], ) -> dict[str, dict[str, Any]]: """Format a list of torrents.""" value = {} for torrent in torrents: value[torrent.name] = format_torrent(torrent) return value
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/transmission/helpers.py", "license": "Apache License 2.0", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/update/trigger.py
"""Provides triggers for update platform.""" from homeassistant.const import STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import Trigger, make_entity_target_state_trigger from .const import DOMAIN TRIGGERS: dict[str, type[Trigger]] = { "update_became_available": make_entity_target_state_trigger(DOMAIN, STATE_ON), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for update platform.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/update/trigger.py", "license": "Apache License 2.0", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/vesync/services.py
"""Support for VeSync Services.""" from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers.dispatcher import async_dispatcher_send from . import VesyncConfigEntry from .const import DOMAIN, SERVICE_UPDATE_DEVS, VS_DEVICES, VS_DISCOVERY @callback def async_setup_services(hass: HomeAssistant) -> None: """Handle for services.""" hass.services.async_register( DOMAIN, SERVICE_UPDATE_DEVS, async_new_device_discovery ) async def async_new_device_discovery(call: ServiceCall) -> None: """Discover and add new devices.""" entries = call.hass.config_entries.async_entries(DOMAIN) config_entry: VesyncConfigEntry | None = entries[0] if entries else None if not config_entry: raise ServiceValidationError("Entry not found") if config_entry.state is not ConfigEntryState.LOADED: raise ServiceValidationError("Entry not loaded") manager = config_entry.runtime_data.manager known_devices = list(manager.devices) await manager.get_devices() new_devices = [device for device in manager.devices if device not in known_devices] if new_devices: async_dispatcher_send(call.hass, VS_DISCOVERY.format(VS_DEVICES), new_devices)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/vesync/services.py", "license": "Apache License 2.0", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/vivotek/config_flow.py
"""Config flow for Vivotek IP cameras integration.""" import logging from typing import Any from libpyvivotek.vivotek import SECURITY_LEVELS, VivotekCameraError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult, OptionsFlow from homeassistant.const import ( CONF_AUTHENTICATION, CONF_IP_ADDRESS, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION, UnitOfFrequency, ) from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.device_registry import format_mac from homeassistant.helpers.selector import ( NumberSelector, NumberSelectorConfig, SelectSelector, SelectSelectorConfig, SelectSelectorMode, ) from . import VivotekConfigEntry, build_cam_client from .camera import DEFAULT_FRAMERATE, DEFAULT_NAME, DEFAULT_STREAM_SOURCE from .const import CONF_FRAMERATE, CONF_SECURITY_LEVEL, CONF_STREAM_PATH, DOMAIN _LOGGER = logging.getLogger(__name__) DESCRIPTION_PLACEHOLDERS = { "doc_url": "https://www.home-assistant.io/integrations/vivotek/" } CONF_SCHEMA = vol.Schema( { vol.Required(CONF_IP_ADDRESS): cv.string, vol.Required(CONF_PORT, default=80): cv.port, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Required(CONF_AUTHENTICATION, default=HTTP_BASIC_AUTHENTICATION): vol.In( [HTTP_BASIC_AUTHENTICATION, HTTP_DIGEST_AUTHENTICATION] ), vol.Required(CONF_SSL, default=False): cv.boolean, vol.Required(CONF_VERIFY_SSL, default=True): cv.boolean, vol.Required(CONF_SECURITY_LEVEL): SelectSelector( SelectSelectorConfig( options=list(SECURITY_LEVELS.keys()), mode=SelectSelectorMode.DROPDOWN, translation_key="security_level", sort=True, ), ), vol.Required( CONF_STREAM_PATH, default=DEFAULT_STREAM_SOURCE, ): cv.string, } ) OPTIONS_SCHEMA = vol.Schema( { vol.Required(CONF_FRAMERATE, default=DEFAULT_FRAMERATE): NumberSelector( NumberSelectorConfig(min=0, unit_of_measurement=UnitOfFrequency.HERTZ) ), } ) class OptionsFlowHandler(OptionsFlow): """Options flow.""" async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Manage the options.""" if user_input is not None: return self.async_create_entry( data=user_input, ) return self.async_show_form( step_id="init", data_schema=self.add_suggested_values_to_schema( OPTIONS_SCHEMA, self.config_entry.options ), ) class VivotekConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Vivotek IP cameras.""" @staticmethod @callback def async_get_options_flow( config_entry: VivotekConfigEntry, ) -> OptionsFlowHandler: """Create the options flow.""" return OptionsFlowHandler() 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: self._async_abort_entries_match( {CONF_IP_ADDRESS: user_input[CONF_IP_ADDRESS]} ) try: cam_client = build_cam_client(user_input) mac_address = await self.hass.async_add_executor_job(cam_client.get_mac) except VivotekCameraError: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected error during camera connection test") errors["base"] = "unknown" else: # prevent duplicates await self.async_set_unique_id(format_mac(mac_address)) self._abort_if_unique_id_configured() return self.async_create_entry( title=DEFAULT_NAME, data=user_input, options={CONF_FRAMERATE: DEFAULT_FRAMERATE}, ) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( CONF_SCHEMA, user_input or {} ), errors=errors, description_placeholders=DESCRIPTION_PLACEHOLDERS, ) async def async_step_import( self, import_data: (dict[str, Any]) ) -> ConfigFlowResult: """Import a Yaml config.""" self._async_abort_entries_match({CONF_IP_ADDRESS: import_data[CONF_IP_ADDRESS]}) port = 443 if import_data[CONF_SSL] else 80 try: cam_client = build_cam_client({**import_data, CONF_PORT: port}) mac_address = await self.hass.async_add_executor_job(cam_client.get_mac) except VivotekCameraError: return self.async_abort(reason="cannot_connect") except Exception: _LOGGER.exception("Unexpected error during camera connection test") return self.async_abort(reason="unknown") await self.async_set_unique_id(format_mac(mac_address)) self._abort_if_unique_id_configured() return self.async_create_entry( title=import_data.get(CONF_NAME, DEFAULT_NAME), data={ CONF_IP_ADDRESS: import_data[CONF_IP_ADDRESS], CONF_PORT: port, CONF_PASSWORD: import_data[CONF_PASSWORD], CONF_USERNAME: import_data[CONF_USERNAME], CONF_AUTHENTICATION: import_data[CONF_AUTHENTICATION], CONF_SSL: import_data[CONF_SSL], CONF_VERIFY_SSL: import_data[CONF_VERIFY_SSL], CONF_SECURITY_LEVEL: import_data[CONF_SECURITY_LEVEL], CONF_STREAM_PATH: import_data[CONF_STREAM_PATH], }, options={ CONF_FRAMERATE: import_data[CONF_FRAMERATE], }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/vivotek/config_flow.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/vivotek/const.py
"""Constants for the Vivotek integration.""" CONF_FRAMERATE = "framerate" CONF_SECURITY_LEVEL = "security_level" CONF_STREAM_PATH = "stream_path" DOMAIN = "vivotek" MANUFACTURER = "Vivotek" INTEGRATION_TITLE = "Vivotek"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/vivotek/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:homeassistant/components/watts/application_credentials.py
"""Application credentials for Watts integration.""" from homeassistant.components.application_credentials import AuthorizationServer from homeassistant.core import HomeAssistant from .const import OAUTH2_AUTHORIZE, OAUTH2_TOKEN async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer: """Return authorization server.""" return AuthorizationServer(authorize_url=OAUTH2_AUTHORIZE, token_url=OAUTH2_TOKEN)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/watts/application_credentials.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:homeassistant/components/watts/climate.py
"""Climate platform for Watts Vision integration.""" from __future__ import annotations import logging from typing import Any from visionpluspython.models import ThermostatDevice from homeassistant.components.climate import ( ClimateEntity, ClimateEntityFeature, HVACMode, ) from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import WattsVisionConfigEntry from .const import DOMAIN, HVAC_MODE_TO_THERMOSTAT, THERMOSTAT_MODE_TO_HVAC from .coordinator import WattsVisionDeviceCoordinator from .entity import WattsVisionEntity _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: WattsVisionConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Watts Vision climate entities from a config entry.""" device_coordinators = entry.runtime_data.device_coordinators known_device_ids: set[str] = set() @callback def _check_new_thermostats() -> None: """Check for new thermostat devices.""" thermostat_coords = { did: coord for did, coord in device_coordinators.items() if isinstance(coord.data.device, ThermostatDevice) } current_device_ids = set(thermostat_coords.keys()) new_device_ids = current_device_ids - known_device_ids if not new_device_ids: return _LOGGER.debug( "Adding climate entities for %d new thermostat(s)", len(new_device_ids), ) new_entities = [] for device_id in new_device_ids: coord = thermostat_coords[device_id] device = coord.data.device assert isinstance(device, ThermostatDevice) new_entities.append(WattsVisionClimate(coord, device)) known_device_ids.update(new_device_ids) async_add_entities(new_entities) _check_new_thermostats() # Listen for new thermostats entry.async_on_unload( async_dispatcher_connect( hass, f"{DOMAIN}_{entry.entry_id}_new_device", _check_new_thermostats, ) ) class WattsVisionClimate(WattsVisionEntity[ThermostatDevice], ClimateEntity): """Representation of a Watts Vision heater as a climate entity.""" _attr_supported_features = ClimateEntityFeature.TARGET_TEMPERATURE _attr_hvac_modes = [HVACMode.HEAT, HVACMode.OFF, HVACMode.AUTO] _attr_name = None def __init__( self, coordinator: WattsVisionDeviceCoordinator, thermostat: ThermostatDevice, ) -> None: """Initialize the climate entity.""" super().__init__(coordinator, thermostat.device_id) self._attr_min_temp = thermostat.min_allowed_temperature self._attr_max_temp = thermostat.max_allowed_temperature if thermostat.temperature_unit.upper() == "C": self._attr_temperature_unit = UnitOfTemperature.CELSIUS else: self._attr_temperature_unit = UnitOfTemperature.FAHRENHEIT @property def current_temperature(self) -> float | None: """Return the current temperature.""" return self.device.current_temperature @property def target_temperature(self) -> float | None: """Return the temperature setpoint.""" return self.device.setpoint @property def hvac_mode(self) -> HVACMode | None: """Return hvac mode.""" return THERMOSTAT_MODE_TO_HVAC.get(self.device.thermostat_mode) async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if temperature is None: return try: await self.coordinator.client.set_thermostat_temperature( self.device_id, temperature ) except RuntimeError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_temperature_error", ) from err _LOGGER.debug( "Successfully set temperature to %s for %s", temperature, self.device_id, ) self.coordinator.trigger_fast_polling() await self.coordinator.async_refresh() async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set new target hvac mode.""" mode = HVAC_MODE_TO_THERMOSTAT[hvac_mode] try: await self.coordinator.client.set_thermostat_mode(self.device_id, mode) except (ValueError, RuntimeError) as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_hvac_mode_error", ) from err _LOGGER.debug( "Successfully set HVAC mode to %s (ThermostatMode.%s) for %s", hvac_mode, mode.name, self.device_id, ) self.coordinator.trigger_fast_polling() await self.coordinator.async_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/watts/climate.py", "license": "Apache License 2.0", "lines": 131, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/watts/config_flow.py
"""Config flow for Watts Vision integration.""" from collections.abc import Mapping import logging from typing import Any from visionpluspython.auth import WattsVisionAuth from homeassistant.config_entries import ( SOURCE_REAUTH, SOURCE_RECONFIGURE, ConfigFlowResult, ) from homeassistant.helpers import config_entry_oauth2_flow from .const import DOMAIN, OAUTH2_SCOPES class OAuth2FlowHandler( config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN ): """Config flow to handle Watts Vision OAuth2 authentication.""" DOMAIN = DOMAIN @property def logger(self) -> logging.Logger: """Return logger.""" return logging.getLogger(__name__) @property def extra_authorize_data(self) -> dict[str, Any]: """Extra parameters for OAuth2 authentication.""" return { "scope": " ".join(OAUTH2_SCOPES), "access_type": "offline", "prompt": "consent", } async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Perform reauthentication 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 reauthentication dialog.""" if user_input is None: return self.async_show_form(step_id="reauth_confirm") return await self.async_step_pick_implementation( user_input={ "implementation": self._get_reauth_entry().data["auth_implementation"] } ) async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration of the integration.""" return await self.async_step_pick_implementation( user_input={ "implementation": self._get_reconfigure_entry().data[ "auth_implementation" ] } ) async def async_oauth_create_entry(self, data: dict[str, Any]) -> ConfigFlowResult: """Create an entry for the OAuth2 flow.""" access_token = data["token"]["access_token"] user_id = WattsVisionAuth.extract_user_id_from_token(access_token) if not user_id: return self.async_abort(reason="invalid_token") await self.async_set_unique_id(user_id) if self.source == SOURCE_REAUTH: self._abort_if_unique_id_mismatch(reason="account_mismatch") return self.async_update_reload_and_abort( self._get_reauth_entry(), data=data, ) if self.source == SOURCE_RECONFIGURE: self._abort_if_unique_id_mismatch(reason="account_mismatch") return self.async_update_reload_and_abort( self._get_reconfigure_entry(), data=data, ) self._abort_if_unique_id_configured() return self.async_create_entry( title="Watts Vision +", data=data, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/watts/config_flow.py", "license": "Apache License 2.0", "lines": 80, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/watts/const.py
"""Constants for the Watts Vision+ integration.""" from visionpluspython.models import SwitchDevice, ThermostatDevice, ThermostatMode from homeassistant.components.climate import HVACMode DOMAIN = "watts" OAUTH2_AUTHORIZE = "https://visionlogin.b2clogin.com/visionlogin.onmicrosoft.com/B2C_1A_VISION_UNIFIEDSIGNUPORSIGNIN/oauth2/v2.0/authorize" OAUTH2_TOKEN = "https://visionlogin.b2clogin.com/visionlogin.onmicrosoft.com/B2C_1A_VISION_UNIFIEDSIGNUPORSIGNIN/oauth2/v2.0/token" OAUTH2_SCOPES = [ "openid", "offline_access", "https://visionlogin.onmicrosoft.com/homeassistant-api/homeassistant.read", ] # Update intervals UPDATE_INTERVAL_SECONDS = 30 FAST_POLLING_INTERVAL_SECONDS = 5 DISCOVERY_INTERVAL_MINUTES = 15 # Mapping from Watts Vision + modes to Home Assistant HVAC modes THERMOSTAT_MODE_TO_HVAC = { "Program": HVACMode.AUTO, "Eco": HVACMode.HEAT, "Comfort": HVACMode.HEAT, "Off": HVACMode.OFF, } # Mapping from Home Assistant HVAC modes to Watts Vision + modes HVAC_MODE_TO_THERMOSTAT = { HVACMode.HEAT: ThermostatMode.COMFORT, HVACMode.OFF: ThermostatMode.OFF, HVACMode.AUTO: ThermostatMode.PROGRAM, } SUPPORTED_DEVICE_TYPES = (ThermostatDevice, SwitchDevice)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/watts/const.py", "license": "Apache License 2.0", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/watts/coordinator.py
"""Data coordinator for Watts Vision integration.""" from __future__ import annotations from dataclasses import dataclass from datetime import datetime, timedelta import logging from typing import TYPE_CHECKING from visionpluspython.client import WattsVisionClient from visionpluspython.exceptions import ( WattsVisionAuthError, WattsVisionConnectionError, WattsVisionDeviceError, WattsVisionError, WattsVisionTimeoutError, ) from visionpluspython.models import Device from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers import device_registry as dr from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ( DISCOVERY_INTERVAL_MINUTES, DOMAIN, FAST_POLLING_INTERVAL_SECONDS, UPDATE_INTERVAL_SECONDS, ) if TYPE_CHECKING: from . import WattsVisionRuntimeData type WattsVisionConfigEntry = ConfigEntry[WattsVisionRuntimeData] _LOGGER = logging.getLogger(__name__) @dataclass class WattsVisionDeviceData: """Data class for device coordinator.""" device: Device class WattsVisionHubCoordinator(DataUpdateCoordinator[dict[str, Device]]): """Hub coordinator for bulk device discovery and updates.""" def __init__( self, hass: HomeAssistant, client: WattsVisionClient, config_entry: WattsVisionConfigEntry, ) -> None: """Initialize the hub coordinator.""" super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=UPDATE_INTERVAL_SECONDS), config_entry=config_entry, ) self.client = client self.last_discovery: datetime | None = None self.previous_devices: set[str] = set() async def _async_update_data(self) -> dict[str, Device]: """Fetch data and periodic device discovery.""" now = datetime.now() is_first_refresh = self.last_discovery is None discovery_interval_elapsed = ( self.last_discovery is not None and now - self.last_discovery >= timedelta(minutes=DISCOVERY_INTERVAL_MINUTES) ) if is_first_refresh or discovery_interval_elapsed: try: devices_list = await self.client.discover_devices() except WattsVisionAuthError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="authentication_failed", ) from err except ( WattsVisionConnectionError, WattsVisionTimeoutError, WattsVisionDeviceError, WattsVisionError, ConnectionError, TimeoutError, ValueError, ) as err: if is_first_refresh: raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="failed_to_discover_devices", ) from err _LOGGER.warning( "Periodic discovery failed: %s, falling back to update", err ) else: self.last_discovery = now devices = {device.device_id: device for device in devices_list} current_devices = set(devices.keys()) if stale_devices := self.previous_devices - current_devices: await self._remove_stale_devices(stale_devices) self.previous_devices = current_devices return devices # Regular update of existing devices device_ids = list(self.data.keys()) if not device_ids: return {} try: devices = await self.client.get_devices_report(device_ids) except WattsVisionAuthError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="authentication_failed", ) from err except ( WattsVisionConnectionError, WattsVisionTimeoutError, WattsVisionDeviceError, WattsVisionError, ConnectionError, TimeoutError, ValueError, ) as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="failed_to_update_devices", ) from err _LOGGER.debug("Updated %d devices", len(devices)) return devices async def _remove_stale_devices(self, stale_device_ids: set[str]) -> None: """Remove stale devices.""" assert self.config_entry is not None device_registry = dr.async_get(self.hass) for device_id in stale_device_ids: _LOGGER.info("Removing stale device: %s", device_id) device = device_registry.async_get_device(identifiers={(DOMAIN, device_id)}) if device: device_registry.async_update_device( device_id=device.id, remove_config_entry_id=self.config_entry.entry_id, ) @property def device_ids(self) -> list[str]: """Get list of all device IDs.""" return list((self.data or {}).keys()) class WattsVisionDeviceCoordinator(DataUpdateCoordinator[WattsVisionDeviceData]): """Device coordinator for individual updates.""" def __init__( self, hass: HomeAssistant, client: WattsVisionClient, config_entry: WattsVisionConfigEntry, hub_coordinator: WattsVisionHubCoordinator, device_id: str, ) -> None: """Initialize the device coordinator.""" super().__init__( hass, _LOGGER, name=f"{DOMAIN}_{device_id}", update_interval=None, # Manual refresh only config_entry=config_entry, ) self.client = client self.device_id = device_id self.hub_coordinator = hub_coordinator self.fast_polling_until: datetime | None = None # Listen to hub coordinator updates self.unsubscribe_hub_listener = hub_coordinator.async_add_listener( self._handle_hub_update ) def _handle_hub_update(self) -> None: """Handle updates from hub coordinator.""" if self.hub_coordinator.data and self.device_id in self.hub_coordinator.data: device = self.hub_coordinator.data[self.device_id] self.async_set_updated_data(WattsVisionDeviceData(device=device)) async def _async_update_data(self) -> WattsVisionDeviceData: """Refresh specific device.""" if self.fast_polling_until and datetime.now() > self.fast_polling_until: self.fast_polling_until = None self.update_interval = None _LOGGER.debug( "Device %s: Fast polling period ended, returning to manual refresh", self.device_id, ) try: device = await self.client.get_device(self.device_id, refresh=True) except ( WattsVisionAuthError, WattsVisionConnectionError, WattsVisionTimeoutError, WattsVisionDeviceError, WattsVisionError, ConnectionError, TimeoutError, ValueError, ) as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="failed_to_refresh_device", translation_placeholders={"device_id": self.device_id}, ) from err if not device: raise UpdateFailed( translation_domain=DOMAIN, translation_key="device_not_found", translation_placeholders={"device_id": self.device_id}, ) _LOGGER.debug("Refreshed device %s", self.device_id) return WattsVisionDeviceData(device=device) def trigger_fast_polling(self, duration: int = 60) -> None: """Activate fast polling for a specified duration after a command.""" self.fast_polling_until = datetime.now() + timedelta(seconds=duration) self.update_interval = timedelta(seconds=FAST_POLLING_INTERVAL_SECONDS) _LOGGER.debug( "Device %s: Activated fast polling for %d seconds", self.device_id, duration )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/watts/coordinator.py", "license": "Apache License 2.0", "lines": 209, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/watts/entity.py
"""Base entity for Watts Vision integration.""" from __future__ import annotations from typing import cast from visionpluspython.models import Device from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import WattsVisionDeviceCoordinator class WattsVisionEntity[_T: Device](CoordinatorEntity[WattsVisionDeviceCoordinator]): """Base entity for Watts Vision devices.""" _attr_has_entity_name = True def __init__( self, coordinator: WattsVisionDeviceCoordinator, device_id: str ) -> None: """Initialize the entity.""" super().__init__(coordinator, context=device_id) self.device_id = device_id self._attr_unique_id = device_id device = coordinator.data.device self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, self.device_id)}, name=device.device_name, manufacturer="Watts", model=f"Vision+ {device.device_type}", suggested_area=device.room_name, ) @property def device(self) -> _T: """Return the device from the coordinator data.""" return cast(_T, self.coordinator.data.device) @property def available(self) -> bool: """Return True if entity is available.""" return super().available and self.coordinator.data.device.is_online
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/watts/entity.py", "license": "Apache License 2.0", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/wmspro/switch.py
"""Support for loads connected with WMS WebControl pro.""" from __future__ import annotations from datetime import timedelta from typing import Any from wmspro.const import ( WMS_WebControl_pro_API_actionDescription, WMS_WebControl_pro_API_responseType, ) from homeassistant.components.switch import SwitchEntity from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import WebControlProConfigEntry from .entity import WebControlProGenericEntity SCAN_INTERVAL = timedelta(seconds=15) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, config_entry: WebControlProConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the WMS based switches from a config entry.""" hub = config_entry.runtime_data async_add_entities( WebControlProSwitch(config_entry.entry_id, dest) for dest in hub.dests.values() if dest.hasAction(WMS_WebControl_pro_API_actionDescription.LoadSwitch) ) class WebControlProSwitch(WebControlProGenericEntity, SwitchEntity): """Representation of a WMS based switch.""" _attr_name = None @property def is_on(self) -> bool: """Return true if switch is on.""" action = self._dest.action(WMS_WebControl_pro_API_actionDescription.LoadSwitch) return action["onOffState"] async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" action = self._dest.action(WMS_WebControl_pro_API_actionDescription.LoadSwitch) await action( onOffState=True, responseType=WMS_WebControl_pro_API_responseType.Detailed ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" action = self._dest.action(WMS_WebControl_pro_API_actionDescription.LoadSwitch) await action( onOffState=False, responseType=WMS_WebControl_pro_API_responseType.Detailed )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/wmspro/switch.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/wsdot/config_flow.py
"""Adds config flow for wsdot.""" import logging from types import MappingProxyType from typing import Any import voluptuous as vol import wsdot as wsdot_api from homeassistant.config_entries import ( SOURCE_USER, ConfigEntry, ConfigFlow, ConfigFlowResult, ConfigSubentry, ConfigSubentryFlow, SubentryFlowResult, ) from homeassistant.const import CONF_API_KEY, CONF_ID, CONF_NAME from homeassistant.core import callback from homeassistant.helpers.selector import SelectSelector, SelectSelectorConfig from .const import CONF_TRAVEL_TIMES, DOMAIN, SUBENTRY_TRAVEL_TIMES _LOGGER = logging.getLogger(__name__) class WSDOTConfigFlow(ConfigFlow, domain=DOMAIN): """Config flow for WSDOT.""" VERSION = 1 MINOR_VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a flow initialized by the user.""" errors = {} if user_input is not None: data = {CONF_API_KEY: user_input[CONF_API_KEY]} self._async_abort_entries_match(data) wsdot_travel_times = wsdot_api.WsdotTravelTimes(user_input[CONF_API_KEY]) try: await wsdot_travel_times.get_all_travel_times() except wsdot_api.WsdotTravelError as ws_error: if ws_error.status == 400: errors[CONF_API_KEY] = "invalid_api_key" else: errors["base"] = "cannot_connect" else: return self.async_create_entry( title=DOMAIN, data=data, ) return self.async_show_form( step_id=SOURCE_USER, data_schema=vol.Schema( { vol.Required(CONF_API_KEY): str, } ), errors=errors, ) async def async_step_import(self, import_info: dict[str, Any]) -> ConfigFlowResult: """Handle a flow initialized by import.""" self._async_abort_entries_match({CONF_API_KEY: import_info[CONF_API_KEY]}) wsdot_travel_times = wsdot_api.WsdotTravelTimes(import_info[CONF_API_KEY]) try: travel_time_routes = await wsdot_travel_times.get_all_travel_times() except wsdot_api.WsdotTravelError as ws_error: if ws_error.status == 400: return self.async_abort(reason="invalid_api_key") return self.async_abort(reason="cannot_connect") subentries = [] for route in import_info[CONF_TRAVEL_TIMES]: maybe_travel_time = [ tt for tt in travel_time_routes # old platform configs could store the id as either a str or an int if str(tt.TravelTimeID) == str(route[CONF_ID]) ] if not maybe_travel_time: return self.async_abort(reason="invalid_travel_time_id") travel_time = maybe_travel_time[0] route_name = travel_time.Name unique_id = "_".join(travel_time.Name.split()) subentries.append( ConfigSubentry( subentry_type=SUBENTRY_TRAVEL_TIMES, unique_id=unique_id, title=route_name, data=MappingProxyType( {CONF_NAME: travel_time.Name, CONF_ID: travel_time.TravelTimeID} ), ).as_dict() ) return self.async_create_entry( title=DOMAIN, data={ CONF_API_KEY: import_info[CONF_API_KEY], }, subentries=subentries, ) @classmethod @callback def async_get_supported_subentry_types( cls, config_entry: ConfigEntry ) -> dict[str, type[ConfigSubentryFlow]]: """Return subentries supported by wsdot.""" return {SUBENTRY_TRAVEL_TIMES: TravelTimeSubentryFlowHandler} class TravelTimeSubentryFlowHandler(ConfigSubentryFlow): """Handle subentry flow for adding WSDOT Travel Times.""" def __init__(self, *args, **kwargs) -> None: """Initialize TravelTimeSubentryFlowHandler.""" super().__init__(*args, **kwargs) self.travel_times: dict[str, int] | None = None async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Add a new Travel Time subentry.""" if self.travel_times is None: client = self._get_entry().runtime_data travel_times = await client.get_all_travel_times() self.travel_times = {tt.Name: tt.TravelTimeID for tt in travel_times} if user_input is not None: name = user_input[CONF_NAME] tt_id = self.travel_times[name] unique_id = str(tt_id) data = {CONF_NAME: name, CONF_ID: tt_id} 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") return self.async_create_entry(title=name, unique_id=unique_id, data=data) names = SelectSelector( SelectSelectorConfig( options=list(self.travel_times.keys()), sort=True, ) ) return self.async_show_form( step_id=SOURCE_USER, data_schema=vol.Schema({vol.Required(CONF_NAME): names}), errors={}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/wsdot/config_flow.py", "license": "Apache License 2.0", "lines": 136, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/wsdot/const.py
"""Constants for wsdot component.""" ATTRIBUTION = "Data provided by WSDOT" CONF_DATA = "data" CONF_TITLE = "title" CONF_TRAVEL_TIMES = "travel_time" DOMAIN = "wsdot" SUBENTRY_TRAVEL_TIMES = "travel_time"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/wsdot/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/actron_air/test_switch.py
"""Tests for the Actron Air switch platform.""" from unittest.mock import MagicMock, patch from actron_neo_api import ActronAirAPIError 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.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_switch_entities( hass: HomeAssistant, mock_actron_api: MagicMock, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, ) -> None: """Test switch entities.""" with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.SWITCH]): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.parametrize( ("entity_id", "method"), [ ("switch.test_system_away_mode", "set_away_mode"), ("switch.test_system_continuous_fan", "set_continuous_mode"), ("switch.test_system_quiet_mode", "set_quiet_mode"), ("switch.test_system_turbo_mode", "set_turbo_mode"), ], ) async def test_switch_toggles( hass: HomeAssistant, mock_actron_api: MagicMock, mock_config_entry: MockConfigEntry, entity_id: str, method: str, ) -> None: """Test switch toggles.""" with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.SWITCH]): await setup_integration(hass, mock_config_entry) status = mock_actron_api.state_manager.get_status.return_value mock_method = getattr(status.user_aircon_settings, method) await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: [entity_id]}, blocking=True, ) mock_method.assert_awaited_once_with(True) mock_method.reset_mock() await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: [entity_id]}, blocking=True, ) mock_method.assert_awaited_once_with(False) async def test_turbo_mode_not_supported( hass: HomeAssistant, mock_actron_api: MagicMock, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, ) -> None: """Test turbo mode switch is not created when not supported.""" status = mock_actron_api.state_manager.get_status.return_value status.user_aircon_settings.turbo_supported = False await setup_integration(hass, mock_config_entry) entity_id = "switch.test_system_turbo_mode" assert not hass.states.get(entity_id) assert not entity_registry.async_get(entity_id) @pytest.mark.parametrize( ("entity_id", "method", "service"), [ ("switch.test_system_away_mode", "set_away_mode", SERVICE_TURN_ON), ("switch.test_system_continuous_fan", "set_continuous_mode", SERVICE_TURN_OFF), ("switch.test_system_quiet_mode", "set_quiet_mode", SERVICE_TURN_ON), ("switch.test_system_turbo_mode", "set_turbo_mode", SERVICE_TURN_OFF), ], ) async def test_switch_api_error( hass: HomeAssistant, mock_actron_api: MagicMock, mock_config_entry: MockConfigEntry, entity_id: str, method: str, service: str, ) -> None: """Test API error handling when toggling switches.""" with patch("homeassistant.components.actron_air.PLATFORMS", [Platform.SWITCH]): await setup_integration(hass, mock_config_entry) status = mock_actron_api.state_manager.get_status.return_value mock_method = getattr(status.user_aircon_settings, method) mock_method.side_effect = ActronAirAPIError("Test error") with pytest.raises(HomeAssistantError, match="Test error"): await hass.services.async_call( SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: [entity_id]}, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/actron_air/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:tests/components/adguard/test_switch.py
"""Tests for the AdGuard Home switch entity.""" from collections.abc import Callable import logging from typing import Any from unittest.mock import AsyncMock from adguardhome import AdGuardHomeError import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.switch import 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 @pytest.fixture def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return [Platform.SWITCH] pytestmark = pytest.mark.usefixtures("init_integration") @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_switch( hass: HomeAssistant, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, ) -> None: """Test the adguard switch platform.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("entity_registry_enabled_by_default") @pytest.mark.parametrize( ("switch_name", "service", "call_assertion"), [ ( "protection", SERVICE_TURN_ON, lambda mock: mock.enable_protection.assert_called_once(), ), ( "protection", SERVICE_TURN_OFF, lambda mock: mock.disable_protection.assert_called_once(), ), ( "parental_control", SERVICE_TURN_ON, lambda mock: mock.parental.enable.assert_called_once(), ), ( "parental_control", SERVICE_TURN_OFF, lambda mock: mock.parental.disable.assert_called_once(), ), ( "safe_search", SERVICE_TURN_ON, lambda mock: mock.safesearch.enable.assert_called_once(), ), ( "safe_search", SERVICE_TURN_OFF, lambda mock: mock.safesearch.disable.assert_called_once(), ), ( "safe_browsing", SERVICE_TURN_ON, lambda mock: mock.safebrowsing.enable.assert_called_once(), ), ( "safe_browsing", SERVICE_TURN_OFF, lambda mock: mock.safebrowsing.disable.assert_called_once(), ), ( "filtering", SERVICE_TURN_ON, lambda mock: mock.filtering.enable.assert_called_once(), ), ( "filtering", SERVICE_TURN_OFF, lambda mock: mock.filtering.disable.assert_called_once(), ), ( "query_log", SERVICE_TURN_ON, lambda mock: mock.querylog.enable.assert_called_once(), ), ( "query_log", SERVICE_TURN_OFF, lambda mock: mock.querylog.disable.assert_called_once(), ), ], ) async def test_switch_actions( hass: HomeAssistant, mock_adguard: AsyncMock, switch_name: str, service: str, call_assertion: Callable[[AsyncMock], Any], ) -> None: """Test the adguard switch actions.""" await hass.services.async_call( "switch", service, {ATTR_ENTITY_ID: f"switch.adguard_home_{switch_name}"}, blocking=True, ) call_assertion(mock_adguard) @pytest.mark.parametrize( ("service", "expected_message"), [ ( SERVICE_TURN_ON, "An error occurred while turning on AdGuard Home switch", ), ( SERVICE_TURN_OFF, "An error occurred while turning off AdGuard Home switch", ), ], ) async def test_switch_action_failed( hass: HomeAssistant, mock_adguard: AsyncMock, caplog: pytest.LogCaptureFixture, service: str, expected_message: str, ) -> None: """Test the adguard switch actions.""" caplog.set_level(logging.ERROR) mock_adguard.enable_protection.side_effect = AdGuardHomeError("Boom") mock_adguard.disable_protection.side_effect = AdGuardHomeError("Boom") await hass.services.async_call( "switch", service, {ATTR_ENTITY_ID: "switch.adguard_home_protection"}, blocking=True, ) assert expected_message in caplog.text
{ "repo_id": "home-assistant/core", "file_path": "tests/components/adguard/test_switch.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:tests/components/airobot/test_diagnostics.py
"""Test the Airobot diagnostics.""" 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_entry_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, init_integration: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test config entry diagnostics.""" result = await get_diagnostics_for_config_entry(hass, hass_client, init_integration) assert result == snapshot
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airobot/test_diagnostics.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airobot/test_number.py
"""Test the Airobot number platform.""" from unittest.mock import AsyncMock from pyairobotrest.exceptions import AirobotError import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.number import ( ATTR_VALUE, DOMAIN as NUMBER_DOMAIN, SERVICE_SET_VALUE, ) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError import homeassistant.helpers.entity_registry as er from tests.common import MockConfigEntry, snapshot_platform @pytest.fixture def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return [Platform.NUMBER] @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_number_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test the number entities.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_number_set_hysteresis_band( hass: HomeAssistant, mock_airobot_client: AsyncMock, ) -> None: """Test setting hysteresis band value.""" await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, { ATTR_ENTITY_ID: "number.test_thermostat_hysteresis_band", ATTR_VALUE: 0.3, }, blocking=True, ) mock_airobot_client.set_hysteresis_band.assert_called_once_with(0.3) @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_number_set_value_error( hass: HomeAssistant, mock_airobot_client: AsyncMock, ) -> None: """Test error handling when setting number value fails.""" mock_airobot_client.set_hysteresis_band.side_effect = AirobotError("Device error") with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, { ATTR_ENTITY_ID: "number.test_thermostat_hysteresis_band", ATTR_VALUE: 0.3, }, blocking=True, ) assert exc_info.value.translation_domain == "airobot" assert exc_info.value.translation_key == "set_value_failed"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airobot/test_number.py", "license": "Apache License 2.0", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airobot/test_sensor.py
"""Tests for the Airobot sensor platform.""" import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform @pytest.fixture def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return [Platform.SENSOR] @pytest.mark.freeze_time("2024-01-01 00:00:00+00:00") @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_sensors( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test the sensor entities.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_sensor_availability_without_optional_sensors( hass: HomeAssistant, ) -> None: """Test sensors are not created when optional hardware is not present.""" # Default mock has no floor sensor, CO2, or AQI - they should not be created assert hass.states.get("sensor.test_thermostat_floor_temperature") is None assert hass.states.get("sensor.test_thermostat_carbon_dioxide") is None assert hass.states.get("sensor.test_thermostat_air_quality_index") is None
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airobot/test_sensor.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airpatrol/test_climate.py
"""Test the AirPatrol climate platform.""" from collections.abc import Generator from datetime import timedelta from typing import Any from unittest.mock import patch from airpatrol.api import AirPatrolAPI from freezegun.api import FrozenDateTimeFactory import pytest from homeassistant.components.airpatrol.climate import ( HA_TO_AP_FAN_MODES, HA_TO_AP_HVAC_MODES, HA_TO_AP_SWING_MODES, ) from homeassistant.components.climate import ( ATTR_FAN_MODE, ATTR_HVAC_MODE, ATTR_SWING_MODE, DOMAIN as CLIMATE_DOMAIN, FAN_HIGH, FAN_LOW, SERVICE_SET_FAN_MODE, SERVICE_SET_HVAC_MODE, SERVICE_SET_SWING_MODE, SERVICE_SET_TEMPERATURE, SWING_OFF, SWING_ON, HVACMode, ) from homeassistant.const import ( ATTR_TEMPERATURE, CONF_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, Platform, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import ( MockConfigEntry, SnapshotAssertion, async_fire_time_changed, snapshot_platform, ) @pytest.fixture(autouse=True) def override_platforms() -> Generator[None]: """Override the platforms to load for airpatrol.""" with patch( "homeassistant.components.airpatrol.PLATFORMS", [Platform.CLIMATE], ): yield @pytest.mark.parametrize( "climate_data", [ { "ParametersData": { "PumpPower": "on", "PumpTemp": "22.000", "PumpMode": "cool", "FanSpeed": "max", "Swing": "off", }, "RoomTemp": "22.5", "RoomHumidity": "45", }, None, ], ) async def test_climate_entities( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test climate.""" await snapshot_platform( hass, entity_registry, snapshot, load_integration.entry_id, ) async def test_climate_entity_unavailable( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, get_data: dict[str, Any], freezer: FrozenDateTimeFactory, ) -> None: """Test climate entity when climate data is missing.""" state = hass.states.get("climate.living_room") assert state assert state.state == HVACMode.COOL get_data[0]["climate"] = None freezer.tick(timedelta(minutes=1)) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get("climate.living_room") assert state assert state.state == "unavailable" async def test_climate_set_temperature( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, climate_data: dict[str, Any], ) -> None: """Test setting temperature.""" TARGET_TEMP = 25.0 state = hass.states.get("climate.living_room") assert state.attributes[ATTR_TEMPERATURE] == 22.0 climate_data["ParametersData"]["PumpTemp"] = f"{TARGET_TEMP:.3f}" await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, { CONF_ENTITY_ID: state.entity_id, ATTR_TEMPERATURE: TARGET_TEMP, }, ) get_client.set_unit_climate_data.assert_called_once() state = hass.states.get("climate.living_room") assert state.attributes[ATTR_TEMPERATURE] == TARGET_TEMP async def test_climate_set_hvac_mode( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, climate_data: dict[str, Any], ) -> None: """Test setting HVAC mode.""" state = hass.states.get("climate.living_room") assert state.state == HVACMode.COOL climate_data["ParametersData"]["PumpMode"] = HA_TO_AP_HVAC_MODES[HVACMode.HEAT] await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, { CONF_ENTITY_ID: state.entity_id, ATTR_HVAC_MODE: HVACMode.HEAT, }, ) get_client.set_unit_climate_data.assert_called_once() state = hass.states.get("climate.living_room") assert state.state == HVACMode.HEAT async def test_climate_set_fan_mode( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, climate_data: dict[str, Any], ) -> None: """Test setting fan mode.""" state = hass.states.get("climate.living_room") assert state.attributes[ATTR_FAN_MODE] == FAN_HIGH climate_data["ParametersData"]["FanSpeed"] = HA_TO_AP_FAN_MODES[FAN_LOW] await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_FAN_MODE, { CONF_ENTITY_ID: state.entity_id, ATTR_FAN_MODE: FAN_LOW, }, ) get_client.set_unit_climate_data.assert_called_once() state = hass.states.get("climate.living_room") assert state.attributes[ATTR_FAN_MODE] == FAN_LOW async def test_climate_set_swing_mode( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, climate_data: dict[str, Any], ) -> None: """Test setting swing mode.""" state = hass.states.get("climate.living_room") assert state.attributes[ATTR_SWING_MODE] == SWING_OFF climate_data["ParametersData"]["Swing"] = HA_TO_AP_SWING_MODES[SWING_ON] await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_SWING_MODE, { CONF_ENTITY_ID: state.entity_id, ATTR_SWING_MODE: SWING_ON, }, ) get_client.set_unit_climate_data.assert_called_once() state = hass.states.get("climate.living_room") assert state.attributes[ATTR_SWING_MODE] == SWING_ON @pytest.mark.parametrize( "climate_data", [ { "ParametersData": { "PumpPower": "off", "PumpTemp": "22.000", "PumpMode": "cool", "FanSpeed": "max", "Swing": "off", }, "RoomTemp": "22.5", "RoomHumidity": "45", } ], ) async def test_climate_turn_on( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, climate_data: dict[str, Any], ) -> None: """Test turning climate on.""" state = hass.states.get("climate.living_room") assert state.state == HVACMode.OFF climate_data["ParametersData"]["PumpPower"] = "on" await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_TURN_ON, { CONF_ENTITY_ID: state.entity_id, }, ) get_client.set_unit_climate_data.assert_called_once() state = hass.states.get("climate.living_room") assert state.state == HVACMode.COOL async def test_climate_turn_off( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, climate_data: dict[str, Any], ) -> None: """Test turning climate off.""" state = hass.states.get("climate.living_room") assert state.state == HVACMode.COOL climate_data["ParametersData"]["PumpPower"] = "off" await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_TURN_OFF, { CONF_ENTITY_ID: state.entity_id, }, ) get_client.set_unit_climate_data.assert_called_once() state = hass.states.get("climate.living_room") assert state.state == HVACMode.OFF @pytest.mark.parametrize( "climate_data", [ { "ParametersData": { "PumpPower": "on", "PumpTemp": "22.000", "PumpMode": "heat", "FanSpeed": "max", "Swing": "off", }, "RoomTemp": "22.5", "RoomHumidity": "45", } ], ) async def test_climate_heat_mode( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, ) -> None: """Test climate in heat mode.""" state = hass.states.get("climate.living_room") assert state.state == HVACMode.HEAT async def test_climate_set_temperature_api_error( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, ) -> None: """Test async_set_temperature handles API error.""" state = hass.states.get("climate.living_room") assert state.attributes[ATTR_TEMPERATURE] == 22.0 get_client.set_unit_climate_data.side_effect = Exception("API Error") await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, { CONF_ENTITY_ID: state.entity_id, ATTR_TEMPERATURE: 25.0, }, ) state = hass.states.get("climate.living_room") assert state.attributes[ATTR_TEMPERATURE] == 22.0 @pytest.mark.parametrize( "climate_data", [ { "ParametersData": { "PumpPower": "off", "PumpTemp": "22.000", "PumpMode": "cool", "FanSpeed": "sideways", "Swing": "off", }, "RoomTemp": "22.5", "RoomHumidity": "45", } ], ) async def test_climate_fan_mode_invalid( hass: HomeAssistant, get_client: AirPatrolAPI, get_data: dict[str, Any], load_integration: MockConfigEntry, ) -> None: """Test fan_mode with unexpected value.""" state = hass.states.get("climate.living_room") assert state.attributes[ATTR_FAN_MODE] is None @pytest.mark.parametrize( "climate_data", [ { "ParametersData": { "PumpPower": "off", "PumpTemp": "22.000", "PumpMode": "cool", "FanSpeed": "max", "Swing": "sideways", }, "RoomTemp": "22.5", "RoomHumidity": "45", } ], ) async def test_climate_swing_mode_invalid( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, ) -> None: """Test swing_mode with unexpected value.""" state = hass.states.get("climate.living_room") assert state.attributes[ATTR_SWING_MODE] is None
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airpatrol/test_climate.py", "license": "Apache License 2.0", "lines": 333, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airpatrol/test_config_flow.py
"""Test the AirPatrol config flow.""" from unittest.mock import patch from airpatrol.api import AirPatrolAPI, AirPatrolAuthenticationError, AirPatrolError import pytest from homeassistant.components.airpatrol.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_ACCESS_TOKEN, CONF_EMAIL, CONF_PASSWORD from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry TEST_USER_INPUT = { CONF_EMAIL: "test@example.com", CONF_PASSWORD: "test_password", } async def test_user_flow_success( hass: HomeAssistant, get_client: AirPatrolAPI, ) -> 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" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_USER_INPUT ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == TEST_USER_INPUT[CONF_EMAIL] assert result["data"] == { **TEST_USER_INPUT, CONF_ACCESS_TOKEN: "test_access_token", } assert result["result"].unique_id == "test_user_id" async def test_async_step_reauth_confirm_success( hass: HomeAssistant, mock_config_entry: MockConfigEntry, get_client: AirPatrolAPI ) -> None: """Test successful reauthentication via async_step_reauth_confirm.""" 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"], user_input=TEST_USER_INPUT ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data[CONF_PASSWORD] == "test_password" assert mock_config_entry.data[CONF_ACCESS_TOKEN] == "test_access_token" async def test_async_step_reauth_confirm_invalid_auth( hass: HomeAssistant, mock_config_entry: MockConfigEntry, get_client: AirPatrolAPI, ) -> None: """Test reauthentication failure due to invalid credentials.""" 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" with patch( "homeassistant.components.airpatrol.config_flow.AirPatrolAPI.authenticate", side_effect=AirPatrolAuthenticationError("fail"), ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_USER_INPUT ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" assert result["errors"] == {"base": "invalid_auth"} result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_USER_INPUT, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert mock_config_entry.data[CONF_PASSWORD] == "test_password" assert mock_config_entry.data[CONF_ACCESS_TOKEN] == "test_access_token" async def test_async_step_reauth_confirm_another_account_failure( hass: HomeAssistant, mock_config_entry: MockConfigEntry, get_client: AirPatrolAPI ) -> None: """Test reauthentication failure due to another 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"] == "reauth_confirm" get_client.get_unique_id.return_value = "different_user_id" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_EMAIL: "test2@example.com", CONF_PASSWORD: "test_password2"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "unique_id_mismatch" @pytest.mark.parametrize( ("side_effect", "expected_error"), [ (AirPatrolError("fail"), "cannot_connect"), (AirPatrolAuthenticationError("fail"), "invalid_auth"), ], ) async def test_user_flow_error( hass: HomeAssistant, side_effect, expected_error, get_client: AirPatrolAPI, ) -> None: """Test user flow with invalid authentication.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" with patch( "homeassistant.components.airpatrol.config_flow.AirPatrolAPI.authenticate", side_effect=side_effect, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_USER_INPUT ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": expected_error} result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_USER_INPUT ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == TEST_USER_INPUT[CONF_EMAIL] assert result["data"] == { **TEST_USER_INPUT, CONF_ACCESS_TOKEN: "test_access_token", } assert result["result"].unique_id == "test_user_id" async def test_user_flow_already_configured( hass: HomeAssistant, get_client: AirPatrolAPI, mock_config_entry: MockConfigEntry, ) -> None: """Test user flow when 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"], user_input=TEST_USER_INPUT ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airpatrol/test_config_flow.py", "license": "Apache License 2.0", "lines": 147, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airpatrol/test_init.py
"""Test the AirPatrol integration setup.""" from unittest.mock import patch from airpatrol.api import AirPatrolAPI, AirPatrolAuthenticationError from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant, State from tests.common import MockConfigEntry async def test_load_unload_config_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, get_client: AirPatrolAPI, ) -> None: """Test loading and unloading the config entry.""" # Add the config entry to hass first mock_config_entry.add_to_hass(hass) # Load the config entry 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 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 async def test_update_data_refresh_token_success( hass: HomeAssistant, mock_config_entry: MockConfigEntry, get_client: AirPatrolAPI, get_data, ) -> None: """Test data update with expired token and successful token refresh.""" get_client.get_data.side_effect = [ AirPatrolAuthenticationError("fail"), get_data, ] 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 get_client.get_data.call_count == 2 assert hass.states.get("climate.living_room") async def test_update_data_auth_failure( hass: HomeAssistant, mock_config_entry: MockConfigEntry, get_client: AirPatrolAPI, ) -> None: """Test permanent authentication failure.""" mock_config_entry.add_to_hass(hass) with patch( "homeassistant.components.airpatrol.coordinator.AirPatrolAPI.authenticate", side_effect=AirPatrolAuthenticationError("fail"), ): get_client.get_data.side_effect = AirPatrolAuthenticationError("fail") await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() state: State | None = hass.states.get("climate.living_room") assert state is None entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id) assert entry.state is ConfigEntryState.SETUP_ERROR assert entry.reason == "Authentication with AirPatrol failed"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airpatrol/test_init.py", "license": "Apache License 2.0", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airpatrol/test_sensor.py
"""Test the AirPatrol sensor platform.""" from collections.abc import Generator from unittest.mock import patch from airpatrol.api import AirPatrolAPI import pytest from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, SnapshotAssertion, snapshot_platform @pytest.fixture(autouse=True) def override_platforms() -> Generator[None]: """Override the platforms to load for airpatrol.""" with patch( "homeassistant.components.airpatrol.PLATFORMS", [Platform.SENSOR], ): yield async def test_sensor_with_climate_data( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test sensor entities are created with climate data.""" await snapshot_platform( hass, entity_registry, snapshot, load_integration.entry_id, ) @pytest.mark.parametrize( "climate_data", [ None, ], ) async def test_sensor_with_no_climate_data( hass: HomeAssistant, load_integration: MockConfigEntry, get_client: AirPatrolAPI, entity_registry: er.EntityRegistry, ) -> None: """Test no sensor entities are created when no climate data is present.""" assert len(entity_registry.entities) == 0
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airpatrol/test_sensor.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/anglian_water/test_coordinator.py
"""Tests for the Anglian Water coordinator.""" from unittest.mock import AsyncMock from pyanglianwater.meter import SmartMeter import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.anglian_water.coordinator import ( AnglianWaterUpdateCoordinator, ) from homeassistant.components.recorder import Recorder from homeassistant.components.recorder.statistics import ( get_last_statistics, statistics_during_period, ) from homeassistant.core import HomeAssistant from homeassistant.util import dt as dt_util from .const import ACCOUNT_NUMBER from tests.common import MockConfigEntry from tests.components.recorder.common import async_wait_recording_done async def test_coordinator_first_run( recorder_mock: Recorder, hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_anglian_water_client: AsyncMock, snapshot: SnapshotAssertion, ) -> None: """Test the coordinator on its first run with no existing statistics.""" coordinator = AnglianWaterUpdateCoordinator( hass, mock_anglian_water_client, mock_config_entry ) await coordinator._async_update_data() await async_wait_recording_done(hass) stats = await hass.async_add_executor_job( statistics_during_period, hass, dt_util.utc_from_timestamp(0), None, { f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage", }, "hour", None, {"state", "sum"}, ) assert stats == snapshot async def test_coordinator_subsequent_run( recorder_mock: Recorder, hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_smart_meter: SmartMeter, mock_anglian_water_client: AsyncMock, snapshot: SnapshotAssertion, ) -> None: """Test the coordinator correctly updates statistics on subsequent runs.""" # 1st run coordinator = AnglianWaterUpdateCoordinator( hass, mock_anglian_water_client, mock_config_entry ) await coordinator._async_update_data() await async_wait_recording_done(hass) # 2nd run with an updated reading for one read and a new read added. mock_smart_meter.readings[-1] = { "read_at": "2024-06-01T14:00:00Z", "consumption": 35, "read": 70, } mock_smart_meter.readings.append( {"read_at": "2024-06-01T15:00:00Z", "consumption": 20, "read": 90} ) await coordinator._async_update_data() await async_wait_recording_done(hass) # Check all stats stats = await hass.async_add_executor_job( statistics_during_period, hass, dt_util.utc_from_timestamp(0), None, { f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage", }, "hour", None, {"state", "sum"}, ) assert stats == snapshot async def test_coordinator_subsequent_run_no_energy_data( recorder_mock: Recorder, hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_smart_meter: SmartMeter, mock_anglian_water_client: AsyncMock, caplog: pytest.LogCaptureFixture, ) -> None: """Test the coordinator handles no recent usage/cost data.""" # 1st run coordinator = AnglianWaterUpdateCoordinator( hass, mock_anglian_water_client, mock_config_entry ) await coordinator._async_update_data() await async_wait_recording_done(hass) # 2nd run with no readings mock_smart_meter.readings = [] await coordinator._async_update_data() assert "No recent usage statistics found, skipping update" in caplog.text # Verify no new stats were added by checking the sum remains 50 statistic_id = f"anglian_water:{ACCOUNT_NUMBER}_testsn_usage" stats = await hass.async_add_executor_job( get_last_statistics, hass, 1, statistic_id, True, {"sum"} ) assert stats[statistic_id][0]["sum"] == 50 async def test_coordinator_invalid_readings( recorder_mock: Recorder, hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_smart_meter: SmartMeter, mock_anglian_water_client: AsyncMock, caplog: pytest.LogCaptureFixture, ) -> None: """Test the coordinator handles bad data / invalid readings correctly.""" coordinator = AnglianWaterUpdateCoordinator( hass, mock_anglian_water_client, mock_config_entry ) await coordinator._async_update_data() await async_wait_recording_done(hass) # Test that an invalid read_at on the first reading skips the entire update mock_smart_meter.readings = [ {"read_at": "invalid-date-format", "consumption": 10, "read": 10}, ] await coordinator._async_update_data() assert ( "Could not parse read_at time invalid-date-format, skipping update" in caplog.text ) # Test that individual invalid readings are skipped mock_smart_meter.readings = [ {"read_at": "2024-06-01T12:00:00Z", "consumption": 10, "read": 10}, {"read_at": "also-invalid-date", "consumption": 15, "read": 25}, ] await coordinator._async_update_data() assert ( "Could not parse read_at time also-invalid-date, skipping reading" in caplog.text )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/anglian_water/test_coordinator.py", "license": "Apache License 2.0", "lines": 142, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/bsblan/test_services.py
"""Tests for BSB-LAN services.""" from datetime import time from typing import Any from unittest.mock import MagicMock from bsblan import BSBLANError, DaySchedule, DeviceTime, TimeSlot from freezegun.api import FrozenDateTimeFactory import pytest import voluptuous as vol from homeassistant.components.bsblan.const import DOMAIN from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import device_registry as dr from homeassistant.util import dt as dt_util from tests.common import MockConfigEntry # Test constants TEST_DEVICE_MAC = "00:80:41:19:69:90" @pytest.fixture async def setup_integration( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bsblan: MagicMock, ) -> None: """Set up the BSB-LAN integration for testing.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() @pytest.fixture def device_entry( device_registry: dr.DeviceRegistry, setup_integration: None, ) -> dr.DeviceEntry: """Get the device entry for testing.""" device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_DEVICE_MAC)}) assert device is not None return device @pytest.mark.usefixtures("setup_integration") @pytest.mark.parametrize( ("service_data", "expected_schedules"), [ ( { "monday_slots": [ {"start_time": time(6, 0), "end_time": time(8, 0)}, {"start_time": time(17, 0), "end_time": time(21, 0)}, ], "tuesday_slots": [ {"start_time": time(6, 0), "end_time": time(8, 0)}, ], }, { "monday": DaySchedule( slots=[ TimeSlot(start=time(6, 0), end=time(8, 0)), TimeSlot(start=time(17, 0), end=time(21, 0)), ] ), "tuesday": DaySchedule( slots=[TimeSlot(start=time(6, 0), end=time(8, 0))] ), }, ), ( { "friday_slots": [ {"start_time": time(17, 0), "end_time": time(21, 0)}, ], "saturday_slots": [ {"start_time": time(8, 0), "end_time": time(22, 0)}, ], }, { "friday": DaySchedule( slots=[TimeSlot(start=time(17, 0), end=time(21, 0))] ), "saturday": DaySchedule( slots=[TimeSlot(start=time(8, 0), end=time(22, 0))] ), }, ), ( { "wednesday_slots": [ {"start_time": time(6, 0), "end_time": time(8, 0)}, ], }, { "wednesday": DaySchedule( slots=[TimeSlot(start=time(6, 0), end=time(8, 0))] ), }, ), ( { "monday_slots": [], # Empty array (shouldn't happen in UI) }, { "monday": DaySchedule(slots=[]), }, ), ], ids=[ "multiple_slots_per_day", "weekend_schedule", "single_day", "clear_schedule_with_empty_array", ], ) async def test_set_hot_water_schedule( hass: HomeAssistant, mock_bsblan: MagicMock, device_entry: dr.DeviceEntry, service_data: dict[str, Any], expected_schedules: dict[str, DaySchedule], ) -> None: """Test setting hot water schedule with various configurations.""" # Call the service with device_id and slot fields service_call_data = {"device_id": device_entry.id} service_call_data.update(service_data) await hass.services.async_call( DOMAIN, "set_hot_water_schedule", service_call_data, blocking=True, ) # Verify the service was called correctly assert len(mock_bsblan.set_hot_water_schedule.mock_calls) == 1 call_args = mock_bsblan.set_hot_water_schedule.call_args # Verify expected values - all values are in the DHWSchedule object dhw_schedule = call_args.args[0] for key, expected_schedule in expected_schedules.items(): actual_schedule = getattr(dhw_schedule, key) assert actual_schedule == expected_schedule async def test_invalid_device_id( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bsblan: MagicMock, ) -> None: """Test error when device ID is invalid.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, "set_hot_water_schedule", { "device_id": "invalid_device_id", "monday_slots": [ {"start_time": time(6, 0), "end_time": time(8, 0)}, ], }, blocking=True, ) assert exc_info.value.translation_key == "invalid_device_id" @pytest.mark.usefixtures("setup_integration") @pytest.mark.parametrize( ("service_name", "service_data"), [ ( "set_hot_water_schedule", {"monday_slots": [{"start_time": time(6, 0), "end_time": time(8, 0)}]}, ), ("sync_time", {}), ], ids=["set_hot_water_schedule", "sync_time"], ) async def test_no_config_entry_for_device( hass: HomeAssistant, device_registry: dr.DeviceRegistry, service_name: str, service_data: dict[str, Any], ) -> None: """Test error when device has no matching BSB-LAN config entry.""" # Create a different config entry (not for bsblan) other_entry = MockConfigEntry(domain="other_domain", data={}) other_entry.add_to_hass(hass) # Create a device for that other entry device_entry = device_registry.async_get_or_create( config_entry_id=other_entry.entry_id, identifiers={("other_domain", "other_device")}, name="Other Device", ) with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, service_name, {"device_id": device_entry.id, **service_data}, blocking=True, ) assert exc_info.value.translation_key == "no_config_entry_for_device" async def test_config_entry_not_loaded( hass: HomeAssistant, mock_config_entry: MockConfigEntry, device_entry: dr.DeviceEntry, ) -> None: """Test error when config entry is not loaded.""" await hass.config_entries.async_unload(mock_config_entry.entry_id) with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, "set_hot_water_schedule", { "device_id": device_entry.id, "monday_slots": [ {"start_time": time(6, 0), "end_time": time(8, 0)}, ], }, blocking=True, ) assert exc_info.value.translation_key == "config_entry_not_loaded" @pytest.mark.usefixtures("setup_integration") async def test_api_error( hass: HomeAssistant, mock_bsblan: MagicMock, device_entry: dr.DeviceEntry, ) -> None: """Test error when BSB-LAN API call fails.""" mock_bsblan.set_hot_water_schedule.side_effect = BSBLANError("API Error") with pytest.raises(HomeAssistantError) as exc_info: await hass.services.async_call( DOMAIN, "set_hot_water_schedule", { "device_id": device_entry.id, "monday_slots": [ {"start_time": time(6, 0), "end_time": time(8, 0)}, ], }, blocking=True, ) assert exc_info.value.translation_key == "set_schedule_failed" @pytest.mark.usefixtures("setup_integration") @pytest.mark.parametrize( ("start_time", "end_time", "expected_error"), [ (time(13, 0), time(11, 0), "end_time_before_start_time"), ("13:00", "11:00", "end_time_before_start_time"), ], ids=[ "time_objects_end_before_start", "strings_end_before_start", ], ) async def test_time_validation_errors( hass: HomeAssistant, device_entry: dr.DeviceEntry, start_time: time | str, end_time: time | str, expected_error: str, ) -> None: """Test validation errors for various time input scenarios.""" with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, "set_hot_water_schedule", { "device_id": device_entry.id, "monday_slots": [ {"start_time": start_time, "end_time": end_time}, ], }, blocking=True, ) assert exc_info.value.translation_key == expected_error @pytest.mark.usefixtures("setup_integration") async def test_unprovided_days_are_none( hass: HomeAssistant, mock_bsblan: MagicMock, device_entry: dr.DeviceEntry, ) -> None: """Test that unprovided days are sent as None to BSB-LAN API.""" # Only provide Monday and Tuesday, leave other days unprovided await hass.services.async_call( DOMAIN, "set_hot_water_schedule", { "device_id": device_entry.id, "monday_slots": [ {"start_time": time(6, 0), "end_time": time(8, 0)}, ], "tuesday_slots": [ {"start_time": time(17, 0), "end_time": time(21, 0)}, ], }, blocking=True, ) # Verify the API was called assert mock_bsblan.set_hot_water_schedule.called call_args = mock_bsblan.set_hot_water_schedule.call_args dhw_schedule = call_args.args[0] # Verify provided days have values assert dhw_schedule.monday == DaySchedule( slots=[TimeSlot(start=time(6, 0), end=time(8, 0))] ) assert dhw_schedule.tuesday == DaySchedule( slots=[TimeSlot(start=time(17, 0), end=time(21, 0))] ) # Verify unprovided days are None (not empty DaySchedule) assert dhw_schedule.wednesday is None assert dhw_schedule.thursday is None assert dhw_schedule.friday is None assert dhw_schedule.saturday is None assert dhw_schedule.sunday is None @pytest.mark.usefixtures("setup_integration") async def test_string_time_formats( hass: HomeAssistant, mock_bsblan: MagicMock, device_entry: dr.DeviceEntry, ) -> None: """Test service with string time formats.""" # Test with string time formats await hass.services.async_call( DOMAIN, "set_hot_water_schedule", { "device_id": device_entry.id, "monday_slots": [ {"start_time": "06:00:00", "end_time": "08:00:00"}, # With seconds ], "tuesday_slots": [ {"start_time": "17:00", "end_time": "21:00"}, # Without seconds ], }, blocking=True, ) # Verify the API was called assert mock_bsblan.set_hot_water_schedule.called call_args = mock_bsblan.set_hot_water_schedule.call_args dhw_schedule = call_args.args[0] # Should parse both formats correctly (seconds are stripped) assert dhw_schedule.monday == DaySchedule( slots=[TimeSlot(start=time(6, 0), end=time(8, 0))] ) assert dhw_schedule.tuesday == DaySchedule( slots=[TimeSlot(start=time(17, 0), end=time(21, 0))] ) @pytest.mark.usefixtures("setup_integration") async def test_non_standard_time_types( hass: HomeAssistant, device_entry: dr.DeviceEntry, ) -> None: """Test service with non-standard time types raises error.""" # Test with integer time values - schema validation will reject these with pytest.raises(vol.MultipleInvalid): await hass.services.async_call( DOMAIN, "set_hot_water_schedule", { "device_id": device_entry.id, "monday_slots": [ {"start_time": 600, "end_time": 800}, ], }, blocking=True, ) async def test_async_setup_services( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bsblan: MagicMock, ) -> None: """Test service registration.""" # Verify service doesn't exist initially assert not hass.services.has_service(DOMAIN, "set_hot_water_schedule") # Set up the integration 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 service is now registered assert hass.services.has_service(DOMAIN, "set_hot_water_schedule") async def test_sync_time_service( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bsblan: MagicMock, device_registry: dr.DeviceRegistry, freezer: FrozenDateTimeFactory, ) -> None: """Test the sync_time service.""" 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 the device device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_DEVICE_MAC)}) assert device is not None # Mock device time that differs from HA time mock_bsblan.time.return_value = DeviceTime.model_validate_json( '{"time": {"name": "Time", "value": "01.01.2020 00:00:00", "unit": "", "desc": "", "dataType": 0, "readonly": 0, "error": 0}}' ) # Call the service await hass.services.async_call( DOMAIN, "sync_time", {"device_id": device.id}, blocking=True, ) # Verify time() was called to check current device time assert mock_bsblan.time.called # Verify set_time() was called with current HA time current_time_str = dt_util.now().strftime("%d.%m.%Y %H:%M:%S") mock_bsblan.set_time.assert_called_once_with(current_time_str) async def test_sync_time_service_no_update_when_same( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bsblan: MagicMock, device_registry: dr.DeviceRegistry, freezer: FrozenDateTimeFactory, ) -> None: """Test the sync_time service doesn't update when time matches.""" 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 the device device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_DEVICE_MAC)}) assert device is not None # Mock device time that matches HA time current_time_str = dt_util.now().strftime("%d.%m.%Y %H:%M:%S") mock_bsblan.time.return_value = DeviceTime.model_validate_json( f'{{"time": {{"name": "Time", "value": "{current_time_str}", "unit": "", "desc": "", "dataType": 0, "readonly": 0, "error": 0}}}}' ) # Call the service await hass.services.async_call( DOMAIN, "sync_time", {"device_id": device.id}, blocking=True, ) # Verify time() was called assert mock_bsblan.time.called # Verify set_time() was NOT called since times match assert not mock_bsblan.set_time.called async def test_sync_time_service_error_handling( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bsblan: MagicMock, device_registry: dr.DeviceRegistry, ) -> None: """Test the sync_time service handles errors gracefully.""" 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 the device device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_DEVICE_MAC)}) assert device is not None # Mock time() to raise an error mock_bsblan.time.side_effect = BSBLANError("Connection failed") # Call the service - should raise HomeAssistantError with pytest.raises(HomeAssistantError, match="Failed to sync time"): await hass.services.async_call( DOMAIN, "sync_time", {"device_id": device.id}, blocking=True, ) async def test_sync_time_service_set_time_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bsblan: MagicMock, device_registry: dr.DeviceRegistry, ) -> None: """Test the sync_time service handles set_time errors.""" 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 the device device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_DEVICE_MAC)}) assert device is not None # Mock device time that differs mock_bsblan.time.return_value = DeviceTime.model_validate_json( '{"time": {"name": "Time", "value": "01.01.2020 00:00:00", "unit": "", "desc": "", "dataType": 0, "readonly": 0, "error": 0}}' ) # Mock set_time() to raise an error mock_bsblan.set_time.side_effect = BSBLANError("Write failed") # Call the service - should raise HomeAssistantError with pytest.raises(HomeAssistantError, match="Failed to sync time"): await hass.services.async_call( DOMAIN, "sync_time", {"device_id": device.id}, blocking=True, ) async def test_sync_time_service_entry_not_found( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bsblan: MagicMock, ) -> None: """Test the sync_time service raises error for non-existent device.""" # Set up the entry (this registers the service) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Call the service with a non-existent device ID with pytest.raises(ServiceValidationError): await hass.services.async_call( DOMAIN, "sync_time", {"device_id": "non_existent_device_id"}, blocking=True, ) async def test_sync_time_service_entry_not_loaded( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_bsblan: MagicMock, device_registry: dr.DeviceRegistry, ) -> None: """Test the sync_time service raises error for unloaded entry.""" # Set up the first entry (this registers the service) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Create a second unloaded entry unloaded_entry = MockConfigEntry( domain=DOMAIN, title="Unloaded BSBLAN", data=mock_config_entry.data.copy(), unique_id="unloaded_unique_id", ) unloaded_entry.add_to_hass(hass) # Don't call async_setup on this entry, so it stays NOT_LOADED # Manually register a device for this unloaded entry unloaded_device = device_registry.async_get_or_create( config_entry_id=unloaded_entry.entry_id, identifiers={(DOMAIN, "unloaded_device_mac")}, name="Unloaded Device", ) # Call the service with the device from the unloaded entry - should raise error with pytest.raises(ServiceValidationError): await hass.services.async_call( DOMAIN, "sync_time", {"device_id": unloaded_device.id}, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/bsblan/test_services.py", "license": "Apache License 2.0", "lines": 531, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/button/test_trigger.py
"""Test button trigger.""" import pytest from homeassistant.const import ( ATTR_LABEL_ID, CONF_ENTITY_ID, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import HomeAssistant, ServiceCall from tests.components import ( TriggerStateDescription, arm_trigger, parametrize_target_entities, set_or_remove_state, target_entities, ) @pytest.fixture async def target_buttons(hass: HomeAssistant) -> list[str]: """Create multiple button entities associated with different targets.""" return (await target_entities(hass, "button"))["included"] @pytest.mark.parametrize("trigger_key", ["button.pressed"]) async def test_button_triggers_gated_by_labs_flag( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str ) -> None: """Test the button triggers are gated by the labs flag.""" await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"}) assert ( "Unnamed automation failed to setup triggers and has been disabled: Trigger " f"'{trigger_key}' requires the experimental 'New triggers and conditions' " "feature to be enabled in Home Assistant Labs settings (feature flag: " "'new_triggers_conditions')" ) in caplog.text @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("button"), ) @pytest.mark.parametrize( ("trigger", "states"), [ ( "button.pressed", [ {"included": {"state": None, "attributes": {}}, "count": 0}, { "included": { "state": "2021-01-01T23:59:59+00:00", "attributes": {}, }, "count": 0, }, { "included": { "state": "2022-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, ], ), ( "button.pressed", [ {"included": {"state": "foo", "attributes": {}}, "count": 0}, { "included": { "state": "2021-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, { "included": { "state": "2022-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, ], ), ( "button.pressed", [ { "included": {"state": STATE_UNAVAILABLE, "attributes": {}}, "count": 0, }, { "included": { "state": "2021-01-01T23:59:59+00:00", "attributes": {}, }, "count": 0, }, { "included": { "state": "2022-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, { "included": {"state": STATE_UNAVAILABLE, "attributes": {}}, "count": 0, }, ], ), ( "button.pressed", [ {"included": {"state": STATE_UNKNOWN, "attributes": {}}, "count": 0}, { "included": { "state": "2021-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, { "included": { "state": "2022-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, {"included": {"state": STATE_UNKNOWN, "attributes": {}}, "count": 0}, ], ), ], ) async def test_button_state_trigger_behavior_any( hass: HomeAssistant, service_calls: list[ServiceCall], target_buttons: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, states: list[TriggerStateDescription], ) -> None: """Test that the button state trigger fires when any button state changes to a specific state.""" other_entity_ids = set(target_buttons) - {entity_id} # Set all buttons, including the tested button, to the initial state for eid in target_buttons: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, None, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Check if changing other buttons also triggers for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == (entities_in_target - 1) * state["count"] service_calls.clear()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/button/test_trigger.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/cookidoo/test_calendar.py
"""Test for calendar platform of the Cookidoo integration.""" from collections.abc import Generator from datetime import UTC, datetime from unittest.mock import AsyncMock, patch import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.config_entries import ConfigEntryState 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 @pytest.fixture(autouse=True) def calendar_only() -> Generator[None]: """Enable only the calendar platform.""" with patch( "homeassistant.components.cookidoo.PLATFORMS", [Platform.CALENDAR], ): yield @pytest.mark.usefixtures("mock_cookidoo_client") async def test_calendar( hass: HomeAssistant, cookidoo_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, ) -> None: """Snapshot test states of calendar platform.""" with patch("homeassistant.components.cookidoo.PLATFORMS", [Platform.CALENDAR]): await setup_integration(hass, cookidoo_config_entry) assert cookidoo_config_entry.state is ConfigEntryState.LOADED await snapshot_platform( hass, entity_registry, snapshot, cookidoo_config_entry.entry_id ) @pytest.mark.usefixtures("entity_registry_enabled_by_default") @pytest.mark.usefixtures("mock_cookidoo_client") async def test_get_events( hass: HomeAssistant, cookidoo_config_entry: MockConfigEntry, mock_cookidoo_client: AsyncMock, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test fetching events from Cookidoo calendar.""" with patch("homeassistant.components.cookidoo.PLATFORMS", [Platform.CALENDAR]): await setup_integration(hass, cookidoo_config_entry) assert cookidoo_config_entry.state is ConfigEntryState.LOADED entities = er.async_entries_for_config_entry( entity_registry, cookidoo_config_entry.entry_id ) assert len(entities) == 1 entity_id = entities[0].entity_id resp = await hass.services.async_call( "calendar", "get_events", { "start_date_time": datetime(2025, 3, 4, tzinfo=UTC), "end_date_time": datetime(2025, 3, 6, tzinfo=UTC), }, target={"entity_id": entity_id}, blocking=True, return_response=True, ) assert resp == snapshot
{ "repo_id": "home-assistant/core", "file_path": "tests/components/cookidoo/test_calendar.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/device_tracker/test_trigger.py
"""Test device_tracker trigger.""" from typing import Any import pytest from homeassistant.const import ( ATTR_LABEL_ID, CONF_ENTITY_ID, STATE_HOME, STATE_NOT_HOME, ) from homeassistant.core import HomeAssistant, ServiceCall from tests.components import ( TriggerStateDescription, arm_trigger, parametrize_target_entities, parametrize_trigger_states, set_or_remove_state, target_entities, ) STATE_WORK_ZONE = "work" @pytest.fixture async def target_device_trackers(hass: HomeAssistant) -> list[str]: """Create multiple device_trackers entities associated with different targets.""" return (await target_entities(hass, "device_tracker"))["included"] @pytest.mark.parametrize( "trigger_key", ["device_tracker.entered_home", "device_tracker.left_home"], ) async def test_device_tracker_triggers_gated_by_labs_flag( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str ) -> None: """Test the device_tracker triggers are gated by the labs flag.""" await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"}) assert ( "Unnamed automation failed to setup triggers and has been disabled: Trigger " f"'{trigger_key}' requires the experimental 'New triggers and conditions' " "feature to be enabled in Home Assistant Labs settings (feature flag: " "'new_triggers_conditions')" ) in caplog.text @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("device_tracker"), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="device_tracker.entered_home", target_states=[STATE_HOME], other_states=[STATE_NOT_HOME, STATE_WORK_ZONE], ), *parametrize_trigger_states( trigger="device_tracker.left_home", target_states=[STATE_NOT_HOME, STATE_WORK_ZONE], other_states=[STATE_HOME], ), ], ) async def test_device_tracker_home_trigger_behavior_any( hass: HomeAssistant, service_calls: list[ServiceCall], target_device_trackers: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the device_tracker home triggers when any device_tracker changes to a specific state.""" other_entity_ids = set(target_device_trackers) - {entity_id} # Set all device_trackers, including the tested device_tracker, to the initial state for eid in target_device_trackers: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Check that changing other device_trackers also triggers for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == (entities_in_target - 1) * state["count"] service_calls.clear() @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("device_tracker"), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="device_tracker.entered_home", target_states=[STATE_HOME], other_states=[STATE_NOT_HOME, STATE_WORK_ZONE], ), *parametrize_trigger_states( trigger="device_tracker.left_home", target_states=[STATE_NOT_HOME, STATE_WORK_ZONE], other_states=[STATE_HOME], ), ], ) async def test_device_tracker_state_trigger_behavior_first( hass: HomeAssistant, service_calls: list[ServiceCall], target_device_trackers: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the device_tracker home triggers when the first device_tracker changes to a specific state.""" other_entity_ids = set(target_device_trackers) - {entity_id} # Set all device_trackers, including the tested device_tracker, to the initial state for eid in target_device_trackers: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Triggering other device_trackers should not cause the trigger to fire again for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("device_tracker"), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="device_tracker.entered_home", target_states=[STATE_HOME], other_states=[STATE_NOT_HOME, STATE_WORK_ZONE], ), *parametrize_trigger_states( trigger="device_tracker.left_home", target_states=[STATE_NOT_HOME, STATE_WORK_ZONE], other_states=[STATE_HOME], ), ], ) async def test_device_tracker_state_trigger_behavior_last( hass: HomeAssistant, service_calls: list[ServiceCall], target_device_trackers: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the device_tracker home triggers when the last device_tracker changes to a specific state.""" other_entity_ids = set(target_device_trackers) - {entity_id} # Set all device_trackers, including the tested device_tracker, to the initial state for eid in target_device_trackers: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config) for state in states[1:]: included_state = state["included"] for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/device_tracker/test_trigger.py", "license": "Apache License 2.0", "lines": 191, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/egauge/test_config_flow.py
"""Tests for the eGauge config flow.""" from unittest.mock import MagicMock from egauge_async.exceptions import EgaugeAuthenticationError, EgaugePermissionError from httpx import ConnectError import pytest from homeassistant.components.egauge.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry async def test_user_flow(hass: HomeAssistant) -> None: """Test the full happy path user flow from start to finish.""" 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"], user_input={ CONF_HOST: "192.168.1.100", CONF_USERNAME: "admin", CONF_PASSWORD: "secret", CONF_SSL: True, CONF_VERIFY_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "egauge-home" assert result["data"] == { CONF_HOST: "192.168.1.100", CONF_USERNAME: "admin", CONF_PASSWORD: "secret", CONF_SSL: True, CONF_VERIFY_SSL: False, } assert result["result"].unique_id == "ABC123456" @pytest.mark.parametrize( ("side_effect", "expected_error"), [ (EgaugeAuthenticationError, "invalid_auth"), (EgaugePermissionError, "missing_permission"), (ConnectError("Connection error"), "cannot_connect"), (Exception("Unexpected error"), "unknown"), ], ) async def test_user_flow_errors( hass: HomeAssistant, mock_egauge_client: MagicMock, side_effect: Exception, expected_error: str, ) -> None: """Test user flow with various errors.""" mock_egauge_client.get_device_serial_number.side_effect = side_effect result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={ CONF_HOST: "192.168.1.100", CONF_USERNAME: "admin", CONF_PASSWORD: "wrong", CONF_SSL: True, CONF_VERIFY_SSL: False, }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": expected_error} # Test recovery after error mock_egauge_client.get_device_serial_number.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={ CONF_HOST: "192.168.1.100", CONF_USERNAME: "admin", CONF_PASSWORD: "secret", CONF_SSL: True, CONF_VERIFY_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "egauge-home" assert result["data"] == { CONF_HOST: "192.168.1.100", CONF_USERNAME: "admin", CONF_PASSWORD: "secret", CONF_SSL: True, CONF_VERIFY_SSL: False, } assert result["result"].unique_id == "ABC123456" async def test_user_flow_already_configured( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: """Test configuration flow aborts when device is already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data={ CONF_HOST: "http://192.168.1.200", CONF_USERNAME: "admin", CONF_PASSWORD: "secret", CONF_SSL: True, CONF_VERIFY_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/egauge/test_config_flow.py", "license": "Apache License 2.0", "lines": 116, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/egauge/test_init.py
"""Tests for the eGauge integration.""" from unittest.mock import MagicMock from egauge_async.exceptions import ( EgaugeAuthenticationError, EgaugeParsingException, EgaugePermissionError, ) from httpx import ConnectError import pytest from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry async def test_setup_success( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_egauge_client: MagicMock, ) -> None: """Test successful setup.""" 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 ConfigEntryState.LOADED assert mock_egauge_client.get_device_serial_number.called assert mock_egauge_client.get_hostname.called assert mock_egauge_client.get_register_info.called @pytest.mark.parametrize( ("exception", "expected"), [ (ConnectError, ConfigEntryState.SETUP_RETRY), (EgaugeAuthenticationError, ConfigEntryState.SETUP_ERROR), (EgaugePermissionError, ConfigEntryState.SETUP_ERROR), (EgaugeParsingException, ConfigEntryState.SETUP_ERROR), ], ) async def test_setup_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_egauge_client: MagicMock, exception: Exception, expected: ConfigEntryState, ) -> None: """Test setup with connection error.""" mock_config_entry.add_to_hass(hass) mock_egauge_client.get_device_serial_number.side_effect = exception await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is expected async def test_unload_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_egauge_client: MagicMock, ) -> None: """Test unloading a config entry.""" 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 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/egauge/test_init.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/egauge/test_sensor.py
"""Tests for the eGauge sensor platform.""" from datetime import timedelta from unittest.mock import MagicMock from egauge_async.exceptions import EgaugeAuthenticationError from freezegun.api import FrozenDateTimeFactory from httpx import ConnectError import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.egauge.const import DOMAIN from homeassistant.const import STATE_UNAVAILABLE 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("init_integration") @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_sensors( 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) # Verify main device created with hostname device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "ABC123456")}) assert device_entry assert device_entry == snapshot @pytest.mark.parametrize( "exception", [EgaugeAuthenticationError, ConnectError("Connection failed")] ) @pytest.mark.freeze_time("2025-01-15T10:00:00+00:00") async def test_sensor_error( hass: HomeAssistant, mock_egauge_client: MagicMock, freezer: FrozenDateTimeFactory, exception: Exception, ) -> None: """Test errors that occur after setup are handled.""" # Trigger exception on next update mock_egauge_client.get_current_measurements.side_effect = exception # Trigger update freezer.tick(timedelta(seconds=30)) async_fire_time_changed(hass) await hass.async_block_till_done(wait_background_tasks=True) # Test Grid power sensor state = hass.states.get("sensor.egauge_home_grid_power") assert state assert state.state == STATE_UNAVAILABLE # Test Grid energy sensor state = hass.states.get("sensor.egauge_home_grid_energy") assert state assert state.state == STATE_UNAVAILABLE # Clear exception mock_egauge_client.get_current_measurements.side_effect = None # Trigger update freezer.tick(timedelta(seconds=30)) async_fire_time_changed(hass) await hass.async_block_till_done(wait_background_tasks=True) # Test Grid power sensor is available state = hass.states.get("sensor.egauge_home_grid_power") assert state assert state.state == "1500.0" # Test Grid energy sensor is available state = hass.states.get("sensor.egauge_home_grid_energy") assert state assert state.state == "125.0" @pytest.mark.freeze_time("2025-01-15T10:00:00+00:00") async def test_register_removed( hass: HomeAssistant, mock_egauge_client: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test case where a register is removed on the eGauge device.""" # Remove "Grid" register original_measurements = await mock_egauge_client.get_current_measurements() original_counters = await mock_egauge_client.get_current_counters() new_measurements = {k: v for k, v in original_measurements.items() if k != "Grid"} new_counters = {k: v for k, v in original_counters.items() if k != "Grid"} mock_egauge_client.get_current_measurements.return_value = new_measurements mock_egauge_client.get_current_counters.return_value = new_counters # Trigger update freezer.tick(timedelta(seconds=30)) async_fire_time_changed(hass) await hass.async_block_till_done(wait_background_tasks=True) # Test Grid power sensor state = hass.states.get("sensor.egauge_home_grid_power") assert state assert state.state == STATE_UNAVAILABLE # Test Grid energy sensor state = hass.states.get("sensor.egauge_home_grid_energy") assert state assert state.state == STATE_UNAVAILABLE # Test that other sensors still work state = hass.states.get("sensor.egauge_home_solar_power") assert state assert state.state == "-2500.0" state = hass.states.get("sensor.egauge_home_solar_energy") assert state assert state.state == "87.5" # Restore "Grid" register mock_egauge_client.get_current_measurements.return_value = original_measurements mock_egauge_client.get_current_counters.return_value = original_counters # Trigger update freezer.tick(timedelta(seconds=30)) async_fire_time_changed(hass) await hass.async_block_till_done(wait_background_tasks=True) # Test Grid power sensor is available state = hass.states.get("sensor.egauge_home_grid_power") assert state assert state.state == "1500.0" # Test Grid energy sensor is available state = hass.states.get("sensor.egauge_home_grid_energy") assert state assert state.state == "125.0"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/egauge/test_sensor.py", "license": "Apache License 2.0", "lines": 115, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/ekeybionyx/test_event.py
"""Test the ekey bionyx event platform.""" from http import HTTPStatus from aiohttp.test_utils import TestClient from homeassistant.components.event import ATTR_EVENT_TYPE, ATTR_EVENT_TYPES from homeassistant.config_entries import ConfigEntryState from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry async def test_event_entity_setup( hass: HomeAssistant, load_config_entry: None, config_entry: MockConfigEntry ) -> None: """Test event entity is set up correctly.""" # Check that entity was created state = hass.states.get(f"event.{config_entry.data['webhooks'][0]['name']}") assert state is not None assert state.state == STATE_UNKNOWN async def test_event_types_attribute( hass: HomeAssistant, load_config_entry: None, config_entry: MockConfigEntry ) -> None: """Test event entity has correct event_types attribute.""" state = hass.states.get(f"event.{config_entry.data['webhooks'][0]['name']}") assert state is not None # Check event_types attribute event_types = state.attributes.get(ATTR_EVENT_TYPES) assert event_types is not None assert event_types == ["event happened"] async def test_config_entry_unload( hass: HomeAssistant, load_config_entry: None, config_entry: MockConfigEntry, ) -> None: """Test config entry can be unloaded.""" assert config_entry.state is ConfigEntryState.LOADED # Verify entity exists state = hass.states.get(f"event.{config_entry.data['webhooks'][0]['name']}") assert state is not None assert state.state == STATE_UNKNOWN # Unload config entry await hass.config_entries.async_unload(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.NOT_LOADED # Entity should become unavailable state = hass.states.get(f"event.{config_entry.data['webhooks'][0]['name']}") assert state is not None assert state.state == STATE_UNAVAILABLE async def test_webhook_handler_triggers_event( hass: HomeAssistant, config_entry: MockConfigEntry, webhook_test_env: TestClient, ) -> None: """Test webhook handler triggers event via HTTP request.""" webhook_data = config_entry.data["webhooks"][0] state = hass.states.get(f"event.{config_entry.data['webhooks'][0]['name']}") assert state is not None assert state.state == STATE_UNKNOWN response = await webhook_test_env.post( f"/api/webhook/{webhook_data['webhook_id']}", json={"auth": webhook_data["auth"]}, ) assert response.status == HTTPStatus.OK await hass.async_block_till_done() state = hass.states.get(f"event.{config_entry.data['webhooks'][0]['name']}") assert state is not None assert state.state not in (STATE_UNKNOWN, None) assert state.attributes.get(ATTR_EVENT_TYPE) == "event happened" async def test_webhook_handler_rejects_invalid_auth( hass: HomeAssistant, config_entry: MockConfigEntry, webhook_test_env: TestClient, ) -> None: """Test webhook handler ignores requests with invalid auth.""" webhook_data = config_entry.data["webhooks"][0] response = await webhook_test_env.post( f"/api/webhook/{webhook_data['webhook_id']}", json={"auth": "invalid"}, ) assert response.status == HTTPStatus.UNAUTHORIZED await hass.async_block_till_done() state = hass.states.get(f"event.{config_entry.data['webhooks'][0]['name']}") assert state is not None assert state.state == STATE_UNKNOWN async def test_webhook_handler_missing_auth( hass: HomeAssistant, config_entry: MockConfigEntry, webhook_test_env: TestClient, ) -> None: """Test webhook handler requires the auth field.""" webhook_data = config_entry.data["webhooks"][0] response = await webhook_test_env.post( f"/api/webhook/{webhook_data['webhook_id']}", json={"not_auth": "value"}, ) assert response.status == HTTPStatus.BAD_REQUEST await hass.async_block_till_done() state = hass.states.get(f"event.{config_entry.data['webhooks'][0]['name']}") assert state is not None assert state.state == STATE_UNKNOWN async def test_webhook_handler_invalid_json( hass: HomeAssistant, config_entry: MockConfigEntry, webhook_test_env: TestClient, ) -> None: """Test webhook handler rejects invalid JSON payloads.""" webhook_data = config_entry.data["webhooks"][0] response = await webhook_test_env.post( f"/api/webhook/{webhook_data['webhook_id']}", data="not json", headers={"Content-Type": "application/json"}, ) assert response.status == HTTPStatus.BAD_REQUEST await hass.async_block_till_done() state = hass.states.get(f"event.{config_entry.data['webhooks'][0]['name']}") assert state is not None assert state.state == STATE_UNKNOWN
{ "repo_id": "home-assistant/core", "file_path": "tests/components/ekeybionyx/test_event.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:tests/components/fish_audio/const.py
"""Constants for the Testing of the Fish Audio text-to-speech integration.""" from unittest.mock import MagicMock from fishaudio.types import Voice from fishaudio.types.account import Credits MOCK_VOICE_1 = MagicMock(spec=Voice) MOCK_VOICE_1.id = "voice-alpha" MOCK_VOICE_1.title = "Alpha Voice" MOCK_VOICE_1.languages = ["en", "es"] MOCK_VOICE_1.task_count = 1000 MOCK_VOICE_2 = MagicMock(spec=Voice) MOCK_VOICE_2.id = "voice-beta" MOCK_VOICE_2.title = "Beta Voice" MOCK_VOICE_2.languages = ["en", "zh"] MOCK_VOICE_2.task_count = 500 MOCK_VOICES = [MOCK_VOICE_1, MOCK_VOICE_2] MOCK_CREDITS = MagicMock(spec=Credits) MOCK_CREDITS.user_id = "test_user"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fish_audio/const.py", "license": "Apache License 2.0", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fish_audio/test_config_flow.py
"""Config flow tests for Fish Audio.""" from __future__ import annotations from unittest.mock import AsyncMock from fishaudio import AuthenticationError, FishAudioError import pytest from homeassistant.components.fish_audio.const import ( CONF_BACKEND, CONF_LANGUAGE, CONF_LATENCY, CONF_NAME, CONF_SELF_ONLY, CONF_SORT_BY, CONF_TITLE, CONF_USER_ID, CONF_VOICE_ID, DOMAIN, ) 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_user_flow_happy_path( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_setup_entry: AsyncMock, ) -> None: """Test the full user flow happy 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"], user_input={CONF_API_KEY: "test-key"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Fish Audio" assert result["data"] == {CONF_API_KEY: "test-key", CONF_USER_ID: "test_user"} assert result["result"].unique_id == "test_user" @pytest.mark.parametrize( ("side_effect", "error_base"), [ (FishAudioError("Connection error"), "cannot_connect"), (AuthenticationError(401, "Invalid API key"), "invalid_auth"), (Exception("Unexpected error"), "unknown"), ], ) async def test_user_flow_api_error( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_setup_entry: AsyncMock, side_effect: Exception, error_base: str, ) -> None: """Test user flow with API errors during validation and recovery.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) # Simulate the error mock_fishaudio_client.account.get_credits.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_API_KEY: "bad-key"} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": error_base} mock_setup_entry.assert_not_called() # Clear the error and retry successfully mock_fishaudio_client.account.get_credits.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_API_KEY: "test-key"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Fish Audio" assert result["data"] == {CONF_API_KEY: "test-key", CONF_USER_ID: "test_user"} assert result["result"].unique_id == "test_user" mock_setup_entry.assert_called_once() async def test_user_flow_already_configured( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_fishaudio_client: AsyncMock, ) -> None: """Test that the user flow is aborted if already configured.""" 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"], user_input={CONF_API_KEY: "test-api-key"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_subflow_happy_path( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test the full subflow happy path.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, "tts"), context={"source": SOURCE_USER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "init" result = await hass.config_entries.subentries.async_configure( result["flow_id"], user_input={ CONF_TITLE: "", CONF_LANGUAGE: "en", CONF_SORT_BY: "task_count", CONF_SELF_ONLY: False, }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "model" result = await hass.config_entries.subentries.async_configure( result["flow_id"], user_input={ CONF_VOICE_ID: "voice-alpha", CONF_BACKEND: "s1", CONF_LATENCY: "balanced", CONF_NAME: "My Custom Voice", }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "My Custom Voice" assert result["data"][CONF_VOICE_ID] == "voice-alpha" assert result["data"][CONF_BACKEND] == "s1" assert result["data"][CONF_LATENCY] == "balanced" assert result["unique_id"] == "voice-alpha-s1" entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id) assert len(entry.subentries) == 3 # Two originals + new one async def test_subflow_cannot_connect( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test the subflow when fetching models fails.""" mock_fishaudio_client.voices.list.side_effect = FishAudioError("API Error") mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, "tts"), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], user_input={CONF_LANGUAGE: "en"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "cannot_connect" async def test_subflow_no_models_found( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test the subflow when no voices are found.""" mock_fishaudio_client.voices.list.return_value = AsyncMock(items=[]) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, "tts"), context={"source": SOURCE_USER}, ) result = await hass.config_entries.subentries.async_configure( result["flow_id"], user_input={CONF_LANGUAGE: "en"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_models_found" async def test_subflow_reconfigure( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reconfiguring an existing TTS subentry.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) subentry = list(mock_config_entry.subentries.values())[0] result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, "tts"), context={"source": "reconfigure", "subentry_id": subentry.subentry_id}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "init" # Step through reconfigure result = await hass.config_entries.subentries.async_configure( result["flow_id"], user_input={ CONF_TITLE: "", CONF_LANGUAGE: "es", CONF_SORT_BY: "task_count", CONF_SELF_ONLY: False, }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "model" result = await hass.config_entries.subentries.async_configure( result["flow_id"], user_input={ CONF_VOICE_ID: "voice-gamma", CONF_BACKEND: "s1", CONF_LATENCY: "normal", CONF_NAME: "Updated Voice", }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reconfigure_successful" async def test_subflow_reconfigure_already_configured( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reconfiguring a TTS subentry to match an existing one.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) # Try to reconfigure the first subentry to match the second one (which already exists) first_subentry = [ s for s in mock_config_entry.subentries.values() if s.title == "Test Voice" ][0] result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, "tts"), context={"source": "reconfigure", "subentry_id": first_subentry.subentry_id}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "init" # Step through reconfigure result = await hass.config_entries.subentries.async_configure( result["flow_id"], user_input={ CONF_TITLE: "", CONF_LANGUAGE: "en", CONF_SORT_BY: "task_count", CONF_SELF_ONLY: False, }, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "model" # Try to set the same voice_id and backend as the second subentry result = await hass.config_entries.subentries.async_configure( result["flow_id"], user_input={ CONF_VOICE_ID: "voice-beta", CONF_BACKEND: "s1", CONF_LATENCY: "normal", CONF_NAME: "Test Voice Updated", }, ) # Should abort because this combination already exists assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_subflow_entry_not_loaded( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: """Test creating a TTS subentry when the parent entry is not loaded.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.subentries.async_init( (mock_config_entry.entry_id, "tts"), context={"source": SOURCE_USER}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "entry_not_loaded"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fish_audio/test_config_flow.py", "license": "Apache License 2.0", "lines": 265, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fish_audio/test_init.py
"""Tests for the Fish Audio integration setup.""" from __future__ import annotations from unittest.mock import AsyncMock from fishaudio import FishAudioError, ServerError import pytest from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry async def test_setup( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test entry setup and unload.""" 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 ConfigEntryState.LOADED # Unload 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", [ FishAudioError("Connection error"), ServerError(500, "Connection error"), ], ) async def test_setup_retry_on_error( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, exception: Exception, ) -> None: """Test entry setup with API errors that should trigger retry.""" mock_fishaudio_client.account.get_credits.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 ConfigEntryState.SETUP_RETRY
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fish_audio/test_init.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fish_audio/test_tts.py
"""Tests for the Fish Audio TTS entity.""" from __future__ import annotations from http import HTTPStatus from pathlib import Path from unittest.mock import AsyncMock, MagicMock from fishaudio import RateLimitError from fishaudio.exceptions import ServerError import pytest from homeassistant.components import tts from homeassistant.components.fish_audio.const import CONF_BACKEND from homeassistant.components.media_player import ( ATTR_MEDIA_CONTENT_ID, DOMAIN as MP_DOMAIN, SERVICE_PLAY_MEDIA, ) from homeassistant.config_entries import ConfigSubentryData 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.exceptions import HomeAssistantError, ServiceValidationError 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(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.fixture async def calls(hass: HomeAssistant) -> list[ServiceCall]: """Mock media player calls.""" return async_mock_service(hass, MP_DOMAIN, SERVICE_PLAY_MEDIA) async def test_tts_service_success( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test TTS service with successful audio generation.""" 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 the TTS entity entity = hass.data[tts.DOMAIN].get_entity("tts.test_voice_test_voice") assert entity is not None # Test the TTS audio generation extension, data = await entity.async_get_tts_audio( message="Hello world", language="en", options={}, ) # Verify the result assert extension == "mp3" assert data == b"fake_audio_data" # Verify the client was called mock_fishaudio_client.tts.convert.assert_called_once() async def test_tts_rate_limited( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test TTS service with rate limit 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() # Get the TTS entity entity = hass.data[tts.DOMAIN].get_entity("tts.test_voice_test_voice") assert entity is not None # Make tts.convert() fail with rate limit error mock_fishaudio_client.tts.convert = AsyncMock( side_effect=RateLimitError(429, "Rate limited") ) # Test that the error is raised with pytest.raises(HomeAssistantError, match="Rate limited"): await entity.async_get_tts_audio( message="Hello world", language="en", options={}, ) # Verify the client was called mock_fishaudio_client.tts.convert.assert_called_once() async def test_tts_missing_voice_id( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test TTS service raises ServiceValidationError when voice_id is missing.""" # Create a config entry with no voice_id entry = MockConfigEntry( domain="fish_audio", data={"api_key": "test-key"}, unique_id="test_user", subentries_data=[ ConfigSubentryData( data={CONF_BACKEND: "s1"}, # Missing CONF_VOICE_ID subentry_type="tts", title="Test Voice", subentry_id="test-sub-id", unique_id="test-voice", ) ], ) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() # Get the TTS entity entity = hass.data[tts.DOMAIN].get_entity("tts.test_voice_test_voice") assert entity is not None # Test that the error is raised with pytest.raises(ServiceValidationError, match="Voice ID not configured"): await entity.async_get_tts_audio( message="Hello world", language="en", options={}, ) async def test_tts_supported_languages( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test TTS entity supported languages.""" 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 the TTS entity entity = hass.data[tts.DOMAIN].get_entity("tts.test_voice_test_voice") assert entity is not None # Verify supported languages assert entity.supported_languages == [ "Any", "en", "zh", "de", "ja", "ar", "fr", "es", "ko", ] # Service-level integration tests async def test_tts_service_speak( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, calls: list[ServiceCall], ) -> None: """Test TTS speak service call.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( tts.DOMAIN, "speak", { ATTR_ENTITY_ID: "tts.test_voice_test_voice", tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something", tts.ATTR_MESSAGE: "Hello world", }, blocking=True, ) assert len(calls) == 1 assert ( await retrieve_media(hass, hass_client, calls[0].data[ATTR_MEDIA_CONTENT_ID]) == HTTPStatus.OK ) async def test_tts_service_speak_with_language( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, calls: list[ServiceCall], ) -> None: """Test TTS speak service call with language parameter.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( tts.DOMAIN, "speak", { ATTR_ENTITY_ID: "tts.test_voice_test_voice", tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something", tts.ATTR_MESSAGE: "Hola mundo", tts.ATTR_LANGUAGE: "es", }, blocking=True, ) assert len(calls) == 1 assert ( await retrieve_media(hass, hass_client, calls[0].data[ATTR_MEDIA_CONTENT_ID]) == HTTPStatus.OK ) async def test_tts_service_speak_server_error( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, calls: list[ServiceCall], ) -> None: """Test TTS speak service call with server 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() # Get the client from runtime_data and make it fail with ServerError entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id) assert entry is not None mock_fishaudio_client.tts.convert = AsyncMock( side_effect=ServerError(500, "Internal server error") ) await hass.services.async_call( tts.DOMAIN, "speak", { ATTR_ENTITY_ID: "tts.test_voice_test_voice", tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something", tts.ATTR_MESSAGE: "Test server error", }, blocking=True, ) assert len(calls) == 1 assert ( await retrieve_media(hass, hass_client, calls[0].data[ATTR_MEDIA_CONTENT_ID]) == HTTPStatus.INTERNAL_SERVER_ERROR ) async def test_tts_service_speak_rate_limit_error( hass: HomeAssistant, mock_fishaudio_client: AsyncMock, mock_config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, calls: list[ServiceCall], ) -> None: """Test TTS speak service call with rate limit 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() # Get the client from runtime_data and make it fail with RateLimitError entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id) assert entry is not None mock_fishaudio_client.tts.convert = AsyncMock( side_effect=RateLimitError(429, "Rate limit exceeded") ) await hass.services.async_call( tts.DOMAIN, "speak", { ATTR_ENTITY_ID: "tts.test_voice_test_voice", tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something", tts.ATTR_MESSAGE: "Test rate limit error", }, blocking=True, ) assert len(calls) == 1 assert ( await retrieve_media(hass, hass_client, calls[0].data[ATTR_MEDIA_CONTENT_ID]) == HTTPStatus.INTERNAL_SERVER_ERROR )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fish_audio/test_tts.py", "license": "Apache License 2.0", "lines": 263, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fluss/test_button.py
"""Tests for the Fluss Buttons.""" from __future__ import annotations from unittest.mock import AsyncMock from fluss_api import FlussApiClient, FlussApiClientError import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS from homeassistant.const import ATTR_ENTITY_ID 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_buttons( hass: HomeAssistant, mock_api_client: AsyncMock, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test setup with multiple devices.""" await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_button_press( hass: HomeAssistant, mock_api_client: FlussApiClient, mock_config_entry: MockConfigEntry, ) -> None: """Test successful button press.""" await setup_integration(hass, mock_config_entry) await hass.services.async_call( BUTTON_DOMAIN, SERVICE_PRESS, {ATTR_ENTITY_ID: "button.device_1"}, blocking=True, ) mock_api_client.async_trigger_device.assert_called_once_with("2a303030sdj1") async def test_button_press_error( hass: HomeAssistant, mock_api_client: FlussApiClient, mock_config_entry: MockConfigEntry, ) -> None: """Test button press with API error.""" await setup_integration(hass, mock_config_entry) mock_api_client.async_trigger_device.side_effect = FlussApiClientError("API Boom") with pytest.raises(HomeAssistantError, match="Failed to trigger device: API Boom"): await hass.services.async_call( BUTTON_DOMAIN, SERVICE_PRESS, {ATTR_ENTITY_ID: "button.device_1"}, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fluss/test_button.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fluss/test_config_flow.py
"""Tests for the Fluss+ config flow.""" from unittest.mock import AsyncMock from fluss_api import ( FlussApiClientAuthenticationError, FlussApiClientCommunicationError, ) import pytest from homeassistant.components.fluss.const import DOMAIN 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_full_flow( hass: HomeAssistant, mock_api_client: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Test full 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" assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: "valid_api_key"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "My Fluss+ Devices" assert result["data"] == {CONF_API_KEY: "valid_api_key"} @pytest.mark.parametrize( ("exception", "expected_error"), [ (FlussApiClientAuthenticationError, "invalid_auth"), (FlussApiClientCommunicationError, "cannot_connect"), (Exception, "unknown"), ], ) async def test_step_user_errors( hass: HomeAssistant, mock_api_client: AsyncMock, mock_setup_entry: AsyncMock, exception: Exception, expected_error: str, ) -> None: """Test error cases for 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_API_KEY: "some_api_key"} mock_api_client.async_get_devices.side_effect = exception result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: "valid_api_key"} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": expected_error} mock_api_client.async_get_devices.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input, ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_duplicate_entry( hass: HomeAssistant, mock_api_client: AsyncMock, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test error cases for user step with recovery.""" 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"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: "test_api_key"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fluss/test_config_flow.py", "license": "Apache License 2.0", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fluss/test_init.py
"""Test script for Fluss+ integration initialization.""" from unittest.mock import AsyncMock from fluss_api import ( FlussApiClientAuthenticationError, FlussApiClientCommunicationError, FlussApiClientError, ) 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_load_unload_config_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_api_client: AsyncMock, ) -> None: """Test the Fluss configuration entry loading/unloading.""" await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED assert len(mock_api_client.async_get_devices.mock_calls) == 1 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"), [ (FlussApiClientAuthenticationError, ConfigEntryState.SETUP_ERROR), (FlussApiClientCommunicationError, ConfigEntryState.SETUP_RETRY), (FlussApiClientError, ConfigEntryState.SETUP_RETRY), ], ) async def test_async_setup_entry_authentication_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_api_client: AsyncMock, exception: Exception, state: ConfigEntryState, ) -> None: """Test that an authentication error during setup leads to SETUP_ERROR state.""" mock_api_client.async_get_devices.side_effect = exception await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is state
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fluss/test_init.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/fressnapf_tracker/test_binary_sensor.py
"""Test the Fressnapf Tracker binary_sensor platform.""" from collections.abc import AsyncGenerator from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform @pytest.fixture(autouse=True) async def platforms() -> AsyncGenerator[None]: """Return the platforms to be loaded for this test.""" with patch( "homeassistant.components.fressnapf_tracker.PLATFORMS", [Platform.BINARY_SENSOR] ): yield @pytest.mark.usefixtures("init_integration") async def test_state_entity_device_snapshots( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test binary_sensor entity is created correctly.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fressnapf_tracker/test_binary_sensor.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:tests/components/fressnapf_tracker/test_config_flow.py
"""Test the Fressnapf Tracker config flow.""" from collections.abc import Callable from unittest.mock import AsyncMock, MagicMock from fressnapftracker import ( FressnapfTrackerInvalidPhoneNumberError, FressnapfTrackerInvalidTokenError, SmsCodeResponse, ) import pytest from homeassistant import config_entries from homeassistant.components.fressnapf_tracker.const import ( CONF_PHONE_NUMBER, CONF_SMS_CODE, CONF_USER_ID, DOMAIN, ) from homeassistant.const import CONF_ACCESS_TOKEN from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from .conftest import MOCK_ACCESS_TOKEN, MOCK_PHONE_NUMBER, MOCK_USER_ID from tests.common import MockConfigEntry @pytest.mark.usefixtures("mock_auth_client") async def test_user_flow_success( hass: HomeAssistant, mock_setup_entry: AsyncMock, ) -> None: """Test the full user 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"] == "user" assert result["errors"] == {} # Submit phone number result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PHONE_NUMBER: MOCK_PHONE_NUMBER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "sms_code" # Submit SMS code result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_SMS_CODE: "0123456"}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == MOCK_PHONE_NUMBER assert result["data"] == { CONF_PHONE_NUMBER: MOCK_PHONE_NUMBER, CONF_USER_ID: MOCK_USER_ID, CONF_ACCESS_TOKEN: MOCK_ACCESS_TOKEN, } assert result["context"]["unique_id"] == str(MOCK_USER_ID) assert len(mock_setup_entry.mock_calls) == 1 @pytest.mark.parametrize( ("side_effect", "error"), [ (FressnapfTrackerInvalidPhoneNumberError, "invalid_phone_number"), (Exception, "unknown"), ], ) @pytest.mark.usefixtures("mock_setup_entry") async def test_user_flow_request_sms_code_errors( hass: HomeAssistant, mock_auth_client: MagicMock, side_effect: Exception, error: str, ) -> None: """Test user flow with errors.""" mock_auth_client.request_sms_code.side_effect = side_effect 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"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PHONE_NUMBER: "invalid"}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": error} # Recover from error mock_auth_client.request_sms_code.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PHONE_NUMBER: MOCK_PHONE_NUMBER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "sms_code" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_SMS_CODE: "0123456"}, ) assert result["type"] is FlowResultType.CREATE_ENTRY @pytest.mark.parametrize( ("side_effect", "error"), [ (FressnapfTrackerInvalidTokenError, "invalid_sms_code"), (Exception, "unknown"), ], ) @pytest.mark.usefixtures("mock_setup_entry") async def test_user_flow_verify_phone_number_errors( hass: HomeAssistant, mock_auth_client: MagicMock, side_effect: Exception, error: str, ) -> None: """Test user flow with invalid SMS code.""" 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_PHONE_NUMBER: MOCK_PHONE_NUMBER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "sms_code" mock_auth_client.verify_phone_number.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_SMS_CODE: "999999"}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "sms_code" assert result["errors"] == {"base": error} # Recover from error mock_auth_client.verify_phone_number.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_SMS_CODE: "0123456"}, ) assert result["type"] is FlowResultType.CREATE_ENTRY @pytest.mark.usefixtures("mock_auth_client") async def test_user_flow_duplicate_user_id( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test user flow aborts on duplicate user_id.""" 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_PHONE_NUMBER: f"{MOCK_PHONE_NUMBER}123"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" @pytest.mark.usefixtures("mock_auth_client") async def test_user_flow_duplicate_phone_number( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test user flow aborts on duplicate phone number.""" 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_PHONE_NUMBER: MOCK_PHONE_NUMBER}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" @pytest.mark.parametrize( ("flow_starter", "expected_step_id", "expected_sms_step_id", "expected_reason"), [ ( lambda entry, hass: entry.start_reauth_flow(hass), "reauth_confirm", "reauth_sms_code", "reauth_successful", ), ( lambda entry, hass: entry.start_reconfigure_flow(hass), "reconfigure", "reconfigure_sms_code", "reconfigure_successful", ), ], ) @pytest.mark.usefixtures( "mock_api_client_init", "mock_api_client_coordinator", "mock_auth_client" ) async def test_reauth_reconfigure_flow( hass: HomeAssistant, mock_config_entry: MockConfigEntry, flow_starter: Callable, expected_step_id: str, expected_sms_step_id: str, expected_reason: str, ) -> None: """Test the reauth and reconfigure flows.""" 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 flow_starter(mock_config_entry, hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == expected_step_id # Submit phone number result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PHONE_NUMBER: MOCK_PHONE_NUMBER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == expected_sms_step_id # Submit SMS code result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_SMS_CODE: "0123456"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == expected_reason @pytest.mark.parametrize( ("flow_starter", "expected_step_id", "expected_sms_step_id", "expected_reason"), [ ( lambda entry, hass: entry.start_reauth_flow(hass), "reauth_confirm", "reauth_sms_code", "reauth_successful", ), ( lambda entry, hass: entry.start_reconfigure_flow(hass), "reconfigure", "reconfigure_sms_code", "reconfigure_successful", ), ], ) @pytest.mark.usefixtures("mock_api_client_init", "mock_api_client_coordinator") async def test_reauth_reconfigure_flow_invalid_phone_number( hass: HomeAssistant, mock_auth_client: MagicMock, mock_config_entry: MockConfigEntry, flow_starter: Callable, expected_step_id: str, expected_sms_step_id: str, expected_reason: str, ) -> None: """Test reauth and reconfigure flows with invalid phone number.""" 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 flow_starter(mock_config_entry, hass) mock_auth_client.request_sms_code.side_effect = ( FressnapfTrackerInvalidPhoneNumberError ) result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PHONE_NUMBER: "invalid"}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == expected_step_id assert result["errors"] == {"base": "invalid_phone_number"} # Recover from error mock_auth_client.request_sms_code.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PHONE_NUMBER: MOCK_PHONE_NUMBER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == expected_sms_step_id result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_SMS_CODE: "0123456"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == expected_reason @pytest.mark.parametrize( ("flow_starter", "expected_sms_step_id", "expected_reason"), [ ( lambda entry, hass: entry.start_reauth_flow(hass), "reauth_sms_code", "reauth_successful", ), ( lambda entry, hass: entry.start_reconfigure_flow(hass), "reconfigure_sms_code", "reconfigure_successful", ), ], ) @pytest.mark.usefixtures("mock_api_client_init", "mock_api_client_coordinator") async def test_reauth_reconfigure_flow_invalid_sms_code( hass: HomeAssistant, mock_auth_client: MagicMock, mock_config_entry: MockConfigEntry, flow_starter: Callable, expected_sms_step_id: str, expected_reason: str, ) -> None: """Test reauth and reconfigure flows with invalid SMS code.""" 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 flow_starter(mock_config_entry, hass) result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PHONE_NUMBER: MOCK_PHONE_NUMBER}, ) mock_auth_client.verify_phone_number.side_effect = FressnapfTrackerInvalidTokenError result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_SMS_CODE: "999999"}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == expected_sms_step_id assert result["errors"] == {"base": "invalid_sms_code"} # Recover from error mock_auth_client.verify_phone_number.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_SMS_CODE: "0123456"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == expected_reason @pytest.mark.parametrize( ("flow_starter", "expected_step_id", "expected_sms_step_id", "expected_reason"), [ ( lambda entry, hass: entry.start_reauth_flow(hass), "reauth_confirm", "reauth_sms_code", "reauth_successful", ), ( lambda entry, hass: entry.start_reconfigure_flow(hass), "reconfigure", "reconfigure_sms_code", "reconfigure_successful", ), ], ) @pytest.mark.usefixtures("mock_api_client_init", "mock_api_client_coordinator") async def test_reauth_reconfigure_flow_invalid_user_id( hass: HomeAssistant, mock_auth_client: MagicMock, mock_config_entry: MockConfigEntry, flow_starter: Callable, expected_step_id: str, expected_sms_step_id: str, expected_reason: str, ) -> None: """Test reauth and reconfigure flows do not allow changing to another account.""" 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 flow_starter(mock_config_entry, hass) mock_auth_client.request_sms_code = AsyncMock( return_value=SmsCodeResponse(id=MOCK_USER_ID + 1) ) result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PHONE_NUMBER: f"{MOCK_PHONE_NUMBER}123"}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == expected_step_id assert result["errors"] == {"base": "account_change_not_allowed"} # Recover from error mock_auth_client.request_sms_code = AsyncMock( return_value=SmsCodeResponse(id=MOCK_USER_ID) ) result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_PHONE_NUMBER: MOCK_PHONE_NUMBER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == expected_sms_step_id result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_SMS_CODE: "0123456"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == expected_reason
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fressnapf_tracker/test_config_flow.py", "license": "Apache License 2.0", "lines": 378, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fressnapf_tracker/test_device_tracker.py
"""Test the Fressnapf Tracker device tracker platform.""" from collections.abc import AsyncGenerator from unittest.mock import AsyncMock, MagicMock, patch from fressnapftracker import Tracker import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import STATE_UNAVAILABLE, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform @pytest.fixture(autouse=True) async def platforms() -> AsyncGenerator[None]: """Return the platforms to be loaded for this test.""" with patch( "homeassistant.components.fressnapf_tracker.PLATFORMS", [Platform.DEVICE_TRACKER], ): yield @pytest.mark.usefixtures("init_integration") async def test_state_entity_device_snapshots( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test device tracker entity is created correctly.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("mock_auth_client") async def test_device_tracker_no_position( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_tracker_no_position: Tracker, mock_api_client_init: MagicMock, ) -> None: """Test device tracker is unavailable when position is None.""" mock_config_entry.add_to_hass(hass) mock_api_client_init.get_tracker = AsyncMock(return_value=mock_tracker_no_position) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() entity_id = "device_tracker.fluffy" state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE assert "latitude" not in state.attributes assert "longitude" not in state.attributes assert "gps_accuracy" not in state.attributes
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fressnapf_tracker/test_device_tracker.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fressnapf_tracker/test_init.py
"""Test the Fressnapf Tracker integration init.""" from collections.abc import Generator from unittest.mock import AsyncMock, MagicMock, patch from fressnapftracker import ( FressnapfTrackerError, FressnapfTrackerInvalidTrackerResponseError, ) import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.fressnapf_tracker.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, issue_registry as ir from .conftest import MOCK_SERIAL_NUMBER from tests.common import MockConfigEntry @pytest.fixture def mock_api_client_malformed_tracker() -> Generator[MagicMock]: """Mock the ApiClient for a malformed tracker response in _tracker_is_valid.""" with patch( "homeassistant.components.fressnapf_tracker.ApiClient", autospec=True, ) as mock_api_client: client = mock_api_client.return_value client.get_tracker = AsyncMock( side_effect=FressnapfTrackerInvalidTrackerResponseError("Invalid tracker") ) yield client @pytest.mark.usefixtures("mock_auth_client", "mock_api_client_init") async def test_setup_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test successful setup of config entry.""" 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 ConfigEntryState.LOADED @pytest.mark.usefixtures("mock_auth_client", "mock_api_client_init") async def test_unload_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test successful unload of config entry.""" 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 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.usefixtures("mock_auth_client") async def test_setup_entry_tracker_is_valid_api_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_api_client_init: MagicMock, ) -> None: """Test setup retries when API returns error during _tracker_is_valid.""" mock_config_entry.add_to_hass(hass) mock_api_client_init.get_tracker = AsyncMock( side_effect=FressnapfTrackerError("API Error") ) 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 @pytest.mark.usefixtures("init_integration") async def test_state_entity_device_snapshots( device_registry: dr.DeviceRegistry, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test sensor entity is created correctly.""" device_entries = dr.async_entries_for_config_entry( device_registry, mock_config_entry.entry_id ) assert device_entries for device_entry in device_entries: assert device_entry == snapshot(name=f"{device_entry.name}-entry"), ( f"device entry snapshot failed for {device_entry.name}" ) @pytest.mark.usefixtures("mock_auth_client", "mock_api_client_malformed_tracker") async def test_invalid_tracker( hass: HomeAssistant, mock_config_entry: MockConfigEntry, issue_registry: ir.IssueRegistry, ) -> None: """Test that an issue is created when an invalid tracker is detected.""" 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 ConfigEntryState.LOADED assert len(issue_registry.issues) == 1 issue_id = f"invalid_fressnapf_tracker_{MOCK_SERIAL_NUMBER}" assert issue_registry.async_get_issue(DOMAIN, issue_id) @pytest.mark.usefixtures("mock_auth_client", "mock_api_client_malformed_tracker") async def test_invalid_tracker_already_exists( hass: HomeAssistant, mock_config_entry: MockConfigEntry, issue_registry: ir.IssueRegistry, ) -> None: """Test that an existing issue is not duplicated.""" ir.async_create_issue( hass, DOMAIN, f"invalid_fressnapf_tracker_{MOCK_SERIAL_NUMBER}", is_fixable=False, severity=ir.IssueSeverity.WARNING, translation_key="invalid_fressnapf_tracker", translation_placeholders={"tracker_id": MOCK_SERIAL_NUMBER}, ) 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 ConfigEntryState.LOADED assert len(issue_registry.issues) == 1
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fressnapf_tracker/test_init.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:tests/components/fressnapf_tracker/test_light.py
"""Test the Fressnapf Tracker light platform.""" from collections.abc import AsyncGenerator from unittest.mock import MagicMock, patch from fressnapftracker import ( FressnapfTrackerError, FressnapfTrackerInvalidTokenError, Tracker, TrackerFeatures, TrackerSettings, ) import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.light import ( ATTR_BRIGHTNESS, DOMAIN as LIGHT_DOMAIN, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.const import ATTR_ENTITY_ID, STATE_ON, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform TRACKER_NO_LED = Tracker( name="Fluffy", battery=0, charging=False, position=None, tracker_settings=TrackerSettings( generation="GPS Tracker 2.0", features=TrackerFeatures(flash_light=False, live_tracking=True), ), ) @pytest.fixture(autouse=True) async def platforms() -> AsyncGenerator[None]: """Return the platforms to be loaded for this test.""" with patch( "homeassistant.components.fressnapf_tracker.PLATFORMS", [Platform.LIGHT] ): yield @pytest.mark.usefixtures("init_integration") async def test_state_entity_device_snapshots( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test light entity is created correctly.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("mock_auth_client") async def test_not_added_when_no_led( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, mock_api_client_init: MagicMock, ) -> None: """Test light entity is created correctly.""" mock_api_client_init.get_tracker.return_value = TRACKER_NO_LED mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() entity_entries = er.async_entries_for_config_entry( entity_registry, mock_config_entry.entry_id ) assert len(entity_entries) == 0 @pytest.mark.usefixtures("init_integration") async def test_turn_on( hass: HomeAssistant, mock_api_client_coordinator: MagicMock, ) -> None: """Test turning the light on.""" entity_id = "light.fluffy_flashlight" state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_ON await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) mock_api_client_coordinator.set_led_brightness.assert_called_once_with(100) @pytest.mark.usefixtures("init_integration") async def test_turn_on_with_brightness( hass: HomeAssistant, mock_api_client_coordinator: MagicMock, ) -> None: """Test turning the light on with brightness.""" entity_id = "light.fluffy_flashlight" await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 128}, blocking=True, ) # 128/255 * 100 = 50 mock_api_client_coordinator.set_led_brightness.assert_called_once_with(50) @pytest.mark.usefixtures("init_integration") async def test_turn_off( hass: HomeAssistant, mock_api_client_coordinator: MagicMock, ) -> None: """Test turning the light off.""" entity_id = "light.fluffy_flashlight" state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_ON await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) mock_api_client_coordinator.set_led_brightness.assert_called_once_with(0) @pytest.mark.parametrize( "activatable_parameter", [ "seen_recently", "nonempty_battery", "not_charging", ], ) @pytest.mark.usefixtures("mock_auth_client") async def test_turn_on_led_not_activatable( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_api_client_init: MagicMock, mock_api_client_coordinator: MagicMock, activatable_parameter: str, ) -> None: """Test turning on the light when LED is not activatable raises.""" setattr( mock_api_client_init.get_tracker.return_value.led_activatable, activatable_parameter, False, ) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() entity_id = "light.fluffy_flashlight" with pytest.raises(HomeAssistantError, match="The flashlight cannot be activated"): await hass.services.async_call( LIGHT_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) mock_api_client_coordinator.set_led_brightness.assert_not_called() @pytest.mark.parametrize( ("api_exception", "expected_exception"), [ (FressnapfTrackerError("Something went wrong"), HomeAssistantError), ( FressnapfTrackerInvalidTokenError("Token no longer valid"), ConfigEntryAuthFailed, ), ], ) @pytest.mark.parametrize("service", [SERVICE_TURN_ON, SERVICE_TURN_OFF]) @pytest.mark.usefixtures("mock_auth_client", "mock_api_client_init") async def test_turn_on_off_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_api_client_coordinator: MagicMock, api_exception: FressnapfTrackerError, expected_exception: type[HomeAssistantError], service: str, ) -> None: """Test that errors during service handling are handled correctly.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() entity_id = "light.fluffy_flashlight" mock_api_client_coordinator.set_led_brightness.side_effect = api_exception with pytest.raises(expected_exception): await hass.services.async_call( LIGHT_DOMAIN, service, {ATTR_ENTITY_ID: entity_id}, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fressnapf_tracker/test_light.py", "license": "Apache License 2.0", "lines": 181, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fressnapf_tracker/test_sensor.py
"""Test the Fressnapf Tracker sensor platform.""" from collections.abc import AsyncGenerator from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform @pytest.fixture(autouse=True) async def platforms() -> AsyncGenerator[None]: """Return the platforms to be loaded for this test.""" with patch( "homeassistant.components.fressnapf_tracker.PLATFORMS", [Platform.SENSOR] ): yield @pytest.mark.usefixtures("init_integration") async def test_state_entity_device_snapshots( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test sensor entity is created correctly.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fressnapf_tracker/test_sensor.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:tests/components/fressnapf_tracker/test_switch.py
"""Test the Fressnapf Tracker switch platform.""" from collections.abc import AsyncGenerator from unittest.mock import MagicMock, patch from fressnapftracker import ( FressnapfTrackerError, FressnapfTrackerInvalidTokenError, Tracker, TrackerFeatures, TrackerSettings, ) 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, STATE_ON, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform TRACKER_NO_ENERGY_SAVING_MODE = Tracker( name="Fluffy", battery=0, charging=False, position=None, tracker_settings=TrackerSettings( generation="GPS Tracker 2.0", features=TrackerFeatures(energy_saving_mode=False), ), ) @pytest.fixture(autouse=True) async def platforms() -> AsyncGenerator[None]: """Return the platforms to be loaded for this test.""" with patch( "homeassistant.components.fressnapf_tracker.PLATFORMS", [Platform.SWITCH] ): yield @pytest.mark.usefixtures("init_integration") async def test_state_entity_device_snapshots( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test switch entity is created correctly.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("mock_auth_client") async def test_not_added_when_no_energy_saving_mode( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, mock_api_client_init: MagicMock, ) -> None: """Test switch entity is created correctly.""" mock_api_client_init.get_tracker.return_value = TRACKER_NO_ENERGY_SAVING_MODE mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() entity_entries = er.async_entries_for_config_entry( entity_registry, mock_config_entry.entry_id ) assert len(entity_entries) == 0 @pytest.mark.usefixtures("init_integration") async def test_turn_on( hass: HomeAssistant, mock_api_client_coordinator: MagicMock, ) -> None: """Test turning the switch on.""" entity_id = "switch.fluffy_sleep_mode" state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_ON await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) mock_api_client_coordinator.set_energy_saving.assert_called_once_with(True) @pytest.mark.usefixtures("init_integration") async def test_turn_off( hass: HomeAssistant, mock_api_client_coordinator: MagicMock, ) -> None: """Test turning the switch off.""" entity_id = "switch.fluffy_sleep_mode" state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_ON await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) mock_api_client_coordinator.set_energy_saving.assert_called_once_with(False) @pytest.mark.parametrize( ("api_exception", "expected_exception"), [ (FressnapfTrackerError("Something went wrong"), HomeAssistantError), ( FressnapfTrackerInvalidTokenError("Token no longer valid"), ConfigEntryAuthFailed, ), ], ) @pytest.mark.parametrize("service", [SERVICE_TURN_ON, SERVICE_TURN_OFF]) @pytest.mark.usefixtures("mock_auth_client", "mock_api_client_init") async def test_turn_on_off_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_api_client_coordinator: MagicMock, api_exception: FressnapfTrackerError, expected_exception: type[HomeAssistantError], service: str, ) -> None: """Test that errors during service handling are handled correctly.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() entity_id = "switch.fluffy_sleep_mode" mock_api_client_coordinator.set_energy_saving.side_effect = api_exception with pytest.raises(expected_exception): await hass.services.async_call( SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: entity_id}, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fressnapf_tracker/test_switch.py", "license": "Apache License 2.0", "lines": 131, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/gentex_homelink/test_config_flow.py
"""Test the homelink config flow.""" from http import HTTPStatus from unittest.mock import AsyncMock import botocore.exceptions import pytest from homeassistant.components.gentex_homelink.const import DOMAIN, OAUTH2_TOKEN_URL from homeassistant.config_entries import SOURCE_USER from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from . import ( INVALID_TEST_ACCESS_JWT, INVALID_TEST_CREDENTIALS, TEST_ACCESS_JWT, TEST_CREDENTIALS, TEST_UNIQUE_ID, setup_integration, ) from tests.common import MockConfigEntry from tests.conftest import AiohttpClientMocker async def test_full_flow( hass: HomeAssistant, mock_srp_auth: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Check full 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 not result["errors"] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_CREDENTIALS, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"] == { "auth_implementation": "gentex_homelink", "token": { "access_token": TEST_ACCESS_JWT, "refresh_token": "refresh", "expires_in": 3600, "token_type": "bearer", "expires_at": result["data"]["token"]["expires_at"], }, } assert result["result"].unique_id == TEST_UNIQUE_ID assert result["title"] == "HomeLink" async def test_unique_configurations( hass: HomeAssistant, mock_srp_auth: AsyncMock, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Check full flow.""" await setup_integration(hass, mock_config_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 not result["errors"] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_CREDENTIALS, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" @pytest.mark.parametrize( ("exception", "error"), [ ( botocore.exceptions.ClientError({"Error": {}}, "Some operation"), "srp_auth_failed", ), (Exception("Some error"), "unknown"), ], ) async def test_exceptions( hass: HomeAssistant, mock_srp_auth: AsyncMock, mock_setup_entry: AsyncMock, exception: Exception, error: str, ) -> None: """Test exceptions are handled correctly.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) mock_srp_auth.async_get_access_token.side_effect = exception result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_CREDENTIALS, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": error} mock_srp_auth.async_get_access_token.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_CREDENTIALS, ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_auth_error( hass: HomeAssistant, mock_srp_auth: AsyncMock, aioclient_mock: AiohttpClientMocker ) -> None: """Test if the auth server returns an error refreshing the token.""" aioclient_mock.clear_requests() aioclient_mock.post(OAUTH2_TOKEN_URL, status=HTTPStatus.UNAUTHORIZED) assert len(aioclient_mock.mock_calls) == 0 result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"email": "test@test.com", "password": "SomePassword"}, ) assert len(aioclient_mock.mock_calls) == 1 assert aioclient_mock.mock_calls[0][0] == "POST" assert result["type"] is FlowResultType.CREATE_ENTRY async def test_reauth_successful( hass: HomeAssistant, mock_srp_auth: AsyncMock, aioclient_mock: AiohttpClientMocker, mock_config_entry: MockConfigEntry, ) -> None: """Test the reauth flow.""" await setup_integration(hass, mock_config_entry) result = await mock_config_entry.start_reauth_flow(hass) assert result["step_id"] == "reauth_confirm" assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=TEST_CREDENTIALS, ) assert result["reason"] == "reauth_successful" assert result["type"] is FlowResultType.ABORT @pytest.mark.parametrize("mock_srp_access_token", [INVALID_TEST_ACCESS_JWT]) async def test_reauth_error( hass: HomeAssistant, mock_srp_auth: AsyncMock, aioclient_mock: AiohttpClientMocker, mock_config_entry: MockConfigEntry, ) -> None: """Test the reauth flow.""" await setup_integration(hass, mock_config_entry) result = await mock_config_entry.start_reauth_flow(hass) assert result["step_id"] == "reauth_confirm" assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=INVALID_TEST_CREDENTIALS, ) assert result["reason"] == "unique_id_mismatch" assert result["type"] is FlowResultType.ABORT
{ "repo_id": "home-assistant/core", "file_path": "tests/components/gentex_homelink/test_config_flow.py", "license": "Apache License 2.0", "lines": 152, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/gentex_homelink/test_event.py
"""Test that the devices and entities are correctly configured.""" import time from unittest.mock import AsyncMock import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import STATE_UNKNOWN from homeassistant.core import HomeAssistant import homeassistant.helpers.entity_registry as er from . import setup_integration, update_callback from tests.common import MockConfigEntry, snapshot_platform from tests.conftest import AiohttpClientMocker @pytest.mark.usefixtures("aioclient_mock_fixture") async def test_entities( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_mqtt_provider: AsyncMock, aioclient_mock: AiohttpClientMocker, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Check if the entities are registered.""" await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("aioclient_mock_fixture") @pytest.mark.freeze_time("2021-07-30") async def test_entities_update( hass: HomeAssistant, mock_config_entry: MockConfigEntry, aioclient_mock: AiohttpClientMocker, mock_mqtt_provider: AsyncMock, ) -> None: """Check if the entities are updated.""" await setup_integration(hass, mock_config_entry) assert hass.states.get("event.testdevice_button_1").state == STATE_UNKNOWN await update_callback( hass, mock_mqtt_provider, "state", { "1": {"requestId": "rid1", "timestamp": time.time()}, "2": {"requestId": "rid2", "timestamp": time.time()}, "3": {"requestId": "rid3", "timestamp": time.time()}, }, ) assert ( hass.states.get("event.testdevice_button_1").state == "2021-07-30T00:00:00.000+00:00" )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/gentex_homelink/test_event.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/gentex_homelink/test_init.py
"""Test that the integration is initialized correctly.""" from unittest.mock import AsyncMock, patch import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.gentex_homelink.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant import homeassistant.helpers.device_registry as dr from . import setup_integration, update_callback from tests.common import MockConfigEntry from tests.conftest import AiohttpClientMocker @pytest.mark.usefixtures("aioclient_mock_fixture") async def test_device( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_mqtt_provider: AsyncMock, aioclient_mock: AiohttpClientMocker, device_registry: dr.DeviceRegistry, snapshot: SnapshotAssertion, ) -> None: """Test device is registered correctly.""" await setup_integration(hass, mock_config_entry) device = device_registry.async_get_device( identifiers={(DOMAIN, "TestDevice")}, ) assert device assert device == snapshot @pytest.mark.usefixtures("aioclient_mock_fixture") async def test_reload_sync( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_mqtt_provider: AsyncMock, aioclient_mock: AiohttpClientMocker, ) -> None: """Test that the config entry is reloaded when a requestSync request is sent.""" await setup_integration(hass, mock_config_entry) with patch.object(hass.config_entries, "async_reload") as async_reload_mock: await update_callback( hass, mock_mqtt_provider, "requestSync", {}, ) async_reload_mock.assert_called_once_with(mock_config_entry.entry_id) @pytest.mark.usefixtures("aioclient_mock_fixture") async def test_load_unload_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_mqtt_provider: AsyncMock, aioclient_mock: AiohttpClientMocker, ) -> None: """Test the entry can be loaded and unloaded.""" 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/gentex_homelink/test_init.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/google_drive/test_diagnostic.py
"""Test GIOS diagnostics.""" import json from unittest.mock import AsyncMock, MagicMock import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, AgentBackup from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.typing import ClientSessionGenerator pytestmark = [ pytest.mark.freeze_time("2021-11-04 17:36:59+01:00"), ] async def test_entry_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, config_entry: MockConfigEntry, mock_api: MagicMock, snapshot: SnapshotAssertion, mock_agent_backup: AgentBackup, ) -> None: """Test config entry diagnostics.""" mock_api.list_files = AsyncMock( return_value={ "files": [ { "id": "HA folder ID", "name": "HA folder name", "description": json.dumps(mock_agent_backup.as_dict()), } ] } ) config_entry.add_to_hass(hass) assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}}) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert ( await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == snapshot )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/google_drive/test_diagnostic.py", "license": "Apache License 2.0", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/google_drive/test_sensor.py
"""Tests for the Google Drive sensor platform.""" import json from unittest.mock import AsyncMock, MagicMock from freezegun.api import FrozenDateTimeFactory from google_drive_api.exceptions import GoogleDriveApiError import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.backup import AgentBackup from homeassistant.components.google_drive.const import SCAN_INTERVAL from homeassistant.const import STATE_UNAVAILABLE 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.freeze_time("2021-11-04 17:36:59+01:00"), ] async def setup_integration(hass: HomeAssistant, config_entry: MockConfigEntry) -> None: """Set up Google Drive integration.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_sensor( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, config_entry: MockConfigEntry, mock_api: MagicMock, ) -> None: """Test the creation and values of the Google Drive sensors.""" await setup_integration(hass, config_entry) await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id) assert ( entity_entry := entity_registry.async_get( "sensor.testuser_domain_com_total_available_storage" ) ) assert entity_entry.device_id assert (device_entry := device_registry.async_get(entity_entry.device_id)) assert device_entry == snapshot @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_sensor_unknown_when_unlimited_plan( hass: HomeAssistant, config_entry: MockConfigEntry, mock_api: MagicMock, ) -> None: """Test the total storage are unknown when the user is on an unlimited plan.""" mock_api.get_user = AsyncMock( return_value={ "storageQuota": { "limit": None, "usage": "100", "usageInDrive": "50", "usageInTrash": "10", } } ) assert not hass.states.get("sensor.testuser_domain_com_total_available_storage") @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_sensor_availability( hass: HomeAssistant, mock_api: MagicMock, config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test the availability handling of the Google Drive sensors.""" await setup_integration(hass, config_entry) mock_api.get_user.side_effect = GoogleDriveApiError("API error") freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() assert ( state := hass.states.get("sensor.testuser_domain_com_total_available_storage") ) assert state.state == STATE_UNAVAILABLE mock_api.list_files.side_effect = [{"files": []}] mock_api.get_user.side_effect = None freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() assert ( state := hass.states.get("sensor.testuser_domain_com_total_available_storage") ) assert state.state != STATE_UNAVAILABLE @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_calculate_backups_size( hass: HomeAssistant, mock_api: MagicMock, config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, mock_agent_backup: AgentBackup, ) -> None: """Test the availability handling of the Google Drive sensors.""" await setup_integration(hass, config_entry) assert ( state := hass.states.get("sensor.testuser_domain_com_total_size_of_backups") ) assert state.state == "0.0" mock_api.list_files = AsyncMock( return_value={ "files": [ { "id": "HA folder ID", "name": "HA folder name", "description": json.dumps(mock_agent_backup.as_dict()), } ] } ) freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() assert ( state := hass.states.get("sensor.testuser_domain_com_total_size_of_backups") ) assert state.state == "100.0"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/google_drive/test_sensor.py", "license": "Apache License 2.0", "lines": 117, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/growatt_server/test_services.py
"""Test Growatt Server services.""" from unittest.mock import patch import growattServer import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.growatt_server.const import DOMAIN from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import device_registry as dr from tests.common import MockConfigEntry @pytest.mark.usefixtures("mock_growatt_v1_api") async def test_read_time_segments_single_device( hass: HomeAssistant, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, snapshot: SnapshotAssertion, ) -> None: """Test reading time segments for single device.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Test service call response = await hass.services.async_call( DOMAIN, "read_time_segments", {"device_id": device_entry.id}, blocking=True, return_response=True, ) assert response == snapshot async def test_update_time_segment_charge_mode( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_growatt_v1_api, device_registry: dr.DeviceRegistry, ) -> None: """Test updating time segment with charge mode.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Test successful update await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) # Verify the API was called mock_growatt_v1_api.min_write_time_segment.assert_called_once() async def test_update_time_segment_discharge_mode( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_growatt_v1_api, device_registry: dr.DeviceRegistry, ) -> None: """Test updating time segment with discharge mode.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 2, "start_time": "14:00", "end_time": "16:00", "batt_mode": "battery_first", "enabled": True, }, blocking=True, ) mock_growatt_v1_api.min_write_time_segment.assert_called_once() async def test_update_time_segment_standby_mode( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_growatt_v1_api, device_registry: dr.DeviceRegistry, ) -> None: """Test updating time segment with standby mode.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 3, "start_time": "20:00", "end_time": "22:00", "batt_mode": "grid_first", "enabled": True, }, blocking=True, ) mock_growatt_v1_api.min_write_time_segment.assert_called_once() async def test_update_time_segment_disabled( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_growatt_v1_api, device_registry: dr.DeviceRegistry, ) -> None: """Test disabling a time segment.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "06:00", "end_time": "08:00", "batt_mode": "load_first", "enabled": False, }, blocking=True, ) mock_growatt_v1_api.min_write_time_segment.assert_called_once() async def test_update_time_segment_with_seconds( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_growatt_v1_api, device_registry: dr.DeviceRegistry, ) -> None: """Test updating time segment with HH:MM:SS format from UI.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Test with HH:MM:SS format (what the UI time selector sends) await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "09:00:00", "end_time": "11:00:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) mock_growatt_v1_api.min_write_time_segment.assert_called_once() async def test_update_time_segment_api_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_growatt_v1_api, device_registry: dr.DeviceRegistry, ) -> None: """Test handling API error when updating time segment.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Mock API error - the library raises an exception instead of returning error dict mock_growatt_v1_api.min_write_time_segment.side_effect = ( growattServer.GrowattV1ApiError( "Error during writing time segment 1", error_code=1, error_msg="API Error", ) ) with pytest.raises(HomeAssistantError, match="API error updating time segment"): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) async def test_no_min_devices_skips_service_registration( hass: HomeAssistant, mock_config_entry_classic: MockConfigEntry, mock_growatt_classic_api, device_registry: dr.DeviceRegistry, ) -> None: """Test that services fail gracefully when no MIN devices exist.""" # Only non-MIN devices (TLX with classic API) mock_growatt_classic_api.device_list.return_value = [ {"deviceSn": "TLX123456", "deviceType": "tlx"} ] mock_config_entry_classic.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry_classic.entry_id) await hass.async_block_till_done() # Verify services are registered (they're always registered in async_setup) assert hass.services.has_service(DOMAIN, "update_time_segment") assert hass.services.has_service(DOMAIN, "read_time_segments") # Get the TLX device (non-MIN) device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "TLX123456")}) assert device_entry is not None # But calling them with a non-MIN device should fail with appropriate error with pytest.raises( ServiceValidationError, match="No MIN devices with token authentication" ): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) async def test_multiple_devices_with_valid_device_id_works( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_growatt_v1_api, device_registry: dr.DeviceRegistry, ) -> None: """Test that multiple devices work when device_id is specified.""" # Configure mock to return two MIN devices mock_growatt_v1_api.device_list.return_value = { "devices": [ {"device_sn": "MIN123456", "type": 7}, {"device_sn": "MIN789012", "type": 7}, ] } 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 the device registry ID for the first MIN device device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Test update service with specific device_id (device registry ID) await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) mock_growatt_v1_api.min_write_time_segment.assert_called_once() # Test read service with specific device_id (device registry ID) response = await hass.services.async_call( DOMAIN, "read_time_segments", {"device_id": device_entry.id}, blocking=True, return_response=True, ) assert response is not None assert "time_segments" in response @pytest.mark.usefixtures("mock_growatt_v1_api") async def test_update_time_segment_invalid_time_format( hass: HomeAssistant, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, ) -> None: """Test handling invalid time format in update_time_segment.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Test with invalid time format with pytest.raises( ServiceValidationError, match="start_time must be in HH:MM or HH:MM:SS format" ): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "invalid", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) @pytest.mark.usefixtures("mock_growatt_v1_api") async def test_update_time_segment_invalid_segment_id( hass: HomeAssistant, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, ) -> None: """Test validation of segment_id range.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Test segment_id too low with pytest.raises( ServiceValidationError, match="segment_id must be between 1 and 9" ): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 0, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) # Test segment_id too high with pytest.raises( ServiceValidationError, match="segment_id must be between 1 and 9" ): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 10, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) @pytest.mark.usefixtures("mock_growatt_v1_api") async def test_update_time_segment_invalid_batt_mode( hass: HomeAssistant, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, ) -> None: """Test validation of batt_mode value.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Test invalid batt_mode with pytest.raises(ServiceValidationError, match="batt_mode must be one of"): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "09:00", "end_time": "11:00", "batt_mode": "invalid_mode", "enabled": True, }, blocking=True, ) @pytest.mark.usefixtures("mock_growatt_v1_api") async def test_read_time_segments_api_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, ) -> None: """Test handling API error when reading time segments.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Mock API error by making coordinator.read_time_segments raise an exception with ( patch( "homeassistant.components.growatt_server.coordinator.GrowattCoordinator.read_time_segments", side_effect=HomeAssistantError("API connection failed"), ), pytest.raises(HomeAssistantError, match="API connection failed"), ): await hass.services.async_call( DOMAIN, "read_time_segments", {"device_id": device_entry.id}, blocking=True, return_response=True, ) @pytest.mark.usefixtures("mock_growatt_v1_api") async def test_service_with_invalid_device_id( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test service with device ID that doesn't exist in registry.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Test with invalid device_id (not in device registry) with pytest.raises(ServiceValidationError, match="Device '.*' not found"): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": "invalid_device_id", "segment_id": 1, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) @pytest.mark.usefixtures("mock_growatt_v1_api") async def test_service_with_non_growatt_device( hass: HomeAssistant, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, ) -> None: """Test service with device from another integration.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Create a device from a different integration other_device = device_registry.async_get_or_create( config_entry_id=mock_config_entry.entry_id, identifiers={("other_domain", "other_device_123")}, name="Other Device", ) # Test with device from different integration with pytest.raises( ServiceValidationError, match="Device '.*' is not a Growatt device" ): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": other_device.id, "segment_id": 1, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) @pytest.mark.usefixtures("mock_growatt_v1_api") async def test_service_with_non_min_growatt_device( hass: HomeAssistant, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, ) -> None: """Test service with Growatt device that is not MIN type.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Manually create a TLX device (V1 API only creates MIN devices) # This simulates having a non-MIN Growatt device from another source tlx_device = device_registry.async_get_or_create( config_entry_id=mock_config_entry.entry_id, identifiers={(DOMAIN, "TLX789012")}, name="TLX Device", ) # Test with TLX device (not a MIN device) with pytest.raises( ServiceValidationError, match="MIN device 'TLX789012' not found or not configured for services", ): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": tlx_device.id, "segment_id": 1, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, ) @pytest.mark.parametrize( "invalid_time", ["25:00", "12:99", "invalid", "12"], ids=["invalid_hour", "invalid_minute", "non_numeric", "missing_parts"], ) @pytest.mark.usefixtures("mock_growatt_v1_api") async def test_update_time_segment_invalid_end_time_format( hass: HomeAssistant, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, invalid_time: str, ) -> None: """Test handling invalid end_time format in update_time_segment.""" 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 the device registry ID device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")}) assert device_entry is not None # Test with invalid end_time format with pytest.raises( ServiceValidationError, match="end_time must be in HH:MM or HH:MM:SS format" ): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "09:00", "end_time": invalid_time, "batt_mode": "load_first", "enabled": True, }, blocking=True, ) async def test_service_with_unloaded_config_entry( hass: HomeAssistant, mock_config_entry_classic: MockConfigEntry, mock_growatt_classic_api, device_registry: dr.DeviceRegistry, ) -> None: """Test service call when config entry is not loaded.""" # Setup with TLX device mock_growatt_classic_api.device_list.return_value = [ {"deviceSn": "TLX123456", "deviceType": "tlx"} ] mock_config_entry_classic.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry_classic.entry_id) await hass.async_block_till_done() # Get the device device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "TLX123456")}) assert device_entry is not None # Unload the config entry await hass.config_entries.async_unload(mock_config_entry_classic.entry_id) await hass.async_block_till_done() # Test service call with unloaded entry (should skip it in get_min_coordinators) with pytest.raises( ServiceValidationError, match="No MIN devices with token authentication" ): await hass.services.async_call( DOMAIN, "update_time_segment", { "device_id": device_entry.id, "segment_id": 1, "start_time": "09:00", "end_time": "11:00", "batt_mode": "load_first", "enabled": True, }, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/growatt_server/test_services.py", "license": "Apache License 2.0", "lines": 586, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/hikvision/test_binary_sensor.py
"""Test Hikvision binary sensors.""" import logging from unittest.mock import MagicMock import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.binary_sensor import BinarySensorDeviceClass from homeassistant.components.hikvision.const import DOMAIN from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_LAST_TRIP_TIME, CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, STATE_OFF, Platform, ) from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant from homeassistant.helpers import ( device_registry as dr, entity_registry as er, issue_registry as ir, ) from homeassistant.setup import async_setup_component from . import setup_integration from .conftest import ( TEST_DEVICE_ID, TEST_DEVICE_NAME, TEST_HOST, TEST_PASSWORD, TEST_PORT, TEST_USERNAME, ) from tests.common import MockConfigEntry, snapshot_platform @pytest.fixture def platforms() -> list[Platform]: """Platforms, which should be loaded during the test.""" return [Platform.BINARY_SENSOR] @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_all_entities( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test all binary sensor entities.""" await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_binary_sensors_created( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, ) -> None: """Test binary sensors are created for each event type.""" await setup_integration(hass, mock_config_entry) # Check Motion sensor (camera type doesn't include channel in name) state = hass.states.get("binary_sensor.front_camera_motion") assert state is not None assert state.state == STATE_OFF assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.MOTION assert ATTR_LAST_TRIP_TIME in state.attributes # Check Line Crossing sensor state = hass.states.get("binary_sensor.front_camera_line_crossing") assert state is not None assert state.state == STATE_OFF assert state.attributes.get(ATTR_DEVICE_CLASS) == BinarySensorDeviceClass.MOTION async def test_binary_sensor_device_info( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, device_registry: dr.DeviceRegistry, ) -> None: """Test binary sensors are linked to device.""" await setup_integration(hass, mock_config_entry) device_entry = device_registry.async_get_device( identifiers={(DOMAIN, TEST_DEVICE_ID)} ) assert device_entry is not None assert device_entry.name == TEST_DEVICE_NAME assert device_entry.manufacturer == "Hikvision" assert device_entry.model == "Camera" async def test_binary_sensor_callback_registered( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, ) -> None: """Test that callback is registered with pyhik.""" await setup_integration(hass, mock_config_entry) # Verify callback was registered for each sensor assert mock_hikcamera.return_value.add_update_callback.call_count == 2 async def test_binary_sensor_no_sensors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, caplog: pytest.LogCaptureFixture, ) -> None: """Test setup when device has no sensors.""" mock_hikcamera.return_value.current_event_states = None with caplog.at_level(logging.WARNING): await setup_integration(hass, mock_config_entry) # No binary sensors should be created states = hass.states.async_entity_ids("binary_sensor") assert len(states) == 0 # Verify warning was logged assert "has no sensors available" in caplog.text @pytest.mark.parametrize("amount_of_channels", [2]) async def test_binary_sensor_nvr_device( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, device_registry: dr.DeviceRegistry, ) -> None: """Test binary sensor naming for NVR devices.""" mock_hikcamera.return_value.get_type = "NVR" mock_hikcamera.return_value.current_event_states = { "Motion": [(True, 1), (False, 2)], } await setup_integration(hass, mock_config_entry) # Verify NVR channel devices are created with via_device linking channel_1_device = device_registry.async_get_device( identifiers={(DOMAIN, f"{TEST_DEVICE_ID}_1")} ) assert channel_1_device is not None assert channel_1_device.via_device_id is not None channel_2_device = device_registry.async_get_device( identifiers={(DOMAIN, f"{TEST_DEVICE_ID}_2")} ) assert channel_2_device is not None assert channel_2_device.via_device_id is not None # Verify sensors are created (entity IDs depend on translation loading) states = hass.states.async_entity_ids("binary_sensor") assert len(states) == 2 async def test_binary_sensor_state_on( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, ) -> None: """Test binary sensor state when on.""" mock_hikcamera.return_value.fetch_attributes.return_value = ( True, None, None, "2024-01-01T12:00:00Z", ) await setup_integration(hass, mock_config_entry) state = hass.states.get("binary_sensor.front_camera_motion") assert state is not None assert state.state == "on" async def test_binary_sensor_device_class_unknown( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, caplog: pytest.LogCaptureFixture, ) -> None: """Test unknown sensor types are logged and skipped.""" mock_hikcamera.return_value.current_event_states = { "Unknown Event": [(False, 1)], } with caplog.at_level(logging.WARNING): await setup_integration(hass, mock_config_entry) # No entity should be created for unknown sensor types states = hass.states.async_entity_ids("binary_sensor") assert len(states) == 0 # Verify warning was logged for unknown sensor type assert "Unknown Hikvision sensor type 'Unknown Event'" in caplog.text async def test_yaml_import_creates_deprecation_issue( hass: HomeAssistant, mock_hikcamera: MagicMock, issue_registry: ir.IssueRegistry, ) -> None: """Test YAML import creates deprecation issue.""" await async_setup_component( hass, "binary_sensor", { "binary_sensor": { "platform": DOMAIN, CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, } }, ) await hass.async_block_till_done() # Check that deprecation issue was created in homeassistant domain issue = issue_registry.async_get_issue( HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{DOMAIN}" ) assert issue is not None assert issue.severity == ir.IssueSeverity.WARNING async def test_yaml_import_with_name( hass: HomeAssistant, mock_hikcamera: MagicMock, ) -> None: """Test YAML import uses custom name for config entry.""" await async_setup_component( hass, "binary_sensor", { "binary_sensor": { "platform": DOMAIN, CONF_NAME: "Custom Camera Name", CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, } }, ) await hass.async_block_till_done() # Check that the config entry was created with the custom name entries = hass.config_entries.async_entries(DOMAIN) assert len(entries) == 1 assert entries[0].title == "Custom Camera Name" async def test_yaml_import_abort_creates_issue( hass: HomeAssistant, mock_hikcamera: MagicMock, issue_registry: ir.IssueRegistry, ) -> None: """Test YAML import creates issue when import is aborted.""" mock_hikcamera.return_value.get_id = None await async_setup_component( hass, "binary_sensor", { "binary_sensor": { "platform": DOMAIN, CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, } }, ) await hass.async_block_till_done() # Check that import failure issue was created issue = issue_registry.async_get_issue( DOMAIN, "deprecated_yaml_import_issue_cannot_connect" ) assert issue is not None assert issue.severity == ir.IssueSeverity.WARNING async def test_binary_sensor_update_callback( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, ) -> None: """Test binary sensor state updates via callback.""" await setup_integration(hass, mock_config_entry) state = hass.states.get("binary_sensor.front_camera_motion") assert state is not None assert state.state == STATE_OFF # Simulate state change via callback mock_hikcamera.return_value.fetch_attributes.return_value = ( True, None, None, "2024-01-01T12:00:00Z", ) # Get the registered callback and call it add_callback_call = mock_hikcamera.return_value.add_update_callback.call_args_list[ 0 ] callback_func = add_callback_call[0][0] callback_func("motion detected") # Wait for the event loop to process the scheduled state update # (callback uses call_soon_threadsafe to schedule update in event loop) await hass.async_block_till_done() # Verify state was updated state = hass.states.get("binary_sensor.front_camera_motion") assert state is not None assert state.state == "on"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/hikvision/test_binary_sensor.py", "license": "Apache License 2.0", "lines": 278, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/hikvision/test_config_flow.py
"""Test the Hikvision config flow.""" from unittest.mock import AsyncMock, MagicMock import requests from homeassistant.components.hikvision.const import DOMAIN from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, ) from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from .conftest import ( TEST_DEVICE_ID, TEST_DEVICE_NAME, TEST_HOST, TEST_PASSWORD, TEST_PORT, TEST_USERNAME, ) from tests.common import MockConfigEntry async def test_form( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test we get the form and can create 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: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == TEST_DEVICE_NAME assert result["result"].unique_id == TEST_DEVICE_ID assert result["data"] == { CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, } # Verify HikCamera was called with the ssl parameter mock_hikcamera.assert_called_once_with( f"http://{TEST_HOST}", TEST_PORT, TEST_USERNAME, TEST_PASSWORD, False ) async def test_form_cannot_connect( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test we handle cannot connect error and can recover.""" mock_hikcamera.return_value.get_id = None 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: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "cannot_connect"} # Recover from error mock_hikcamera.return_value.get_id = TEST_DEVICE_ID result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["result"].unique_id == TEST_DEVICE_ID async def test_form_exception( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test we handle exception during connection and can recover.""" mock_hikcamera.side_effect = requests.exceptions.RequestException( "Connection failed" ) 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: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "cannot_connect"} # Recover from error mock_hikcamera.side_effect = None mock_hikcamera.return_value.get_id = TEST_DEVICE_ID mock_hikcamera.return_value.get_name = TEST_DEVICE_NAME result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["result"].unique_id == TEST_DEVICE_ID async def test_form_unknown_exception( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test we handle unknown exception during connection and can recover.""" mock_hikcamera.side_effect = Exception("Unexpected error") 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: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "unknown"} # Recover from error mock_hikcamera.side_effect = None mock_hikcamera.return_value.get_id = TEST_DEVICE_ID mock_hikcamera.return_value.get_name = TEST_DEVICE_NAME result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["result"].unique_id == TEST_DEVICE_ID async def test_form_already_configured( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test we handle already configured devices.""" 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"], { CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_import_flow( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test YAML import flow creates config entry.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == TEST_DEVICE_NAME assert result["result"].unique_id == TEST_DEVICE_ID assert result["data"] == { CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, } # Verify HikCamera was called with the ssl parameter mock_hikcamera.assert_called_once_with( f"http://{TEST_HOST}", TEST_PORT, TEST_USERNAME, TEST_PASSWORD, False ) async def test_import_flow_with_defaults( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test YAML import flow uses default values.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_HOST: TEST_HOST, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["result"].unique_id == TEST_DEVICE_ID # Default port (80) and SSL (False) should be used assert result["data"][CONF_PORT] == 80 assert result["data"][CONF_SSL] is False async def test_import_flow_cannot_connect( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test YAML import flow aborts on connection error.""" mock_hikcamera.side_effect = requests.exceptions.RequestException( "Connection failed" ) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "cannot_connect" async def test_import_flow_no_device_id( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test YAML import flow aborts when device_id is None.""" mock_hikcamera.return_value.get_id = None result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "cannot_connect" async def test_import_flow_unknown_exception( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test YAML import flow aborts on unknown exception.""" mock_hikcamera.side_effect = Exception("Unexpected error") result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "unknown" async def test_import_flow_already_configured( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test YAML import flow aborts when device is already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: False, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_form_with_ssl( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_hikcamera: MagicMock, ) -> None: """Test user flow with ssl enabled passes ssl parameter to HikCamera.""" 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: TEST_HOST, CONF_PORT: TEST_PORT, CONF_USERNAME: TEST_USERNAME, CONF_PASSWORD: TEST_PASSWORD, CONF_SSL: True, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"][CONF_SSL] is True # Verify HikCamera was called with ssl=True mock_hikcamera.assert_called_once_with( f"https://{TEST_HOST}", TEST_PORT, TEST_USERNAME, TEST_PASSWORD, True )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/hikvision/test_config_flow.py", "license": "Apache License 2.0", "lines": 355, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/hikvision/test_init.py
"""Test Hikvision integration setup and unload.""" from unittest.mock import MagicMock from xml.etree.ElementTree import ParseError import pytest import requests from homeassistant.config_entries import ConfigEntryState from homeassistant.const import CONF_SSL from homeassistant.core import HomeAssistant from . import setup_integration from .conftest import TEST_HOST, TEST_PASSWORD, TEST_PORT, TEST_USERNAME from tests.common import MockConfigEntry async def test_setup_and_unload_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, ) -> None: """Test successful setup and unload of config entry.""" await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED mock_hikcamera.return_value.start_stream.assert_called_once() # Verify HikCamera was called with the ssl parameter mock_hikcamera.assert_called_once_with( f"http://{TEST_HOST}", TEST_PORT, TEST_USERNAME, TEST_PASSWORD, False ) 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 mock_hikcamera.return_value.disconnect.assert_called_once() async def test_setup_entry_with_ssl( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, ) -> None: """Test setup with ssl enabled passes ssl parameter to HikCamera.""" mock_config_entry.add_to_hass(hass) hass.config_entries.async_update_entry( mock_config_entry, data={**mock_config_entry.data, CONF_SSL: True} ) 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 # Verify HikCamera was called with ssl=True mock_hikcamera.assert_called_once_with( f"https://{TEST_HOST}", TEST_PORT, TEST_USERNAME, TEST_PASSWORD, True ) async def test_setup_entry_connection_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, ) -> None: """Test setup fails on connection error.""" mock_hikcamera.side_effect = requests.exceptions.RequestException( "Connection failed" ) 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 ConfigEntryState.SETUP_RETRY async def test_setup_entry_no_device_id( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hikcamera: MagicMock, ) -> None: """Test setup fails when device_id is None.""" mock_hikcamera.return_value.get_id = 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() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY async def test_setup_entry_nvr_fetches_events( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hik_nvr: MagicMock, ) -> None: """Test setup fetches NVR events for NVR devices.""" await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED mock_hik_nvr.return_value.get_event_triggers.assert_called_once() mock_hik_nvr.return_value.inject_events.assert_called_once() async def test_setup_entry_nvr_event_fetch_request_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hik_nvr: MagicMock, caplog: pytest.LogCaptureFixture, ) -> None: """Test setup continues when NVR event fetch fails with request error.""" mock_hik_nvr.return_value.get_event_triggers.side_effect = ( requests.exceptions.RequestException("Connection error") ) await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED mock_hik_nvr.return_value.get_event_triggers.assert_called_once() mock_hik_nvr.return_value.inject_events.assert_not_called() assert f"Unable to fetch event triggers from {TEST_HOST}" in caplog.text async def test_setup_entry_nvr_event_fetch_parse_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hik_nvr: MagicMock, caplog: pytest.LogCaptureFixture, ) -> None: """Test setup continues when NVR event fetch fails with parse error.""" mock_hik_nvr.return_value.get_event_triggers.side_effect = ParseError("Invalid XML") await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED mock_hik_nvr.return_value.get_event_triggers.assert_called_once() mock_hik_nvr.return_value.inject_events.assert_not_called() assert f"Unable to fetch event triggers from {TEST_HOST}" in caplog.text async def test_setup_entry_nvr_no_events_returned( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hik_nvr: MagicMock, ) -> None: """Test setup continues when NVR returns no events.""" mock_hik_nvr.return_value.get_event_triggers.return_value = None await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED mock_hik_nvr.return_value.get_event_triggers.assert_called_once() mock_hik_nvr.return_value.inject_events.assert_not_called() async def test_setup_entry_nvr_empty_events_returned( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hik_nvr: MagicMock, ) -> None: """Test setup continues when NVR returns empty events.""" mock_hik_nvr.return_value.get_event_triggers.return_value = {} await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED mock_hik_nvr.return_value.get_event_triggers.assert_called_once() mock_hik_nvr.return_value.inject_events.assert_not_called()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/hikvision/test_init.py", "license": "Apache License 2.0", "lines": 129, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/humidifier/test_trigger.py
"""Test humidifier trigger.""" from typing import Any import pytest from homeassistant.components.humidifier.const import ( ATTR_ACTION, ATTR_CURRENT_HUMIDITY, HumidifierAction, ) from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant, ServiceCall from tests.components import ( TriggerStateDescription, arm_trigger, parametrize_numerical_attribute_changed_trigger_states, parametrize_numerical_attribute_crossed_threshold_trigger_states, parametrize_target_entities, parametrize_trigger_states, set_or_remove_state, target_entities, ) @pytest.fixture async def target_humidifiers(hass: HomeAssistant) -> list[str]: """Create multiple humidifier entities associated with different targets.""" return (await target_entities(hass, "humidifier"))["included"] @pytest.mark.parametrize( "trigger_key", [ "humidifier.current_humidity_changed", "humidifier.current_humidity_crossed_threshold", "humidifier.started_drying", "humidifier.started_humidifying", "humidifier.turned_off", "humidifier.turned_on", ], ) async def test_humidifier_triggers_gated_by_labs_flag( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str ) -> None: """Test the humidifier triggers are gated by the labs flag.""" await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"}) assert ( "Unnamed automation failed to setup triggers and has been disabled: Trigger " f"'{trigger_key}' requires the experimental 'New triggers and conditions' " "feature to be enabled in Home Assistant Labs settings (feature flag: " "'new_triggers_conditions')" ) in caplog.text @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("humidifier"), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="humidifier.turned_on", target_states=[STATE_ON], other_states=[STATE_OFF], ), *parametrize_trigger_states( trigger="humidifier.turned_off", target_states=[STATE_OFF], other_states=[STATE_ON], ), ], ) async def test_humidifier_state_trigger_behavior_any( hass: HomeAssistant, service_calls: list[ServiceCall], target_humidifiers: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the humidifier state trigger fires when any humidifier state changes to a specific state.""" other_entity_ids = set(target_humidifiers) - {entity_id} # Set all humidifiers, including the tested humidifier, to the initial state for eid in target_humidifiers: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Check if changing other humidifiers also triggers for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == (entities_in_target - 1) * state["count"] service_calls.clear() @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("humidifier"), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_numerical_attribute_changed_trigger_states( "humidifier.current_humidity_changed", STATE_ON, ATTR_CURRENT_HUMIDITY ), *parametrize_numerical_attribute_crossed_threshold_trigger_states( "humidifier.current_humidity_crossed_threshold", STATE_ON, ATTR_CURRENT_HUMIDITY, ), *parametrize_trigger_states( trigger="humidifier.started_drying", target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.DRYING})], other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})], ), *parametrize_trigger_states( trigger="humidifier.started_humidifying", target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.HUMIDIFYING})], other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})], ), ], ) async def test_humidifier_state_attribute_trigger_behavior_any( hass: HomeAssistant, service_calls: list[ServiceCall], target_humidifiers: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the humidifier state trigger fires when any humidifier state changes to a specific state.""" other_entity_ids = set(target_humidifiers) - {entity_id} # Set all humidifiers, including the tested humidifier, to the initial state for eid in target_humidifiers: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, trigger_options, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Check if changing other humidifiers also triggers for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == (entities_in_target - 1) * state["count"] service_calls.clear() @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("humidifier"), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="humidifier.turned_on", target_states=[STATE_ON], other_states=[STATE_OFF], ), *parametrize_trigger_states( trigger="humidifier.turned_off", target_states=[STATE_OFF], other_states=[STATE_ON], ), ], ) async def test_humidifier_state_trigger_behavior_first( hass: HomeAssistant, service_calls: list[ServiceCall], target_humidifiers: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the humidifier state trigger fires when the first humidifier changes to a specific state.""" other_entity_ids = set(target_humidifiers) - {entity_id} # Set all humidifiers, including the tested humidifier, to the initial state for eid in target_humidifiers: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Triggering other humidifiers should not cause the trigger to fire again for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("humidifier"), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_numerical_attribute_crossed_threshold_trigger_states( "humidifier.current_humidity_crossed_threshold", STATE_ON, ATTR_CURRENT_HUMIDITY, ), *parametrize_trigger_states( trigger="humidifier.started_drying", target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.DRYING})], other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})], ), *parametrize_trigger_states( trigger="humidifier.started_humidifying", target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.HUMIDIFYING})], other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})], ), ], ) async def test_humidifier_state_attribute_trigger_behavior_first( hass: HomeAssistant, service_calls: list[ServiceCall], target_humidifiers: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[tuple[tuple[str, dict], int]], ) -> None: """Test that the humidifier state trigger fires when the first humidifier state changes to a specific state.""" other_entity_ids = set(target_humidifiers) - {entity_id} # Set all humidifiers, including the tested humidifier, to the initial state for eid in target_humidifiers: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger( hass, trigger, {"behavior": "first"} | trigger_options, trigger_target_config ) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Triggering other humidifiers should not cause the trigger to fire again for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("humidifier"), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="humidifier.turned_on", target_states=[STATE_ON], other_states=[STATE_OFF], ), *parametrize_trigger_states( trigger="humidifier.turned_off", target_states=[STATE_OFF], other_states=[STATE_ON], ), ], ) async def test_humidifier_state_trigger_behavior_last( hass: HomeAssistant, service_calls: list[ServiceCall], target_humidifiers: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the humidifier state trigger fires when the last humidifier changes to a specific state.""" other_entity_ids = set(target_humidifiers) - {entity_id} # Set all humidifiers, including the tested humidifier, to the initial state for eid in target_humidifiers: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config) for state in states[1:]: included_state = state["included"] for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("humidifier"), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_numerical_attribute_crossed_threshold_trigger_states( "humidifier.current_humidity_crossed_threshold", STATE_ON, ATTR_CURRENT_HUMIDITY, ), *parametrize_trigger_states( trigger="humidifier.started_drying", target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.DRYING})], other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})], ), *parametrize_trigger_states( trigger="humidifier.started_humidifying", target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.HUMIDIFYING})], other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})], ), ], ) async def test_humidifier_state_attribute_trigger_behavior_last( hass: HomeAssistant, service_calls: list[ServiceCall], target_humidifiers: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[tuple[tuple[str, dict], int]], ) -> None: """Test that the humidifier state trigger fires when the last humidifier state changes to a specific state.""" other_entity_ids = set(target_humidifiers) - {entity_id} # Set all humidifiers, including the tested humidifier, to the initial state for eid in target_humidifiers: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger( hass, trigger, {"behavior": "last"} | trigger_options, trigger_target_config ) for state in states[1:]: included_state = state["included"] for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/humidifier/test_trigger.py", "license": "Apache License 2.0", "lines": 374, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/lamarzocco/test_bluetooth.py
"""Tests for La Marzocco Bluetooth connection.""" from datetime import timedelta from unittest.mock import MagicMock, patch from bleak.backends.device import BLEDevice from freezegun.api import FrozenDateTimeFactory from pylamarzocco.const import MachineMode, ModelName, WidgetType from pylamarzocco.exceptions import BluetoothConnectionFailed, RequestNotSuccessful import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.lamarzocco.const import CONF_OFFLINE_MODE, DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, STATE_OFF, STATE_ON, STATE_UNAVAILABLE, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from . import async_init_integration, get_bluetooth_service_info from tests.common import MockConfigEntry, async_fire_time_changed # Entities with bt_offline_mode=True BLUETOOTH_ONLY_BASE_ENTITIES = [ ("binary_sensor", "water_tank_empty"), ("switch", ""), ("switch", "steam_boiler"), ("number", "coffee_target_temperature"), ("switch", "smart_standby_enabled"), ("number", "smart_standby_time"), ] MICRA_BT_OFFLINE_ENTITIES = [ *BLUETOOTH_ONLY_BASE_ENTITIES, ("select", "steam_level"), ] GS3_BT_OFFLINE_ENTITIES = [ *BLUETOOTH_ONLY_BASE_ENTITIES, ("number", "steam_target_temperature"), ] def build_entity_id( platform: str, serial_number: str, entity_suffix: str, ) -> str: """Build full entity ID.""" if entity_suffix: return f"{platform}.{serial_number}_{entity_suffix}" return f"{platform}.{serial_number}" async def test_bluetooth_coordinator_updates_based_on_websocket_state( hass: HomeAssistant, mock_lamarzocco: MagicMock, mock_config_entry_bluetooth: MockConfigEntry, mock_ble_device_from_address: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test Bluetooth coordinator updates based on websocket connection state.""" mock_lamarzocco.websocket.connected = False await async_init_integration(hass, mock_config_entry_bluetooth) await hass.async_block_till_done() # Reset call count after initial setup mock_lamarzocco.get_dashboard_from_bluetooth.reset_mock() # Test 1: When websocket is connected, Bluetooth should skip updates mock_lamarzocco.websocket.connected = True mock_lamarzocco.dashboard.connected = True freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() assert not mock_lamarzocco.get_dashboard_from_bluetooth.called # Test 2: When websocket is disconnected, Bluetooth should update mock_lamarzocco.dashboard.connected = False freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() assert mock_lamarzocco.get_dashboard_from_bluetooth.called @pytest.mark.parametrize( ("device_fixture", "entities"), [ (ModelName.LINEA_MICRA, MICRA_BT_OFFLINE_ENTITIES), (ModelName.GS3_AV, GS3_BT_OFFLINE_ENTITIES), ], ) async def test_bt_offline_mode_entity_available_when_cloud_fails( hass: HomeAssistant, mock_lamarzocco: MagicMock, mock_config_entry_bluetooth: MockConfigEntry, freezer: FrozenDateTimeFactory, device_fixture: ModelName, entities: list[tuple[str, str]], ) -> None: """Test entities with bt_offline_mode=True remain available when cloud coordinators fail.""" await async_init_integration(hass, mock_config_entry_bluetooth) # Check all entities are initially available for entity_id in entities: state = hass.states.get( build_entity_id(entity_id[0], mock_lamarzocco.serial_number, entity_id[1]) ) assert state assert state.state != STATE_UNAVAILABLE # Simulate cloud coordinator failures mock_lamarzocco.websocket.connected = False mock_lamarzocco.get_dashboard.side_effect = RequestNotSuccessful("") # Trigger update freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # All bt_offline_mode entities should still be available for entity_id in entities: state = hass.states.get( build_entity_id(entity_id[0], mock_lamarzocco.serial_number, entity_id[1]) ) assert state assert state.state != STATE_UNAVAILABLE async def test_entity_without_bt_becomes_unavailable_when_cloud_fails_no_bt( hass: HomeAssistant, mock_lamarzocco: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test entities become unavailable when cloud fails and no bluetooth coordinator exists.""" await async_init_integration(hass, mock_config_entry) # Water tank sensor (even with bt_offline_mode=True, needs BT coordinator to work) water_tank_sensor = ( f"binary_sensor.{mock_lamarzocco.serial_number}_water_tank_empty" ) state = hass.states.get(water_tank_sensor) assert state # Initially should be available initial_state = state.state assert initial_state != STATE_UNAVAILABLE # Simulate cloud coordinator failures without bluetooth fallback mock_lamarzocco.websocket.connected = False mock_lamarzocco.ensure_token_valid.side_effect = RequestNotSuccessful("") # Trigger update freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # Water tank sensor should become unavailable because cloud failed and no BT state = hass.states.get(water_tank_sensor) assert state assert state.state == STATE_UNAVAILABLE async def test_bluetooth_coordinator_handles_connection_failure( hass: HomeAssistant, mock_lamarzocco: MagicMock, mock_config_entry_bluetooth: MockConfigEntry, mock_ble_device_from_address: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test Bluetooth coordinator handles connection failures gracefully.""" # Start with websocket terminated to ensure Bluetooth coordinator is active mock_lamarzocco.websocket.connected = False await async_init_integration(hass, mock_config_entry_bluetooth) # Water tank sensor has bt_offline_mode=True water_tank_sensor = ( f"binary_sensor.{mock_lamarzocco.serial_number}_water_tank_empty" ) state = hass.states.get(water_tank_sensor) assert state assert state.state != STATE_UNAVAILABLE # Simulate Bluetooth connection failure mock_lamarzocco.websocket.connected = False mock_lamarzocco.dashboard.connected = False mock_lamarzocco.get_dashboard_from_bluetooth.side_effect = ( BluetoothConnectionFailed("") ) # Trigger Bluetooth coordinator update freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # now it should be unavailable due to BT failure state = hass.states.get(water_tank_sensor) assert state assert state.state == STATE_UNAVAILABLE async def test_bluetooth_coordinator_triggers_entity_updates( hass: HomeAssistant, mock_lamarzocco: MagicMock, mock_config_entry_bluetooth: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test Bluetooth coordinator updates trigger entity state updates.""" mock_lamarzocco.dashboard.config[ WidgetType.CM_MACHINE_STATUS ].mode = MachineMode.STANDBY await async_init_integration(hass, mock_config_entry_bluetooth) main_switch = f"switch.{mock_lamarzocco.serial_number}" state = hass.states.get(main_switch) assert state assert state.state == STATE_OFF # Simulate Bluetooth update changing machine mode to brewing mock_lamarzocco.dashboard.config[ WidgetType.CM_MACHINE_STATUS ].mode = MachineMode.BREWING_MODE mock_lamarzocco.websocket.connected = False mock_lamarzocco.dashboard.connected = False # Trigger Bluetooth coordinator update freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # Verify entity state was updated state = hass.states.get(main_switch) assert state assert state.state == STATE_ON @pytest.mark.parametrize( ("device_fixture", "entities"), [ (ModelName.LINEA_MICRA, MICRA_BT_OFFLINE_ENTITIES), (ModelName.GS3_AV, GS3_BT_OFFLINE_ENTITIES), ], ) async def test_setup_through_bluetooth_only( hass: HomeAssistant, mock_config_entry_bluetooth: MockConfigEntry, mock_lamarzocco_bluetooth: MagicMock, mock_ble_device_from_address: MagicMock, mock_cloud_client: MagicMock, device_registry: dr.DeviceRegistry, device_fixture: ModelName, entities: list[tuple[str, str]], snapshot: SnapshotAssertion, ) -> None: """Test we can setup without a cloud connection.""" # Simulate cloud connection failures mock_cloud_client.get_thing_settings.side_effect = RequestNotSuccessful("") mock_cloud_client.async_get_access_token.side_effect = RequestNotSuccessful("") mock_lamarzocco_bluetooth.get_dashboard.side_effect = RequestNotSuccessful("") mock_lamarzocco_bluetooth.get_coffee_and_flush_counter.side_effect = ( RequestNotSuccessful("") ) mock_lamarzocco_bluetooth.get_schedule.side_effect = RequestNotSuccessful("") mock_lamarzocco_bluetooth.get_settings.side_effect = RequestNotSuccessful("") await async_init_integration(hass, mock_config_entry_bluetooth) assert mock_config_entry_bluetooth.state is ConfigEntryState.LOADED # Check all Bluetooth entities are available for entity_id in entities: entity = build_entity_id( entity_id[0], mock_lamarzocco_bluetooth.serial_number, entity_id[1] ) state = hass.states.get(entity) assert state assert state.state != STATE_UNAVAILABLE assert state == snapshot(name=entity) # snapshot device device = device_registry.async_get_device( {(DOMAIN, mock_lamarzocco_bluetooth.serial_number)} ) assert device assert device == snapshot( name=f"device_bluetooth_{mock_lamarzocco_bluetooth.serial_number}" ) async def test_manual_offline_mode_no_bluetooth_device( hass: HomeAssistant, mock_lamarzocco: MagicMock, mock_config_entry_bluetooth: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test manual offline mode with no Bluetooth device found.""" mock_config_entry_bluetooth.add_to_hass(hass) hass.config_entries.async_update_entry( mock_config_entry_bluetooth, options={CONF_OFFLINE_MODE: True} ) await hass.config_entries.async_setup(mock_config_entry_bluetooth.entry_id) await hass.async_block_till_done() assert mock_config_entry_bluetooth.state is ConfigEntryState.SETUP_RETRY async def test_manual_offline_mode( hass: HomeAssistant, mock_lamarzocco: MagicMock, mock_config_entry_bluetooth: MockConfigEntry, freezer: FrozenDateTimeFactory, mock_ble_device_from_address: MagicMock, ) -> None: """Test that manual offline mode successfully sets up and updates entities via Bluetooth, and marks non-Bluetooth entities as unavailable.""" mock_config_entry_bluetooth.add_to_hass(hass) hass.config_entries.async_update_entry( mock_config_entry_bluetooth, options={CONF_OFFLINE_MODE: True} ) await hass.config_entries.async_setup(mock_config_entry_bluetooth.entry_id) await hass.async_block_till_done() main_switch = f"switch.{mock_lamarzocco.serial_number}" state = hass.states.get(main_switch) assert state assert state.state == STATE_ON # Simulate Bluetooth update changing machine mode to standby mock_lamarzocco.dashboard.config[ WidgetType.CM_MACHINE_STATUS ].mode = MachineMode.STANDBY # Trigger Bluetooth coordinator update freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # Verify entity state was updated state = hass.states.get(main_switch) assert state assert state.state == STATE_OFF # verify other entities are unavailable sample_entities = ( f"binary_sensor.{mock_lamarzocco.serial_number}_backflush_active", f"update.{mock_lamarzocco.serial_number}_gateway_firmware", ) for entity_id in sample_entities: state = hass.states.get(entity_id) assert state assert state.state == STATE_UNAVAILABLE @pytest.mark.parametrize( ("mock_ble_device", "has_client"), [ (None, False), ( BLEDevice( address="aa:bb:cc:dd:ee:ff", name="name", details={}, ), True, ), ], ) async def test_bluetooth_is_set_from_discovery( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_lamarzocco: MagicMock, mock_cloud_client: MagicMock, mock_ble_device: BLEDevice | None, has_client: bool, mock_ble_device_from_address: MagicMock, ) -> None: """Check we can fill a device from discovery info.""" service_info = get_bluetooth_service_info( ModelName.GS3_MP, mock_lamarzocco.serial_number ) mock_cloud_client.get_thing_settings.return_value.ble_auth_token = "token" with ( patch( "homeassistant.components.lamarzocco.async_discovered_service_info", return_value=[service_info], ) as discovery, patch( "homeassistant.components.lamarzocco.LaMarzoccoMachine" ) as mock_machine_class, ): mock_machine_class.return_value = mock_lamarzocco await async_init_integration(hass, mock_config_entry) discovery.assert_called_once() assert mock_machine_class.call_count == 1 _, kwargs = mock_machine_class.call_args assert (kwargs["bluetooth_client"] is not None) == has_client assert mock_config_entry.data["mac"] == service_info.address assert mock_config_entry.data["token"] == "token" async def test_disconnect_on_stop( hass: HomeAssistant, mock_config_entry_bluetooth: MockConfigEntry, mock_ble_device_from_address: MagicMock, mock_bluetooth_client: MagicMock, ) -> None: """Test we close the connection with the La Marzocco when Home Assistant stops.""" await async_init_integration(hass, mock_config_entry_bluetooth) await hass.async_block_till_done() assert mock_config_entry_bluetooth.state is ConfigEntryState.LOADED hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) await hass.async_block_till_done() mock_bluetooth_client.disconnect.assert_awaited_once()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/lamarzocco/test_bluetooth.py", "license": "Apache License 2.0", "lines": 358, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/lock/test_trigger.py
"""Test lock triggers.""" from typing import Any import pytest from homeassistant.components.lock import DOMAIN, LockState from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID from homeassistant.core import HomeAssistant, ServiceCall from tests.components import ( TriggerStateDescription, arm_trigger, other_states, parametrize_target_entities, parametrize_trigger_states, set_or_remove_state, target_entities, ) @pytest.fixture async def target_locks(hass: HomeAssistant) -> list[str]: """Create multiple lock entities associated with different targets.""" return (await target_entities(hass, DOMAIN))["included"] @pytest.mark.parametrize( "trigger_key", [ "lock.jammed", "lock.locked", "lock.opened", "lock.unlocked", ], ) async def test_lock_triggers_gated_by_labs_flag( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str ) -> None: """Test the lock triggers are gated by the labs flag.""" await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"}) assert ( "Unnamed automation failed to setup triggers and has been disabled: Trigger " f"'{trigger_key}' requires the experimental 'New triggers and conditions' " "feature to be enabled in Home Assistant Labs settings (feature flag: " "'new_triggers_conditions')" ) in caplog.text @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="lock.jammed", target_states=[LockState.JAMMED], other_states=other_states(LockState.JAMMED), ), *parametrize_trigger_states( trigger="lock.locked", target_states=[LockState.LOCKED], other_states=other_states(LockState.LOCKED), ), *parametrize_trigger_states( trigger="lock.opened", target_states=[LockState.OPEN], other_states=other_states(LockState.OPEN), ), *parametrize_trigger_states( trigger="lock.unlocked", target_states=[LockState.UNLOCKED], other_states=other_states(LockState.UNLOCKED), ), ], ) async def test_lock_state_trigger_behavior_any( hass: HomeAssistant, service_calls: list[ServiceCall], target_locks: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the lock state trigger fires when any lock state changes to a specific state.""" other_entity_ids = set(target_locks) - {entity_id} # Set all locks, including the tested one, to the initial state for eid in target_locks: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Check if changing other locks also triggers for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == (entities_in_target - 1) * state["count"] service_calls.clear() @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="lock.jammed", target_states=[LockState.JAMMED], other_states=other_states(LockState.JAMMED), ), *parametrize_trigger_states( trigger="lock.locked", target_states=[LockState.LOCKED], other_states=other_states(LockState.LOCKED), ), *parametrize_trigger_states( trigger="lock.opened", target_states=[LockState.OPEN], other_states=other_states(LockState.OPEN), ), *parametrize_trigger_states( trigger="lock.unlocked", target_states=[LockState.UNLOCKED], other_states=other_states(LockState.UNLOCKED), ), ], ) async def test_lock_state_trigger_behavior_first( hass: HomeAssistant, service_calls: list[ServiceCall], target_locks: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the lock state trigger fires when the first lock changes to a specific state.""" other_entity_ids = set(target_locks) - {entity_id} # Set all locks, including the tested one, to the initial state for eid in target_locks: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Triggering other locks should not cause the trigger to fire again for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="lock.jammed", target_states=[LockState.JAMMED], other_states=other_states(LockState.JAMMED), ), *parametrize_trigger_states( trigger="lock.locked", target_states=[LockState.LOCKED], other_states=other_states(LockState.LOCKED), ), *parametrize_trigger_states( trigger="lock.opened", target_states=[LockState.OPEN], other_states=other_states(LockState.OPEN), ), *parametrize_trigger_states( trigger="lock.unlocked", target_states=[LockState.UNLOCKED], other_states=other_states(LockState.UNLOCKED), ), ], ) async def test_lock_state_trigger_behavior_last( hass: HomeAssistant, service_calls: list[ServiceCall], target_locks: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the lock state trigger fires when the last lock changes to a specific state.""" other_entity_ids = set(target_locks) - {entity_id} # Set all locks, including the tested one, to the initial state for eid in target_locks: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config) for state in states[1:]: included_state = state["included"] for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/lock/test_trigger.py", "license": "Apache License 2.0", "lines": 222, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/nederlandse_spoorwegen/test_diagnostics.py
"""Tests for the diagnostics data provided by the Nederlandse Spoorwegen integration.""" from unittest.mock import AsyncMock import pytest from syrupy.assertion import SnapshotAssertion from syrupy.filters import props from homeassistant.components.nederlandse_spoorwegen.const import DOMAIN from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from . import setup_integration from .const import SUBENTRY_ID_1 from tests.common import MockConfigEntry from tests.components.diagnostics import ( get_diagnostics_for_config_entry, get_diagnostics_for_device, ) from tests.typing import ClientSessionGenerator @pytest.mark.freeze_time("2025-09-15 14:30:00+00:00") async def test_entry_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, mock_nsapi: AsyncMock, ) -> None: """Test config entry diagnostics.""" mock_config_entry.add_to_hass(hass) await setup_integration(hass, mock_config_entry) # Trigger update for all coordinators before diagnostics for coordinator in mock_config_entry.runtime_data.values(): await coordinator.async_refresh() result = await get_diagnostics_for_config_entry( hass, hass_client, mock_config_entry ) assert result == snapshot(exclude=props("created_at", "modified_at")) @pytest.mark.freeze_time("2025-09-15 14:30:00+00:00") async def test_device_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, device_registry: dr.DeviceRegistry, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, mock_nsapi: AsyncMock, ) -> None: """Test device diagnostics.""" # Ensure integration is set up so device exists await setup_integration(hass, mock_config_entry) device = device_registry.async_get_device(identifiers={(DOMAIN, SUBENTRY_ID_1)}) assert device is not None # Trigger update for the coordinator before diagnostics coordinator = mock_config_entry.runtime_data[SUBENTRY_ID_1] await coordinator.async_refresh() result = await get_diagnostics_for_device( hass, hass_client, mock_config_entry, device ) assert result == snapshot(exclude=props("created_at", "modified_at"))
{ "repo_id": "home-assistant/core", "file_path": "tests/components/nederlandse_spoorwegen/test_diagnostics.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:tests/components/nintendo_parental_controls/test_select.py
"""Tests for Nintendo Switch Parental Controls select platform.""" from unittest.mock import AsyncMock, patch from pynintendoparental.enum import DeviceTimerMode from syrupy.assertion import SnapshotAssertion from homeassistant.components.select import ( ATTR_OPTION, DOMAIN as SELECT_DOMAIN, SERVICE_SELECT_OPTION, ) 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 from tests.common import MockConfigEntry, snapshot_platform async def test_select( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_nintendo_client: AsyncMock, mock_nintendo_device: AsyncMock, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test select platform.""" with patch( "homeassistant.components.nintendo_parental_controls._PLATFORMS", [Platform.SELECT], ): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_select_option( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_nintendo_client: AsyncMock, mock_nintendo_device: AsyncMock, ) -> None: """Test select option service.""" with patch( "homeassistant.components.nintendo_parental_controls._PLATFORMS", [Platform.SELECT], ): await setup_integration(hass, mock_config_entry) await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.home_assistant_test_restriction_mode", ATTR_OPTION: DeviceTimerMode.EACH_DAY_OF_THE_WEEK.name.lower(), }, blocking=True, ) mock_nintendo_device.set_timer_mode.assert_awaited_once_with( DeviceTimerMode.EACH_DAY_OF_THE_WEEK )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/nintendo_parental_controls/test_select.py", "license": "Apache License 2.0", "lines": 53, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/openrgb/test_select.py
"""Tests for the OpenRGB select platform.""" from collections.abc import Generator from types import SimpleNamespace from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory from openrgb.utils import OpenRGBDisconnected import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.openrgb.const import DOMAIN, SCAN_INTERVAL from homeassistant.components.select import DOMAIN as SELECT_DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_OPTION, SERVICE_SELECT_OPTION, STATE_UNAVAILABLE, Platform, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import device_registry as dr, entity_registry as er from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.fixture(autouse=True) def select_only() -> Generator[None]: """Enable only the select platform.""" with patch( "homeassistant.components.openrgb.PLATFORMS", [Platform.SELECT], ): yield @pytest.fixture def mock_profiles() -> list[SimpleNamespace]: """Return a list of mock profiles.""" return [ SimpleNamespace(name="Gaming"), SimpleNamespace(name="Work"), SimpleNamespace(name="Rainbow"), ] # Test basic entity setup and configuration @pytest.mark.usefixtures("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 select entities.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) # Ensure entity is correctly assigned to the OpenRGB server device device_entry = device_registry.async_get_device( identifiers={(DOMAIN, mock_config_entry.entry_id)} ) assert device_entry entity_entries = er.async_entries_for_config_entry( entity_registry, mock_config_entry.entry_id ) assert len(entity_entries) == 1 assert entity_entries[0].device_id == device_entry.id @pytest.mark.usefixtures("mock_openrgb_client") async def test_select_with_profiles( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, mock_profiles: list[SimpleNamespace], ) -> None: """Test select entity with available profiles.""" mock_openrgb_client.profiles = mock_profiles 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 ConfigEntryState.LOADED # Verify select entity has profile options state = hass.states.get("select.test_computer_profile") assert state assert state.attributes.get("options") == ["Gaming", "Work", "Rainbow"] @pytest.mark.usefixtures("mock_openrgb_client") async def test_select_with_no_profiles( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, ) -> None: """Test select entity when no profiles are available.""" mock_openrgb_client.profiles = [] 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 ConfigEntryState.LOADED # Verify select entity is unavailable when no profiles exist state = hass.states.get("select.test_computer_profile") assert state assert state.state == STATE_UNAVAILABLE assert state.attributes.get("options") == [] @pytest.mark.usefixtures("mock_openrgb_client") async def test_select_option_success( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, mock_profiles: list[SimpleNamespace], ) -> None: """Test selecting a profile successfully.""" mock_openrgb_client.profiles = mock_profiles 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 ConfigEntryState.LOADED # Select a profile await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.test_computer_profile", ATTR_OPTION: "Gaming", }, blocking=True, ) # Verify load_profile was called with the correct profile name mock_openrgb_client.load_profile.assert_called_once_with("Gaming") # Verify the current option is set to the selected profile state = hass.states.get("select.test_computer_profile") assert state assert state.state == "Gaming" @pytest.mark.usefixtures("mock_openrgb_client") async def test_select_option_not_found( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, mock_profiles: list[SimpleNamespace], ) -> None: """Test selecting a profile that doesn't exist.""" mock_openrgb_client.profiles = mock_profiles 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 ConfigEntryState.LOADED # Try to select a non-existent profile # The select platform will validate that the option is in the options list with pytest.raises( ServiceValidationError, match="Option NonExistent is not valid for entity select.test_computer_profile", ): await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.test_computer_profile", ATTR_OPTION: "NonExistent", }, blocking=True, ) @pytest.mark.usefixtures("mock_openrgb_client") async def test_select_option_connection_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, mock_profiles: list[SimpleNamespace], ) -> None: """Test selecting a profile with connection error.""" mock_openrgb_client.profiles = mock_profiles mock_openrgb_client.load_profile.side_effect = OpenRGBDisconnected( "Connection lost" ) 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 ConfigEntryState.LOADED # Try to select a profile - should raise HomeAssistantError with pytest.raises(HomeAssistantError): await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.test_computer_profile", ATTR_OPTION: "Gaming", }, blocking=True, ) @pytest.mark.usefixtures("mock_openrgb_client") async def test_select_option_value_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, mock_profiles: list[SimpleNamespace], ) -> None: """Test selecting a profile with ValueError.""" mock_openrgb_client.profiles = mock_profiles mock_openrgb_client.load_profile.side_effect = ValueError("Invalid profile data") 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 ConfigEntryState.LOADED # Try to select a profile - should raise HomeAssistantError with pytest.raises(HomeAssistantError): await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.test_computer_profile", ATTR_OPTION: "Gaming", }, blocking=True, ) @pytest.mark.usefixtures("mock_openrgb_client") async def test_profiles_update_on_refresh( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, mock_profiles: list[SimpleNamespace], freezer: FrozenDateTimeFactory, ) -> None: """Test that profile list updates when profiles change.""" # Start with initial profiles mock_openrgb_client.profiles = mock_profiles[:2] # Only Gaming and Work 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 ConfigEntryState.LOADED # Verify initial profile options state = hass.states.get("select.test_computer_profile") assert state assert state.attributes.get("options") == ["Gaming", "Work"] # Add a new profile mock_openrgb_client.profiles = mock_profiles # All three profiles freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() await hass.async_block_till_done() # Verify updated profile options state = hass.states.get("select.test_computer_profile") assert state assert state.attributes.get("options") == ["Gaming", "Work", "Rainbow"] @pytest.mark.usefixtures("mock_openrgb_client") async def test_select_becomes_unavailable_when_profiles_removed( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, mock_profiles: list[SimpleNamespace], freezer: FrozenDateTimeFactory, ) -> None: """Test select becomes unavailable when all profiles are removed.""" # Start with profiles mock_openrgb_client.profiles = mock_profiles 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 ConfigEntryState.LOADED # Verify select entity is available with profiles state = hass.states.get("select.test_computer_profile") assert state assert state.state != STATE_UNAVAILABLE assert state.attributes.get("options") == ["Gaming", "Work", "Rainbow"] # Remove all profiles mock_openrgb_client.profiles = [] freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() await hass.async_block_till_done() # Verify select entity becomes unavailable state = hass.states.get("select.test_computer_profile") assert state assert state.state == STATE_UNAVAILABLE assert state.attributes.get("options") == [] @pytest.mark.usefixtures("mock_openrgb_client") async def test_current_option_cleared_when_device_state_changes( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, mock_openrgb_device: MagicMock, mock_profiles: list[SimpleNamespace], freezer: FrozenDateTimeFactory, ) -> None: """Test current option is cleared when device state changes externally.""" mock_openrgb_client.profiles = mock_profiles 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 ConfigEntryState.LOADED # Select a profile await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.test_computer_profile", ATTR_OPTION: "Gaming", }, blocking=True, ) # Verify the current option is set state = hass.states.get("select.test_computer_profile") assert state assert state.state == "Gaming" # Simulate external device state change by modifying active_mode mock_openrgb_device.active_mode = 0 freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() await hass.async_block_till_done() # Verify current option is cleared because device state changed state = hass.states.get("select.test_computer_profile") assert state assert state.state == "unknown" @pytest.mark.usefixtures("mock_openrgb_client") async def test_current_option_cleared_when_colors_change( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_openrgb_client: MagicMock, mock_openrgb_device: MagicMock, mock_profiles: list[SimpleNamespace], freezer: FrozenDateTimeFactory, ) -> None: """Test current option is cleared when device colors change externally.""" mock_openrgb_client.profiles = mock_profiles 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 ConfigEntryState.LOADED # Select a profile await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.test_computer_profile", ATTR_OPTION: "Work", }, blocking=True, ) # Verify the current option is set state = hass.states.get("select.test_computer_profile") assert state assert state.state == "Work" # Simulate external color change mock_openrgb_device.colors[0].red = 0 mock_openrgb_device.colors[0].green = 255 freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() await hass.async_block_till_done() # Verify current option is cleared because device colors changed state = hass.states.get("select.test_computer_profile") assert state assert state.state == "unknown"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/openrgb/test_select.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/pooldose/test_number.py
"""Tests for the Seko PoolDose number platform.""" from copy import deepcopy from datetime import timedelta from unittest.mock import AsyncMock from freezegun.api import FrozenDateTimeFactory from pooldose.request_status import RequestStatus import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.number import DOMAIN as NUMBER_DOMAIN, SERVICE_SET_VALUE from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import entity_registry as er 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.NUMBER] @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_all_numbers( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test the Pooldose numbers.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("init_integration") async def test_number_entity_unavailable_no_coordinator_data( hass: HomeAssistant, init_integration: MockConfigEntry, mock_pooldose_client: AsyncMock, freezer: FrozenDateTimeFactory, ) -> None: """Test number entity becomes unavailable when coordinator has no data.""" # Verify entity has a state initially ph_target_state = hass.states.get("number.pool_device_ph_target") assert ph_target_state.state == "6.5" # Update coordinator data to None mock_pooldose_client.instant_values_structured.return_value = (None, None) freezer.tick(timedelta(minutes=5)) async_fire_time_changed(hass) await hass.async_block_till_done() # Check entity becomes unavailable ph_target_state = hass.states.get("number.pool_device_ph_target") assert ph_target_state.state == "unavailable" @pytest.mark.usefixtures("init_integration") async def test_number_state_changes( hass: HomeAssistant, init_integration: MockConfigEntry, mock_pooldose_client: AsyncMock, freezer: FrozenDateTimeFactory, ) -> None: """Test number state changes when coordinator updates.""" # Initial state ph_target_state = hass.states.get("number.pool_device_ph_target") assert ph_target_state.state == "6.5" # Update coordinator data with number value changed current_data = mock_pooldose_client.instant_values_structured.return_value[1] updated_data = deepcopy(current_data) updated_data["number"]["ph_target"]["value"] = 7.2 mock_pooldose_client.instant_values_structured.return_value = ( RequestStatus.SUCCESS, updated_data, ) freezer.tick(timedelta(minutes=5)) async_fire_time_changed(hass) await hass.async_block_till_done() # Check state changed ph_target_state = hass.states.get("number.pool_device_ph_target") assert ph_target_state.state == "7.2" @pytest.mark.usefixtures("init_integration") async def test_set_number_value( hass: HomeAssistant, mock_pooldose_client: AsyncMock, ) -> None: """Test setting a number value.""" # Verify initial state ph_target_state = hass.states.get("number.pool_device_ph_target") assert ph_target_state.state == "6.5" # Set new value await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, {ATTR_ENTITY_ID: "number.pool_device_ph_target", "value": 7.0}, blocking=True, ) # Verify API was called mock_pooldose_client.set_number.assert_called_once_with("ph_target", 7.0) # Verify state updated immediately (optimistic update) ph_target_state = hass.states.get("number.pool_device_ph_target") assert ph_target_state.state == "7.0" @pytest.mark.usefixtures("init_integration") async def test_actions_cannot_connect_number( hass: HomeAssistant, mock_pooldose_client: AsyncMock, init_integration: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """When the client write method raises, ServiceValidationError('cannot_connect') is raised.""" client = mock_pooldose_client entity_id = "number.pool_device_ph_target" before = hass.states.get(entity_id) assert before is not None client.is_connected = False client.set_number = AsyncMock(return_value=False) with pytest.raises(ServiceValidationError) as excinfo: await hass.services.async_call( "number", "set_value", {"entity_id": entity_id, "value": 7.0}, blocking=True ) assert excinfo.value.translation_key == "cannot_connect" after = hass.states.get(entity_id) assert after is not None assert before.state == after.state @pytest.mark.usefixtures("init_integration") async def test_actions_write_rejected_number( hass: HomeAssistant, mock_pooldose_client: AsyncMock, init_integration: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """When the client write method returns False, ServiceValidationError('write_rejected') is raised.""" client = mock_pooldose_client entity_id = "number.pool_device_ph_target" before = hass.states.get(entity_id) assert before is not None client.set_number = AsyncMock(return_value=False) with pytest.raises(ServiceValidationError) as excinfo: await hass.services.async_call( "number", "set_value", {"entity_id": entity_id, "value": 7.0}, blocking=True ) assert excinfo.value.translation_key == "write_rejected" after = hass.states.get(entity_id) assert after is not None assert before.state == after.state
{ "repo_id": "home-assistant/core", "file_path": "tests/components/pooldose/test_number.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:tests/components/pooldose/test_select.py
"""Tests for the Seko PoolDose select platform.""" from datetime import timedelta from unittest.mock import AsyncMock from freezegun.api import FrozenDateTimeFactory from pooldose.request_status import RequestStatus import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.select import DOMAIN as SELECT_DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_OPTION, Platform, UnitOfVolume, UnitOfVolumeFlowRate, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import entity_registry as er 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.SELECT] @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_all_selects( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test the Pooldose select entities.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_select_entity_unavailable_no_coordinator_data( hass: HomeAssistant, init_integration: MockConfigEntry, mock_pooldose_client: AsyncMock, freezer: FrozenDateTimeFactory, ) -> None: """Test select entity becomes unavailable when coordinator has no data.""" # Verify entity has a state initially water_meter_state = hass.states.get("select.pool_device_water_meter_unit") assert water_meter_state.state == UnitOfVolume.CUBIC_METERS # Update coordinator data to None mock_pooldose_client.instant_values_structured.return_value = (None, None) freezer.tick(timedelta(minutes=5)) async_fire_time_changed(hass) await hass.async_block_till_done() # Check entity becomes unavailable water_meter_state = hass.states.get("select.pool_device_water_meter_unit") assert water_meter_state.state == "unavailable" @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_select_state_changes( hass: HomeAssistant, init_integration: MockConfigEntry, mock_pooldose_client: AsyncMock, freezer: FrozenDateTimeFactory, ) -> None: """Test select state changes when coordinator updates.""" # Initial state ph_method_state = hass.states.get("select.pool_device_ph_dosing_method") assert ph_method_state.state == "proportional" # Update coordinator data with select value changed current_data = mock_pooldose_client.instant_values_structured.return_value[1] updated_data = current_data.copy() updated_data["select"]["ph_type_dosing_method"]["value"] = "timed" mock_pooldose_client.instant_values_structured.return_value = ( RequestStatus.SUCCESS, updated_data, ) freezer.tick(timedelta(minutes=5)) async_fire_time_changed(hass) await hass.async_block_till_done() # Check state changed ph_method_state = hass.states.get("select.pool_device_ph_dosing_method") assert ph_method_state.state == "timed" @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_select_option_unit_conversion( hass: HomeAssistant, mock_pooldose_client: AsyncMock, ) -> None: """Test selecting an option with unit conversion (HA unit -> API value).""" # Verify initial state is m³ (displayed as Unicode) water_meter_state = hass.states.get("select.pool_device_water_meter_unit") assert water_meter_state.state == UnitOfVolume.CUBIC_METERS # Select Liters option await hass.services.async_call( SELECT_DOMAIN, "select_option", { ATTR_ENTITY_ID: "select.pool_device_water_meter_unit", ATTR_OPTION: UnitOfVolume.LITERS, }, blocking=True, ) # Verify API was called with "L" (not Unicode) mock_pooldose_client.set_select.assert_called_once_with("water_meter_unit", "L") # Verify state updated to L (Unicode) water_meter_state = hass.states.get("select.pool_device_water_meter_unit") assert water_meter_state.state == UnitOfVolume.LITERS @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_select_option_flow_rate_unit_conversion( hass: HomeAssistant, mock_pooldose_client: AsyncMock, ) -> None: """Test selecting flow rate unit with conversion.""" # Verify initial state flow_rate_state = hass.states.get("select.pool_device_flow_rate_unit") assert flow_rate_state.state == UnitOfVolumeFlowRate.LITERS_PER_SECOND # Select cubic meters per hour await hass.services.async_call( SELECT_DOMAIN, "select_option", { ATTR_ENTITY_ID: "select.pool_device_flow_rate_unit", ATTR_OPTION: UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR, }, blocking=True, ) # Verify API was called with "m3/h" (not Unicode m³/h) mock_pooldose_client.set_select.assert_called_once_with("flow_rate_unit", "m3/h") # Verify state updated to m³/h (with Unicode) flow_rate_state = hass.states.get("select.pool_device_flow_rate_unit") assert flow_rate_state.state == UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR @pytest.mark.usefixtures("init_integration") async def test_select_option_no_conversion( hass: HomeAssistant, mock_pooldose_client: AsyncMock, ) -> None: """Test selecting an option without unit conversion.""" # Verify initial state ph_set_state = hass.states.get("select.pool_device_ph_dosing_set") assert ph_set_state.state == "acid" # Select alkaline option await hass.services.async_call( SELECT_DOMAIN, "select_option", { ATTR_ENTITY_ID: "select.pool_device_ph_dosing_set", ATTR_OPTION: "alcalyne", }, blocking=True, ) # Verify API was called with exact value mock_pooldose_client.set_select.assert_called_once_with( "ph_type_dosing_set", "alcalyne" ) # Verify state updated ph_set_state = hass.states.get("select.pool_device_ph_dosing_set") assert ph_set_state.state == "alcalyne" @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_select_dosing_method_options( hass: HomeAssistant, mock_pooldose_client: AsyncMock, ) -> None: """Test selecting different dosing method options.""" # Test ORP dosing method orp_method_state = hass.states.get("select.pool_device_orp_dosing_method") assert orp_method_state.state == "on_off" # Change to proportional await hass.services.async_call( SELECT_DOMAIN, "select_option", { ATTR_ENTITY_ID: "select.pool_device_orp_dosing_method", ATTR_OPTION: "proportional", }, blocking=True, ) # Verify API call mock_pooldose_client.set_select.assert_called_once_with( "orp_type_dosing_method", "proportional" ) # Verify state orp_method_state = hass.states.get("select.pool_device_orp_dosing_method") assert orp_method_state.state == "proportional" @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_select_dosing_set_high_low( hass: HomeAssistant, mock_pooldose_client: AsyncMock, ) -> None: """Test selecting high/low dosing intensity.""" # Chlorine dosing set starts as high in fixture cl_set_state = hass.states.get("select.pool_device_chlorine_dosing_set") assert cl_set_state.state == "high" # Change to low await hass.services.async_call( SELECT_DOMAIN, "select_option", { ATTR_ENTITY_ID: "select.pool_device_chlorine_dosing_set", ATTR_OPTION: "low", }, blocking=True, ) # Verify API call mock_pooldose_client.set_select.assert_called_once_with("cl_type_dosing_set", "low") # Verify state cl_set_state = hass.states.get("select.pool_device_chlorine_dosing_set") assert cl_set_state.state == "low" @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_actions_cannot_connect_select( hass: HomeAssistant, mock_pooldose_client: AsyncMock, init_integration: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """When the client write method raises, ServiceValidationError('cannot_connect') is raised.""" client = mock_pooldose_client entity_id = "select.pool_device_ph_dosing_set" before = hass.states.get(entity_id) assert before is not None client.is_connected = False client.set_select = AsyncMock(return_value=False) with pytest.raises(ServiceValidationError) as excinfo: await hass.services.async_call( "select", "select_option", {"entity_id": entity_id, "option": "acid"}, blocking=True, ) assert excinfo.value.translation_key == "cannot_connect" after = hass.states.get(entity_id) assert after is not None assert before.state == after.state @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_actions_write_rejected_select( hass: HomeAssistant, mock_pooldose_client: AsyncMock, init_integration: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """When the client write method returns False, ServiceValidationError('write_rejected') is raised.""" client = mock_pooldose_client entity_id = "select.pool_device_ph_dosing_set" before = hass.states.get(entity_id) assert before is not None client.set_select = AsyncMock(return_value=False) with pytest.raises(ServiceValidationError) as excinfo: await hass.services.async_call( "select", "select_option", {"entity_id": entity_id, "option": "acid"}, blocking=True, ) assert excinfo.value.translation_key == "write_rejected" after = hass.states.get(entity_id) assert after is not None assert before.state == after.state
{ "repo_id": "home-assistant/core", "file_path": "tests/components/pooldose/test_select.py", "license": "Apache License 2.0", "lines": 249, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/risco/test_services.py
"""Tests for the Risco services.""" from datetime import datetime from unittest.mock import patch import pytest from homeassistant.components.risco import DOMAIN from homeassistant.components.risco.const import SERVICE_SET_TIME from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ATTR_CONFIG_ENTRY_ID, ATTR_TIME from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from .conftest import TEST_CLOUD_CONFIG from tests.common import MockConfigEntry async def test_set_time_service( hass: HomeAssistant, setup_risco_local, local_config_entry ) -> None: """Test the set_time service.""" with patch("homeassistant.components.risco.RiscoLocal.set_time") as mock: time_str = "2025-02-21T12:00:00" time = datetime.fromisoformat(time_str) data = { ATTR_CONFIG_ENTRY_ID: local_config_entry.entry_id, ATTR_TIME: time_str, } await hass.services.async_call( DOMAIN, SERVICE_SET_TIME, service_data=data, blocking=True ) mock.assert_called_once_with(time) @pytest.mark.freeze_time("2025-02-21T12:00:00Z") async def test_set_time_service_with_no_time( hass: HomeAssistant, setup_risco_local, local_config_entry ) -> None: """Test the set_time service when no time is provided.""" with patch("homeassistant.components.risco.RiscoLocal.set_time") as mock_set_time: data = { "config_entry_id": local_config_entry.entry_id, } await hass.services.async_call( DOMAIN, SERVICE_SET_TIME, service_data=data, blocking=True ) mock_set_time.assert_called_once_with(datetime.now()) async def test_set_time_service_with_invalid_entry( hass: HomeAssistant, setup_risco_local ) -> None: """Test the set_time service with an invalid config entry.""" data = { ATTR_CONFIG_ENTRY_ID: "invalid_entry_id", } with pytest.raises(ServiceValidationError) as err: await hass.services.async_call( DOMAIN, SERVICE_SET_TIME, service_data=data, blocking=True ) assert err.value.translation_key == "service_config_entry_not_found" async def test_set_time_service_with_not_loaded_entry( hass: HomeAssistant, setup_risco_local, local_config_entry ) -> None: """Test the set_time service with a config entry that is not loaded.""" await hass.config_entries.async_unload(local_config_entry.entry_id) await hass.async_block_till_done() assert local_config_entry.state is ConfigEntryState.NOT_LOADED data = { ATTR_CONFIG_ENTRY_ID: local_config_entry.entry_id, } with pytest.raises(ServiceValidationError) as err: await hass.services.async_call( DOMAIN, SERVICE_SET_TIME, service_data=data, blocking=True ) assert err.value.translation_key == "service_config_entry_not_loaded" async def test_set_time_service_with_cloud_entry( hass: HomeAssistant, setup_risco_local ) -> None: """Test the set_time service with a cloud config entry.""" cloud_entry = MockConfigEntry( domain=DOMAIN, unique_id="test-cloud", data=TEST_CLOUD_CONFIG, ) cloud_entry.add_to_hass(hass) cloud_entry.mock_state(hass, ConfigEntryState.LOADED) data = { ATTR_CONFIG_ENTRY_ID: cloud_entry.entry_id, } with pytest.raises( ServiceValidationError, match="This service only works with local" ): await hass.services.async_call( DOMAIN, SERVICE_SET_TIME, service_data=data, blocking=True )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/risco/test_services.py", "license": "Apache License 2.0", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/saunum/test_binary_sensor.py
"""Test the Saunum binary sensor platform.""" from __future__ import annotations from dataclasses import replace from freezegun.api import FrozenDateTimeFactory from pysaunum import SaunumException import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import STATE_UNAVAILABLE, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er 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.BINARY_SENSOR] @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, ) -> None: """Test all entities.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_binary_sensor_not_created_when_value_is_none( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_saunum_client, ) -> None: """Test binary sensors are not created when initial value is None.""" base_data = mock_saunum_client.async_get_data.return_value mock_saunum_client.async_get_data.return_value = replace( base_data, door_open=None, alarm_door_open=None, alarm_door_sensor=None, alarm_thermal_cutoff=None, alarm_internal_temp=None, alarm_temp_sensor_short=None, alarm_temp_sensor_open=None, ) 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 hass.states.get("binary_sensor.saunum_leil_door") is None assert hass.states.get("binary_sensor.saunum_leil_alarm_door_open") is None assert hass.states.get("binary_sensor.saunum_leil_alarm_door_sensor") is None assert hass.states.get("binary_sensor.saunum_leil_alarm_thermal_cutoff") is None assert hass.states.get("binary_sensor.saunum_leil_alarm_internal_temp") is None assert hass.states.get("binary_sensor.saunum_leil_alarm_temp_sensor_short") is None assert hass.states.get("binary_sensor.saunum_leil_alarm_temp_sensor_open") is None @pytest.mark.usefixtures("init_integration") async def test_entity_unavailable_on_update_failure( hass: HomeAssistant, mock_saunum_client, freezer: FrozenDateTimeFactory, ) -> None: """Test that entity becomes unavailable when coordinator update fails.""" entity_id = "binary_sensor.saunum_leil_door" # Verify entity is initially available state = hass.states.get(entity_id) assert state is not None assert state.state != STATE_UNAVAILABLE # Make the next update fail mock_saunum_client.async_get_data.side_effect = SaunumException("Read error") # Move time forward to trigger a coordinator update (60 seconds) freezer.tick(60) async_fire_time_changed(hass) await hass.async_block_till_done() # Entity should now be unavailable state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE
{ "repo_id": "home-assistant/core", "file_path": "tests/components/saunum/test_binary_sensor.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/saunum/test_sensor.py
"""Test the Saunum sensor platform.""" from __future__ import annotations from dataclasses import replace from freezegun.api import FrozenDateTimeFactory from pysaunum import SaunumException import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import STATE_UNAVAILABLE, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er 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.SENSOR] @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, ) -> None: """Test all entities.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_sensor_not_created_when_value_is_none( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_saunum_client, ) -> None: """Test sensors are not created when initial value is None.""" base_data = mock_saunum_client.async_get_data.return_value mock_saunum_client.async_get_data.return_value = replace( base_data, current_temperature=None, heater_elements_active=None, on_time=None, ) 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 hass.states.get("sensor.saunum_leil_current_temperature") is None assert hass.states.get("sensor.saunum_leil_heater_elements_active") is None assert hass.states.get("sensor.saunum_leil_on_time") is None @pytest.mark.usefixtures("init_integration") async def test_entity_unavailable_on_update_failure( hass: HomeAssistant, mock_saunum_client, freezer: FrozenDateTimeFactory, ) -> None: """Test that entity becomes unavailable when coordinator update fails.""" entity_id = "sensor.saunum_leil_temperature" # Verify entity is initially available state = hass.states.get(entity_id) assert state is not None assert state.state != STATE_UNAVAILABLE # Make the next update fail mock_saunum_client.async_get_data.side_effect = SaunumException("Read error") # Move time forward to trigger a coordinator update (60 seconds) freezer.tick(60) async_fire_time_changed(hass) await hass.async_block_till_done() # Entity should now be unavailable state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE
{ "repo_id": "home-assistant/core", "file_path": "tests/components/saunum/test_sensor.py", "license": "Apache License 2.0", "lines": 65, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/scene/test_trigger.py
"""Test scene trigger.""" import pytest from homeassistant.const import ( ATTR_LABEL_ID, CONF_ENTITY_ID, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import HomeAssistant, ServiceCall from tests.components import ( TriggerStateDescription, arm_trigger, parametrize_target_entities, set_or_remove_state, target_entities, ) @pytest.fixture async def target_scenes(hass: HomeAssistant) -> list[str]: """Create multiple scene entities associated with different targets.""" return (await target_entities(hass, "scene"))["included"] @pytest.mark.parametrize("trigger_key", ["scene.activated"]) async def test_scene_triggers_gated_by_labs_flag( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str ) -> None: """Test the scene triggers are gated by the labs flag.""" await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"}) assert ( "Unnamed automation failed to setup triggers and has been disabled: Trigger " f"'{trigger_key}' requires the experimental 'New triggers and conditions' " "feature to be enabled in Home Assistant Labs settings (feature flag: " "'new_triggers_conditions')" ) in caplog.text @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities("scene"), ) @pytest.mark.parametrize( ("trigger", "states"), [ ( "scene.activated", [ {"included": {"state": None, "attributes": {}}, "count": 0}, { "included": { "state": "2021-01-01T23:59:59+00:00", "attributes": {}, }, "count": 0, }, { "included": { "state": "2022-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, ], ), ( "scene.activated", [ {"included": {"state": "foo", "attributes": {}}, "count": 0}, { "included": { "state": "2021-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, { "included": { "state": "2022-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, ], ), ( "scene.activated", [ { "included": {"state": STATE_UNAVAILABLE, "attributes": {}}, "count": 0, }, { "included": { "state": "2021-01-01T23:59:59+00:00", "attributes": {}, }, "count": 0, }, { "included": { "state": "2022-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, { "included": {"state": STATE_UNAVAILABLE, "attributes": {}}, "count": 0, }, ], ), ( "scene.activated", [ {"included": {"state": STATE_UNKNOWN, "attributes": {}}, "count": 0}, { "included": { "state": "2021-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, { "included": { "state": "2022-01-01T23:59:59+00:00", "attributes": {}, }, "count": 1, }, {"included": {"state": STATE_UNKNOWN, "attributes": {}}, "count": 0}, ], ), ], ) async def test_scene_state_trigger_behavior_any( hass: HomeAssistant, service_calls: list[ServiceCall], target_scenes: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, states: list[TriggerStateDescription], ) -> None: """Test that the scene state trigger fires when any scene state changes to a specific state.""" other_entity_ids = set(target_scenes) - {entity_id} # Set all scenes, including the tested scene, to the initial state for eid in target_scenes: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, None, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Check if changing other scenes also triggers for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == (entities_in_target - 1) * state["count"] service_calls.clear()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/scene/test_trigger.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/shelly/test_services.py
"""Tests for Shelly services.""" from unittest.mock import Mock from aioshelly.exceptions import DeviceConnectionError, RpcCallError import pytest from homeassistant.components.shelly.const import ATTR_KEY, ATTR_VALUE, DOMAIN from homeassistant.components.shelly.services import ( SERVICE_GET_KVS_VALUE, SERVICE_SET_KVS_VALUE, ) from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ATTR_DEVICE_ID from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import device_registry as dr from . import init_integration from tests.common import MockConfigEntry async def test_service_get_kvs_value( hass: HomeAssistant, mock_rpc_device: Mock, device_registry: dr.DeviceRegistry, ) -> None: """Test get_kvs_value service.""" entry = await init_integration(hass, 2) device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] mock_rpc_device.kvs_get.return_value = { "etag": "16mLia9TRt8lGhj9Zf5Dp6Hw==", "value": "test_value", } response = await hass.services.async_call( DOMAIN, SERVICE_GET_KVS_VALUE, {ATTR_DEVICE_ID: device.id, ATTR_KEY: "test_key"}, blocking=True, return_response=True, ) assert response == {"value": "test_value"} mock_rpc_device.kvs_get.assert_called_once_with("test_key") async def test_service_get_kvs_value_invalid_device(hass: HomeAssistant) -> None: """Test get_kvs_value service with invalid device ID.""" await init_integration(hass, 2) with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_GET_KVS_VALUE, {ATTR_DEVICE_ID: "invalid_device_id", ATTR_KEY: "test_key"}, blocking=True, return_response=True, ) assert exc_info.value.translation_domain == DOMAIN assert exc_info.value.translation_key == "invalid_device_id" assert exc_info.value.translation_placeholders == { ATTR_DEVICE_ID: "invalid_device_id" } async def test_service_get_kvs_value_block_device( hass: HomeAssistant, mock_block_device: Mock, device_registry: dr.DeviceRegistry ) -> None: """Test get_kvs_value service with non-RPC (Gen1) device.""" entry = await init_integration(hass, 1) device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_GET_KVS_VALUE, {ATTR_DEVICE_ID: device.id, ATTR_KEY: "test_key"}, blocking=True, return_response=True, ) assert exc_info.value.translation_domain == DOMAIN assert exc_info.value.translation_key == "kvs_not_supported" assert exc_info.value.translation_placeholders == {"device": entry.title} @pytest.mark.parametrize( ("exc", "translation_key"), [ (RpcCallError(999), "rpc_call_error"), (DeviceConnectionError, "device_communication_error"), ], ) async def test_service_get_kvs_value_exc( hass: HomeAssistant, mock_rpc_device: Mock, device_registry: dr.DeviceRegistry, exc: Exception, translation_key: str, ) -> None: """Test get_kvs_value service with exception.""" entry = await init_integration(hass, 2) device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] mock_rpc_device.kvs_get.side_effect = exc with pytest.raises(HomeAssistantError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_GET_KVS_VALUE, {ATTR_DEVICE_ID: device.id, ATTR_KEY: "test_key"}, blocking=True, return_response=True, ) assert exc_info.value.translation_domain == DOMAIN assert exc_info.value.translation_key == translation_key assert exc_info.value.translation_placeholders == {"device": entry.title} async def test_config_entry_not_loaded( hass: HomeAssistant, device_registry: dr.DeviceRegistry, mock_rpc_device: Mock, ) -> None: """Test config entry not loaded.""" entry = await init_integration(hass, 2) device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] await hass.config_entries.async_unload(entry.entry_id) await hass.async_block_till_done() assert entry.state is ConfigEntryState.NOT_LOADED with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_GET_KVS_VALUE, {ATTR_DEVICE_ID: device.id, ATTR_KEY: "test_key"}, blocking=True, return_response=True, ) assert exc_info.value.translation_domain == DOMAIN assert exc_info.value.translation_key == "entry_not_loaded" assert exc_info.value.translation_placeholders == {"device": entry.title} async def test_service_get_kvs_value_sleeping_device( hass: HomeAssistant, mock_rpc_device: Mock, device_registry: dr.DeviceRegistry ) -> None: """Test get_kvs_value service with RPC sleeping device.""" entry = await init_integration(hass, 2, sleep_period=1000) # Make device online mock_rpc_device.mock_online() await hass.async_block_till_done(wait_background_tasks=True) device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_GET_KVS_VALUE, {ATTR_DEVICE_ID: device.id, ATTR_KEY: "test_key"}, blocking=True, return_response=True, ) assert exc_info.value.translation_domain == DOMAIN assert exc_info.value.translation_key == "kvs_not_supported" assert exc_info.value.translation_placeholders == {"device": entry.title} async def test_service_set_kvs_value( hass: HomeAssistant, mock_rpc_device: Mock, device_registry: dr.DeviceRegistry, ) -> None: """Test set_kvs_value service.""" entry = await init_integration(hass, 2) device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] await hass.services.async_call( DOMAIN, SERVICE_SET_KVS_VALUE, {ATTR_DEVICE_ID: device.id, ATTR_KEY: "test_key", ATTR_VALUE: "test_value"}, blocking=True, ) mock_rpc_device.kvs_set.assert_called_once_with("test_key", "test_value") async def test_service_get_kvs_value_config_entry_not_found( hass: HomeAssistant, mock_rpc_device: Mock, device_registry: dr.DeviceRegistry ) -> None: """Test device with no config entries.""" entry = await init_integration(hass, 2) device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] # Remove all config entries from device device_registry.devices[device.id].config_entries.clear() with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_GET_KVS_VALUE, {ATTR_DEVICE_ID: device.id, ATTR_KEY: "test_key"}, blocking=True, return_response=True, ) assert exc_info.value.translation_domain == DOMAIN assert exc_info.value.translation_key == "config_entry_not_found" assert exc_info.value.translation_placeholders == {"device_id": device.id} async def test_service_get_kvs_value_device_not_initialized( hass: HomeAssistant, mock_rpc_device: Mock, device_registry: dr.DeviceRegistry, monkeypatch: pytest.MonkeyPatch, ) -> None: """Test get_kvs_value if runtime_data.rpc is None.""" entry = await init_integration(hass, 2) device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] monkeypatch.delattr(entry.runtime_data, "rpc") with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_GET_KVS_VALUE, {ATTR_DEVICE_ID: device.id, ATTR_KEY: "test_key"}, blocking=True, return_response=True, ) assert exc_info.value.translation_domain == DOMAIN assert exc_info.value.translation_key == "device_not_initialized" assert exc_info.value.translation_placeholders == {"device": entry.title} async def test_service_get_kvs_value_wrong_domain( hass: HomeAssistant, mock_rpc_device: Mock, device_registry: dr.DeviceRegistry, ) -> None: """Test get_kvs_value when device has config entries from different domains.""" entry = await init_integration(hass, 2) device = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] # Create a config entry with different domain and add it to the device other_entry = MockConfigEntry( domain="other_domain", data={}, ) other_entry.add_to_hass(hass) # Add the other domain's config entry to the device device_registry.async_update_device( device.id, add_config_entry_id=other_entry.entry_id ) # Remove the original Shelly config entry device_registry.async_update_device( device.id, remove_config_entry_id=entry.entry_id ) with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_GET_KVS_VALUE, {ATTR_DEVICE_ID: device.id, ATTR_KEY: "test_key"}, blocking=True, return_response=True, ) assert exc_info.value.translation_domain == DOMAIN assert exc_info.value.translation_key == "config_entry_not_found" assert exc_info.value.translation_placeholders == {"device_id": device.id}
{ "repo_id": "home-assistant/core", "file_path": "tests/components/shelly/test_services.py", "license": "Apache License 2.0", "lines": 229, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/siren/test_trigger.py
"""Test siren triggers.""" from typing import Any import pytest from homeassistant.components.siren import DOMAIN from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant, ServiceCall from tests.components import ( TriggerStateDescription, arm_trigger, parametrize_target_entities, parametrize_trigger_states, set_or_remove_state, target_entities, ) @pytest.fixture async def target_sirens(hass: HomeAssistant) -> list[str]: """Create multiple siren entities associated with different targets.""" return (await target_entities(hass, DOMAIN))["included"] @pytest.mark.parametrize( "trigger_key", [ "siren.turned_off", "siren.turned_on", ], ) async def test_siren_triggers_gated_by_labs_flag( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str ) -> None: """Test the siren triggers are gated by the labs flag.""" await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"}) assert ( "Unnamed automation failed to setup triggers and has been disabled: Trigger " f"'{trigger_key}' requires the experimental 'New triggers and conditions' " "feature to be enabled in Home Assistant Labs settings (feature flag: " "'new_triggers_conditions')" ) in caplog.text @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="siren.turned_off", target_states=[STATE_OFF], other_states=[STATE_ON], ), *parametrize_trigger_states( trigger="siren.turned_on", target_states=[STATE_ON], other_states=[STATE_OFF], ), ], ) async def test_siren_state_trigger_behavior_any( hass: HomeAssistant, service_calls: list[ServiceCall], target_sirens: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the siren state trigger fires when any siren state changes to a specific state.""" other_entity_ids = set(target_sirens) - {entity_id} # Set all sirens, including the tested one, to the initial state for eid in target_sirens: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Check if changing other sirens also triggers for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == (entities_in_target - 1) * state["count"] service_calls.clear() @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="siren.turned_off", target_states=[STATE_OFF], other_states=[STATE_ON], ), *parametrize_trigger_states( trigger="siren.turned_on", target_states=[STATE_ON], other_states=[STATE_OFF], ), ], ) async def test_siren_state_trigger_behavior_first( hass: HomeAssistant, service_calls: list[ServiceCall], target_sirens: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the siren state trigger fires when the first siren changes to a specific state.""" other_entity_ids = set(target_sirens) - {entity_id} # Set all sirens, including the tested one, to the initial state for eid in target_sirens: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Triggering other sirens should not cause the trigger to fire again for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="siren.turned_off", target_states=[STATE_OFF], other_states=[STATE_ON], ), *parametrize_trigger_states( trigger="siren.turned_on", target_states=[STATE_ON], other_states=[STATE_OFF], ), ], ) async def test_siren_state_trigger_behavior_last( hass: HomeAssistant, service_calls: list[ServiceCall], target_sirens: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the siren state trigger fires when the last siren changes to a specific state.""" other_entity_ids = set(target_sirens) - {entity_id} # Set all sirens, including the tested one, to the initial state for eid in target_sirens: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config) for state in states[1:]: included_state = state["included"] for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/siren/test_trigger.py", "license": "Apache License 2.0", "lines": 189, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/sunricher_dali/test_scene.py
"""Test the Sunricher DALI scene platform.""" from unittest.mock import MagicMock import pytest from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN, SERVICE_TURN_ON from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er from . import trigger_availability_callback from tests.common import MockConfigEntry, SnapshotAssertion, snapshot_platform TEST_SCENE_1_ENTITY_ID = "scene.test_gateway_living_room_evening" TEST_SCENE_2_ENTITY_ID = "scene.test_gateway_kitchen_bright" TEST_DIMMER_ENTITY_ID = "light.dimmer_0000_02" TEST_CCT_ENTITY_ID = "light.cct_0000_03" @pytest.fixture def platforms() -> list[Platform]: """Fixture to specify which platforms to test.""" return [Platform.SCENE] @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, mock_scenes: list[MagicMock], ) -> None: """Test the scene entities and their attributes.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) device_entry = device_registry.async_get_device( identifiers={("sunricher_dali", "6A242121110E")} ) 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 state = hass.states.get(TEST_SCENE_1_ENTITY_ID) assert state is not None async def test_activate_scenes( hass: HomeAssistant, init_integration: MockConfigEntry, mock_scenes: list[MagicMock], ) -> None: """Test activating single and multiple scenes.""" await hass.services.async_call( SCENE_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: TEST_SCENE_1_ENTITY_ID}, blocking=True, ) mock_scenes[0].activate.assert_called_once() await hass.services.async_call( SCENE_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: [TEST_SCENE_1_ENTITY_ID, TEST_SCENE_2_ENTITY_ID]}, blocking=True, ) assert mock_scenes[0].activate.call_count == 2 mock_scenes[1].activate.assert_called_once() async def test_scene_availability( hass: HomeAssistant, init_integration: MockConfigEntry, mock_scenes: list[MagicMock], ) -> None: """Test scene availability changes when gateway goes offline.""" state = hass.states.get(TEST_SCENE_1_ENTITY_ID) assert state is not None assert state.state != "unavailable" # Simulate gateway going offline trigger_availability_callback(mock_scenes[0], False) await hass.async_block_till_done() state = hass.states.get(TEST_SCENE_1_ENTITY_ID) assert state.state == "unavailable" # Simulate gateway coming back online trigger_availability_callback(mock_scenes[0], True) await hass.async_block_till_done() state = hass.states.get(TEST_SCENE_1_ENTITY_ID) assert state.state != "unavailable"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/sunricher_dali/test_scene.py", "license": "Apache License 2.0", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/switch/test_trigger.py
"""Test switch triggers.""" from typing import Any import pytest from homeassistant.components.switch import DOMAIN from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant, ServiceCall from tests.components import ( TriggerStateDescription, arm_trigger, parametrize_target_entities, parametrize_trigger_states, set_or_remove_state, target_entities, ) @pytest.fixture async def target_switches(hass: HomeAssistant) -> list[str]: """Create multiple switch entities associated with different targets.""" return (await target_entities(hass, DOMAIN))["included"] @pytest.mark.parametrize( "trigger_key", [ "switch.turned_off", "switch.turned_on", ], ) async def test_switch_triggers_gated_by_labs_flag( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str ) -> None: """Test the switch triggers are gated by the labs flag.""" await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"}) assert ( "Unnamed automation failed to setup triggers and has been disabled: Trigger " f"'{trigger_key}' requires the experimental 'New triggers and conditions' " "feature to be enabled in Home Assistant Labs settings (feature flag: " "'new_triggers_conditions')" ) in caplog.text @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="switch.turned_off", target_states=[STATE_OFF], other_states=[STATE_ON], ), *parametrize_trigger_states( trigger="switch.turned_on", target_states=[STATE_ON], other_states=[STATE_OFF], ), ], ) async def test_switch_state_trigger_behavior_any( hass: HomeAssistant, service_calls: list[ServiceCall], target_switches: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the switch state trigger fires when any switch state changes to a specific state.""" other_entity_ids = set(target_switches) - {entity_id} # Set all switches, including the tested one, to the initial state for eid in target_switches: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Check if changing other switches also triggers for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == (entities_in_target - 1) * state["count"] service_calls.clear() @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="switch.turned_off", target_states=[STATE_OFF], other_states=[STATE_ON], ), *parametrize_trigger_states( trigger="switch.turned_on", target_states=[STATE_ON], other_states=[STATE_OFF], ), ], ) async def test_switch_state_trigger_behavior_first( hass: HomeAssistant, service_calls: list[ServiceCall], target_switches: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the switch state trigger fires when the first switch changes to a specific state.""" other_entity_ids = set(target_switches) - {entity_id} # Set all switches, including the tested one, to the initial state for eid in target_switches: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Triggering other switches should not cause the trigger to fire again for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="switch.turned_off", target_states=[STATE_OFF], other_states=[STATE_ON], ), *parametrize_trigger_states( trigger="switch.turned_on", target_states=[STATE_ON], other_states=[STATE_OFF], ), ], ) async def test_switch_state_trigger_behavior_last( hass: HomeAssistant, service_calls: list[ServiceCall], target_switches: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the switch state trigger fires when the last switch changes to a specific state.""" other_entity_ids = set(target_switches) - {entity_id} # Set all switches, including the tested one, to the initial state for eid in target_switches: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config) for state in states[1:]: included_state = state["included"] for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/switch/test_trigger.py", "license": "Apache License 2.0", "lines": 189, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/switchbot/test_button.py
"""Tests for the switchbot button platform.""" from collections.abc import Callable from datetime import UTC, datetime, timedelta, timezone from unittest.mock import AsyncMock, patch import pytest from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from . import ART_FRAME_INFO, DOMAIN, WOMETERTHPC_SERVICE_INFO from tests.common import MockConfigEntry from tests.components.bluetooth import inject_bluetooth_service_info @pytest.mark.parametrize( ("service", "mock_method", "entity_id"), [ (SERVICE_PRESS, "next_image", "button.test_name_next_image"), (SERVICE_PRESS, "prev_image", "button.test_name_previous_image"), ], ) async def test_art_frame_button_press( hass: HomeAssistant, mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], service: str, mock_method: str, entity_id: str, ) -> None: """Test pressing the button on the art frame device.""" inject_bluetooth_service_info(hass, ART_FRAME_INFO) entry = mock_entry_encrypted_factory("art_frame") entry.add_to_hass(hass) mock_basic_info = AsyncMock( return_value=b"\x016\x07\x01\x00\x00\x04\x00\xde\x18\xa5\x00\x00\x00\x00\x00\x00" ) mocked_instance = AsyncMock(return_value=True) with patch.multiple( "homeassistant.components.switchbot.button.switchbot.SwitchbotArtFrame", _get_basic_info=mock_basic_info, **{mock_method: mocked_instance}, ): assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() entity_ids = [ entity.entity_id for entity in hass.states.async_all(BUTTON_DOMAIN) ] assert entity_ids, "No button entities found" await hass.services.async_call( BUTTON_DOMAIN, service, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) mocked_instance.assert_awaited_once() async def test_meter_pro_co2_sync_datetime_button( hass: HomeAssistant, mock_entry_factory: Callable[[str], MockConfigEntry], ) -> None: """Test pressing the sync datetime button on Meter Pro CO2.""" 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_set_datetime = AsyncMock(return_value=True) # Use a fixed datetime for testing fixed_time = datetime(2025, 1, 9, 12, 30, 45, tzinfo=UTC) with ( patch( "switchbot.SwitchbotMeterProCO2.set_datetime", mock_set_datetime, ), patch( "homeassistant.components.switchbot.button.dt_util.now", return_value=fixed_time, ), ): assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() entity_ids = [ entity.entity_id for entity in hass.states.async_all(BUTTON_DOMAIN) ] assert "button.test_name_sync_date_and_time" in entity_ids await hass.services.async_call( BUTTON_DOMAIN, SERVICE_PRESS, {ATTR_ENTITY_ID: "button.test_name_sync_date_and_time"}, blocking=True, ) mock_set_datetime.assert_awaited_once_with( timestamp=int(fixed_time.timestamp()), utc_offset_hours=0, utc_offset_minutes=0, ) @pytest.mark.parametrize( ("tz", "expected_utc_offset_hours", "expected_utc_offset_minutes"), [ (timezone(timedelta(hours=0, minutes=0)), 0, 0), (timezone(timedelta(hours=0, minutes=30)), 0, 30), (timezone(timedelta(hours=8, minutes=0)), 8, 0), (timezone(timedelta(hours=-5, minutes=30)), -5, 30), (timezone(timedelta(hours=5, minutes=30)), 5, 30), (timezone(timedelta(hours=-5, minutes=-30)), -6, 30), # -6h + 30m = -5:30 (timezone(timedelta(hours=-5, minutes=-45)), -6, 15), # -6h + 15m = -5:45 ], ) async def test_meter_pro_co2_sync_datetime_button_with_timezone( hass: HomeAssistant, mock_entry_factory: Callable[[str], MockConfigEntry], tz: timezone, expected_utc_offset_hours: int, expected_utc_offset_minutes: int, ) -> None: """Test sync datetime button with non-UTC timezone.""" 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_set_datetime = AsyncMock(return_value=True) fixed_time = datetime(2025, 1, 9, 18, 0, 45, tzinfo=tz) with ( patch( "switchbot.SwitchbotMeterProCO2.set_datetime", mock_set_datetime, ), patch( "homeassistant.components.switchbot.button.dt_util.now", return_value=fixed_time, ), ): assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( BUTTON_DOMAIN, SERVICE_PRESS, {ATTR_ENTITY_ID: "button.test_name_sync_date_and_time"}, blocking=True, ) mock_set_datetime.assert_awaited_once_with( timestamp=int(fixed_time.timestamp()), utc_offset_hours=expected_utc_offset_hours, utc_offset_minutes=expected_utc_offset_minutes, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/switchbot/test_button.py", "license": "Apache License 2.0", "lines": 140, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/template/test_validators.py
"""Test template validators.""" from typing import Any import pytest from homeassistant.components.template import validators as cv from homeassistant.components.template.template_entity import TemplateEntity from homeassistant.core import HomeAssistant from homeassistant.helpers.template import Template from .conftest import Brewery def expect_boolean_on(true_value: Any = True) -> list[tuple[Any, Any]]: """Tuple of commonn boolean on value expected pairs.""" return [ ("on", true_value), ("On", true_value), ("oN", true_value), ("true", true_value), ("yes", true_value), ("enable", true_value), ("1", true_value), (True, true_value), (1, true_value), (8.23432, true_value), (0.23432, true_value), ] def expect_boolean_off(false_value: Any = False) -> list[tuple[Any, Any]]: """Tuple of commonn boolean off value expected pairs.""" return [ ("off", false_value), ("false", false_value), ("no", false_value), ("disable", false_value), ("0", false_value), (False, false_value), (0, false_value), ] def expect_none(*args: Any) -> list[tuple[Any, None]]: """Tuple of results that should return None.""" return [(v, None) for v in args] def check_for_error(value: Any, expected: Any, caplog_text: str, error: str) -> None: """Test the validator error.""" if expected is None and value is not None: assert error in caplog_text else: assert error not in caplog_text def create_test_entity(hass: HomeAssistant, config: dict) -> TemplateEntity: """Create a template result handler.""" class Test(TemplateEntity): _entity_id_format = "test.{}" config = { "name": Template("Test", hass), **config, } return Test(hass, config, "something_unique") @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected one of mmmm, beer, is, good", ), ( {}, "Received invalid state: {} for entity Test, expected one of mmmm, beer, is, good", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("mmmm", Brewery.MMMM), ("MmMM", Brewery.MMMM), ("mmMM", Brewery.MMMM), ("beer", Brewery.BEER), ("is", Brewery.IS), ("good", Brewery.GOOD), *expect_none( None, "mm", "beeal;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "7", "-1", True, False, 1, 1.0, {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_enum( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test enum validator.""" entity = create_test_entity(hass, config) assert cv.strenum(entity, "state", Brewery)(value) == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( "value", [ "unknown", "unavailable", "UknoWn", # codespell:ignore "UnavailablE", # codespell:ignore UnavailablE ], ) async def test_none_on_unknown_and_unavailable( hass: HomeAssistant, value: Any, ) -> None: """Test enum validator.""" entity = create_test_entity(hass, {}) assert ( cv.strenum(entity, "state", Brewery, none_on_unknown_unavailable=True)(value) is None ) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected one of mmmm, beer, is, good, 1, true, yes, on, enable, 0, false, no, off, disable", ), ( {}, "Received invalid state: {} for entity Test, expected one of mmmm, beer, is, good, 1, true, yes, on, enable, 0, false, no, off, disable", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("mmmm", Brewery.MMMM), ("MmMM", Brewery.MMMM), ("mmMM", Brewery.MMMM), ("beer", Brewery.BEER), ("is", Brewery.IS), ("good", Brewery.GOOD), *expect_boolean_on(Brewery.MMMM), *expect_boolean_off(Brewery.BEER), *expect_none( None, "mm", "beeal;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "7", "-1", {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_enum_with_on_off( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test enum validator.""" entity = create_test_entity(hass, config) assert ( cv.strenum(entity, "state", Brewery, Brewery.MMMM, Brewery.BEER)(value) == expected ) check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected one of mmmm, beer, is, good, 1, true, yes, on, enable", ), ( {}, "Received invalid state: {} for entity Test, expected one of mmmm, beer, is, good, 1, true, yes, on, enable", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("mmmm", Brewery.MMMM), ("MmMM", Brewery.MMMM), ("mmMM", Brewery.MMMM), ("beer", Brewery.BEER), ("is", Brewery.IS), ("good", Brewery.GOOD), *expect_boolean_on(Brewery.MMMM), *expect_boolean_off(None), *expect_none( None, "mm", "beeal;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "7", "-1", {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_enum_with_on( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test enum with state_on validator.""" entity = create_test_entity(hass, config) assert ( cv.strenum(entity, "state", Brewery, state_on=Brewery.MMMM)(value) == expected ) check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected one of mmmm, beer, is, good, 0, false, no, off, disable", ), ( {}, "Received invalid state: {} for entity Test, expected one of mmmm, beer, is, good, 0, false, no, off, disable", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("mmmm", Brewery.MMMM), ("MmMM", Brewery.MMMM), ("mmMM", Brewery.MMMM), ("beer", Brewery.BEER), ("is", Brewery.IS), ("good", Brewery.GOOD), *expect_boolean_on(None), *expect_boolean_off(Brewery.BEER), *expect_none( None, "mm", "beeal;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "7", "-1", {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_enum_with_off( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test enum with state_off validator.""" entity = create_test_entity(hass, config) assert ( cv.strenum(entity, "state", Brewery, state_off=Brewery.BEER)(value) == expected ) check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected one of 1, true, yes, on, enable, 0, false, no, off, disable", ), ( {}, "Received invalid state: {} for entity Test, expected one of 1, true, yes, on, enable, 0, false, no, off, disable", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ *expect_boolean_on(), *expect_boolean_off(), *expect_none( None, "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "7", "-1", {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_boolean( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test boolean validator.""" entity = create_test_entity(hass, config) assert cv.boolean(entity, "state")(value) == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected one of 1, true, yes, on, enable, 0, false, no, off, disable", ), ( {}, "Received invalid state: {} for entity Test, expected one of 1, true, yes, on, enable, 0, false, no, off, disable", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("something_unique", True), *expect_boolean_on(), *expect_boolean_off(), *expect_none( None, "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "7", "-1", {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_boolean_as_true( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test boolean validator.""" entity = create_test_entity(hass, config) assert cv.boolean(entity, "state", as_true=("something_unique",))(value) == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected one of 1, true, yes, on, enable, 0, false, no, off, disable, something_unique", ), ( {}, "Received invalid state: {} for entity Test, expected one of 1, true, yes, on, enable, 0, false, no, off, disable, something_unique", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("something_unique", False), *expect_boolean_on(), *expect_boolean_off(), *expect_none( None, "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "7", "-1", {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_boolean_as_false( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test boolean validator.""" entity = create_test_entity(hass, config) assert ( cv.boolean(entity, "state", as_false=("something_unique",))(value) == expected ) check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected a number", ), ( {}, "Received invalid state: {} for entity Test, expected a number", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("7.5", 7.5), ("0.0", 0.0), ("-324.4564", -324.4564), ("5e-4", 0.0005), ("5e4", 50000.0), (7.5, 7.5), (0.0, 0.0), (-324.4564, -324.4564), (1, 1.0), *expect_none( None, "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru True, False, {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_number_as_float( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test number validator.""" entity = create_test_entity(hass, config) value = cv.number(entity, "state")(value) assert value == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected a number", ), ( {}, "Received invalid state: {} for entity Test, expected a number", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("7.5", 7), ("0.0", 0), ("-324.4564", -324), ("5e-4", 0), ("5e4", 50000), (7.5, 7), (0.0, 0), (-324.4564, -324), (1, 1), *expect_none( None, "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru True, False, {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_number_as_int( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test number with return_type int validator.""" entity = create_test_entity(hass, config) value = cv.number(entity, "state", return_type=int)(value) assert value == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected a number greater than or equal to 0.0", ), ( {}, "Received invalid state: {} for entity Test, expected a number greater than or equal to 0.0", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("7.5", 7.5), ("0.0", 0), ("5e-4", 0.0005), ("5e4", 50000.0), (7.5, 7.5), (0.0, 0), (1, 1.0), *expect_none( None, "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "-324.4564", -324.4564, "-0.00001", -0.00001, True, False, {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_number_with_minimum( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test number with minimum validator.""" entity = create_test_entity(hass, config) value = cv.number(entity, "state", minimum=0.0)(value) assert value == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected a number less than or equal to 0.0", ), ( {}, "Received invalid state: {} for entity Test, expected a number less than or equal to 0.0", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("-7.5", -7.5), ("0.0", 0), ("-5e-4", -0.0005), ("-5e4", -50000), (-7.5, -7.5), (0.0, 0.0), (-1, -1.0), *expect_none( None, "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "324.4564", "0.00001", True, False, {}, {"junk": "stuff"}, {"junk"}, ), ], ) async def test_number_with_maximum( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test number with maximum validator.""" entity = create_test_entity(hass, config) value = cv.number(entity, "state", maximum=0.0)(value) assert value == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected a number between 0.0 and 100.0", ), ( {}, "Received invalid state: {} for entity Test, expected a number between 0.0 and 100.0", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("7.5", 7.5), ("0.0", 0), ("0.0012", 0.0012), ("99.0", 99.0), ("100", 100), *expect_none( None, "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "324.4564", "-5e4101", True, False, {}, {"junk": "stuff"}, {"junk"}, ), ], ) async def test_number_in_range( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test number within a range validator.""" entity = create_test_entity(hass, config) value = cv.number(entity, "state", minimum=0.0, maximum=100.0)(value) assert value == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected a list of strings", ), ( {}, "Received invalid state: {} for entity Test, expected a list of strings", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ (["beer", "is", "good"], ["beer", "is", "good"]), (["beer", None, True], ["beer", "None", "True"]), ([], []), (["99.0", 99.0, 99], ["99.0", "99.0", "99"]), *expect_none( None, "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru 83242.2342, True, False, {}, {"junk": "stuff"}, {"junk"}, ), ], ) async def test_list_of_strings( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test result as a list of strings.""" entity = create_test_entity(hass, config) value = cv.list_of_strings(entity, "state")(value) assert value == expected check_for_error(value, expected, caplog.text, error.format(value)) async def test_list_of_strings_none_on_empty( hass: HomeAssistant, ) -> None: """Test result as a list of strings with an empty list returning None.""" entity = create_test_entity(hass, {"default_entity_id": "test.test"}) value = cv.list_of_strings(entity, "state", none_on_empty=True)([]) assert value is None @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected beer, is, GOOD", ), ( {}, "Received invalid state: {} for entity Test, expected beer, is, GOOD", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("beer", "beer"), ("is", "is"), ("GOOD", "GOOD"), *expect_none( None, "BEER", "IS", "good", "al;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru 83242.2342, True, False, {}, {"junk": "stuff"}, {"junk"}, ), ], ) async def test_item_in_list( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test result is in a list.""" entity = create_test_entity(hass, config) value = cv.item_in_list(entity, "state", ["beer", "is", "GOOD"])(value) assert value == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected one of beer, is, GOOD", ), ( {}, "Received invalid state: {} for entity Test, expected one of beer, is, GOOD", ), ], ) async def test_item_in_list_changes( hass: HomeAssistant, config: dict, error: str, caplog: pytest.LogCaptureFixture, ) -> None: """Test test an item is in a list after the list changes.""" entity = create_test_entity(hass, config) items = ["beer", "is", "GOOD"] value = cv.item_in_list(entity, "state", items)("mmmm") assert value is None assert error.format("mmmm") in caplog.text items.append("mmmm") value = cv.item_in_list(entity, "state", items)("mmmm") assert value == "mmmm" assert error.format(value) + ", mmmm" not in caplog.text @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, bar is empty", ), ( {}, "Received invalid state: {} for entity Test, bar is empty", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [("anything", None)], ) @pytest.mark.parametrize( ("the_list"), [None, []], ) async def test_empty_items_in_list( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, the_list: list | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test result is in a list.""" entity = create_test_entity(hass, config) value = cv.item_in_list(entity, "state", the_list, "bar")(value) assert value == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected a url", ), ( {}, "Received invalid state: {} for entity Test, expected a url", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("http://foo.bar", "http://foo.bar"), ("https://foo.bar", "https://foo.bar"), *expect_none( None, "/local/thing", "beeal;dfj", "unknown", "unavailable", "tru", # codespell:ignore tru "7", "-1", True, False, 1, 1.0, {}, {"junk": "stuff"}, {"junk"}, [], ["stuff"], ), ], ) async def test_url( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test enum validator.""" entity = create_test_entity(hass, config) assert cv.url(entity, "state")(value) == expected check_for_error(value, expected, caplog.text, error.format(value)) @pytest.mark.parametrize( ("config", "error"), [ ( {"default_entity_id": "test.test"}, "Received invalid test state: {} for entity test.test, expected a string", ), ( {}, "Received invalid state: {} for entity Test, expected a string", ), ], ) @pytest.mark.parametrize( ("value", "expected"), [ ("a string", "a string"), (True, "True"), (False, "False"), (1, "1"), (1.0, "1.0"), *expect_none( None, {}, {"junk": "stuff"}, [], ["stuff"], ), ], ) async def test_string( hass: HomeAssistant, config: dict, error: str, value: Any, expected: bool | None, caplog: pytest.LogCaptureFixture, ) -> None: """Test enum validator.""" entity = create_test_entity(hass, config) assert cv.string(entity, "state")(value) == expected check_for_error(value, expected, caplog.text, error.format(value))
{ "repo_id": "home-assistant/core", "file_path": "tests/components/template/test_validators.py", "license": "Apache License 2.0", "lines": 962, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/tibber/test_sensor.py
"""Tests for the Tibber Data API sensors and coordinator.""" from __future__ import annotations from unittest.mock import AsyncMock import pytest from homeassistant.components.recorder import Recorder from homeassistant.components.tibber.const import DOMAIN from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .conftest import create_tibber_device from tests.common import MockConfigEntry async def test_data_api_sensors_are_created( recorder_mock: Recorder, hass: HomeAssistant, config_entry: MockConfigEntry, data_api_client_mock: AsyncMock, setup_credentials: None, entity_registry: er.EntityRegistry, ) -> None: """Ensure Data API sensors are created and expose values from the coordinator.""" data_api_client_mock.get_all_devices = AsyncMock( return_value={"device-id": create_tibber_device(state_of_charge=72.0)} ) data_api_client_mock.update_devices = AsyncMock( return_value={"device-id": create_tibber_device(state_of_charge=83.0)} ) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() data_api_client_mock.get_all_devices.assert_awaited_once() data_api_client_mock.update_devices.assert_awaited_once() unique_id = "external-id_storage.stateOfCharge" 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) == 83.0 @pytest.mark.parametrize( ("sensor_id", "expected_value", "description"), [ ("storage.ratedCapacity", 10000.0, "Storage rated capacity"), ("storage.ratedPower", 5000.0, "Storage rated power"), ("storage.availableEnergy", 7500.0, "Storage available energy"), ("powerFlow.battery.power", 2500.0, "Battery power flow"), ("powerFlow.grid.power", 1500.0, "Grid power flow"), ("powerFlow.load.power", 4000.0, "Load power flow"), ("powerFlow.toGrid", 25.5, "Power flow to grid percentage"), ("powerFlow.toLoad", 60.0, "Power flow to load percentage"), ("powerFlow.fromGrid", 15.0, "Power flow from grid percentage"), ("powerFlow.fromLoad", 10.0, "Power flow from load percentage"), ("energyFlow.hour.battery.charged", 2000.0, "Hourly battery charged"), ("energyFlow.hour.battery.discharged", 1500.0, "Hourly battery discharged"), ("energyFlow.hour.grid.imported", 1000.0, "Hourly grid imported"), ("energyFlow.hour.grid.exported", 800.0, "Hourly grid exported"), ("energyFlow.hour.load.consumed", 3000.0, "Hourly load consumed"), ("energyFlow.hour.load.generated", 200.0, "Hourly load generated"), ("energyFlow.month.battery.charged", 50000.0, "Monthly battery charged"), ("energyFlow.month.battery.discharged", 40000.0, "Monthly battery discharged"), ("energyFlow.month.grid.imported", 25000.0, "Monthly grid imported"), ("energyFlow.month.grid.exported", 20000.0, "Monthly grid exported"), ("energyFlow.month.load.consumed", 60000.0, "Monthly load consumed"), ("energyFlow.month.load.generated", 5000.0, "Monthly load generated"), ("range.remaining", 250.5, "Remaining range"), ("charging.current.max", 32.0, "Max charging current"), ("charging.current.offlineFallback", 16.0, "Offline fallback charging current"), ("temp.setpoint", 22.5, "Temperature setpoint"), ("temp.current", 21.0, "Current temperature"), ("temp.comfort", 20.5, "Comfort temperature"), ("grid.phaseCount", 3.0, "Grid phase count"), ], ) async def test_new_data_api_sensor_values( recorder_mock: Recorder, hass: HomeAssistant, config_entry: MockConfigEntry, data_api_client_mock: AsyncMock, setup_credentials: None, entity_registry: er.EntityRegistry, sensor_id: str, expected_value: float, description: str, ) -> None: """Test individual new Data API sensor values.""" device = create_tibber_device(sensor_values={sensor_id: expected_value}) data_api_client_mock.get_all_devices = AsyncMock(return_value={"device-id": device}) data_api_client_mock.update_devices = AsyncMock(return_value={"device-id": device}) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() unique_id = f"external-id_{sensor_id}" entity_id = entity_registry.async_get_entity_id("sensor", DOMAIN, unique_id) assert entity_id is not None, f"Entity not found for {description}" state = hass.states.get(entity_id) assert state is not None, f"State not found for {description}" assert float(state.state) == expected_value, ( f"Expected {expected_value} for {description}, got {state.state}" ) async def test_new_data_api_sensors_with_disabled_by_default( recorder_mock: Recorder, hass: HomeAssistant, config_entry: MockConfigEntry, data_api_client_mock: AsyncMock, setup_credentials: None, entity_registry: er.EntityRegistry, ) -> None: """Test that sensors with entity_registry_enabled_default=False are disabled by default.""" sensor_values = { "cellular.rssi": -75.0, "energyFlow.hour.battery.source.grid": 500.0, "energyFlow.hour.battery.source.load": 300.0, "energyFlow.hour.load.source.battery": 700.0, "energyFlow.hour.load.source.grid": 500.0, "energyFlow.month.battery.source.grid": 10000.0, "energyFlow.month.battery.source.battery": 5000.0, "energyFlow.month.battery.source.load": 8000.0, "energyFlow.month.grid.source.battery": 3000.0, "energyFlow.month.grid.source.grid": 1000.0, "energyFlow.month.grid.source.load": 2000.0, "energyFlow.month.load.source.battery": 15000.0, "energyFlow.month.load.source.grid": 10000.0, } device = create_tibber_device(sensor_values=sensor_values) data_api_client_mock.get_all_devices = AsyncMock(return_value={"device-id": device}) data_api_client_mock.update_devices = AsyncMock(return_value={"device-id": device}) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() disabled_sensors = [ "cellular.rssi", "energyFlow.hour.battery.source.grid", "energyFlow.hour.battery.source.load", "energyFlow.hour.load.source.battery", "energyFlow.hour.load.source.grid", "energyFlow.month.battery.source.grid", "energyFlow.month.battery.source.battery", "energyFlow.month.battery.source.load", "energyFlow.month.grid.source.battery", "energyFlow.month.grid.source.grid", "energyFlow.month.grid.source.load", "energyFlow.month.load.source.battery", "energyFlow.month.load.source.grid", ] for sensor_id in disabled_sensors: unique_id = f"external-id_{sensor_id}" entity_id = entity_registry.async_get_entity_id("sensor", DOMAIN, unique_id) assert entity_id is not None, f"Entity not found for sensor {sensor_id}" entity_entry = entity_registry.async_get(entity_id) assert entity_entry is not None assert entity_entry.disabled, ( f"Sensor {sensor_id} should be disabled by default" )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/tibber/test_sensor.py", "license": "Apache License 2.0", "lines": 147, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/tplink_omada/test_binary_sensor.py
"""Tests for TP-Link Omada sensor entities.""" from datetime import timedelta from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from tplink_omada_client.definitions import DeviceStatus, DeviceStatusCategory from tplink_omada_client.devices import OmadaListDevice from homeassistant.components.tplink_omada.const import DOMAIN from homeassistant.components.tplink_omada.coordinator import POLL_DEVICES from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import ( Generator, MockConfigEntry, async_fire_time_changed, async_load_json_array_fixture, snapshot_platform, ) POLL_INTERVAL = timedelta(seconds=POLL_DEVICES) @pytest.fixture(autouse=True) def patch_binary_sensor_platforms() -> Generator[None]: """Patch PLATFORMS to only include binary_sensor for tests.""" with patch("homeassistant.components.tplink_omada.PLATFORMS", ["binary_sensor"]): yield async def test_entities( hass: HomeAssistant, entity_registry: er.EntityRegistry, init_integration: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test the creation of the TP-Link Omada binary sensor entities.""" await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id) async def test_no_gateway_creates_no_port_sensors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_omada_client: MagicMock, mock_omada_site_client: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test that if there is no gateway, no gateway port sensors are created.""" await _remove_test_device(hass, mock_omada_site_client, 0) 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() mock_omada_site_client.get_gateway.assert_not_called() async def test_disconnected_device_sensor_not_registered( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_omada_client: MagicMock, mock_omada_site_client: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test that if the gateway is not connected to the controller, gateway entities are not created.""" await _set_test_device_status( hass, mock_omada_site_client, 0, DeviceStatus.DISCONNECTED.value, DeviceStatusCategory.DISCONNECTED.value, ) 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() entity_id = "binary_sensor.test_router_port_1_lan_status" entity = hass.states.get(entity_id) assert entity is None # "Connect" the gateway await _set_test_device_status( hass, mock_omada_site_client, 0, DeviceStatus.CONNECTED.value, DeviceStatusCategory.CONNECTED.value, ) freezer.tick(POLL_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() entity = hass.states.get(entity_id) assert entity is not None assert entity.state == "off" mock_omada_site_client.get_gateway.assert_called_once_with("AA-BB-CC-DD-EE-FF") async def _set_test_device_status( hass: HomeAssistant, mock_omada_site_client: MagicMock, dev_index: int, status: int, status_category: int, ) -> None: devices_data = await async_load_json_array_fixture(hass, "devices.json", DOMAIN) devices_data[dev_index]["status"] = status devices_data[dev_index]["statusCategory"] = status_category devices = [OmadaListDevice(d) for d in devices_data] mock_omada_site_client.get_devices.reset_mock() mock_omada_site_client.get_devices.return_value = devices async def _remove_test_device( hass: HomeAssistant, mock_omada_site_client: MagicMock, dev_index: int, ) -> None: devices_data = await async_load_json_array_fixture(hass, "devices.json", DOMAIN) del devices_data[dev_index] devices = [OmadaListDevice(d) for d in devices_data] mock_omada_site_client.get_devices.reset_mock() mock_omada_site_client.get_devices.return_value = devices
{ "repo_id": "home-assistant/core", "file_path": "tests/components/tplink_omada/test_binary_sensor.py", "license": "Apache License 2.0", "lines": 105, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/tplink_omada/test_services.py
"""Tests for TP-Link Omada integration services.""" from unittest.mock import MagicMock import pytest from tplink_omada_client.exceptions import OmadaClientException from homeassistant.components.tplink_omada.const import DOMAIN from homeassistant.components.tplink_omada.services import async_setup_services from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from tests.common import MockConfigEntry async def test_service_reconnect_no_config_entries( hass: HomeAssistant, ) -> None: """Test reconnect service raises error when no config entries exist.""" # Register services directly without any config entries async_setup_services(hass) mac = "AA:BB:CC:DD:EE:FF" with pytest.raises( ServiceValidationError, match="No active TP-Link Omada controllers found" ): await hass.services.async_call( DOMAIN, "reconnect_client", {"mac": mac}, blocking=True, ) async def test_service_reconnect_client( hass: HomeAssistant, mock_omada_site_client: MagicMock, mock_omada_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reconnect client service.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() mac = "AA:BB:CC:DD:EE:FF" await hass.services.async_call( DOMAIN, "reconnect_client", {"config_entry_id": mock_config_entry.entry_id, "mac": mac}, blocking=True, ) mock_omada_site_client.reconnect_client.assert_awaited_once_with(mac) async def test_service_reconnect_failed_with_invalid_entry( hass: HomeAssistant, mock_omada_site_client: MagicMock, mock_omada_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reconnect with invalid config entry raises ServiceValidationError.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() mac = "AA:BB:CC:DD:EE:FF" with pytest.raises( ServiceValidationError, match="Specified TP-Link Omada controller not found" ): await hass.services.async_call( DOMAIN, "reconnect_client", {"config_entry_id": "invalid_entry_id", "mac": mac}, blocking=True, ) async def test_service_reconnect_without_config_entry_id( hass: HomeAssistant, mock_omada_site_client: MagicMock, mock_omada_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reconnect client service without config_entry_id uses first loaded entry.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() mac = "AA:BB:CC:DD:EE:FF" await hass.services.async_call( DOMAIN, "reconnect_client", {"mac": mac}, blocking=True, ) mock_omada_site_client.reconnect_client.assert_awaited_once_with(mac) async def test_service_reconnect_entry_not_loaded( hass: HomeAssistant, mock_omada_site_client: MagicMock, mock_omada_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reconnect service raises error when entry is not loaded.""" # Set up first entry so service is registered mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() unloaded_entry = MockConfigEntry( title="Unloaded Omada Controller", domain=DOMAIN, unique_id="67890", ) unloaded_entry.add_to_hass(hass) mac = "AA:BB:CC:DD:EE:FF" with pytest.raises( ServiceValidationError, match="The TP-Link Omada integration is not currently available", ): await hass.services.async_call( DOMAIN, "reconnect_client", {"config_entry_id": unloaded_entry.entry_id, "mac": mac}, blocking=True, ) async def test_service_reconnect_failed_raises_homeassistanterror( hass: HomeAssistant, mock_omada_site_client: MagicMock, mock_omada_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reconnect client service raises the right kind of exception on service failure.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() mac = "AA:BB:CC:DD:EE:FF" mock_omada_site_client.reconnect_client.side_effect = OmadaClientException with pytest.raises(HomeAssistantError): await hass.services.async_call( DOMAIN, "reconnect_client", {"config_entry_id": mock_config_entry.entry_id, "mac": mac}, blocking=True, ) mock_omada_site_client.reconnect_client.assert_awaited_once_with(mac)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/tplink_omada/test_services.py", "license": "Apache License 2.0", "lines": 129, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/transmission/test_sensor.py
"""Tests for the Transmission sensor platform.""" 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, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test the sensor entities.""" with patch("homeassistant.components.transmission.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/transmission/test_sensor.py", "license": "Apache License 2.0", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test