sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
home-assistant/core:homeassistant/components/smarla/const.py | """Constants for the Swing2Sleep Smarla integration."""
from homeassistant.const import Platform
DOMAIN = "smarla"
HOST = "https://devices.swing2sleep.de"
PLATFORMS = [Platform.NUMBER, Platform.SENSOR, Platform.SWITCH, Platform.UPDATE]
DEVICE_MODEL_NAME = "Smarla"
MANUFACTURER_NAME = "Swing2Sleep"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/smarla/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/smarla/entity.py | """Common base for entities."""
from dataclasses import dataclass
import logging
from typing import Any
from pysmarlaapi import Federwiege
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import Entity, EntityDescription
from .const import DEVICE_MODEL_NAME, DOMAIN, MANUFACTURER_NAME
_LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True, kw_only=True)
class SmarlaEntityDescription(EntityDescription):
"""Class describing Swing2Sleep Smarla entities."""
service: str
property: str
class SmarlaBaseEntity(Entity):
"""Common Base Entity class for defining Smarla device."""
entity_description: SmarlaEntityDescription
_attr_should_poll = False
_attr_has_entity_name = True
def __init__(self, federwiege: Federwiege, desc: SmarlaEntityDescription) -> None:
"""Initialize the entity."""
self.entity_description = desc
self._federwiege = federwiege
self._property = federwiege.get_property(desc.service, desc.property)
self._attr_unique_id = f"{federwiege.serial_number}-{desc.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, federwiege.serial_number)},
name=DEVICE_MODEL_NAME,
model=DEVICE_MODEL_NAME,
manufacturer=MANUFACTURER_NAME,
serial_number=federwiege.serial_number,
)
self._unavailable_logged = False
@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._federwiege.available
async def on_availability_change(self, available: bool) -> None:
"""Handle availability changes."""
if not self.available and not self._unavailable_logged:
_LOGGER.info("Entity %s is unavailable", self.entity_id)
self._unavailable_logged = True
elif self.available and self._unavailable_logged:
_LOGGER.info("Entity %s is back online", self.entity_id)
self._unavailable_logged = False
# Notify ha that state changed
self.async_write_ha_state()
async def on_change(self, value: Any) -> None:
"""Notify ha when state changes."""
self.async_write_ha_state()
async def async_added_to_hass(self) -> None:
"""Run when this Entity has been added to HA."""
await self._federwiege.add_listener(self.on_availability_change)
await self._property.add_listener(self.on_change)
async def async_will_remove_from_hass(self) -> None:
"""Entity being removed from hass."""
await self._property.remove_listener(self.on_change)
await self._federwiege.remove_listener(self.on_availability_change)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/smarla/entity.py",
"license": "Apache License 2.0",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/smarla/switch.py | """Support for the Swing2Sleep Smarla switch entities."""
from dataclasses import dataclass
from typing import Any
from pysmarlaapi.federwiege.services.classes import Property
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import FederwiegeConfigEntry
from .entity import SmarlaBaseEntity, SmarlaEntityDescription
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class SmarlaSwitchEntityDescription(SmarlaEntityDescription, SwitchEntityDescription):
"""Class describing Swing2Sleep Smarla switch entity."""
SWITCHES: list[SmarlaSwitchEntityDescription] = [
SmarlaSwitchEntityDescription(
key="swing_active",
name=None,
service="babywiege",
property="swing_active",
),
SmarlaSwitchEntityDescription(
key="smart_mode",
translation_key="smart_mode",
service="babywiege",
property="smart_mode",
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: FederwiegeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Smarla switches from config entry."""
federwiege = config_entry.runtime_data
async_add_entities(SmarlaSwitch(federwiege, desc) for desc in SWITCHES)
class SmarlaSwitch(SmarlaBaseEntity, SwitchEntity):
"""Representation of Smarla switch."""
entity_description: SmarlaSwitchEntityDescription
_property: Property[bool]
@property
def is_on(self) -> bool | None:
"""Return the entity value to represent the entity state."""
return self._property.get()
def turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
self._property.set(True)
def turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
self._property.set(False)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/smarla/switch.py",
"license": "Apache License 2.0",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/smartthings/water_heater.py | """Support for water heaters through the SmartThings cloud API."""
from __future__ import annotations
from typing import Any
from pysmartthings import Attribute, Capability, Command, SmartThings
from homeassistant.components.water_heater import (
DEFAULT_MAX_TEMP,
DEFAULT_MIN_TEMP,
STATE_ECO,
STATE_HEAT_PUMP,
STATE_HIGH_DEMAND,
STATE_PERFORMANCE,
WaterHeaterEntity,
WaterHeaterEntityFeature,
)
from homeassistant.const import ATTR_TEMPERATURE, STATE_OFF, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.unit_conversion import TemperatureConverter
from . import FullDevice, SmartThingsConfigEntry
from .const import MAIN, UNIT_MAP
from .entity import SmartThingsEntity
OPERATION_MAP_TO_HA: dict[str, str] = {
"eco": STATE_ECO,
"std": STATE_HEAT_PUMP,
"force": STATE_HIGH_DEMAND,
"power": STATE_PERFORMANCE,
}
HA_TO_OPERATION_MAP = {v: k for k, v in OPERATION_MAP_TO_HA.items()}
async def async_setup_entry(
hass: HomeAssistant,
entry: SmartThingsConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add water heaters for a config entry."""
entry_data = entry.runtime_data
async_add_entities(
SmartThingsWaterHeater(entry_data.client, device)
for device in entry_data.devices.values()
if all(
capability in device.status[MAIN]
for capability in (
Capability.SWITCH,
Capability.AIR_CONDITIONER_MODE,
Capability.TEMPERATURE_MEASUREMENT,
Capability.CUSTOM_THERMOSTAT_SETPOINT_CONTROL,
Capability.THERMOSTAT_COOLING_SETPOINT,
Capability.SAMSUNG_CE_EHS_THERMOSTAT,
Capability.CUSTOM_OUTING_MODE,
)
)
and device.status[MAIN][Capability.TEMPERATURE_MEASUREMENT][
Attribute.TEMPERATURE
].value
is not None
)
class SmartThingsWaterHeater(SmartThingsEntity, WaterHeaterEntity):
"""Define a SmartThings Water Heater."""
_attr_name = None
_attr_translation_key = "water_heater"
def __init__(self, client: SmartThings, device: FullDevice) -> None:
"""Init the class."""
super().__init__(
client,
device,
{
Capability.SWITCH,
Capability.AIR_CONDITIONER_MODE,
Capability.TEMPERATURE_MEASUREMENT,
Capability.CUSTOM_THERMOSTAT_SETPOINT_CONTROL,
Capability.THERMOSTAT_COOLING_SETPOINT,
Capability.CUSTOM_OUTING_MODE,
},
)
unit = self._internal_state[Capability.TEMPERATURE_MEASUREMENT][
Attribute.TEMPERATURE
].unit
assert unit is not None
self._attr_temperature_unit = UNIT_MAP[unit]
@property
def supported_features(self) -> WaterHeaterEntityFeature:
"""Return the supported features."""
features = (
WaterHeaterEntityFeature.OPERATION_MODE
| WaterHeaterEntityFeature.AWAY_MODE
| WaterHeaterEntityFeature.ON_OFF
)
if self.get_attribute_value(Capability.SWITCH, Attribute.SWITCH) == "on":
features |= WaterHeaterEntityFeature.TARGET_TEMPERATURE
return features
@property
def min_temp(self) -> float:
"""Return the minimum temperature."""
min_temperature = TemperatureConverter.convert(
DEFAULT_MIN_TEMP, UnitOfTemperature.FAHRENHEIT, self._attr_temperature_unit
)
return min(min_temperature, self.target_temperature_low)
@property
def max_temp(self) -> float:
"""Return the maximum temperature."""
max_temperature = TemperatureConverter.convert(
DEFAULT_MAX_TEMP, UnitOfTemperature.FAHRENHEIT, self._attr_temperature_unit
)
return max(max_temperature, self.target_temperature_high)
@property
def operation_list(self) -> list[str]:
"""Return the list of available operation modes."""
return [
STATE_OFF,
*(
OPERATION_MAP_TO_HA[mode]
for mode in self.get_attribute_value(
Capability.AIR_CONDITIONER_MODE, Attribute.SUPPORTED_AC_MODES
)
if mode in OPERATION_MAP_TO_HA
),
]
@property
def current_operation(self) -> str | None:
"""Return the current operation mode."""
if self.get_attribute_value(Capability.SWITCH, Attribute.SWITCH) == "off":
return STATE_OFF
return OPERATION_MAP_TO_HA.get(
self.get_attribute_value(
Capability.AIR_CONDITIONER_MODE, Attribute.AIR_CONDITIONER_MODE
)
)
@property
def current_temperature(self) -> float | None:
"""Return the current temperature."""
return self.get_attribute_value(
Capability.TEMPERATURE_MEASUREMENT, Attribute.TEMPERATURE
)
@property
def target_temperature(self) -> float | None:
"""Return the target temperature."""
return self.get_attribute_value(
Capability.THERMOSTAT_COOLING_SETPOINT, Attribute.COOLING_SETPOINT
)
@property
def target_temperature_low(self) -> float:
"""Return the minimum temperature."""
return self.get_attribute_value(
Capability.CUSTOM_THERMOSTAT_SETPOINT_CONTROL, Attribute.MINIMUM_SETPOINT
)
@property
def target_temperature_high(self) -> float:
"""Return the maximum temperature."""
return self.get_attribute_value(
Capability.CUSTOM_THERMOSTAT_SETPOINT_CONTROL, Attribute.MAXIMUM_SETPOINT
)
@property
def is_away_mode_on(self) -> bool:
"""Return if away mode is on."""
return (
self.get_attribute_value(
Capability.CUSTOM_OUTING_MODE, Attribute.OUTING_MODE
)
== "on"
)
async def async_set_operation_mode(self, operation_mode: str) -> None:
"""Set new target operation mode."""
if operation_mode == STATE_OFF:
await self.async_turn_off()
return
if self.current_operation == STATE_OFF:
await self.async_turn_on()
await self.execute_device_command(
Capability.AIR_CONDITIONER_MODE,
Command.SET_AIR_CONDITIONER_MODE,
argument=HA_TO_OPERATION_MAP[operation_mode],
)
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
await self.execute_device_command(
Capability.THERMOSTAT_COOLING_SETPOINT,
Command.SET_COOLING_SETPOINT,
argument=kwargs[ATTR_TEMPERATURE],
)
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the water heater on."""
await self.execute_device_command(
Capability.SWITCH,
Command.ON,
)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the water heater off."""
await self.execute_device_command(
Capability.SWITCH,
Command.OFF,
)
async def async_turn_away_mode_on(self) -> None:
"""Turn away mode on."""
await self.execute_device_command(
Capability.CUSTOM_OUTING_MODE,
Command.SET_OUTING_MODE,
argument="on",
)
async def async_turn_away_mode_off(self) -> None:
"""Turn away mode off."""
await self.execute_device_command(
Capability.CUSTOM_OUTING_MODE,
Command.SET_OUTING_MODE,
argument="off",
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/smartthings/water_heater.py",
"license": "Apache License 2.0",
"lines": 204,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/squeezebox/switch.py | """Switch entity representing a Squeezebox alarm."""
import datetime
import logging
from typing import Any, cast
from pysqueezebox.player import Alarm
from homeassistant.components.switch import SwitchEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.device_registry import format_mac
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.event import async_track_time_change
from .const import ATTR_ALARM_ID, DOMAIN, SIGNAL_PLAYER_DISCOVERED
from .coordinator import SqueezeBoxPlayerUpdateCoordinator
from .entity import SqueezeboxEntity
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 1
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Squeezebox alarm switch."""
async def _player_discovered(
coordinator: SqueezeBoxPlayerUpdateCoordinator,
) -> None:
def _async_listener() -> None:
"""Handle alarm creation and deletion after coordinator data update."""
new_alarms: set[str] = set()
received_alarms: set[str] = set()
if coordinator.data["alarms"] and coordinator.available:
received_alarms = set(coordinator.data["alarms"])
new_alarms = received_alarms - coordinator.known_alarms
removed_alarms = coordinator.known_alarms - received_alarms
if new_alarms:
for new_alarm in new_alarms:
coordinator.known_alarms.add(new_alarm)
_LOGGER.debug(
"Setting up alarm entity for alarm %s on player %s",
new_alarm,
coordinator.player,
)
async_add_entities([SqueezeBoxAlarmEntity(coordinator, new_alarm)])
if removed_alarms and coordinator.available:
for removed_alarm in removed_alarms:
_uid = f"{coordinator.player_uuid}_alarm_{removed_alarm}"
_LOGGER.debug(
"Alarm %s with unique_id %s needs to be deleted",
removed_alarm,
_uid,
)
entity_registry = er.async_get(hass)
_entity_id = entity_registry.async_get_entity_id(
Platform.SWITCH,
DOMAIN,
_uid,
)
if _entity_id:
entity_registry.async_remove(_entity_id)
coordinator.known_alarms.remove(removed_alarm)
_LOGGER.debug(
"Setting up alarm enabled entity for player %s", coordinator.player
)
# Add listener first for future coordinator refresh
coordinator.async_add_listener(_async_listener)
# If coordinator already has alarm data from the initial refresh,
# call the listener immediately to process existing alarms and create alarm entities.
if coordinator.data["alarms"]:
_LOGGER.debug(
"Coordinator has alarm data, calling _async_listener immediately for player %s",
coordinator.player,
)
_async_listener()
async_add_entities([SqueezeBoxAlarmsEnabledEntity(coordinator)])
entry.async_on_unload(
async_dispatcher_connect(
hass, SIGNAL_PLAYER_DISCOVERED + entry.entry_id, _player_discovered
)
)
class SqueezeBoxAlarmEntity(SqueezeboxEntity, SwitchEntity):
"""Representation of a Squeezebox alarm switch."""
_attr_translation_key = "alarm"
_attr_entity_category = EntityCategory.CONFIG
def __init__(
self, coordinator: SqueezeBoxPlayerUpdateCoordinator, alarm_id: str
) -> None:
"""Initialize the Squeezebox alarm switch."""
super().__init__(coordinator)
self._alarm_id = alarm_id
self._attr_translation_placeholders = {"alarm_id": self._alarm_id}
self._attr_unique_id: str = (
f"{format_mac(self._player.player_id)}_alarm_{self._alarm_id}"
)
async def async_added_to_hass(self) -> None:
"""Set up alarm switch when added to hass."""
await super().async_added_to_hass()
async def async_write_state_daily(now: datetime.datetime) -> None:
"""Update alarm state attributes each calendar day."""
_LOGGER.debug("Updating state attributes for %s", self.name)
self.async_write_ha_state()
self.async_on_remove(
async_track_time_change(
self.hass, async_write_state_daily, hour=0, minute=0, second=0
)
)
@property
def alarm(self) -> Alarm:
"""Return the alarm object."""
return self.coordinator.data["alarms"][self._alarm_id]
@property
def available(self) -> bool:
"""Return whether the alarm is available."""
return super().available and self._alarm_id in self.coordinator.data["alarms"]
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return attributes of Squeezebox alarm switch."""
return {ATTR_ALARM_ID: str(self._alarm_id)}
@property
def is_on(self) -> bool:
"""Return the state of the switch."""
return cast(bool, self.alarm["enabled"])
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the switch."""
await self.coordinator.player.async_update_alarm(self._alarm_id, enabled=False)
await self.coordinator.async_request_refresh()
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the switch."""
await self.coordinator.player.async_update_alarm(self._alarm_id, enabled=True)
await self.coordinator.async_request_refresh()
class SqueezeBoxAlarmsEnabledEntity(SqueezeboxEntity, SwitchEntity):
"""Representation of a Squeezebox players alarms enabled master switch."""
_attr_translation_key = "alarms_enabled"
_attr_entity_category = EntityCategory.CONFIG
def __init__(self, coordinator: SqueezeBoxPlayerUpdateCoordinator) -> None:
"""Initialize the Squeezebox alarm switch."""
super().__init__(coordinator)
self._attr_unique_id: str = (
f"{format_mac(self._player.player_id)}_alarms_enabled"
)
@property
def is_on(self) -> bool:
"""Return the state of the switch."""
return cast(bool, self.coordinator.player.alarms_enabled)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the switch."""
await self.coordinator.player.async_set_alarms_enabled(False)
await self.coordinator.async_request_refresh()
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the switch."""
await self.coordinator.player.async_set_alarms_enabled(True)
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/squeezebox/switch.py",
"license": "Apache License 2.0",
"lines": 153,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/squeezebox/update.py | """Platform for update integration for squeezebox."""
from __future__ import annotations
from collections.abc import Callable
from datetime import datetime
import logging
from typing import Any
from homeassistant.components.update import (
UpdateEntity,
UpdateEntityDescription,
UpdateEntityFeature,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.event import async_call_later
from . import SqueezeboxConfigEntry
from .const import (
DOMAIN,
SERVER_MODEL,
STATUS_QUERY_VERSION,
STATUS_UPDATE_NEWPLUGINS,
STATUS_UPDATE_NEWVERSION,
UPDATE_PLUGINS_RELEASE_SUMMARY,
UPDATE_RELEASE_SUMMARY,
)
from .entity import LMSStatusEntity
newserver = UpdateEntityDescription(
key=STATUS_UPDATE_NEWVERSION,
)
newplugins = UpdateEntityDescription(
key=STATUS_UPDATE_NEWPLUGINS,
)
POLL_AFTER_INSTALL = 120
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
entry: SqueezeboxConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Platform setup using common elements."""
async_add_entities(
[
ServerStatusUpdateLMS(entry.runtime_data.coordinator, newserver),
ServerStatusUpdatePlugins(entry.runtime_data.coordinator, newplugins),
]
)
class ServerStatusUpdate(LMSStatusEntity, UpdateEntity):
"""LMS Status update sensors via cooridnatior."""
@property
def latest_version(self) -> str:
"""LMS Status directly from coordinator data."""
return str(self.coordinator.data[self.entity_description.key])
class ServerStatusUpdateLMS(ServerStatusUpdate):
"""LMS Status update sensor from LMS via cooridnatior."""
title: str = SERVER_MODEL
@property
def installed_version(self) -> str:
"""LMS Status directly from coordinator data."""
return str(self.coordinator.data[STATUS_QUERY_VERSION])
@property
def release_url(self) -> str:
"""LMS Update info page."""
return str(self.coordinator.lms.generate_image_url("updateinfo.html"))
@property
def release_summary(self) -> None | str:
"""If install is supported give some info."""
return (
str(self.coordinator.data[UPDATE_RELEASE_SUMMARY])
if self.coordinator.data[UPDATE_RELEASE_SUMMARY]
else None
)
class ServerStatusUpdatePlugins(ServerStatusUpdate):
"""LMS Plugings update sensor from LMS via cooridnatior."""
auto_update = True
title: str = SERVER_MODEL + " Plugins"
installed_version = "Current"
restart_triggered = False
_cancel_update: Callable | None = None
@property
def supported_features(self) -> UpdateEntityFeature:
"""Support install if we can."""
return (
(UpdateEntityFeature.INSTALL | UpdateEntityFeature.PROGRESS)
if self.coordinator.can_server_restart
else UpdateEntityFeature(0)
)
@property
def release_summary(self) -> None | str:
"""If install is supported give some info."""
rs = self.coordinator.data[UPDATE_PLUGINS_RELEASE_SUMMARY]
return (
(rs or "")
+ "The Plugins will be updated on the next restart triggered by selecting the Update button. Allow enough time for the service to restart. It will become briefly unavailable."
if self.coordinator.can_server_restart
else rs
)
@property
def release_url(self) -> str:
"""LMS Plugins info page."""
return str(
self.coordinator.lms.generate_image_url(
"/settings/index.html?activePage=SETUP_PLUGINS"
)
)
@property
def in_progress(self) -> bool:
"""Are we restarting."""
if self.latest_version == self.installed_version and self.restart_triggered:
_LOGGER.debug("plugin progress reset %s", self.coordinator.lms.name)
if callable(self._cancel_update):
self._cancel_update()
self.restart_triggered = False
return self.restart_triggered
async def async_install(
self, version: str | None, backup: bool, **kwargs: Any
) -> None:
"""Install all plugin updates."""
_LOGGER.debug(
"server restart for plugin install on %s", self.coordinator.lms.name
)
self.restart_triggered = True
self.async_write_ha_state()
result = await self.coordinator.lms.async_query("restartserver")
_LOGGER.debug("restart server result %s", result)
if not result:
self._cancel_update = async_call_later(
self.hass, POLL_AFTER_INSTALL, self._async_update_catchall
)
else:
self.restart_triggered = False
self.async_write_ha_state()
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="update_restart_failed",
)
async def _async_update_catchall(self, now: datetime | None = None) -> None:
"""Request update. clear restart catchall."""
if self.restart_triggered:
_LOGGER.debug("server restart catchall for %s", self.coordinator.lms.name)
self.restart_triggered = False
self.async_write_ha_state()
await self.async_update()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/squeezebox/update.py",
"license": "Apache License 2.0",
"lines": 144,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/sun/condition.py | """Offer sun based automation rules."""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any, Unpack, cast
import voluptuous as vol
from homeassistant.const import CONF_OPTIONS, SUN_EVENT_SUNRISE, SUN_EVENT_SUNSET
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.automation import move_top_level_schema_fields_to_options
from homeassistant.helpers.condition import (
Condition,
ConditionChecker,
ConditionCheckParams,
ConditionConfig,
condition_trace_set_result,
condition_trace_update_result,
)
from homeassistant.helpers.sun import get_astral_event_date
from homeassistant.helpers.typing import ConfigType
from homeassistant.util import dt as dt_util
_OPTIONS_SCHEMA_DICT: dict[vol.Marker, Any] = {
vol.Optional("before"): cv.sun_event,
vol.Optional("before_offset"): cv.time_period,
vol.Optional("after"): cv.sun_event,
vol.Optional("after_offset"): cv.time_period,
}
_CONDITION_SCHEMA = vol.Schema(
{
vol.Required(CONF_OPTIONS): vol.All(
_OPTIONS_SCHEMA_DICT,
cv.has_at_least_one_key("before", "after"),
)
}
)
def sun(
hass: HomeAssistant,
before: str | None = None,
after: str | None = None,
before_offset: timedelta | None = None,
after_offset: timedelta | None = None,
) -> bool:
"""Test if current time matches sun requirements."""
utcnow = dt_util.utcnow()
today = dt_util.as_local(utcnow).date()
before_offset = before_offset or timedelta(0)
after_offset = after_offset or timedelta(0)
sunrise = get_astral_event_date(hass, SUN_EVENT_SUNRISE, today)
sunset = get_astral_event_date(hass, SUN_EVENT_SUNSET, today)
has_sunrise_condition = SUN_EVENT_SUNRISE in (before, after)
has_sunset_condition = SUN_EVENT_SUNSET in (before, after)
after_sunrise = today > dt_util.as_local(cast(datetime, sunrise)).date()
if after_sunrise and has_sunrise_condition:
tomorrow = today + timedelta(days=1)
sunrise = get_astral_event_date(hass, SUN_EVENT_SUNRISE, tomorrow)
after_sunset = today > dt_util.as_local(cast(datetime, sunset)).date()
if after_sunset and has_sunset_condition:
tomorrow = today + timedelta(days=1)
sunset = get_astral_event_date(hass, SUN_EVENT_SUNSET, tomorrow)
# Special case: before sunrise OR after sunset
# This will handle the very rare case in the polar region when the sun rises/sets
# but does not set/rise.
# However this entire condition does not handle those full days of darkness
# or light, the following should be used instead:
#
# condition:
# condition: state
# entity_id: sun.sun
# state: 'above_horizon' (or 'below_horizon')
#
if before == SUN_EVENT_SUNRISE and after == SUN_EVENT_SUNSET:
wanted_time_before = cast(datetime, sunrise) + before_offset
condition_trace_update_result(wanted_time_before=wanted_time_before)
wanted_time_after = cast(datetime, sunset) + after_offset
condition_trace_update_result(wanted_time_after=wanted_time_after)
return utcnow < wanted_time_before or utcnow > wanted_time_after
if sunrise is None and has_sunrise_condition:
# There is no sunrise today
condition_trace_set_result(False, message="no sunrise today")
return False
if sunset is None and has_sunset_condition:
# There is no sunset today
condition_trace_set_result(False, message="no sunset today")
return False
if before == SUN_EVENT_SUNRISE:
wanted_time_before = cast(datetime, sunrise) + before_offset
condition_trace_update_result(wanted_time_before=wanted_time_before)
if utcnow > wanted_time_before:
return False
if before == SUN_EVENT_SUNSET:
wanted_time_before = cast(datetime, sunset) + before_offset
condition_trace_update_result(wanted_time_before=wanted_time_before)
if utcnow > wanted_time_before:
return False
if after == SUN_EVENT_SUNRISE:
wanted_time_after = cast(datetime, sunrise) + after_offset
condition_trace_update_result(wanted_time_after=wanted_time_after)
if utcnow < wanted_time_after:
return False
if after == SUN_EVENT_SUNSET:
wanted_time_after = cast(datetime, sunset) + after_offset
condition_trace_update_result(wanted_time_after=wanted_time_after)
if utcnow < wanted_time_after:
return False
return True
class SunCondition(Condition):
"""Sun condition."""
_options: dict[str, Any]
@classmethod
async def async_validate_complete_config(
cls, hass: HomeAssistant, complete_config: ConfigType
) -> ConfigType:
"""Validate complete config."""
complete_config = move_top_level_schema_fields_to_options(
complete_config, _OPTIONS_SCHEMA_DICT
)
return await super().async_validate_complete_config(hass, complete_config)
@classmethod
async def async_validate_config(
cls, hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
return cast(ConfigType, _CONDITION_SCHEMA(config))
def __init__(self, hass: HomeAssistant, config: ConditionConfig) -> None:
"""Initialize condition."""
super().__init__(hass, config)
assert config.options is not None
self._options = config.options
async def async_get_checker(self) -> ConditionChecker:
"""Wrap action method with sun based condition."""
before = self._options.get("before")
after = self._options.get("after")
before_offset = self._options.get("before_offset")
after_offset = self._options.get("after_offset")
def sun_if(**kwargs: Unpack[ConditionCheckParams]) -> bool:
"""Validate time based if-condition."""
return sun(self._hass, before, after, before_offset, after_offset)
return sun_if
CONDITIONS: dict[str, type[Condition]] = {
"_": SunCondition,
}
async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]:
"""Return the sun conditions."""
return CONDITIONS
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sun/condition.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/switchbot/vacuum.py | """Support for switchbot vacuums."""
from __future__ import annotations
from typing import Any
import switchbot
from switchbot import SwitchbotModel
from homeassistant.components.vacuum import (
StateVacuumEntity,
VacuumActivity,
VacuumEntityFeature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import SwitchbotConfigEntry, SwitchbotDataUpdateCoordinator
from .entity import SwitchbotEntity
PARALLEL_UPDATES = 0
DEVICE_SUPPORT_PROTOCOL_VERSION_1 = [
SwitchbotModel.K10_VACUUM,
SwitchbotModel.K10_PRO_VACUUM,
]
PROTOCOL_VERSION_1_STATE_TO_HA_STATE: dict[int, VacuumActivity] = {
0: VacuumActivity.CLEANING,
1: VacuumActivity.DOCKED,
}
PROTOCOL_VERSION_2_STATE_TO_HA_STATE: dict[int, VacuumActivity] = {
1: VacuumActivity.IDLE, # idle
2: VacuumActivity.DOCKED, # charge
3: VacuumActivity.DOCKED, # charge complete
4: VacuumActivity.IDLE, # self-check
5: VacuumActivity.IDLE, # the drum is moist
6: VacuumActivity.CLEANING, # exploration
7: VacuumActivity.CLEANING, # re-location
8: VacuumActivity.CLEANING, # cleaning and sweeping
9: VacuumActivity.CLEANING, # cleaning
10: VacuumActivity.CLEANING, # sweeping
11: VacuumActivity.PAUSED, # pause
12: VacuumActivity.CLEANING, # getting out of trouble
13: VacuumActivity.ERROR, # trouble
14: VacuumActivity.CLEANING, # mpo cleaning
15: VacuumActivity.RETURNING, # returning
16: VacuumActivity.CLEANING, # deep cleaning
17: VacuumActivity.CLEANING, # Sewage extraction
18: VacuumActivity.CLEANING, # replenish water for mop
19: VacuumActivity.CLEANING, # dust collection
20: VacuumActivity.CLEANING, # dry
21: VacuumActivity.IDLE, # dormant
22: VacuumActivity.IDLE, # network configuration
23: VacuumActivity.CLEANING, # remote control
24: VacuumActivity.RETURNING, # return to base
25: VacuumActivity.IDLE, # shut down
26: VacuumActivity.IDLE, # mark water base station
27: VacuumActivity.IDLE, # rinse the filter screen
28: VacuumActivity.IDLE, # mark humidifier location
29: VacuumActivity.IDLE, # on the way to the humidifier
30: VacuumActivity.IDLE, # add water for humidifier
31: VacuumActivity.IDLE, # upgrading
32: VacuumActivity.PAUSED, # pause during recharging
33: VacuumActivity.IDLE, # integrated with the platform
34: VacuumActivity.CLEANING, # working for the platform
}
SWITCHBOT_VACUUM_STATE_MAP: dict[int, dict[int, VacuumActivity]] = {
1: PROTOCOL_VERSION_1_STATE_TO_HA_STATE,
2: PROTOCOL_VERSION_2_STATE_TO_HA_STATE,
}
async def async_setup_entry(
hass: HomeAssistant,
entry: SwitchbotConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the switchbot vacuum."""
async_add_entities([SwitchbotVacuumEntity(entry.runtime_data)])
class SwitchbotVacuumEntity(SwitchbotEntity, StateVacuumEntity):
"""Representation of a SwitchBot vacuum."""
_device: switchbot.SwitchbotVacuum
_attr_supported_features = (
VacuumEntityFeature.RETURN_HOME
| VacuumEntityFeature.START
| VacuumEntityFeature.STATE
)
_attr_translation_key = "vacuum"
_attr_name = None
def __init__(self, coordinator: SwitchbotDataUpdateCoordinator) -> None:
"""Initialize the Switchbot."""
super().__init__(coordinator)
self.protocol_version = (
1 if coordinator.model in DEVICE_SUPPORT_PROTOCOL_VERSION_1 else 2
)
@property
def activity(self) -> VacuumActivity | None:
"""Return the status of the vacuum cleaner."""
status_code = self._device.get_work_status()
return SWITCHBOT_VACUUM_STATE_MAP[self.protocol_version].get(status_code)
async def async_start(self) -> None:
"""Start or resume the cleaning task."""
self._last_run_success = bool(
await self._device.clean_up(self.protocol_version)
)
async def async_return_to_base(self, **kwargs: Any) -> None:
"""Return to dock."""
self._last_run_success = bool(
await self._device.return_to_dock(self.protocol_version)
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/switchbot/vacuum.py",
"license": "Apache License 2.0",
"lines": 101,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/switchbot_cloud/binary_sensor.py | """Support for SwitchBot Cloud binary sensors."""
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from switchbot_api import Device, SwitchBotAPI
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import SwitchbotCloudData
from .const import DOMAIN
from .coordinator import SwitchBotCoordinator
from .entity import SwitchBotCloudEntity
@dataclass(frozen=True)
class SwitchBotCloudBinarySensorEntityDescription(BinarySensorEntityDescription):
"""Describes a Switchbot Cloud binary sensor."""
# Value or values to consider binary sensor to be "on"
on_value: bool | str = True
value_fn: Callable[[dict[str, Any]], bool | None] | None = None
CALIBRATION_DESCRIPTION = SwitchBotCloudBinarySensorEntityDescription(
key="calibrate",
name="Calibration",
translation_key="calibration",
device_class=BinarySensorDeviceClass.PROBLEM,
entity_category=EntityCategory.DIAGNOSTIC,
on_value=False,
)
DOOR_OPEN_DESCRIPTION = SwitchBotCloudBinarySensorEntityDescription(
key="doorState",
device_class=BinarySensorDeviceClass.DOOR,
on_value="opened",
)
MOVE_DETECTED_DESCRIPTION = SwitchBotCloudBinarySensorEntityDescription(
key="moveDetected",
device_class=BinarySensorDeviceClass.MOTION,
value_fn=(
lambda data: (
data.get("moveDetected") is True
or data.get("detectionState") == "DETECTED"
or data.get("detected") is True
)
),
)
IS_LIGHT_DESCRIPTION = SwitchBotCloudBinarySensorEntityDescription(
key="brightness",
device_class=BinarySensorDeviceClass.LIGHT,
on_value="bright",
)
LEAK_DESCRIPTION = SwitchBotCloudBinarySensorEntityDescription(
key="status",
device_class=BinarySensorDeviceClass.MOISTURE,
value_fn=lambda data: any(data.get(key) for key in ("status", "detectionState")),
)
OPEN_DESCRIPTION = SwitchBotCloudBinarySensorEntityDescription(
key="openState",
device_class=BinarySensorDeviceClass.OPENING,
value_fn=lambda data: data.get("openState") in ("open", "timeOutNotClose"),
)
BINARY_SENSOR_DESCRIPTIONS_BY_DEVICE_TYPES = {
"Smart Lock": (
CALIBRATION_DESCRIPTION,
DOOR_OPEN_DESCRIPTION,
),
"Smart Lock Lite": (
CALIBRATION_DESCRIPTION,
DOOR_OPEN_DESCRIPTION,
),
"Smart Lock Pro": (
CALIBRATION_DESCRIPTION,
DOOR_OPEN_DESCRIPTION,
),
"Smart Lock Ultra": (
CALIBRATION_DESCRIPTION,
DOOR_OPEN_DESCRIPTION,
),
"Smart Lock Vision": (
CALIBRATION_DESCRIPTION,
DOOR_OPEN_DESCRIPTION,
),
"Smart Lock Vision Pro": (
CALIBRATION_DESCRIPTION,
DOOR_OPEN_DESCRIPTION,
),
"Smart Lock Pro Wifi": (
CALIBRATION_DESCRIPTION,
DOOR_OPEN_DESCRIPTION,
),
"Curtain": (CALIBRATION_DESCRIPTION,),
"Curtain3": (CALIBRATION_DESCRIPTION,),
"Roller Shade": (CALIBRATION_DESCRIPTION,),
"Blind Tilt": (CALIBRATION_DESCRIPTION,),
"Garage Door Opener": (DOOR_OPEN_DESCRIPTION,),
"Motion Sensor": (MOVE_DETECTED_DESCRIPTION,),
"Contact Sensor": (
MOVE_DETECTED_DESCRIPTION,
IS_LIGHT_DESCRIPTION,
OPEN_DESCRIPTION,
),
"Hub 3": (MOVE_DETECTED_DESCRIPTION,),
"Water Detector": (LEAK_DESCRIPTION,),
"Climate Panel": (
IS_LIGHT_DESCRIPTION,
MOVE_DETECTED_DESCRIPTION,
),
"Presence Sensor": (MOVE_DETECTED_DESCRIPTION,),
}
async def async_setup_entry(
hass: HomeAssistant,
config: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up SwitchBot Cloud entry."""
data: SwitchbotCloudData = hass.data[DOMAIN][config.entry_id]
async_add_entities(
SwitchBotCloudBinarySensor(data.api, device, coordinator, description)
for device, coordinator in data.devices.binary_sensors
for description in BINARY_SENSOR_DESCRIPTIONS_BY_DEVICE_TYPES[
device.device_type
]
)
class SwitchBotCloudBinarySensor(SwitchBotCloudEntity, BinarySensorEntity):
"""Representation of a Switchbot binary sensor."""
entity_description: SwitchBotCloudBinarySensorEntityDescription
def __init__(
self,
api: SwitchBotAPI,
device: Device,
coordinator: SwitchBotCoordinator,
description: SwitchBotCloudBinarySensorEntityDescription,
) -> None:
"""Initialize SwitchBot Cloud sensor entity."""
super().__init__(api, device, coordinator)
self.entity_description = description
self._attr_unique_id = f"{device.device_id}_{description.key}"
def _set_attributes(self) -> None:
"""Set attributes from coordinator data."""
if not self.coordinator.data:
return
if self.entity_description.value_fn:
self._attr_is_on = self.entity_description.value_fn(self.coordinator.data)
return
self._attr_is_on = (
self.coordinator.data.get(self.entity_description.key)
== self.entity_description.on_value
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/switchbot_cloud/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 150,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/tuya/event.py | """Support for Tuya event entities."""
from __future__ import annotations
from base64 import b64decode
from dataclasses import dataclass
from typing import Any
from tuya_device_handlers.device_wrapper.base import DeviceWrapper
from tuya_device_handlers.device_wrapper.common import (
DPCodeEnumWrapper,
DPCodeRawWrapper,
DPCodeStringWrapper,
DPCodeTypeInformationWrapper,
)
from tuya_sharing import CustomerDevice, Manager
from homeassistant.components.event import (
EventDeviceClass,
EventEntity,
EventEntityDescription,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import TuyaConfigEntry
from .const import TUYA_DISCOVERY_NEW, DeviceCategory, DPCode
from .entity import TuyaEntity
class _EventEnumWrapper(DPCodeEnumWrapper):
"""Wrapper for event enum DP codes."""
def read_device_status( # type: ignore[override]
self, device: CustomerDevice
) -> tuple[str, None] | None:
"""Return the event details."""
if (raw_value := super().read_device_status(device)) is None:
return None
return (raw_value, None)
class _AlarmMessageWrapper(DPCodeStringWrapper):
"""Wrapper for a STRING message on DPCode.ALARM_MESSAGE."""
def __init__(self, dpcode: str, type_information: Any) -> None:
"""Init _AlarmMessageWrapper."""
super().__init__(dpcode, type_information)
self.options = ["triggered"]
def read_device_status(
self, device: CustomerDevice
) -> tuple[str, dict[str, Any]] | None:
"""Return the event attributes for the alarm message."""
if (raw_value := super().read_device_status(device)) is None:
return None
return ("triggered", {"message": b64decode(raw_value).decode("utf-8")})
class _DoorbellPicWrapper(DPCodeRawWrapper):
"""Wrapper for a RAW message on DPCode.DOORBELL_PIC.
It is expected that the RAW data is base64/utf8 encoded URL of the picture.
"""
def __init__(self, dpcode: str, type_information: Any) -> None:
"""Init _DoorbellPicWrapper."""
super().__init__(dpcode, type_information)
self.options = ["triggered"]
def read_device_status( # type: ignore[override]
self, device: CustomerDevice
) -> tuple[str, dict[str, Any]] | None:
"""Return the event attributes for the doorbell picture."""
if (status := super().read_device_status(device)) is None:
return None
return ("triggered", {"message": status.decode("utf-8")})
@dataclass(frozen=True)
class TuyaEventEntityDescription(EventEntityDescription):
"""Describe a Tuya Event entity."""
wrapper_class: type[DPCodeTypeInformationWrapper] = _EventEnumWrapper
# All descriptions can be found here. Mostly the Enum data types in the
# default status set of each category (that don't have a set instruction)
# end up being events.
EVENTS: dict[DeviceCategory, tuple[TuyaEventEntityDescription, ...]] = {
DeviceCategory.SP: (
TuyaEventEntityDescription(
key=DPCode.ALARM_MESSAGE,
device_class=EventDeviceClass.DOORBELL,
translation_key="doorbell_message",
wrapper_class=_AlarmMessageWrapper,
),
TuyaEventEntityDescription(
key=DPCode.DOORBELL_PIC,
device_class=EventDeviceClass.DOORBELL,
translation_key="doorbell_picture",
wrapper_class=_DoorbellPicWrapper,
),
),
DeviceCategory.WXKG: (
TuyaEventEntityDescription(
key=DPCode.SWITCH_MODE1,
device_class=EventDeviceClass.BUTTON,
translation_key="numbered_button",
translation_placeholders={"button_number": "1"},
),
TuyaEventEntityDescription(
key=DPCode.SWITCH_MODE2,
device_class=EventDeviceClass.BUTTON,
translation_key="numbered_button",
translation_placeholders={"button_number": "2"},
),
TuyaEventEntityDescription(
key=DPCode.SWITCH_MODE3,
device_class=EventDeviceClass.BUTTON,
translation_key="numbered_button",
translation_placeholders={"button_number": "3"},
),
TuyaEventEntityDescription(
key=DPCode.SWITCH_MODE4,
device_class=EventDeviceClass.BUTTON,
translation_key="numbered_button",
translation_placeholders={"button_number": "4"},
),
TuyaEventEntityDescription(
key=DPCode.SWITCH_MODE5,
device_class=EventDeviceClass.BUTTON,
translation_key="numbered_button",
translation_placeholders={"button_number": "5"},
),
TuyaEventEntityDescription(
key=DPCode.SWITCH_MODE6,
device_class=EventDeviceClass.BUTTON,
translation_key="numbered_button",
translation_placeholders={"button_number": "6"},
),
TuyaEventEntityDescription(
key=DPCode.SWITCH_MODE7,
device_class=EventDeviceClass.BUTTON,
translation_key="numbered_button",
translation_placeholders={"button_number": "7"},
),
TuyaEventEntityDescription(
key=DPCode.SWITCH_MODE8,
device_class=EventDeviceClass.BUTTON,
translation_key="numbered_button",
translation_placeholders={"button_number": "8"},
),
TuyaEventEntityDescription(
key=DPCode.SWITCH_MODE9,
device_class=EventDeviceClass.BUTTON,
translation_key="numbered_button",
translation_placeholders={"button_number": "9"},
),
),
}
async def async_setup_entry(
hass: HomeAssistant,
entry: TuyaConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Tuya events dynamically through Tuya discovery."""
manager = entry.runtime_data.manager
@callback
def async_discover_device(device_ids: list[str]) -> None:
"""Discover and add a discovered Tuya binary sensor."""
entities: list[TuyaEventEntity] = []
for device_id in device_ids:
device = manager.device_map[device_id]
if descriptions := EVENTS.get(device.category):
entities.extend(
TuyaEventEntity(
device, manager, description, dpcode_wrapper=dpcode_wrapper
)
for description in descriptions
if (
dpcode_wrapper := description.wrapper_class.find_dpcode(
device, description.key
)
)
)
async_add_entities(entities)
async_discover_device([*manager.device_map])
entry.async_on_unload(
async_dispatcher_connect(hass, TUYA_DISCOVERY_NEW, async_discover_device)
)
class TuyaEventEntity(TuyaEntity, EventEntity):
"""Tuya Event Entity."""
entity_description: EventEntityDescription
def __init__(
self,
device: CustomerDevice,
device_manager: Manager,
description: EventEntityDescription,
dpcode_wrapper: DeviceWrapper[tuple[str, dict[str, Any] | None]],
) -> None:
"""Init Tuya event entity."""
super().__init__(device, device_manager)
self.entity_description = description
self._attr_unique_id = f"{super().unique_id}{description.key}"
self._dpcode_wrapper = dpcode_wrapper
self._attr_event_types = dpcode_wrapper.options
async def _process_device_update(
self,
updated_status_properties: list[str],
dp_timestamps: dict[str, int] | None,
) -> bool:
"""Called when Tuya device sends an update with updated properties.
Returns True if the Home Assistant state should be written,
or False if the state write should be skipped.
"""
if self._dpcode_wrapper.skip_update(
self.device, updated_status_properties, dp_timestamps
) or not (event_data := self._dpcode_wrapper.read_device_status(self.device)):
return False
event_type, event_attributes = event_data
self._trigger_event(event_type, event_attributes)
return True
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/tuya/event.py",
"license": "Apache License 2.0",
"lines": 202,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/wallbox/select.py | """Home Assistant component for accessing the Wallbox Portal API. The switch component creates a switch entity."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from requests import HTTPError
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import (
CHARGER_DATA_KEY,
CHARGER_ECO_SMART_KEY,
CHARGER_FEATURES_KEY,
CHARGER_PLAN_KEY,
CHARGER_POWER_BOOST_KEY,
CHARGER_SERIAL_NUMBER_KEY,
DOMAIN,
EcoSmartMode,
)
from .coordinator import WallboxConfigEntry, WallboxCoordinator
from .entity import WallboxEntity
@dataclass(frozen=True, kw_only=True)
class WallboxSelectEntityDescription(SelectEntityDescription):
"""Describes Wallbox select entity."""
current_option_fn: Callable[[WallboxCoordinator], str | None]
select_option_fn: Callable[[WallboxCoordinator, str], Awaitable[None]]
supported_fn: Callable[[WallboxCoordinator], bool]
SELECT_TYPES: dict[str, WallboxSelectEntityDescription] = {
CHARGER_ECO_SMART_KEY: WallboxSelectEntityDescription(
key=CHARGER_ECO_SMART_KEY,
translation_key=CHARGER_ECO_SMART_KEY,
options=[
EcoSmartMode.OFF,
EcoSmartMode.ECO_MODE,
EcoSmartMode.FULL_SOLAR,
],
select_option_fn=lambda coordinator, mode: coordinator.async_set_eco_smart(
mode
),
current_option_fn=lambda coordinator: coordinator.data[CHARGER_ECO_SMART_KEY],
supported_fn=lambda coordinator: coordinator.data[CHARGER_DATA_KEY][
CHARGER_PLAN_KEY
][CHARGER_FEATURES_KEY].count(CHARGER_POWER_BOOST_KEY),
)
}
async def async_setup_entry(
hass: HomeAssistant,
entry: WallboxConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Create wallbox select entities in HASS."""
coordinator: WallboxCoordinator = entry.runtime_data
if coordinator.data[CHARGER_ECO_SMART_KEY] != EcoSmartMode.DISABLED:
async_add_entities(
WallboxSelect(coordinator, description)
for ent in coordinator.data
if (
(description := SELECT_TYPES.get(ent))
and description.supported_fn(coordinator)
)
)
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
class WallboxSelect(WallboxEntity, SelectEntity):
"""Representation of the Wallbox portal."""
entity_description: WallboxSelectEntityDescription
def __init__(
self,
coordinator: WallboxCoordinator,
description: WallboxSelectEntityDescription,
) -> None:
"""Initialize a Wallbox select entity."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{description.key}-{coordinator.data[CHARGER_DATA_KEY][CHARGER_SERIAL_NUMBER_KEY]}"
@property
def current_option(self) -> str | None:
"""Return an option."""
return self.entity_description.current_option_fn(self.coordinator)
async def async_select_option(self, option: str) -> None:
"""Handle the selection of an option."""
try:
await self.entity_description.select_option_fn(self.coordinator, option)
except (ConnectionError, HTTPError) as e:
raise HomeAssistantError(
translation_key="api_failed", translation_domain=DOMAIN
) from e
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/wallbox/select.py",
"license": "Apache License 2.0",
"lines": 88,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/wmspro/button.py | """Identify support for WMS WebControl pro."""
from __future__ import annotations
from wmspro.const import WMS_WebControl_pro_API_actionDescription
from homeassistant.components.button import ButtonDeviceClass, ButtonEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import WebControlProConfigEntry
from .entity import WebControlProGenericEntity
async def async_setup_entry(
hass: HomeAssistant,
config_entry: WebControlProConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the WMS based identify buttons from a config entry."""
hub = config_entry.runtime_data
entities: list[WebControlProGenericEntity] = [
WebControlProIdentifyButton(config_entry.entry_id, dest)
for dest in hub.dests.values()
if dest.hasAction(WMS_WebControl_pro_API_actionDescription.Identify)
]
async_add_entities(entities)
class WebControlProIdentifyButton(WebControlProGenericEntity, ButtonEntity):
"""Representation of a WMS based identify button."""
_attr_device_class = ButtonDeviceClass.IDENTIFY
async def async_press(self) -> None:
"""Handle the button press."""
action = self._dest.action(WMS_WebControl_pro_API_actionDescription.Identify)
await action()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/wmspro/button.py",
"license": "Apache License 2.0",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/zimi/config_flow.py | """Config flow for zcc integration."""
from __future__ import annotations
import logging
from typing import Any
import voluptuous as vol
from zcc import (
ControlPoint,
ControlPointCannotConnectError,
ControlPointConnectionRefusedError,
ControlPointDescription,
ControlPointDiscoveryService,
ControlPointError,
ControlPointInvalidHostError,
ControlPointTimeoutError,
)
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PORT
from homeassistant.helpers.device_registry import format_mac
from homeassistant.helpers.selector import (
SelectOptionDict,
SelectSelector,
SelectSelectorConfig,
SelectSelectorMode,
)
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
DEFAULT_PORT = 5003
STEP_MANUAL_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
}
)
SELECTED_HOST_AND_PORT = "selected_host_and_port"
class ZimiConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for zcc."""
api: ControlPoint = None
api_descriptions: list[ControlPointDescription]
data: dict[str, Any]
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial auto-discovery step."""
self.data = {}
try:
self.api_descriptions = await ControlPointDiscoveryService().discovers()
except ControlPointError:
# ControlPointError is expected if no zcc are found on LAN
return await self.async_step_manual()
if len(self.api_descriptions) == 1:
self.data[CONF_HOST] = self.api_descriptions[0].host
self.data[CONF_PORT] = self.api_descriptions[0].port
await self.check_connection(self.data[CONF_HOST], self.data[CONF_PORT])
return await self.create_entry()
return await self.async_step_selection()
async def async_step_selection(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle selection of zcc to configure if multiple are discovered."""
errors: dict[str, str] | None = {}
if user_input is not None:
self.data[CONF_HOST] = user_input[SELECTED_HOST_AND_PORT].split(":")[0]
self.data[CONF_PORT] = int(user_input[SELECTED_HOST_AND_PORT].split(":")[1])
errors = await self.check_connection(
self.data[CONF_HOST], self.data[CONF_PORT]
)
if not errors:
return await self.create_entry()
available_options = [
SelectOptionDict(
label=f"{description.host}:{description.port}",
value=f"{description.host}:{description.port}",
)
for description in self.api_descriptions
]
available_schema = vol.Schema(
{
vol.Required(
SELECTED_HOST_AND_PORT, default=available_options[0]["value"]
): SelectSelector(
SelectSelectorConfig(
options=available_options,
mode=SelectSelectorMode.DROPDOWN,
)
)
}
)
return self.async_show_form(
step_id="selection", data_schema=available_schema, errors=errors
)
async def async_step_manual(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle manual configuration step if needed."""
errors: dict[str, str] | None = {}
if user_input is not None:
self.data = {**self.data, **user_input}
errors = await self.check_connection(
self.data[CONF_HOST], self.data[CONF_PORT]
)
if not errors:
return await self.create_entry()
return self.async_show_form(
step_id="manual",
data_schema=self.add_suggested_values_to_schema(
STEP_MANUAL_DATA_SCHEMA, self.data
),
errors=errors,
)
async def check_connection(self, host: str, port: int) -> dict[str, str] | None:
"""Check connection to zcc.
Stores mac and returns None if successful, otherwise returns error message.
"""
try:
result = await ControlPointDiscoveryService().validate_connection(
self.data[CONF_HOST], self.data[CONF_PORT]
)
except ControlPointInvalidHostError:
return {"base": "invalid_host"}
except ControlPointConnectionRefusedError:
return {"base": "connection_refused"}
except ControlPointCannotConnectError:
return {"base": "cannot_connect"}
except ControlPointTimeoutError:
return {"base": "timeout"}
except Exception:
_LOGGER.exception("Unexpected error")
return {"base": "unknown"}
self.data[CONF_MAC] = format_mac(result.mac)
return None
async def create_entry(self) -> ConfigFlowResult:
"""Create entry for zcc."""
await self.async_set_unique_id(self.data[CONF_MAC])
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"ZIMI Controller ({self.data[CONF_HOST]}:{self.data[CONF_PORT]})",
data=self.data,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zimi/config_flow.py",
"license": "Apache License 2.0",
"lines": 138,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/zimi/cover.py | """Platform for cover integration."""
from __future__ import annotations
import logging
from typing import Any
from homeassistant.components.cover import (
CoverDeviceClass,
CoverEntity,
CoverEntityFeature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import ZimiConfigEntry
from .entity import ZimiEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ZimiConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Zimi Cover platform."""
api = config_entry.runtime_data
covers = [ZimiCover(device, api) for device in api.blinds]
covers.extend(ZimiCover(device, api) for device in api.doors)
async_add_entities(covers)
class ZimiCover(ZimiEntity, CoverEntity):
"""Representation of a Zimi cover."""
_attr_device_class = CoverDeviceClass.GARAGE
_attr_supported_features = (
CoverEntityFeature.OPEN
| CoverEntityFeature.CLOSE
| CoverEntityFeature.SET_POSITION
| CoverEntityFeature.STOP
)
async def async_close_cover(self, **kwargs: Any) -> None:
"""Close the cover/door."""
_LOGGER.debug("Sending close_cover() for %s", self.name)
await self._device.close_door()
@property
def current_cover_position(self) -> int | None:
"""Return the current cover/door position."""
return self._device.percentage
@property
def is_closed(self) -> bool | None:
"""Return true if cover is closed."""
return self._device.is_closed
@property
def is_closing(self) -> bool | None:
"""Return true if cover is closing."""
return self._device.is_closing
@property
def is_opening(self) -> bool | None:
"""Return true if cover is opening."""
return self._device.is_opening
@property
def is_open(self) -> bool | None:
"""Return true if cover is open."""
return self._device.is_open
async def async_open_cover(self, **kwargs: Any) -> None:
"""Open the cover/door."""
_LOGGER.debug("Sending open_cover() for %s", self.name)
await self._device.open_door()
async def async_set_cover_position(self, **kwargs: Any) -> None:
"""Open the cover/door to a specified percentage."""
position = kwargs.get("position", 0)
_LOGGER.debug("Sending set_cover_position(%d) for %s", position, self.name)
await self._device.open_to_percentage(position)
async def async_stop_cover(self, **kwargs: Any) -> None:
"""Stop the cover."""
_LOGGER.debug(
"Stopping open_cover() by setting to current position for %s", self.name
)
await self.async_set_cover_position(position=self.current_cover_position)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zimi/cover.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/zimi/entity.py | """Base entity for zimi integrations."""
from __future__ import annotations
import logging
from zcc import ControlPoint
from zcc.device import ControlPointDevice
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import Entity
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
class ZimiEntity(Entity):
"""Representation of a Zimi API entity."""
_attr_should_poll = False
_attr_has_entity_name = True
def __init__(
self, device: ControlPointDevice, api: ControlPoint, use_device_name=True
) -> None:
"""Initialize an HA Entity which is a ZimiDevice."""
self._device = device
self._attr_unique_id = device.identifier
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.manufacture_info.identifier)},
manufacturer=device.manufacture_info.manufacturer,
model=device.manufacture_info.model,
name=device.manufacture_info.name,
hw_version=device.manufacture_info.hwVersion,
sw_version=device.manufacture_info.firmwareVersion,
suggested_area=device.room,
via_device=(DOMAIN, api.mac),
)
if use_device_name:
self._attr_name = device.name.strip()
self._attr_suggested_area = device.room
@property
def available(self) -> bool:
"""Return True if Home Assistant is able to read the state and control the underlying device."""
return self._device.is_connected
async def async_added_to_hass(self) -> None:
"""Subscribe to the events."""
await super().async_added_to_hass()
self._device.subscribe(self)
async def async_will_remove_from_hass(self) -> None:
"""Cleanup ZimiLight with removal of notification prior to removal."""
self._device.unsubscribe(self)
await super().async_will_remove_from_hass()
def notify(self, _observable: object) -> None:
"""Receive notification from device that state has changed.
No data is fetched for the notification but schedule_update_ha_state is called.
"""
_LOGGER.debug(
"Received notification() for %s in %s", self._device.name, self._device.room
)
self.schedule_update_ha_state(force_refresh=True)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zimi/entity.py",
"license": "Apache License 2.0",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/zimi/fan.py | """Platform for fan integration."""
from __future__ import annotations
import logging
import math
from typing import Any
from homeassistant.components.fan import FanEntity, FanEntityFeature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.percentage import (
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from homeassistant.util.scaling import int_states_in_range
from . import ZimiConfigEntry
from .entity import ZimiEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ZimiConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Zimi Fan platform."""
api = config_entry.runtime_data
async_add_entities([ZimiFan(device, api) for device in api.fans])
class ZimiFan(ZimiEntity, FanEntity):
"""Representation of a Zimi fan."""
_attr_speed_range = (0, 7)
_attr_supported_features = (
FanEntityFeature.SET_SPEED
| FanEntityFeature.TURN_OFF
| FanEntityFeature.TURN_ON
)
async def async_set_percentage(self, percentage: int) -> None:
"""Set the desired speed for the fan."""
if percentage == 0:
await self.async_turn_off()
return
target_speed = math.ceil(
percentage_to_ranged_value(self._attr_speed_range, percentage)
)
_LOGGER.debug(
"Sending async_set_percentage() for %s with percentage %s",
self.name,
percentage,
)
await self._device.set_fanspeed(target_speed)
async def async_turn_on(
self,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Instruct the fan to turn on."""
_LOGGER.debug("Sending turn_on() for %s", self.name)
await self._device.turn_on()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Instruct the fan to turn off."""
_LOGGER.debug("Sending turn_off() for %s", self.name)
await self._device.turn_off()
@property
def percentage(self) -> int:
"""Return the current speed percentage for the fan."""
if not self._device.fanspeed:
return 0
return ranged_value_to_percentage(self._attr_speed_range, self._device.fanspeed)
@property
def speed_count(self) -> int:
"""Return the number of speeds the fan supports."""
return int_states_in_range(self._attr_speed_range)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zimi/fan.py",
"license": "Apache License 2.0",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/zimi/helpers.py | """The zcc integration helpers."""
from __future__ import annotations
import logging
from zcc import ControlPoint, ControlPointDescription
from homeassistant.exceptions import ConfigEntryNotReady
_LOGGER = logging.getLogger(__name__)
async def async_connect_to_controller(
host: str, port: int, fast: bool = False
) -> ControlPoint:
"""Connect to Zimi Cloud Controller with defined parameters."""
_LOGGER.debug("Connecting to %s:%d", host, port)
api = ControlPoint(
description=ControlPointDescription(
host=host,
port=port,
)
)
await api.connect(fast=fast)
if api.ready:
_LOGGER.debug("Connected")
if not fast:
api.start_watchdog()
_LOGGER.debug("Started watchdog")
return api
raise ConfigEntryNotReady("Connection failed: not ready")
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zimi/helpers.py",
"license": "Apache License 2.0",
"lines": 25,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/zimi/light.py | """Light platform for zcc integration."""
from __future__ import annotations
import logging
from typing import Any
from zcc import ControlPoint
from zcc.device import ControlPointDevice
from homeassistant.components.light import ATTR_BRIGHTNESS, ColorMode, LightEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import ZimiConfigEntry
from .entity import ZimiEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ZimiConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Zimi Light platform."""
api = config_entry.runtime_data
lights: list[ZimiLight | ZimiDimmer] = [
ZimiLight(device, api) for device in api.lights if device.type != "dimmer"
]
lights.extend(
ZimiDimmer(device, api) for device in api.lights if device.type == "dimmer"
)
async_add_entities(lights)
class ZimiLight(ZimiEntity, LightEntity):
"""Representation of a Zimi Light."""
def __init__(self, device: ControlPointDevice, api: ControlPoint) -> None:
"""Initialize a ZimiLight."""
super().__init__(device, api)
self._attr_color_mode = ColorMode.ONOFF
self._attr_supported_color_modes = {ColorMode.ONOFF}
@property
def is_on(self) -> bool:
"""Return true if light is on."""
return self._device.is_on
async def async_turn_on(self, **kwargs: Any) -> None:
"""Instruct the light to turn on (with optional brightness)."""
_LOGGER.debug(
"Sending turn_on() for %s in %s", self._device.name, self._device.room
)
await self._device.turn_on()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Instruct the light to turn off."""
_LOGGER.debug(
"Sending turn_off() for %s in %s", self._device.name, self._device.room
)
await self._device.turn_off()
class ZimiDimmer(ZimiLight):
"""Zimi Light supporting dimming."""
def __init__(self, device: ControlPointDevice, api: ControlPoint) -> None:
"""Initialize a ZimiDimmer."""
super().__init__(device, api)
self._attr_color_mode = ColorMode.BRIGHTNESS
self._attr_supported_color_modes = {ColorMode.BRIGHTNESS}
async def async_turn_on(self, **kwargs: Any) -> None:
"""Instruct the light to turn on (with optional brightness)."""
brightness = kwargs.get(ATTR_BRIGHTNESS, 255) * 100 / 255
_LOGGER.debug(
"Sending turn_on(brightness=%d) for %s in %s",
brightness,
self._device.name,
self._device.room,
)
await self._device.set_brightness(brightness)
@property
def brightness(self) -> int | None:
"""Return the brightness of the light."""
return round(self._device.brightness * 255 / 100)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zimi/light.py",
"license": "Apache License 2.0",
"lines": 70,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/zimi/sensor.py | """Platform for sensor integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
import logging
from zcc import ControlPoint
from zcc.device import ControlPointDevice
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from . import ZimiConfigEntry
from .entity import ZimiEntity
@dataclass(frozen=True, kw_only=True)
class ZimiSensorEntityDescription(SensorEntityDescription):
"""Class describing Zimi sensor entities."""
value_fn: Callable[[ControlPointDevice], StateType]
GARAGE_SENSOR_DESCRIPTIONS: tuple[ZimiSensorEntityDescription, ...] = (
ZimiSensorEntityDescription(
key="door_temperature",
translation_key="door_temperature",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
device_class=SensorDeviceClass.TEMPERATURE,
value_fn=lambda device: device.door_temp,
),
ZimiSensorEntityDescription(
key="garage_battery",
native_unit_of_measurement=PERCENTAGE,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.BATTERY,
value_fn=lambda device: device.battery_level,
),
ZimiSensorEntityDescription(
key="garage_temperature",
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
device_class=SensorDeviceClass.TEMPERATURE,
value_fn=lambda device: device.garage_temp,
),
ZimiSensorEntityDescription(
key="garage_humidty",
native_unit_of_measurement=PERCENTAGE,
device_class=SensorDeviceClass.HUMIDITY,
value_fn=lambda device: device.garage_humidity,
),
)
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ZimiConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Zimi Sensor platform."""
api = config_entry.runtime_data
async_add_entities(
ZimiSensor(device, description, api)
for device in api.sensors
for description in GARAGE_SENSOR_DESCRIPTIONS
)
class ZimiSensor(ZimiEntity, SensorEntity):
"""Representation of a Zimi sensor."""
entity_description: ZimiSensorEntityDescription
def __init__(
self,
device: ControlPointDevice,
description: ZimiSensorEntityDescription,
api: ControlPoint,
) -> None:
"""Initialize an ZimiSensor with specified type."""
super().__init__(device, api, use_device_name=False)
self.entity_description = description
self._attr_unique_id = device.identifier + "." + self.entity_description.key
@property
def native_value(self) -> StateType:
"""Return the state of the sensor."""
return self.entity_description.value_fn(self._device)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zimi/sensor.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/zimi/switch.py | """Switch platform for zcc integration."""
from __future__ import annotations
import logging
from typing import Any
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import ZimiConfigEntry
from .entity import ZimiEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ZimiConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Zimi Switch platform."""
api = config_entry.runtime_data
outlets = [ZimiSwitch(device, api) for device in api.outlets]
async_add_entities(outlets)
class ZimiSwitch(ZimiEntity, SwitchEntity):
"""Representation of an Zimi Switch."""
@property
def is_on(self) -> bool:
"""Return true if switch is on."""
return self._device.is_on
async def async_turn_on(self, **kwargs: Any) -> None:
"""Instruct the switch to turn on."""
_LOGGER.debug(
"Sending turn_on() for %s in %s", self._device.name, self._device.room
)
await self._device.turn_on()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Instruct the switch to turn off."""
_LOGGER.debug(
"Sending turn_off() for %s in %s", self._device.name, self._device.room
)
await self._device.turn_off()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zimi/switch.py",
"license": "Apache License 2.0",
"lines": 37,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/helpers/helper_integration.py | """Helpers for helper integrations."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from typing import Any
from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, valid_entity_id
from . import device_registry as dr, entity_registry as er
from .event import async_track_entity_registry_updated_event
def async_handle_source_entity_changes(
hass: HomeAssistant,
*,
add_helper_config_entry_to_device: bool = True,
helper_config_entry_id: str,
set_source_entity_id_or_uuid: Callable[[str], None],
source_device_id: str | None,
source_entity_id_or_uuid: str,
source_entity_removed: Callable[[], Coroutine[Any, Any, None]] | None = None,
) -> CALLBACK_TYPE:
"""Handle changes to a helper entity's source entity.
The following changes are handled:
- Entity removal: If the source entity is removed:
- If source_entity_removed is provided, it is called to handle the removal.
- If source_entity_removed is not provided, The helper entity is updated to
not link to any device.
- Entity ID changed: If the source entity's entity ID changes and the source
entity is identified by an entity ID, the set_source_entity_id_or_uuid is
called. If the source entity is identified by a UUID, the helper config entry
is reloaded.
- Source entity moved to another device: The helper entity is updated to link
to the new device, and the helper config entry removed from the old device
and added to the new device. Then the helper config entry is reloaded.
- Source entity removed from the device: The helper entity is updated to link
to no device, and the helper config entry removed from the old device. Then
the helper config entry is reloaded.
:param set_source_entity_id_or_uuid: A function which updates the source entity
ID or UUID, e.g., in the helper config entry options.
:param source_entity_removed: A function which is called when the source entity
is removed. This can be used to clean up any resources related to the source
entity or ask the user to select a new source entity.
"""
async def async_registry_updated(
event: Event[er.EventEntityRegistryUpdatedData],
) -> None:
"""Handle entity registry update."""
nonlocal source_device_id
data = event.data
if data["action"] == "remove":
if source_entity_removed:
await source_entity_removed()
else:
for (
helper_entity_entry
) in entity_registry.entities.get_entries_for_config_entry_id(
helper_config_entry_id
):
# Update the helper entity to link to the new device (or no device)
entity_registry.async_update_entity(
helper_entity_entry.entity_id, device_id=None
)
if data["action"] != "update":
return
if "entity_id" in data["changes"]:
# Entity_id changed, update or reload the config entry
if valid_entity_id(source_entity_id_or_uuid):
# If the entity is pointed to by an entity ID, update the entry
set_source_entity_id_or_uuid(data["entity_id"])
else:
await hass.config_entries.async_reload(helper_config_entry_id)
if not source_device_id or "device_id" not in data["changes"]:
return
# Handle the source entity being moved to a different device or removed
# from the device
if (
not (source_entity_entry := entity_registry.async_get(data["entity_id"]))
or not device_registry.async_get(source_device_id)
or source_entity_entry.device_id == source_device_id
):
# No need to do any cleanup
return
# The source entity has been moved to a different device, update the helper
# entities to link to the new device and the helper device to include the
# helper config entry
for helper_entity in entity_registry.entities.get_entries_for_config_entry_id(
helper_config_entry_id
):
# Update the helper entity to link to the new device (or no device)
entity_registry.async_update_entity(
helper_entity.entity_id, device_id=source_entity_entry.device_id
)
if add_helper_config_entry_to_device:
if source_entity_entry.device_id is not None:
device_registry.async_update_device(
source_entity_entry.device_id,
add_config_entry_id=helper_config_entry_id,
)
device_registry.async_update_device(
source_device_id, remove_config_entry_id=helper_config_entry_id
)
source_device_id = source_entity_entry.device_id
# Reload the config entry so the helper entity is recreated with
# correct device info
await hass.config_entries.async_reload(helper_config_entry_id)
device_registry = dr.async_get(hass)
entity_registry = er.async_get(hass)
source_entity_id = er.async_validate_entity_id(
entity_registry, source_entity_id_or_uuid
)
return async_track_entity_registry_updated_event(
hass, source_entity_id, async_registry_updated
)
def async_remove_helper_config_entry_from_source_device(
hass: HomeAssistant,
*,
helper_config_entry_id: str,
source_device_id: str,
) -> None:
"""Remove helper config entry from source device.
This is a convenience function to migrate from helpers which added their config
entry to the source device.
"""
device_registry = dr.async_get(hass)
if (
not (source_device := device_registry.async_get(source_device_id))
or helper_config_entry_id not in source_device.config_entries
):
return
entity_registry = er.async_get(hass)
helper_entity_entries = er.async_entries_for_config_entry(
entity_registry, helper_config_entry_id
)
# Disconnect helper entities from the device to prevent them from
# being removed when the config entry link to the device is removed.
modified_helpers: list[er.RegistryEntry] = []
for helper in helper_entity_entries:
if helper.device_id != source_device_id:
continue
modified_helpers.append(helper)
entity_registry.async_update_entity(helper.entity_id, device_id=None)
# Remove the helper config entry from the device
device_registry.async_update_device(
source_device_id, remove_config_entry_id=helper_config_entry_id
)
# Connect the helper entity to the device
for helper in modified_helpers:
entity_registry.async_update_entity(
helper.entity_id, device_id=source_device_id
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/helpers/helper_integration.py",
"license": "Apache License 2.0",
"lines": 146,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/alexa_devices/const.py | """Alexa Devices tests const."""
from datetime import UTC, datetime
from aioamazondevices.const.schedules import (
NOTIFICATION_ALARM,
NOTIFICATION_REMINDER,
NOTIFICATION_TIMER,
)
from aioamazondevices.structures import AmazonDevice, AmazonDeviceSensor, AmazonSchedule
TEST_CODE = "023123"
TEST_PASSWORD = "fake_password"
TEST_USERNAME = "fake_email@gmail.com"
TEST_DEVICE_1_SN = "echo_test_serial_number"
TEST_DEVICE_1_ID = "echo_test_device_id"
TEST_DEVICE_1 = AmazonDevice(
account_name="Echo Test",
capabilities=["AUDIO_PLAYER", "MICROPHONE"],
device_family="mine",
device_type="echo",
household_device=False,
device_owner_customer_id="amazon_ower_id",
device_cluster_members=[TEST_DEVICE_1_SN],
online=True,
serial_number=TEST_DEVICE_1_SN,
software_version="echo_test_software_version",
entity_id="11111111-2222-3333-4444-555555555555",
endpoint_id="G1234567890123456789012345678A",
sensors={
"dnd": AmazonDeviceSensor(
name="dnd",
value=False,
error=False,
error_msg=None,
error_type=None,
scale=None,
),
"temperature": AmazonDeviceSensor(
name="temperature",
value="22.5",
error=False,
error_msg=None,
error_type=None,
scale="CELSIUS",
),
},
notifications_supported=True,
notifications={
NOTIFICATION_ALARM: AmazonSchedule(
type=NOTIFICATION_ALARM,
status="ON",
label="Morning Alarm",
next_occurrence=datetime(2023, 10, 1, 7, 0, 0, tzinfo=UTC),
),
NOTIFICATION_REMINDER: AmazonSchedule(
type=NOTIFICATION_REMINDER,
status="ON",
label="Take out the trash",
next_occurrence=None,
),
NOTIFICATION_TIMER: AmazonSchedule(
type=NOTIFICATION_TIMER,
status="OFF",
label="",
next_occurrence=None,
),
},
)
TEST_DEVICE_2_SN = "echo_test_2_serial_number"
TEST_DEVICE_2_ID = "echo_test_2_device_id"
TEST_DEVICE_2 = AmazonDevice(
account_name="Echo Test 2",
capabilities=["AUDIO_PLAYER", "MICROPHONE"],
device_family="mine",
device_type="echo",
household_device=True,
device_owner_customer_id="amazon_ower_id",
device_cluster_members=[TEST_DEVICE_2_SN],
online=True,
serial_number=TEST_DEVICE_2_SN,
software_version="echo_test_2_software_version",
entity_id="11111111-2222-3333-4444-555555555555",
endpoint_id="G1234567890123456789012345678A",
sensors={
"temperature": AmazonDeviceSensor(
name="temperature",
value="22.5",
error=False,
error_msg=None,
error_type=None,
scale="CELSIUS",
)
},
notifications_supported=False,
notifications={},
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/const.py",
"license": "Apache License 2.0",
"lines": 94,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/alexa_devices/test_binary_sensor.py | """Tests for the Alexa Devices binary sensor platform."""
from unittest.mock import AsyncMock, patch
from aioamazondevices.exceptions import (
CannotAuthenticate,
CannotConnect,
CannotRetrieveData,
)
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.alexa_devices.const import DOMAIN
from homeassistant.components.alexa_devices.coordinator import SCAN_INTERVAL
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from homeassistant.const import STATE_ON, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import setup_integration
from .const import TEST_DEVICE_1, TEST_DEVICE_1_SN, TEST_DEVICE_2, TEST_DEVICE_2_SN
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.alexa_devices.PLATFORMS", [Platform.BINARY_SENSOR]
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"side_effect",
[
CannotConnect,
CannotRetrieveData,
CannotAuthenticate,
],
)
async def test_coordinator_data_update_fails(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
side_effect: Exception,
) -> None:
"""Test coordinator data update exceptions."""
entity_id = "binary_sensor.echo_test_connectivity"
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(entity_id))
assert state.state == STATE_ON
mock_amazon_devices_client.get_devices_data.side_effect = side_effect
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
async def test_offline_device(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test offline device handling."""
entity_id = "binary_sensor.echo_test_connectivity"
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].online = False
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].online = True
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state != STATE_UNAVAILABLE
async def test_dynamic_device(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test device added dynamically."""
entity_id_1 = "binary_sensor.echo_test_connectivity"
entity_id_2 = "binary_sensor.echo_test_2_connectivity"
mock_amazon_devices_client.get_devices_data.return_value = {
TEST_DEVICE_1_SN: TEST_DEVICE_1,
}
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(entity_id_1))
assert state.state == STATE_ON
assert not hass.states.get(entity_id_2)
mock_amazon_devices_client.get_devices_data.return_value = {
TEST_DEVICE_1_SN: TEST_DEVICE_1,
TEST_DEVICE_2_SN: TEST_DEVICE_2,
}
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id_1))
assert state.state == STATE_ON
assert (state := hass.states.get(entity_id_2))
assert state.state == STATE_ON
@pytest.mark.parametrize(
"key",
[
"bluetooth",
"babyCryDetectionState",
"beepingApplianceDetectionState",
"coughDetectionState",
"dogBarkDetectionState",
"waterSoundsDetectionState",
],
)
async def test_deprecated_sensor_removal(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
key: str,
) -> None:
"""Test deprecated sensors are removed."""
mock_config_entry.add_to_hass(hass)
device = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, mock_config_entry.entry_id)},
name=mock_config_entry.title,
manufacturer="Amazon",
model="Echo Dot",
entry_type=dr.DeviceEntryType.SERVICE,
)
entity = entity_registry.async_get_or_create(
BINARY_SENSOR_DOMAIN,
DOMAIN,
unique_id=f"{TEST_DEVICE_1_SN}-{key}",
device_id=device.id,
config_entry=mock_config_entry,
has_entity_name=True,
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
entity2 = entity_registry.async_get(entity.entity_id)
assert entity2 is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 148,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/alexa_devices/test_config_flow.py | """Tests for the Alexa Devices config flow."""
from unittest.mock import AsyncMock
from aioamazondevices.exceptions import (
CannotAuthenticate,
CannotConnect,
CannotRetrieveData,
)
import pytest
from homeassistant.components.alexa_devices.const import (
CONF_LOGIN_DATA,
CONF_SITE,
DOMAIN,
)
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_CODE, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import TEST_CODE, TEST_PASSWORD, TEST_USERNAME
from tests.common import MockConfigEntry
async def test_full_flow(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test 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"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: TEST_PASSWORD,
CONF_CODE: TEST_CODE,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == TEST_USERNAME
assert result["data"] == {
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: TEST_PASSWORD,
CONF_LOGIN_DATA: {
"customer_info": {"user_id": TEST_USERNAME},
CONF_SITE: "https://www.amazon.com",
},
}
assert result["result"].unique_id == TEST_USERNAME
mock_amazon_devices_client.login.login_mode_interactive.assert_called_once_with(
"023123"
)
@pytest.mark.parametrize(
("exception", "error"),
[
(CannotConnect, "cannot_connect"),
(CannotAuthenticate, "invalid_auth"),
(CannotRetrieveData, "cannot_retrieve_data"),
],
)
async def test_flow_errors(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_setup_entry: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test flow errors."""
mock_amazon_devices_client.login.login_mode_interactive.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: TEST_PASSWORD,
CONF_CODE: TEST_CODE,
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error}
mock_amazon_devices_client.login.login_mode_interactive.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: TEST_PASSWORD,
CONF_CODE: TEST_CODE,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_already_configured(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test duplicate flow."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: TEST_PASSWORD,
CONF_CODE: TEST_CODE,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reauth_successful(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test starting a reauthentication flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_PASSWORD: "other_fake_password",
CONF_CODE: "000000",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == {
CONF_CODE: "000000",
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: "other_fake_password",
CONF_LOGIN_DATA: {
"customer_info": {"user_id": TEST_USERNAME},
CONF_SITE: "https://www.amazon.com",
},
}
@pytest.mark.parametrize(
("side_effect", "error"),
[
(CannotConnect, "cannot_connect"),
(CannotAuthenticate, "invalid_auth"),
(CannotRetrieveData, "cannot_retrieve_data"),
],
)
async def test_reauth_not_successful(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
side_effect: Exception,
error: str,
) -> None:
"""Test starting a reauthentication flow but no connection found."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
mock_amazon_devices_client.login.login_mode_interactive.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_PASSWORD: "other_fake_password",
CONF_CODE: "000000",
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": error}
mock_amazon_devices_client.login.login_mode_interactive.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_PASSWORD: "fake_password",
CONF_CODE: "111111",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == {
CONF_CODE: "111111",
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: "fake_password",
CONF_LOGIN_DATA: {
"customer_info": {"user_id": TEST_USERNAME},
CONF_SITE: "https://www.amazon.com",
},
}
async def test_reconfigure_successful(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the entry can be reconfigured."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
# original entry
assert mock_config_entry.data[CONF_USERNAME] == TEST_USERNAME
new_password = "new_fake_password"
reconfigure_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_PASSWORD: new_password,
CONF_CODE: TEST_CODE,
},
)
assert reconfigure_result["type"] is FlowResultType.ABORT
assert reconfigure_result["reason"] == "reconfigure_successful"
# changed entry
assert mock_config_entry.data == {
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: new_password,
CONF_LOGIN_DATA: {
"customer_info": {"user_id": TEST_USERNAME},
CONF_SITE: "https://www.amazon.com",
},
}
@pytest.mark.parametrize(
("side_effect", "error"),
[
(CannotConnect, "cannot_connect"),
(CannotAuthenticate, "invalid_auth"),
(CannotRetrieveData, "cannot_retrieve_data"),
],
)
async def test_reconfigure_fails(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
side_effect: Exception,
error: str,
) -> None:
"""Test that the host can be reconfigured."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_amazon_devices_client.login.login_mode_interactive.side_effect = side_effect
reconfigure_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_PASSWORD: TEST_PASSWORD,
CONF_CODE: TEST_CODE,
},
)
assert reconfigure_result["type"] is FlowResultType.FORM
assert reconfigure_result["step_id"] == "reconfigure"
assert reconfigure_result["errors"] == {"base": error}
mock_amazon_devices_client.login.login_mode_interactive.side_effect = None
reconfigure_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_PASSWORD: TEST_PASSWORD,
CONF_CODE: TEST_CODE,
},
)
assert reconfigure_result["type"] is FlowResultType.ABORT
assert reconfigure_result["reason"] == "reconfigure_successful"
assert mock_config_entry.data == {
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: TEST_PASSWORD,
CONF_LOGIN_DATA: {
"customer_info": {"user_id": TEST_USERNAME},
CONF_SITE: "https://www.amazon.com",
},
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 282,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/alexa_devices/test_diagnostics.py | """Tests for Alexa Devices diagnostics platform."""
from __future__ import annotations
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.components.alexa_devices.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from . import setup_integration
from .const import TEST_DEVICE_1_SN
from tests.common import MockConfigEntry
from tests.components.diagnostics import (
get_diagnostics_for_config_entry,
get_diagnostics_for_device,
)
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
) -> None:
"""Test Amazon config entry diagnostics."""
await setup_integration(hass, mock_config_entry)
assert await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
) == snapshot(
exclude=props(
"entry_id",
"created_at",
"modified_at",
)
)
async def test_device_diagnostics(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test Amazon device diagnostics."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_DEVICE_1_SN)})
assert device, repr(device_registry.devices)
assert await get_diagnostics_for_device(
hass, hass_client, mock_config_entry, device
) == snapshot(
exclude=props(
"entry_id",
"created_at",
"modified_at",
)
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/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/alexa_devices/test_init.py | """Tests for the Alexa Devices integration."""
from unittest.mock import AsyncMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.alexa_devices.const import (
CONF_LOGIN_DATA,
CONF_SITE,
DOMAIN,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_COUNTRY, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from . import setup_integration
from .const import TEST_DEVICE_1_SN, TEST_PASSWORD, TEST_USERNAME
from tests.common import MockConfigEntry
async def test_device_info(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test device registry integration."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, TEST_DEVICE_1_SN)}
)
assert device_entry is not None
assert device_entry == snapshot
@pytest.mark.parametrize(
("minor_version", "extra_data"),
[
# Standard migration case
(
1,
{
CONF_COUNTRY: "US",
CONF_LOGIN_DATA: {
"session": "test-session",
},
},
),
# Edge case #1: no country, site already in login data, minor version 1
(
1,
{
CONF_LOGIN_DATA: {
"session": "test-session",
CONF_SITE: "https://www.amazon.com",
},
},
),
# Edge case #2: no country, site in data (wrong place), minor version 1
(
1,
{
CONF_SITE: "https://www.amazon.com",
CONF_LOGIN_DATA: {
"session": "test-session",
},
},
),
# Edge case #3: no country, site already in login data, minor version 2
(
2,
{
CONF_LOGIN_DATA: {
"session": "test-session",
CONF_SITE: "https://www.amazon.com",
},
},
),
# Edge case #4: no country, site in data (wrong place), minor version 2
(
2,
{
CONF_SITE: "https://www.amazon.com",
CONF_LOGIN_DATA: {
"session": "test-session",
},
},
),
],
)
async def test_migrate_entry(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
minor_version: int,
extra_data: dict[str, str],
) -> None:
"""Test successful migration of entry data."""
config_entry = MockConfigEntry(
domain=DOMAIN,
title="Amazon Test Account",
data={
CONF_USERNAME: TEST_USERNAME,
CONF_PASSWORD: TEST_PASSWORD,
**(extra_data),
},
unique_id=TEST_USERNAME,
version=1,
minor_version=minor_version,
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert config_entry.state is ConfigEntryState.LOADED
assert config_entry.minor_version == 3
assert config_entry.data[CONF_LOGIN_DATA][CONF_SITE] == "https://www.amazon.com"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/test_init.py",
"license": "Apache License 2.0",
"lines": 112,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/alexa_devices/test_notify.py | """Tests for the Alexa Devices notify platform."""
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.alexa_devices.coordinator import SCAN_INTERVAL
from homeassistant.components.notify import (
ATTR_MESSAGE,
DOMAIN as NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from . import setup_integration
from .const import TEST_DEVICE_1_SN
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.alexa_devices.PLATFORMS", [Platform.NOTIFY]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"mode",
["speak", "announce"],
)
async def test_notify_send_message(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mode: str,
) -> None:
"""Test notify send message."""
await setup_integration(hass, mock_config_entry)
entity_id = f"notify.echo_test_{mode}"
now = dt_util.parse_datetime("2021-01-09 12:00:00+00:00")
assert now
freezer.move_to(now)
await hass.services.async_call(
NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
{
ATTR_ENTITY_ID: entity_id,
ATTR_MESSAGE: "Test Message",
},
blocking=True,
)
assert (state := hass.states.get(entity_id))
assert state.state == now.isoformat()
async def test_offline_device(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test offline device handling."""
entity_id = "notify.echo_test_announce"
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].online = False
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].online = True
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state != STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/test_notify.py",
"license": "Apache License 2.0",
"lines": 80,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/alexa_devices/test_switch.py | """Tests for the Alexa Devices switch platform."""
from copy import deepcopy
from unittest.mock import AsyncMock, patch
from aioamazondevices.api import AmazonDeviceSensor
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.alexa_devices.coordinator import SCAN_INTERVAL
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from .conftest import TEST_DEVICE_1, TEST_DEVICE_1_SN
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
ENTITY_ID = "switch.echo_test_do_not_disturb"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.alexa_devices.PLATFORMS", [Platform.SWITCH]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_switch_dnd(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test switching DND."""
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(ENTITY_ID))
assert state.state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
assert mock_amazon_devices_client.set_do_not_disturb.call_count == 1
device_data = deepcopy(TEST_DEVICE_1)
device_data.sensors = {
"dnd": AmazonDeviceSensor(
name="dnd",
value=True,
error=False,
error_msg=None,
error_type=None,
scale=None,
),
"temperature": AmazonDeviceSensor(
name="temperature",
value="22.5",
error=False,
error_msg=None,
error_type=None,
scale="CELSIUS",
),
}
mock_amazon_devices_client.get_devices_data.return_value = {
TEST_DEVICE_1_SN: device_data
}
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(ENTITY_ID))
assert state.state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
device_data.sensors = {
"dnd": AmazonDeviceSensor(
name="dnd",
value=False,
error=False,
error_msg=None,
error_type=None,
scale=None,
),
"temperature": AmazonDeviceSensor(
name="temperature",
value="22.5",
error=False,
error_msg=None,
error_type=None,
scale="CELSIUS",
),
}
mock_amazon_devices_client.get_devices_data.return_value = {
TEST_DEVICE_1_SN: device_data
}
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_amazon_devices_client.set_do_not_disturb.call_count == 2
assert (state := hass.states.get(ENTITY_ID))
assert state.state == STATE_OFF
async def test_offline_device(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test offline device handling."""
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].online = False
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(ENTITY_ID))
assert state.state == STATE_UNAVAILABLE
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].online = True
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(ENTITY_ID))
assert state.state != STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/test_switch.py",
"license": "Apache License 2.0",
"lines": 136,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/backup/test_event.py | """The tests for the Backup event entity."""
from unittest.mock import AsyncMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.backup.const import DOMAIN
from homeassistant.components.backup.event import ATTR_BACKUP_STAGE, ATTR_FAILED_REASON
from homeassistant.components.event import ATTR_EVENT_TYPE
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .common import setup_backup_integration
from tests.common import snapshot_platform
from tests.typing import WebSocketGenerator
async def test_event_entity(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test automatic backup event entity."""
with patch("homeassistant.components.backup.PLATFORMS", [Platform.EVENT]):
await setup_backup_integration(hass, with_hassio=False)
await hass.async_block_till_done(wait_background_tasks=True)
entry = hass.config_entries.async_entries(DOMAIN)[0]
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
async def test_event_entity_backup_completed(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test completed automatic backup event."""
with patch("homeassistant.components.backup.PLATFORMS", [Platform.EVENT]):
await setup_backup_integration(hass, with_hassio=False)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("event.backup_automatic_backup")
assert state.attributes[ATTR_EVENT_TYPE] is None
client = await hass_ws_client(hass)
await hass.async_block_till_done()
await client.send_json_auto_id(
{"type": "backup/generate", "agent_ids": ["backup.local"]}
)
assert await client.receive_json()
state = hass.states.get("event.backup_automatic_backup")
assert state.attributes[ATTR_EVENT_TYPE] == "in_progress"
assert state.attributes[ATTR_BACKUP_STAGE] is not None
assert state.attributes[ATTR_FAILED_REASON] is None
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("event.backup_automatic_backup")
assert state.attributes[ATTR_EVENT_TYPE] == "completed"
assert state.attributes[ATTR_BACKUP_STAGE] is None
assert state.attributes[ATTR_FAILED_REASON] is None
async def test_event_entity_backup_failed(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
create_backup: AsyncMock,
) -> None:
"""Test failed automatic backup event."""
with patch("homeassistant.components.backup.PLATFORMS", [Platform.EVENT]):
await setup_backup_integration(hass, with_hassio=False)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("event.backup_automatic_backup")
assert state.attributes[ATTR_EVENT_TYPE] is None
create_backup.side_effect = Exception("Boom!")
client = await hass_ws_client(hass)
await hass.async_block_till_done()
await client.send_json_auto_id(
{"type": "backup/generate", "agent_ids": ["backup.local"]}
)
assert await client.receive_json()
state = hass.states.get("event.backup_automatic_backup")
assert state.attributes[ATTR_EVENT_TYPE] == "failed"
assert state.attributes[ATTR_BACKUP_STAGE] is None
assert state.attributes[ATTR_FAILED_REASON] == "unknown_error"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/backup/test_event.py",
"license": "Apache License 2.0",
"lines": 71,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/blue_current/test_button.py | """The tests for Blue Current buttons."""
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, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import init_integration
from tests.common import MockConfigEntry, snapshot_platform
charge_point_buttons = ["stop_charge_session", "reset", "reboot"]
async def test_buttons_created(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test if all buttons are created."""
await init_integration(hass, config_entry, Platform.BUTTON)
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.freeze_time("2023-01-13 12:00:00+00:00")
async def test_charge_point_buttons(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test the underlying charge point buttons."""
await init_integration(hass, config_entry, Platform.BUTTON)
for button in charge_point_buttons:
state = hass.states.get(f"button.101_{button}")
assert state is not None
assert state.state == STATE_UNKNOWN
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: f"button.101_{button}"},
blocking=True,
)
state = hass.states.get(f"button.101_{button}")
assert state
assert state.state == "2023-01-13T12:00:00+00:00"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/blue_current/test_button.py",
"license": "Apache License 2.0",
"lines": 38,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/bluesound/test_button.py | """Test for bluesound buttons."""
from unittest.mock import call
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 .conftest import PlayerMocks
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_set_sleep_timer(
hass: HomeAssistant,
player_mocks: PlayerMocks,
setup_config_entry: None,
) -> None:
"""Test the media player volume set."""
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.player_name1111_set_sleep_timer"},
blocking=True,
)
player_mocks.player_data.player.sleep_timer.assert_called_once()
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_clear_sleep_timer(
hass: HomeAssistant,
player_mocks: PlayerMocks,
setup_config_entry: None,
) -> None:
"""Test the media player volume set."""
player_mocks.player_data.player.sleep_timer.side_effect = [15, 30, 45, 60, 90, 0]
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.player_name1111_clear_sleep_timer"},
blocking=True,
)
player_mocks.player_data.player.sleep_timer.assert_has_calls([call()] * 6)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/bluesound/test_button.py",
"license": "Apache License 2.0",
"lines": 36,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/bosch_alarm/test_binary_sensor.py | """Tests for Bosch Alarm component."""
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
from bosch_alarm_mode2.const import ALARM_PANEL_FAULTS
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import STATE_OFF, STATE_ON, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import call_observable, setup_integration
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.bosch_alarm.PLATFORMS", [Platform.BINARY_SENSOR]
):
yield
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_binary_sensor(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_panel: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the binary sensor state."""
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize("model", ["b5512"])
async def test_panel_faults(
hass: HomeAssistant,
mock_panel: AsyncMock,
area: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that fault sensor state changes after inducing a fault."""
await setup_integration(hass, mock_config_entry)
entity_id = "binary_sensor.bosch_b5512_us1b_battery"
assert hass.states.get(entity_id).state == STATE_OFF
mock_panel.panel_faults_ids = [ALARM_PANEL_FAULTS.BATTERY_LOW]
await call_observable(hass, mock_panel.faults_observer)
assert hass.states.get(entity_id).state == STATE_ON
@pytest.mark.parametrize("model", ["b5512"])
async def test_area_ready_to_arm(
hass: HomeAssistant,
mock_panel: AsyncMock,
area: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that fault sensor state changes after inducing a fault."""
await setup_integration(hass, mock_config_entry)
entity_id = "binary_sensor.area1_area_ready_to_arm_away"
entity_id_2 = "binary_sensor.area1_area_ready_to_arm_home"
assert hass.states.get(entity_id).state == STATE_ON
assert hass.states.get(entity_id_2).state == STATE_ON
area.all_ready = False
await call_observable(hass, area.status_observer)
assert hass.states.get(entity_id).state == STATE_OFF
assert hass.states.get(entity_id_2).state == STATE_ON
area.part_ready = False
await call_observable(hass, area.status_observer)
assert hass.states.get(entity_id).state == STATE_OFF
assert hass.states.get(entity_id_2).state == STATE_OFF
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/bosch_alarm/test_binary_sensor.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/bosch_alarm/test_services.py | """Tests for Bosch Alarm component."""
import asyncio
from collections.abc import AsyncGenerator
import datetime as dt
from unittest.mock import AsyncMock, patch
import pytest
import voluptuous as vol
from homeassistant.components.bosch_alarm.const import (
ATTR_DATETIME,
DOMAIN,
SERVICE_SET_DATE_TIME,
)
from homeassistant.const import ATTR_CONFIG_ENTRY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from . import setup_integration
from tests.common import MockConfigEntry
@pytest.fixture(autouse=True)
async def platforms() -> AsyncGenerator[None]:
"""Return the platforms to be loaded for this test."""
with patch("homeassistant.components.bosch_alarm.PLATFORMS", []):
yield
async def test_set_date_time_service(
hass: HomeAssistant,
mock_panel: AsyncMock,
area: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the service calls succeed if the service call is valid."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
DOMAIN,
SERVICE_SET_DATE_TIME,
{
ATTR_CONFIG_ENTRY_ID: mock_config_entry.entry_id,
ATTR_DATETIME: dt_util.now(),
},
blocking=True,
)
mock_panel.set_panel_date.assert_called_once()
async def test_set_date_time_service_fails_bad_entity(
hass: HomeAssistant,
mock_panel: AsyncMock,
area: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the service calls fail if the service call is done for an incorrect entity."""
await setup_integration(hass, mock_config_entry)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_SET_DATE_TIME,
{
ATTR_CONFIG_ENTRY_ID: "bad-config_id",
ATTR_DATETIME: dt_util.now(),
},
blocking=True,
)
assert err.value.translation_key == "service_config_entry_not_found"
assert err.value.translation_placeholders["entry_id"] == "bad-config_id"
async def test_set_date_time_service_fails_bad_params(
hass: HomeAssistant,
mock_panel: AsyncMock,
area: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the service calls fail if the service call is done with incorrect params."""
await setup_integration(hass, mock_config_entry)
with pytest.raises(
vol.MultipleInvalid,
match=r"Invalid datetime specified: for dictionary value @ data\['datetime'\]",
):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_DATE_TIME,
{
ATTR_CONFIG_ENTRY_ID: mock_config_entry.entry_id,
ATTR_DATETIME: "",
},
blocking=True,
)
async def test_set_date_time_service_fails_bad_year_before(
hass: HomeAssistant,
mock_panel: AsyncMock,
area: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the service calls fail if the panel fails the service call."""
await setup_integration(hass, mock_config_entry)
with pytest.raises(
vol.MultipleInvalid,
match=r"datetime must be before 2038 for dictionary value @ data\['datetime'\]",
):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_DATE_TIME,
{
ATTR_CONFIG_ENTRY_ID: mock_config_entry.entry_id,
ATTR_DATETIME: dt.datetime(2038, 1, 1),
},
blocking=True,
)
async def test_set_date_time_service_fails_bad_year_after(
hass: HomeAssistant,
mock_panel: AsyncMock,
area: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the service calls fail if the panel fails the service call."""
await setup_integration(hass, mock_config_entry)
mock_panel.set_panel_date.side_effect = ValueError()
with pytest.raises(
vol.MultipleInvalid,
match=r"datetime must be after 2009 for dictionary value @ data\['datetime'\]",
):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_DATE_TIME,
{
ATTR_CONFIG_ENTRY_ID: mock_config_entry.entry_id,
ATTR_DATETIME: dt.datetime(2009, 1, 1),
},
blocking=True,
)
async def test_set_date_time_service_fails_connection_error(
hass: HomeAssistant,
mock_panel: AsyncMock,
area: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the service calls fail if the panel fails the service call."""
await setup_integration(hass, mock_config_entry)
mock_panel.set_panel_date.side_effect = asyncio.InvalidStateError()
with pytest.raises(
HomeAssistantError,
match=f'Could not connect to "{mock_config_entry.title}"',
):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_DATE_TIME,
{
ATTR_CONFIG_ENTRY_ID: mock_config_entry.entry_id,
ATTR_DATETIME: dt_util.now(),
},
blocking=True,
)
async def test_set_date_time_service_fails_unloaded(
hass: HomeAssistant,
mock_panel: AsyncMock,
area: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that the service calls fail if the config entry is unloaded."""
await async_setup_component(hass, DOMAIN, {})
mock_config_entry.add_to_hass(hass)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_SET_DATE_TIME,
{
ATTR_CONFIG_ENTRY_ID: mock_config_entry.entry_id,
ATTR_DATETIME: dt_util.now(),
},
blocking=True,
)
assert err.value.translation_key == "service_config_entry_not_loaded"
assert err.value.translation_placeholders["entry_title"] == "Mock Title"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/bosch_alarm/test_services.py",
"license": "Apache License 2.0",
"lines": 169,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/bosch_alarm/test_switch.py | """Tests for Bosch Alarm component."""
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import call_observable, setup_integration
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.bosch_alarm.PLATFORMS", [Platform.SWITCH]):
yield
async def test_update_switch_device(
hass: HomeAssistant,
mock_panel: AsyncMock,
output: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that output state changes after turning on the output."""
await setup_integration(hass, mock_config_entry)
entity_id = "switch.output_a"
assert hass.states.get(entity_id).state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
output.is_active.return_value = True
await call_observable(hass, output.status_observer)
assert hass.states.get(entity_id).state == STATE_ON
async def test_unlock_door(
hass: HomeAssistant,
mock_panel: AsyncMock,
door: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that door state changes after unlocking the door."""
await setup_integration(hass, mock_config_entry)
entity_id = "switch.main_door_locked"
assert hass.states.get(entity_id).state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
door.is_locked.return_value = False
door.is_open.return_value = True
await call_observable(hass, door.status_observer)
assert hass.states.get(entity_id).state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
door.is_locked.return_value = True
door.is_open.return_value = False
await call_observable(hass, door.status_observer)
assert hass.states.get(entity_id).state == STATE_ON
async def test_secure_door(
hass: HomeAssistant,
mock_panel: AsyncMock,
door: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that door state changes after unlocking the door."""
await setup_integration(hass, mock_config_entry)
entity_id = "switch.main_door_secured"
assert hass.states.get(entity_id).state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
door.is_secured.return_value = True
await call_observable(hass, door.status_observer)
assert hass.states.get(entity_id).state == STATE_ON
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
door.is_secured.return_value = False
await call_observable(hass, door.status_observer)
assert hass.states.get(entity_id).state == STATE_OFF
async def test_cycle_door(
hass: HomeAssistant,
mock_panel: AsyncMock,
door: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that door state changes after unlocking the door."""
await setup_integration(hass, mock_config_entry)
entity_id = "switch.main_door_momentarily_unlocked"
assert hass.states.get(entity_id).state == STATE_OFF
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
door.is_cycling.return_value = True
await call_observable(hass, door.status_observer)
assert hass.states.get(entity_id).state == STATE_ON
async def test_switch(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_panel: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the switch state."""
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/bosch_alarm/test_switch.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/comelit/test_utils.py | """Tests for Comelit SimpleHome utils."""
from unittest.mock import AsyncMock
from aiocomelit.api import ComelitSerialBridgeObject
from aiocomelit.const import CLIMATE, WATT
from aiocomelit.exceptions import CannotAuthenticate, CannotConnect, CannotRetrieveData
import pytest
from homeassistant.components.climate import HVACMode
from homeassistant.components.comelit.const import DOMAIN
from homeassistant.components.humidifier import ATTR_HUMIDITY
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SERVICE_TURN_ON
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from . import setup_integration
from tests.common import MockConfigEntry
ENTITY_ID_0 = "switch.switch0"
ENTITY_ID_1 = "climate.climate0"
ENTITY_ID_2 = "humidifier.climate0_dehumidifier"
ENTITY_ID_3 = "humidifier.climate0_humidifier"
async def test_device_remove_stale(
hass: HomeAssistant,
mock_serial_bridge: AsyncMock,
mock_serial_bridge_config_entry: MockConfigEntry,
) -> None:
"""Test removal of stale devices with no entities."""
await setup_integration(hass, mock_serial_bridge_config_entry)
assert (state := hass.states.get(ENTITY_ID_1))
assert state.state == HVACMode.HEAT
assert state.attributes[ATTR_TEMPERATURE] == 5.0
assert (state := hass.states.get(ENTITY_ID_2))
assert state.state == STATE_OFF
assert state.attributes[ATTR_HUMIDITY] == 50.0
assert (state := hass.states.get(ENTITY_ID_3))
assert state.state == STATE_ON
assert state.attributes[ATTR_HUMIDITY] == 50.0
mock_serial_bridge.get_all_devices.return_value[CLIMATE] = {
0: ComelitSerialBridgeObject(
index=0,
name="Climate0",
status=0,
human_status="off",
type="climate",
val=[
[0, 0, "O", "A", 0, 0, 0, "N"],
[0, 0, "O", "A", 0, 0, 0, "N"],
[0, 0],
],
protected=0,
zone="Living room",
power=0.0,
power_unit=WATT,
),
}
await hass.config_entries.async_reload(mock_serial_bridge_config_entry.entry_id)
await hass.async_block_till_done()
assert (state := hass.states.get(ENTITY_ID_1)) is None
assert (state := hass.states.get(ENTITY_ID_2)) is None
assert (state := hass.states.get(ENTITY_ID_3)) is None
@pytest.mark.parametrize(
("side_effect", "key", "error"),
[
(CannotConnect, "cannot_connect", "CannotConnect()"),
(CannotRetrieveData, "cannot_retrieve_data", "CannotRetrieveData()"),
],
)
async def test_bridge_api_call_exceptions(
hass: HomeAssistant,
mock_serial_bridge: AsyncMock,
mock_serial_bridge_config_entry: MockConfigEntry,
side_effect: Exception,
key: str,
error: str,
) -> None:
"""Test bridge_api_call decorator for exceptions."""
await setup_integration(hass, mock_serial_bridge_config_entry)
assert (state := hass.states.get(ENTITY_ID_0))
assert state.state == STATE_OFF
mock_serial_bridge.set_device_status.side_effect = side_effect
# Call API
with pytest.raises(HomeAssistantError) as exc_info:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_ID_0},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == key
assert exc_info.value.translation_placeholders == {"error": error}
async def test_bridge_api_call_reauth(
hass: HomeAssistant,
mock_serial_bridge: AsyncMock,
mock_serial_bridge_config_entry: MockConfigEntry,
) -> None:
"""Test bridge_api_call decorator for reauth."""
await setup_integration(hass, mock_serial_bridge_config_entry)
assert (state := hass.states.get(ENTITY_ID_0))
assert state.state == STATE_OFF
mock_serial_bridge.set_device_status.side_effect = CannotAuthenticate
# Call API
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_ID_0},
blocking=True,
)
assert mock_serial_bridge_config_entry.state is ConfigEntryState.LOADED
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
flow = flows[0]
assert flow.get("step_id") == "reauth_confirm"
assert flow.get("handler") == DOMAIN
assert "context" in flow
assert flow["context"].get("source") == SOURCE_REAUTH
assert flow["context"].get("entry_id") == mock_serial_bridge_config_entry.entry_id
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/comelit/test_utils.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/eheimdigital/test_diagnostics.py | """Tests for the diagnostics module."""
from unittest.mock import MagicMock
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.core import HomeAssistant
from .conftest import init_integration
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,
snapshot: SnapshotAssertion,
eheimdigital_hub_mock: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test config entry diagnostics."""
await init_integration(hass, mock_config_entry)
for device in eheimdigital_hub_mock.return_value.devices.values():
await eheimdigital_hub_mock.call_args.kwargs["device_found_callback"](
device.mac_address, device.device_type
)
mock_config_entry.runtime_data.data = eheimdigital_hub_mock.return_value.devices
result = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
assert result == snapshot(exclude=props("created_at", "modified_at", "entry_id"))
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/eheimdigital/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 27,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/eheimdigital/test_select.py | """Tests for the select module."""
from unittest.mock import AsyncMock, MagicMock, patch
from eheimdigital.types import FilterMode, FilterModeProf
import pytest
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 .conftest import init_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_setup(
hass: HomeAssistant,
eheimdigital_hub_mock: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test select platform setup."""
mock_config_entry.add_to_hass(hass)
with (
patch("homeassistant.components.eheimdigital.PLATFORMS", [Platform.SELECT]),
patch(
"homeassistant.components.eheimdigital.coordinator.asyncio.Event",
new=AsyncMock,
),
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
for device in eheimdigital_hub_mock.return_value.devices:
await eheimdigital_hub_mock.call_args.kwargs["device_found_callback"](
device, eheimdigital_hub_mock.return_value.devices[device].device_type
)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("device_name", "entity_list"),
[
(
"classic_vario_mock",
[
(
"select.mock_classicvario_filter_mode",
"manual",
"pumpMode",
int(FilterMode.MANUAL),
),
],
),
(
"filter_mock",
[
(
"select.mock_filter_filter_mode",
"constant_flow",
"title",
"START_FILTER_NORMAL_MODE_WITH_COMP",
),
(
"select.mock_filter_manual_speed",
"61.5",
"frequency",
int(61.5 * 100),
),
("select.mock_filter_constant_flow_speed", "440", "flow_rate", 1),
("select.mock_filter_day_speed", "480", "dfs_soll_day", 2),
("select.mock_filter_night_speed", "860", "dfs_soll_night", 14),
("select.mock_filter_high_pulse_speed", "620", "dfs_soll_high", 6),
("select.mock_filter_low_pulse_speed", "770", "dfs_soll_low", 11),
],
),
],
)
async def test_set_value(
hass: HomeAssistant,
eheimdigital_hub_mock: MagicMock,
mock_config_entry: MockConfigEntry,
device_name: str,
entity_list: list[tuple[str, str, str, int]],
request: pytest.FixtureRequest,
) -> None:
"""Test setting a value."""
device: MagicMock = request.getfixturevalue(device_name)
await init_integration(hass, mock_config_entry)
await eheimdigital_hub_mock.call_args.kwargs["device_found_callback"](
device.mac_address, device.device_type
)
await hass.async_block_till_done()
for item in entity_list:
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: item[0], ATTR_OPTION: item[1]},
blocking=True,
)
calls = [call for call in device.hub.mock_calls if call[0] == "send_packet"]
assert calls[-1][1][0][item[2]] == item[3]
@pytest.mark.usefixtures("classic_vario_mock", "heater_mock")
@pytest.mark.parametrize(
("device_name", "entity_list"),
[
(
"classic_vario_mock",
[
(
"select.mock_classicvario_filter_mode",
"classic_vario_data",
"pumpMode",
int(FilterMode.BIO),
"bio",
),
],
),
(
"filter_mock",
[
(
"select.mock_filter_filter_mode",
"filter_data",
"pumpMode",
int(FilterModeProf.CONSTANT_FLOW),
"constant_flow",
),
(
"select.mock_filter_manual_speed",
"filter_data",
"freqSoll",
int(61.5 * 100),
"61.5",
),
(
"select.mock_filter_constant_flow_speed",
"filter_data",
"sollStep",
1,
"440",
),
(
"select.mock_filter_day_speed",
"filter_data",
"nm_dfs_soll_day",
2,
"480",
),
(
"select.mock_filter_night_speed",
"filter_data",
"nm_dfs_soll_night",
14,
"860",
),
(
"select.mock_filter_high_pulse_speed",
"filter_data",
"pm_dfs_soll_high",
6,
"620",
),
(
"select.mock_filter_low_pulse_speed",
"filter_data",
"pm_dfs_soll_low",
11,
"770",
),
],
),
],
)
async def test_state_update(
hass: HomeAssistant,
eheimdigital_hub_mock: MagicMock,
mock_config_entry: MockConfigEntry,
device_name: str,
entity_list: list[tuple[str, str, str, int, str]],
request: pytest.FixtureRequest,
) -> None:
"""Test state updates."""
device: MagicMock = request.getfixturevalue(device_name)
await init_integration(hass, mock_config_entry)
await eheimdigital_hub_mock.call_args.kwargs["device_found_callback"](
device.mac_address, device.device_type
)
await hass.async_block_till_done()
for item in entity_list:
getattr(device, item[1])[item[2]] = item[3]
await eheimdigital_hub_mock.call_args.kwargs["receive_callback"]()
assert (state := hass.states.get(item[0]))
assert state.state == item[4]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/eheimdigital/test_select.py",
"license": "Apache License 2.0",
"lines": 192,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_travel_time/test_helpers.py | """Tests for google_travel_time.helpers."""
from google.maps.routing_v2 import Location, Waypoint
from google.type import latlng_pb2
import pytest
from homeassistant.components.google_travel_time import helpers
from homeassistant.core import HomeAssistant
@pytest.mark.parametrize(
("location", "expected_result"),
[
(
"12.34,56.78",
Waypoint(
location=Location(
lat_lng=latlng_pb2.LatLng(
latitude=12.34,
longitude=56.78,
)
)
),
),
(
"12.34, 56.78",
Waypoint(
location=Location(
lat_lng=latlng_pb2.LatLng(
latitude=12.34,
longitude=56.78,
)
)
),
),
("Some Address", Waypoint(address="Some Address")),
("Some Street 1, 12345 City", Waypoint(address="Some Street 1, 12345 City")),
],
)
def test_convert_to_waypoint_coordinates(
hass: HomeAssistant, location: str, expected_result: Waypoint
) -> None:
"""Test convert_to_waypoint returns correct Waypoint for coordinates or address."""
waypoint = helpers.convert_to_waypoint(hass, location)
assert waypoint == expected_result
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_travel_time/test_helpers.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/homee/test_alarm_control_panel.py | """Test Homee alarm control panels."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.alarm_control_panel import (
DOMAIN as ALARM_CONTROL_PANEL_DOMAIN,
SERVICE_ALARM_ARM_AWAY,
SERVICE_ALARM_ARM_HOME,
SERVICE_ALARM_ARM_NIGHT,
SERVICE_ALARM_ARM_VACATION,
SERVICE_ALARM_DISARM,
)
from homeassistant.components.homee.const import DOMAIN
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 . import build_mock_node, setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def setup_alarm_control_panel(
hass: HomeAssistant, mock_homee: MagicMock, mock_config_entry: MockConfigEntry
) -> None:
"""Setups the integration for select tests."""
mock_homee.nodes = [build_mock_node("homee.json")]
mock_homee.get_node_by_id.return_value = mock_homee.nodes[0]
await setup_integration(hass, mock_config_entry)
@pytest.mark.parametrize(
("service", "state"),
[
(SERVICE_ALARM_ARM_HOME, 0),
(SERVICE_ALARM_ARM_NIGHT, 1),
(SERVICE_ALARM_ARM_AWAY, 2),
(SERVICE_ALARM_ARM_VACATION, 3),
],
)
async def test_alarm_control_panel_services(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
service: str,
state: int,
) -> None:
"""Test alarm control panel services."""
await setup_alarm_control_panel(hass, mock_homee, mock_config_entry)
await hass.services.async_call(
ALARM_CONTROL_PANEL_DOMAIN,
service,
{ATTR_ENTITY_ID: "alarm_control_panel.testhomee_status"},
blocking=True,
)
mock_homee.set_value.assert_called_once_with(-1, 1, state)
async def test_alarm_control_panel_service_disarm_error(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that disarm service calls no action."""
await setup_alarm_control_panel(hass, mock_homee, mock_config_entry)
with pytest.raises(ServiceValidationError) as exc_info:
await hass.services.async_call(
ALARM_CONTROL_PANEL_DOMAIN,
SERVICE_ALARM_DISARM,
{ATTR_ENTITY_ID: "alarm_control_panel.testhomee_status"},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == "disarm_not_supported"
async def test_alarm_control_panel_snapshot(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the alarm-control_panel snapshots."""
with patch(
"homeassistant.components.homee.PLATFORMS", [Platform.ALARM_CONTROL_PANEL]
):
await setup_alarm_control_panel(hass, mock_homee, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homee/test_alarm_control_panel.py",
"license": "Apache License 2.0",
"lines": 80,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homee/test_event.py | """Test homee events."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.event import ATTR_EVENT_TYPE
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import build_mock_node, setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.parametrize(
("entity_id", "attribute_id", "expected_event_types"),
[
(
"event.remote_control_up_down_remote",
1,
[
"released",
"up",
"down",
"stop",
"up_long",
"down_long",
"stop_long",
"c_button",
"b_button",
"a_button",
],
),
(
"event.remote_control_switch_2",
3,
["upper", "lower", "released"],
),
],
)
async def test_event_triggers(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
attribute_id: int,
expected_event_types: list[str],
) -> None:
"""Test that the correct event fires when the attribute changes."""
mock_homee.nodes = [build_mock_node("events.json")]
mock_homee.get_node_by_id.return_value = mock_homee.nodes[0]
await setup_integration(hass, mock_config_entry)
# Simulate the event triggers.
attribute = mock_homee.nodes[0].attributes[attribute_id - 1]
for i, event_type in enumerate(expected_event_types):
attribute.current_value = i
attribute.add_on_changed_listener.call_args_list[1][0][0](attribute)
await hass.async_block_till_done()
# Check if the event was fired
state = hass.states.get(entity_id)
assert state.attributes[ATTR_EVENT_TYPE] == event_type
@pytest.mark.parametrize(
("profile"),
[
(20),
(24),
(25),
(26),
(41),
],
)
async def test_event_snapshot(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
profile: int,
) -> None:
"""Test the event entity snapshot."""
with patch("homeassistant.components.homee.PLATFORMS", [Platform.EVENT]):
mock_homee.nodes = [build_mock_node("events.json")]
mock_homee.nodes[0].profile = profile
mock_homee.get_node_by_id.return_value = mock_homee.nodes[0]
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/homee/test_event.py",
"license": "Apache License 2.0",
"lines": 82,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homee/test_fan.py | """Test Homee fans."""
from unittest.mock import MagicMock, call, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.fan import (
ATTR_PERCENTAGE,
ATTR_PRESET_MODE,
DOMAIN as FAN_DOMAIN,
SERVICE_DECREASE_SPEED,
SERVICE_INCREASE_SPEED,
SERVICE_SET_PERCENTAGE,
SERVICE_SET_PRESET_MODE,
SERVICE_TOGGLE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.components.homee.const import (
DOMAIN,
PRESET_AUTO,
PRESET_MANUAL,
PRESET_SUMMER,
)
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 . import build_mock_node, setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.parametrize(
("speed", "expected"),
[
(0, 0),
(1, 12),
(2, 25),
(3, 37),
(4, 50),
(5, 62),
(6, 75),
(7, 87),
(8, 100),
],
)
async def test_percentage(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_homee: MagicMock,
speed: int,
expected: int,
) -> None:
"""Test percentage."""
mock_homee.nodes = [build_mock_node("fan.json")]
mock_homee.nodes[0].attributes[0].current_value = speed
await setup_integration(hass, mock_config_entry)
assert hass.states.get("fan.test_fan").attributes["percentage"] == expected
@pytest.mark.parametrize(
("mode_value", "expected"),
[
(0, "manual"),
(1, "auto"),
(2, "summer"),
],
)
async def test_preset_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_homee: MagicMock,
mode_value: int,
expected: str,
) -> None:
"""Test preset mode."""
mock_homee.nodes = [build_mock_node("fan.json")]
mock_homee.nodes[0].attributes[1].current_value = mode_value
await setup_integration(hass, mock_config_entry)
assert hass.states.get("fan.test_fan").attributes["preset_mode"] == expected
@pytest.mark.parametrize(
("service", "options", "expected"),
[
(SERVICE_TURN_ON, {ATTR_PERCENTAGE: 100}, (77, 1, 8)),
(SERVICE_TURN_ON, {ATTR_PERCENTAGE: 86}, (77, 1, 7)),
(SERVICE_TURN_ON, {ATTR_PERCENTAGE: 63}, (77, 1, 6)),
(SERVICE_TURN_ON, {ATTR_PERCENTAGE: 60}, (77, 1, 5)),
(SERVICE_TURN_ON, {ATTR_PERCENTAGE: 50}, (77, 1, 4)),
(SERVICE_TURN_ON, {ATTR_PERCENTAGE: 34}, (77, 1, 3)),
(SERVICE_TURN_ON, {ATTR_PERCENTAGE: 17}, (77, 1, 2)),
(SERVICE_TURN_ON, {ATTR_PERCENTAGE: 8}, (77, 1, 1)),
(SERVICE_TURN_ON, {}, (77, 1, 6)),
(SERVICE_TURN_OFF, {}, (77, 1, 0)),
(SERVICE_INCREASE_SPEED, {}, (77, 1, 4)),
(SERVICE_DECREASE_SPEED, {}, (77, 1, 2)),
(SERVICE_SET_PERCENTAGE, {ATTR_PERCENTAGE: 42}, (77, 1, 4)),
(SERVICE_SET_PRESET_MODE, {ATTR_PRESET_MODE: PRESET_MANUAL}, (77, 2, 0)),
(SERVICE_SET_PRESET_MODE, {ATTR_PRESET_MODE: PRESET_AUTO}, (77, 2, 1)),
(SERVICE_SET_PRESET_MODE, {ATTR_PRESET_MODE: PRESET_SUMMER}, (77, 2, 2)),
(SERVICE_TOGGLE, {}, (77, 1, 0)),
],
)
async def test_fan_services(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_homee: MagicMock,
service: str,
options: int | None,
expected: tuple[int, int, int],
) -> None:
"""Test fan services."""
mock_homee.nodes = [build_mock_node("fan.json")]
await setup_integration(hass, mock_config_entry)
OPTIONS = {ATTR_ENTITY_ID: "fan.test_fan"}
OPTIONS.update(options)
await hass.services.async_call(
FAN_DOMAIN,
service,
OPTIONS,
blocking=True,
)
mock_homee.set_value.assert_called_once_with(*expected)
async def test_turn_on_preset_last_value_zero(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_homee: MagicMock,
) -> None:
"""Test turn on with preset last value == 0."""
mock_homee.nodes = [build_mock_node("fan.json")]
mock_homee.nodes[0].attributes[0].last_value = 0
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "fan.test_fan", ATTR_PRESET_MODE: PRESET_MANUAL},
blocking=True,
)
assert mock_homee.set_value.call_args_list == [
call(77, 2, 0),
call(77, 1, 8),
]
async def test_turn_on_invalid_preset(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_homee: MagicMock,
) -> None:
"""Test turn on with invalid preset."""
mock_homee.nodes = [build_mock_node("fan.json")]
await setup_integration(hass, mock_config_entry)
with pytest.raises(ServiceValidationError) as exc_info:
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "fan.test_fan", ATTR_PRESET_MODE: PRESET_AUTO},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == "invalid_preset_mode"
async def test_fan_snapshot(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the fan snapshot."""
mock_homee.nodes = [build_mock_node("fan.json")]
mock_homee.get_node_by_id.return_value = mock_homee.nodes[0]
with patch("homeassistant.components.homee.PLATFORMS", [Platform.FAN]):
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/homee/test_fan.py",
"license": "Apache License 2.0",
"lines": 165,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/immich/const.py | """Constants for the Immich integration tests."""
from aioimmich.albums.models import ImmichAlbum
from aioimmich.assets.models import ImmichAsset
from homeassistant.const import (
CONF_API_KEY,
CONF_HOST,
CONF_PORT,
CONF_SSL,
CONF_URL,
CONF_VERIFY_SSL,
)
MOCK_USER_DATA = {
CONF_URL: "http://localhost",
CONF_API_KEY: "abcdef0123456789",
CONF_VERIFY_SSL: False,
}
MOCK_CONFIG_ENTRY_DATA = {
CONF_HOST: "localhost",
CONF_API_KEY: "abcdef0123456789",
CONF_PORT: 80,
CONF_SSL: False,
CONF_VERIFY_SSL: False,
}
ALBUM_DATA = {
"id": "721e1a4b-aa12-441e-8d3b-5ac7ab283bb6",
"albumName": "My Album",
"albumThumbnailAssetId": "0d03a7ad-ddc7-45a6-adee-68d322a6d2f5",
"albumUsers": [],
"assetCount": 1,
"assets": [],
"createdAt": "2025-05-11T10:13:22.799Z",
"hasSharedLink": False,
"isActivityEnabled": False,
"ownerId": "e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"owner": {
"id": "e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"email": "admin@immich.local",
"name": "admin",
"profileImagePath": "",
"avatarColor": "primary",
"profileChangedAt": "2025-05-11T10:07:46.866Z",
},
"shared": False,
"updatedAt": "2025-05-17T11:26:03.696Z",
}
MOCK_ALBUM_WITHOUT_ASSETS = ImmichAlbum.from_dict(ALBUM_DATA)
MOCK_ALBUM_WITH_ASSETS = ImmichAlbum.from_dict(
{
**ALBUM_DATA,
"assets": [
{
"id": "2e94c203-50aa-4ad2-8e29-56dd74e0eff4",
"deviceAssetId": "web-filename.jpg-1675185639000",
"ownerId": "e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"deviceId": "WEB",
"libraryId": None,
"type": "IMAGE",
"originalPath": "upload/upload/e7ef5713-9dab-4bd4-b899-715b0ca4379e/b4/b8/b4b8ef00-8a6d-4056-91ff-7f86dc66e427.jpg",
"originalFileName": "filename.jpg",
"originalMimeType": "image/jpeg",
"thumbhash": "1igGFALX8mVGdHc5aChJf5nxNg==",
"fileCreatedAt": "2023-01-31T17:20:37.085+00:00",
"fileModifiedAt": "2023-01-31T17:20:39+00:00",
"localDateTime": "2023-01-31T18:20:37.085+00:00",
"updatedAt": "2025-05-11T10:13:49.590401+00:00",
"isFavorite": False,
"isArchived": False,
"isTrashed": False,
"duration": "0:00:00.00000",
"exifInfo": {},
"livePhotoVideoId": None,
"people": [],
"checksum": "HJm7TVOP80S+eiYZnAhWyRaB/Yc=",
"isOffline": False,
"hasMetadata": True,
"duplicateId": None,
"resized": True,
},
{
"id": "2e65a5f2-db83-44c4-81ab-f5ff20c9bd7b",
"deviceAssetId": "web-filename.mp4-1675185639000",
"ownerId": "e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"deviceId": "WEB",
"libraryId": None,
"type": "IMAGE",
"originalPath": "upload/upload/e7ef5713-9dab-4bd4-b899-715b0ca4379e/b4/b8/b4b8ef00-8a6d-4056-eeff-7f86dc66e427.mp4",
"originalFileName": "filename.mp4",
"originalMimeType": "video/mp4",
"thumbhash": "1igGFALX8mVGdHc5aChJf5nxNg==",
"fileCreatedAt": "2023-01-31T17:20:37.085+00:00",
"fileModifiedAt": "2023-01-31T17:20:39+00:00",
"localDateTime": "2023-01-31T18:20:37.085+00:00",
"updatedAt": "2025-05-11T10:13:49.590401+00:00",
"isFavorite": False,
"isArchived": False,
"isTrashed": False,
"duration": "0:00:00.00000",
"exifInfo": {},
"livePhotoVideoId": None,
"people": [],
"checksum": "HJm7TVOP80S+eiYZnAhWyRaB/Yc=",
"isOffline": False,
"hasMetadata": True,
"duplicateId": None,
"resized": True,
},
],
}
)
MOCK_PEOPLE_ASSETS = [
ImmichAsset.from_dict(
{
"id": "2242eda3-94c2-49ee-86d4-e9e071b6fbf4",
"deviceAssetId": "1000092019",
"ownerId": "e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"deviceId": "5933dd9394fc6bf0493a26b4e38acca1076f30ab246442976d2917f1d57d99a1",
"libraryId": None,
"type": "IMAGE",
"originalPath": "/usr/src/app/upload/upload/e7ef5713-9dab-4bd4-b899-715b0ca4379e/8e/a3/8ea31ee8-49c3-4be9-aa9d-b8ef26ba0abe.jpg",
"originalFileName": "20250714_201122.jpg",
"originalMimeType": "image/jpeg",
"thumbhash": "XRgGDILGeMlPaJaMWIeagJcJSA==",
"fileCreatedAt": "2025-07-14T18:11:22.648Z",
"fileModifiedAt": "2025-07-14T18:11:25.000Z",
"localDateTime": "2025-07-14T20:11:22.648Z",
"updatedAt": "2025-07-26T10:16:39.131Z",
"isFavorite": False,
"isArchived": False,
"isTrashed": False,
"visibility": "timeline",
"duration": "0:00:00.00000",
"livePhotoVideoId": None,
"people": [],
"unassignedFaces": [],
"checksum": "GcBJkDFoXx9d/wyl1xH89R4/NBQ=",
"isOffline": False,
"hasMetadata": True,
"duplicateId": None,
"resized": True,
}
),
ImmichAsset.from_dict(
{
"id": "046ac0d9-8acd-44d8-953f-ecb3c786358a",
"deviceAssetId": "1000092018",
"ownerId": "e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"deviceId": "5933dd9394fc6bf0493a26b4e38acca1076f30ab246442976d2917f1d57d99a1",
"libraryId": None,
"type": "IMAGE",
"originalPath": "/usr/src/app/upload/upload/e7ef5713-9dab-4bd4-b899-715b0ca4379e/f5/b4/f5b4b200-47dd-45e8-98a4-4128df3f9189.jpg",
"originalFileName": "20250714_201121.jpg",
"originalMimeType": "image/jpeg",
"thumbhash": "XRgGDILHeMlPeJaMSJmKgJcIWQ==",
"fileCreatedAt": "2025-07-14T18:11:21.582Z",
"fileModifiedAt": "2025-07-14T18:11:24.000Z",
"localDateTime": "2025-07-14T20:11:21.582Z",
"updatedAt": "2025-07-26T10:16:39.131Z",
"isFavorite": False,
"isArchived": False,
"isTrashed": False,
"visibility": "timeline",
"duration": "0:00:00.00000",
"livePhotoVideoId": None,
"people": [],
"unassignedFaces": [],
"checksum": "X6kMpPulu/HJQnKmTqCoQYl3Sjc=",
"isOffline": False,
"hasMetadata": True,
"duplicateId": None,
"resized": True,
},
),
]
MOCK_TAGS_ASSETS = [
ImmichAsset.from_dict(
{
"id": "ae3d82fc-beb5-4abc-ae83-11fcfa5e7629",
"deviceAssetId": "2132393",
"ownerId": "e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"deviceId": "CLI",
"libraryId": None,
"type": "IMAGE",
"originalPath": "/usr/src/app/upload/upload/e7ef5713-9dab-4bd4-b899-715b0ca4379e/07/d0/07d04d86-7188-4335-95ca-9bd9fd2b399d.JPG",
"originalFileName": "20110306_025024.jpg",
"originalMimeType": "image/jpeg",
"thumbhash": "WCgSFYRXaYdQiYineIiHd4SghQUY",
"fileCreatedAt": "2011-03-06T01:50:24.000Z",
"fileModifiedAt": "2011-03-06T01:50:24.000Z",
"localDateTime": "2011-03-06T02:50:24.000Z",
"updatedAt": "2025-07-26T10:16:39.477Z",
"isFavorite": False,
"isArchived": False,
"isTrashed": False,
"visibility": "timeline",
"duration": "0:00:00.00000",
"livePhotoVideoId": None,
"people": [],
"checksum": "eNwN0AN2hEYZJJkonl7ylGzJzko=",
"isOffline": False,
"hasMetadata": True,
"duplicateId": None,
"resized": True,
},
),
ImmichAsset.from_dict(
{
"id": "b71d0d08-6727-44ae-8bba-83c190f95df4",
"deviceAssetId": "2142137",
"ownerId": "e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"deviceId": "CLI",
"libraryId": None,
"type": "IMAGE",
"originalPath": "/usr/src/app/upload/upload/e7ef5713-9dab-4bd4-b899-715b0ca4379e/4a/f4/4af42484-86f8-47a0-958a-f32da89ee03a.JPG",
"originalFileName": "20110306_024053.jpg",
"originalMimeType": "image/jpeg",
"thumbhash": "4AcKFYZPZnhSmGl5daaYeG859ytT",
"fileCreatedAt": "2011-03-06T01:40:53.000Z",
"fileModifiedAt": "2011-03-06T01:40:52.000Z",
"localDateTime": "2011-03-06T02:40:53.000Z",
"updatedAt": "2025-07-26T10:16:39.474Z",
"isFavorite": False,
"isArchived": False,
"isTrashed": False,
"visibility": "timeline",
"duration": "0:00:00.00000",
"livePhotoVideoId": None,
"people": [],
"checksum": "VtokCjIwKqnHBFzH3kHakIJiq5I=",
"isOffline": False,
"hasMetadata": True,
"duplicateId": None,
"resized": True,
},
),
]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/immich/const.py",
"license": "Apache License 2.0",
"lines": 235,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/immich/test_config_flow.py | """Test the Immich config flow."""
from unittest.mock import AsyncMock, Mock
from aiohttp import ClientError
from aioimmich.exceptions import ImmichUnauthorizedError
import pytest
from homeassistant.components.immich.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import (
CONF_API_KEY,
CONF_HOST,
CONF_PORT,
CONF_SSL,
CONF_URL,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import MOCK_CONFIG_ENTRY_DATA, MOCK_USER_DATA
from tests.common import MockConfigEntry
async def test_step_user(
hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_immich: Mock
) -> None:
"""Test a user initiated config flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_DATA,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "user"
assert result["data"] == MOCK_CONFIG_ENTRY_DATA
assert result["result"].unique_id == "e7ef5713-9dab-4bd4-b899-715b0ca4379e"
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("exception", "error"),
[
(
ImmichUnauthorizedError(
{
"message": "Invalid API key",
"error": "Unauthenticated",
"statusCode": 401,
"correlationId": "abcdefg",
}
),
"invalid_auth",
),
(ClientError, "cannot_connect"),
(Exception, "unknown"),
],
)
async def test_step_user_error_handling(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_immich: Mock,
exception: Exception,
error: str,
) -> None:
"""Test a user initiated config flow with errors."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
mock_immich.users.async_get_my_user.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_DATA,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": error}
mock_immich.users.async_get_my_user.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_DATA,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_step_user_invalid_url(
hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_immich: Mock
) -> None:
"""Test a user initiated config flow with errors."""
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"],
{**MOCK_USER_DATA, CONF_URL: "hts://invalid"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {CONF_URL: "invalid_url"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_USER_DATA,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_user_already_configured(
hass: HomeAssistant, mock_immich: Mock, mock_config_entry: MockConfigEntry
) -> None:
"""Test starting a flow by user 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"],
MOCK_USER_DATA,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reauth_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauthentication flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_API_KEY: "other_fake_api_key",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == "other_fake_api_key"
@pytest.mark.parametrize(
("exception", "error"),
[
(
ImmichUnauthorizedError(
{
"message": "Invalid API key",
"error": "Unauthenticated",
"statusCode": 401,
"correlationId": "abcdefg",
}
),
"invalid_auth",
),
(ClientError, "cannot_connect"),
(Exception, "unknown"),
],
)
async def test_reauth_flow_error_handling(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
exception: Exception,
error: str,
) -> None:
"""Test reauthentication flow with errors."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
mock_immich.users.async_get_my_user.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_API_KEY: "other_fake_api_key",
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": error}
mock_immich.users.async_get_my_user.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_API_KEY: "other_fake_api_key",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == "other_fake_api_key"
assert len(mock_setup_entry.mock_calls) == 1
async def test_reauth_flow_mismatch(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauthentication flow with mis-matching unique id."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
mock_immich.users.async_get_my_user.return_value.user_id = "other_user_id"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_API_KEY: "other_fake_api_key",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
async def test_reconfigure_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfigure flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "https://localhost:8443", CONF_VERIFY_SSL: True},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "localhost"
assert mock_config_entry.data[CONF_PORT] == 8443
assert mock_config_entry.data[CONF_SSL] is True
assert mock_config_entry.data[CONF_VERIFY_SSL] is True
@pytest.mark.parametrize(
("exception", "error"),
[
(
ImmichUnauthorizedError(
{
"message": "Invalid API key",
"error": "Unauthenticated",
"statusCode": 401,
"correlationId": "abcdefg",
}
),
"invalid_auth",
),
(ClientError, "cannot_connect"),
(Exception, "unknown"),
],
)
async def test_step_reconfigure_error_handling(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
exception: Exception,
error: str,
) -> None:
"""Test a user initiated config flow with errors."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_immich.users.async_get_my_user.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "https://localhost:8443", CONF_VERIFY_SSL: True},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {"base": error}
mock_immich.users.async_get_my_user.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "https://localhost:8443", CONF_VERIFY_SSL: True},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
async def test_step_reconfigure_invalid_url(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test a user initiated config flow with errors."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "hts://invalid"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {CONF_URL: "invalid_url"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "https://localhost:8443", CONF_VERIFY_SSL: True},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/immich/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 302,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/immich/test_diagnostics.py | """Tests for the Immich integration."""
from __future__ import annotations
from unittest.mock import Mock
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test config entry diagnostics."""
await setup_integration(hass, mock_config_entry)
result = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
assert result == snapshot(exclude=props("created_at", "modified_at", "entry_id"))
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/immich/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 23,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/immich/test_media_source.py | """Tests for Immich media source."""
from pathlib import Path
import tempfile
from unittest.mock import Mock, patch
from aiohttp import web
from aioimmich.exceptions import ImmichError
import pytest
from homeassistant.components.immich.const import DOMAIN
from homeassistant.components.immich.media_source import (
ImmichMediaSource,
ImmichMediaView,
async_get_media_source,
)
from homeassistant.components.media_player import BrowseError, BrowseMedia, MediaClass
from homeassistant.components.media_source import MediaSourceItem, Unresolvable
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from homeassistant.util.aiohttp import MockRequest, MockStreamReaderChunked
from . import setup_integration
from tests.common import MockConfigEntry
async def test_get_media_source(hass: HomeAssistant) -> None:
"""Test the async_get_media_source."""
assert await async_setup_component(hass, "media_source", {})
source = await async_get_media_source(hass)
assert isinstance(source, ImmichMediaSource)
assert source.domain == DOMAIN
@pytest.mark.parametrize(
("identifier", "exception_msg"),
[
("unique_id", "identifier_no_mime_type_unresolvable"),
(
"unique_id|albums|album_id",
"identifier_no_mime_type_unresolvable",
),
(
"unique_id|albums|album_id|asset_id|filename",
"identifier_unresolvable",
),
],
)
async def test_resolve_media_bad_identifier(
hass: HomeAssistant, identifier: str, exception_msg: str
) -> None:
"""Test resolve_media with bad identifiers."""
assert await async_setup_component(hass, "media_source", {})
source = await async_get_media_source(hass)
item = MediaSourceItem(hass, DOMAIN, identifier, None)
with pytest.raises(Unresolvable, match=exception_msg):
await source.async_resolve_media(item)
@pytest.mark.parametrize(
("identifier", "url", "mime_type"),
[
(
"unique_id|albums|album_id|asset_id|filename.jpg|image/jpeg",
"/immich/unique_id/asset_id/fullsize/image/jpeg",
"image/jpeg",
),
(
"unique_id|albums|album_id|asset_id|filename.png|image/png",
"/immich/unique_id/asset_id/fullsize/image/png",
"image/png",
),
(
"unique_id|albums|album_id|asset_id|filename.mp4|video/mp4",
"/immich/unique_id/asset_id/fullsize/video/mp4",
"video/mp4",
),
],
)
async def test_resolve_media_success(
hass: HomeAssistant, identifier: str, url: str, mime_type: str
) -> None:
"""Test successful resolving an item."""
assert await async_setup_component(hass, "media_source", {})
source = await async_get_media_source(hass)
item = MediaSourceItem(hass, DOMAIN, identifier, None)
result = await source.async_resolve_media(item)
assert result.url == url
assert result.mime_type == mime_type
async def test_browse_media_unconfigured(hass: HomeAssistant) -> None:
"""Test browse_media without any devices being configured."""
assert await async_setup_component(hass, "media_source", {})
source = await async_get_media_source(hass)
item = MediaSourceItem(
hass, DOMAIN, "unique_id/albums/album_id/asset_id/filename.png", None
)
with pytest.raises(BrowseError, match="not_configured"):
await source.async_browse_media(item)
async def test_browse_media_get_root(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test browse_media returning root media sources."""
assert await async_setup_component(hass, "media_source", {})
with patch("homeassistant.components.immich.PLATFORMS", []):
await setup_integration(hass, mock_config_entry)
source = await async_get_media_source(hass)
# get root
item = MediaSourceItem(hass, DOMAIN, "", None)
result = await source.async_browse_media(item)
assert result
assert len(result.children) == 1
media_file = result.children[0]
assert isinstance(media_file, BrowseMedia)
assert media_file.title == "Someone"
assert media_file.media_content_id == (
"media-source://immich/e7ef5713-9dab-4bd4-b899-715b0ca4379e"
)
# get collections
item = MediaSourceItem(hass, DOMAIN, "e7ef5713-9dab-4bd4-b899-715b0ca4379e", None)
result = await source.async_browse_media(item)
assert result
assert len(result.children) == 3
media_file = result.children[0]
assert isinstance(media_file, BrowseMedia)
assert media_file.title == "albums"
assert media_file.media_content_id == (
"media-source://immich/e7ef5713-9dab-4bd4-b899-715b0ca4379e|albums"
)
media_file = result.children[1]
assert isinstance(media_file, BrowseMedia)
assert media_file.title == "people"
assert media_file.media_content_id == (
"media-source://immich/e7ef5713-9dab-4bd4-b899-715b0ca4379e|people"
)
media_file = result.children[2]
assert isinstance(media_file, BrowseMedia)
assert media_file.title == "tags"
assert media_file.media_content_id == (
"media-source://immich/e7ef5713-9dab-4bd4-b899-715b0ca4379e|tags"
)
@pytest.mark.parametrize(
("collection", "children"),
[
(
"albums",
[{"title": "My Album", "asset_id": "721e1a4b-aa12-441e-8d3b-5ac7ab283bb6"}],
),
(
"people",
[
{"title": "Me", "asset_id": "6176838a-ac5a-4d1f-9a35-91c591d962d8"},
{"title": "I", "asset_id": "3e66aa4a-a4a8-41a4-86fe-2ae5e490078f"},
{"title": "Myself", "asset_id": "a3c83297-684a-4576-82dc-b07432e8a18f"},
],
),
(
"tags",
[
{
"title": "Halloween",
"asset_id": "67301cb8-cb73-4e8a-99e9-475cb3f7e7b5",
},
{
"title": "Holidays",
"asset_id": "69bd487f-dc1e-4420-94c6-656f0515773d",
},
],
),
],
)
async def test_browse_media_collections(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
collection: str,
children: list[dict],
) -> None:
"""Test browse through collections."""
assert await async_setup_component(hass, "media_source", {})
with patch("homeassistant.components.immich.PLATFORMS", []):
await setup_integration(hass, mock_config_entry)
source = await async_get_media_source(hass)
item = MediaSourceItem(
hass, DOMAIN, f"{mock_config_entry.unique_id}|{collection}", None
)
result = await source.async_browse_media(item)
assert result
assert len(result.children) == len(children)
for idx, child in enumerate(children):
media_file = result.children[idx]
assert isinstance(media_file, BrowseMedia)
assert media_file.title == child["title"]
assert media_file.media_content_id == (
"media-source://immich/"
f"{mock_config_entry.unique_id}|{collection}|"
f"{child['asset_id']}"
)
@pytest.mark.parametrize(
("collection", "mocked_get_fn"),
[
("albums", ("albums", "async_get_all_albums")),
("people", ("people", "async_get_all_people")),
("tags", ("tags", "async_get_all_tags")),
],
)
async def test_browse_media_collections_error(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
collection: str,
mocked_get_fn: tuple[str, str],
) -> None:
"""Test browse_media with unknown collection."""
assert await async_setup_component(hass, "media_source", {})
with patch("homeassistant.components.immich.PLATFORMS", []):
await setup_integration(hass, mock_config_entry)
getattr(
getattr(mock_immich, mocked_get_fn[0]), mocked_get_fn[1]
).side_effect = ImmichError(
{
"message": "Not found or no album.read access",
"error": "Bad Request",
"statusCode": 400,
"correlationId": "e0hlizyl",
}
)
source = await async_get_media_source(hass)
item = MediaSourceItem(
hass, DOMAIN, f"{mock_config_entry.unique_id}|{collection}", None
)
result = await source.async_browse_media(item)
assert result
assert result.identifier is None
assert len(result.children) == 0
@pytest.mark.parametrize(
("collection", "mocked_get_fn"),
[
("albums", ("albums", "async_get_album_info")),
("people", ("search", "async_get_all_by_person_ids")),
("tags", ("search", "async_get_all_by_tag_ids")),
],
)
async def test_browse_media_collection_items_error(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
collection: str,
mocked_get_fn: tuple[str, str],
) -> None:
"""Test browse_media returning albums."""
assert await async_setup_component(hass, "media_source", {})
with patch("homeassistant.components.immich.PLATFORMS", []):
await setup_integration(hass, mock_config_entry)
source = await async_get_media_source(hass)
getattr(
getattr(mock_immich, mocked_get_fn[0]), mocked_get_fn[1]
).side_effect = ImmichError(
{
"message": "Not found or no album.read access",
"error": "Bad Request",
"statusCode": 400,
"correlationId": "e0hlizyl",
}
)
item = MediaSourceItem(
hass,
DOMAIN,
f"{mock_config_entry.unique_id}|{collection}|721e1a4b-aa12-441e-8d3b-5ac7ab283bb6",
None,
)
result = await source.async_browse_media(item)
assert result
assert result.identifier is None
assert len(result.children) == 0
@pytest.mark.parametrize(
("collection", "collection_id", "children"),
[
(
"albums",
"721e1a4b-aa12-441e-8d3b-5ac7ab283bb6",
[
{
"original_file_name": "filename.jpg",
"asset_id": "2e94c203-50aa-4ad2-8e29-56dd74e0eff4",
"media_class": MediaClass.IMAGE,
"media_content_type": "image/jpeg",
"thumb_mime_type": "image/jpeg",
"can_play": False,
},
{
"original_file_name": "filename.mp4",
"asset_id": "2e65a5f2-db83-44c4-81ab-f5ff20c9bd7b",
"media_class": MediaClass.VIDEO,
"media_content_type": "video/mp4",
"thumb_mime_type": "image/jpeg",
"can_play": True,
},
],
),
(
"people",
"6176838a-ac5a-4d1f-9a35-91c591d962d8",
[
{
"original_file_name": "20250714_201122.jpg",
"asset_id": "2242eda3-94c2-49ee-86d4-e9e071b6fbf4",
"media_class": MediaClass.IMAGE,
"media_content_type": "image/jpeg",
"thumb_mime_type": "image/jpeg",
"can_play": False,
},
{
"original_file_name": "20250714_201121.jpg",
"asset_id": "046ac0d9-8acd-44d8-953f-ecb3c786358a",
"media_class": MediaClass.IMAGE,
"media_content_type": "image/jpeg",
"thumb_mime_type": "image/jpeg",
"can_play": False,
},
],
),
(
"tags",
"6176838a-ac5a-4d1f-9a35-91c591d962d8",
[
{
"original_file_name": "20110306_025024.jpg",
"asset_id": "ae3d82fc-beb5-4abc-ae83-11fcfa5e7629",
"media_class": MediaClass.IMAGE,
"media_content_type": "image/jpeg",
"thumb_mime_type": "image/jpeg",
"can_play": False,
},
{
"original_file_name": "20110306_024053.jpg",
"asset_id": "b71d0d08-6727-44ae-8bba-83c190f95df4",
"media_class": MediaClass.IMAGE,
"media_content_type": "image/jpeg",
"thumb_mime_type": "image/jpeg",
"can_play": False,
},
],
),
],
)
async def test_browse_media_collection_get_items(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
collection: str,
collection_id: str,
children: list[dict],
) -> None:
"""Test browse_media returning albums."""
assert await async_setup_component(hass, "media_source", {})
with patch("homeassistant.components.immich.PLATFORMS", []):
await setup_integration(hass, mock_config_entry)
source = await async_get_media_source(hass)
item = MediaSourceItem(
hass,
DOMAIN,
f"{mock_config_entry.unique_id}|{collection}|{collection_id}",
None,
)
result = await source.async_browse_media(item)
assert result
assert len(result.children) == len(children)
for idx, child in enumerate(children):
media_file = result.children[idx]
assert isinstance(media_file, BrowseMedia)
assert media_file.identifier == (
f"{mock_config_entry.unique_id}|{collection}|{collection_id}|"
f"{child['asset_id']}|{child['original_file_name']}|{child['media_content_type']}"
)
assert media_file.title == child["original_file_name"]
assert media_file.media_class == child["media_class"]
assert media_file.media_content_type == child["media_content_type"]
assert media_file.can_play is child["can_play"]
assert not media_file.can_expand
assert media_file.thumbnail == (
f"/immich/{mock_config_entry.unique_id}/"
f"{child['asset_id']}/thumbnail/{child['thumb_mime_type']}"
)
async def test_media_view(
hass: HomeAssistant,
tmp_path: Path,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test SynologyDsmMediaView returning albums."""
view = ImmichMediaView(hass)
request = MockRequest(b"", DOMAIN)
# immich noch configured
with pytest.raises(web.HTTPNotFound):
await view.get(request, "", "")
# setup immich
assert await async_setup_component(hass, "media_source", {})
with patch("homeassistant.components.immich.PLATFORMS", []):
await setup_integration(hass, mock_config_entry)
# wrong url (without mime type)
with pytest.raises(web.HTTPNotFound):
await view.get(
request,
"e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"2e94c203-50aa-4ad2-8e29-56dd74e0eff4/thumbnail",
)
# exception in async_view_asset()
mock_immich.assets.async_view_asset.side_effect = ImmichError(
{
"message": "Not found or no asset.read access",
"error": "Bad Request",
"statusCode": 400,
"correlationId": "e0hlizyl",
}
)
with pytest.raises(web.HTTPNotFound):
await view.get(
request,
"e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"2e94c203-50aa-4ad2-8e29-56dd74e0eff4/thumbnail/image/jpeg",
)
# exception in async_get_person_thumbnail()
mock_immich.people.async_get_person_thumbnail.side_effect = ImmichError(
{
"message": "Not found or no asset.read access",
"error": "Bad Request",
"statusCode": 400,
"correlationId": "e0hlizyl",
}
)
with pytest.raises(web.HTTPNotFound):
await view.get(
request,
"e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"2e94c203-50aa-4ad2-8e29-56dd74e0eff4/person/image/jpeg",
)
# exception in async_play_video_stream()
mock_immich.assets.async_play_video_stream.side_effect = ImmichError(
{
"message": "Not found or no asset.read access",
"error": "Bad Request",
"statusCode": 400,
"correlationId": "e0hlizyl",
}
)
with pytest.raises(web.HTTPNotFound):
await view.get(
request,
"e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"2e65a5f2-db83-44c4-81ab-f5ff20c9bd7b/fullsize/video/mp4",
)
# success
mock_immich.assets.async_view_asset.side_effect = None
mock_immich.assets.async_view_asset.return_value = b"xxxx"
with patch.object(tempfile, "tempdir", tmp_path):
result = await view.get(
request,
"e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"2e94c203-50aa-4ad2-8e29-56dd74e0eff4/thumbnail/image/jpeg",
)
assert isinstance(result, web.Response)
with patch.object(tempfile, "tempdir", tmp_path):
result = await view.get(
request,
"e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"2e94c203-50aa-4ad2-8e29-56dd74e0eff4/fullsize/image/jpeg",
)
assert isinstance(result, web.Response)
mock_immich.people.async_get_person_thumbnail.side_effect = None
mock_immich.people.async_get_person_thumbnail.return_value = b"xxxx"
with patch.object(tempfile, "tempdir", tmp_path):
result = await view.get(
request,
"e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"2e94c203-50aa-4ad2-8e29-56dd74e0eff4/person/image/jpeg",
)
assert isinstance(result, web.Response)
with patch.object(tempfile, "tempdir", tmp_path):
result = await view.get(
request,
"e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"2e94c203-50aa-4ad2-8e29-56dd74e0eff4/fullsize/image/jpeg",
)
assert isinstance(result, web.Response)
mock_immich.assets.async_play_video_stream.side_effect = None
mock_immich.assets.async_play_video_stream.return_value = MockStreamReaderChunked(
b"xxxx"
)
with patch.object(tempfile, "tempdir", tmp_path):
result = await view.get(
request,
"e7ef5713-9dab-4bd4-b899-715b0ca4379e",
"2e65a5f2-db83-44c4-81ab-f5ff20c9bd7b/fullsize/video/mp4",
)
assert isinstance(result, web.StreamResponse)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/immich/test_media_source.py",
"license": "Apache License 2.0",
"lines": 487,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/immich/test_sensor.py | """Test the Immich sensor platform."""
from unittest.mock import Mock, 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 . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensors(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Immich sensor platform."""
with patch("homeassistant.components.immich.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_admin_sensors(
hass: HomeAssistant,
mock_non_admin_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the integration doesn't create admin sensors if not admin."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("sensor.mock_title_photos_count") is None
assert hass.states.get("sensor.mock_title_videos_count") is None
assert hass.states.get("sensor.mock_title_disk_used_by_photos") is None
assert hass.states.get("sensor.mock_title_disk_used_by_videos") is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/immich/test_sensor.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/jewish_calendar/test_diagnostics.py | """Tests for the diagnostics data provided by the Jewish Calendar integration."""
import datetime as dt
import pytest
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
@pytest.mark.parametrize(
("location_data"), ["Jerusalem", "New York", None], indirect=True
)
@pytest.mark.parametrize("test_time", [dt.datetime(2025, 5, 19)], indirect=True)
@pytest.mark.usefixtures("setup_at_time")
async def test_diagnostics(
hass: HomeAssistant,
config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics with different locations."""
diagnostics_data = await get_diagnostics_for_config_entry(
hass, hass_client, config_entry
)
assert diagnostics_data == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/jewish_calendar/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/miele/test_vacuum.py | """Tests for miele vacuum module."""
from unittest.mock import MagicMock, Mock
from aiohttp import ClientResponseError
from pymiele import MieleDevices
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.miele.const import DOMAIN, PROCESS_ACTION, PROGRAM_ID
from homeassistant.components.vacuum import (
ATTR_FAN_SPEED,
DOMAIN as VACUUM_DOMAIN,
SERVICE_CLEAN_SPOT,
SERVICE_PAUSE,
SERVICE_SET_FAN_SPEED,
SERVICE_START,
SERVICE_STOP,
)
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 get_actions_callback, get_data_callback
from tests.common import (
MockConfigEntry,
async_load_json_object_fixture,
snapshot_platform,
)
TEST_PLATFORM = VACUUM_DOMAIN
ENTITY_ID = "vacuum.robot_vacuum_cleaner"
pytestmark = [
pytest.mark.parametrize("platforms", [(TEST_PLATFORM,)]),
pytest.mark.parametrize("load_device_file", ["vacuum_device.json"]),
]
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_states(
hass: HomeAssistant,
mock_miele_client: MagicMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
setup_platform: None,
) -> None:
"""Test vacuum entity setup."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_vacuum_states_api_push(
hass: HomeAssistant,
mock_miele_client: MagicMock,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
setup_platform: MockConfigEntry,
device_fixture: MieleDevices,
) -> None:
"""Test vacuum state when the API pushes data via SSE."""
data_callback = get_data_callback(mock_miele_client)
await data_callback(device_fixture)
await hass.async_block_till_done()
act_file = await async_load_json_object_fixture(
hass, "action_push_vacuum.json", DOMAIN
)
action_callback = get_actions_callback(mock_miele_client)
await action_callback(act_file)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, setup_platform.entry_id)
@pytest.mark.parametrize(
("service", "action_command", "vacuum_power"),
[
(SERVICE_START, PROCESS_ACTION, 1),
(SERVICE_STOP, PROCESS_ACTION, 2),
(SERVICE_PAUSE, PROCESS_ACTION, 3),
(SERVICE_CLEAN_SPOT, PROGRAM_ID, 2),
],
)
async def test_vacuum_program(
hass: HomeAssistant,
mock_miele_client: MagicMock,
setup_platform: None,
service: str,
vacuum_power: int | str,
action_command: str,
) -> None:
"""Test the vacuum can be controlled."""
await hass.services.async_call(
TEST_PLATFORM, service, {ATTR_ENTITY_ID: ENTITY_ID}, blocking=True
)
mock_miele_client.send_action.assert_called_once_with(
"Dummy_Vacuum_1", {action_command: vacuum_power}
)
@pytest.mark.parametrize(
("fan_speed", "expected"), [("normal", 1), ("turbo", 3), ("silent", 4)]
)
async def test_vacuum_fan_speed(
hass: HomeAssistant,
mock_miele_client: MagicMock,
setup_platform: None,
fan_speed: str,
expected: int,
) -> None:
"""Test the vacuum can be controlled."""
await hass.services.async_call(
TEST_PLATFORM,
SERVICE_SET_FAN_SPEED,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_FAN_SPEED: fan_speed},
blocking=True,
)
mock_miele_client.send_action.assert_called_once_with(
"Dummy_Vacuum_1", {"programId": expected}
)
@pytest.mark.parametrize(
("service"),
[
(SERVICE_START),
(SERVICE_STOP),
],
)
async def test_api_failure(
hass: HomeAssistant,
mock_miele_client: MagicMock,
setup_platform: None,
service: str,
) -> None:
"""Test handling of exception from API."""
mock_miele_client.send_action.side_effect = ClientResponseError(Mock(), Mock())
with pytest.raises(
HomeAssistantError, match=f"Failed to set state for {ENTITY_ID}"
):
await hass.services.async_call(
TEST_PLATFORM, service, {ATTR_ENTITY_ID: ENTITY_ID}, blocking=True
)
mock_miele_client.send_action.assert_called_once()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/miele/test_vacuum.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/nanoleaf/test_light.py | """Tests for the Nanoleaf light platform."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.light import ATTR_EFFECT_LIST, DOMAIN as LIGHT_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
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_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_nanoleaf: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.nanoleaf.PLATFORMS", [Platform.LIGHT]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize("service", [SERVICE_TURN_ON, SERVICE_TURN_OFF])
async def test_turning_on_or_off_writes_state(
hass: HomeAssistant,
mock_nanoleaf: AsyncMock,
mock_config_entry: MockConfigEntry,
service: str,
) -> None:
"""Test turning on or off the light writes the state."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("light.nanoleaf").attributes[ATTR_EFFECT_LIST] == [
"Rainbow",
"Sunset",
"Nemo",
]
mock_nanoleaf.effects_list = ["Rainbow", "Sunset", "Nemo", "Something Else"]
await hass.services.async_call(
LIGHT_DOMAIN,
service,
{
ATTR_ENTITY_ID: "light.nanoleaf",
},
blocking=True,
)
assert hass.states.get("light.nanoleaf").attributes[ATTR_EFFECT_LIST] == [
"Rainbow",
"Sunset",
"Nemo",
"Something Else",
]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nanoleaf/test_light.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/openweathermap/test_sensor.py | """Tests for OpenWeatherMap sensors."""
from unittest.mock import MagicMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.openweathermap.const import (
OWM_MODE_AIRPOLLUTION,
OWM_MODE_FREE_CURRENT,
OWM_MODE_FREE_FORECAST,
OWM_MODE_V30,
)
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_platform
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.parametrize(
"mode", [OWM_MODE_V30, OWM_MODE_FREE_CURRENT, OWM_MODE_AIRPOLLUTION], indirect=True
)
async def test_sensor_states(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
owm_client_mock: MagicMock,
mode: str,
) -> None:
"""Test sensor states are correctly collected from library with different modes and mocked function responses."""
await setup_platform(hass, mock_config_entry, [Platform.SENSOR])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize("mode", [OWM_MODE_FREE_FORECAST], indirect=True)
async def test_mode_no_sensor(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
owm_client_mock: MagicMock,
mode: str,
) -> None:
"""Test modes that do not provide any sensor."""
await setup_platform(hass, mock_config_entry, [Platform.SENSOR])
assert len(entity_registry.entities) == 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openweathermap/test_sensor.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/paperless_ngx/const.py | """Constants for the Paperless NGX integration tests."""
from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL
USER_INPUT_ONE = {
CONF_URL: "https://192.168.69.16:8000",
CONF_API_KEY: "12345678",
CONF_VERIFY_SSL: True,
}
USER_INPUT_TWO = {
CONF_URL: "https://paperless.example.de",
CONF_API_KEY: "87654321",
CONF_VERIFY_SSL: True,
}
USER_INPUT_REAUTH = {CONF_API_KEY: "192837465"}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/paperless_ngx/const.py",
"license": "Apache License 2.0",
"lines": 13,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/paperless_ngx/test_config_flow.py | """Tests for the Paperless-ngx config flow."""
from collections.abc import Generator
from unittest.mock import AsyncMock
from pypaperless.exceptions import (
InitializationError,
PaperlessConnectionError,
PaperlessForbiddenError,
PaperlessInactiveOrDeletedError,
PaperlessInvalidTokenError,
)
import pytest
from homeassistant import config_entries
from homeassistant.components.paperless_ngx.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import USER_INPUT_ONE, USER_INPUT_REAUTH, USER_INPUT_TWO
from tests.common import MockConfigEntry, patch
@pytest.fixture(autouse=True)
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.paperless_ngx.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry
async def test_full_config_flow(hass: HomeAssistant) -> None:
"""Test registering an integration and finishing flow works."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["flow_id"]
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT_ONE,
)
config_entry = result["result"]
assert config_entry.title == USER_INPUT_ONE[CONF_URL]
assert result["type"] is FlowResultType.CREATE_ENTRY
assert config_entry.data == USER_INPUT_ONE
async def test_full_reauth_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test reauth an integration and finishing flow works."""
mock_config_entry.add_to_hass(hass)
reauth_flow = await mock_config_entry.start_reauth_flow(hass)
assert reauth_flow["type"] is FlowResultType.FORM
assert reauth_flow["step_id"] == "reauth_confirm"
result_configure = await hass.config_entries.flow.async_configure(
reauth_flow["flow_id"], USER_INPUT_REAUTH
)
assert result_configure["type"] is FlowResultType.ABORT
assert result_configure["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == USER_INPUT_REAUTH[CONF_API_KEY]
async def test_full_reconfigure_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test reconfigure an integration and finishing flow works."""
mock_config_entry.add_to_hass(hass)
reconfigure_flow = await mock_config_entry.start_reconfigure_flow(hass)
assert reconfigure_flow["type"] is FlowResultType.FORM
assert reconfigure_flow["step_id"] == "reconfigure"
result_configure = await hass.config_entries.flow.async_configure(
reconfigure_flow["flow_id"],
USER_INPUT_TWO,
)
assert result_configure["type"] is FlowResultType.ABORT
assert result_configure["reason"] == "reconfigure_successful"
assert mock_config_entry.data == USER_INPUT_TWO
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(PaperlessConnectionError(), {CONF_URL: "cannot_connect"}),
(PaperlessInvalidTokenError(), {CONF_API_KEY: "invalid_api_key"}),
(PaperlessInactiveOrDeletedError(), {CONF_API_KEY: "user_inactive_or_deleted"}),
(PaperlessForbiddenError(), {CONF_API_KEY: "forbidden"}),
(InitializationError(), {CONF_URL: "cannot_connect"}),
(Exception("BOOM!"), {"base": "unknown"}),
],
)
async def test_config_flow_error_handling(
hass: HomeAssistant,
mock_paperless: AsyncMock,
side_effect: Exception,
expected_error: dict[str, str],
) -> None:
"""Test user step shows correct error for various client initialization issues."""
mock_paperless.initialize.side_effect = side_effect
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=USER_INPUT_ONE,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == expected_error
mock_paperless.initialize.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=USER_INPUT_ONE,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == USER_INPUT_ONE[CONF_URL]
assert result["data"] == USER_INPUT_ONE
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(PaperlessConnectionError(), {CONF_URL: "cannot_connect"}),
(PaperlessInvalidTokenError(), {CONF_API_KEY: "invalid_api_key"}),
(PaperlessInactiveOrDeletedError(), {CONF_API_KEY: "user_inactive_or_deleted"}),
(PaperlessForbiddenError(), {CONF_API_KEY: "forbidden"}),
(InitializationError(), {CONF_URL: "cannot_connect"}),
(Exception("BOOM!"), {"base": "unknown"}),
],
)
async def test_reauth_flow_error_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_paperless: AsyncMock,
side_effect: Exception,
expected_error: str,
) -> None:
"""Test reauth flow with various initialization errors."""
mock_config_entry.add_to_hass(hass)
mock_paperless.initialize.side_effect = side_effect
reauth_flow = await mock_config_entry.start_reauth_flow(hass)
assert reauth_flow["type"] is FlowResultType.FORM
assert reauth_flow["step_id"] == "reauth_confirm"
result_configure = await hass.config_entries.flow.async_configure(
reauth_flow["flow_id"], USER_INPUT_REAUTH
)
await hass.async_block_till_done()
assert result_configure["type"] is FlowResultType.FORM
assert result_configure["errors"] == expected_error
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(PaperlessConnectionError(), {CONF_URL: "cannot_connect"}),
(PaperlessInvalidTokenError(), {CONF_API_KEY: "invalid_api_key"}),
(PaperlessInactiveOrDeletedError(), {CONF_API_KEY: "user_inactive_or_deleted"}),
(PaperlessForbiddenError(), {CONF_API_KEY: "forbidden"}),
(InitializationError(), {CONF_URL: "cannot_connect"}),
(Exception("BOOM!"), {"base": "unknown"}),
],
)
async def test_reconfigure_flow_error_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_paperless: AsyncMock,
side_effect: Exception,
expected_error: str,
) -> None:
"""Test reconfigure flow with various initialization errors."""
mock_config_entry.add_to_hass(hass)
mock_paperless.initialize.side_effect = side_effect
reauth_flow = await mock_config_entry.start_reconfigure_flow(hass)
assert reauth_flow["type"] is FlowResultType.FORM
assert reauth_flow["step_id"] == "reconfigure"
result_configure = await hass.config_entries.flow.async_configure(
reauth_flow["flow_id"],
USER_INPUT_TWO,
)
await hass.async_block_till_done()
assert result_configure["type"] is FlowResultType.FORM
assert result_configure["errors"] == expected_error
async def test_config_already_exists(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test we only allow a single config flow."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=USER_INPUT_ONE,
context={"source": config_entries.SOURCE_USER},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_config_already_exists_reconfigure(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test we only allow a single config if reconfiguring an entry."""
mock_config_entry.add_to_hass(hass)
mock_config_entry_two = MockConfigEntry(
entry_id="J87G00V55WEVTJ0CJHM0GADBH5",
title="Paperless-ngx - Two",
domain=DOMAIN,
data=USER_INPUT_TWO,
)
mock_config_entry_two.add_to_hass(hass)
reconfigure_flow = await mock_config_entry_two.start_reconfigure_flow(hass)
assert reconfigure_flow["type"] is FlowResultType.FORM
assert reconfigure_flow["step_id"] == "reconfigure"
result_configure = await hass.config_entries.flow.async_configure(
reconfigure_flow["flow_id"],
USER_INPUT_ONE,
)
assert result_configure["type"] is FlowResultType.ABORT
assert result_configure["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/paperless_ngx/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 206,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/paperless_ngx/test_diagnostics.py | """Tests for Paperless-ngx sensor platform."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_config_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_paperless: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test generating diagnostics for a device entry."""
await setup_integration(hass, mock_config_entry)
assert (
await get_diagnostics_for_config_entry(hass, hass_client, mock_config_entry)
== snapshot
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/paperless_ngx/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/paperless_ngx/test_init.py | """Test the Paperless-ngx integration initialization."""
from unittest.mock import AsyncMock
from pypaperless.exceptions import (
InitializationError,
PaperlessConnectionError,
PaperlessForbiddenError,
PaperlessInactiveOrDeletedError,
PaperlessInvalidTokenError,
)
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,
) -> None:
"""Test loading and unloading the integration."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
async def test_load_config_status_forbidden(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_paperless: AsyncMock,
) -> None:
"""Test loading and unloading the integration."""
mock_paperless.status.side_effect = PaperlessForbiddenError
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
("side_effect", "expected_state", "expected_error_key"),
[
(PaperlessConnectionError(), ConfigEntryState.SETUP_RETRY, "cannot_connect"),
(PaperlessInvalidTokenError(), ConfigEntryState.SETUP_ERROR, "invalid_api_key"),
(
PaperlessInactiveOrDeletedError(),
ConfigEntryState.SETUP_ERROR,
"user_inactive_or_deleted",
),
(PaperlessForbiddenError(), ConfigEntryState.SETUP_ERROR, "forbidden"),
(InitializationError(), ConfigEntryState.SETUP_RETRY, "cannot_connect"),
],
)
async def test_setup_config_error_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_paperless: AsyncMock,
side_effect: Exception,
expected_state: ConfigEntryState,
expected_error_key: str,
) -> None:
"""Test all initialization error paths during setup."""
mock_paperless.initialize.side_effect = side_effect
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state == expected_state
assert mock_config_entry.error_reason_translation_key == expected_error_key
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/paperless_ngx/test_init.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/paperless_ngx/test_sensor.py | """Tests for Paperless-ngx sensor platform."""
from freezegun.api import FrozenDateTimeFactory
from pypaperless.exceptions import (
PaperlessConnectionError,
PaperlessForbiddenError,
PaperlessInactiveOrDeletedError,
PaperlessInvalidTokenError,
)
from pypaperless.models import Statistic
import pytest
from homeassistant.components.paperless_ngx.coordinator import (
UPDATE_INTERVAL_STATISTICS,
)
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import (
AsyncMock,
MockConfigEntry,
SnapshotAssertion,
async_fire_time_changed,
patch,
snapshot_platform,
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_platform(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test paperless_ngx update sensors."""
with patch("homeassistant.components.paperless_ngx.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("init_integration")
async def test_statistic_sensor_state(
hass: HomeAssistant,
mock_paperless: AsyncMock,
freezer: FrozenDateTimeFactory,
mock_statistic_data_update,
) -> None:
"""Ensure sensor entities are added automatically."""
# initialize with 999 documents
state = hass.states.get("sensor.paperless_ngx_total_documents")
assert state.state == "999"
# update to 420 documents
mock_paperless.statistics = AsyncMock(
return_value=Statistic.create_with_data(
mock_paperless, data=mock_statistic_data_update, fetched=True
)
)
freezer.tick(UPDATE_INTERVAL_STATISTICS)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("sensor.paperless_ngx_total_documents")
assert state.state == "420"
@pytest.mark.usefixtures("init_integration")
@pytest.mark.parametrize(
("error_cls", "assert_state"),
[
(PaperlessForbiddenError, "420"),
(PaperlessConnectionError, "420"),
(PaperlessInactiveOrDeletedError, STATE_UNAVAILABLE),
(PaperlessInvalidTokenError, STATE_UNAVAILABLE),
],
)
async def test__statistic_sensor_state_on_error(
hass: HomeAssistant,
mock_paperless: AsyncMock,
freezer: FrozenDateTimeFactory,
mock_statistic_data_update,
error_cls,
assert_state,
) -> None:
"""Ensure sensor entities are added automatically."""
# simulate error
mock_paperless.statistics.side_effect = error_cls
freezer.tick(UPDATE_INTERVAL_STATISTICS)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("sensor.paperless_ngx_total_documents")
assert state.state == STATE_UNAVAILABLE
# recover from not auth errors
mock_paperless.statistics = AsyncMock(
return_value=Statistic.create_with_data(
mock_paperless, data=mock_statistic_data_update, fetched=True
)
)
freezer.tick(UPDATE_INTERVAL_STATISTICS)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("sensor.paperless_ngx_total_documents")
assert state.state == assert_state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/paperless_ngx/test_sensor.py",
"license": "Apache License 2.0",
"lines": 95,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/probe_plus/test_config_flow.py | """Test the config flow for the Probe Plus."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
import pytest
from homeassistant.components.probe_plus.const import DOMAIN
from homeassistant.config_entries import SOURCE_BLUETOOTH, SOURCE_IGNORE, SOURCE_USER
from homeassistant.const import CONF_ADDRESS, CONF_MODEL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.bluetooth import BluetoothServiceInfo
from tests.common import MockConfigEntry
service_info = BluetoothServiceInfo(
name="FM210",
address="aa:bb:cc:dd:ee:ff",
rssi=-63,
manufacturer_data={},
service_data={},
service_uuids=[],
source="local",
)
@pytest.fixture
def mock_discovered_service_info() -> Generator[AsyncMock]:
"""Override getting Bluetooth service info."""
with patch(
"homeassistant.components.probe_plus.config_flow.async_discovered_service_info",
return_value=[service_info],
) as mock_discovered_service_info:
yield mock_discovered_service_info
async def test_user_config_flow_creates_entry(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_discovered_service_info: AsyncMock,
) -> None:
"""Test the user configuration flow successfully creates a 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"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["result"].unique_id == "aa:bb:cc:dd:ee:ff"
assert result["title"] == "FM210 aa:bb:cc:dd:ee:ff"
assert result["data"] == {CONF_ADDRESS: "aa:bb:cc:dd:ee:ff", CONF_MODEL: "FM210"}
async def test_user_flow_already_configured(
hass: HomeAssistant,
mock_discovered_service_info: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test that the user flow aborts when the entry is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
# this aborts with no devices found as the config flow
# already checks for existing config entries when validating the discovered devices
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"
async def test_bluetooth_discovery(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_discovered_service_info: AsyncMock,
) -> None:
"""Test we can discover a device."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=service_info
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "bluetooth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "FM210 aa:bb:cc:dd:ee:ff"
assert result["result"].unique_id == "aa:bb:cc:dd:ee:ff"
assert result["data"] == {CONF_ADDRESS: service_info.address, CONF_MODEL: "FM210"}
async def test_already_configured_bluetooth_discovery(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Ensure configure device is not discovered again."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=service_info
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_no_bluetooth_devices(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_discovered_service_info: AsyncMock,
) -> None:
"""Test flow aborts on unsupported device."""
mock_discovered_service_info.return_value = []
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"
async def test_user_setup_replaces_ignored_device(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_discovered_service_info: AsyncMock,
) -> None:
"""Test the user flow can replace an ignored device."""
entry = MockConfigEntry(
domain=DOMAIN,
unique_id="aa:bb:cc:dd:ee:ff",
source=SOURCE_IGNORE,
data={},
)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
# Verify the ignored device is in the dropdown
assert "aa:bb:cc:dd:ee:ff" in result["data_schema"].schema[CONF_ADDRESS].container
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_ADDRESS: "aa:bb:cc:dd:ee:ff"},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["result"].unique_id == "aa:bb:cc:dd:ee:ff"
assert result2["title"] == "FM210 aa:bb:cc:dd:ee:ff"
assert result2["data"] == {CONF_ADDRESS: "aa:bb:cc:dd:ee:ff", CONF_MODEL: "FM210"}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/probe_plus/test_config_flow.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/pterodactyl/const.py | """Constants for Pterodactyl tests."""
from homeassistant.const import CONF_API_KEY, CONF_URL
TEST_URL = "https://192.168.0.1:8080/"
TEST_API_KEY = "TestClientApiKey"
TEST_USER_INPUT = {
CONF_URL: TEST_URL,
CONF_API_KEY: TEST_API_KEY,
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/pterodactyl/const.py",
"license": "Apache License 2.0",
"lines": 8,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/pterodactyl/test_binary_sensor.py | """Tests for the binary sensor platform of the Pterodactyl integration."""
from collections.abc import Generator
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from requests.exceptions import ConnectionError
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import STATE_ON, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("mock_pterodactyl")
async def test_binary_sensor(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test binary sensor."""
with patch(
"homeassistant.components.pterodactyl._PLATFORMS", [Platform.BINARY_SENSOR]
):
mock_config_entry = await setup_integration(hass, mock_config_entry)
assert len(hass.states.async_all(Platform.BINARY_SENSOR)) == 2
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
@pytest.mark.usefixtures("mock_pterodactyl")
async def test_binary_sensor_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test binary sensor update."""
await setup_integration(hass, mock_config_entry)
freezer.tick(timedelta(seconds=90))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert len(hass.states.async_all(Platform.BINARY_SENSOR)) == 2
assert (
hass.states.get(f"{Platform.BINARY_SENSOR}.test_server_1_status").state
== STATE_ON
)
assert (
hass.states.get(f"{Platform.BINARY_SENSOR}.test_server_2_status").state
== STATE_ON
)
async def test_binary_sensor_update_failure(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pterodactyl: Generator[AsyncMock],
freezer: FrozenDateTimeFactory,
) -> None:
"""Test failed binary sensor update."""
await setup_integration(hass, mock_config_entry)
mock_pterodactyl.client.servers.get_server.side_effect = ConnectionError(
"Simulated connection error"
)
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert len(hass.states.async_all(Platform.BINARY_SENSOR)) == 2
assert (
hass.states.get(f"{Platform.BINARY_SENSOR}.test_server_1_status").state
== STATE_UNAVAILABLE
)
assert (
hass.states.get(f"{Platform.BINARY_SENSOR}.test_server_2_status").state
== STATE_UNAVAILABLE
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/pterodactyl/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 72,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/qbus/test_scene.py | """Test Qbus scene entities."""
from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN, SERVICE_TURN_ON
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from tests.common import async_fire_mqtt_message
from tests.typing import MqttMockHAClient
_PAYLOAD_SCENE_STATE = '{"id":"UL25","properties":{"value":true},"type":"state"}'
_PAYLOAD_SCENE_ACTIVATE = '{"id": "UL25", "type": "action", "action": "active"}'
_TOPIC_SCENE_STATE = "cloudapp/QBUSMQTTGW/UL1/UL25/state"
_TOPIC_SCENE_SET_STATE = "cloudapp/QBUSMQTTGW/UL1/UL25/setState"
_SCENE_ENTITY_ID = "scene.ctd_000001_watching_tv"
async def test_scene(
hass: HomeAssistant,
mqtt_mock: MqttMockHAClient,
setup_integration: None,
) -> None:
"""Test scene."""
assert hass.states.get(_SCENE_ENTITY_ID).state == STATE_UNKNOWN
# Activate scene
mqtt_mock.reset_mock()
await hass.services.async_call(
SCENE_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: _SCENE_ENTITY_ID},
blocking=True,
)
mqtt_mock.async_publish.assert_called_once_with(
_TOPIC_SCENE_SET_STATE, _PAYLOAD_SCENE_ACTIVATE, 0, False
)
# Simulate response
async_fire_mqtt_message(hass, _TOPIC_SCENE_STATE, _PAYLOAD_SCENE_STATE)
await hass.async_block_till_done()
assert hass.states.get(_SCENE_ENTITY_ID).state != STATE_UNKNOWN
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/qbus/test_scene.py",
"license": "Apache License 2.0",
"lines": 33,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/quantum_gateway/test_device_tracker.py | """Tests for the quantum_gateway device tracker."""
from unittest.mock import AsyncMock
import pytest
from requests import RequestException
from homeassistant.const import STATE_HOME
from homeassistant.core import HomeAssistant
from . import setup_platform
from tests.components.device_tracker.test_init import mock_yaml_devices # noqa: F401
@pytest.mark.usefixtures("yaml_devices")
async def test_get_scanner(hass: HomeAssistant, mock_scanner: AsyncMock) -> None:
"""Test creating a quantum gateway scanner."""
await setup_platform(hass)
device_1 = hass.states.get("device_tracker.desktop")
assert device_1 is not None
assert device_1.state == STATE_HOME
device_2 = hass.states.get("device_tracker.ff_ff_ff_ff_ff_ff")
assert device_2 is not None
assert device_2.state == STATE_HOME
@pytest.mark.usefixtures("yaml_devices")
async def test_get_scanner_error(hass: HomeAssistant, mock_scanner: AsyncMock) -> None:
"""Test failure when creating a quantum gateway scanner."""
mock_scanner.side_effect = RequestException("Error")
await setup_platform(hass)
assert "quantum_gateway.device_tracker" not in hass.config.components
@pytest.mark.usefixtures("yaml_devices")
async def test_scan_devices_error(hass: HomeAssistant, mock_scanner: AsyncMock) -> None:
"""Test failure when scanning devices."""
mock_scanner.return_value.scan_devices.side_effect = RequestException("Error")
await setup_platform(hass)
assert "quantum_gateway.device_tracker" in hass.config.components
device_1 = hass.states.get("device_tracker.desktop")
assert device_1 is None
device_2 = hass.states.get("device_tracker.ff_ff_ff_ff_ff_ff")
assert device_2 is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/quantum_gateway/test_device_tracker.py",
"license": "Apache License 2.0",
"lines": 34,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/rehlko/test_binary_sensor.py | """Tests for the Rehlko binary sensors."""
from __future__ import annotations
import logging
from typing import Any
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.rehlko.const import GENERATOR_DATA_DEVICE
from homeassistant.components.rehlko.coordinator import SCAN_INTERVAL_MINUTES
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNKNOWN, 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(name="platform_binary_sensor", autouse=True)
async def platform_binary_sensor_fixture():
"""Patch Rehlko to only load binary_sensor platform."""
with patch("homeassistant.components.rehlko.PLATFORMS", [Platform.BINARY_SENSOR]):
yield
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensors(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
rehlko_config_entry: MockConfigEntry,
load_rehlko_config_entry: None,
) -> None:
"""Test the Rehlko binary sensors."""
await snapshot_platform(
hass, entity_registry, snapshot, rehlko_config_entry.entry_id
)
async def test_binary_sensor_states(
hass: HomeAssistant,
generator: dict[str, Any],
mock_rehlko: AsyncMock,
load_rehlko_config_entry: None,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the Rehlko binary sensor state logic."""
assert generator["engineOilPressureOk"] is True
state = hass.states.get("binary_sensor.generator_1_oil_pressure")
assert state.state == STATE_OFF
generator["engineOilPressureOk"] = False
freezer.tick(SCAN_INTERVAL_MINUTES)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.generator_1_oil_pressure")
assert state.state == STATE_ON
generator["engineOilPressureOk"] = "Unknown State"
with caplog.at_level(logging.WARNING):
caplog.clear()
freezer.tick(SCAN_INTERVAL_MINUTES)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.generator_1_oil_pressure")
assert state.state == STATE_UNKNOWN
assert "Unknown State" in caplog.text
assert "engineOilPressureOk" in caplog.text
async def test_binary_sensor_connectivity_availability(
hass: HomeAssistant,
generator: dict[str, Any],
mock_rehlko: AsyncMock,
load_rehlko_config_entry: None,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the connectivity entity availability when device is disconnected."""
state = hass.states.get("binary_sensor.generator_1_connectivity")
assert state.state == STATE_ON
# Entity should be available when device is disconnected
generator[GENERATOR_DATA_DEVICE]["isConnected"] = False
freezer.tick(SCAN_INTERVAL_MINUTES)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.generator_1_connectivity")
assert state.state == STATE_OFF
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/rehlko/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 77,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/shelly/test_devices.py | """Test real devices."""
from unittest.mock import Mock
from aioshelly.const import MODEL_2PM_G3, MODEL_BLU_GATEWAY_G3, MODEL_PRO_EM3
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.shelly.const import (
DOMAIN,
MODEL_FRANKEVER_IRRIGATION_CONTROLLER,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceRegistry
from homeassistant.helpers.entity_registry import EntityRegistry
from . import force_uptime_value, init_integration, snapshot_device_entities
from tests.common import async_load_json_object_fixture
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_shelly_2pm_gen3_no_relay_names(
hass: HomeAssistant,
mock_rpc_device: Mock,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
monkeypatch: pytest.MonkeyPatch,
snapshot: SnapshotAssertion,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test Shelly 2PM Gen3 without relay names.
This device has two relays/channels,we should get a main device and two sub
devices.
"""
device_fixture = await async_load_json_object_fixture(hass, "2pm_gen3.json", DOMAIN)
monkeypatch.setattr(mock_rpc_device, "shelly", device_fixture["shelly"])
monkeypatch.setattr(mock_rpc_device, "status", device_fixture["status"])
monkeypatch.setattr(mock_rpc_device, "config", device_fixture["config"])
await force_uptime_value(hass, freezer)
config_entry = await init_integration(hass, gen=3, model=MODEL_2PM_G3)
# Relay 0 sub-device
entity_id = "switch.test_name_output_0"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Output 0"
entity_id = "sensor.test_name_output_0_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Output 0"
# Relay 1 sub-device
entity_id = "switch.test_name_output_1"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Output 1"
entity_id = "sensor.test_name_output_1_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Output 1"
# Main device
entity_id = "update.test_name_firmware"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
await snapshot_device_entities(
hass, entity_registry, snapshot, config_entry.entry_id
)
async def test_shelly_2pm_gen3_relay_names(
hass: HomeAssistant,
mock_rpc_device: Mock,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test Shelly 2PM Gen3 with relay names.
This device has two relays/channels,we should get a main device and two sub
devices.
"""
device_fixture = await async_load_json_object_fixture(hass, "2pm_gen3.json", DOMAIN)
device_fixture["config"]["switch:0"]["name"] = "Kitchen light"
device_fixture["config"]["switch:1"]["name"] = "Living room light"
monkeypatch.setattr(mock_rpc_device, "shelly", device_fixture["shelly"])
monkeypatch.setattr(mock_rpc_device, "status", device_fixture["status"])
monkeypatch.setattr(mock_rpc_device, "config", device_fixture["config"])
await init_integration(hass, gen=3, model=MODEL_2PM_G3)
# Relay 0 sub-device
entity_id = "switch.kitchen_light"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Kitchen light"
entity_id = "sensor.kitchen_light_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Kitchen light"
# Relay 1 sub-device
entity_id = "switch.living_room_light"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Living room light"
entity_id = "sensor.living_room_light_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Living room light"
# Main device
entity_id = "update.test_name_firmware"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_shelly_2pm_gen3_cover(
hass: HomeAssistant,
mock_rpc_device: Mock,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
monkeypatch: pytest.MonkeyPatch,
snapshot: SnapshotAssertion,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test Shelly 2PM Gen3 with cover profile.
With the cover profile we should only get the main device and no subdevices.
"""
device_fixture = await async_load_json_object_fixture(
hass, "2pm_gen3_cover.json", DOMAIN
)
monkeypatch.setattr(mock_rpc_device, "shelly", device_fixture["shelly"])
monkeypatch.setattr(mock_rpc_device, "status", device_fixture["status"])
monkeypatch.setattr(mock_rpc_device, "config", device_fixture["config"])
await force_uptime_value(hass, freezer)
config_entry = await init_integration(hass, gen=3, model=MODEL_2PM_G3)
entity_id = "cover.test_name"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
entity_id = "sensor.test_name_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
entity_id = "update.test_name_firmware"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
await snapshot_device_entities(
hass, entity_registry, snapshot, config_entry.entry_id
)
async def test_shelly_2pm_gen3_cover_with_name(
hass: HomeAssistant,
mock_rpc_device: Mock,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test Shelly 2PM Gen3 with cover profile and the cover name.
With the cover profile we should only get the main device and no subdevices.
"""
device_fixture = await async_load_json_object_fixture(
hass, "2pm_gen3_cover.json", DOMAIN
)
device_fixture["config"]["cover:0"]["name"] = "Bedroom blinds"
monkeypatch.setattr(mock_rpc_device, "shelly", device_fixture["shelly"])
monkeypatch.setattr(mock_rpc_device, "status", device_fixture["status"])
monkeypatch.setattr(mock_rpc_device, "config", device_fixture["config"])
await init_integration(hass, gen=3, model=MODEL_2PM_G3)
entity_id = "cover.test_name_bedroom_blinds"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
entity_id = "sensor.test_name_bedroom_blinds_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
entity_id = "update.test_name_firmware"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_shelly_pro_3em(
hass: HomeAssistant,
mock_rpc_device: Mock,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
monkeypatch: pytest.MonkeyPatch,
snapshot: SnapshotAssertion,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test Shelly Pro 3EM.
We should get the main device and three subdevices, one subdevice per one phase.
"""
device_fixture = await async_load_json_object_fixture(hass, "pro_3em.json", DOMAIN)
monkeypatch.setattr(mock_rpc_device, "shelly", device_fixture["shelly"])
monkeypatch.setattr(mock_rpc_device, "status", device_fixture["status"])
monkeypatch.setattr(mock_rpc_device, "config", device_fixture["config"])
await force_uptime_value(hass, freezer)
config_entry = await init_integration(hass, gen=2, model=MODEL_PRO_EM3)
# Main device
entity_id = "sensor.test_name_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
# Phase A sub-device
entity_id = "sensor.test_name_phase_a_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Phase A"
# Phase B sub-device
entity_id = "sensor.test_name_phase_b_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Phase B"
# Phase C sub-device
entity_id = "sensor.test_name_phase_c_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Phase C"
await snapshot_device_entities(
hass, entity_registry, snapshot, config_entry.entry_id
)
async def test_shelly_pro_3em_with_emeter_name(
hass: HomeAssistant,
mock_rpc_device: Mock,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test Shelly Pro 3EM when the name for Emeter is set.
We should get the main device and three subdevices, one subdevice per one phase.
"""
device_fixture = await async_load_json_object_fixture(hass, "pro_3em.json", DOMAIN)
device_fixture["config"]["em:0"]["name"] = "Emeter name"
monkeypatch.setattr(mock_rpc_device, "shelly", device_fixture["shelly"])
monkeypatch.setattr(mock_rpc_device, "status", device_fixture["status"])
monkeypatch.setattr(mock_rpc_device, "config", device_fixture["config"])
await init_integration(hass, gen=2, model=MODEL_PRO_EM3)
# Main device
entity_id = "sensor.test_name_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
# Phase A sub-device
entity_id = "sensor.test_name_phase_a_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Phase A"
# Phase B sub-device
entity_id = "sensor.test_name_phase_b_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Phase B"
# Phase C sub-device
entity_id = "sensor.test_name_phase_c_power"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name Phase C"
async def test_shelly_fk_06x_with_zone_names(
hass: HomeAssistant,
mock_rpc_device: Mock,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Test Shelly Irrigation controller FK-06X with zone names.
We should get the main device and 6 subdevices, one subdevice per one zone.
"""
device_fixture = await async_load_json_object_fixture(
hass, "fk-06x_gen3_irrigation.json", DOMAIN
)
monkeypatch.setattr(mock_rpc_device, "shelly", device_fixture["shelly"])
monkeypatch.setattr(mock_rpc_device, "status", device_fixture["status"])
monkeypatch.setattr(mock_rpc_device, "config", device_fixture["config"])
await init_integration(hass, gen=3, model=MODEL_FRANKEVER_IRRIGATION_CONTROLLER)
# Main device
entity_id = "sensor.test_name_average_temperature"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
# 3 zones with names, 3 with default names
zone_names = [
"Zone Name 1",
"Zone Name 2",
"Zone Name 3",
"Zone 4",
"Zone 5",
"Zone 6",
]
for zone_name in zone_names:
entity_id = f"valve.{zone_name.lower().replace(' ', '_')}"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == zone_name
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_block_channel_with_name(
hass: HomeAssistant,
mock_block_device: Mock,
monkeypatch: pytest.MonkeyPatch,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
) -> None:
"""Test block channel with name."""
monkeypatch.setitem(
mock_block_device.settings["relays"][0], "name", "Kitchen light"
)
await init_integration(hass, 1)
# channel 1 sub-device; num_outputs is 2 so the name of the channel should be used
entity_id = "switch.kitchen_light"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Kitchen light"
# main device
entity_id = "update.test_name_firmware"
state = hass.states.get(entity_id)
assert state
entry = entity_registry.async_get(entity_id)
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "Test name"
async def test_blu_trv_device_info(
hass: HomeAssistant,
mock_blu_trv: Mock,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
) -> None:
"""Test BLU TRV device info."""
await init_integration(hass, 3, model=MODEL_BLU_GATEWAY_G3)
entry = entity_registry.async_get("climate.trv_name")
assert entry
device_entry = device_registry.async_get(entry.device_id)
assert device_entry
assert device_entry.name == "TRV-Name"
assert device_entry.model_id == "SBTR-001AEU"
assert device_entry.sw_version == "v1.2.10"
@pytest.mark.parametrize(
"fixture",
[
"cury_gen4",
"duo_bulb_gen3",
"power_strip_gen4",
"presence_gen4",
"wall_display_xl",
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_device(
hass: HomeAssistant,
mock_rpc_device: Mock,
entity_registry: EntityRegistry,
snapshot: SnapshotAssertion,
monkeypatch: pytest.MonkeyPatch,
freezer: FrozenDateTimeFactory,
fixture: str,
) -> None:
"""Test device."""
device_fixture = await async_load_json_object_fixture(
hass, f"{fixture}.json", DOMAIN
)
monkeypatch.setattr(mock_rpc_device, "shelly", device_fixture["shelly"])
monkeypatch.setattr(mock_rpc_device, "status", device_fixture["status"])
monkeypatch.setattr(mock_rpc_device, "config", device_fixture["config"])
model = device_fixture["shelly"]["model"]
gen = device_fixture["shelly"]["gen"]
await force_uptime_value(hass, freezer)
config_entry = await init_integration(hass, gen=gen, model=model)
await snapshot_device_entities(
hass, entity_registry, snapshot, config_entry.entry_id
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/shelly/test_devices.py",
"license": "Apache License 2.0",
"lines": 466,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/smarla/const.py | """Constants for the Smarla integration tests."""
import base64
import json
from homeassistant.const import CONF_ACCESS_TOKEN
def _make_mock_user_input(token_json):
access_token = base64.b64encode(json.dumps(token_json).encode()).decode()
return {CONF_ACCESS_TOKEN: access_token}
MOCK_ACCESS_TOKEN_JSON = {
"refreshToken": "test",
"appIdentifier": "HA-test",
"serialNumber": "ABCD",
}
MOCK_USER_INPUT = _make_mock_user_input(MOCK_ACCESS_TOKEN_JSON)
MOCK_ACCESS_TOKEN_JSON_RECONFIGURE = {
**MOCK_ACCESS_TOKEN_JSON,
"refreshToken": "reconfiguretest",
}
MOCK_USER_INPUT_RECONFIGURE = _make_mock_user_input(MOCK_ACCESS_TOKEN_JSON_RECONFIGURE)
MOCK_ACCESS_TOKEN_JSON_MISMATCH = {
**MOCK_ACCESS_TOKEN_JSON_RECONFIGURE,
"serialNumber": "DCBA",
}
MOCK_USER_INPUT_MISMATCH = _make_mock_user_input(MOCK_ACCESS_TOKEN_JSON_MISMATCH)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/smarla/const.py",
"license": "Apache License 2.0",
"lines": 23,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/smarla/test_config_flow.py | """Test config flow for Swing2Sleep Smarla integration."""
from unittest.mock import MagicMock, patch
from pysmarlaapi.connection.exceptions import (
AuthenticationException,
ConnectionException,
)
import pytest
from homeassistant.components.smarla.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import (
MOCK_ACCESS_TOKEN_JSON,
MOCK_USER_INPUT,
MOCK_USER_INPUT_MISMATCH,
MOCK_USER_INPUT_RECONFIGURE,
)
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_setup_entry", "mock_connection")
async def test_config_flow(hass: HomeAssistant) -> None:
"""Test creating a 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"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == MOCK_ACCESS_TOKEN_JSON["serialNumber"]
assert result["data"] == MOCK_USER_INPUT
assert result["result"].unique_id == MOCK_ACCESS_TOKEN_JSON["serialNumber"]
@pytest.mark.usefixtures("mock_setup_entry", "mock_connection")
async def test_malformed_token(hass: HomeAssistant) -> None:
"""Test we show user form on malformed token input."""
with patch(
"homeassistant.components.smarla.config_flow.Connection", side_effect=ValueError
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=MOCK_USER_INPUT,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "malformed_token"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
("exception", "error_key"),
[
(AuthenticationException, "invalid_auth"),
(ConnectionException, "cannot_connect"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_validation_exception(
hass: HomeAssistant,
mock_connection: MagicMock,
exception: type[Exception],
error_key: str,
) -> None:
"""Test we show user form on validation exception."""
mock_connection.refresh_token.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=MOCK_USER_INPUT,
)
mock_connection.refresh_token.side_effect = None
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": error_key}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.usefixtures("mock_setup_entry", "mock_connection")
async def test_device_exists_abort(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test we abort config flow if Smarla device already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=MOCK_USER_INPUT,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
@pytest.mark.usefixtures("mock_setup_entry", "mock_connection")
async def test_reauth_successful(
mock_config_entry: MockConfigEntry,
hass: HomeAssistant,
) -> None:
"""Test a successful reauthentication flow."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
result = await 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=MOCK_USER_INPUT_RECONFIGURE,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == MOCK_USER_INPUT_RECONFIGURE
@pytest.mark.usefixtures("mock_setup_entry", "mock_connection")
async def test_reauth_mismatch(
mock_config_entry: MockConfigEntry,
hass: HomeAssistant,
) -> None:
"""Test a reauthentication flow with mismatched 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()
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=MOCK_USER_INPUT_MISMATCH,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
assert mock_config_entry.data == MOCK_USER_INPUT
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/smarla/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 136,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/smarla/test_init.py | """Test switch platform for Swing2Sleep Smarla integration."""
from collections.abc import Awaitable, Callable
from unittest.mock import MagicMock
from pysmarlaapi.connection.exceptions import (
AuthenticationException,
ConnectionException,
)
import pytest
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
("exception", "expected_state"),
[
(AuthenticationException, ConfigEntryState.SETUP_ERROR),
(ConnectionException, ConfigEntryState.SETUP_RETRY),
],
)
@pytest.mark.usefixtures("mock_federwiege")
async def test_init_exception(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
exception: type[Exception],
expected_state: ConfigEntryState,
) -> None:
"""Test init config setup exception."""
mock_connection.refresh_token.side_effect = exception
assert not await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is expected_state
async def test_init_auth_failure_during_runtime(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_federwiege_cls: MagicMock,
) -> None:
"""Test behavior on invalid authentication during runtime."""
invalid_auth_callback: Callable[[], Awaitable[None]] | None = None
def mocked_federwiege(_1, _2, callback):
nonlocal invalid_auth_callback
invalid_auth_callback = callback
return mock_federwiege_cls.return_value
# Mock Federwiege class to gather authentication failure callback
mock_federwiege_cls.side_effect = mocked_federwiege
assert await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
# Check that config entry has no active reauth flows
assert not any(mock_config_entry.async_get_active_flows(hass, {"reauth"}))
# Simulate authentication failure during runtime
assert invalid_auth_callback is not None
await invalid_auth_callback()
await hass.async_block_till_done()
# Check that a reauth flow has been started
assert any(mock_config_entry.async_get_active_flows(hass, {"reauth"}))
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/smarla/test_init.py",
"license": "Apache License 2.0",
"lines": 54,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/smarla/test_switch.py | """Test switch platform for Swing2Sleep Smarla integration."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration, update_property_listeners
from tests.common import MockConfigEntry, snapshot_platform
SWITCH_ENTITIES = [
{
"entity_id": "switch.smarla",
"service": "babywiege",
"property": "swing_active",
},
{
"entity_id": "switch.smarla_smart_mode",
"service": "babywiege",
"property": "smart_mode",
},
]
@pytest.mark.usefixtures("mock_federwiege")
async def test_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the Smarla entities."""
with (
patch("homeassistant.components.smarla.PLATFORMS", [Platform.SWITCH]),
):
assert await setup_integration(hass, mock_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
@pytest.mark.parametrize(
("service", "parameter"),
[
(SERVICE_TURN_ON, True),
(SERVICE_TURN_OFF, False),
],
)
@pytest.mark.parametrize("entity_info", SWITCH_ENTITIES)
async def test_switch_action(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_federwiege: MagicMock,
entity_info: dict[str, str],
service: str,
parameter: bool,
) -> None:
"""Test Smarla Switch on/off behavior."""
assert await setup_integration(hass, mock_config_entry)
mock_switch_property = mock_federwiege.get_property(
entity_info["service"], entity_info["property"]
)
entity_id = entity_info["entity_id"]
# Turn on
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_switch_property.set.assert_called_once_with(parameter)
@pytest.mark.parametrize("entity_info", SWITCH_ENTITIES)
async def test_switch_state_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_federwiege: MagicMock,
entity_info: dict[str, str],
) -> None:
"""Test Smarla Switch callback."""
assert await setup_integration(hass, mock_config_entry)
mock_switch_property = mock_federwiege.get_property(
entity_info["service"], entity_info["property"]
)
entity_id = entity_info["entity_id"]
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_OFF
mock_switch_property.get.return_value = True
await update_property_listeners(mock_switch_property)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_ON
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/smarla/test_switch.py",
"license": "Apache License 2.0",
"lines": 96,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/smartthings/test_water_heater.py | """Test for the SmartThings water heater platform."""
from unittest.mock import AsyncMock, call
from pysmartthings import Attribute, Capability, Command
from pysmartthings.models import HealthStatus
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.smartthings import MAIN
from homeassistant.components.water_heater import (
ATTR_AWAY_MODE,
ATTR_CURRENT_TEMPERATURE,
ATTR_OPERATION_LIST,
ATTR_OPERATION_MODE,
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
DOMAIN as WATER_HEATER_DOMAIN,
SERVICE_SET_AWAY_MODE,
SERVICE_SET_OPERATION_MODE,
SERVICE_SET_TEMPERATURE,
STATE_ECO,
STATE_HEAT_PUMP,
STATE_HIGH_DEMAND,
STATE_PERFORMANCE,
WaterHeaterEntityFeature,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_SUPPORTED_FEATURES,
ATTR_TEMPERATURE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import (
setup_integration,
snapshot_smartthings_entities,
trigger_health_update,
trigger_update,
)
from tests.common import MockConfigEntry
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
await setup_integration(hass, mock_config_entry)
snapshot_smartthings_entities(
hass, entity_registry, snapshot, Platform.WATER_HEATER
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
@pytest.mark.parametrize(
("operation_mode", "argument"),
[
(STATE_ECO, "eco"),
(STATE_HEAT_PUMP, "std"),
(STATE_HIGH_DEMAND, "force"),
(STATE_PERFORMANCE, "power"),
],
)
async def test_set_operation_mode(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
operation_mode: str,
argument: str,
) -> None:
"""Test set operation mode."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_OPERATION_MODE,
{
ATTR_ENTITY_ID: "water_heater.warmepumpe",
ATTR_OPERATION_MODE: operation_mode,
},
blocking=True,
)
devices.execute_device_command.assert_called_once_with(
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.AIR_CONDITIONER_MODE,
Command.SET_AIR_CONDITIONER_MODE,
MAIN,
argument=argument,
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_set_operation_mode_off(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test set operation mode to off."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_OPERATION_MODE,
{
ATTR_ENTITY_ID: "water_heater.warmepumpe",
ATTR_OPERATION_MODE: STATE_OFF,
},
blocking=True,
)
devices.execute_device_command.assert_called_once_with(
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.SWITCH,
Command.OFF,
MAIN,
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000001_sub"])
async def test_set_operation_mode_from_off(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test set operation mode."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("water_heater.eco_heating_system").state == STATE_OFF
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_OPERATION_MODE,
{
ATTR_ENTITY_ID: "water_heater.eco_heating_system",
ATTR_OPERATION_MODE: STATE_ECO,
},
blocking=True,
)
assert devices.execute_device_command.mock_calls == [
call(
"1f98ebd0-ac48-d802-7f62-000001200100",
Capability.SWITCH,
Command.ON,
MAIN,
),
call(
"1f98ebd0-ac48-d802-7f62-000001200100",
Capability.AIR_CONDITIONER_MODE,
Command.SET_AIR_CONDITIONER_MODE,
MAIN,
argument="eco",
),
]
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_set_operation_to_off(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test set operation mode to off."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_OPERATION_MODE,
{
ATTR_ENTITY_ID: "water_heater.warmepumpe",
ATTR_OPERATION_MODE: STATE_OFF,
},
blocking=True,
)
devices.execute_device_command.assert_called_once_with(
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.SWITCH,
Command.OFF,
MAIN,
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
@pytest.mark.parametrize(
("service", "command"),
[
(SERVICE_TURN_ON, Command.ON),
(SERVICE_TURN_OFF, Command.OFF),
],
)
async def test_turn_on_off(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
service: str,
command: Command,
) -> None:
"""Test turn on and off."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
WATER_HEATER_DOMAIN,
service,
{
ATTR_ENTITY_ID: "water_heater.warmepumpe",
},
blocking=True,
)
devices.execute_device_command.assert_called_once_with(
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.SWITCH,
command,
MAIN,
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_set_temperature(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test set operation mode."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "water_heater.warmepumpe",
ATTR_TEMPERATURE: 56,
},
blocking=True,
)
devices.execute_device_command.assert_called_once_with(
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.THERMOSTAT_COOLING_SETPOINT,
Command.SET_COOLING_SETPOINT,
MAIN,
argument=56,
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
@pytest.mark.parametrize(
("on", "argument"),
[
(True, "on"),
(False, "off"),
],
)
async def test_away_mode(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
on: bool,
argument: str,
) -> None:
"""Test set away mode."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_AWAY_MODE,
{
ATTR_ENTITY_ID: "water_heater.warmepumpe",
ATTR_AWAY_MODE: on,
},
blocking=True,
)
devices.execute_device_command.assert_called_once_with(
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.CUSTOM_OUTING_MODE,
Command.SET_OUTING_MODE,
MAIN,
argument=argument,
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_operation_list_update(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test state update."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("water_heater.warmepumpe").attributes[
ATTR_OPERATION_LIST
] == [
STATE_OFF,
STATE_ECO,
STATE_HEAT_PUMP,
STATE_PERFORMANCE,
STATE_HIGH_DEMAND,
]
await trigger_update(
hass,
devices,
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.AIR_CONDITIONER_MODE,
Attribute.SUPPORTED_AC_MODES,
["eco", "force", "power"],
)
assert hass.states.get("water_heater.warmepumpe").attributes[
ATTR_OPERATION_LIST
] == [
STATE_OFF,
STATE_ECO,
STATE_HIGH_DEMAND,
STATE_PERFORMANCE,
]
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_current_operation_update(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test state update."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("water_heater.warmepumpe").state == STATE_HEAT_PUMP
await trigger_update(
hass,
devices,
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.AIR_CONDITIONER_MODE,
Attribute.AIR_CONDITIONER_MODE,
"eco",
)
assert hass.states.get("water_heater.warmepumpe").state == STATE_ECO
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_switch_update(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test state update."""
await setup_integration(hass, mock_config_entry)
state = hass.states.get("water_heater.warmepumpe")
assert state.state == STATE_HEAT_PUMP
assert (
state.attributes[ATTR_SUPPORTED_FEATURES]
== WaterHeaterEntityFeature.ON_OFF
| WaterHeaterEntityFeature.TARGET_TEMPERATURE
| WaterHeaterEntityFeature.OPERATION_MODE
| WaterHeaterEntityFeature.AWAY_MODE
)
await trigger_update(
hass,
devices,
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.SWITCH,
Attribute.SWITCH,
"off",
)
state = hass.states.get("water_heater.warmepumpe")
assert state.state == STATE_OFF
assert (
state.attributes[ATTR_SUPPORTED_FEATURES]
== WaterHeaterEntityFeature.ON_OFF
| WaterHeaterEntityFeature.OPERATION_MODE
| WaterHeaterEntityFeature.AWAY_MODE
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_current_temperature_update(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test state update."""
await setup_integration(hass, mock_config_entry)
assert (
hass.states.get("water_heater.warmepumpe").attributes[ATTR_CURRENT_TEMPERATURE]
== 49.6
)
await trigger_update(
hass,
devices,
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.TEMPERATURE_MEASUREMENT,
Attribute.TEMPERATURE,
50.0,
)
assert (
hass.states.get("water_heater.warmepumpe").attributes[ATTR_CURRENT_TEMPERATURE]
== 50.0
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_target_temperature_update(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test state update."""
await setup_integration(hass, mock_config_entry)
assert (
hass.states.get("water_heater.warmepumpe").attributes[ATTR_TEMPERATURE] == 52.0
)
await trigger_update(
hass,
devices,
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.THERMOSTAT_COOLING_SETPOINT,
Attribute.COOLING_SETPOINT,
50.0,
)
assert (
hass.states.get("water_heater.warmepumpe").attributes[ATTR_TEMPERATURE] == 50.0
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
@pytest.mark.parametrize(
("attribute", "old_value", "state_attribute"),
[
(Attribute.MINIMUM_SETPOINT, 40, ATTR_TARGET_TEMP_LOW),
(Attribute.MAXIMUM_SETPOINT, 57, ATTR_TARGET_TEMP_HIGH),
],
)
async def test_target_temperature_bound_update(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
attribute: Attribute,
old_value: float,
state_attribute: str,
) -> None:
"""Test state update."""
await setup_integration(hass, mock_config_entry)
assert (
hass.states.get("water_heater.warmepumpe").attributes[state_attribute]
== old_value
)
await trigger_update(
hass,
devices,
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.CUSTOM_THERMOSTAT_SETPOINT_CONTROL,
attribute,
50.0,
)
assert (
hass.states.get("water_heater.warmepumpe").attributes[state_attribute] == 50.0
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_away_mode_update(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test state update."""
await setup_integration(hass, mock_config_entry)
assert (
hass.states.get("water_heater.warmepumpe").attributes[ATTR_AWAY_MODE]
== STATE_OFF
)
await trigger_update(
hass,
devices,
"3810e5ad-5351-d9f9-12ff-000001200000",
Capability.CUSTOM_OUTING_MODE,
Attribute.OUTING_MODE,
"on",
)
assert (
hass.states.get("water_heater.warmepumpe").attributes[ATTR_AWAY_MODE]
== STATE_ON
)
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_availability(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test availability."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("water_heater.warmepumpe").state == STATE_HEAT_PUMP
await trigger_health_update(
hass, devices, "3810e5ad-5351-d9f9-12ff-000001200000", HealthStatus.OFFLINE
)
assert hass.states.get("water_heater.warmepumpe").state == STATE_UNAVAILABLE
await trigger_health_update(
hass, devices, "3810e5ad-5351-d9f9-12ff-000001200000", HealthStatus.ONLINE
)
assert hass.states.get("water_heater.warmepumpe").state == STATE_HEAT_PUMP
@pytest.mark.parametrize("device_fixture", ["da_sac_ehs_000002_sub"])
async def test_availability_at_start(
hass: HomeAssistant,
unavailable_device: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test unavailable at boot."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("water_heater.warmepumpe").state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/smartthings/test_water_heater.py",
"license": "Apache License 2.0",
"lines": 471,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/squeezebox/test_switch.py | """Tests for the Squeezebox alarm switch platform."""
from datetime import timedelta
from unittest.mock import MagicMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.squeezebox.const import PLAYER_UPDATE_INTERVAL
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
CONF_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import EntityRegistry
from .conftest import TEST_ALARM_ID
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.fixture(autouse=True)
def squeezebox_alarm_platform():
"""Only set up the switch platform for squeezebox tests."""
with patch("homeassistant.components.squeezebox.PLATFORMS", [Platform.SWITCH]):
yield
@pytest.fixture
async def mock_alarms_player(
hass: HomeAssistant,
config_entry: MockConfigEntry,
lms: MagicMock,
) -> MagicMock:
"""Mock the alarms of a configured player."""
players = await lms.async_get_players()
players[0].alarms = [
{
"id": TEST_ALARM_ID,
"enabled": True,
"time": "07:00",
"dow": [0, 1, 2, 3, 4, 5, 6],
"repeat": False,
"url": "CURRENT_PLAYLIST",
"volume": 50,
},
]
with patch("homeassistant.components.squeezebox.Server", return_value=lms):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return players[0]
async def test_entity_registry(
hass: HomeAssistant,
entity_registry: EntityRegistry,
mock_alarms_player: MagicMock,
snapshot: SnapshotAssertion,
config_entry: MockConfigEntry,
) -> None:
"""Test squeezebox media_player entity registered in the entity registry."""
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
async def test_switch_state(
hass: HomeAssistant,
mock_alarms_player: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test the state of the switch."""
assert hass.states.get(f"switch.alarm_{TEST_ALARM_ID}").state == "on"
mock_alarms_player.alarms[0]["enabled"] = False
freezer.tick(timedelta(seconds=PLAYER_UPDATE_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(f"switch.alarm_{TEST_ALARM_ID}").state == "off"
async def test_switch_deleted(
hass: HomeAssistant,
mock_alarms_player: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test detecting switch deleted."""
assert hass.states.get(f"switch.alarm_{TEST_ALARM_ID}").state == "on"
mock_alarms_player.alarms = []
freezer.tick(timedelta(seconds=PLAYER_UPDATE_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(f"switch.alarm_{TEST_ALARM_ID}") is None
async def test_turn_on(
hass: HomeAssistant,
mock_alarms_player: MagicMock,
) -> None:
"""Test turning on the switch."""
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{CONF_ENTITY_ID: f"switch.alarm_{TEST_ALARM_ID}"},
blocking=True,
)
mock_alarms_player.async_update_alarm.assert_called_once_with(
TEST_ALARM_ID, enabled=True
)
async def test_turn_off(
hass: HomeAssistant,
mock_alarms_player: MagicMock,
) -> None:
"""Test turning on the switch."""
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{CONF_ENTITY_ID: f"switch.alarm_{TEST_ALARM_ID}"},
blocking=True,
)
mock_alarms_player.async_update_alarm.assert_called_once_with(
TEST_ALARM_ID, enabled=False
)
async def test_alarms_enabled_state(
hass: HomeAssistant,
mock_alarms_player: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test the alarms enabled switch."""
assert hass.states.get("switch.alarms_enabled").state == "on"
mock_alarms_player.alarms_enabled = False
freezer.tick(timedelta(seconds=PLAYER_UPDATE_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get("switch.alarms_enabled").state == "off"
async def test_alarms_enabled_turn_on(
hass: HomeAssistant,
mock_alarms_player: MagicMock,
) -> None:
"""Test turning on the alarms enabled switch."""
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{CONF_ENTITY_ID: "switch.alarms_enabled"},
blocking=True,
)
mock_alarms_player.async_set_alarms_enabled.assert_called_once_with(True)
async def test_alarms_enabled_turn_off(
hass: HomeAssistant,
mock_alarms_player: MagicMock,
) -> None:
"""Test turning off the alarms enabled switch."""
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{CONF_ENTITY_ID: "switch.alarms_enabled"},
blocking=True,
)
mock_alarms_player.async_set_alarms_enabled.assert_called_once_with(False)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/squeezebox/test_switch.py",
"license": "Apache License 2.0",
"lines": 143,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/squeezebox/test_update.py | """Test squeezebox update platform."""
import copy
from datetime import timedelta
from unittest.mock import patch
import pytest
from homeassistant.components.squeezebox.const import (
SENSOR_UPDATE_INTERVAL,
STATUS_UPDATE_NEWPLUGINS,
)
from homeassistant.components.update import (
ATTR_IN_PROGRESS,
DOMAIN as UPDATE_DOMAIN,
SERVICE_INSTALL,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util import dt as dt_util
from .conftest import FAKE_QUERY_RESPONSE
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_update_lms(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test binary sensor states and attributes."""
# Setup component
with (
patch(
"homeassistant.components.squeezebox.PLATFORMS",
[Platform.UPDATE],
),
patch(
"homeassistant.components.squeezebox.Server.async_query",
return_value=copy.deepcopy(FAKE_QUERY_RESPONSE),
),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("update.fakelib_lyrion_music_server")
assert state is not None
assert state.state == STATE_ON
async def test_update_plugins_install_fallback(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test binary sensor states and attributes."""
entity_id = "update.fakelib_updated_plugins"
# Setup component
with (
patch(
"homeassistant.components.squeezebox.PLATFORMS",
[Platform.UPDATE],
),
patch(
"homeassistant.components.squeezebox.Server.async_query",
return_value=copy.deepcopy(FAKE_QUERY_RESPONSE),
),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_ON
polltime = 30
with (
patch(
"homeassistant.components.squeezebox.Server.async_query",
return_value=False,
),
patch(
"homeassistant.components.squeezebox.update.POLL_AFTER_INSTALL",
polltime,
),
):
await hass.services.async_call(
UPDATE_DOMAIN,
SERVICE_INSTALL,
{
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
state = hass.states.get(entity_id)
attrs = state.attributes
assert attrs[ATTR_IN_PROGRESS]
with (
patch(
"homeassistant.components.squeezebox.Server.async_status",
return_value=copy.deepcopy(FAKE_QUERY_RESPONSE),
),
):
async_fire_time_changed(
hass,
dt_util.utcnow() + timedelta(seconds=polltime + 1),
)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_ON
attrs = state.attributes
assert not attrs[ATTR_IN_PROGRESS]
async def test_update_plugins_install_restart_fail(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test binary sensor states and attributes."""
entity_id = "update.fakelib_updated_plugins"
# Setup component
with (
patch(
"homeassistant.components.squeezebox.PLATFORMS",
[Platform.UPDATE],
),
patch(
"homeassistant.components.squeezebox.Server.async_query",
return_value=copy.deepcopy(FAKE_QUERY_RESPONSE),
),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done(wait_background_tasks=True)
with (
patch(
"homeassistant.components.squeezebox.Server.async_query",
return_value=True,
),
pytest.raises(HomeAssistantError),
):
await hass.services.async_call(
UPDATE_DOMAIN,
SERVICE_INSTALL,
{
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_ON
attrs = state.attributes
assert not attrs[ATTR_IN_PROGRESS]
async def test_update_plugins_install_ok(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test binary sensor states and attributes."""
entity_id = "update.fakelib_updated_plugins"
# Setup component
with (
patch(
"homeassistant.components.squeezebox.PLATFORMS",
[Platform.UPDATE],
),
patch(
"homeassistant.components.squeezebox.Server.async_query",
return_value=copy.deepcopy(FAKE_QUERY_RESPONSE),
),
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done(wait_background_tasks=True)
with (
patch(
"homeassistant.components.squeezebox.Server.async_query",
return_value=False,
),
):
await hass.services.async_call(
UPDATE_DOMAIN,
SERVICE_INSTALL,
{
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_ON
attrs = state.attributes
assert attrs[ATTR_IN_PROGRESS]
resp = copy.deepcopy(FAKE_QUERY_RESPONSE)
del resp[STATUS_UPDATE_NEWPLUGINS]
with (
patch(
"homeassistant.components.squeezebox.Server.async_status",
return_value=resp,
),
patch(
"homeassistant.components.squeezebox.Server.async_query",
return_value=copy.deepcopy(FAKE_QUERY_RESPONSE),
),
):
async_fire_time_changed(
hass,
dt_util.utcnow() + timedelta(seconds=SENSOR_UPDATE_INTERVAL + 1),
)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_OFF
attrs = state.attributes
assert not attrs[ATTR_IN_PROGRESS]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/squeezebox/test_update.py",
"license": "Apache License 2.0",
"lines": 200,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/sun/test_condition.py | """The tests for sun conditions."""
from datetime import datetime
from freezegun import freeze_time
import pytest
from homeassistant.components import automation
from homeassistant.const import SUN_EVENT_SUNRISE, SUN_EVENT_SUNSET
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import trace
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.typing import WebSocketGenerator
@pytest.fixture(autouse=True)
def prepare_condition_trace() -> None:
"""Clear previous trace."""
trace.trace_clear()
def _find_run_id(traces, trace_type, item_id):
"""Find newest run_id for a script or automation."""
for _trace in reversed(traces):
if _trace["domain"] == trace_type and _trace["item_id"] == item_id:
return _trace["run_id"]
return None
async def assert_automation_condition_trace(hass_ws_client, automation_id, expected):
"""Test the result of automation condition."""
msg_id = 1
def next_id():
nonlocal msg_id
msg_id += 1
return msg_id
client = await hass_ws_client()
# List traces
await client.send_json(
{"id": next_id(), "type": "trace/list", "domain": "automation"}
)
response = await client.receive_json()
assert response["success"]
run_id = _find_run_id(response["result"], "automation", automation_id)
# Get trace
await client.send_json(
{
"id": next_id(),
"type": "trace/get",
"domain": "automation",
"item_id": "sun",
"run_id": run_id,
}
)
response = await client.receive_json()
assert response["success"]
trace = response["result"]
assert len(trace["trace"]["condition/0"]) == 1
condition_trace = trace["trace"]["condition/0"][0]["result"]
assert condition_trace == expected
async def test_if_action_before_sunrise_no_offset(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was before sunrise.
Before sunrise is true from midnight until sunset, local time.
"""
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"before": SUN_EVENT_SUNRISE},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-09-16 06:33:18 local, sunset: 2015-09-16 18:53:45 local
# sunrise: 2015-09-16 13:33:18 UTC, sunset: 2015-09-17 01:53:45 UTC
# now = sunrise + 1s -> 'before sunrise' not true
now = datetime(2015, 9, 16, 13, 33, 19, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 0
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-16T13:33:18.342542+00:00"},
)
# now = sunrise -> 'before sunrise' true
now = datetime(2015, 9, 16, 13, 33, 18, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-16T13:33:18.342542+00:00"},
)
# now = local midnight -> 'before sunrise' true
now = datetime(2015, 9, 16, 7, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-16T13:33:18.342542+00:00"},
)
# now = local midnight - 1s -> 'before sunrise' not true
now = datetime(2015, 9, 17, 6, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-16T13:33:18.342542+00:00"},
)
async def test_if_action_after_sunrise_no_offset(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was after sunrise.
After sunrise is true from sunrise until midnight, local time.
"""
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"after": SUN_EVENT_SUNRISE},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-09-16 06:33:18 local, sunset: 2015-09-16 18:53:45 local
# sunrise: 2015-09-16 13:33:18 UTC, sunset: 2015-09-17 01:53:45 UTC
# now = sunrise - 1s -> 'after sunrise' not true
now = datetime(2015, 9, 16, 13, 33, 17, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 0
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-09-16T13:33:18.342542+00:00"},
)
# now = sunrise + 1s -> 'after sunrise' true
now = datetime(2015, 9, 16, 13, 33, 19, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-16T13:33:18.342542+00:00"},
)
# now = local midnight -> 'after sunrise' not true
now = datetime(2015, 9, 16, 7, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-09-16T13:33:18.342542+00:00"},
)
# now = local midnight - 1s -> 'after sunrise' true
now = datetime(2015, 9, 17, 6, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-16T13:33:18.342542+00:00"},
)
async def test_if_action_before_sunrise_with_offset(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was before sunrise with offset.
Before sunrise is true from midnight until sunset, local time.
"""
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {
"before": SUN_EVENT_SUNRISE,
"before_offset": "+1:00:00",
},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-09-16 06:33:18 local, sunset: 2015-09-16 18:53:45 local
# sunrise: 2015-09-16 13:33:18 UTC, sunset: 2015-09-17 01:53:45 UTC
# now = sunrise + 1s + 1h -> 'before sunrise' with offset +1h not true
now = datetime(2015, 9, 16, 14, 33, 19, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 0
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-16T14:33:18.342542+00:00"},
)
# now = sunrise + 1h -> 'before sunrise' with offset +1h true
now = datetime(2015, 9, 16, 14, 33, 18, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-16T14:33:18.342542+00:00"},
)
# now = UTC midnight -> 'before sunrise' with offset +1h not true
now = datetime(2015, 9, 17, 0, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-16T14:33:18.342542+00:00"},
)
# now = UTC midnight - 1s -> 'before sunrise' with offset +1h not true
now = datetime(2015, 9, 16, 23, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-16T14:33:18.342542+00:00"},
)
# now = local midnight -> 'before sunrise' with offset +1h true
now = datetime(2015, 9, 16, 7, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-16T14:33:18.342542+00:00"},
)
# now = local midnight - 1s -> 'before sunrise' with offset +1h not true
now = datetime(2015, 9, 17, 6, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-16T14:33:18.342542+00:00"},
)
# now = sunset -> 'before sunrise' with offset +1h not true
now = datetime(2015, 9, 17, 1, 53, 45, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-16T14:33:18.342542+00:00"},
)
# now = sunset -1s -> 'before sunrise' with offset +1h not true
now = datetime(2015, 9, 17, 1, 53, 44, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-16T14:33:18.342542+00:00"},
)
async def test_if_action_before_sunset_with_offset(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was before sunset with offset.
Before sunset is true from midnight until sunset, local time.
"""
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"before": "sunset", "before_offset": "+1:00:00"},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-09-16 06:33:18 local, sunset: 2015-09-16 18:53:45 local
# sunrise: 2015-09-16 13:33:18 UTC, sunset: 2015-09-17 01:53:45 UTC
# now = local midnight -> 'before sunset' with offset +1h true
now = datetime(2015, 9, 16, 7, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-17T02:53:44.723614+00:00"},
)
# now = sunset + 1s + 1h -> 'before sunset' with offset +1h not true
now = datetime(2015, 9, 17, 2, 53, 46, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-17T02:53:44.723614+00:00"},
)
# now = sunset + 1h -> 'before sunset' with offset +1h true
now = datetime(2015, 9, 17, 2, 53, 44, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-17T02:53:44.723614+00:00"},
)
# now = UTC midnight -> 'before sunset' with offset +1h true
now = datetime(2015, 9, 17, 0, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 3
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-17T02:53:44.723614+00:00"},
)
# now = UTC midnight - 1s -> 'before sunset' with offset +1h true
now = datetime(2015, 9, 16, 23, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 4
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-17T02:53:44.723614+00:00"},
)
# now = sunrise -> 'before sunset' with offset +1h true
now = datetime(2015, 9, 16, 13, 33, 18, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 5
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-17T02:53:44.723614+00:00"},
)
# now = sunrise -1s -> 'before sunset' with offset +1h true
now = datetime(2015, 9, 16, 13, 33, 17, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 6
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-09-17T02:53:44.723614+00:00"},
)
# now = local midnight-1s -> 'after sunrise' with offset +1h not true
now = datetime(2015, 9, 17, 6, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 6
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-17T02:53:44.723614+00:00"},
)
async def test_if_action_after_sunrise_with_offset(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was after sunrise with offset.
After sunrise is true from sunrise until midnight, local time.
"""
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"after": SUN_EVENT_SUNRISE, "after_offset": "+1:00:00"},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-09-16 06:33:18 local, sunset: 2015-09-16 18:53:45 local
# sunrise: 2015-09-16 13:33:18 UTC, sunset: 2015-09-17 01:53:45 UTC
# now = sunrise - 1s + 1h -> 'after sunrise' with offset +1h not true
now = datetime(2015, 9, 16, 14, 33, 17, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 0
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-09-16T14:33:18.342542+00:00"},
)
# now = sunrise + 1h -> 'after sunrise' with offset +1h true
now = datetime(2015, 9, 16, 14, 33, 58, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-16T14:33:18.342542+00:00"},
)
# now = UTC noon -> 'after sunrise' with offset +1h not true
now = datetime(2015, 9, 16, 12, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-09-16T14:33:18.342542+00:00"},
)
# now = UTC noon - 1s -> 'after sunrise' with offset +1h not true
now = datetime(2015, 9, 16, 11, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-09-16T14:33:18.342542+00:00"},
)
# now = local noon -> 'after sunrise' with offset +1h true
now = datetime(2015, 9, 16, 19, 1, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-16T14:33:18.342542+00:00"},
)
# now = local noon - 1s -> 'after sunrise' with offset +1h true
now = datetime(2015, 9, 16, 18, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 3
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-16T14:33:18.342542+00:00"},
)
# now = sunset -> 'after sunrise' with offset +1h true
now = datetime(2015, 9, 17, 1, 53, 45, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 4
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-16T14:33:18.342542+00:00"},
)
# now = sunset + 1s -> 'after sunrise' with offset +1h true
now = datetime(2015, 9, 17, 1, 53, 45, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 5
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-16T14:33:18.342542+00:00"},
)
# now = local midnight-1s -> 'after sunrise' with offset +1h true
now = datetime(2015, 9, 17, 6, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 6
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-16T14:33:18.342542+00:00"},
)
# now = local midnight -> 'after sunrise' with offset +1h not true
now = datetime(2015, 9, 17, 7, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 6
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-09-17T14:33:57.053037+00:00"},
)
async def test_if_action_after_sunset_with_offset(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was after sunset with offset.
After sunset is true from sunset until midnight, local time.
"""
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"after": "sunset", "after_offset": "+1:00:00"},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-09-16 06:33:18 local, sunset: 2015-09-16 18:53:45 local
# sunrise: 2015-09-16 13:33:18 UTC, sunset: 2015-09-17 01:53:45 UTC
# now = sunset - 1s + 1h -> 'after sunset' with offset +1h not true
now = datetime(2015, 9, 17, 2, 53, 44, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 0
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-09-17T02:53:44.723614+00:00"},
)
# now = sunset + 1h -> 'after sunset' with offset +1h true
now = datetime(2015, 9, 17, 2, 53, 45, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-17T02:53:44.723614+00:00"},
)
# now = midnight-1s -> 'after sunset' with offset +1h true
now = datetime(2015, 9, 16, 6, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-09-16T02:55:06.099767+00:00"},
)
# now = midnight -> 'after sunset' with offset +1h not true
now = datetime(2015, 9, 16, 7, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-09-17T02:53:44.723614+00:00"},
)
async def test_if_action_after_and_before_during(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was after sunrise and before sunset.
This is true from sunrise until sunset.
"""
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"after": SUN_EVENT_SUNRISE, "before": SUN_EVENT_SUNSET},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-09-16 06:33:18 local, sunset: 2015-09-16 18:53:45 local
# sunrise: 2015-09-16 13:33:18 UTC, sunset: 2015-09-17 01:53:45 UTC
# now = sunrise - 1s -> 'after sunrise' + 'before sunset' not true
now = datetime(2015, 9, 16, 13, 33, 17, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 0
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": False,
"wanted_time_before": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_after": "2015-09-16T13:33:18.342542+00:00",
},
)
# now = sunset + 1s -> 'after sunrise' + 'before sunset' not true
now = datetime(2015, 9, 17, 1, 53, 46, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 0
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-09-17T01:53:44.723614+00:00"},
)
# now = sunrise + 1s -> 'after sunrise' + 'before sunset' true
now = datetime(2015, 9, 16, 13, 33, 19, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": True,
"wanted_time_before": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_after": "2015-09-16T13:33:18.342542+00:00",
},
)
# now = sunset - 1s -> 'after sunrise' + 'before sunset' true
now = datetime(2015, 9, 17, 1, 53, 44, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": True,
"wanted_time_before": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_after": "2015-09-16T13:33:18.342542+00:00",
},
)
# now = 9AM local -> 'after sunrise' + 'before sunset' true
now = datetime(2015, 9, 16, 16, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 3
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": True,
"wanted_time_before": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_after": "2015-09-16T13:33:18.342542+00:00",
},
)
async def test_if_action_before_or_after_during(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was before sunrise or after sunset.
This is true from midnight until sunrise and from sunset until midnight
"""
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"before": SUN_EVENT_SUNRISE, "after": SUN_EVENT_SUNSET},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-09-16 06:33:18 local, sunset: 2015-09-16 18:53:45 local
# sunrise: 2015-09-16 13:33:18 UTC, sunset: 2015-09-17 01:53:45 UTC
# now = sunrise - 1s -> 'before sunrise' | 'after sunset' true
now = datetime(2015, 9, 16, 13, 33, 17, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": True,
"wanted_time_after": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_before": "2015-09-16T13:33:18.342542+00:00",
},
)
# now = sunset + 1s -> 'before sunrise' | 'after sunset' true
now = datetime(2015, 9, 17, 1, 53, 46, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": True,
"wanted_time_after": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_before": "2015-09-16T13:33:18.342542+00:00",
},
)
# now = sunrise + 1s -> 'before sunrise' | 'after sunset' false
now = datetime(2015, 9, 16, 13, 33, 19, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": False,
"wanted_time_after": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_before": "2015-09-16T13:33:18.342542+00:00",
},
)
# now = sunset - 1s -> 'before sunrise' | 'after sunset' false
now = datetime(2015, 9, 17, 1, 53, 44, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": False,
"wanted_time_after": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_before": "2015-09-16T13:33:18.342542+00:00",
},
)
# now = midnight + 1s local -> 'before sunrise' | 'after sunset' true
now = datetime(2015, 9, 16, 7, 0, 1, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 3
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": True,
"wanted_time_after": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_before": "2015-09-16T13:33:18.342542+00:00",
},
)
# now = midnight - 1s local -> 'before sunrise' | 'after sunset' true
now = datetime(2015, 9, 17, 6, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 4
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{
"result": True,
"wanted_time_after": "2015-09-17T01:53:44.723614+00:00",
"wanted_time_before": "2015-09-16T13:33:18.342542+00:00",
},
)
async def test_if_action_before_sunrise_no_offset_kotzebue(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was before sunrise.
Local timezone: Alaska time
Location: Kotzebue, which has a very skewed local timezone with sunrise
at 7 AM and sunset at 3AM during summer
After sunrise is true from sunrise until midnight, local time.
"""
await hass.config.async_set_time_zone("America/Anchorage")
hass.config.latitude = 66.5
hass.config.longitude = 162.4
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"before": SUN_EVENT_SUNRISE},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-07-24 07:21:12 local, sunset: 2015-07-25 03:13:33 local
# sunrise: 2015-07-24 15:21:12 UTC, sunset: 2015-07-25 11:13:33 UTC
# now = sunrise + 1s -> 'before sunrise' not true
now = datetime(2015, 7, 24, 15, 21, 13, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 0
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-07-24T15:16:46.975735+00:00"},
)
# now = sunrise - 1h -> 'before sunrise' true
now = datetime(2015, 7, 24, 14, 21, 12, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-07-24T15:16:46.975735+00:00"},
)
# now = local midnight -> 'before sunrise' true
now = datetime(2015, 7, 24, 8, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-07-24T15:16:46.975735+00:00"},
)
# now = local midnight - 1s -> 'before sunrise' not true
now = datetime(2015, 7, 24, 7, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-07-23T15:12:19.155123+00:00"},
)
async def test_if_action_after_sunrise_no_offset_kotzebue(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was after sunrise.
Local timezone: Alaska time
Location: Kotzebue, which has a very skewed local timezone with sunrise
at 7 AM and sunset at 3AM during summer
Before sunrise is true from midnight until sunrise, local time.
"""
await hass.config.async_set_time_zone("America/Anchorage")
hass.config.latitude = 66.5
hass.config.longitude = 162.4
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"after": SUN_EVENT_SUNRISE},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-07-24 07:21:12 local, sunset: 2015-07-25 03:13:33 local
# sunrise: 2015-07-24 15:21:12 UTC, sunset: 2015-07-25 11:13:33 UTC
# now = sunrise -> 'after sunrise' true
now = datetime(2015, 7, 24, 15, 21, 12, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-07-24T15:16:46.975735+00:00"},
)
# now = sunrise - 1h -> 'after sunrise' not true
now = datetime(2015, 7, 24, 14, 21, 12, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-07-24T15:16:46.975735+00:00"},
)
# now = local midnight -> 'after sunrise' not true
now = datetime(2015, 7, 24, 8, 0, 1, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-07-24T15:16:46.975735+00:00"},
)
# now = local midnight - 1s -> 'after sunrise' true
now = datetime(2015, 7, 24, 7, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-07-23T15:12:19.155123+00:00"},
)
async def test_if_action_before_sunset_no_offset_kotzebue(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was before sunrise.
Local timezone: Alaska time
Location: Kotzebue, which has a very skewed local timezone with sunrise
at 7 AM and sunset at 3AM during summer
Before sunset is true from midnight until sunset, local time.
"""
await hass.config.async_set_time_zone("America/Anchorage")
hass.config.latitude = 66.5
hass.config.longitude = 162.4
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"before": SUN_EVENT_SUNSET},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-07-24 07:21:12 local, sunset: 2015-07-25 03:13:33 local
# sunrise: 2015-07-24 15:21:12 UTC, sunset: 2015-07-25 11:13:33 UTC
# now = sunset + 1s -> 'before sunset' not true
now = datetime(2015, 7, 25, 11, 13, 34, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 0
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-07-25T11:13:32.501837+00:00"},
)
# now = sunset - 1h-> 'before sunset' true
now = datetime(2015, 7, 25, 10, 13, 33, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-07-25T11:13:32.501837+00:00"},
)
# now = local midnight -> 'before sunrise' true
now = datetime(2015, 7, 24, 8, 0, 0, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_before": "2015-07-24T11:17:54.446913+00:00"},
)
# now = local midnight - 1s -> 'before sunrise' not true
now = datetime(2015, 7, 24, 7, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_before": "2015-07-23T11:22:18.467277+00:00"},
)
async def test_if_action_after_sunset_no_offset_kotzebue(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
service_calls: list[ServiceCall],
) -> None:
"""Test if action was after sunrise.
Local timezone: Alaska time
Location: Kotzebue, which has a very skewed local timezone with sunrise
at 7 AM and sunset at 3AM during summer
After sunset is true from sunset until midnight, local time.
"""
await hass.config.async_set_time_zone("America/Anchorage")
hass.config.latitude = 66.5
hass.config.longitude = 162.4
await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: {
"id": "sun",
"trigger": {"platform": "event", "event_type": "test_event"},
"condition": {
"condition": "sun",
"options": {"after": SUN_EVENT_SUNSET},
},
"action": {"service": "test.automation"},
}
},
)
# sunrise: 2015-07-24 07:21:12 local, sunset: 2015-07-25 03:13:33 local
# sunrise: 2015-07-24 15:21:12 UTC, sunset: 2015-07-25 11:13:33 UTC
# now = sunset -> 'after sunset' true
now = datetime(2015, 7, 25, 11, 13, 33, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-07-25T11:13:32.501837+00:00"},
)
# now = sunset - 1s -> 'after sunset' not true
now = datetime(2015, 7, 25, 11, 13, 32, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-07-25T11:13:32.501837+00:00"},
)
# now = local midnight -> 'after sunset' not true
now = datetime(2015, 7, 24, 8, 0, 1, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 1
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": False, "wanted_time_after": "2015-07-24T11:17:54.446913+00:00"},
)
# now = local midnight - 1s -> 'after sunset' true
now = datetime(2015, 7, 24, 7, 59, 59, tzinfo=dt_util.UTC)
with freeze_time(now):
hass.bus.async_fire("test_event")
await hass.async_block_till_done()
assert len(service_calls) == 2
await assert_automation_condition_trace(
hass_ws_client,
"sun",
{"result": True, "wanted_time_after": "2015-07-23T11:22:18.467277+00:00"},
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sun/test_condition.py",
"license": "Apache License 2.0",
"lines": 1134,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/switchbot/test_init.py | """Test the switchbot init."""
from collections.abc import Callable
from unittest.mock import AsyncMock, patch
import pytest
from homeassistant.components.switchbot.const import (
CONF_CURTAIN_SPEED,
CONF_RETRY_COUNT,
DEFAULT_CURTAIN_SPEED,
DEFAULT_RETRY_COUNT,
DOMAIN,
)
from homeassistant.const import CONF_ADDRESS, CONF_NAME, CONF_SENSOR_TYPE
from homeassistant.core import HomeAssistant
from . import (
HUBMINI_MATTER_SERVICE_INFO,
LOCK_SERVICE_INFO,
WOCURTAIN_SERVICE_INFO,
WOSENSORTH_SERVICE_INFO,
patch_async_ble_device_from_address,
)
from tests.common import MockConfigEntry
from tests.components.bluetooth import inject_bluetooth_service_info
@pytest.mark.parametrize(
("exception", "error_message"),
[
(
ValueError("wrong model"),
"Switchbot device initialization failed because of incorrect configuration parameters: wrong model",
),
],
)
async def test_exception_handling_for_device_initialization(
hass: HomeAssistant,
mock_entry_encrypted_factory: Callable[[str], MockConfigEntry],
exception: Exception,
error_message: str,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test exception handling for lock initialization."""
inject_bluetooth_service_info(hass, LOCK_SERVICE_INFO)
entry = mock_entry_encrypted_factory(sensor_type="lock")
entry.add_to_hass(hass)
with patch(
"homeassistant.components.switchbot.lock.switchbot.SwitchbotLock.__init__",
side_effect=exception,
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert error_message in caplog.text
async def test_setup_entry_without_ble_device(
hass: HomeAssistant,
mock_entry_factory: Callable[[str], MockConfigEntry],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test setup entry without ble device."""
entry = mock_entry_factory("hygrometer_co2")
entry.add_to_hass(hass)
with patch_async_ble_device_from_address(None):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert (
"Could not find Switchbot hygrometer_co2 with address aa:bb:cc:dd:ee:ff"
in caplog.text
)
async def test_coordinator_wait_ready_timeout(
hass: HomeAssistant,
mock_entry_factory: Callable[[str], MockConfigEntry],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the coordinator async_wait_ready timeout by calling it directly."""
inject_bluetooth_service_info(hass, HUBMINI_MATTER_SERVICE_INFO)
entry = mock_entry_factory("hubmini_matter")
entry.add_to_hass(hass)
timeout_mock = AsyncMock()
timeout_mock.__aenter__.side_effect = TimeoutError
timeout_mock.__aexit__.return_value = None
with patch(
"homeassistant.components.switchbot.coordinator.asyncio.timeout",
return_value=timeout_mock,
):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert "aa:bb:cc:dd:ee:ff is not advertising state" in caplog.text
@pytest.mark.parametrize(
("sensor_type", "service_info", "expected_options"),
[
(
"curtain",
WOCURTAIN_SERVICE_INFO,
{
CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT,
CONF_CURTAIN_SPEED: DEFAULT_CURTAIN_SPEED,
},
),
(
"hygrometer",
WOSENSORTH_SERVICE_INFO,
{
CONF_RETRY_COUNT: DEFAULT_RETRY_COUNT,
},
),
],
)
async def test_migrate_entry_from_v1_1_to_v1_2(
hass: HomeAssistant,
sensor_type: str,
service_info,
expected_options: dict,
) -> None:
"""Test migration from version 1.1 to 1.2 adds default options."""
inject_bluetooth_service_info(hass, service_info)
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
CONF_NAME: "test-name",
CONF_SENSOR_TYPE: sensor_type,
},
unique_id="aabbccddeeff",
version=1,
minor_version=1,
options={},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.version == 1
assert entry.minor_version == 2
assert entry.options == expected_options
async def test_migrate_entry_preserves_existing_options(
hass: HomeAssistant,
) -> None:
"""Test migration preserves existing options."""
inject_bluetooth_service_info(hass, WOCURTAIN_SERVICE_INFO)
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
CONF_NAME: "test-name",
CONF_SENSOR_TYPE: "curtain",
},
unique_id="aabbccddeeff",
version=1,
minor_version=1,
options={CONF_RETRY_COUNT: 5},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.version == 1
assert entry.minor_version == 2
# Existing retry_count should be preserved, curtain_speed added
assert entry.options[CONF_RETRY_COUNT] == 5
assert entry.options[CONF_CURTAIN_SPEED] == DEFAULT_CURTAIN_SPEED
async def test_migrate_entry_fails_for_future_version(
hass: HomeAssistant,
) -> None:
"""Test migration fails for future versions."""
inject_bluetooth_service_info(hass, WOCURTAIN_SERVICE_INFO)
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_ADDRESS: "aa:bb:cc:dd:ee:ff",
CONF_NAME: "test-name",
CONF_SENSOR_TYPE: "curtain",
},
unique_id="aabbccddeeff",
version=2,
minor_version=1,
options={},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Entry should not be loaded due to failed migration
assert entry.version == 2
assert entry.minor_version == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/switchbot/test_init.py",
"license": "Apache License 2.0",
"lines": 177,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/switchbot/test_vacuum.py | """Tests for switchbot vacuum."""
from collections.abc import Callable
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from homeassistant.components.bluetooth import BluetoothServiceInfoBleak
from homeassistant.components.vacuum import (
DOMAIN as VACUUM_DOMAIN,
SERVICE_RETURN_TO_BASE,
SERVICE_START,
)
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from . import (
K10_POR_COMBO_VACUUM_SERVICE_INFO,
K10_PRO_VACUUM_SERVICE_INFO,
K10_VACUUM_SERVICE_INFO,
K11_PLUS_VACUUM_SERVICE_INFO,
K20_VACUUM_SERVICE_INFO,
S10_VACUUM_SERVICE_INFO,
S20_VACUUM_SERVICE_INFO,
)
from tests.common import MockConfigEntry
from tests.components.bluetooth import inject_bluetooth_service_info
@pytest.mark.parametrize(
("sensor_type", "service_info"),
[
("k20_vacuum", K20_VACUUM_SERVICE_INFO),
("s10_vacuum", S10_VACUUM_SERVICE_INFO),
("k10_pro_combo_vacumm", K10_POR_COMBO_VACUUM_SERVICE_INFO),
("k10_vacuum", K10_VACUUM_SERVICE_INFO),
("k10_pro_vacuum", K10_PRO_VACUUM_SERVICE_INFO),
("k11+_vacuum", K11_PLUS_VACUUM_SERVICE_INFO),
("s20_vacuum", S20_VACUUM_SERVICE_INFO),
],
)
@pytest.mark.parametrize(
("service", "mock_method"),
[(SERVICE_START, "clean_up"), (SERVICE_RETURN_TO_BASE, "return_to_dock")],
)
async def test_vacuum_controlling(
hass: HomeAssistant,
mock_entry_factory: Callable[[str], MockConfigEntry],
sensor_type: str,
service: str,
mock_method: str,
service_info: BluetoothServiceInfoBleak,
) -> None:
"""Test switchbot vacuum controlling."""
inject_bluetooth_service_info(hass, service_info)
entry = mock_entry_factory(sensor_type)
entry.add_to_hass(hass)
mocked_instance = AsyncMock(return_value=True)
with patch.multiple(
"homeassistant.components.switchbot.vacuum.switchbot.SwitchbotVacuum",
update=MagicMock(return_value=None),
**{mock_method: mocked_instance},
):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
entity_id = "vacuum.test_name"
await hass.services.async_call(
VACUUM_DOMAIN,
service,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mocked_instance.assert_awaited_once()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/switchbot/test_vacuum.py",
"license": "Apache License 2.0",
"lines": 67,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/wallbox/test_select.py | """Test Wallbox Select component."""
from unittest.mock import patch
import pytest
from homeassistant.components.select import (
ATTR_OPTION,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
)
from homeassistant.components.wallbox.const import EcoSmartMode
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant, HomeAssistantError
from .conftest import http_404_error, http_429_error, setup_integration
from .const import (
MOCK_SELECT_ENTITY_ID,
WALLBOX_STATUS_RESPONSE,
WALLBOX_STATUS_RESPONSE_ECO_MODE,
WALLBOX_STATUS_RESPONSE_FULL_SOLAR,
WALLBOX_STATUS_RESPONSE_NO_POWER_BOOST,
)
from tests.common import MockConfigEntry
TEST_OPTIONS = [
(EcoSmartMode.OFF, WALLBOX_STATUS_RESPONSE),
(EcoSmartMode.ECO_MODE, WALLBOX_STATUS_RESPONSE_ECO_MODE),
(EcoSmartMode.FULL_SOLAR, WALLBOX_STATUS_RESPONSE_FULL_SOLAR),
]
@pytest.mark.parametrize(("mode", "response"), TEST_OPTIONS)
async def test_wallbox_select_solar_charging_class(
hass: HomeAssistant, entry: MockConfigEntry, mode, response, mock_wallbox
) -> None:
"""Test wallbox select class."""
with patch.object(mock_wallbox, "getChargerStatus", return_value=response):
await setup_integration(hass, entry)
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: MOCK_SELECT_ENTITY_ID,
ATTR_OPTION: mode,
},
blocking=True,
)
state = hass.states.get(MOCK_SELECT_ENTITY_ID)
assert state.state == mode
async def test_wallbox_select_no_power_boost_class(
hass: HomeAssistant, entry: MockConfigEntry, mock_wallbox
) -> None:
"""Test wallbox select class."""
with patch.object(
mock_wallbox,
"getChargerStatus",
return_value=WALLBOX_STATUS_RESPONSE_NO_POWER_BOOST,
):
await setup_integration(hass, entry)
state = hass.states.get(MOCK_SELECT_ENTITY_ID)
assert state is None
@pytest.mark.parametrize(("mode", "response"), TEST_OPTIONS)
async def test_wallbox_select_class_error(
hass: HomeAssistant,
entry: MockConfigEntry,
mode,
response,
mock_wallbox,
) -> None:
"""Test wallbox select class connection error."""
await setup_integration(hass, entry)
with (
patch.object(mock_wallbox, "getChargerStatus", return_value=response),
patch.object(mock_wallbox, "disableEcoSmart", side_effect=http_404_error),
patch.object(mock_wallbox, "enableEcoSmart", side_effect=http_404_error),
pytest.raises(HomeAssistantError),
):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: MOCK_SELECT_ENTITY_ID,
ATTR_OPTION: mode,
},
blocking=True,
)
@pytest.mark.parametrize(("mode", "response"), TEST_OPTIONS)
async def test_wallbox_select_too_many_requests_error(
hass: HomeAssistant,
entry: MockConfigEntry,
mode,
response,
mock_wallbox,
) -> None:
"""Test wallbox select class connection error."""
await setup_integration(hass, entry)
with (
patch.object(mock_wallbox, "getChargerStatus", return_value=response),
patch.object(mock_wallbox, "disableEcoSmart", side_effect=http_429_error),
patch.object(mock_wallbox, "enableEcoSmart", side_effect=http_429_error),
pytest.raises(HomeAssistantError),
):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: MOCK_SELECT_ENTITY_ID,
ATTR_OPTION: mode,
},
blocking=True,
)
@pytest.mark.parametrize(("mode", "response"), TEST_OPTIONS)
async def test_wallbox_select_connection_error(
hass: HomeAssistant,
entry: MockConfigEntry,
mode,
response,
mock_wallbox,
) -> None:
"""Test wallbox select class connection error."""
await setup_integration(hass, entry)
with (
patch.object(mock_wallbox, "getChargerStatus", return_value=response),
patch.object(mock_wallbox, "disableEcoSmart", side_effect=ConnectionError),
patch.object(mock_wallbox, "enableEcoSmart", side_effect=ConnectionError),
pytest.raises(HomeAssistantError),
):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: MOCK_SELECT_ENTITY_ID,
ATTR_OPTION: mode,
},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/wallbox/test_select.py",
"license": "Apache License 2.0",
"lines": 130,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/wmspro/test_button.py | """Test the wmspro button support."""
from unittest.mock import AsyncMock, patch
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 . import setup_config_entry
from tests.common import MockConfigEntry
async def test_button_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hub_ping: AsyncMock,
mock_hub_configuration_prod_awning_dimmer: AsyncMock,
mock_hub_status_prod_awning: AsyncMock,
mock_action_call: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test that a button entity is created and updated correctly."""
assert await setup_config_entry(hass, mock_config_entry)
assert len(mock_hub_ping.mock_calls) == 1
assert len(mock_hub_configuration_prod_awning_dimmer.mock_calls) == 1
assert len(mock_hub_status_prod_awning.mock_calls) == 2
entity = hass.states.get("button.markise_identify")
assert entity is not None
assert entity == snapshot
async def test_button_press(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hub_ping: AsyncMock,
mock_hub_configuration_prod_awning_dimmer: AsyncMock,
mock_hub_status_prod_awning: AsyncMock,
mock_action_call: AsyncMock,
) -> None:
"""Test that a button entity is pressed correctly."""
assert await setup_config_entry(hass, mock_config_entry)
with patch(
"wmspro.destination.Destination.refresh",
return_value=True,
):
before = len(mock_hub_status_prod_awning.mock_calls)
entity = hass.states.get("button.markise_identify")
before_state = entity.state
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity.entity_id},
blocking=True,
)
entity = hass.states.get("button.markise_identify")
assert entity is not None
assert entity.state != before_state
assert len(mock_hub_status_prod_awning.mock_calls) == before
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/wmspro/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/helpers/test_helper_integration.py | """Tests for the helper entity helpers."""
from collections.abc import Generator
from unittest.mock import AsyncMock, Mock
import pytest
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import Event, HomeAssistant, callback
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.event import async_track_entity_registry_updated_event
from homeassistant.helpers.helper_integration import (
async_handle_source_entity_changes,
async_remove_helper_config_entry_from_source_device,
)
from tests.common import (
MockConfigEntry,
MockModule,
mock_config_flow,
mock_integration,
mock_platform,
)
HELPER_DOMAIN = "helper"
SOURCE_DOMAIN = "test"
@pytest.fixture
def source_config_entry(hass: HomeAssistant) -> er.RegistryEntry:
"""Fixture to create a source config entry."""
source_config_entry = MockConfigEntry()
source_config_entry.add_to_hass(hass)
return source_config_entry
@pytest.fixture
def source_device(
device_registry: dr.DeviceRegistry,
source_config_entry: ConfigEntry,
) -> dr.DeviceEntry:
"""Fixture to create a source device."""
return device_registry.async_get_or_create(
config_entry_id=source_config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
@pytest.fixture
def source_entity_entry(
entity_registry: er.EntityRegistry,
source_config_entry: ConfigEntry,
source_device: dr.DeviceEntry,
) -> er.RegistryEntry:
"""Fixture to create a source entity entry."""
return entity_registry.async_get_or_create(
"sensor",
SOURCE_DOMAIN,
"unique",
config_entry=source_config_entry,
device_id=source_device.id,
original_name="ABC",
)
@pytest.fixture
def helper_config_entry(
hass: HomeAssistant,
source_entity_entry: er.RegistryEntry,
use_entity_registry_id: bool,
) -> MockConfigEntry:
"""Fixture to create a helper config entry."""
config_entry = MockConfigEntry(
data={},
domain=HELPER_DOMAIN,
options={
"name": "My helper",
"round": 1.0,
"source": source_entity_entry.id
if use_entity_registry_id
else source_entity_entry.entity_id,
"time_window": {"seconds": 0.0},
"unit_prefix": "k",
"unit_time": "min",
},
title="My helper",
)
config_entry.add_to_hass(hass)
return config_entry
@pytest.fixture
def mock_helper_flow() -> Generator[None]:
"""Mock helper config flow."""
class MockConfigFlow:
"""Mock the helper config flow."""
VERSION = 1
MINOR_VERSION = 1
with mock_config_flow(HELPER_DOMAIN, MockConfigFlow):
yield
@pytest.fixture
def helper_entity_entry(
entity_registry: er.EntityRegistry,
helper_config_entry: ConfigEntry,
source_device: dr.DeviceEntry,
) -> er.RegistryEntry:
"""Fixture to create a helper entity entry."""
return entity_registry.async_get_or_create(
"sensor",
HELPER_DOMAIN,
helper_config_entry.entry_id,
config_entry=helper_config_entry,
device_id=source_device.id,
original_name="ABC",
)
@pytest.fixture
def async_remove_entry() -> AsyncMock:
"""Fixture to mock async_remove_entry."""
return AsyncMock(return_value=True)
@pytest.fixture
def async_unload_entry() -> AsyncMock:
"""Fixture to mock async_unload_entry."""
return AsyncMock(return_value=True)
@pytest.fixture
def set_source_entity_id_or_uuid() -> Mock:
"""Fixture to mock set_source_entity_id_or_uuid."""
return Mock()
@pytest.fixture
def source_entity_removed() -> AsyncMock:
"""Fixture to mock source_entity_removed."""
return AsyncMock()
@pytest.fixture
def mock_helper_integration(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
helper_config_entry: MockConfigEntry,
source_entity_entry: er.RegistryEntry,
async_remove_entry: AsyncMock,
async_unload_entry: AsyncMock,
set_source_entity_id_or_uuid: Mock,
source_entity_removed: AsyncMock | None,
) -> None:
"""Mock the helper integration."""
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Mock setup entry."""
async_handle_source_entity_changes(
hass,
helper_config_entry_id=helper_config_entry.entry_id,
set_source_entity_id_or_uuid=set_source_entity_id_or_uuid,
source_device_id=source_entity_entry.device_id,
source_entity_id_or_uuid=helper_config_entry.options["source"],
source_entity_removed=source_entity_removed,
)
return True
mock_integration(
hass,
MockModule(
HELPER_DOMAIN,
async_remove_entry=async_remove_entry,
async_setup_entry=async_setup_entry,
async_unload_entry=async_unload_entry,
),
)
mock_platform(hass, f"{HELPER_DOMAIN}.config_flow", None)
def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[str]:
"""Track entity registry actions for an entity."""
events = []
@callback
def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None:
"""Add entity registry updated event to the list."""
events.append(event.data["action"])
async_track_entity_registry_updated_event(hass, entity_id, add_event)
return events
def listen_entity_registry_events(
hass: HomeAssistant,
) -> list[er.EventEntityRegistryUpdatedData]:
"""Track entity registry actions for an entity."""
events: list[er.EventEntityRegistryUpdatedData] = []
@callback
def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None:
"""Add entity registry updated event to the list."""
events.append(event.data)
hass.bus.async_listen(er.EVENT_ENTITY_REGISTRY_UPDATED, add_event)
return events
@pytest.mark.parametrize("source_entity_removed", [None])
@pytest.mark.parametrize("use_entity_registry_id", [True, False])
@pytest.mark.usefixtures("mock_helper_flow", "mock_helper_integration")
async def test_async_handle_source_entity_changes_source_entity_removed(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
helper_config_entry: MockConfigEntry,
helper_entity_entry: er.RegistryEntry,
source_config_entry: ConfigEntry,
source_device: dr.DeviceEntry,
source_entity_entry: er.RegistryEntry,
async_remove_entry: AsyncMock,
async_unload_entry: AsyncMock,
set_source_entity_id_or_uuid: Mock,
) -> None:
"""Test the helper config entry is removed when the source entity is removed."""
# Add the helper config entry to the source device
device_registry.async_update_device(
source_device.id, add_config_entry_id=helper_config_entry.entry_id
)
# Add another config entry to the source device
other_config_entry = MockConfigEntry()
other_config_entry.add_to_hass(hass)
device_registry.async_update_device(
source_device.id, add_config_entry_id=other_config_entry.entry_id
)
assert await hass.config_entries.async_setup(helper_config_entry.entry_id)
await hass.async_block_till_done()
# Check preconditions
helper_entity_entry = entity_registry.async_get(helper_entity_entry.entity_id)
assert helper_entity_entry.device_id == source_entity_entry.device_id
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id in source_device.config_entries
events = track_entity_registry_actions(hass, helper_entity_entry.entity_id)
# Remove the source entitys's config entry from the device, this removes the
# source entity
device_registry.async_update_device(
source_device.id, remove_config_entry_id=source_config_entry.entry_id
)
await hass.async_block_till_done()
await hass.async_block_till_done()
# Check that the helper entity is not linked to the source device anymore
helper_entity_entry = entity_registry.async_get(helper_entity_entry.entity_id)
assert helper_entity_entry.device_id is None
async_unload_entry.assert_not_called()
async_remove_entry.assert_not_called()
set_source_entity_id_or_uuid.assert_not_called()
# Check that the helper config entry is not removed from the device
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id in source_device.config_entries
# Check that the helper config entry is not removed
assert helper_config_entry.entry_id in hass.config_entries.async_entry_ids()
# Check we got the expected events
assert events == ["update"]
@pytest.mark.parametrize("use_entity_registry_id", [True, False])
@pytest.mark.usefixtures("mock_helper_flow", "mock_helper_integration")
async def test_async_handle_source_entity_changes_source_entity_removed_custom_handler(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
helper_config_entry: MockConfigEntry,
helper_entity_entry: er.RegistryEntry,
source_config_entry: ConfigEntry,
source_device: dr.DeviceEntry,
source_entity_entry: er.RegistryEntry,
async_remove_entry: AsyncMock,
async_unload_entry: AsyncMock,
set_source_entity_id_or_uuid: Mock,
source_entity_removed: AsyncMock,
) -> None:
"""Test the helper config entry is removed when the source entity is removed."""
# Add the helper config entry to the source device
device_registry.async_update_device(
source_device.id, add_config_entry_id=helper_config_entry.entry_id
)
# Add another config entry to the source device
other_config_entry = MockConfigEntry()
other_config_entry.add_to_hass(hass)
device_registry.async_update_device(
source_device.id, add_config_entry_id=other_config_entry.entry_id
)
assert await hass.config_entries.async_setup(helper_config_entry.entry_id)
await hass.async_block_till_done()
# Check preconditions
helper_entity_entry = entity_registry.async_get(helper_entity_entry.entity_id)
assert helper_entity_entry.device_id == source_entity_entry.device_id
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id in source_device.config_entries
events = track_entity_registry_actions(hass, helper_entity_entry.entity_id)
# Remove the source entitys's config entry from the device, this removes the
# source entity
device_registry.async_update_device(
source_device.id, remove_config_entry_id=source_config_entry.entry_id
)
await hass.async_block_till_done()
await hass.async_block_till_done()
# Check that the source_entity_removed callback was called
source_entity_removed.assert_called_once()
async_unload_entry.assert_not_called()
async_remove_entry.assert_not_called()
set_source_entity_id_or_uuid.assert_not_called()
# Check that the helper config entry is not removed from the device
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id in source_device.config_entries
# Check that the helper config entry is not removed
assert helper_config_entry.entry_id in hass.config_entries.async_entry_ids()
# Check we got the expected events
assert events == []
@pytest.mark.parametrize("use_entity_registry_id", [True, False])
@pytest.mark.usefixtures("mock_helper_flow", "mock_helper_integration")
async def test_async_handle_source_entity_changes_source_entity_removed_from_device(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
helper_config_entry: MockConfigEntry,
helper_entity_entry: er.RegistryEntry,
source_device: dr.DeviceEntry,
source_entity_entry: er.RegistryEntry,
async_remove_entry: AsyncMock,
async_unload_entry: AsyncMock,
set_source_entity_id_or_uuid: Mock,
) -> None:
"""Test the source entity removed from the source device."""
# Add the helper config entry to the source device
device_registry.async_update_device(
source_device.id, add_config_entry_id=helper_config_entry.entry_id
)
assert await hass.config_entries.async_setup(helper_config_entry.entry_id)
await hass.async_block_till_done()
# Check preconditions
helper_entity_entry = entity_registry.async_get(helper_entity_entry.entity_id)
assert helper_entity_entry.device_id == source_entity_entry.device_id
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id in source_device.config_entries
events = track_entity_registry_actions(hass, helper_entity_entry.entity_id)
# Remove the source entity from the device
entity_registry.async_update_entity(source_entity_entry.entity_id, device_id=None)
await hass.async_block_till_done()
async_remove_entry.assert_not_called()
async_unload_entry.assert_called_once()
set_source_entity_id_or_uuid.assert_not_called()
# Check that the helper config entry is removed from the device
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id not in source_device.config_entries
# Check that the helper config entry is not removed
assert helper_config_entry.entry_id in hass.config_entries.async_entry_ids()
# Check we got the expected events
assert events == ["update"]
@pytest.mark.parametrize("use_entity_registry_id", [True, False])
@pytest.mark.usefixtures("mock_helper_flow", "mock_helper_integration")
async def test_async_handle_source_entity_changes_source_entity_moved_other_device(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
helper_config_entry: MockConfigEntry,
helper_entity_entry: er.RegistryEntry,
source_config_entry: ConfigEntry,
source_device: dr.DeviceEntry,
source_entity_entry: er.RegistryEntry,
async_remove_entry: AsyncMock,
async_unload_entry: AsyncMock,
set_source_entity_id_or_uuid: Mock,
) -> None:
"""Test the source entity is moved to another device."""
# Add the helper config entry to the source device
device_registry.async_update_device(
source_device.id, add_config_entry_id=helper_config_entry.entry_id
)
# Create another device to move the source entity to
source_device_2 = device_registry.async_get_or_create(
config_entry_id=source_config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:FF")},
)
assert await hass.config_entries.async_setup(helper_config_entry.entry_id)
await hass.async_block_till_done()
# Check preconditions
helper_entity_entry = entity_registry.async_get(helper_entity_entry.entity_id)
assert helper_entity_entry.device_id == source_entity_entry.device_id
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id in source_device.config_entries
source_device_2 = device_registry.async_get(source_device_2.id)
assert helper_config_entry.entry_id not in source_device_2.config_entries
events = track_entity_registry_actions(hass, helper_entity_entry.entity_id)
# Move the source entity to another device
entity_registry.async_update_entity(
source_entity_entry.entity_id, device_id=source_device_2.id
)
await hass.async_block_till_done()
async_remove_entry.assert_not_called()
async_unload_entry.assert_called_once()
set_source_entity_id_or_uuid.assert_not_called()
# Check that the helper config entry is moved to the other device
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id not in source_device.config_entries
source_device_2 = device_registry.async_get(source_device_2.id)
assert helper_config_entry.entry_id in source_device_2.config_entries
# Check that the helper config entry is not removed
assert helper_config_entry.entry_id in hass.config_entries.async_entry_ids()
# Check we got the expected events
assert events == ["update"]
@pytest.mark.parametrize(
("use_entity_registry_id", "unload_calls", "set_source_entity_id_calls"),
[(True, 1, 0), (False, 0, 1)],
)
@pytest.mark.usefixtures("mock_helper_flow", "mock_helper_integration")
async def test_async_handle_source_entity_new_entity_id(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
helper_config_entry: MockConfigEntry,
helper_entity_entry: er.RegistryEntry,
source_device: dr.DeviceEntry,
source_entity_entry: er.RegistryEntry,
async_remove_entry: AsyncMock,
async_unload_entry: AsyncMock,
set_source_entity_id_or_uuid: Mock,
unload_calls: int,
set_source_entity_id_calls: int,
) -> None:
"""Test the source entity's entity ID is changed."""
# Add the helper config entry to the source device
device_registry.async_update_device(
source_device.id, add_config_entry_id=helper_config_entry.entry_id
)
assert await hass.config_entries.async_setup(helper_config_entry.entry_id)
await hass.async_block_till_done()
# Check preconditions
helper_entity_entry = entity_registry.async_get(helper_entity_entry.entity_id)
assert helper_entity_entry.device_id == source_entity_entry.device_id
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id in source_device.config_entries
events = track_entity_registry_actions(hass, helper_entity_entry.entity_id)
# Change the source entity's entity ID
entity_registry.async_update_entity(
source_entity_entry.entity_id, new_entity_id="sensor.new_entity_id"
)
await hass.async_block_till_done()
async_remove_entry.assert_not_called()
assert len(async_unload_entry.mock_calls) == unload_calls
assert len(set_source_entity_id_or_uuid.mock_calls) == set_source_entity_id_calls
# Check that the helper config is still in the device
source_device = device_registry.async_get(source_device.id)
assert helper_config_entry.entry_id in source_device.config_entries
# Check that the helper config entry is not removed
assert helper_config_entry.entry_id in hass.config_entries.async_entry_ids()
# Check we got the expected events
assert events == []
@pytest.mark.parametrize("use_entity_registry_id", [True, False])
@pytest.mark.usefixtures("source_entity_entry")
async def test_async_remove_helper_config_entry_from_source_device(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
helper_config_entry: MockConfigEntry,
helper_entity_entry: er.RegistryEntry,
source_device: dr.DeviceEntry,
) -> None:
"""Test removing the helper config entry from the source device."""
# Add the helper config entry to the source device
device_registry.async_update_device(
source_device.id, add_config_entry_id=helper_config_entry.entry_id
)
# Create a helper entity entry, not connected to the source device
extra_helper_entity_entry = entity_registry.async_get_or_create(
"sensor",
HELPER_DOMAIN,
f"{helper_config_entry.entry_id}_2",
config_entry=helper_config_entry,
original_name="ABC",
)
assert extra_helper_entity_entry.entity_id != helper_entity_entry.entity_id
events = listen_entity_registry_events(hass)
async_remove_helper_config_entry_from_source_device(
hass,
helper_config_entry_id=helper_config_entry.entry_id,
source_device_id=source_device.id,
)
# Check we got the expected events
assert events == [
{
"action": "update",
"changes": {"device_id": source_device.id},
"entity_id": helper_entity_entry.entity_id,
},
{
"action": "update",
"changes": {"device_id": None},
"entity_id": helper_entity_entry.entity_id,
},
]
@pytest.mark.parametrize("use_entity_registry_id", [True, False])
@pytest.mark.usefixtures("source_entity_entry")
async def test_async_remove_helper_config_entry_from_source_device_helper_not_in_device(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
helper_config_entry: MockConfigEntry,
helper_entity_entry: er.RegistryEntry,
source_device: dr.DeviceEntry,
) -> None:
"""Test removing the helper config entry from the source device."""
# Create a helper entity entry, not connected to the source device
extra_helper_entity_entry = entity_registry.async_get_or_create(
"sensor",
HELPER_DOMAIN,
f"{helper_config_entry.entry_id}_2",
config_entry=helper_config_entry,
original_name="ABC",
)
assert extra_helper_entity_entry.entity_id != helper_entity_entry.entity_id
events = listen_entity_registry_events(hass)
async_remove_helper_config_entry_from_source_device(
hass,
helper_config_entry_id=helper_config_entry.entry_id,
source_device_id=source_device.id,
)
# Check we got the expected events
assert events == []
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/test_helper_integration.py",
"license": "Apache License 2.0",
"lines": 488,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/adax/coordinator.py | """DataUpdateCoordinator for the Adax component."""
import logging
from typing import Any, cast
from adax import Adax
from adax_local import Adax as AdaxLocal
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_IP_ADDRESS, CONF_PASSWORD, CONF_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import ACCOUNT_ID, SCAN_INTERVAL
_LOGGER = logging.getLogger(__name__)
type AdaxConfigEntry = ConfigEntry[AdaxCloudCoordinator | AdaxLocalCoordinator]
class AdaxCloudCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]]):
"""Coordinator for updating data to and from Adax (cloud)."""
def __init__(self, hass: HomeAssistant, entry: AdaxConfigEntry) -> None:
"""Initialize the Adax coordinator used for Cloud mode."""
super().__init__(
hass,
config_entry=entry,
logger=_LOGGER,
name="AdaxCloud",
update_interval=SCAN_INTERVAL,
)
self.adax_data_handler = Adax(
entry.data[ACCOUNT_ID],
entry.data[CONF_PASSWORD],
websession=async_get_clientsession(hass),
)
async def _async_update_data(self) -> dict[str, dict[str, Any]]:
"""Fetch data from the Adax."""
try:
if hasattr(self.adax_data_handler, "fetch_rooms_info"):
rooms = await self.adax_data_handler.fetch_rooms_info() or []
_LOGGER.debug("fetch_rooms_info returned: %s", rooms)
else:
_LOGGER.debug("fetch_rooms_info method not available, using get_rooms")
rooms = []
if not rooms:
_LOGGER.debug(
"No rooms from fetch_rooms_info, trying get_rooms as fallback"
)
rooms = await self.adax_data_handler.get_rooms() or []
_LOGGER.debug("get_rooms fallback returned: %s", rooms)
if not rooms:
raise UpdateFailed("No rooms available from Adax API")
except OSError as e:
raise UpdateFailed(f"Error communicating with API: {e}") from e
for room in rooms:
room["energyWh"] = int(room.get("energyWh", 0))
return {r["id"]: r for r in rooms}
class AdaxLocalCoordinator(DataUpdateCoordinator[dict[str, Any] | None]):
"""Coordinator for updating data to and from Adax (local)."""
def __init__(self, hass: HomeAssistant, entry: AdaxConfigEntry) -> None:
"""Initialize the Adax coordinator used for Local mode."""
super().__init__(
hass,
config_entry=entry,
logger=_LOGGER,
name="AdaxLocal",
update_interval=SCAN_INTERVAL,
)
self.adax_data_handler = AdaxLocal(
entry.data[CONF_IP_ADDRESS],
entry.data[CONF_TOKEN],
websession=async_get_clientsession(hass, verify_ssl=False),
)
async def _async_update_data(self) -> dict[str, Any]:
"""Fetch data from the Adax."""
if result := await self.adax_data_handler.get_status():
return cast(dict[str, Any], result)
raise UpdateFailed("Got invalid status from device")
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/adax/coordinator.py",
"license": "Apache License 2.0",
"lines": 72,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/aws_s3/backup.py | """Backup platform for the AWS S3 integration."""
from collections.abc import AsyncIterator, Callable, Coroutine
import functools
import json
import logging
from time import time
from typing import Any, cast
from botocore.exceptions import BotoCoreError
from homeassistant.components.backup import (
AgentBackup,
BackupAgent,
BackupAgentError,
BackupNotFound,
suggested_filename,
)
from homeassistant.core import HomeAssistant, callback
from . import S3ConfigEntry
from .const import CONF_BUCKET, CONF_PREFIX, DATA_BACKUP_AGENT_LISTENERS, DOMAIN
from .helpers import async_list_backups_from_s3
_LOGGER = logging.getLogger(__name__)
CACHE_TTL = 300
# S3 part size requirements: 5 MiB to 5 GiB per part
# https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html
# We set the threshold to 20 MiB to avoid too many parts.
# Note that each part is allocated in the memory.
MULTIPART_MIN_PART_SIZE_BYTES = 20 * 2**20
def handle_boto_errors[T](
func: Callable[..., Coroutine[Any, Any, T]],
) -> Callable[..., Coroutine[Any, Any, T]]:
"""Handle BotoCoreError exceptions by converting them to BackupAgentError."""
@functools.wraps(func)
async def wrapper(*args: Any, **kwargs: Any) -> T:
"""Catch BotoCoreError and raise BackupAgentError."""
try:
return await func(*args, **kwargs)
except BotoCoreError as err:
error_msg = f"Failed during {func.__name__}"
raise BackupAgentError(error_msg) from err
return wrapper
async def async_get_backup_agents(
hass: HomeAssistant,
) -> list[BackupAgent]:
"""Return a list of backup agents."""
entries: list[S3ConfigEntry] = hass.config_entries.async_loaded_entries(DOMAIN)
return [S3BackupAgent(hass, entry) for entry in entries]
@callback
def async_register_backup_agents_listener(
hass: HomeAssistant,
*,
listener: Callable[[], None],
**kwargs: Any,
) -> Callable[[], None]:
"""Register a listener to be called when agents are added or removed.
:return: A function to unregister the listener.
"""
hass.data.setdefault(DATA_BACKUP_AGENT_LISTENERS, []).append(listener)
@callback
def remove_listener() -> None:
"""Remove the listener."""
hass.data[DATA_BACKUP_AGENT_LISTENERS].remove(listener)
if not hass.data[DATA_BACKUP_AGENT_LISTENERS]:
del hass.data[DATA_BACKUP_AGENT_LISTENERS]
return remove_listener
def suggested_filenames(backup: AgentBackup) -> tuple[str, str]:
"""Return the suggested filenames for the backup and metadata files."""
base_name = suggested_filename(backup).rsplit(".", 1)[0]
return f"{base_name}.tar", f"{base_name}.metadata.json"
class S3BackupAgent(BackupAgent):
"""Backup agent for the S3 integration."""
domain = DOMAIN
def __init__(self, hass: HomeAssistant, entry: S3ConfigEntry) -> None:
"""Initialize the S3 agent."""
super().__init__()
self._client = entry.runtime_data.client
self._bucket: str = entry.data[CONF_BUCKET]
self.name = entry.title
self.unique_id = entry.entry_id
self._backup_cache: dict[str, AgentBackup] = {}
self._cache_expiration = time()
self._prefix: str = entry.data.get(CONF_PREFIX, "")
def _with_prefix(self, key: str) -> str:
"""Add prefix to a key if configured."""
if not self._prefix:
return key
return f"{self._prefix}/{key}"
@handle_boto_errors
async def async_download_backup(
self,
backup_id: str,
**kwargs: Any,
) -> AsyncIterator[bytes]:
"""Download a backup file.
:param backup_id: The ID of the backup that was returned in async_list_backups.
:return: An async iterator that yields bytes.
"""
backup = await self._find_backup_by_id(backup_id)
tar_filename, _ = suggested_filenames(backup)
response = await self._client.get_object(
Bucket=self._bucket, Key=self._with_prefix(tar_filename)
)
return response["Body"].iter_chunks()
async def async_upload_backup(
self,
*,
open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]],
backup: AgentBackup,
**kwargs: Any,
) -> None:
"""Upload a backup.
:param open_stream: A function returning an async iterator that yields bytes.
:param backup: Metadata about the backup that should be uploaded.
"""
tar_filename, metadata_filename = suggested_filenames(backup)
try:
if backup.size < MULTIPART_MIN_PART_SIZE_BYTES:
await self._upload_simple(tar_filename, open_stream)
else:
await self._upload_multipart(tar_filename, open_stream)
# Upload the metadata file
metadata_content = json.dumps(backup.as_dict())
await self._client.put_object(
Bucket=self._bucket,
Key=self._with_prefix(metadata_filename),
Body=metadata_content,
)
except BotoCoreError as err:
raise BackupAgentError("Failed to upload backup") from err
else:
# Reset cache after successful upload
self._cache_expiration = time()
async def _upload_simple(
self,
tar_filename: str,
open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]],
) -> None:
"""Upload a small file using simple upload.
:param tar_filename: The target filename for the backup.
:param open_stream: A function returning an async iterator that yields bytes.
"""
_LOGGER.debug("Starting simple upload for %s", tar_filename)
stream = await open_stream()
file_data = bytearray()
async for chunk in stream:
file_data.extend(chunk)
await self._client.put_object(
Bucket=self._bucket,
Key=self._with_prefix(tar_filename),
Body=bytes(file_data),
)
async def _upload_multipart(
self,
tar_filename: str,
open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]],
):
"""Upload a large file using multipart upload.
:param tar_filename: The target filename for the backup.
:param open_stream: A function returning an async iterator that yields bytes.
"""
_LOGGER.debug("Starting multipart upload for %s", tar_filename)
multipart_upload = await self._client.create_multipart_upload(
Bucket=self._bucket,
Key=self._with_prefix(tar_filename),
)
upload_id = multipart_upload["UploadId"]
try:
parts: list[dict[str, Any]] = []
part_number = 1
buffer = bytearray() # bytes buffer to store the data
offset = 0 # start index of unread data inside buffer
stream = await open_stream()
async for chunk in stream:
buffer.extend(chunk)
# Upload parts of exactly MULTIPART_MIN_PART_SIZE_BYTES to ensure
# all non-trailing parts have the same size (defensive implementation)
view = memoryview(buffer)
try:
while len(buffer) - offset >= MULTIPART_MIN_PART_SIZE_BYTES:
start = offset
end = offset + MULTIPART_MIN_PART_SIZE_BYTES
part_data = view[start:end]
offset = end
_LOGGER.debug(
"Uploading part number %d, size %d",
part_number,
len(part_data),
)
part = await cast(Any, self._client).upload_part(
Bucket=self._bucket,
Key=self._with_prefix(tar_filename),
PartNumber=part_number,
UploadId=upload_id,
Body=part_data.tobytes(),
)
parts.append({"PartNumber": part_number, "ETag": part["ETag"]})
part_number += 1
finally:
view.release()
# Compact the buffer if the consumed offset has grown large enough. This
# avoids unnecessary memory copies when compacting after every part upload.
if offset and offset >= MULTIPART_MIN_PART_SIZE_BYTES:
buffer = bytearray(buffer[offset:])
offset = 0
# Upload the final buffer as the last part (no minimum size requirement)
# Offset should be 0 after the last compaction, but we use it as the start
# index to be defensive in case the buffer was not compacted.
if offset < len(buffer):
remaining_data = memoryview(buffer)[offset:]
_LOGGER.debug(
"Uploading final part number %d, size %d",
part_number,
len(remaining_data),
)
part = await cast(Any, self._client).upload_part(
Bucket=self._bucket,
Key=self._with_prefix(tar_filename),
PartNumber=part_number,
UploadId=upload_id,
Body=remaining_data.tobytes(),
)
parts.append({"PartNumber": part_number, "ETag": part["ETag"]})
await cast(Any, self._client).complete_multipart_upload(
Bucket=self._bucket,
Key=self._with_prefix(tar_filename),
UploadId=upload_id,
MultipartUpload={"Parts": parts},
)
except BotoCoreError:
try:
await self._client.abort_multipart_upload(
Bucket=self._bucket,
Key=self._with_prefix(tar_filename),
UploadId=upload_id,
)
except BotoCoreError:
_LOGGER.exception("Failed to abort multipart upload")
raise
@handle_boto_errors
async def async_delete_backup(
self,
backup_id: str,
**kwargs: Any,
) -> None:
"""Delete a backup file.
:param backup_id: The ID of the backup that was returned in async_list_backups.
"""
backup = await self._find_backup_by_id(backup_id)
tar_filename, metadata_filename = suggested_filenames(backup)
# Delete both the backup file and its metadata file
await self._client.delete_object(
Bucket=self._bucket, Key=self._with_prefix(tar_filename)
)
await self._client.delete_object(
Bucket=self._bucket, Key=self._with_prefix(metadata_filename)
)
# Reset cache after successful deletion
self._cache_expiration = time()
@handle_boto_errors
async def async_list_backups(self, **kwargs: Any) -> list[AgentBackup]:
"""List backups."""
backups = await self._list_backups()
return list(backups.values())
@handle_boto_errors
async def async_get_backup(
self,
backup_id: str,
**kwargs: Any,
) -> AgentBackup:
"""Return a backup."""
return await self._find_backup_by_id(backup_id)
async def _find_backup_by_id(self, backup_id: str) -> AgentBackup:
"""Find a backup by its backup ID."""
backups = await self._list_backups()
if backup := backups.get(backup_id):
return backup
raise BackupNotFound(f"Backup {backup_id} not found")
async def _list_backups(self) -> dict[str, AgentBackup]:
"""List backups, using a cache if possible."""
if time() <= self._cache_expiration:
return self._backup_cache
backups_list = await async_list_backups_from_s3(
self._client, self._bucket, self._prefix
)
self._backup_cache = {b.backup_id: b for b in backups_list}
self._cache_expiration = time() + CACHE_TTL
return self._backup_cache
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/aws_s3/backup.py",
"license": "Apache License 2.0",
"lines": 285,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/aws_s3/config_flow.py | """Config flow for the AWS S3 integration."""
from __future__ import annotations
from typing import Any
from urllib.parse import urlparse
from aiobotocore.session import AioSession
from botocore.exceptions import ClientError, ConnectionError, ParamValidationError
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.selector import (
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from .const import (
AWS_DOMAIN,
CONF_ACCESS_KEY_ID,
CONF_BUCKET,
CONF_ENDPOINT_URL,
CONF_PREFIX,
CONF_SECRET_ACCESS_KEY,
DEFAULT_ENDPOINT_URL,
DESCRIPTION_AWS_S3_DOCS_URL,
DESCRIPTION_BOTO3_DOCS_URL,
DOMAIN,
)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_ACCESS_KEY_ID): cv.string,
vol.Required(CONF_SECRET_ACCESS_KEY): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.PASSWORD)
),
vol.Required(CONF_BUCKET): cv.string,
vol.Required(CONF_ENDPOINT_URL, default=DEFAULT_ENDPOINT_URL): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.URL)
),
vol.Optional(CONF_PREFIX, default=""): cv.string,
}
)
class S3ConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow."""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a flow initiated by the user."""
errors: dict[str, str] = {}
if user_input is not None:
normalized_prefix = user_input.get(CONF_PREFIX, "").strip("/")
# Check for existing entries, treating missing prefix as empty
for entry in self._async_current_entries(include_ignore=False):
entry_prefix = (entry.data.get(CONF_PREFIX) or "").strip("/")
if (
entry.data.get(CONF_BUCKET) == user_input[CONF_BUCKET]
and entry.data.get(CONF_ENDPOINT_URL)
== user_input[CONF_ENDPOINT_URL]
and entry_prefix == normalized_prefix
):
return self.async_abort(reason="already_configured")
hostname = urlparse(user_input[CONF_ENDPOINT_URL]).hostname
if not hostname or not hostname.endswith(AWS_DOMAIN):
errors[CONF_ENDPOINT_URL] = "invalid_endpoint_url"
else:
try:
session = AioSession()
async with session.create_client(
"s3",
endpoint_url=user_input.get(CONF_ENDPOINT_URL),
aws_secret_access_key=user_input[CONF_SECRET_ACCESS_KEY],
aws_access_key_id=user_input[CONF_ACCESS_KEY_ID],
) as client:
await client.head_bucket(Bucket=user_input[CONF_BUCKET])
except ClientError:
errors["base"] = "invalid_credentials"
except ParamValidationError as err:
if "Invalid bucket name" in str(err):
errors[CONF_BUCKET] = "invalid_bucket_name"
except ValueError:
errors[CONF_ENDPOINT_URL] = "invalid_endpoint_url"
except ConnectionError:
errors[CONF_ENDPOINT_URL] = "cannot_connect"
else:
data = dict(user_input)
if not normalized_prefix:
# Do not persist empty optional values
data.pop(CONF_PREFIX, None)
else:
data[CONF_PREFIX] = normalized_prefix
title = user_input[CONF_BUCKET]
if normalized_prefix:
title = f"{title} - {normalized_prefix}"
return self.async_create_entry(title=title, data=data)
return self.async_show_form(
step_id="user",
data_schema=self.add_suggested_values_to_schema(
STEP_USER_DATA_SCHEMA, user_input
),
errors=errors,
description_placeholders={
"aws_s3_docs_url": DESCRIPTION_AWS_S3_DOCS_URL,
"boto3_docs_url": DESCRIPTION_BOTO3_DOCS_URL,
},
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/aws_s3/config_flow.py",
"license": "Apache License 2.0",
"lines": 102,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/aws_s3/const.py | """Constants for the AWS S3 integration."""
from collections.abc import Callable
from typing import Final
from homeassistant.util.hass_dict import HassKey
DOMAIN: Final = "aws_s3"
CONF_ACCESS_KEY_ID = "access_key_id"
CONF_SECRET_ACCESS_KEY = "secret_access_key"
CONF_ENDPOINT_URL = "endpoint_url"
CONF_BUCKET = "bucket"
CONF_PREFIX = "prefix"
AWS_DOMAIN = "amazonaws.com"
DEFAULT_ENDPOINT_URL = f"https://s3.eu-central-1.{AWS_DOMAIN}/"
DATA_BACKUP_AGENT_LISTENERS: HassKey[list[Callable[[], None]]] = HassKey(
f"{DOMAIN}.backup_agent_listeners"
)
DESCRIPTION_AWS_S3_DOCS_URL = "https://docs.aws.amazon.com/general/latest/gr/s3.html"
DESCRIPTION_BOTO3_DOCS_URL = "https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/aws_s3/const.py",
"license": "Apache License 2.0",
"lines": 17,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/eheimdigital/switch.py | """EHEIM Digital switches."""
from typing import Any, override
from eheimdigital.classic_vario import EheimDigitalClassicVario
from eheimdigital.device import EheimDigitalDevice
from eheimdigital.filter import EheimDigitalFilter
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import EheimDigitalConfigEntry, EheimDigitalUpdateCoordinator
from .entity import EheimDigitalEntity, exception_handler
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
entry: EheimDigitalConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the callbacks for the coordinator so switches can be added as devices are found."""
coordinator = entry.runtime_data
def async_setup_device_entities(
device_address: dict[str, EheimDigitalDevice],
) -> None:
"""Set up the switch entities for one or multiple devices."""
entities: list[SwitchEntity] = []
for device in device_address.values():
if isinstance(device, (EheimDigitalClassicVario, EheimDigitalFilter)):
entities.append(EheimDigitalFilterSwitch(coordinator, device)) # noqa: PERF401
async_add_entities(entities)
coordinator.add_platform_callback(async_setup_device_entities)
async_setup_device_entities(coordinator.hub.devices)
class EheimDigitalFilterSwitch(
EheimDigitalEntity[EheimDigitalClassicVario | EheimDigitalFilter], SwitchEntity
):
"""Represent an EHEIM Digital classicVARIO or filter switch entity."""
_attr_translation_key = "filter_active"
_attr_name = None
def __init__(
self,
coordinator: EheimDigitalUpdateCoordinator,
device: EheimDigitalClassicVario | EheimDigitalFilter,
) -> None:
"""Initialize an EHEIM Digital classicVARIO or filter switch entity."""
super().__init__(coordinator, device)
self._attr_unique_id = device.mac_address
self._async_update_attrs()
@override
@exception_handler
async def async_turn_off(self, **kwargs: Any) -> None:
await self._device.set_active(active=False)
@override
@exception_handler
async def async_turn_on(self, **kwargs: Any) -> None:
await self._device.set_active(active=True)
@override
def _async_update_attrs(self) -> None:
self._attr_is_on = self._device.is_active
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/eheimdigital/switch.py",
"license": "Apache License 2.0",
"lines": 56,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/eheimdigital/time.py | """EHEIM Digital time entities."""
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from datetime import time
from typing import Any, final, override
from eheimdigital.classic_vario import EheimDigitalClassicVario
from eheimdigital.device import EheimDigitalDevice
from eheimdigital.filter import EheimDigitalFilter
from eheimdigital.heater import EheimDigitalHeater
from homeassistant.components.time import TimeEntity, TimeEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import EheimDigitalConfigEntry, EheimDigitalUpdateCoordinator
from .entity import EheimDigitalEntity, exception_handler
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class EheimDigitalTimeDescription[_DeviceT: EheimDigitalDevice](TimeEntityDescription):
"""Class describing EHEIM Digital time entities."""
value_fn: Callable[[_DeviceT], time | None]
set_value_fn: Callable[[_DeviceT, time], Awaitable[None]]
FILTER_DESCRIPTIONS: tuple[EheimDigitalTimeDescription[EheimDigitalFilter], ...] = (
EheimDigitalTimeDescription[EheimDigitalFilter](
key="day_start_time",
translation_key="day_start_time",
entity_category=EntityCategory.CONFIG,
value_fn=lambda device: device.day_start_time,
set_value_fn=lambda device, value: device.set_day_start_time(value),
),
EheimDigitalTimeDescription[EheimDigitalFilter](
key="night_start_time",
translation_key="night_start_time",
entity_category=EntityCategory.CONFIG,
value_fn=lambda device: device.night_start_time,
set_value_fn=lambda device, value: device.set_night_start_time(value),
),
)
CLASSICVARIO_DESCRIPTIONS: tuple[
EheimDigitalTimeDescription[EheimDigitalClassicVario], ...
] = (
EheimDigitalTimeDescription[EheimDigitalClassicVario](
key="day_start_time",
translation_key="day_start_time",
entity_category=EntityCategory.CONFIG,
value_fn=lambda device: device.day_start_time,
set_value_fn=lambda device, value: device.set_day_start_time(value),
),
EheimDigitalTimeDescription[EheimDigitalClassicVario](
key="night_start_time",
translation_key="night_start_time",
entity_category=EntityCategory.CONFIG,
value_fn=lambda device: device.night_start_time,
set_value_fn=lambda device, value: device.set_night_start_time(value),
),
)
HEATER_DESCRIPTIONS: tuple[EheimDigitalTimeDescription[EheimDigitalHeater], ...] = (
EheimDigitalTimeDescription[EheimDigitalHeater](
key="day_start_time",
translation_key="day_start_time",
entity_category=EntityCategory.CONFIG,
value_fn=lambda device: device.day_start_time,
set_value_fn=lambda device, value: device.set_day_start_time(value),
),
EheimDigitalTimeDescription[EheimDigitalHeater](
key="night_start_time",
translation_key="night_start_time",
entity_category=EntityCategory.CONFIG,
value_fn=lambda device: device.night_start_time,
set_value_fn=lambda device, value: device.set_night_start_time(value),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: EheimDigitalConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the callbacks for the coordinator so times can be added as devices are found."""
coordinator = entry.runtime_data
def async_setup_device_entities(
device_address: dict[str, EheimDigitalDevice],
) -> None:
"""Set up the time entities for one or multiple devices."""
entities: list[EheimDigitalTime[Any]] = []
for device in device_address.values():
if isinstance(device, EheimDigitalFilter):
entities.extend(
EheimDigitalTime[EheimDigitalFilter](
coordinator, device, description
)
for description in FILTER_DESCRIPTIONS
)
if isinstance(device, EheimDigitalClassicVario):
entities.extend(
EheimDigitalTime[EheimDigitalClassicVario](
coordinator, device, description
)
for description in CLASSICVARIO_DESCRIPTIONS
)
if isinstance(device, EheimDigitalHeater):
entities.extend(
EheimDigitalTime[EheimDigitalHeater](
coordinator, device, description
)
for description in HEATER_DESCRIPTIONS
)
async_add_entities(entities)
coordinator.add_platform_callback(async_setup_device_entities)
async_setup_device_entities(coordinator.hub.devices)
@final
class EheimDigitalTime[_DeviceT: EheimDigitalDevice](
EheimDigitalEntity[_DeviceT], TimeEntity
):
"""Represent an EHEIM Digital time entity."""
entity_description: EheimDigitalTimeDescription[_DeviceT]
def __init__(
self,
coordinator: EheimDigitalUpdateCoordinator,
device: _DeviceT,
description: EheimDigitalTimeDescription[_DeviceT],
) -> None:
"""Initialize an EHEIM Digital time entity."""
super().__init__(coordinator, device)
self.entity_description = description
self._attr_unique_id = f"{device.mac_address}_{description.key}"
@override
@exception_handler
async def async_set_value(self, value: time) -> None:
"""Change the time."""
return await self.entity_description.set_value_fn(self._device, value)
@override
def _async_update_attrs(self) -> None:
"""Update the entity attributes."""
self._attr_native_value = self.entity_description.value_fn(self._device)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/eheimdigital/time.py",
"license": "Apache License 2.0",
"lines": 133,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/miele/fan.py | """Platform for Miele fan entity."""
from __future__ import annotations
from dataclasses import dataclass
import logging
import math
from typing import Any, Final
from aiohttp import ClientResponseError
from homeassistant.components.fan import (
FanEntity,
FanEntityDescription,
FanEntityFeature,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.percentage import (
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from homeassistant.util.scaling import int_states_in_range
from .const import DOMAIN, POWER_OFF, POWER_ON, VENTILATION_STEP, MieleAppliance
from .coordinator import MieleConfigEntry, MieleDataUpdateCoordinator
from .entity import MieleEntity
PARALLEL_UPDATES = 1
_LOGGER = logging.getLogger(__name__)
SPEED_RANGE = (1, 4)
@dataclass(frozen=True, kw_only=True)
class MieleFanDefinition:
"""Class for defining fan entities."""
types: tuple[MieleAppliance, ...]
description: FanEntityDescription
FAN_TYPES: Final[tuple[MieleFanDefinition, ...]] = (
MieleFanDefinition(
types=(MieleAppliance.HOOD,),
description=FanEntityDescription(
key="fan",
translation_key="fan",
),
),
MieleFanDefinition(
types=(MieleAppliance.HOB_INDUCT_EXTR,),
description=FanEntityDescription(
key="fan_readonly",
translation_key="fan",
),
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: MieleConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the fan platform."""
coordinator = config_entry.runtime_data.coordinator
added_devices: set[str] = set()
def _async_add_new_devices() -> None:
nonlocal added_devices
new_devices_set, current_devices = coordinator.async_add_devices(added_devices)
added_devices = current_devices
async_add_entities(
MieleFan(coordinator, device_id, definition.description)
for device_id, device in coordinator.data.devices.items()
for definition in FAN_TYPES
if device_id in new_devices_set and device.device_type in definition.types
)
config_entry.async_on_unload(coordinator.async_add_listener(_async_add_new_devices))
_async_add_new_devices()
class MieleFan(MieleEntity, FanEntity):
"""Representation of a Fan."""
entity_description: FanEntityDescription
def __init__(
self,
coordinator: MieleDataUpdateCoordinator,
device_id: str,
description: FanEntityDescription,
) -> None:
"""Initialize the fan."""
self._attr_supported_features: FanEntityFeature = (
FanEntityFeature(0)
if description.key == "fan_readonly"
else FanEntityFeature.SET_SPEED
| FanEntityFeature.TURN_OFF
| FanEntityFeature.TURN_ON
)
super().__init__(coordinator, device_id, description)
@property
def is_on(self) -> bool:
"""Return current on/off state."""
return (
self.device.state_ventilation_step is not None
and self.device.state_ventilation_step > 0
)
@property
def speed_count(self) -> int:
"""Return the number of speeds the fan supports."""
return int_states_in_range(SPEED_RANGE)
@property
def percentage(self) -> int | None:
"""Return the current speed percentage."""
return ranged_value_to_percentage(
SPEED_RANGE,
(self.device.state_ventilation_step or 0),
)
async def async_set_percentage(self, percentage: int) -> None:
"""Set the speed percentage of the fan."""
_LOGGER.debug("Set_percentage: %s", percentage)
ventilation_step = math.ceil(
percentage_to_ranged_value(SPEED_RANGE, percentage)
)
_LOGGER.debug("Calc ventilation_step: %s", ventilation_step)
if ventilation_step == 0:
await self.async_turn_off()
else:
try:
await self.api.send_action(
self._device_id, {VENTILATION_STEP: ventilation_step}
)
except ClientResponseError as err:
_LOGGER.debug("Error setting fan state for %s: %s", self.entity_id, err)
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="set_state_error",
translation_placeholders={
"entity": self.entity_id,
},
) from err
self.device.state_ventilation_step = ventilation_step
self.async_write_ha_state()
async def async_turn_on(
self,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn on the fan."""
_LOGGER.debug(
"Turn_on -> percentage: %s, preset_mode: %s", percentage, preset_mode
)
try:
await self.api.send_action(self._device_id, {POWER_ON: True})
except ClientResponseError as ex:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="set_state_error",
translation_placeholders={
"entity": self.entity_id,
"err_status": str(ex.status),
},
) from ex
if percentage is not None:
await self.async_set_percentage(percentage)
return
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the fan off."""
try:
await self.api.send_action(self._device_id, {POWER_OFF: True})
except ClientResponseError as ex:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="set_state_error",
translation_placeholders={
"entity": self.entity_id,
"err_status": str(ex.status),
},
) from ex
self.device.state_ventilation_step = 0
self.async_write_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/miele/fan.py",
"license": "Apache License 2.0",
"lines": 167,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/rehlko/config_flow.py | """Config flow for Rehlko integration."""
from __future__ import annotations
from collections.abc import Mapping
import logging
from typing import Any
from aiokem import AioKem, AuthenticationError
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import CONNECTION_EXCEPTIONS, DOMAIN
_LOGGER = logging.getLogger(__name__)
class RehlkoConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Rehlko."""
VERSION = 1
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:
errors, token_subject = await self._async_validate_or_error(user_input)
if not errors:
await self.async_set_unique_id(token_subject)
self._abort_if_unique_id_configured()
email: str = user_input[CONF_EMAIL]
normalized_email = email.lower()
return self.async_create_entry(title=normalized_email, data=user_input)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_EMAIL): str,
vol.Required(CONF_PASSWORD): str,
}
),
errors=errors,
)
async def _async_validate_or_error(
self, config: dict[str, Any]
) -> tuple[dict[str, str], str | None]:
"""Validate the user input."""
errors: dict[str, str] = {}
token_subject = None
rehlko = AioKem(session=async_get_clientsession(self.hass))
try:
await rehlko.authenticate(config[CONF_EMAIL], config[CONF_PASSWORD])
except CONNECTION_EXCEPTIONS:
errors["base"] = "cannot_connect"
except AuthenticationError:
errors[CONF_PASSWORD] = "invalid_auth"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
token_subject = rehlko.get_token_subject()
return errors, token_subject
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Handle reauth."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reauth input."""
errors: dict[str, str] = {}
reauth_entry = self._get_reauth_entry()
existing_data = reauth_entry.data
description_placeholders: dict[str, str] = {
CONF_EMAIL: existing_data[CONF_EMAIL]
}
if user_input is not None:
errors, _ = await self._async_validate_or_error(
{**existing_data, **user_input}
)
if not errors:
return self.async_update_reload_and_abort(
reauth_entry,
data_updates=user_input,
)
return self.async_show_form(
description_placeholders=description_placeholders,
step_id="reauth_confirm",
data_schema=vol.Schema({vol.Required(CONF_PASSWORD): str}),
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/rehlko/config_flow.py",
"license": "Apache License 2.0",
"lines": 87,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/rehlko/const.py | """Constants for the Rehlko integration."""
from aiokem import CommunicationError
DOMAIN = "rehlko"
CONF_REFRESH_TOKEN = "refresh_token"
DEVICE_DATA_DEVICES = "devices"
DEVICE_DATA_PRODUCT = "product"
DEVICE_DATA_FIRMWARE_VERSION = "firmwareVersion"
DEVICE_DATA_MODEL_NAME = "modelDisplayName"
DEVICE_DATA_ID = "id"
DEVICE_DATA_DISPLAY_NAME = "displayName"
DEVICE_DATA_MAC_ADDRESS = "macAddress"
DEVICE_DATA_IS_CONNECTED = "isConnected"
KOHLER = "Kohler"
GENERATOR_DATA_DEVICE = "device"
GENERATOR_DATA_EXERCISE = "exercise"
CONNECTION_EXCEPTIONS = (
TimeoutError,
CommunicationError,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/rehlko/const.py",
"license": "Apache License 2.0",
"lines": 19,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/rehlko/coordinator.py | """The Rehlko coordinator."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import timedelta
import logging
from typing import Any
from aiokem import AioKem, CommunicationError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
type RehlkoConfigEntry = ConfigEntry[RehlkoRuntimeData]
SCAN_INTERVAL_MINUTES = timedelta(minutes=10)
@dataclass
class RehlkoRuntimeData:
"""Dataclass to hold runtime data for the Rehlko integration."""
coordinators: dict[int, RehlkoUpdateCoordinator]
rehlko: AioKem
homes: list[dict[str, Any]]
class RehlkoUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""Class to manage fetching Rehlko data API."""
config_entry: RehlkoConfigEntry
def __init__(
self,
hass: HomeAssistant,
logger: logging.Logger,
config_entry: RehlkoConfigEntry,
rehlko: AioKem,
home_data: dict[str, Any],
device_data: dict[str, Any],
device_id: int,
name: str,
) -> None:
"""Initialize."""
self.rehlko = rehlko
self.device_data = device_data
self.device_id = device_id
self.home_data = home_data
super().__init__(
hass=hass,
logger=logger,
config_entry=config_entry,
name=name,
update_interval=SCAN_INTERVAL_MINUTES,
)
async def _async_update_data(self) -> dict[str, Any]:
"""Update data via library."""
try:
result = await self.rehlko.get_generator_data(self.device_id)
except CommunicationError as error:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_failed",
) from error
return result
@property
def entry_unique_id(self) -> str:
"""Get the unique ID for the entry."""
assert self.config_entry.unique_id
return self.config_entry.unique_id
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/rehlko/coordinator.py",
"license": "Apache License 2.0",
"lines": 61,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/rehlko/entity.py | """Base class for Rehlko entities."""
from __future__ import annotations
from typing import Any
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import (
DEVICE_DATA_DISPLAY_NAME,
DEVICE_DATA_FIRMWARE_VERSION,
DEVICE_DATA_IS_CONNECTED,
DEVICE_DATA_MAC_ADDRESS,
DEVICE_DATA_MODEL_NAME,
DEVICE_DATA_PRODUCT,
DOMAIN,
GENERATOR_DATA_DEVICE,
KOHLER,
)
from .coordinator import RehlkoUpdateCoordinator
def _get_device_connections(mac_address: str) -> set[tuple[str, str]]:
"""Get device connections."""
try:
mac_address_hex = mac_address.replace(":", "")
except ValueError: # MacAddress may be invalid if the gateway is offline
return set()
return {(dr.CONNECTION_NETWORK_MAC, mac_address_hex)}
class RehlkoEntity(CoordinatorEntity[RehlkoUpdateCoordinator]):
"""Representation of a Rehlko entity."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: RehlkoUpdateCoordinator,
device_id: int,
device_data: dict,
description: EntityDescription,
document_key: str | None = None,
connectivity_key: str | None = DEVICE_DATA_IS_CONNECTED,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self.entity_description = description
self._device_id = device_id
self._attr_unique_id = (
f"{coordinator.entry_unique_id}_{device_id}_{description.key}"
)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, f"{coordinator.entry_unique_id}_{device_id}")},
name=device_data[DEVICE_DATA_DISPLAY_NAME],
hw_version=device_data[DEVICE_DATA_PRODUCT],
sw_version=device_data[DEVICE_DATA_FIRMWARE_VERSION],
model=device_data[DEVICE_DATA_MODEL_NAME],
manufacturer=KOHLER,
connections=_get_device_connections(device_data[DEVICE_DATA_MAC_ADDRESS]),
)
self._document_key = document_key
self._connectivity_key = connectivity_key
@property
def _device_data(self) -> dict[str, Any]:
"""Return the device data."""
return self.coordinator.data[GENERATOR_DATA_DEVICE]
@property
def _rehlko_value(self) -> str:
"""Return the sensor value."""
if self._document_key:
return self.coordinator.data[self._document_key][
self.entity_description.key
]
return self.coordinator.data[self.entity_description.key]
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and (
not self._connectivity_key or self._device_data[self._connectivity_key]
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/rehlko/entity.py",
"license": "Apache License 2.0",
"lines": 74,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/rehlko/sensor.py | """Support for Rehlko sensors."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import (
PERCENTAGE,
REVOLUTIONS_PER_MINUTE,
EntityCategory,
UnitOfElectricPotential,
UnitOfFrequency,
UnitOfPower,
UnitOfPressure,
UnitOfTemperature,
UnitOfTime,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .const import (
DEVICE_DATA_DEVICES,
DEVICE_DATA_ID,
GENERATOR_DATA_DEVICE,
GENERATOR_DATA_EXERCISE,
)
from .coordinator import RehlkoConfigEntry
from .entity import RehlkoEntity
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class RehlkoSensorEntityDescription(SensorEntityDescription):
"""Class describing Rehlko sensor entities."""
document_key: str | None = None
value_fn: Callable[[str], datetime | None] | None = None
SENSORS: tuple[RehlkoSensorEntityDescription, ...] = (
RehlkoSensorEntityDescription(
key="engineSpeedRpm",
translation_key="engine_speed",
entity_category=EntityCategory.DIAGNOSTIC,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=REVOLUTIONS_PER_MINUTE,
),
RehlkoSensorEntityDescription(
key="engineOilPressurePsi",
translation_key="engine_oil_pressure",
native_unit_of_measurement=UnitOfPressure.PSI,
device_class=SensorDeviceClass.PRESSURE,
state_class=SensorStateClass.MEASUREMENT,
),
RehlkoSensorEntityDescription(
key="engineCoolantTempF",
translation_key="engine_coolant_temperature",
native_unit_of_measurement=UnitOfTemperature.FAHRENHEIT,
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
),
RehlkoSensorEntityDescription(
key="batteryVoltageV",
translation_key="battery_voltage",
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
device_class=SensorDeviceClass.VOLTAGE,
state_class=SensorStateClass.MEASUREMENT,
),
RehlkoSensorEntityDescription(
key="lubeOilTempF",
translation_key="lube_oil_temperature",
native_unit_of_measurement=UnitOfTemperature.FAHRENHEIT,
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
),
RehlkoSensorEntityDescription(
key="controllerTempF",
translation_key="controller_temperature",
native_unit_of_measurement=UnitOfTemperature.FAHRENHEIT,
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
),
RehlkoSensorEntityDescription(
key="engineCompartmentTempF",
translation_key="engine_compartment_temperature",
native_unit_of_measurement=UnitOfTemperature.FAHRENHEIT,
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
),
RehlkoSensorEntityDescription(
key="engineFrequencyHz",
translation_key="engine_frequency",
native_unit_of_measurement=UnitOfFrequency.HERTZ,
device_class=SensorDeviceClass.FREQUENCY,
state_class=SensorStateClass.MEASUREMENT,
),
RehlkoSensorEntityDescription(
key="totalOperationHours",
translation_key="total_operation",
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.HOURS,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
),
RehlkoSensorEntityDescription(
key="totalRuntimeHours",
translation_key="total_runtime",
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.HOURS,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
document_key=GENERATOR_DATA_DEVICE,
),
RehlkoSensorEntityDescription(
key="runtimeSinceLastMaintenanceHours",
translation_key="runtime_since_last_maintenance",
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.HOURS,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
),
RehlkoSensorEntityDescription(
key="deviceIpAddress",
translation_key="device_ip_address",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
document_key=GENERATOR_DATA_DEVICE,
),
RehlkoSensorEntityDescription(
key="serverIpAddress",
translation_key="server_ip_address",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
),
RehlkoSensorEntityDescription(
key="utilityVoltageV",
translation_key="utility_voltage",
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
device_class=SensorDeviceClass.VOLTAGE,
state_class=SensorStateClass.MEASUREMENT,
),
RehlkoSensorEntityDescription(
key="generatorVoltageAvgV",
translation_key="generator_voltage_avg",
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
device_class=SensorDeviceClass.VOLTAGE,
state_class=SensorStateClass.MEASUREMENT,
),
RehlkoSensorEntityDescription(
key="generatorLoadW",
translation_key="generator_load",
native_unit_of_measurement=UnitOfPower.WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
),
RehlkoSensorEntityDescription(
key="generatorLoadPercent",
translation_key="generator_load_percent",
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
),
RehlkoSensorEntityDescription(
key="status",
translation_key="generator_status",
document_key=GENERATOR_DATA_DEVICE,
),
RehlkoSensorEntityDescription(
key="engineState",
translation_key="engine_state",
),
RehlkoSensorEntityDescription(
key="powerSource",
translation_key="power_source",
),
RehlkoSensorEntityDescription(
key="lastRanTimestamp",
translation_key="last_run",
device_class=SensorDeviceClass.TIMESTAMP,
value_fn=datetime.fromisoformat,
),
RehlkoSensorEntityDescription(
key="lastMaintenanceTimestamp",
translation_key="last_maintainance",
device_class=SensorDeviceClass.TIMESTAMP,
document_key=GENERATOR_DATA_DEVICE,
value_fn=datetime.fromisoformat,
entity_registry_enabled_default=False,
),
RehlkoSensorEntityDescription(
key="nextMaintenanceTimestamp",
translation_key="next_maintainance",
device_class=SensorDeviceClass.TIMESTAMP,
document_key=GENERATOR_DATA_DEVICE,
value_fn=datetime.fromisoformat,
entity_registry_enabled_default=False,
),
RehlkoSensorEntityDescription(
key="lastStartTimestamp",
translation_key="last_exercise",
device_class=SensorDeviceClass.TIMESTAMP,
document_key=GENERATOR_DATA_EXERCISE,
value_fn=datetime.fromisoformat,
entity_registry_enabled_default=False,
),
RehlkoSensorEntityDescription(
key="nextStartTimestamp",
translation_key="next_exercise",
device_class=SensorDeviceClass.TIMESTAMP,
document_key=GENERATOR_DATA_EXERCISE,
value_fn=datetime.fromisoformat,
entity_registry_enabled_default=False,
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: RehlkoConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up sensors."""
homes = config_entry.runtime_data.homes
coordinators = config_entry.runtime_data.coordinators
async_add_entities(
RehlkoSensorEntity(
coordinators[device_data[DEVICE_DATA_ID]],
device_data[DEVICE_DATA_ID],
device_data,
sensor_description,
sensor_description.document_key,
)
for home_data in homes
for device_data in home_data[DEVICE_DATA_DEVICES]
for sensor_description in SENSORS
)
class RehlkoSensorEntity(RehlkoEntity, SensorEntity):
"""Representation of a Rehlko sensor."""
entity_description: RehlkoSensorEntityDescription
@property
def native_value(self) -> StateType | datetime:
"""Return the sensor state."""
if self.entity_description.value_fn:
return self.entity_description.value_fn(self._rehlko_value)
return self._rehlko_value
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/rehlko/sensor.py",
"license": "Apache License 2.0",
"lines": 249,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/remote_calendar/ics.py | """Module for parsing ICS content.
This module exists to fix known issues where calendar providers return calendars
that do not follow rfcc5545. This module will attempt to fix the calendar and return
a valid calendar object.
"""
import logging
from ical.calendar import Calendar
from ical.calendar_stream import IcsCalendarStream
from ical.compat import enable_compat_mode
from ical.exceptions import CalendarParseError
from homeassistant.core import HomeAssistant
_LOGGER = logging.getLogger(__name__)
class InvalidIcsException(Exception):
"""Exception to indicate that the ICS content is invalid."""
def _compat_calendar_from_ics(ics: str) -> Calendar:
"""Parse the ICS content and return a Calendar object.
This function is called in a separate thread to avoid blocking the event
loop while loading packages or parsing the ICS content for large calendars.
It uses the `enable_compat_mode` context manager to fix known issues with
calendar providers that return invalid calendars.
"""
with enable_compat_mode(ics) as compat_ics:
return IcsCalendarStream.calendar_from_ics(compat_ics)
async def parse_calendar(hass: HomeAssistant, ics: str) -> Calendar:
"""Parse the ICS content and return a Calendar object."""
try:
return await hass.async_add_executor_job(_compat_calendar_from_ics, ics)
except CalendarParseError as err:
_LOGGER.error("Error parsing calendar information: %s", err.message)
_LOGGER.debug("Additional calendar error detail: %s", str(err.detailed_error))
raise InvalidIcsException(err.message) from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/remote_calendar/ics.py",
"license": "Apache License 2.0",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
home-assistant/core:homeassistant/components/shelly/repairs.py | """Repairs flow for Shelly."""
from __future__ import annotations
from typing import TYPE_CHECKING
from aioshelly.block_device import BlockDevice
from aioshelly.const import MODEL_OUT_PLUG_S_G3, MODEL_PLUG_S_G3, RPC_GENERATIONS
from aioshelly.exceptions import DeviceConnectionError, RpcCallError
from aioshelly.rpc_device import RpcDevice
from awesomeversion import AwesomeVersion
import voluptuous as vol
from homeassistant import data_entry_flow
from homeassistant.components.repairs import ConfirmRepairFlow, RepairsFlow
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import issue_registry as ir
from .const import (
BLE_SCANNER_FIRMWARE_UNSUPPORTED_ISSUE_ID,
BLE_SCANNER_MIN_FIRMWARE,
CONF_BLE_SCANNER_MODE,
DEPRECATED_FIRMWARE_ISSUE_ID,
DEPRECATED_FIRMWARES,
DOMAIN,
OPEN_WIFI_AP_ISSUE_ID,
OUTBOUND_WEBSOCKET_INCORRECTLY_ENABLED_ISSUE_ID,
BLEScannerMode,
)
from .coordinator import ShellyConfigEntry
from .utils import (
get_coiot_address,
get_coiot_port,
get_device_entry_gen,
get_rpc_ws_url,
)
@callback
def async_manage_ble_scanner_firmware_unsupported_issue(
hass: HomeAssistant,
entry: ShellyConfigEntry,
) -> None:
"""Manage the BLE scanner firmware unsupported issue."""
issue_id = BLE_SCANNER_FIRMWARE_UNSUPPORTED_ISSUE_ID.format(unique=entry.unique_id)
if TYPE_CHECKING:
assert entry.runtime_data.rpc is not None
device = entry.runtime_data.rpc.device
supports_scripts = entry.runtime_data.rpc_supports_scripts
if supports_scripts and device.model not in (MODEL_PLUG_S_G3, MODEL_OUT_PLUG_S_G3):
firmware = AwesomeVersion(device.shelly["ver"])
if (
firmware < BLE_SCANNER_MIN_FIRMWARE
and entry.options.get(CONF_BLE_SCANNER_MODE) == BLEScannerMode.ACTIVE
):
ir.async_create_issue(
hass,
DOMAIN,
issue_id,
is_fixable=True,
is_persistent=True,
severity=ir.IssueSeverity.WARNING,
translation_key="ble_scanner_firmware_unsupported",
translation_placeholders={
"device_name": device.name,
"ip_address": device.ip_address,
"firmware": firmware,
},
data={"entry_id": entry.entry_id},
)
return
ir.async_delete_issue(hass, DOMAIN, issue_id)
@callback
def async_manage_deprecated_firmware_issue(
hass: HomeAssistant,
entry: ShellyConfigEntry,
) -> None:
"""Manage deprecated firmware issue."""
issue_id = DEPRECATED_FIRMWARE_ISSUE_ID.format(unique=entry.unique_id)
if TYPE_CHECKING:
assert entry.runtime_data.rpc is not None
device = entry.runtime_data.rpc.device
model = entry.data["model"]
if model in DEPRECATED_FIRMWARES:
min_firmware = DEPRECATED_FIRMWARES[model]["min_firmware"]
ha_version = DEPRECATED_FIRMWARES[model]["ha_version"]
firmware = AwesomeVersion(device.shelly["ver"])
if firmware < min_firmware:
ir.async_create_issue(
hass,
DOMAIN,
issue_id,
is_fixable=True,
is_persistent=True,
severity=ir.IssueSeverity.WARNING,
translation_key="deprecated_firmware",
translation_placeholders={
"device_name": device.name,
"ip_address": device.ip_address,
"firmware": firmware,
"ha_version": ha_version,
},
data={"entry_id": entry.entry_id},
)
return
ir.async_delete_issue(hass, DOMAIN, issue_id)
@callback
def async_manage_outbound_websocket_incorrectly_enabled_issue(
hass: HomeAssistant,
entry: ShellyConfigEntry,
) -> None:
"""Manage the Outbound WebSocket incorrectly enabled issue."""
issue_id = OUTBOUND_WEBSOCKET_INCORRECTLY_ENABLED_ISSUE_ID.format(
unique=entry.unique_id
)
if TYPE_CHECKING:
assert entry.runtime_data.rpc is not None
device = entry.runtime_data.rpc.device
if (
(ws_config := device.config.get("ws"))
and ws_config["enable"]
and ws_config["server"] == get_rpc_ws_url(hass)
):
ir.async_create_issue(
hass,
DOMAIN,
issue_id,
is_fixable=True,
is_persistent=True,
severity=ir.IssueSeverity.WARNING,
translation_key="outbound_websocket_incorrectly_enabled",
translation_placeholders={
"device_name": device.name,
"ip_address": device.ip_address,
},
data={"entry_id": entry.entry_id},
)
return
ir.async_delete_issue(hass, DOMAIN, issue_id)
@callback
def async_manage_open_wifi_ap_issue(
hass: HomeAssistant,
entry: ShellyConfigEntry,
) -> None:
"""Manage the open WiFi AP issue."""
issue_id = OPEN_WIFI_AP_ISSUE_ID.format(unique=entry.unique_id)
if TYPE_CHECKING:
assert entry.runtime_data.rpc is not None
device = entry.runtime_data.rpc.device
# Check if WiFi AP is enabled and is open (no password)
if (
(wifi_config := device.config.get("wifi"))
and (ap_config := wifi_config.get("ap"))
and ap_config.get("enable")
and ap_config.get("is_open")
):
ir.async_create_issue(
hass,
DOMAIN,
issue_id,
is_fixable=True,
is_persistent=False,
severity=ir.IssueSeverity.WARNING,
translation_key="open_wifi_ap",
translation_placeholders={
"device_name": device.name,
"ip_address": device.ip_address,
},
data={"entry_id": entry.entry_id},
)
return
ir.async_delete_issue(hass, DOMAIN, issue_id)
class ShellyBlockRepairsFlow(RepairsFlow):
"""Handler for an issue fixing flow."""
def __init__(self, device: BlockDevice) -> None:
"""Initialize."""
self._device = device
class CoiotConfigureFlow(ShellyBlockRepairsFlow):
"""Handler for fixing CoIoT configuration flow."""
async def async_step_init(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the first step of a fix flow."""
issue_registry = ir.async_get(self.hass)
description_placeholders = None
if issue := issue_registry.async_get_issue(DOMAIN, self.issue_id):
description_placeholders = issue.translation_placeholders
return self.async_show_menu(
menu_options=["confirm", "ignore"],
description_placeholders=description_placeholders,
)
async def async_step_confirm(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the confirm step of a fix flow."""
coiot_addr = await get_coiot_address(self.hass)
coiot_port = get_coiot_port(self.hass)
if coiot_addr is None or coiot_port is None:
return self.async_abort(reason="cannot_configure")
try:
await self._device.configure_coiot_protocol(coiot_addr, coiot_port)
await self._device.trigger_reboot()
except DeviceConnectionError:
return self.async_abort(reason="cannot_connect")
return self.async_create_entry(title="", data={})
async def async_step_ignore(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the ignore step of a fix flow."""
ir.async_ignore_issue(self.hass, DOMAIN, self.issue_id, True)
return self.async_abort(reason="issue_ignored")
class ShellyRpcRepairsFlow(RepairsFlow):
"""Handler for an issue fixing flow."""
def __init__(self, device: RpcDevice) -> None:
"""Initialize."""
self._device = device
async def async_step_init(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the first step of a fix flow."""
return await self.async_step_confirm()
async def async_step_confirm(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the confirm step of a fix flow."""
if user_input is not None:
return await self._async_step_confirm()
issue_registry = ir.async_get(self.hass)
description_placeholders = None
if issue := issue_registry.async_get_issue(self.handler, self.issue_id):
description_placeholders = issue.translation_placeholders
return self.async_show_form(
step_id="confirm",
data_schema=vol.Schema({}),
description_placeholders=description_placeholders,
)
async def _async_step_confirm(self) -> data_entry_flow.FlowResult:
"""Handle the confirm step of a fix flow."""
raise NotImplementedError
class FirmwareUpdateFlow(ShellyRpcRepairsFlow):
"""Handler for Firmware Update flow."""
async def _async_step_confirm(self) -> data_entry_flow.FlowResult:
"""Handle the confirm step of a fix flow."""
return await self.async_step_update_firmware()
async def async_step_update_firmware(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the confirm step of a fix flow."""
if not self._device.status["sys"]["available_updates"]:
return self.async_abort(reason="update_not_available")
try:
await self._device.trigger_ota_update()
except DeviceConnectionError, RpcCallError:
return self.async_abort(reason="cannot_connect")
return self.async_create_entry(title="", data={})
class DisableOutboundWebSocketFlow(ShellyRpcRepairsFlow):
"""Handler for Disable Outbound WebSocket flow."""
async def _async_step_confirm(self) -> data_entry_flow.FlowResult:
"""Handle the confirm step of a fix flow."""
return await self.async_step_disable_outbound_websocket()
async def async_step_disable_outbound_websocket(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the confirm step of a fix flow."""
try:
result = await self._device.ws_setconfig(
False, self._device.config["ws"]["server"]
)
if result["restart_required"]:
await self._device.trigger_reboot()
except DeviceConnectionError, RpcCallError:
return self.async_abort(reason="cannot_connect")
return self.async_create_entry(title="", data={})
class DisableOpenWiFiApFlow(RepairsFlow):
"""Handler for Disable Open WiFi AP flow."""
def __init__(self, device: RpcDevice, issue_id: str) -> None:
"""Initialize."""
self._device = device
self.issue_id = issue_id
async def async_step_init(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the first step of a fix flow."""
issue_registry = ir.async_get(self.hass)
description_placeholders = None
if issue := issue_registry.async_get_issue(DOMAIN, self.issue_id):
description_placeholders = issue.translation_placeholders
return self.async_show_menu(
menu_options=["confirm", "ignore"],
description_placeholders=description_placeholders,
)
async def async_step_confirm(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the confirm step of a fix flow."""
try:
result = await self._device.wifi_setconfig(ap_enable=False)
if result.get("restart_required"):
await self._device.trigger_reboot()
except DeviceConnectionError, RpcCallError:
return self.async_abort(reason="cannot_connect")
return self.async_create_entry(title="", data={})
async def async_step_ignore(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the ignore step of a fix flow."""
ir.async_ignore_issue(self.hass, DOMAIN, self.issue_id, True)
return self.async_abort(reason="issue_ignored")
async def async_create_fix_flow(
hass: HomeAssistant, issue_id: str, data: dict[str, str] | None
) -> RepairsFlow:
"""Create flow."""
if TYPE_CHECKING:
assert isinstance(data, dict)
entry_id = data["entry_id"]
entry = hass.config_entries.async_get_entry(entry_id)
if TYPE_CHECKING:
assert entry is not None
if get_device_entry_gen(entry) in RPC_GENERATIONS:
device = entry.runtime_data.rpc.device
else:
device = entry.runtime_data.block.device
if "coiot_unconfigured" in issue_id:
return CoiotConfigureFlow(device)
if (
"ble_scanner_firmware_unsupported" in issue_id
or "deprecated_firmware" in issue_id
):
return FirmwareUpdateFlow(device)
if "outbound_websocket_incorrectly_enabled" in issue_id:
return DisableOutboundWebSocketFlow(device)
if "open_wifi_ap" in issue_id:
return DisableOpenWiFiApFlow(device, issue_id)
return ConfirmRepairFlow()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/shelly/repairs.py",
"license": "Apache License 2.0",
"lines": 327,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/ssdp/websocket_api.py | """The ssdp integration websocket apis."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any, Final
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.core import HassJob, HomeAssistant, callback
from homeassistant.helpers.json import json_bytes
from homeassistant.helpers.service_info.ssdp import (
ATTR_UPNP_FRIENDLY_NAME,
SsdpServiceInfo,
)
from .const import DOMAIN, SSDP_SCANNER
from .scanner import Scanner, SsdpChange
FIELD_SSDP_ST: Final = "ssdp_st"
FIELD_SSDP_LOCATION: Final = "ssdp_location"
@callback
def async_setup(hass: HomeAssistant) -> None:
"""Set up the ssdp websocket API."""
websocket_api.async_register_command(hass, ws_subscribe_discovery)
@websocket_api.require_admin
@websocket_api.websocket_command(
{
vol.Required("type"): "ssdp/subscribe_discovery",
}
)
@websocket_api.async_response
async def ws_subscribe_discovery(
hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle subscribe advertisements websocket command."""
scanner: Scanner = hass.data[DOMAIN][SSDP_SCANNER]
msg_id: int = msg["id"]
def _async_event_message(message: dict[str, Any]) -> None:
connection.send_message(
json_bytes(websocket_api.event_message(msg_id, message))
)
@callback
def _async_on_data(info: SsdpServiceInfo, change: SsdpChange) -> None:
if change is not SsdpChange.BYEBYE:
_async_event_message(
{
"add": [
{"name": info.upnp.get(ATTR_UPNP_FRIENDLY_NAME), **asdict(info)}
]
}
)
return
remove_msg = {
FIELD_SSDP_ST: info.ssdp_st,
FIELD_SSDP_LOCATION: info.ssdp_location,
}
_async_event_message({"remove": [remove_msg]})
job = HassJob(_async_on_data)
connection.send_message(json_bytes(websocket_api.result_message(msg_id)))
connection.subscriptions[msg_id] = await scanner.async_register_callback(job, None)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ssdp/websocket_api.py",
"license": "Apache License 2.0",
"lines": 56,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/stiebel_eltron/config_flow.py | """Config flow for the STIEBEL ELTRON integration."""
from __future__ import annotations
import logging
from typing import Any
from pymodbus.client import ModbusTcpClient
from pystiebeleltron.pystiebeleltron import StiebelEltronAPI
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT
from .const import DEFAULT_PORT, DOMAIN
_LOGGER = logging.getLogger(__name__)
class StiebelEltronConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for STIEBEL ELTRON."""
VERSION = 1
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_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT]}
)
client = StiebelEltronAPI(
ModbusTcpClient(user_input[CONF_HOST], port=user_input[CONF_PORT]), 1
)
try:
success = await self.hass.async_add_executor_job(client.update)
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
if not success:
errors["base"] = "cannot_connect"
if not errors:
return self.async_create_entry(title="Stiebel Eltron", data=user_input)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Required(CONF_PORT, default=DEFAULT_PORT): int,
}
),
errors=errors,
)
async def async_step_import(self, user_input: dict[str, Any]) -> ConfigFlowResult:
"""Handle import."""
self._async_abort_entries_match(
{CONF_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT]}
)
client = StiebelEltronAPI(
ModbusTcpClient(user_input[CONF_HOST], port=user_input[CONF_PORT]), 1
)
try:
success = await self.hass.async_add_executor_job(client.update)
except Exception:
_LOGGER.exception("Unexpected exception")
return self.async_abort(reason="unknown")
if not success:
return self.async_abort(reason="cannot_connect")
return self.async_create_entry(
title=user_input[CONF_NAME],
data={
CONF_HOST: user_input[CONF_HOST],
CONF_PORT: user_input[CONF_PORT],
},
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/stiebel_eltron/config_flow.py",
"license": "Apache License 2.0",
"lines": 68,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/stiebel_eltron/const.py | """Constants for the STIEBEL ELTRON integration."""
DOMAIN = "stiebel_eltron"
CONF_HUB = "hub"
DEFAULT_HUB = "modbus_hub"
DEFAULT_PORT = 502
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/stiebel_eltron/const.py",
"license": "Apache License 2.0",
"lines": 5,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/switchbot/fan.py | """Support for SwitchBot Fans."""
from __future__ import annotations
import logging
from typing import Any
import switchbot
from switchbot import AirPurifierMode, FanMode
from homeassistant.components.fan import FanEntity, FanEntityFeature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.restore_state import RestoreEntity
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 fan based on a config entry."""
coordinator = entry.runtime_data
if isinstance(coordinator.device, switchbot.SwitchbotAirPurifier):
async_add_entities([SwitchBotAirPurifierEntity(coordinator)])
else:
async_add_entities([SwitchBotFanEntity(coordinator)])
class SwitchBotFanEntity(SwitchbotEntity, FanEntity, RestoreEntity):
"""Representation of a Switchbot."""
_device: switchbot.SwitchbotFan
_attr_supported_features = (
FanEntityFeature.SET_SPEED
| FanEntityFeature.OSCILLATE
| FanEntityFeature.PRESET_MODE
| FanEntityFeature.TURN_OFF
| FanEntityFeature.TURN_ON
)
_attr_preset_modes = FanMode.get_modes()
_attr_translation_key = "fan"
_attr_name = None
def __init__(self, coordinator: SwitchbotDataUpdateCoordinator) -> None:
"""Initialize the switchbot."""
super().__init__(coordinator)
self._attr_is_on = False
@property
def is_on(self) -> bool | None:
"""Return true if device is on."""
return self._device.is_on()
@property
def percentage(self) -> int | None:
"""Return the current speed as a percentage."""
return self._device.get_current_percentage()
@property
def oscillating(self) -> bool | None:
"""Return whether or not the fan is currently oscillating."""
return self._device.get_oscillating_state()
@property
def preset_mode(self) -> str | None:
"""Return the current preset mode."""
return self._device.get_current_mode()
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the fan."""
_LOGGER.debug(
"Switchbot fan to set preset mode %s %s", preset_mode, self._address
)
self._last_run_success = bool(await self._device.set_preset_mode(preset_mode))
self.async_write_ha_state()
async def async_set_percentage(self, percentage: int) -> None:
"""Set the speed percentage of the fan."""
_LOGGER.debug(
"Switchbot fan to set percentage %d %s", percentage, self._address
)
self._last_run_success = bool(await self._device.set_percentage(percentage))
self.async_write_ha_state()
async def async_oscillate(self, oscillating: bool) -> None:
"""Oscillate the fan."""
_LOGGER.debug(
"Switchbot fan to set oscillating %s %s", oscillating, self._address
)
self._last_run_success = bool(await self._device.set_oscillation(oscillating))
self.async_write_ha_state()
async def async_turn_on(
self,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn on the fan."""
_LOGGER.debug(
"Switchbot fan to set turn on %s %s %s",
percentage,
preset_mode,
self._address,
)
self._last_run_success = bool(await self._device.turn_on())
self.async_write_ha_state()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the fan."""
_LOGGER.debug("Switchbot fan to set turn off %s", self._address)
self._last_run_success = bool(await self._device.turn_off())
self.async_write_ha_state()
class SwitchBotAirPurifierEntity(SwitchbotEntity, FanEntity):
"""Representation of a Switchbot air purifier."""
_device: switchbot.SwitchbotAirPurifier
_attr_supported_features = (
FanEntityFeature.PRESET_MODE
| FanEntityFeature.TURN_OFF
| FanEntityFeature.TURN_ON
)
_attr_preset_modes = AirPurifierMode.get_modes()
_attr_translation_key = "air_purifier"
_attr_name = None
@property
def is_on(self) -> bool | None:
"""Return true if device is on."""
return self._device.is_on()
@property
def preset_mode(self) -> str | None:
"""Return the current preset mode."""
return self._device.get_current_mode()
@exception_handler
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the air purifier."""
_LOGGER.debug(
"Switchbot air purifier to set preset mode %s %s",
preset_mode,
self._address,
)
self._last_run_success = bool(await self._device.set_preset_mode(preset_mode))
self.async_write_ha_state()
@exception_handler
async def async_turn_on(
self,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn on the air purifier."""
_LOGGER.debug(
"Switchbot air purifier to set turn on %s %s %s",
percentage,
preset_mode,
self._address,
)
self._last_run_success = bool(await self._device.turn_on())
self.async_write_ha_state()
@exception_handler
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the air purifier."""
_LOGGER.debug("Switchbot air purifier to set turn off %s", self._address)
self._last_run_success = bool(await self._device.turn_off())
self.async_write_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/switchbot/fan.py",
"license": "Apache License 2.0",
"lines": 150,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/whirlpool/binary_sensor.py | """Binary sensors for the Whirlpool Appliances integration."""
from collections.abc import Callable
from dataclasses import dataclass
from datetime import timedelta
from whirlpool.appliance import Appliance
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import WhirlpoolConfigEntry
from .entity import WhirlpoolEntity
PARALLEL_UPDATES = 1
SCAN_INTERVAL = timedelta(minutes=5)
@dataclass(frozen=True, kw_only=True)
class WhirlpoolBinarySensorEntityDescription(BinarySensorEntityDescription):
"""Describes a Whirlpool binary sensor entity."""
value_fn: Callable[[Appliance], bool | None]
WASHER_DRYER_SENSORS: list[WhirlpoolBinarySensorEntityDescription] = [
WhirlpoolBinarySensorEntityDescription(
key="door",
device_class=BinarySensorDeviceClass.DOOR,
value_fn=lambda appliance: appliance.get_door_open(),
)
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: WhirlpoolConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Config flow entry for Whirlpool binary sensors."""
appliances_manager = config_entry.runtime_data
washer_binary_sensors = [
WhirlpoolBinarySensor(washer, description)
for washer in appliances_manager.washers
for description in WASHER_DRYER_SENSORS
]
dryer_binary_sensors = [
WhirlpoolBinarySensor(dryer, description)
for dryer in appliances_manager.dryers
for description in WASHER_DRYER_SENSORS
]
async_add_entities([*washer_binary_sensors, *dryer_binary_sensors])
class WhirlpoolBinarySensor(WhirlpoolEntity, BinarySensorEntity):
"""A class for the Whirlpool binary sensors."""
def __init__(
self, appliance: Appliance, description: WhirlpoolBinarySensorEntityDescription
) -> None:
"""Initialize the washer sensor."""
super().__init__(appliance, unique_id_suffix=f"-{description.key}")
self.entity_description: WhirlpoolBinarySensorEntityDescription = description
@property
def is_on(self) -> bool | None:
"""Return true if the binary sensor is on."""
return self.entity_description.value_fn(self._appliance)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/whirlpool/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 57,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/adax/test_climate.py | """Test Adax climate entity."""
from homeassistant.components.adax.const import SCAN_INTERVAL
from homeassistant.components.climate import ATTR_CURRENT_TEMPERATURE, HVACMode
from homeassistant.const import ATTR_TEMPERATURE, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from . import setup_integration
from .conftest import CLOUD_DEVICE_DATA, LOCAL_DEVICE_DATA
from tests.common import AsyncMock, MockConfigEntry, async_fire_time_changed
from tests.test_setup import FrozenDateTimeFactory
async def test_climate_cloud(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_cloud_config_entry: MockConfigEntry,
mock_adax_cloud: AsyncMock,
) -> None:
"""Test states of the (cloud) Climate entity."""
await setup_integration(hass, mock_cloud_config_entry)
mock_adax_cloud.fetch_rooms_info.assert_called_once()
assert len(hass.states.async_entity_ids(Platform.CLIMATE)) == 1
entity_id = hass.states.async_entity_ids(Platform.CLIMATE)[0]
state = hass.states.get(entity_id)
assert state
assert state.state == HVACMode.HEAT
assert (
state.attributes[ATTR_TEMPERATURE] == CLOUD_DEVICE_DATA[0]["targetTemperature"]
)
assert (
state.attributes[ATTR_CURRENT_TEMPERATURE]
== CLOUD_DEVICE_DATA[0]["temperature"]
)
mock_adax_cloud.fetch_rooms_info.side_effect = Exception()
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNAVAILABLE
async def test_climate_local(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_local_config_entry: MockConfigEntry,
mock_adax_local: AsyncMock,
) -> None:
"""Test states of the (local) Climate entity."""
await setup_integration(hass, mock_local_config_entry)
mock_adax_local.get_status.assert_called_once()
assert len(hass.states.async_entity_ids(Platform.CLIMATE)) == 1
entity_id = hass.states.async_entity_ids(Platform.CLIMATE)[0]
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == HVACMode.HEAT
assert (
state.attributes[ATTR_TEMPERATURE] == (LOCAL_DEVICE_DATA["target_temperature"])
)
assert (
state.attributes[ATTR_CURRENT_TEMPERATURE]
== (LOCAL_DEVICE_DATA["current_temperature"])
)
mock_adax_local.get_status.side_effect = Exception()
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/adax/test_climate.py",
"license": "Apache License 2.0",
"lines": 68,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/aws_s3/const.py | """Consts for AWS S3 tests."""
from homeassistant.components.aws_s3.const import (
CONF_ACCESS_KEY_ID,
CONF_BUCKET,
CONF_ENDPOINT_URL,
CONF_PREFIX,
CONF_SECRET_ACCESS_KEY,
)
# What gets persisted in the config entry (empty prefix is not stored)
CONFIG_ENTRY_DATA = {
CONF_ACCESS_KEY_ID: "TestTestTestTestTest",
CONF_SECRET_ACCESS_KEY: "TestTestTestTestTestTestTestTestTestTest",
CONF_ENDPOINT_URL: "https://s3.eu-south-1.amazonaws.com",
CONF_BUCKET: "test",
}
# What users submit to the flow (can include empty prefix)
USER_INPUT = {
**CONFIG_ENTRY_DATA,
CONF_PREFIX: "",
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/aws_s3/const.py",
"license": "Apache License 2.0",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/aws_s3/test_backup.py | """Test the AWS S3 backup platform."""
from collections.abc import AsyncGenerator
from io import StringIO
import json
from time import time
from unittest.mock import ANY, AsyncMock, Mock, patch
from botocore.exceptions import ConnectTimeoutError
import pytest
from homeassistant.components.aws_s3.backup import (
MULTIPART_MIN_PART_SIZE_BYTES,
BotoCoreError,
S3BackupAgent,
async_register_backup_agents_listener,
suggested_filenames,
)
from homeassistant.components.aws_s3.const import (
CONF_ENDPOINT_URL,
DATA_BACKUP_AGENT_LISTENERS,
DOMAIN,
)
from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, AgentBackup
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import setup_integration
from .const import USER_INPUT
from tests.common import MockConfigEntry
from tests.typing import ClientSessionGenerator, MagicMock, WebSocketGenerator
@pytest.fixture(autouse=True)
async def setup_backup_integration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> AsyncGenerator[None]:
"""Set up S3 integration."""
with (
patch("homeassistant.components.backup.is_hassio", return_value=False),
patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0),
):
assert await async_setup_component(hass, BACKUP_DOMAIN, {})
await setup_integration(hass, mock_config_entry)
await hass.async_block_till_done()
yield
async def test_suggested_filenames() -> None:
"""Test the suggested_filenames function."""
backup = AgentBackup(
backup_id="a1b2c3",
date="2021-01-01T01:02:03+00:00",
addons=[],
database_included=False,
extra_metadata={},
folders=[],
homeassistant_included=False,
homeassistant_version=None,
name="my_pretty_backup",
protected=False,
size=0,
)
tar_filename, metadata_filename = suggested_filenames(backup)
assert tar_filename == "my_pretty_backup_2021-01-01_01.02_03000000.tar"
assert (
metadata_filename == "my_pretty_backup_2021-01-01_01.02_03000000.metadata.json"
)
async def test_agents_info(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test backup agent info."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/agents/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
"agents": [
{"agent_id": "backup.local", "name": "local"},
{
"agent_id": f"{DOMAIN}.{mock_config_entry.entry_id}",
"name": mock_config_entry.title,
},
],
}
async def test_agents_list_backups(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test agent list backups."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backups"] == [
{
"addons": test_backup.addons,
"agents": {
f"{DOMAIN}.{mock_config_entry.entry_id}": {
"protected": test_backup.protected,
"size": test_backup.size,
}
},
"backup_id": test_backup.backup_id,
"database_included": test_backup.database_included,
"date": test_backup.date,
"extra_metadata": test_backup.extra_metadata,
"failed_addons": [],
"failed_agent_ids": [],
"failed_folders": [],
"folders": test_backup.folders,
"homeassistant_included": test_backup.homeassistant_included,
"homeassistant_version": test_backup.homeassistant_version,
"name": test_backup.name,
"with_automatic_settings": None,
}
]
async def test_agents_get_backup(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test agent get backup."""
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": test_backup.backup_id}
)
response = await client.receive_json()
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backup"] == {
"addons": test_backup.addons,
"agents": {
f"{DOMAIN}.{mock_config_entry.entry_id}": {
"protected": test_backup.protected,
"size": test_backup.size,
}
},
"backup_id": test_backup.backup_id,
"database_included": test_backup.database_included,
"date": test_backup.date,
"extra_metadata": test_backup.extra_metadata,
"failed_addons": [],
"failed_agent_ids": [],
"failed_folders": [],
"folders": test_backup.folders,
"homeassistant_included": test_backup.homeassistant_included,
"homeassistant_version": test_backup.homeassistant_version,
"name": test_backup.name,
"with_automatic_settings": None,
}
async def test_agents_get_backup_does_not_throw_on_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_client: MagicMock,
) -> None:
"""Test agent get backup does not throw on a backup not found."""
mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [
{"Contents": []}
]
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/details", "backup_id": "random"})
response = await client.receive_json()
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backup"] is None
async def test_agents_list_backups_with_corrupted_metadata(
hass: HomeAssistant,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
test_backup: AgentBackup,
) -> None:
"""Test listing backups when one metadata file is corrupted."""
# Create agent
agent = S3BackupAgent(hass, mock_config_entry)
# Set up mock responses for both valid and corrupted metadata files
mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [
{
"Contents": [
{
"Key": "valid_backup.metadata.json",
"LastModified": "2023-01-01T00:00:00+00:00",
},
{
"Key": "corrupted_backup.metadata.json",
"LastModified": "2023-01-01T00:00:00+00:00",
},
]
}
]
# Mock responses for get_object calls
valid_metadata = json.dumps(test_backup.as_dict())
corrupted_metadata = "{invalid json content"
async def mock_get_object(**kwargs):
"""Mock get_object with different responses based on the key."""
key = kwargs.get("Key", "")
if "valid_backup" in key:
mock_body = AsyncMock()
mock_body.read.return_value = valid_metadata.encode()
return {"Body": mock_body}
# Corrupted metadata
mock_body = AsyncMock()
mock_body.read.return_value = corrupted_metadata.encode()
return {"Body": mock_body}
mock_client.get_object.side_effect = mock_get_object
backups = await agent.async_list_backups()
assert len(backups) == 1
assert backups[0].backup_id == test_backup.backup_id
assert "Failed to process metadata file" in caplog.text
async def test_agents_delete(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_client: MagicMock,
) -> None:
"""Test agent delete backup."""
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": "23e64aec",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {"agent_errors": {}}
# Should delete both the tar and the metadata file
assert mock_client.delete_object.call_count == 2
async def test_agents_delete_not_throwing_on_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_client: MagicMock,
) -> None:
"""Test agent delete backup does not throw on a backup not found."""
mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [
{"Contents": []}
]
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": "random",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {"agent_errors": {}}
assert mock_client.delete_object.call_count == 0
async def test_agents_upload(
hass_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test agent upload backup."""
client = await hass_client()
with (
patch(
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
return_value=test_backup,
),
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=test_backup,
),
patch("pathlib.Path.open") as mocked_open,
):
# we must emit at least two chunks
# the "appendix" chunk triggers the upload of the final buffer part
mocked_open.return_value.read = Mock(
side_effect=[
b"a" * test_backup.size,
b"appendix",
b"",
]
)
resp = await client.post(
f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.entry_id}",
data={"file": StringIO("test")},
)
assert resp.status == 201
assert f"Uploading backup {test_backup.backup_id}" in caplog.text
if test_backup.size < MULTIPART_MIN_PART_SIZE_BYTES:
# single part + metadata both as regular upload (no multiparts)
assert mock_client.create_multipart_upload.await_count == 0
assert mock_client.put_object.await_count == 2
else:
assert "Uploading final part" in caplog.text
# 2 parts as multipart + metadata as regular upload
assert mock_client.create_multipart_upload.await_count == 1
assert mock_client.upload_part.await_count == 2
assert mock_client.complete_multipart_upload.await_count == 1
assert mock_client.put_object.await_count == 1
async def test_agents_upload_network_failure(
hass_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test agent upload backup with network failure."""
client = await hass_client()
with (
patch(
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
return_value=test_backup,
),
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=test_backup,
),
patch("pathlib.Path.open") as mocked_open,
):
mocked_open.return_value.read = Mock(side_effect=[b"test", b""])
# simulate network failure
mock_client.put_object.side_effect = mock_client.upload_part.side_effect = (
mock_client.abort_multipart_upload.side_effect
) = ConnectTimeoutError(endpoint_url=USER_INPUT[CONF_ENDPOINT_URL])
resp = await client.post(
f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.entry_id}",
data={"file": StringIO("test")},
)
assert resp.status == 201
assert "Upload failed for aws_s3" in caplog.text
async def test_agents_download(
hass_client: ClientSessionGenerator,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test agent download backup."""
client = await hass_client()
backup_id = "23e64aec"
resp = await client.get(
f"/api/backup/download/{backup_id}?agent_id={DOMAIN}.{mock_config_entry.entry_id}"
)
assert resp.status == 200
assert await resp.content.read() == b"backup data"
# Coordinator first refresh reads metadata (1) + download reads metadata (1) + tar (1)
assert mock_client.get_object.call_count == 3
async def test_error_during_delete(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test the error wrapper."""
mock_client.delete_object.side_effect = BotoCoreError
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": test_backup.backup_id,
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
"agent_errors": {
f"{DOMAIN}.{mock_config_entry.entry_id}": "Failed during async_delete_backup"
}
}
async def test_cache_expiration(
hass: HomeAssistant,
mock_client: MagicMock,
test_backup: AgentBackup,
) -> None:
"""Test that the cache expires correctly."""
# Mock the entry
mock_entry = MockConfigEntry(
domain=DOMAIN,
data={"bucket": "test-bucket"},
unique_id="test-unique-id",
title="Test S3",
)
mock_entry.runtime_data = MagicMock(client=mock_client)
# Create agent
agent = S3BackupAgent(hass, mock_entry)
# Reset call counts from coordinator's initial refresh
mock_client.reset_mock()
# Mock metadata response
metadata_content = json.dumps(test_backup.as_dict())
mock_body = AsyncMock()
mock_body.read.return_value = metadata_content.encode()
mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [
{
"Contents": [
{
"Key": "test.metadata.json",
"LastModified": "2023-01-01T00:00:00+00:00",
}
]
}
]
mock_client.get_object.return_value = {"Body": mock_body}
# First call should query S3
await agent.async_list_backups()
assert mock_client.get_paginator.call_count == 1
assert mock_client.get_object.call_count == 1
# Second call should use cache
await agent.async_list_backups()
assert mock_client.get_paginator.call_count == 1
assert mock_client.get_object.call_count == 1
# Set cache to expire
agent._cache_expiration = time() - 1
# Third call should query S3 again
await agent.async_list_backups()
assert mock_client.get_paginator.call_count == 2
assert mock_client.get_object.call_count == 2
async def test_listeners_get_cleaned_up(hass: HomeAssistant) -> None:
"""Test listener gets cleaned up."""
listener = MagicMock()
remove_listener = async_register_backup_agents_listener(hass, listener=listener)
hass.data[DATA_BACKUP_AGENT_LISTENERS] = [
listener
] # make sure it's the last listener
remove_listener()
assert DATA_BACKUP_AGENT_LISTENERS not in hass.data
async def test_list_backups_with_pagination(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test listing backups when paginating through multiple pages."""
# Create agent
agent = S3BackupAgent(hass, mock_config_entry)
# Create two different backups
backup1 = AgentBackup(
backup_id="backup1",
date="2023-01-01T00:00:00+00:00",
addons=[],
database_included=False,
extra_metadata={},
folders=[],
homeassistant_included=False,
homeassistant_version=None,
name="Backup 1",
protected=False,
size=0,
)
backup2 = AgentBackup(
backup_id="backup2",
date="2023-01-02T00:00:00+00:00",
addons=[],
database_included=False,
extra_metadata={},
folders=[],
homeassistant_included=False,
homeassistant_version=None,
name="Backup 2",
protected=False,
size=0,
)
# Setup two pages of results
page1 = {
"Contents": [
{
"Key": "backup1.metadata.json",
"LastModified": "2023-01-01T00:00:00+00:00",
},
{"Key": "backup1.tar", "LastModified": "2023-01-01T00:00:00+00:00"},
]
}
page2 = {
"Contents": [
{
"Key": "backup2.metadata.json",
"LastModified": "2023-01-02T00:00:00+00:00",
},
{"Key": "backup2.tar", "LastModified": "2023-01-02T00:00:00+00:00"},
]
}
# Setup mock client
mock_client = mock_config_entry.runtime_data.client
mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [
page1,
page2,
]
# Mock get_object responses based on the key
async def mock_get_object(**kwargs):
"""Mock get_object with different responses based on the key."""
key = kwargs.get("Key", "")
if "backup1" in key:
mock_body = AsyncMock()
mock_body.read.return_value = json.dumps(backup1.as_dict()).encode()
return {"Body": mock_body}
# backup2
mock_body = AsyncMock()
mock_body.read.return_value = json.dumps(backup2.as_dict()).encode()
return {"Body": mock_body}
mock_client.get_object.side_effect = mock_get_object
# List backups and verify we got both
backups = await agent.async_list_backups()
assert len(backups) == 2
backup_ids = {backup.backup_id for backup in backups}
assert backup_ids == {"backup1", "backup2"}
@pytest.mark.parametrize(
("config_entry_extra_data", "expected_paginate_extra_kwargs"),
[
({"prefix": "backups/home"}, {"Prefix": "backups/home/"}),
({}, {}),
],
ids=["with_prefix", "no_prefix"],
)
async def test_agent_list_backups_parametrized(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
mock_client: MagicMock,
test_backup: AgentBackup,
config_entry_extra_data: dict,
expected_paginate_extra_kwargs: dict,
) -> None:
"""Test agent list backups with and without prefix."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"]["agent_errors"] == {}
# Verify pagination call with expected parameters
mock_client.get_paginator.return_value.paginate.assert_called_with(
**{"Bucket": "test"} | expected_paginate_extra_kwargs
)
@pytest.mark.parametrize(
("config_entry_extra_data", "expected_key_prefix"),
[
({"prefix": "backups/home"}, "backups/home/"),
({}, ""),
],
ids=["with_prefix", "no_prefix"],
)
async def test_agent_delete_backup_parametrized(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
expected_key_prefix: str,
) -> None:
"""Test agent delete backup with and without prefix."""
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": "23e64aec",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {"agent_errors": {}}
tar_filename, metadata_filename = suggested_filenames(test_backup)
expected_tar_key = f"{expected_key_prefix}{tar_filename}"
expected_metadata_key = f"{expected_key_prefix}{metadata_filename}"
mock_client.delete_object.assert_any_call(Bucket="test", Key=expected_tar_key)
mock_client.delete_object.assert_any_call(Bucket="test", Key=expected_metadata_key)
@pytest.mark.parametrize(
("config_entry_extra_data", "expected_key_prefix"),
[
({"prefix": "backups/home"}, "backups/home/"),
({}, ""),
],
ids=["with_prefix", "no_prefix"],
)
async def test_agent_upload_backup_parametrized(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
expected_key_prefix: str,
) -> None:
"""Test agent upload backup with and without prefix."""
client = await hass_client()
with (
patch(
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
return_value=test_backup,
),
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=test_backup,
),
patch("pathlib.Path.open") as mocked_open,
):
# we must emit at least two chunks
# the "appendix" chunk triggers the upload of the final buffer part
mocked_open.return_value.read = Mock(
side_effect=[
b"a" * test_backup.size,
b"appendix",
b"",
]
)
resp = await client.post(
f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.entry_id}",
data={"file": StringIO("test")},
)
assert resp.status == 201
tar_filename, metadata_filename = suggested_filenames(test_backup)
expected_tar_key = f"{expected_key_prefix}{tar_filename}"
expected_metadata_key = f"{expected_key_prefix}{metadata_filename}"
if test_backup.size < MULTIPART_MIN_PART_SIZE_BYTES:
mock_client.put_object.assert_any_call(
Bucket="test", Key=expected_tar_key, Body=ANY
)
mock_client.put_object.assert_any_call(
Bucket="test", Key=expected_metadata_key, Body=ANY
)
else:
mock_client.create_multipart_upload.assert_called_with(
Bucket="test", Key=expected_tar_key
)
mock_client.upload_part.assert_any_call(
Bucket="test",
Key=expected_tar_key,
PartNumber=1,
UploadId="upload_id",
Body=ANY,
)
mock_client.complete_multipart_upload.assert_called_with(
Bucket="test",
Key=expected_tar_key,
UploadId="upload_id",
MultipartUpload=ANY,
)
mock_client.put_object.assert_called_with(
Bucket="test", Key=expected_metadata_key, Body=ANY
)
@pytest.mark.parametrize(
("config_entry_extra_data", "expected_key_prefix"),
[
({"prefix": "backups/home"}, "backups/home/"),
({}, ""),
],
ids=["with_prefix", "no_prefix"],
)
async def test_agent_download_backup_parametrized(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
expected_key_prefix: str,
) -> None:
"""Test agent download backup with and without prefix."""
client = await hass_client()
backup_id = "23e64aec"
resp = await client.get(
f"/api/backup/download/{backup_id}?agent_id={DOMAIN}.{mock_config_entry.entry_id}"
)
assert resp.status == 200
assert await resp.content.read() == b"backup data"
tar_filename, _ = suggested_filenames(test_backup)
expected_tar_key = f"{expected_key_prefix}{tar_filename}"
mock_client.get_object.assert_any_call(Bucket="test", Key=expected_tar_key)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/aws_s3/test_backup.py",
"license": "Apache License 2.0",
"lines": 654,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/aws_s3/test_config_flow.py | """Test the AWS S3 config flow."""
from unittest.mock import AsyncMock, patch
from botocore.exceptions import (
ClientError,
EndpointConnectionError,
ParamValidationError,
)
import pytest
from homeassistant import config_entries
from homeassistant.components.aws_s3.const import (
CONF_BUCKET,
CONF_ENDPOINT_URL,
CONF_PREFIX,
DOMAIN,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import CONFIG_ENTRY_DATA, USER_INPUT
from tests.common import MockConfigEntry
async def _async_start_flow(
hass: HomeAssistant,
user_input: dict[str, str] | None = None,
) -> FlowResultType:
"""Initialize the config flow."""
if user_input is None:
user_input = USER_INPUT
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
return await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input,
)
@pytest.mark.parametrize(
("user_input", "expected_title", "expected_data"),
[
(USER_INPUT, "test", CONFIG_ENTRY_DATA),
(
USER_INPUT | {CONF_PREFIX: "my-prefix"},
"test - my-prefix",
USER_INPUT | {CONF_PREFIX: "my-prefix"},
),
(
USER_INPUT | {CONF_PREFIX: "/backups/"},
"test - backups",
CONFIG_ENTRY_DATA | {CONF_PREFIX: "backups"},
),
(
USER_INPUT | {CONF_PREFIX: "/"},
"test",
CONFIG_ENTRY_DATA,
),
(
USER_INPUT | {CONF_PREFIX: "my-prefix/"},
"test - my-prefix",
CONFIG_ENTRY_DATA | {CONF_PREFIX: "my-prefix"},
),
],
ids=[
"no_prefix",
"with_prefix",
"with_leading_and_trailing_slash",
"only_slash",
"with_trailing_slash",
],
)
async def test_flow(
hass: HomeAssistant,
user_input: dict,
expected_title: str,
expected_data: dict,
) -> None:
"""Test config flow with and without prefix, including prefix normalization."""
result = await _async_start_flow(hass, user_input)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == expected_title
assert result["data"] == expected_data
@pytest.mark.parametrize(
("exception", "errors"),
[
(
ParamValidationError(report="Invalid bucket name"),
{CONF_BUCKET: "invalid_bucket_name"},
),
(ValueError(), {CONF_ENDPOINT_URL: "invalid_endpoint_url"}),
(
EndpointConnectionError(endpoint_url="http://example.com"),
{CONF_ENDPOINT_URL: "cannot_connect"},
),
],
)
async def test_flow_create_client_errors(
hass: HomeAssistant,
exception: Exception,
errors: dict[str, str],
) -> None:
"""Test config flow errors."""
with patch(
"aiobotocore.session.AioSession.create_client",
side_effect=exception,
):
result = await _async_start_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == errors
# Fix and finish the test
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test"
assert result["data"] == CONFIG_ENTRY_DATA
async def test_flow_head_bucket_error(
hass: HomeAssistant,
mock_client: AsyncMock,
) -> None:
"""Test setup_entry error when calling head_bucket."""
mock_client.head_bucket.side_effect = ClientError(
error_response={"Error": {"Code": "InvalidAccessKeyId"}},
operation_name="head_bucket",
)
result = await _async_start_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "invalid_credentials"}
# Fix and finish the test
mock_client.head_bucket.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test"
assert result["data"] == CONFIG_ENTRY_DATA
async def test_abort_if_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test we abort if the account is already configured."""
mock_config_entry.add_to_hass(hass)
result = await _async_start_flow(hass)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("endpoint_url"),
[
("@@@"),
("http://example.com"),
],
)
async def test_flow_create_not_aws_endpoint(
hass: HomeAssistant, endpoint_url: str
) -> None:
"""Test config flow with a not aws endpoint should raise an error."""
result = await _async_start_flow(
hass, USER_INPUT | {CONF_ENDPOINT_URL: endpoint_url}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {CONF_ENDPOINT_URL: "invalid_endpoint_url"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test"
assert result["data"] == CONFIG_ENTRY_DATA
async def test_abort_if_already_configured_with_same_prefix(
hass: HomeAssistant,
mock_client: AsyncMock,
) -> None:
"""Test we abort if same bucket, endpoint, and prefix are already configured."""
entry = MockConfigEntry(
domain=DOMAIN,
data=CONFIG_ENTRY_DATA | {CONF_PREFIX: "my-prefix"},
)
entry.add_to_hass(hass)
result = await _async_start_flow(hass, USER_INPUT | {CONF_PREFIX: "my-prefix"})
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_abort_if_entry_without_prefix(
hass: HomeAssistant,
mock_client: AsyncMock,
) -> None:
"""Test we abort if an entry without prefix matches bucket and endpoint."""
# Entry without CONF_PREFIX in data (empty prefix is not persisted)
entry = MockConfigEntry(domain=DOMAIN, data=CONFIG_ENTRY_DATA)
entry.add_to_hass(hass)
# Try to configure the same bucket/endpoint with an empty prefix
result = await _async_start_flow(hass, USER_INPUT)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_no_abort_if_different_prefix(
hass: HomeAssistant,
mock_client: AsyncMock,
) -> None:
"""Test we do not abort when same bucket+endpoint but a different prefix is used."""
entry = MockConfigEntry(
domain=DOMAIN,
data=CONFIG_ENTRY_DATA | {CONF_PREFIX: "prefix-a"},
)
entry.add_to_hass(hass)
result = await _async_start_flow(hass, USER_INPUT | {CONF_PREFIX: "prefix-b"})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"][CONF_PREFIX] == "prefix-b"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/aws_s3/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 204,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/aws_s3/test_init.py | """Test the AWS S3 storage integration."""
from unittest.mock import AsyncMock, patch
from botocore.exceptions import (
ClientError,
EndpointConnectionError,
ParamValidationError,
)
import pytest
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
async def test_load_unload_config_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test loading and unloading the integration."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
("exception", "state"),
[
(
ParamValidationError(report="Invalid bucket name"),
ConfigEntryState.SETUP_ERROR,
),
(ValueError(), ConfigEntryState.SETUP_ERROR),
(
EndpointConnectionError(endpoint_url="https://example.com"),
ConfigEntryState.SETUP_RETRY,
),
],
)
async def test_setup_entry_create_client_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
exception: Exception,
state: ConfigEntryState,
) -> None:
"""Test various setup errors."""
with patch(
"aiobotocore.session.AioSession.create_client",
side_effect=exception,
):
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is state
async def test_setup_entry_head_bucket_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_client: AsyncMock,
) -> None:
"""Test setup_entry error when calling head_bucket."""
mock_client.head_bucket.side_effect = ClientError(
error_response={"Error": {"Code": "InvalidAccessKeyId"}},
operation_name="head_bucket",
)
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/aws_s3/test_init.py",
"license": "Apache License 2.0",
"lines": 61,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/eheimdigital/test_switch.py | """Tests for the switch module."""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .conftest import init_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_setup(
hass: HomeAssistant,
eheimdigital_hub_mock: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test switch platform setup for the filter."""
mock_config_entry.add_to_hass(hass)
with (
patch("homeassistant.components.eheimdigital.PLATFORMS", [Platform.SWITCH]),
patch(
"homeassistant.components.eheimdigital.coordinator.asyncio.Event",
new=AsyncMock,
),
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
for device in eheimdigital_hub_mock.return_value.devices:
await eheimdigital_hub_mock.call_args.kwargs["device_found_callback"](
device, eheimdigital_hub_mock.return_value.devices[device].device_type
)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("service", "active"), [(SERVICE_TURN_OFF, False), (SERVICE_TURN_ON, True)]
)
@pytest.mark.parametrize(
("device_name", "entity_id", "property_name"),
[
("classic_vario_mock", "switch.mock_classicvario", "filterActive"),
("filter_mock", "switch.mock_filter", "active"),
],
)
async def test_turn_on_off(
hass: HomeAssistant,
eheimdigital_hub_mock: MagicMock,
mock_config_entry: MockConfigEntry,
device_name: str,
entity_id: str,
property_name: str,
service: str,
active: bool,
request: pytest.FixtureRequest,
) -> None:
"""Test turning on/off the switch."""
device: MagicMock = request.getfixturevalue(device_name)
await init_integration(hass, mock_config_entry)
await eheimdigital_hub_mock.call_args.kwargs["device_found_callback"](
device.mac_address, device.device_type
)
await hass.async_block_till_done()
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
calls = [call for call in device.hub.mock_calls if call[0] == "send_packet"]
assert calls[-1][1][0][property_name] == int(active)
@pytest.mark.usefixtures("classic_vario_mock", "filter_mock")
@pytest.mark.parametrize(
("device_name", "entity_list"),
[
(
"classic_vario_mock",
[
(
"switch.mock_classicvario",
"classic_vario_data",
"filterActive",
1,
"on",
),
(
"switch.mock_classicvario",
"classic_vario_data",
"filterActive",
0,
"off",
),
],
),
(
"filter_mock",
[
(
"switch.mock_filter",
"filter_data",
"filterActive",
1,
"on",
),
(
"switch.mock_filter",
"filter_data",
"filterActive",
0,
"off",
),
],
),
],
)
async def test_state_update(
hass: HomeAssistant,
eheimdigital_hub_mock: MagicMock,
mock_config_entry: MockConfigEntry,
device_name: str,
entity_list: list[tuple[str, str, str, float, float]],
request: pytest.FixtureRequest,
) -> None:
"""Test the switch state update."""
device: MagicMock = request.getfixturevalue(device_name)
await init_integration(hass, mock_config_entry)
await eheimdigital_hub_mock.call_args.kwargs["device_found_callback"](
device.mac_address, device.device_type
)
await hass.async_block_till_done()
for item in entity_list:
getattr(device, item[1])[item[2]] = item[3]
await eheimdigital_hub_mock.call_args.kwargs["receive_callback"]()
assert (state := hass.states.get(item[0]))
assert state.state == str(item[4])
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/eheimdigital/test_switch.py",
"license": "Apache License 2.0",
"lines": 138,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.