sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
home-assistant/core:homeassistant/components/velux/button.py | """Support for VELUX KLF 200 gateway button."""
from __future__ import annotations
from pyvlx import PyVLX, PyVLXException
from homeassistant.components.button import ButtonDeviceClass, ButtonEntity
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import VeluxConfigEntry
from .const import DOMAIN
PARALLEL_UPDATES = 1
async def async_setup_entry(
hass: HomeAssistant,
config_entry: VeluxConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up button entities for the Velux integration."""
async_add_entities(
[VeluxGatewayRebootButton(config_entry.entry_id, config_entry.runtime_data)]
)
class VeluxGatewayRebootButton(ButtonEntity):
"""Representation of the Velux Gateway reboot button."""
_attr_has_entity_name = True
_attr_device_class = ButtonDeviceClass.RESTART
_attr_entity_category = EntityCategory.CONFIG
def __init__(self, config_entry_id: str, pyvlx: PyVLX) -> None:
"""Initialize the gateway reboot button."""
self.pyvlx = pyvlx
self._attr_unique_id = f"{config_entry_id}_reboot-gateway"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, f"gateway_{config_entry_id}")},
)
async def async_press(self) -> None:
"""Handle the button press - reboot the gateway."""
try:
await self.pyvlx.reboot_gateway()
except PyVLXException as ex:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="reboot_failed",
) from ex
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/velux/button.py",
"license": "Apache License 2.0",
"lines": 42,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/vesync/update.py | """Update entity for VeSync.."""
from pyvesync.base_devices.vesyncbasedevice import VeSyncBaseDevice
from pyvesync.device_container import DeviceContainer
from homeassistant.components.update import UpdateDeviceClass, UpdateEntity
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import VS_DEVICES, VS_DISCOVERY
from .coordinator import VesyncConfigEntry, VeSyncDataCoordinator
from .entity import VeSyncBaseEntity
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
config_entry: VesyncConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up update entity."""
coordinator = config_entry.runtime_data
@callback
def discover(devices: list[VeSyncBaseDevice]) -> None:
"""Add new devices to platform."""
_setup_entities(devices, async_add_entities, coordinator)
config_entry.async_on_unload(
async_dispatcher_connect(hass, VS_DISCOVERY.format(VS_DEVICES), discover)
)
_setup_entities(
config_entry.runtime_data.manager.devices, async_add_entities, coordinator
)
@callback
def _setup_entities(
devices: DeviceContainer | list[VeSyncBaseDevice],
async_add_entities: AddConfigEntryEntitiesCallback,
coordinator: VeSyncDataCoordinator,
) -> None:
"""Check if device is a light and add entity."""
async_add_entities(
VeSyncDeviceUpdate(
device=device,
coordinator=coordinator,
)
for device in devices
)
class VeSyncDeviceUpdate(VeSyncBaseEntity, UpdateEntity):
"""Representation of a VeSync device update entity."""
_attr_device_class = UpdateDeviceClass.FIRMWARE
@property
def installed_version(self) -> str | None:
"""Return installed_version."""
return self.device.current_firm_version
@property
def latest_version(self) -> str | None:
"""Return latest_version."""
return self.device.latest_firm_version
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vesync/update.py",
"license": "Apache License 2.0",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/victron_ble/config_flow.py | """Config flow for Victron Bluetooth Low Energy integration."""
from __future__ import annotations
import logging
from typing import Any
from victron_ble_ha_parser import VictronBluetoothDeviceData
import voluptuous as vol
from homeassistant.components.bluetooth import (
BluetoothServiceInfoBleak,
async_discovered_service_info,
)
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_ADDRESS
from .const import DOMAIN, VICTRON_IDENTIFIER
_LOGGER = logging.getLogger(__name__)
STEP_ACCESS_TOKEN_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_ACCESS_TOKEN): str,
}
)
class VictronBLEConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Victron Bluetooth Low Energy."""
VERSION = 1
def __init__(self) -> None:
"""Initialize the config flow."""
self._discovered_device: str | None = None
self._discovered_devices: dict[str, str] = {}
self._discovered_devices_info: dict[str, BluetoothServiceInfoBleak] = {}
async def async_step_bluetooth(
self, discovery_info: BluetoothServiceInfoBleak
) -> ConfigFlowResult:
"""Handle the bluetooth discovery step."""
_LOGGER.debug("async_step_bluetooth: %s", discovery_info.address)
await self.async_set_unique_id(discovery_info.address)
self._abort_if_unique_id_configured()
device = VictronBluetoothDeviceData()
if not device.supported(discovery_info):
_LOGGER.debug("device %s not supported", discovery_info.address)
return self.async_abort(reason="not_supported")
self._discovered_device = discovery_info.address
self._discovered_devices_info[discovery_info.address] = discovery_info
self._discovered_devices[discovery_info.address] = discovery_info.name
self.context["title_placeholders"] = {"title": discovery_info.name}
return await self.async_step_access_token()
async def async_step_access_token(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle advertisement key input."""
# should only be called if there are discovered devices
assert self._discovered_device is not None
discovery_info = self._discovered_devices_info[self._discovered_device]
title = discovery_info.name
if user_input is not None:
# see if we can create a device with the access token
device = VictronBluetoothDeviceData(user_input[CONF_ACCESS_TOKEN])
if device.validate_advertisement_key(
discovery_info.manufacturer_data[VICTRON_IDENTIFIER]
):
return self.async_create_entry(
title=title,
data=user_input,
)
return self.async_abort(reason="invalid_access_token")
return self.async_show_form(
step_id="access_token",
data_schema=STEP_ACCESS_TOKEN_DATA_SCHEMA,
description_placeholders={"title": title},
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle select a device to set up."""
if user_input is not None:
address = user_input[CONF_ADDRESS]
await self.async_set_unique_id(address, raise_on_progress=False)
self._abort_if_unique_id_configured()
self._discovered_device = address
title = self._discovered_devices_info[address].name
return self.async_show_form(
step_id="access_token",
data_schema=STEP_ACCESS_TOKEN_DATA_SCHEMA,
description_placeholders={"title": title},
)
current_addresses = self._async_current_ids()
for discovery_info in async_discovered_service_info(self.hass, False):
address = discovery_info.address
if address in current_addresses or address in self._discovered_devices:
continue
device = VictronBluetoothDeviceData()
if device.supported(discovery_info):
self._discovered_devices_info[address] = discovery_info
self._discovered_devices[address] = discovery_info.name
if len(self._discovered_devices) < 1:
return self.async_abort(reason="no_devices_found")
_LOGGER.debug("Discovered %s devices", len(self._discovered_devices))
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{vol.Required(CONF_ADDRESS): vol.In(self._discovered_devices)}
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/victron_ble/config_flow.py",
"license": "Apache License 2.0",
"lines": 100,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/victron_ble/sensor.py | """Sensor platform for Victron BLE."""
from collections.abc import Callable
from dataclasses import dataclass
import logging
from typing import Any
from sensor_state_data import DeviceKey
from victron_ble_ha_parser import Keys, Units
from homeassistant.components.bluetooth.passive_update_processor import (
PassiveBluetoothDataProcessor,
PassiveBluetoothDataUpdate,
PassiveBluetoothEntityKey,
PassiveBluetoothProcessorEntity,
)
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
PERCENTAGE,
SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
UnitOfElectricCurrent,
UnitOfElectricPotential,
UnitOfEnergy,
UnitOfPower,
UnitOfTemperature,
UnitOfTime,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.sensor import sensor_device_info_to_hass_device_info
LOGGER = logging.getLogger(__name__)
AC_IN_OPTIONS = [
"ac_in_1",
"ac_in_2",
"not_connected",
]
ALARM_OPTIONS = [
"no_alarm",
"low_voltage",
"high_voltage",
"low_soc",
"low_starter_voltage",
"high_starter_voltage",
"low_temperature",
"high_temperature",
"mid_voltage",
"overload",
"dc_ripple",
"low_v_ac_out",
"high_v_ac_out",
"short_circuit",
"bms_lockout",
]
CHARGER_ERROR_OPTIONS = [
"no_error",
"temperature_battery_high",
"voltage_high",
"remote_temperature_auto_reset",
"remote_temperature_not_auto_reset",
"remote_battery",
"high_ripple",
"temperature_battery_low",
"temperature_charger",
"over_current",
"bulk_time",
"current_sensor",
"internal_temperature",
"fan",
"overheated",
"short_circuit",
"converter_issue",
"over_charge",
"input_voltage",
"input_current",
"input_power",
"input_shutdown_voltage",
"input_shutdown_current",
"input_shutdown_failure",
"inverter_shutdown_pv_isolation",
"inverter_shutdown_ground_fault",
"inverter_overload",
"inverter_temperature",
"inverter_peak_current",
"inverter_output_voltage",
"inverter_self_test",
"inverter_ac",
"communication",
"synchronisation",
"bms",
"network",
"pv_input_shutdown",
"cpu_temperature",
"calibration_lost",
"firmware",
"settings",
"tester_fail",
"internal_dc_voltage",
"self_test",
"internal_supply",
]
def error_to_state(value: float | str | None) -> str | None:
"""Convert error code to state string."""
value_map: dict[Any, str] = {
"internal_supply_a": "internal_supply",
"internal_supply_b": "internal_supply",
"internal_supply_c": "internal_supply",
"internal_supply_d": "internal_supply",
"inverter_shutdown_41": "inverter_shutdown_pv_isolation",
"inverter_shutdown_42": "inverter_shutdown_pv_isolation",
"inverter_shutdown_43": "inverter_shutdown_ground_fault",
"internal_temperature_a": "internal_temperature",
"internal_temperature_b": "internal_temperature",
"inverter_output_voltage_a": "inverter_output_voltage",
"inverter_output_voltage_b": "inverter_output_voltage",
"internal_dc_voltage_a": "internal_dc_voltage",
"internal_dc_voltage_b": "internal_dc_voltage",
"remote_temperature_a": "remote_temperature_auto_reset",
"remote_temperature_b": "remote_temperature_auto_reset",
"remote_temperature_c": "remote_temperature_not_auto_reset",
"remote_battery_a": "remote_battery",
"remote_battery_b": "remote_battery",
"remote_battery_c": "remote_battery",
"pv_input_shutdown_80": "pv_input_shutdown",
"pv_input_shutdown_81": "pv_input_shutdown",
"pv_input_shutdown_82": "pv_input_shutdown",
"pv_input_shutdown_83": "pv_input_shutdown",
"pv_input_shutdown_84": "pv_input_shutdown",
"pv_input_shutdown_85": "pv_input_shutdown",
"pv_input_shutdown_86": "pv_input_shutdown",
"pv_input_shutdown_87": "pv_input_shutdown",
"inverter_self_test_a": "inverter_self_test",
"inverter_self_test_b": "inverter_self_test",
"inverter_self_test_c": "inverter_self_test",
"network_a": "network",
"network_b": "network",
"network_c": "network",
"network_d": "network",
}
return value_map.get(value)
DEVICE_STATE_OPTIONS = [
"off",
"low_power",
"fault",
"bulk",
"absorption",
"float",
"storage",
"equalize_manual",
"inverting",
"power_supply",
"starting_up",
"repeated_absorption",
"recondition",
"battery_safe",
"active",
"external_control",
"not_available",
]
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class VictronBLESensorEntityDescription(SensorEntityDescription):
"""Describes Victron BLE sensor entity."""
value_fn: Callable[[float | int | str | None], float | int | str | None] = (
lambda x: x
)
SENSOR_DESCRIPTIONS = {
Keys.AC_IN_POWER: VictronBLESensorEntityDescription(
key=Keys.AC_IN_POWER,
translation_key=Keys.AC_IN_POWER,
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.WATT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.AC_IN_STATE: VictronBLESensorEntityDescription(
key=Keys.AC_IN_STATE,
device_class=SensorDeviceClass.ENUM,
translation_key="ac_in_state",
options=AC_IN_OPTIONS,
),
Keys.AC_OUT_POWER: VictronBLESensorEntityDescription(
key=Keys.AC_OUT_POWER,
translation_key=Keys.AC_OUT_POWER,
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.WATT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.AC_OUT_STATE: VictronBLESensorEntityDescription(
key=Keys.AC_OUT_STATE,
device_class=SensorDeviceClass.ENUM,
translation_key="device_state",
options=DEVICE_STATE_OPTIONS,
),
Keys.ALARM: VictronBLESensorEntityDescription(
key=Keys.ALARM,
device_class=SensorDeviceClass.ENUM,
translation_key="alarm",
options=ALARM_OPTIONS,
),
Keys.BALANCER_STATUS: VictronBLESensorEntityDescription(
key=Keys.BALANCER_STATUS,
device_class=SensorDeviceClass.ENUM,
translation_key="balancer_status",
options=["balanced", "balancing", "imbalance"],
),
Keys.BATTERY_CURRENT: VictronBLESensorEntityDescription(
key=Keys.BATTERY_CURRENT,
translation_key=Keys.BATTERY_CURRENT,
device_class=SensorDeviceClass.CURRENT,
native_unit_of_measurement=UnitOfElectricCurrent.AMPERE,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.BATTERY_TEMPERATURE: VictronBLESensorEntityDescription(
key=Keys.BATTERY_TEMPERATURE,
translation_key=Keys.BATTERY_TEMPERATURE,
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.BATTERY_VOLTAGE: VictronBLESensorEntityDescription(
key=Keys.BATTERY_VOLTAGE,
translation_key=Keys.BATTERY_VOLTAGE,
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.CHARGE_STATE: VictronBLESensorEntityDescription(
key=Keys.CHARGE_STATE,
device_class=SensorDeviceClass.ENUM,
translation_key="charge_state",
options=DEVICE_STATE_OPTIONS,
),
Keys.CHARGER_ERROR: VictronBLESensorEntityDescription(
key=Keys.CHARGER_ERROR,
device_class=SensorDeviceClass.ENUM,
translation_key="charger_error",
options=CHARGER_ERROR_OPTIONS,
value_fn=error_to_state,
),
Keys.CONSUMED_AMPERE_HOURS: VictronBLESensorEntityDescription(
key=Keys.CONSUMED_AMPERE_HOURS,
translation_key=Keys.CONSUMED_AMPERE_HOURS,
native_unit_of_measurement=Units.ELECTRIC_CURRENT_FLOW_AMPERE_HOUR,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.CURRENT: VictronBLESensorEntityDescription(
key=Keys.CURRENT,
device_class=SensorDeviceClass.CURRENT,
native_unit_of_measurement=UnitOfElectricCurrent.AMPERE,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.DEVICE_STATE: VictronBLESensorEntityDescription(
key=Keys.DEVICE_STATE,
device_class=SensorDeviceClass.ENUM,
translation_key="device_state",
options=DEVICE_STATE_OPTIONS,
),
Keys.ERROR_CODE: VictronBLESensorEntityDescription(
key=Keys.ERROR_CODE,
device_class=SensorDeviceClass.ENUM,
translation_key="charger_error",
options=CHARGER_ERROR_OPTIONS,
),
Keys.EXTERNAL_DEVICE_LOAD: VictronBLESensorEntityDescription(
key=Keys.EXTERNAL_DEVICE_LOAD,
translation_key=Keys.EXTERNAL_DEVICE_LOAD,
device_class=SensorDeviceClass.CURRENT,
native_unit_of_measurement=UnitOfElectricCurrent.AMPERE,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.INPUT_VOLTAGE: VictronBLESensorEntityDescription(
key=Keys.INPUT_VOLTAGE,
translation_key=Keys.INPUT_VOLTAGE,
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.METER_TYPE: VictronBLESensorEntityDescription(
key=Keys.METER_TYPE,
device_class=SensorDeviceClass.ENUM,
translation_key="meter_type",
options=[
"solar_charger",
"wind_charger",
"shaft_generator",
"alternator",
"fuel_cell",
"water_generator",
"dc_dc_charger",
"ac_charger",
"generic_source",
"generic_load",
"electric_drive",
"fridge",
"water_pump",
"bilge_pump",
"dc_system",
"inverter",
"water_heater",
],
),
Keys.MIDPOINT_VOLTAGE: VictronBLESensorEntityDescription(
key=Keys.MIDPOINT_VOLTAGE,
translation_key=Keys.MIDPOINT_VOLTAGE,
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.OFF_REASON: VictronBLESensorEntityDescription(
key=Keys.OFF_REASON,
device_class=SensorDeviceClass.ENUM,
translation_key="off_reason",
options=[
"no_reason",
"no_input_power",
"switched_off_switch",
"switched_off_register",
"remote_input",
"protection_active",
"load_output_disabled",
"pay_as_you_go_out_of_credit",
"bms",
"engine_shutdown",
"analysing_input_voltage",
],
),
Keys.OUTPUT_VOLTAGE: VictronBLESensorEntityDescription(
key=Keys.OUTPUT_VOLTAGE,
translation_key=Keys.OUTPUT_VOLTAGE,
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.REMAINING_MINUTES: VictronBLESensorEntityDescription(
key=Keys.REMAINING_MINUTES,
translation_key=Keys.REMAINING_MINUTES,
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.MINUTES,
state_class=SensorStateClass.MEASUREMENT,
),
SensorDeviceClass.SIGNAL_STRENGTH: VictronBLESensorEntityDescription(
key=SensorDeviceClass.SIGNAL_STRENGTH.value,
device_class=SensorDeviceClass.SIGNAL_STRENGTH,
native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.SOLAR_POWER: VictronBLESensorEntityDescription(
key=Keys.SOLAR_POWER,
translation_key=Keys.SOLAR_POWER,
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.WATT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.STARTER_VOLTAGE: VictronBLESensorEntityDescription(
key=Keys.STARTER_VOLTAGE,
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.STATE_OF_CHARGE: VictronBLESensorEntityDescription(
key=Keys.STATE_OF_CHARGE,
device_class=SensorDeviceClass.BATTERY,
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.TEMPERATURE: VictronBLESensorEntityDescription(
key=Keys.TEMPERATURE,
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.VOLTAGE: VictronBLESensorEntityDescription(
key=Keys.VOLTAGE,
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
),
Keys.WARNING: VictronBLESensorEntityDescription(
key=Keys.WARNING,
device_class=SensorDeviceClass.ENUM,
translation_key="alarm",
options=ALARM_OPTIONS,
),
Keys.YIELD_TODAY: VictronBLESensorEntityDescription(
key=Keys.YIELD_TODAY,
translation_key=Keys.YIELD_TODAY,
device_class=SensorDeviceClass.ENERGY,
native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
state_class=SensorStateClass.TOTAL_INCREASING,
),
}
for i in range(1, 8):
cell_key = getattr(Keys, f"CELL_{i}_VOLTAGE")
SENSOR_DESCRIPTIONS[cell_key] = VictronBLESensorEntityDescription(
key=cell_key,
translation_key="cell_voltage",
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
)
def _device_key_to_bluetooth_entity_key(
device_key: DeviceKey,
) -> PassiveBluetoothEntityKey:
"""Convert a device key to an entity key."""
return PassiveBluetoothEntityKey(device_key.key, device_key.device_id)
def sensor_update_to_bluetooth_data_update(
sensor_update,
) -> PassiveBluetoothDataUpdate:
"""Convert a sensor update to a bluetooth data update."""
return PassiveBluetoothDataUpdate(
devices={
device_id: sensor_device_info_to_hass_device_info(device_info)
for device_id, device_info in sensor_update.devices.items()
},
entity_descriptions={
_device_key_to_bluetooth_entity_key(device_key): SENSOR_DESCRIPTIONS[
device_key.key
]
for device_key in sensor_update.entity_descriptions
if device_key.key in SENSOR_DESCRIPTIONS
},
entity_data={
_device_key_to_bluetooth_entity_key(device_key): sensor_values.native_value
for device_key, sensor_values in sensor_update.entity_values.items()
if device_key.key in SENSOR_DESCRIPTIONS
},
entity_names={},
)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Victron BLE sensor."""
coordinator = entry.runtime_data
processor = PassiveBluetoothDataProcessor(sensor_update_to_bluetooth_data_update)
entry.async_on_unload(
processor.async_add_entities_listener(
VictronBLESensorEntity, async_add_entities
)
)
entry.async_on_unload(coordinator.async_register_processor(processor))
class VictronBLESensorEntity(PassiveBluetoothProcessorEntity, SensorEntity):
"""Representation of Victron BLE sensor."""
entity_description: VictronBLESensorEntityDescription
@property
def native_value(self) -> float | int | str | None:
"""Return the state of the sensor."""
value = self.processor.entity_data.get(self.entity_key)
return self.entity_description.value_fn(value)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/victron_ble/sensor.py",
"license": "Apache License 2.0",
"lines": 453,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/volvo/lock.py | """Volvo locks."""
from dataclasses import dataclass
import logging
from typing import Any, cast
from volvocarsapi.models import VolvoApiException, VolvoCarsApiBaseModel, VolvoCarsValue
from homeassistant.components.lock import LockEntity, LockEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN
from .coordinator import VolvoConfigEntry
from .entity import VolvoEntity, VolvoEntityDescription
PARALLEL_UPDATES = 0
_LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True, kw_only=True)
class VolvoLockDescription(VolvoEntityDescription, LockEntityDescription):
"""Describes a Volvo lock entity."""
api_lock_value: str = "LOCKED"
api_unlock_value: str = "UNLOCKED"
lock_command: str
unlock_command: str
required_command_key: str
_DESCRIPTIONS: tuple[VolvoLockDescription, ...] = (
VolvoLockDescription(
key="lock",
api_field="centralLock",
lock_command="lock",
unlock_command="unlock",
required_command_key="LOCK",
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: VolvoConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up locks."""
coordinators = entry.runtime_data.interval_coordinators
async_add_entities(
[
VolvoLock(coordinator, description)
for coordinator in coordinators
for description in _DESCRIPTIONS
if description.required_command_key
in entry.runtime_data.context.supported_commands
and description.api_field in coordinator.data
]
)
class VolvoLock(VolvoEntity, LockEntity):
"""Volvo lock."""
entity_description: VolvoLockDescription
async def async_lock(self, **kwargs: Any) -> None:
"""Lock the car."""
await self._async_handle_command(self.entity_description.lock_command, True)
async def async_unlock(self, **kwargs: Any) -> None:
"""Unlock the car."""
await self._async_handle_command(self.entity_description.unlock_command, False)
def _update_state(self, api_field: VolvoCarsApiBaseModel | None) -> None:
"""Update the state of the entity."""
assert isinstance(api_field, VolvoCarsValue)
self._attr_is_locked = api_field.value == "LOCKED"
async def _async_handle_command(self, command: str, locked: bool) -> None:
_LOGGER.debug("Lock '%s' is %s", command, "locked" if locked else "unlocked")
if locked:
self._attr_is_locking = True
else:
self._attr_is_unlocking = True
self.async_write_ha_state()
try:
result = await self.coordinator.context.api.async_execute_command(command)
except VolvoApiException as ex:
_LOGGER.debug("Lock '%s' error", command)
error = self._reset_and_create_error(command, message=ex.message)
raise error from ex
status = result.invoke_status if result else ""
_LOGGER.debug("Lock '%s' result: %s", command, status)
if status.upper() not in ("COMPLETED", "DELIVERED"):
error = self._reset_and_create_error(
command, status=status, message=result.message if result else ""
)
raise error
api_field = cast(
VolvoCarsValue,
self.coordinator.get_api_field(self.entity_description.api_field),
)
self._attr_is_locking = False
self._attr_is_unlocking = False
if locked:
api_field.value = self.entity_description.api_lock_value
else:
api_field.value = self.entity_description.api_unlock_value
self._attr_is_locked = locked
self.async_write_ha_state()
def _reset_and_create_error(
self, command: str, *, status: str = "", message: str = ""
) -> HomeAssistantError:
self._attr_is_locking = False
self._attr_is_unlocking = False
self.async_write_ha_state()
return HomeAssistantError(
translation_domain=DOMAIN,
translation_key="command_failure",
translation_placeholders={
"command": command,
"status": status,
"message": message,
},
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/volvo/lock.py",
"license": "Apache License 2.0",
"lines": 108,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/waqi/diagnostics.py | """Diagnostics support for WAQI."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from homeassistant.core import HomeAssistant
from .coordinator import WAQIConfigEntry
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: WAQIConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return {
subentry_id: asdict(coordinator.data)
for subentry_id, coordinator in entry.runtime_data.items()
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/waqi/diagnostics.py",
"license": "Apache License 2.0",
"lines": 14,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/websocket_api/automation.py | """Automation related helper methods for the Websocket API."""
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from enum import StrEnum
import logging
from typing import Any, Self
from homeassistant.const import CONF_TARGET
from homeassistant.core import HomeAssistant
from homeassistant.helpers import target as target_helpers
from homeassistant.helpers.condition import (
async_get_all_descriptions as async_get_all_condition_descriptions,
)
from homeassistant.helpers.entity import (
entity_sources,
get_device_class,
get_supported_features,
)
from homeassistant.helpers.service import (
async_get_all_descriptions as async_get_all_service_descriptions,
)
from homeassistant.helpers.trigger import (
async_get_all_descriptions as async_get_all_trigger_descriptions,
)
from homeassistant.helpers.typing import ConfigType
from homeassistant.util.hass_dict import HassKey
_LOGGER = logging.getLogger(__name__)
FLATTENED_SERVICE_DESCRIPTIONS_CACHE: HassKey[
tuple[dict[str, dict[str, Any]], dict[str, dict[str, Any]]]
] = HassKey("websocket_automation_flat_service_description_cache")
AUTOMATION_COMPONENT_LOOKUP_CACHE: HassKey[
dict[
AutomationComponentType,
tuple[Mapping[str, Any], _AutomationComponentLookupTable],
]
] = HassKey("websocket_automation_component_lookup_cache")
class AutomationComponentType(StrEnum):
"""Types of automation components."""
TRIGGERS = "triggers"
CONDITIONS = "conditions"
SERVICES = "services"
@dataclass(slots=True, kw_only=True)
class _EntityFilter:
"""Single entity filter configuration."""
integration: str | None
domains: set[str]
device_classes: set[str]
supported_features: set[int]
def matches(
self, hass: HomeAssistant, entity_id: str, domain: str, integration: str
) -> bool:
"""Return if entity matches all criteria in this filter."""
if self.integration and integration != self.integration:
return False
if self.domains and domain not in self.domains:
return False
if self.device_classes:
if (
entity_device_class := get_device_class(hass, entity_id)
) is None or entity_device_class not in self.device_classes:
return False
if self.supported_features:
entity_supported_features = get_supported_features(hass, entity_id)
if not any(
feature & entity_supported_features == feature
for feature in self.supported_features
):
return False
return True
@dataclass(slots=True, kw_only=True)
class _AutomationComponentLookupData:
"""Helper class for looking up automation components."""
component: str
filters: list[_EntityFilter]
@classmethod
def create(cls, component: str, target_description: dict[str, Any]) -> Self:
"""Build automation component lookup data from target description."""
filters: list[_EntityFilter] = []
entity_filters_config = target_description.get("entity", [])
for entity_filter_config in entity_filters_config:
entity_filter = _EntityFilter(
integration=entity_filter_config.get("integration"),
domains=set(entity_filter_config.get("domain", [])),
device_classes=set(entity_filter_config.get("device_class", [])),
supported_features=set(
entity_filter_config.get("supported_features", [])
),
)
filters.append(entity_filter)
return cls(component=component, filters=filters)
def matches(
self, hass: HomeAssistant, entity_id: str, domain: str, integration: str
) -> bool:
"""Return if entity matches ANY of the filters."""
if not self.filters:
return True
return any(
f.matches(hass, entity_id, domain, integration) for f in self.filters
)
@dataclass(slots=True, kw_only=True)
class _AutomationComponentLookupTable:
"""Helper class for looking up automation components."""
domain_components: dict[str | None, list[_AutomationComponentLookupData]]
component_count: int
def _get_automation_component_domains(
target_description: dict[str, Any],
) -> set[str | None]:
"""Get a list of domains (including integration domains) of an automation component.
The list of domains is extracted from each target's entity filters.
If a filter is missing both domain and integration keys, None is added to the
returned set.
"""
entity_filters_config = target_description.get("entity", [])
if not entity_filters_config:
return {None}
domains: set[str | None] = set()
for entity_filter_config in entity_filters_config:
filter_integration = entity_filter_config.get("integration")
filter_domains = entity_filter_config.get("domain", [])
if not filter_domains and not filter_integration:
domains.add(None)
continue
if filter_integration:
domains.add(filter_integration)
for domain in filter_domains:
domains.add(domain)
return domains
def _get_automation_component_lookup_table(
hass: HomeAssistant,
component_type: AutomationComponentType,
component_descriptions: Mapping[str, Mapping[str, Any] | None],
) -> _AutomationComponentLookupTable:
"""Get a dict of automation components keyed by domain, along with the total number of components.
Returns a cached object if available.
"""
try:
cache = hass.data[AUTOMATION_COMPONENT_LOOKUP_CACHE]
except KeyError:
cache = hass.data[AUTOMATION_COMPONENT_LOOKUP_CACHE] = {}
if (cached := cache.get(component_type)) is not None:
cached_descriptions, cached_lookup = cached
if cached_descriptions is component_descriptions:
return cached_lookup
_LOGGER.debug(
"Automation component lookup data for %s has no cache yet", component_type
)
lookup_table = _AutomationComponentLookupTable(
domain_components={}, component_count=0
)
for component, description in component_descriptions.items():
if description is None or CONF_TARGET not in description:
_LOGGER.debug("Skipping component %s without target description", component)
continue
domains = _get_automation_component_domains(description[CONF_TARGET])
lookup_data = _AutomationComponentLookupData.create(
component, description[CONF_TARGET]
)
for domain in domains:
lookup_table.domain_components.setdefault(domain, []).append(lookup_data)
lookup_table.component_count += 1
cache[component_type] = (component_descriptions, lookup_table)
return lookup_table
def _async_get_automation_components_for_target(
hass: HomeAssistant,
component_type: AutomationComponentType,
target_selection: ConfigType,
expand_group: bool,
component_descriptions: Mapping[str, Mapping[str, Any] | None],
) -> set[str]:
"""Get automation components (triggers/conditions/services) for a target.
Returns all components that can be used on any entity that are currently part of a target.
"""
extracted = target_helpers.async_extract_referenced_entity_ids(
hass,
target_helpers.TargetSelection(target_selection),
expand_group=expand_group,
)
_LOGGER.debug("Extracted entities for lookup: %s", extracted)
lookup_table = _get_automation_component_lookup_table(
hass, component_type, component_descriptions
)
_LOGGER.debug(
"Automation components per domain: %s", lookup_table.domain_components
)
entity_infos = entity_sources(hass)
matched_components: set[str] = set()
for entity_id in extracted.referenced | extracted.indirectly_referenced:
if lookup_table.component_count == len(matched_components):
# All automation components matched already, so we don't need to iterate further
break
entity_info = entity_infos.get(entity_id)
if entity_info is None:
_LOGGER.debug("No entity source found for %s", entity_id)
continue
entity_domain = entity_id.split(".")[0]
entity_integration = entity_info["domain"]
for domain in (entity_domain, entity_integration, None):
if not (
domain_component_data := lookup_table.domain_components.get(domain)
):
continue
for component_data in domain_component_data:
if component_data.component in matched_components:
continue
if component_data.matches(
hass, entity_id, entity_domain, entity_integration
):
matched_components.add(component_data.component)
return matched_components
async def async_get_triggers_for_target(
hass: HomeAssistant, target_selector: ConfigType, expand_group: bool
) -> set[str]:
"""Get triggers for a target."""
descriptions = await async_get_all_trigger_descriptions(hass)
return _async_get_automation_components_for_target(
hass,
AutomationComponentType.TRIGGERS,
target_selector,
expand_group,
descriptions,
)
async def async_get_conditions_for_target(
hass: HomeAssistant, target_selector: ConfigType, expand_group: bool
) -> set[str]:
"""Get conditions for a target."""
descriptions = await async_get_all_condition_descriptions(hass)
return _async_get_automation_components_for_target(
hass,
AutomationComponentType.CONDITIONS,
target_selector,
expand_group,
descriptions,
)
async def async_get_services_for_target(
hass: HomeAssistant, target_selector: ConfigType, expand_group: bool
) -> set[str]:
"""Get services for a target."""
descriptions = await async_get_all_service_descriptions(hass)
def get_flattened_service_descriptions() -> dict[str, dict[str, Any]]:
"""Get flattened service descriptions, with caching."""
if FLATTENED_SERVICE_DESCRIPTIONS_CACHE in hass.data:
cached_descriptions, cached_flattened_descriptions = hass.data[
FLATTENED_SERVICE_DESCRIPTIONS_CACHE
]
# If the descriptions are the same, return the cached flattened version
if cached_descriptions is descriptions:
return cached_flattened_descriptions
# Flatten dicts to be keyed by domain.name to match trigger/condition format
flattened_descriptions = {
f"{domain}.{service_name}": desc
for domain, services in descriptions.items()
for service_name, desc in services.items()
}
hass.data[FLATTENED_SERVICE_DESCRIPTIONS_CACHE] = (
descriptions,
flattened_descriptions,
)
return flattened_descriptions
return _async_get_automation_components_for_target(
hass,
AutomationComponentType.SERVICES,
target_selector,
expand_group,
get_flattened_service_descriptions(),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/websocket_api/automation.py",
"license": "Apache License 2.0",
"lines": 265,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/xbox/diagnostics.py | """Diagnostics platform for the Xbox integration."""
from __future__ import annotations
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.core import HomeAssistant
from .coordinator import XboxConfigEntry
TO_REDACT = {
"bio",
"display_name",
"display_pic_raw",
"gamertag",
"linked_accounts",
"location",
"modern_gamertag_suffix",
"modern_gamertag",
"real_name",
"unique_modern_gamertag",
"xuid",
}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: XboxConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
presence = [
async_redact_data(person.model_dump(), TO_REDACT)
for person in config_entry.runtime_data.presence.data.presence.values()
]
consoles_status = [
{
"status": console.status.model_dump(),
"app_details": (
console.app_details.model_dump() if console.app_details else None
),
}
for console in config_entry.runtime_data.status.data.values()
]
consoles_list = [
console.model_dump()
for console in config_entry.runtime_data.consoles.data.values()
]
title_info = [
title.model_dump()
for title in config_entry.runtime_data.presence.data.title_info.values()
]
return {
"consoles_status": consoles_status,
"consoles_list": consoles_list,
"presence": presence,
"title_info": title_info,
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/xbox/diagnostics.py",
"license": "Apache License 2.0",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/helpers/template/extensions/areas.py | """Area functions for Home Assistant templates."""
from __future__ import annotations
from collections.abc import Iterable
from typing import TYPE_CHECKING
import voluptuous as vol
from homeassistant.helpers import (
area_registry as ar,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.template.helpers import resolve_area_id
from .base import BaseTemplateExtension, TemplateFunction
if TYPE_CHECKING:
from homeassistant.helpers.template import TemplateEnvironment
class AreaExtension(BaseTemplateExtension):
"""Extension for area-related template functions."""
def __init__(self, environment: TemplateEnvironment) -> None:
"""Initialize the area extension."""
super().__init__(
environment,
functions=[
TemplateFunction(
"areas",
self.areas,
as_global=True,
requires_hass=True,
),
TemplateFunction(
"area_id",
self.area_id,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"area_name",
self.area_name,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"area_entities",
self.area_entities,
as_global=True,
as_filter=True,
requires_hass=True,
),
TemplateFunction(
"area_devices",
self.area_devices,
as_global=True,
as_filter=True,
requires_hass=True,
),
],
)
def areas(self) -> Iterable[str | None]:
"""Return all areas."""
return list(ar.async_get(self.hass).areas)
def area_id(self, lookup_value: str) -> str | None:
"""Get the area ID from an area name, alias, device id, or entity id."""
return resolve_area_id(self.hass, lookup_value)
def _get_area_name(self, area_reg: ar.AreaRegistry, valid_area_id: str) -> str:
"""Get area name from valid area ID."""
area = area_reg.async_get_area(valid_area_id)
assert area
return area.name
def area_name(self, lookup_value: str) -> str | None:
"""Get the area name from an area id, device id, or entity id."""
area_reg = ar.async_get(self.hass)
if area := area_reg.async_get_area(lookup_value):
return area.name
dev_reg = dr.async_get(self.hass)
ent_reg = er.async_get(self.hass)
# Import here, not at top-level to avoid circular import
from homeassistant.helpers import config_validation as cv # noqa: PLC0415
try:
cv.entity_id(lookup_value)
except vol.Invalid:
pass
else:
if entity := ent_reg.async_get(lookup_value):
# If entity has an area ID, get the area name for that
if entity.area_id:
return self._get_area_name(area_reg, entity.area_id)
# If entity has a device ID and the device exists with an area ID, get the
# area name for that
if (
entity.device_id
and (device := dev_reg.async_get(entity.device_id))
and device.area_id
):
return self._get_area_name(area_reg, device.area_id)
if (device := dev_reg.async_get(lookup_value)) and device.area_id:
return self._get_area_name(area_reg, device.area_id)
return None
def area_entities(self, area_id_or_name: str) -> Iterable[str]:
"""Return entities for a given area ID or name."""
_area_id: str | None
# if area_name returns a value, we know the input was an ID, otherwise we
# assume it's a name, and if it's neither, we return early
if self.area_name(area_id_or_name) is None:
_area_id = self.area_id(area_id_or_name)
else:
_area_id = area_id_or_name
if _area_id is None:
return []
ent_reg = er.async_get(self.hass)
entity_ids = [
entry.entity_id for entry in er.async_entries_for_area(ent_reg, _area_id)
]
dev_reg = dr.async_get(self.hass)
# We also need to add entities tied to a device in the area that don't themselves
# have an area specified since they inherit the area from the device.
entity_ids.extend(
[
entity.entity_id
for device in dr.async_entries_for_area(dev_reg, _area_id)
for entity in er.async_entries_for_device(ent_reg, device.id)
if entity.area_id is None
]
)
return entity_ids
def area_devices(self, area_id_or_name: str) -> Iterable[str]:
"""Return device IDs for a given area ID or name."""
_area_id: str | None
# if area_name returns a value, we know the input was an ID, otherwise we
# assume it's a name, and if it's neither, we return early
if self.area_name(area_id_or_name) is not None:
_area_id = area_id_or_name
else:
_area_id = self.area_id(area_id_or_name)
if _area_id is None:
return []
dev_reg = dr.async_get(self.hass)
entries = dr.async_entries_for_area(dev_reg, _area_id)
return [entry.id for entry in entries]
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/helpers/template/extensions/areas.py",
"license": "Apache License 2.0",
"lines": 140,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/helpers/template/extensions/datetime.py | """DateTime functions for Home Assistant templates."""
from __future__ import annotations
from datetime import date, datetime, time, timedelta
from typing import TYPE_CHECKING, Any
from homeassistant.helpers.template.helpers import raise_no_default
from homeassistant.helpers.template.render_info import render_info_cv
from homeassistant.util import dt as dt_util
from .base import BaseTemplateExtension, TemplateFunction
if TYPE_CHECKING:
from homeassistant.helpers.template import TemplateEnvironment
_SENTINEL = object()
DATE_STR_FORMAT = "%Y-%m-%d %H:%M:%S"
class DateTimeExtension(BaseTemplateExtension):
"""Extension for datetime-related template functions."""
def __init__(self, environment: TemplateEnvironment) -> None:
"""Initialize the datetime extension."""
super().__init__(
environment,
functions=[
TemplateFunction(
"as_datetime",
self.as_datetime,
as_global=True,
as_filter=True,
),
TemplateFunction(
"as_local",
self.as_local,
as_global=True,
as_filter=True,
),
TemplateFunction(
"as_timedelta",
self.as_timedelta,
as_global=True,
as_filter=True,
),
TemplateFunction(
"as_timestamp",
self.as_timestamp,
as_global=True,
as_filter=True,
),
TemplateFunction(
"strptime",
self.strptime,
as_global=True,
),
TemplateFunction(
"timedelta",
timedelta,
as_global=True,
),
TemplateFunction(
"timestamp_custom",
self.timestamp_custom,
as_filter=True,
),
TemplateFunction(
"timestamp_local",
self.timestamp_local,
as_filter=True,
),
TemplateFunction(
"timestamp_utc",
self.timestamp_utc,
as_filter=True,
),
TemplateFunction(
"datetime",
self.is_datetime,
as_test=True,
),
# Functions that require hass
TemplateFunction(
"now",
self.now,
as_global=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"utcnow",
self.utcnow,
as_global=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"relative_time",
self.relative_time,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"time_since",
self.time_since,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"time_until",
self.time_until,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"today_at",
self.today_at,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
],
)
def timestamp_custom(
self,
value: Any,
date_format: str = DATE_STR_FORMAT,
local: bool = True,
default: Any = _SENTINEL,
) -> Any:
"""Filter to convert given timestamp to format."""
try:
result = dt_util.utc_from_timestamp(value)
if local:
result = dt_util.as_local(result)
return result.strftime(date_format)
except ValueError, TypeError:
# If timestamp can't be converted
if default is _SENTINEL:
raise_no_default("timestamp_custom", value)
return default
def timestamp_local(self, value: Any, default: Any = _SENTINEL) -> Any:
"""Filter to convert given timestamp to local date/time."""
try:
return dt_util.as_local(dt_util.utc_from_timestamp(value)).isoformat()
except ValueError, TypeError:
# If timestamp can't be converted
if default is _SENTINEL:
raise_no_default("timestamp_local", value)
return default
def timestamp_utc(self, value: Any, default: Any = _SENTINEL) -> Any:
"""Filter to convert given timestamp to UTC date/time."""
try:
return dt_util.utc_from_timestamp(value).isoformat()
except ValueError, TypeError:
# If timestamp can't be converted
if default is _SENTINEL:
raise_no_default("timestamp_utc", value)
return default
def as_timestamp(self, value: Any, default: Any = _SENTINEL) -> Any:
"""Filter and function which tries to convert value to timestamp."""
try:
return dt_util.as_timestamp(value)
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("as_timestamp", value)
return default
def as_datetime(self, value: Any, default: Any = _SENTINEL) -> Any:
"""Filter to convert a time string or UNIX timestamp to datetime object."""
# Return datetime.datetime object without changes
if type(value) is datetime:
return value
# Add midnight to datetime.date object
if type(value) is date:
return datetime.combine(value, time(0, 0, 0))
try:
# Check for a valid UNIX timestamp string, int or float
timestamp = float(value)
return dt_util.utc_from_timestamp(timestamp)
except ValueError, TypeError:
# Try to parse datetime string to datetime object
try:
return dt_util.parse_datetime(value, raise_on_error=True)
except ValueError, TypeError:
if default is _SENTINEL:
# Return None on string input
# to ensure backwards compatibility with HA Core 2024.1 and before.
if isinstance(value, str):
return None
raise_no_default("as_datetime", value)
return default
def as_timedelta(self, value: str) -> timedelta | None:
"""Parse a ISO8601 duration like 'PT10M' to a timedelta."""
return dt_util.parse_duration(value)
def strptime(self, string: str, fmt: str, default: Any = _SENTINEL) -> Any:
"""Parse a time string to datetime."""
try:
return datetime.strptime(string, fmt)
except ValueError, AttributeError, TypeError:
if default is _SENTINEL:
raise_no_default("strptime", string)
return default
def as_local(self, value: datetime) -> datetime:
"""Filter and function to convert time to local."""
return dt_util.as_local(value)
def is_datetime(self, value: Any) -> bool:
"""Return whether a value is a datetime."""
return isinstance(value, datetime)
def now(self) -> datetime:
"""Record fetching now."""
if (render_info := render_info_cv.get()) is not None:
render_info.has_time = True
return dt_util.now()
def utcnow(self) -> datetime:
"""Record fetching utcnow."""
if (render_info := render_info_cv.get()) is not None:
render_info.has_time = True
return dt_util.utcnow()
def today_at(self, time_str: str = "") -> datetime:
"""Record fetching now where the time has been replaced with value."""
if (render_info := render_info_cv.get()) is not None:
render_info.has_time = True
today = dt_util.start_of_local_day()
if not time_str:
return today
if (time_today := dt_util.parse_time(time_str)) is None:
raise ValueError(
f"could not convert {type(time_str).__name__} to datetime: '{time_str}'"
)
return datetime.combine(today, time_today, today.tzinfo)
def relative_time(self, value: Any) -> Any:
"""Take a datetime and return its "age" as a string.
The age can be in second, minute, hour, day, month or year. Only the
biggest unit is considered, e.g. if it's 2 days and 3 hours, "2 days" will
be returned.
If the input datetime is in the future,
the input datetime will be returned.
If the input are not a datetime object the input will be returned unmodified.
Note: This template function is deprecated in favor of `time_until`, but is still
supported so as not to break old templates.
"""
if (render_info := render_info_cv.get()) is not None:
render_info.has_time = True
if not isinstance(value, datetime):
return value
if not value.tzinfo:
value = dt_util.as_local(value)
if dt_util.now() < value:
return value
return dt_util.get_age(value)
def time_since(self, value: Any | datetime, precision: int = 1) -> Any:
"""Take a datetime and return its "age" as a string.
The age can be in seconds, minutes, hours, days, months and year.
precision is the number of units to return, with the last unit rounded.
If the value not a datetime object the input will be returned unmodified.
"""
if (render_info := render_info_cv.get()) is not None:
render_info.has_time = True
if not isinstance(value, datetime):
return value
if not value.tzinfo:
value = dt_util.as_local(value)
if dt_util.now() < value:
return value
return dt_util.get_age(value, precision)
def time_until(self, value: Any | datetime, precision: int = 1) -> Any:
"""Take a datetime and return the amount of time until that time as a string.
The time until can be in seconds, minutes, hours, days, months and years.
precision is the number of units to return, with the last unit rounded.
If the value not a datetime object the input will be returned unmodified.
"""
if (render_info := render_info_cv.get()) is not None:
render_info.has_time = True
if not isinstance(value, datetime):
return value
if not value.tzinfo:
value = dt_util.as_local(value)
if dt_util.now() > value:
return value
return dt_util.get_time_remaining(value, precision)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/helpers/template/extensions/datetime.py",
"license": "Apache License 2.0",
"lines": 279,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/helpers/template/extensions/devices.py | """Device functions for Home Assistant templates."""
from __future__ import annotations
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
import voluptuous as vol
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from .base import BaseTemplateExtension, TemplateFunction
if TYPE_CHECKING:
from homeassistant.helpers.template import TemplateEnvironment
class DeviceExtension(BaseTemplateExtension):
"""Extension for device-related template functions."""
def __init__(self, environment: TemplateEnvironment) -> None:
"""Initialize the device extension."""
super().__init__(
environment,
functions=[
TemplateFunction(
"device_entities",
self.device_entities,
as_global=True,
as_filter=True,
requires_hass=True,
),
TemplateFunction(
"device_id",
self.device_id,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"device_name",
self.device_name,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"device_attr",
self.device_attr,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"is_device_attr",
self.is_device_attr,
as_global=True,
as_test=True,
requires_hass=True,
limited_ok=False,
),
],
)
def device_entities(self, _device_id: str) -> Iterable[str]:
"""Get entity ids for entities tied to a device."""
entity_reg = er.async_get(self.hass)
entries = er.async_entries_for_device(entity_reg, _device_id)
return [entry.entity_id for entry in entries]
def device_id(self, entity_id_or_device_name: str) -> str | None:
"""Get a device ID from an entity ID or device name."""
entity_reg = er.async_get(self.hass)
entity = entity_reg.async_get(entity_id_or_device_name)
if entity is not None:
return entity.device_id
dev_reg = dr.async_get(self.hass)
return next(
(
device_id
for device_id, device in dev_reg.devices.items()
if (name := device.name_by_user or device.name)
and (str(entity_id_or_device_name) == name)
),
None,
)
def device_name(self, lookup_value: str) -> str | None:
"""Get the device name from an device id, or entity id."""
device_reg = dr.async_get(self.hass)
if device := device_reg.async_get(lookup_value):
return device.name_by_user or device.name
ent_reg = er.async_get(self.hass)
try:
cv.entity_id(lookup_value)
except vol.Invalid:
pass
else:
if entity := ent_reg.async_get(lookup_value):
if entity.device_id and (
device := device_reg.async_get(entity.device_id)
):
return device.name_by_user or device.name
return None
def device_attr(self, device_or_entity_id: str, attr_name: str) -> Any:
"""Get the device specific attribute."""
device_reg = dr.async_get(self.hass)
if not isinstance(device_or_entity_id, str):
raise TemplateError("Must provide a device or entity ID")
device = None
if (
"." in device_or_entity_id
and (_device_id := self.device_id(device_or_entity_id)) is not None
):
device = device_reg.async_get(_device_id)
elif "." not in device_or_entity_id:
device = device_reg.async_get(device_or_entity_id)
if device is None or not hasattr(device, attr_name):
return None
return getattr(device, attr_name)
def is_device_attr(
self, device_or_entity_id: str, attr_name: str, attr_value: Any
) -> bool:
"""Test if a device's attribute is a specific value."""
return bool(self.device_attr(device_or_entity_id, attr_name) == attr_value)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/helpers/template/extensions/devices.py",
"license": "Apache License 2.0",
"lines": 121,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/helpers/template/extensions/floors.py | """Floor functions for Home Assistant templates."""
from __future__ import annotations
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
from homeassistant.helpers import (
area_registry as ar,
device_registry as dr,
entity_registry as er,
floor_registry as fr,
)
from homeassistant.helpers.template.helpers import resolve_area_id
from .base import BaseTemplateExtension, TemplateFunction
if TYPE_CHECKING:
from homeassistant.helpers.template import TemplateEnvironment
class FloorExtension(BaseTemplateExtension):
"""Extension for floor-related template functions."""
def __init__(self, environment: TemplateEnvironment) -> None:
"""Initialize the floor extension."""
super().__init__(
environment,
functions=[
TemplateFunction(
"floors",
self.floors,
as_global=True,
requires_hass=True,
),
TemplateFunction(
"floor_id",
self.floor_id,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"floor_name",
self.floor_name,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"floor_areas",
self.floor_areas,
as_global=True,
as_filter=True,
requires_hass=True,
),
TemplateFunction(
"floor_entities",
self.floor_entities,
as_global=True,
as_filter=True,
requires_hass=True,
),
],
)
def floors(self) -> Iterable[str | None]:
"""Return all floors."""
floor_registry = fr.async_get(self.hass)
return [floor.floor_id for floor in floor_registry.async_list_floors()]
def floor_id(self, lookup_value: Any) -> str | None:
"""Get the floor ID from a floor or area name, alias, device id, or entity id."""
floor_registry = fr.async_get(self.hass)
lookup_str = str(lookup_value)
# Check if it's a floor name or alias
if floor := floor_registry.async_get_floor_by_name(lookup_str):
return floor.floor_id
floors_list = floor_registry.async_get_floors_by_alias(lookup_str)
if floors_list:
return floors_list[0].floor_id
# Resolve to area ID and get floor from area
if aid := resolve_area_id(self.hass, lookup_value):
area_reg = ar.async_get(self.hass)
if area := area_reg.async_get_area(aid):
return area.floor_id
return None
def floor_name(self, lookup_value: str) -> str | None:
"""Get the floor name from a floor id."""
floor_registry = fr.async_get(self.hass)
# Check if it's a floor ID
if floor := floor_registry.async_get_floor(lookup_value):
return floor.name
# Resolve to area ID and get floor name from area's floor
if aid := resolve_area_id(self.hass, lookup_value):
area_reg = ar.async_get(self.hass)
if (
(area := area_reg.async_get_area(aid))
and area.floor_id
and (floor := floor_registry.async_get_floor(area.floor_id))
):
return floor.name
return None
def _floor_id_or_name(self, floor_id_or_name: str) -> str | None:
"""Get the floor ID from a floor name or ID."""
# If floor_name returns a value, we know the input was an ID, otherwise we
# assume it's a name, and if it's neither, we return early.
if self.floor_name(floor_id_or_name) is not None:
return floor_id_or_name
return self.floor_id(floor_id_or_name)
def floor_areas(self, floor_id_or_name: str) -> Iterable[str]:
"""Return area IDs for a given floor ID or name."""
if (_floor_id := self._floor_id_or_name(floor_id_or_name)) is None:
return []
area_reg = ar.async_get(self.hass)
entries = ar.async_entries_for_floor(area_reg, _floor_id)
return [entry.id for entry in entries if entry.id]
def floor_entities(self, floor_id_or_name: str) -> Iterable[str]:
"""Return entity_ids for a given floor ID or name."""
ent_reg = er.async_get(self.hass)
dev_reg = dr.async_get(self.hass)
entity_ids = []
for area_id in self.floor_areas(floor_id_or_name):
# Get entities directly assigned to the area
entity_ids.extend(
[
entry.entity_id
for entry in er.async_entries_for_area(ent_reg, area_id)
]
)
# Also add entities tied to a device in the area that don't themselves
# have an area specified since they inherit the area from the device
entity_ids.extend(
[
entity.entity_id
for device in dr.async_entries_for_area(dev_reg, area_id)
for entity in er.async_entries_for_device(ent_reg, device.id)
if entity.area_id is None
]
)
return entity_ids
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/helpers/template/extensions/floors.py",
"license": "Apache License 2.0",
"lines": 133,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/helpers/template/extensions/issues.py | """Issue functions for Home Assistant templates."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from homeassistant.helpers import issue_registry as ir
from .base import BaseTemplateExtension, TemplateFunction
if TYPE_CHECKING:
from homeassistant.helpers.template import TemplateEnvironment
class IssuesExtension(BaseTemplateExtension):
"""Extension for issue-related template functions."""
def __init__(self, environment: TemplateEnvironment) -> None:
"""Initialize the issues extension."""
super().__init__(
environment,
functions=[
TemplateFunction(
"issues",
self.issues,
as_global=True,
requires_hass=True,
),
TemplateFunction(
"issue",
self.issue,
as_global=True,
as_filter=True,
requires_hass=True,
),
],
)
def issues(self) -> dict[tuple[str, str], dict[str, Any]]:
"""Return all open issues."""
current_issues = ir.async_get(self.hass).issues
# Use JSON for safe representation
return {
key: issue_entry.to_json()
for (key, issue_entry) in current_issues.items()
if issue_entry.active
}
def issue(self, domain: str, issue_id: str) -> dict[str, Any] | None:
"""Get issue by domain and issue_id."""
result = ir.async_get(self.hass).async_get_issue(domain, issue_id)
if result:
return result.to_json()
return None
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/helpers/template/extensions/issues.py",
"license": "Apache License 2.0",
"lines": 44,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/helpers/template/extensions/labels.py | """Label functions for Home Assistant templates."""
from __future__ import annotations
from collections.abc import Iterable
from typing import TYPE_CHECKING, Any
import voluptuous as vol
from homeassistant.helpers import (
area_registry as ar,
device_registry as dr,
entity_registry as er,
label_registry as lr,
)
from .base import BaseTemplateExtension, TemplateFunction
if TYPE_CHECKING:
from homeassistant.helpers.template import TemplateEnvironment
class LabelExtension(BaseTemplateExtension):
"""Extension for label-related template functions."""
def __init__(self, environment: TemplateEnvironment) -> None:
"""Initialize the label extension."""
super().__init__(
environment,
functions=[
TemplateFunction(
"labels",
self.labels,
as_global=True,
as_filter=True,
requires_hass=True,
),
TemplateFunction(
"label_id",
self.label_id,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"label_name",
self.label_name,
as_global=True,
as_filter=True,
requires_hass=True,
limited_ok=False,
),
TemplateFunction(
"label_description",
self.label_description,
as_global=True,
as_filter=True,
requires_hass=True,
),
TemplateFunction(
"label_areas",
self.label_areas,
as_global=True,
as_filter=True,
requires_hass=True,
),
TemplateFunction(
"label_devices",
self.label_devices,
as_global=True,
as_filter=True,
requires_hass=True,
),
TemplateFunction(
"label_entities",
self.label_entities,
as_global=True,
as_filter=True,
requires_hass=True,
),
],
)
def labels(self, lookup_value: Any = None) -> Iterable[str | None]:
"""Return all labels, or those from a area ID, device ID, or entity ID."""
label_reg = lr.async_get(self.hass)
if lookup_value is None:
return list(label_reg.labels)
ent_reg = er.async_get(self.hass)
# Import here, not at top-level to avoid circular import
from homeassistant.helpers import config_validation as cv # noqa: PLC0415
lookup_value = str(lookup_value)
try:
cv.entity_id(lookup_value)
except vol.Invalid:
pass
else:
if entity := ent_reg.async_get(lookup_value):
return list(entity.labels)
# Check if this could be a device ID
dev_reg = dr.async_get(self.hass)
if device := dev_reg.async_get(lookup_value):
return list(device.labels)
# Check if this could be a area ID
area_reg = ar.async_get(self.hass)
if area := area_reg.async_get_area(lookup_value):
return list(area.labels)
return []
def label_id(self, lookup_value: Any) -> str | None:
"""Get the label ID from a label name."""
label_reg = lr.async_get(self.hass)
if label := label_reg.async_get_label_by_name(str(lookup_value)):
return label.label_id
return None
def label_name(self, lookup_value: str) -> str | None:
"""Get the label name from a label ID."""
label_reg = lr.async_get(self.hass)
if label := label_reg.async_get_label(lookup_value):
return label.name
return None
def label_description(self, lookup_value: str) -> str | None:
"""Get the label description from a label ID."""
label_reg = lr.async_get(self.hass)
if label := label_reg.async_get_label(lookup_value):
return label.description
return None
def _label_id_or_name(self, label_id_or_name: str) -> str | None:
"""Get the label ID from a label name or ID."""
# If label_name returns a value, we know the input was an ID, otherwise we
# assume it's a name, and if it's neither, we return early.
if self.label_name(label_id_or_name) is not None:
return label_id_or_name
return self.label_id(label_id_or_name)
def label_areas(self, label_id_or_name: str) -> Iterable[str]:
"""Return areas for a given label ID or name."""
if (_label_id := self._label_id_or_name(label_id_or_name)) is None:
return []
area_reg = ar.async_get(self.hass)
entries = ar.async_entries_for_label(area_reg, _label_id)
return [entry.id for entry in entries]
def label_devices(self, label_id_or_name: str) -> Iterable[str]:
"""Return device IDs for a given label ID or name."""
if (_label_id := self._label_id_or_name(label_id_or_name)) is None:
return []
dev_reg = dr.async_get(self.hass)
entries = dr.async_entries_for_label(dev_reg, _label_id)
return [entry.id for entry in entries]
def label_entities(self, label_id_or_name: str) -> Iterable[str]:
"""Return entities for a given label ID or name."""
if (_label_id := self._label_id_or_name(label_id_or_name)) is None:
return []
ent_reg = er.async_get(self.hass)
entries = er.async_entries_for_label(ent_reg, _label_id)
return [entry.entity_id for entry in entries]
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/helpers/template/extensions/labels.py",
"license": "Apache License 2.0",
"lines": 145,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:script/hassfest/labs.py | """Generate lab preview features file."""
from __future__ import annotations
from .model import Config, Integration
from .serializer import format_python_namespace
def generate_and_validate(integrations: dict[str, Integration]) -> str:
"""Validate and generate lab preview features data."""
labs_dict: dict[str, dict[str, dict[str, str]]] = {}
for domain in sorted(integrations):
integration = integrations[domain]
preview_features = integration.manifest.get("preview_features")
if not preview_features:
continue
if not isinstance(preview_features, dict):
integration.add_error(
"labs",
f"preview_features must be a dict, got {type(preview_features).__name__}",
)
continue
# Extract features with full data
domain_preview_features: dict[str, dict[str, str]] = {}
for preview_feature_id, preview_feature_config in preview_features.items():
if not isinstance(preview_feature_id, str):
integration.add_error(
"labs",
f"preview_features keys must be strings, got {type(preview_feature_id).__name__}",
)
break
if not isinstance(preview_feature_config, dict):
integration.add_error(
"labs",
f"preview_features[{preview_feature_id}] must be a dict, got {type(preview_feature_config).__name__}",
)
break
# Include the full feature configuration
domain_preview_features[preview_feature_id] = {
"feedback_url": preview_feature_config.get("feedback_url", ""),
"learn_more_url": preview_feature_config.get("learn_more_url", ""),
"report_issue_url": preview_feature_config.get("report_issue_url", ""),
}
else:
# Only add if all features are valid
if domain_preview_features:
labs_dict[domain] = domain_preview_features
return format_python_namespace(
{
"LABS_PREVIEW_FEATURES": labs_dict,
}
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Validate lab preview features file."""
labs_path = config.root / "homeassistant/generated/labs.py"
config.cache["labs"] = content = generate_and_validate(integrations)
if config.specific_integrations:
return
if not labs_path.exists() or labs_path.read_text() != content:
config.add_error(
"labs",
"File labs.py is not up to date. Run python3 -m script.hassfest",
fixable=True,
)
def generate(integrations: dict[str, Integration], config: Config) -> None:
"""Generate lab preview features file."""
labs_path = config.root / "homeassistant/generated/labs.py"
labs_path.write_text(config.cache["labs"])
| {
"repo_id": "home-assistant/core",
"file_path": "script/hassfest/labs.py",
"license": "Apache License 2.0",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/adguard/test_init.py | """Tests for the AdGuard Home."""
from unittest.mock import AsyncMock
from adguardhome import AdGuardHomeConnectionError
import pytest
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return []
@pytest.mark.usefixtures("init_integration")
async def test_setup(
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the adguard setup."""
assert mock_config_entry.state is ConfigEntryState.LOADED
async def test_setup_failed(
hass: HomeAssistant,
mock_adguard: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the adguard setup failed."""
mock_adguard.version.side_effect = AdGuardHomeConnectionError("Connection error")
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/adguard/test_init.py",
"license": "Apache License 2.0",
"lines": 29,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/adguard/test_sensor.py | """Tests for the AdGuard Home sensor entities."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return [Platform.SENSOR]
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_sensors(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the adguard sensor platform."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/adguard/test_sensor.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/adguard/test_service.py | """Tests for the AdGuard Home sensor entities."""
from collections.abc import Callable
from typing import Any
from unittest.mock import AsyncMock
import pytest
from homeassistant.components.adguard.const import (
DOMAIN,
SERVICE_ADD_URL,
SERVICE_DISABLE_URL,
SERVICE_ENABLE_URL,
SERVICE_REFRESH,
SERVICE_REMOVE_URL,
)
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
pytestmark = pytest.mark.usefixtures("init_integration")
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return []
async def test_service_registration(
hass: HomeAssistant,
) -> None:
"""Test the adguard services be registered."""
services = hass.services.async_services_for_domain(DOMAIN)
assert len(services) == 5
assert SERVICE_ADD_URL in services
assert SERVICE_DISABLE_URL in services
assert SERVICE_ENABLE_URL in services
assert SERVICE_REFRESH in services
assert SERVICE_REMOVE_URL in services
@pytest.mark.parametrize(
("service", "service_call_data", "call_assertion"),
[
(
SERVICE_ADD_URL,
{"name": "Example", "url": "https://example.com/1.txt"},
lambda mock: mock.filtering.add_url.assert_called_once(),
),
(
SERVICE_DISABLE_URL,
{"url": "https://example.com/1.txt"},
lambda mock: mock.filtering.disable_url.assert_called_once(),
),
(
SERVICE_ENABLE_URL,
{"url": "https://example.com/1.txt"},
lambda mock: mock.filtering.enable_url.assert_called_once(),
),
(
SERVICE_REFRESH,
{"force": False},
lambda mock: mock.filtering.refresh.assert_called_once(),
),
(
SERVICE_REMOVE_URL,
{"url": "https://example.com/1.txt"},
lambda mock: mock.filtering.remove_url.assert_called_once(),
),
],
)
async def test_service(
hass: HomeAssistant,
mock_adguard: AsyncMock,
service: str,
service_call_data: dict,
call_assertion: Callable[[AsyncMock], Any],
) -> None:
"""Test the adguard services be unregistered with unloading last entry."""
await hass.services.async_call(
DOMAIN,
service,
service_call_data,
blocking=True,
)
call_assertion(mock_adguard)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/adguard/test_service.py",
"license": "Apache License 2.0",
"lines": 76,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/adguard/test_update.py | """Tests for the AdGuard Home update entity."""
from unittest.mock import AsyncMock, patch
from adguardhome import AdGuardHomeError
from adguardhome.update import AdGuardHomeAvailableUpdate
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return [Platform.UPDATE]
@pytest.mark.usefixtures("init_integration")
async def test_update(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the adguard update platform."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_update_disabled(
hass: HomeAssistant,
mock_adguard: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the adguard update is disabled."""
mock_adguard.update.update_available.return_value = AdGuardHomeAvailableUpdate(
disabled=True,
)
mock_config_entry.add_to_hass(hass)
with patch("homeassistant.components.adguard.PLATFORMS", [Platform.UPDATE]):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert not hass.states.async_all()
@pytest.mark.usefixtures("init_integration")
async def test_update_install(
hass: HomeAssistant,
mock_adguard: AsyncMock,
) -> None:
"""Test the adguard update installation."""
await hass.services.async_call(
"update",
"install",
{"entity_id": "update.adguard_home"},
blocking=True,
)
mock_adguard.update.begin_update.assert_called_once()
@pytest.mark.usefixtures("init_integration")
async def test_update_install_failed(
hass: HomeAssistant,
mock_adguard: AsyncMock,
) -> None:
"""Test the adguard update install failed."""
mock_adguard.update.begin_update.side_effect = AdGuardHomeError("boom")
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
"update",
"install",
{"entity_id": "update.adguard_home"},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/adguard/test_update.py",
"license": "Apache License 2.0",
"lines": 65,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/airobot/test_climate.py | """Test the Airobot climate platform."""
from datetime import timedelta
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
from pyairobotrest.const import MODE_AWAY, MODE_HOME
from pyairobotrest.exceptions import AirobotConnectionError, AirobotError
from pyairobotrest.models import ThermostatSettings, ThermostatStatus
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.climate import (
ATTR_PRESET_MODE,
ATTR_TEMPERATURE,
DOMAIN as CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
SERVICE_SET_TEMPERATURE,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
import homeassistant.helpers.entity_registry as er
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return [Platform.CLIMATE]
@pytest.mark.usefixtures("init_integration")
async def test_climate_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
platforms: list[Platform],
) -> None:
"""Test climate entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("mode", "temperature", "method"),
[
(1, 24.0, "set_home_temperature"), # Home mode
(0, 18.0, "set_away_temperature"), # Away mode
],
)
async def test_climate_set_temperature(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
mock_settings: ThermostatSettings,
mock_config_entry: MockConfigEntry,
mode: int,
temperature: float,
method: str,
) -> None:
"""Test setting temperature in different modes."""
# Set device mode
mock_settings.mode = mode
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "climate.test_thermostat",
ATTR_TEMPERATURE: temperature,
},
blocking=True,
)
getattr(mock_airobot_client, method).assert_called_once_with(temperature)
@pytest.mark.usefixtures("init_integration")
async def test_climate_set_temperature_error(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
) -> None:
"""Test error handling when setting temperature fails."""
mock_airobot_client.set_home_temperature.side_effect = AirobotError("Device error")
with pytest.raises(
ServiceValidationError, match="Failed to set temperature"
) as exc_info:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "climate.test_thermostat",
ATTR_TEMPERATURE: 24.0,
},
blocking=True,
)
assert exc_info.value.translation_domain == "airobot"
assert exc_info.value.translation_key == "set_temperature_failed"
assert exc_info.value.translation_placeholders == {"temperature": "24.0"}
@pytest.mark.parametrize(
("preset_mode", "method", "arg"),
[
("home", "set_mode", MODE_HOME),
("away", "set_mode", MODE_AWAY),
("boost", "set_boost_mode", True),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_climate_set_preset_mode(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
preset_mode: str,
method: str,
arg: int | bool,
) -> None:
"""Test setting different preset modes."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
{
ATTR_ENTITY_ID: "climate.test_thermostat",
ATTR_PRESET_MODE: preset_mode,
},
blocking=True,
)
getattr(mock_airobot_client, method).assert_called_once_with(arg)
async def test_climate_set_preset_mode_from_boost_to_home(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
mock_settings: ThermostatSettings,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test disabling boost when switching to home mode."""
# Set boost mode enabled
mock_settings.setting_flags.boost_enabled = True
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
{
ATTR_ENTITY_ID: "climate.test_thermostat",
ATTR_PRESET_MODE: "home",
},
blocking=True,
)
# Should disable boost first, then set mode to home
mock_airobot_client.set_boost_mode.assert_called_once_with(False)
mock_airobot_client.set_mode.assert_called_once_with(MODE_HOME)
@pytest.mark.usefixtures("init_integration")
async def test_climate_set_preset_mode_error(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
) -> None:
"""Test error handling when setting preset mode fails."""
mock_airobot_client.set_boost_mode.side_effect = AirobotError("Device error")
with pytest.raises(
ServiceValidationError, match="Failed to set preset mode"
) as exc_info:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
{
ATTR_ENTITY_ID: "climate.test_thermostat",
ATTR_PRESET_MODE: "boost",
},
blocking=True,
)
assert exc_info.value.translation_domain == "airobot"
assert exc_info.value.translation_key == "set_preset_mode_failed"
assert exc_info.value.translation_placeholders == {"preset_mode": "boost"}
async def test_climate_heating_state(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
mock_status: ThermostatStatus,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test climate entity shows heating action when heating."""
# Set heating on
mock_status.status_flags.heating_on = True
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.test_thermostat")
assert state
assert state.attributes.get("hvac_action") == "heating"
@pytest.mark.usefixtures("init_integration")
async def test_climate_unavailable_on_update_failure(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test climate entity becomes unavailable when coordinator update fails."""
# Initially available
state = hass.states.get("climate.test_thermostat")
assert state
assert state.state != "unavailable"
# Simulate connection error during update
mock_airobot_client.get_statuses.side_effect = AirobotConnectionError(
"Connection lost"
)
mock_airobot_client.get_settings.side_effect = AirobotConnectionError(
"Connection lost"
)
# Advance time to trigger coordinator update (30 second interval)
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Entity should now be unavailable
state = hass.states.get("climate.test_thermostat")
assert state
assert state.state == "unavailable"
@pytest.mark.parametrize(
("temp_floor", "temp_air", "expected_temp"),
[
(25.0, 22.0, 25.0), # Floor sensor available - should use floor temp
(None, 22.0, 22.0), # Floor sensor not available - should use air temp
],
)
async def test_climate_current_temperature(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
mock_status: ThermostatStatus,
mock_config_entry: MockConfigEntry,
temp_floor: float | None,
temp_air: float,
expected_temp: float,
) -> None:
"""Test current temperature prioritizes floor sensor when available."""
mock_status.temp_floor = temp_floor
mock_status.temp_air = temp_air
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.test_thermostat")
assert state
assert state.attributes.get("current_temperature") == expected_temp
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/airobot/test_climate.py",
"license": "Apache License 2.0",
"lines": 228,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/airobot/test_config_flow.py | """Test the Airobot config flow."""
from unittest.mock import AsyncMock
from pyairobotrest.exceptions import (
AirobotAuthError,
AirobotConnectionError,
AirobotError,
)
import pytest
from homeassistant import config_entries
from homeassistant.components.airobot.const import DOMAIN
from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo
from tests.common import MockConfigEntry
TEST_USER_INPUT = {
CONF_HOST: "192.168.1.100",
CONF_USERNAME: "T01A1B2C3",
CONF_PASSWORD: "test-password",
}
async def test_user_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
) -> None:
"""Test user flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Test Thermostat"
assert result["data"] == TEST_USER_INPUT
assert result["result"].unique_id == "T01A1B2C3"
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("exception", "error_base"),
[
(AirobotAuthError("Authentication failed"), "invalid_auth"),
(AirobotConnectionError("Connection failed"), "cannot_connect"),
(AirobotError("Generic error"), "cannot_connect"),
(Exception("Unexpected error"), "unknown"),
],
)
async def test_form_exceptions(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
exception: Exception,
error_base: str,
) -> None:
"""Test we handle various errors in user flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
mock_airobot_client.get_settings.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_USER_INPUT,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_base}
mock_airobot_client.get_settings.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Test Thermostat"
assert result["data"] == TEST_USER_INPUT
assert len(mock_setup_entry.mock_calls) == 1
async def test_duplicate_entry(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test duplicate detection."""
mock_config_entry.add_to_hass(hass)
# Try to configure the same device again
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_USER_INPUT,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_dhcp_discovery(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
) -> None:
"""Test DHCP discovery flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_DHCP},
data=DhcpServiceInfo(
ip="192.168.1.100",
macaddress="b8d61aabcdef",
hostname="airobot-thermostat-t01a1b2c3",
),
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "dhcp_confirm"
assert result["description_placeholders"] == {
"host": "192.168.1.100",
"device_id": "T01A1B2C3",
}
# Complete the flow by providing password only
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_PASSWORD: "test-password"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Test Thermostat"
assert result["data"][CONF_HOST] == "192.168.1.100"
assert result["data"][CONF_USERNAME] == "T01A1B2C3"
assert result["data"][CONF_PASSWORD] == "test-password"
assert result["data"][CONF_MAC] == "b8d61aabcdef"
@pytest.mark.parametrize(
("exception", "error_base"),
[
(AirobotAuthError("Invalid credentials"), "invalid_auth"),
(AirobotConnectionError("Connection failed"), "cannot_connect"),
(Exception("Unknown error"), "unknown"),
],
)
async def test_dhcp_discovery_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
exception: Exception,
error_base: str,
) -> None:
"""Test DHCP discovery with error handling."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_DHCP},
data=DhcpServiceInfo(
ip="192.168.1.100",
macaddress="aabbccddeeff",
hostname="airobot-thermostat-t01d4e5f6",
),
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "dhcp_confirm"
mock_airobot_client.get_statuses.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_PASSWORD: "wrong"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_base}
# Recover from error
mock_airobot_client.get_statuses.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_PASSWORD: "test-password"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Test Thermostat"
assert len(mock_setup_entry.mock_calls) == 1
async def test_dhcp_discovery_duplicate(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test DHCP discovery with duplicate device."""
mock_config_entry.add_to_hass(hass)
# DHCP discovers the same device with potentially different IP
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_DHCP},
data=DhcpServiceInfo(
ip="192.168.1.101", # Different IP
macaddress="b8d61aabcdef", # Same MAC
hostname="airobot-thermostat-t01a1b2c3", # Same hostname = same device_id
),
)
await hass.async_block_till_done()
# Should abort immediately since device_id extracted from hostname matches existing entry
# and update the IP address
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
# Verify the IP was updated in the existing entry
assert mock_config_entry.data[CONF_HOST] == "192.168.1.101"
async def test_reauth_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauthentication flow."""
mock_config_entry.add_to_hass(hass)
# Trigger reauthentication
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["description_placeholders"]["username"] == "T01A1B2C3"
assert result["description_placeholders"]["host"] == "192.168.1.100"
# Provide new password
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_PASSWORD: "new-password"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_PASSWORD] == "new-password"
@pytest.mark.parametrize(
("exception", "error_base"),
[
(AirobotAuthError("Invalid credentials"), "invalid_auth"),
(AirobotConnectionError("Connection failed"), "cannot_connect"),
(Exception("Unknown error"), "unknown"),
],
)
async def test_reauth_flow_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
error_base: str,
) -> None:
"""Test reauthentication flow with errors."""
mock_config_entry.add_to_hass(hass)
# Trigger reauthentication
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
# First attempt with error
mock_airobot_client.get_statuses.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_PASSWORD: "wrong-password"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_base}
# Recover from error
mock_airobot_client.get_statuses.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_PASSWORD: "new-password"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_PASSWORD] == "new-password"
async def test_reconfigure_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration flow."""
mock_config_entry.add_to_hass(hass)
# Trigger reconfiguration
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
# Update configuration (e.g., new IP address and password)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.200",
CONF_USERNAME: "T01A1B2C3",
CONF_PASSWORD: "new-password",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "192.168.1.200"
assert mock_config_entry.data[CONF_USERNAME] == "T01A1B2C3"
assert mock_config_entry.data[CONF_PASSWORD] == "new-password"
async def test_reconfigure_flow_wrong_device(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration flow with wrong device."""
mock_config_entry.add_to_hass(hass)
# Trigger reconfiguration
result = await mock_config_entry.start_reconfigure_flow(hass)
# Try to reconfigure with a different device ID
mock_airobot_client.get_settings.return_value.device_name = "Different Device"
mock_airobot_client.get_statuses.return_value.device_id = "T01DIFFERENT"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.200",
CONF_USERNAME: "T01DIFFERENT",
CONF_PASSWORD: "test-password",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "wrong_device"
@pytest.mark.parametrize(
("exception", "error_base"),
[
(AirobotAuthError("Invalid credentials"), "invalid_auth"),
(AirobotConnectionError("Connection failed"), "cannot_connect"),
(Exception("Unknown error"), "unknown"),
],
)
async def test_reconfigure_flow_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_airobot_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
error_base: str,
) -> None:
"""Test reconfiguration flow with errors."""
mock_config_entry.add_to_hass(hass)
# Trigger reconfiguration
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
# First attempt with error
mock_airobot_client.get_statuses.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.200",
CONF_USERNAME: "T01A1B2C3",
CONF_PASSWORD: "wrong-password",
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_base}
# Recover from error
mock_airobot_client.get_statuses.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.200",
CONF_USERNAME: "T01A1B2C3",
CONF_PASSWORD: "new-password",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "192.168.1.200"
assert mock_config_entry.data[CONF_PASSWORD] == "new-password"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/airobot/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 355,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/airobot/test_init.py | """Test the Airobot integration init."""
from unittest.mock import AsyncMock
from pyairobotrest.exceptions import AirobotAuthError, AirobotConnectionError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.airobot.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("init_integration")
async def test_setup_entry_success(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test successful setup of a config entry."""
assert mock_config_entry.state is ConfigEntryState.LOADED
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
@pytest.mark.parametrize(
("exception", "expected_state"),
[
(AirobotAuthError("Authentication failed"), ConfigEntryState.SETUP_ERROR),
(AirobotConnectionError("Connection failed"), ConfigEntryState.SETUP_RETRY),
],
)
async def test_setup_entry_exceptions(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
expected_state: ConfigEntryState,
) -> None:
"""Test setup fails with various exceptions."""
mock_config_entry.add_to_hass(hass)
mock_airobot_client.get_statuses.side_effect = exception
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is expected_state
async def test_setup_entry_auth_error_triggers_reauth(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setup with auth error triggers reauth flow."""
mock_config_entry.add_to_hass(hass)
mock_airobot_client.get_statuses.side_effect = AirobotAuthError(
"Authentication failed"
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
@pytest.mark.usefixtures("init_integration")
async def test_unload_entry(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test unloading a 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.usefixtures("init_integration")
async def test_device_entry(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test device registry entry."""
assert (
device_entry := device_registry.async_get_device(
identifiers={(DOMAIN, "T01A1B2C3")}
)
)
assert device_entry == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/airobot/test_init.py",
"license": "Apache License 2.0",
"lines": 74,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/alarm_control_panel/test_trigger.py | """Test alarm control panel triggers."""
from typing import Any
import pytest
from homeassistant.components.alarm_control_panel import (
AlarmControlPanelEntityFeature,
AlarmControlPanelState,
)
from homeassistant.const import ATTR_LABEL_ID, ATTR_SUPPORTED_FEATURES, CONF_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
other_states,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_alarm_control_panels(hass: HomeAssistant) -> list[str]:
"""Create multiple alarm control panel entities associated with different targets."""
return (await target_entities(hass, "alarm_control_panel"))["included"]
@pytest.mark.parametrize(
"trigger_key",
[
"alarm_control_panel.armed",
"alarm_control_panel.armed_away",
"alarm_control_panel.armed_home",
"alarm_control_panel.armed_night",
"alarm_control_panel.armed_vacation",
"alarm_control_panel.disarmed",
"alarm_control_panel.triggered",
],
)
async def test_alarm_control_panel_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the ACP triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("alarm_control_panel"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="alarm_control_panel.armed",
target_states=[
AlarmControlPanelState.ARMED_AWAY,
AlarmControlPanelState.ARMED_CUSTOM_BYPASS,
AlarmControlPanelState.ARMED_HOME,
AlarmControlPanelState.ARMED_NIGHT,
AlarmControlPanelState.ARMED_VACATION,
],
other_states=[
AlarmControlPanelState.ARMING,
AlarmControlPanelState.DISARMED,
AlarmControlPanelState.DISARMING,
AlarmControlPanelState.PENDING,
AlarmControlPanelState.TRIGGERED,
],
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_away",
target_states=[AlarmControlPanelState.ARMED_AWAY],
other_states=other_states(AlarmControlPanelState.ARMED_AWAY),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_AWAY
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_home",
target_states=[AlarmControlPanelState.ARMED_HOME],
other_states=other_states(AlarmControlPanelState.ARMED_HOME),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_HOME
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_night",
target_states=[AlarmControlPanelState.ARMED_NIGHT],
other_states=other_states(AlarmControlPanelState.ARMED_NIGHT),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_NIGHT
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_vacation",
target_states=[AlarmControlPanelState.ARMED_VACATION],
other_states=other_states(AlarmControlPanelState.ARMED_VACATION),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_VACATION
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.disarmed",
target_states=[AlarmControlPanelState.DISARMED],
other_states=other_states(AlarmControlPanelState.DISARMED),
),
*parametrize_trigger_states(
trigger="alarm_control_panel.triggered",
target_states=[AlarmControlPanelState.TRIGGERED],
other_states=other_states(AlarmControlPanelState.TRIGGERED),
),
],
)
async def test_alarm_control_panel_state_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_alarm_control_panels: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the alarm control panel state trigger fires when any alarm control panel state changes to a specific state."""
other_entity_ids = set(target_alarm_control_panels) - {entity_id}
# Set all alarm control panels, including the tested one, to the initial state
for eid in target_alarm_control_panels:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other alarm control panels also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("alarm_control_panel"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="alarm_control_panel.armed",
target_states=[
AlarmControlPanelState.ARMED_AWAY,
AlarmControlPanelState.ARMED_CUSTOM_BYPASS,
AlarmControlPanelState.ARMED_HOME,
AlarmControlPanelState.ARMED_NIGHT,
AlarmControlPanelState.ARMED_VACATION,
],
other_states=[
AlarmControlPanelState.ARMING,
AlarmControlPanelState.DISARMED,
AlarmControlPanelState.DISARMING,
AlarmControlPanelState.PENDING,
AlarmControlPanelState.TRIGGERED,
],
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_away",
target_states=[AlarmControlPanelState.ARMED_AWAY],
other_states=other_states(AlarmControlPanelState.ARMED_AWAY),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_AWAY
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_home",
target_states=[AlarmControlPanelState.ARMED_HOME],
other_states=other_states(AlarmControlPanelState.ARMED_HOME),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_HOME
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_night",
target_states=[AlarmControlPanelState.ARMED_NIGHT],
other_states=other_states(AlarmControlPanelState.ARMED_NIGHT),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_NIGHT
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_vacation",
target_states=[AlarmControlPanelState.ARMED_VACATION],
other_states=other_states(AlarmControlPanelState.ARMED_VACATION),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_VACATION
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.disarmed",
target_states=[AlarmControlPanelState.DISARMED],
other_states=other_states(AlarmControlPanelState.DISARMED),
),
*parametrize_trigger_states(
trigger="alarm_control_panel.triggered",
target_states=[AlarmControlPanelState.TRIGGERED],
other_states=other_states(AlarmControlPanelState.TRIGGERED),
),
],
)
async def test_alarm_control_panel_state_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_alarm_control_panels: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the alarm control panel state trigger fires when the first alarm control panel changes to a specific state."""
other_entity_ids = set(target_alarm_control_panels) - {entity_id}
# Set all alarm control panels, including the tested one, to the initial state
for eid in target_alarm_control_panels:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other alarm control panels should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("alarm_control_panel"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="alarm_control_panel.armed",
target_states=[
AlarmControlPanelState.ARMED_AWAY,
AlarmControlPanelState.ARMED_CUSTOM_BYPASS,
AlarmControlPanelState.ARMED_HOME,
AlarmControlPanelState.ARMED_NIGHT,
AlarmControlPanelState.ARMED_VACATION,
],
other_states=[
AlarmControlPanelState.ARMING,
AlarmControlPanelState.DISARMED,
AlarmControlPanelState.DISARMING,
AlarmControlPanelState.PENDING,
AlarmControlPanelState.TRIGGERED,
],
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_away",
target_states=[AlarmControlPanelState.ARMED_AWAY],
other_states=other_states(AlarmControlPanelState.ARMED_AWAY),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_AWAY
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_home",
target_states=[AlarmControlPanelState.ARMED_HOME],
other_states=other_states(AlarmControlPanelState.ARMED_HOME),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_HOME
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_night",
target_states=[AlarmControlPanelState.ARMED_NIGHT],
other_states=other_states(AlarmControlPanelState.ARMED_NIGHT),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_NIGHT
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.armed_vacation",
target_states=[AlarmControlPanelState.ARMED_VACATION],
other_states=other_states(AlarmControlPanelState.ARMED_VACATION),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_VACATION
},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="alarm_control_panel.disarmed",
target_states=[AlarmControlPanelState.DISARMED],
other_states=other_states(AlarmControlPanelState.DISARMED),
),
*parametrize_trigger_states(
trigger="alarm_control_panel.triggered",
target_states=[AlarmControlPanelState.TRIGGERED],
other_states=other_states(AlarmControlPanelState.TRIGGERED),
),
],
)
async def test_alarm_control_panel_state_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_alarm_control_panels: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the alarm_control_panel state trigger fires when the last alarm_control_panel changes to a specific state."""
other_entity_ids = set(target_alarm_control_panels) - {entity_id}
# Set all alarm control panels, including the tested one, to the initial state
for eid in target_alarm_control_panels:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alarm_control_panel/test_trigger.py",
"license": "Apache License 2.0",
"lines": 357,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/anglian_water/const.py | """Constants for the Anglian Water test suite."""
ACCOUNT_NUMBER = "171266493"
ACCESS_TOKEN = "valid_token"
USERNAME = "hello@example.com"
PASSWORD = "SecurePassword123"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/anglian_water/const.py",
"license": "Apache License 2.0",
"lines": 5,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/anglian_water/test_config_flow.py | """Test the Anglian Water config flow."""
from unittest.mock import AsyncMock
from pyanglianwater.exceptions import (
InvalidAccountIdError,
SelfAssertedError,
SmartMeterUnavailableError,
)
import pytest
from homeassistant import config_entries
from homeassistant.components.anglian_water.const import CONF_ACCOUNT_NUMBER, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import ACCESS_TOKEN, ACCOUNT_NUMBER, PASSWORD, USERNAME
from tests.common import MockConfigEntry, async_load_json_object_fixture
async def test_multiple_account_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_anglian_water_authenticator: AsyncMock,
mock_anglian_water_client: AsyncMock,
) -> None:
"""Test the config flow when there are multiple accounts."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result is not None
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_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "select_account"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_ACCOUNT_NUMBER: ACCOUNT_NUMBER,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == ACCOUNT_NUMBER
assert result["data"][CONF_USERNAME] == USERNAME
assert result["data"][CONF_PASSWORD] == PASSWORD
assert result["data"][CONF_ACCESS_TOKEN] == ACCESS_TOKEN
assert result["data"][CONF_ACCOUNT_NUMBER] == ACCOUNT_NUMBER
assert result["result"].unique_id == ACCOUNT_NUMBER
async def test_single_account_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_anglian_water_authenticator: AsyncMock,
mock_anglian_water_client: AsyncMock,
) -> None:
"""Test the config flow when there is just a single account."""
mock_anglian_water_client.api.get_associated_accounts.return_value = (
await async_load_json_object_fixture(
hass, "single_associated_accounts.json", DOMAIN
)
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result is not None
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_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == ACCOUNT_NUMBER
assert result["data"][CONF_USERNAME] == USERNAME
assert result["data"][CONF_PASSWORD] == PASSWORD
assert result["data"][CONF_ACCESS_TOKEN] == ACCESS_TOKEN
assert result["data"][CONF_ACCOUNT_NUMBER] == ACCOUNT_NUMBER
assert result["result"].unique_id == ACCOUNT_NUMBER
async def test_already_configured(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_anglian_water_authenticator: AsyncMock,
mock_anglian_water_client: AsyncMock,
) -> None:
"""Test that the flow aborts when the entry is already added."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result is not None
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_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "select_account"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_ACCOUNT_NUMBER: ACCOUNT_NUMBER,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("exception_type", "expected_error"),
[(SelfAssertedError, "invalid_auth"), (ValueError, "unknown")],
)
async def test_auth_recover_exception(
hass: HomeAssistant,
mock_anglian_water_authenticator: AsyncMock,
mock_anglian_water_client: AsyncMock,
exception_type,
expected_error,
) -> None:
"""Test that the flow can recover from an auth exception."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result is not None
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
mock_anglian_water_authenticator.send_login_request.side_effect = exception_type
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": expected_error}
# Now test we can recover
mock_anglian_water_authenticator.send_login_request.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "select_account"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_ACCOUNT_NUMBER: ACCOUNT_NUMBER,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == ACCOUNT_NUMBER
assert result["data"][CONF_USERNAME] == USERNAME
assert result["data"][CONF_PASSWORD] == PASSWORD
assert result["data"][CONF_ACCESS_TOKEN] == ACCESS_TOKEN
assert result["data"][CONF_ACCOUNT_NUMBER] == ACCOUNT_NUMBER
assert result["result"].unique_id == ACCOUNT_NUMBER
@pytest.mark.parametrize(
("exception_type", "expected_error"),
[
(SmartMeterUnavailableError, "smart_meter_unavailable"),
(InvalidAccountIdError, "smart_meter_unavailable"),
],
)
async def test_account_recover_exception(
hass: HomeAssistant,
mock_anglian_water_authenticator: AsyncMock,
mock_anglian_water_client: AsyncMock,
exception_type,
expected_error,
) -> None:
"""Test that the flow can recover from an account related exception."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result is not None
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_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
},
)
mock_anglian_water_client.validate_smart_meter.side_effect = exception_type
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "select_account"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_ACCOUNT_NUMBER: ACCOUNT_NUMBER,
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "select_account"
assert result["errors"] == {"base": expected_error}
# Now test we can recover
mock_anglian_water_client.validate_smart_meter.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_ACCOUNT_NUMBER: ACCOUNT_NUMBER,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == ACCOUNT_NUMBER
assert result["data"][CONF_USERNAME] == USERNAME
assert result["data"][CONF_PASSWORD] == PASSWORD
assert result["data"][CONF_ACCESS_TOKEN] == ACCESS_TOKEN
assert result["data"][CONF_ACCOUNT_NUMBER] == ACCOUNT_NUMBER
assert result["result"].unique_id == ACCOUNT_NUMBER
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/anglian_water/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 223,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/anglian_water/test_sensor.py | """Test Anglian Water sensors."""
from unittest.mock import AsyncMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.recorder import Recorder
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_sensor(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_anglian_water_client: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test sensor platform."""
with patch(
"homeassistant.components.anglian_water._PLATFORMS",
[Platform.SENSOR],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/anglian_water/test_sensor.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/anthropic/test_ai_task.py | """Tests for the Anthropic integration."""
from pathlib import Path
from unittest.mock import AsyncMock, patch
from anthropic.types import Message, TextBlock, Usage
from freezegun import freeze_time
import pytest
from syrupy.assertion import SnapshotAssertion
import voluptuous as vol
from homeassistant.components import ai_task, media_source
from homeassistant.components.anthropic.const import CONF_CHAT_MODEL
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er, selector
from . import create_content_block, create_thinking_block, create_tool_use_block
from tests.common import MockConfigEntry
async def test_generate_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation."""
entity_id = "ai_task.claude_ai_task"
# Ensure entity is linked to the subentry
entity_entry = entity_registry.async_get(entity_id)
ai_task_entry = next(
iter(
entry
for entry in mock_config_entry.subentries.values()
if entry.subentry_type == "ai_task_data"
)
)
assert entity_entry is not None
assert entity_entry.config_entry_id == mock_config_entry.entry_id
assert entity_entry.config_subentry_id == ai_task_entry.subentry_id
mock_create_stream.return_value = [create_content_block(0, ["The test data"])]
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Generate test data",
)
assert result.data == "The test data"
async def test_translation_key(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
entity_registry: er.EntityRegistry,
) -> None:
"""Test entity translation key."""
entry = entity_registry.async_get("ai_task.claude_ai_task")
assert entry is not None
assert entry.translation_key == "ai_task_data"
async def test_empty_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
) -> None:
"""Test AI Task data generation but the data returned is empty."""
mock_create_stream.return_value = [create_content_block(0, [""])]
with pytest.raises(
HomeAssistantError, match="Last content in chat log is not an AssistantContent"
):
await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.claude_ai_task",
instructions="Generate test data",
)
async def test_stream_wrong_type(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
) -> None:
"""Test error if the response is not a stream."""
mock_create_stream.return_value = Message(
type="message",
id="message_id",
model="claude-opus-4-6",
role="assistant",
content=[TextBlock(type="text", text="This is not a stream")],
usage=Usage(input_tokens=42, output_tokens=42),
)
with pytest.raises(HomeAssistantError, match="Expected a stream of messages"):
await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.claude_ai_task",
instructions="Generate test data",
)
@freeze_time("2026-01-01 12:00:00")
async def test_generate_structured_data_legacy(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test AI Task structured data generation with legacy method."""
for subentry in mock_config_entry.subentries.values():
hass.config_entries.async_update_subentry(
mock_config_entry,
subentry,
data={
CONF_CHAT_MODEL: "claude-sonnet-4-0",
},
)
mock_create_stream.return_value = [
create_tool_use_block(
0,
"toolu_0123456789AbCdEfGhIjKlM",
"test_task",
['{"charac', 'ters": ["Mario', '", "Luigi"]}'],
),
]
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.claude_ai_task",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
assert result.data == {"characters": ["Mario", "Luigi"]}
assert mock_create_stream.call_args.kwargs.copy() == snapshot
@freeze_time("2026-01-01 12:00:00")
async def test_generate_structured_data_legacy_tools(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test AI Task structured data generation with legacy method and tools enabled."""
mock_create_stream.return_value = [
create_tool_use_block(
0,
"toolu_0123456789AbCdEfGhIjKlM",
"test_task",
['{"charac', 'ters": ["Mario', '", "Luigi"]}'],
),
]
for subentry in mock_config_entry.subentries.values():
hass.config_entries.async_update_subentry(
mock_config_entry,
subentry,
data={"chat_model": "claude-sonnet-4-0", "web_search": True},
)
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.claude_ai_task",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
assert result.data == {"characters": ["Mario", "Luigi"]}
assert mock_create_stream.call_args.kwargs.copy() == snapshot
@freeze_time("2026-01-01 12:00:00")
async def test_generate_structured_data_legacy_extended_thinking(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test AI Task structured data generation with legacy method and extended_thinking."""
mock_create_stream.return_value = [
(
*create_thinking_block(
0,
["Let's use the tool to respond"],
),
*create_tool_use_block(
1,
"toolu_0123456789AbCdEfGhIjKlM",
"test_task",
['{"charac', 'ters": ["Mario', '", "Luigi"]}'],
),
),
]
for subentry in mock_config_entry.subentries.values():
hass.config_entries.async_update_subentry(
mock_config_entry,
subentry,
data={
"chat_model": "claude-sonnet-4-0",
"thinking_budget": 1500,
},
)
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.claude_ai_task",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
assert result.data == {"characters": ["Mario", "Luigi"]}
assert mock_create_stream.call_args.kwargs.copy() == snapshot
@freeze_time("2026-01-01 12:00:00")
async def test_generate_structured_data_legacy_extra_text_block(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test AI Task structured data generation with legacy method and extra text block."""
mock_create_stream.return_value = [
(
*create_thinking_block(
0,
["Let's use the tool to respond"],
),
*create_content_block(1, ["Sure!"]),
*create_tool_use_block(
2,
"toolu_0123456789AbCdEfGhIjKlM",
"test_task",
['{"charac', 'ters": ["Mario', '", "Luigi"]}'],
),
),
]
for subentry in mock_config_entry.subentries.values():
hass.config_entries.async_update_subentry(
mock_config_entry,
subentry,
data={
"chat_model": "claude-sonnet-4-0",
"thinking_budget": 1500,
},
)
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.claude_ai_task",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
assert result.data == {"characters": ["Mario", "Luigi"]}
assert mock_create_stream.call_args.kwargs.copy() == snapshot
async def test_generate_invalid_structured_data_legacy(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
) -> None:
"""Test AI Task with invalid JSON response with legacy method."""
for subentry in mock_config_entry.subentries.values():
hass.config_entries.async_update_subentry(
mock_config_entry,
subentry,
data={
CONF_CHAT_MODEL: "claude-sonnet-4-0",
},
)
mock_create_stream.return_value = [
create_tool_use_block(
0,
"toolu_0123456789AbCdEfGhIjKlM",
"test_task",
"INVALID JSON RESPONSE",
)
]
with pytest.raises(
HomeAssistantError, match="Error with Claude structured response"
):
await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.claude_ai_task",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
@freeze_time("2026-01-01 12:00:00")
async def test_generate_structured_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test AI Task structured data generation."""
mock_create_stream.return_value = [
create_content_block(0, ['{"charac', 'ters": ["Mario', '", "Luigi"]}'])
]
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.claude_ai_task",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
assert result.data == {"characters": ["Mario", "Luigi"]}
assert mock_create_stream.call_args.kwargs.copy() == snapshot
async def test_generate_data_with_attachments(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation with attachments."""
entity_id = "ai_task.claude_ai_task"
mock_create_stream.return_value = [create_content_block(0, ["Hi there!"])]
# Test with attachments
with (
patch(
"homeassistant.components.media_source.async_resolve_media",
side_effect=[
media_source.PlayMedia(
url="http://example.com/doorbell_snapshot.jpg",
mime_type="image/jpg",
path=Path("doorbell_snapshot.jpg"),
),
media_source.PlayMedia(
url="http://example.com/context.pdf",
mime_type="application/pdf",
path=Path("context.pdf"),
),
],
),
patch("pathlib.Path.exists", return_value=True),
patch("pathlib.Path.read_bytes", return_value=b"fake_image_data"),
):
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Test prompt",
attachments=[
{"media_content_id": "media-source://media/doorbell_snapshot.jpg"},
{"media_content_id": "media-source://media/context.pdf"},
],
)
assert result.data == "Hi there!"
# Verify that the create stream was called with the correct parameters
# The last call should have the user message with attachments
call_args = mock_create_stream.call_args
assert call_args is not None
# Check that the input includes the attachments
input_messages = call_args[1]["messages"]
assert len(input_messages) > 0
# Find the user message with attachments
user_message_with_attachments = input_messages[-2]
assert user_message_with_attachments is not None
assert isinstance(user_message_with_attachments["content"], list)
assert len(user_message_with_attachments["content"]) == 3 # Text + attachments
text_block, image_block, document_block = user_message_with_attachments["content"]
# Text block
assert text_block["type"] == "text"
assert text_block["text"] == "Test prompt"
# Image attachment
assert image_block["type"] == "image"
assert image_block["source"] == {
"data": "ZmFrZV9pbWFnZV9kYXRh",
"media_type": "image/jpeg",
"type": "base64",
}
# Document attachment (ignore extra metadata like cache_control)
assert document_block["type"] == "document"
assert document_block["source"]["data"] == "ZmFrZV9pbWFnZV9kYXRh"
assert document_block["source"]["media_type"] == "application/pdf"
assert document_block["source"]["type"] == "base64"
async def test_generate_data_invalid_attachments(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_init_component,
mock_create_stream: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation with attachments of unsupported type."""
entity_id = "ai_task.claude_ai_task"
mock_create_stream.return_value = [create_content_block(0, ["Hi there!"])]
# Test path that doesn't exist
with (
patch(
"homeassistant.components.media_source.async_resolve_media",
side_effect=[
media_source.PlayMedia(
url="http://example.com/doorbell_snapshot.jpg",
mime_type="image/jpeg",
path=Path("doorbell_snapshot.jpg"),
)
],
),
patch("pathlib.Path.exists", return_value=False),
pytest.raises(
HomeAssistantError, match="`doorbell_snapshot.jpg` does not exist"
),
):
await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Test prompt",
attachments=[
{"media_content_id": "media-source://media/doorbell_snapshot.jpg"},
],
)
# Test unsupported file type
with (
patch(
"homeassistant.components.media_source.async_resolve_media",
side_effect=[
media_source.PlayMedia(
url="http://example.com/doorbell_snapshot.txt",
mime_type=None,
path=Path("doorbell_snapshot.txt"),
)
],
),
patch("pathlib.Path.exists", return_value=True),
patch(
"homeassistant.components.anthropic.entity.guess_file_type",
return_value=("text/plain", None),
),
pytest.raises(
HomeAssistantError,
match="Only images and PDF are supported by the Anthropic API",
),
):
await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Test prompt",
attachments=[
{"media_content_id": "media-source://media/doorbell_snapshot.txt"},
],
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/anthropic/test_ai_task.py",
"license": "Apache License 2.0",
"lines": 492,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/assist_satellite/test_trigger.py | """Test assist satellite triggers."""
from typing import Any
import pytest
from homeassistant.components.assist_satellite.entity import AssistSatelliteState
from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
other_states,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_assist_satellites(hass: HomeAssistant) -> list[str]:
"""Create multiple assist satellite entities associated with different targets."""
return (await target_entities(hass, "assist_satellite"))["included"]
@pytest.mark.parametrize(
"trigger_key",
[
"assist_satellite.idle",
"assist_satellite.listening",
"assist_satellite.processing",
"assist_satellite.responding",
],
)
async def test_assist_satellite_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the Assist satellite triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("assist_satellite"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="assist_satellite.idle",
target_states=[AssistSatelliteState.IDLE],
other_states=other_states(AssistSatelliteState.IDLE),
),
*parametrize_trigger_states(
trigger="assist_satellite.listening",
target_states=[AssistSatelliteState.LISTENING],
other_states=other_states(AssistSatelliteState.LISTENING),
),
*parametrize_trigger_states(
trigger="assist_satellite.processing",
target_states=[AssistSatelliteState.PROCESSING],
other_states=other_states(AssistSatelliteState.PROCESSING),
),
*parametrize_trigger_states(
trigger="assist_satellite.responding",
target_states=[AssistSatelliteState.RESPONDING],
other_states=other_states(AssistSatelliteState.RESPONDING),
),
],
)
async def test_assist_satellite_state_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_assist_satellites: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the assist satellite state trigger fires when any assist satellite state changes to a specific state."""
other_entity_ids = set(target_assist_satellites) - {entity_id}
# Set all assist satellites, including the tested one, to the initial state
for eid in target_assist_satellites:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other assist satellites also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("assist_satellite"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="assist_satellite.idle",
target_states=[AssistSatelliteState.IDLE],
other_states=other_states(AssistSatelliteState.IDLE),
),
*parametrize_trigger_states(
trigger="assist_satellite.listening",
target_states=[AssistSatelliteState.LISTENING],
other_states=other_states(AssistSatelliteState.LISTENING),
),
*parametrize_trigger_states(
trigger="assist_satellite.processing",
target_states=[AssistSatelliteState.PROCESSING],
other_states=other_states(AssistSatelliteState.PROCESSING),
),
*parametrize_trigger_states(
trigger="assist_satellite.responding",
target_states=[AssistSatelliteState.RESPONDING],
other_states=other_states(AssistSatelliteState.RESPONDING),
),
],
)
async def test_assist_satellite_state_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_assist_satellites: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the assist satellite state trigger fires when the first assist satellite changes to a specific state."""
other_entity_ids = set(target_assist_satellites) - {entity_id}
# Set all assist satellites, including the tested one, to the initial state
for eid in target_assist_satellites:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other assist satellites should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("assist_satellite"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="assist_satellite.idle",
target_states=[AssistSatelliteState.IDLE],
other_states=other_states(AssistSatelliteState.IDLE),
),
*parametrize_trigger_states(
trigger="assist_satellite.listening",
target_states=[AssistSatelliteState.LISTENING],
other_states=other_states(AssistSatelliteState.LISTENING),
),
*parametrize_trigger_states(
trigger="assist_satellite.processing",
target_states=[AssistSatelliteState.PROCESSING],
other_states=other_states(AssistSatelliteState.PROCESSING),
),
*parametrize_trigger_states(
trigger="assist_satellite.responding",
target_states=[AssistSatelliteState.RESPONDING],
other_states=other_states(AssistSatelliteState.RESPONDING),
),
],
)
async def test_assist_satellite_state_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_assist_satellites: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the assist_satellite state trigger fires when the last assist_satellite changes to a specific state."""
other_entity_ids = set(target_assist_satellites) - {entity_id}
# Set all assist satellites, including the tested one, to the initial state
for eid in target_assist_satellites:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/assist_satellite/test_trigger.py",
"license": "Apache License 2.0",
"lines": 222,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/backblaze_b2/const.py | """Consts for Backblaze B2 tests."""
from homeassistant.components.backblaze_b2.const import CONF_BUCKET, CONF_PREFIX
from homeassistant.components.backup import AgentBackup
USER_INPUT = {
CONF_BUCKET: "testBucket",
CONF_PREFIX: "testprefix/",
}
TEST_BACKUP = AgentBackup(
addons=[],
backup_id="23e64aec",
date="2024-11-22T11:48:48.727189+01:00",
database_included=True,
extra_metadata={},
folders=[],
homeassistant_included=True,
homeassistant_version="2024.12.0.dev0",
name="Core 2024.12.0.dev0",
protected=False,
size=48,
)
BACKUP_METADATA = {
"metadata_version": "1",
"backup_id": "23e64aec",
"backup_metadata": TEST_BACKUP.as_dict(),
}
METADATA_FILE_SUFFIX = ".metadata.json"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/backblaze_b2/const.py",
"license": "Apache License 2.0",
"lines": 26,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/backblaze_b2/test_backup.py | """Backblaze B2 backup agent tests."""
import asyncio
from collections.abc import AsyncGenerator
from io import StringIO
import json
import logging
import threading
import time
from unittest.mock import Mock, patch
from b2sdk._internal.raw_simulator import BucketSimulator
from b2sdk.v2.exception import B2Error
import pytest
from homeassistant.components.backblaze_b2.backup import (
_parse_metadata,
async_register_backup_agents_listener,
)
from homeassistant.components.backblaze_b2.const import (
DATA_BACKUP_AGENT_LISTENERS,
DOMAIN,
)
from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import setup_integration
from .const import BACKUP_METADATA, TEST_BACKUP
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 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
@pytest.fixture
def mock_backup_files():
"""Create standard mock backup file and metadata file."""
mock_main = Mock()
mock_main.file_name = f"testprefix/{TEST_BACKUP.backup_id}.tar"
mock_main.size = TEST_BACKUP.size
mock_main.delete = Mock()
mock_metadata = Mock()
mock_metadata.file_name = f"testprefix/{TEST_BACKUP.backup_id}.metadata.json"
mock_metadata.size = 100
mock_download = Mock()
mock_response = Mock()
mock_response.content = json.dumps(BACKUP_METADATA).encode()
mock_download.response = mock_response
mock_metadata.download = Mock(return_value=mock_download)
mock_metadata.delete = Mock()
return mock_main, mock_metadata
async def test_agents_info(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test 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 any(
agent["agent_id"] == f"{DOMAIN}.{mock_config_entry.entry_id}"
for agent in response["result"]["agents"]
)
async def test_agents_list_backups(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test listing 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 "backups" in response["result"]
async def test_agents_get_backup(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test getting 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"]
if response["result"]["backup"]:
assert response["result"]["backup"]["backup_id"] == TEST_BACKUP.backup_id
async def test_agents_get_backup_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test getting nonexistent backup."""
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"]["backup"] is None
async def test_agents_delete(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_backup_files,
) -> None:
"""Test deleting backup."""
client = await hass_ws_client(hass)
mock_main, mock_metadata = mock_backup_files
def mock_ls(_self, _prefix=""):
return iter([(mock_main, None), (mock_metadata, None)])
with patch.object(BucketSimulator, "ls", mock_ls):
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": {}}
mock_main.delete.assert_called_once()
mock_metadata.delete.assert_called_once()
async def test_agents_delete_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test deleting nonexistent backup."""
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": {}}
async def test_agents_download(
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test downloading backup."""
client = await hass_client()
resp = await client.get(
f"/api/backup/download/{TEST_BACKUP.backup_id}?agent_id={DOMAIN}.{mock_config_entry.entry_id}"
)
assert resp.status == 200
async def test_agents_download_not_found(
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test downloading nonexistent backup."""
client = await hass_client()
resp = await client.get(
f"/api/backup/download/nonexistent?agent_id={DOMAIN}.{mock_config_entry.entry_id}"
)
assert resp.status == 404
async def test_get_file_for_download_raises_not_found(
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test exception handling for nonexistent backup."""
client = await hass_client()
def mock_ls_empty(_self, _prefix=""):
return iter([])
with patch.object(BucketSimulator, "ls", mock_ls_empty):
resp = await client.get(
f"/api/backup/download/nonexistent?agent_id={DOMAIN}.{mock_config_entry.entry_id}"
)
assert resp.status == 404
@pytest.mark.parametrize(
("error_type", "exception"),
[
("b2_error", B2Error),
("runtime_error", RuntimeError),
],
)
async def test_error_during_delete(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
mock_backup_files,
error_type: str,
exception: type[Exception],
) -> None:
"""Test error handling during deletion."""
client = await hass_ws_client(hass)
mock_main, mock_metadata = mock_backup_files
mock_metadata.delete = Mock(side_effect=exception("Delete failed"))
def mock_ls(_self, _prefix=""):
return iter([(mock_main, None), (mock_metadata, None)])
with patch.object(BucketSimulator, "ls", mock_ls):
await client.send_json_auto_id(
{"type": "backup/delete", "backup_id": TEST_BACKUP.backup_id}
)
response = await client.receive_json()
assert response["success"]
assert (
f"{DOMAIN}.{mock_config_entry.entry_id}" in response["result"]["agent_errors"]
)
async def test_listeners_get_cleaned_up(hass: HomeAssistant) -> None:
"""Test listener cleanup."""
listener = MagicMock()
remove_listener = async_register_backup_agents_listener(hass, listener=listener)
hass.data[DATA_BACKUP_AGENT_LISTENERS] = [listener] # type: ignore[misc]
remove_listener()
assert DATA_BACKUP_AGENT_LISTENERS not in hass.data
async def test_parse_metadata_invalid_json() -> None:
"""Test metadata parsing."""
with pytest.raises(ValueError, match="Invalid JSON format"):
_parse_metadata("invalid json")
with pytest.raises(TypeError, match="JSON content is not a dictionary"):
_parse_metadata('["not", "a", "dict"]')
async def test_error_during_list_backups(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test error handling during list."""
client = await hass_ws_client(hass)
def mock_ls_error(_self, _prefix=""):
raise B2Error("API error")
with patch.object(BucketSimulator, "ls", mock_ls_error):
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
assert (
f"{DOMAIN}.{mock_config_entry.entry_id}" in response["result"]["agent_errors"]
)
async def test_error_during_get_backup(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test error handling during get."""
client = await hass_ws_client(hass)
def mock_ls_error(_self, _prefix=""):
raise B2Error("API error")
with patch.object(BucketSimulator, "ls", mock_ls_error):
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": "test_backup"}
)
response = await client.receive_json()
assert response["success"]
assert (
f"{DOMAIN}.{mock_config_entry.entry_id}" in response["result"]["agent_errors"]
)
async def test_metadata_file_download_error_during_list(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test metadata download error handling."""
client = await hass_ws_client(hass)
mock_metadata = Mock()
mock_metadata.file_name = "testprefix/test.metadata.json"
mock_metadata.download = Mock(side_effect=B2Error("Download failed"))
mock_tar = Mock()
mock_tar.file_name = "testprefix/test.tar"
def mock_ls(_self, _prefix=""):
return iter([(mock_metadata, None), (mock_tar, None)])
with patch.object(BucketSimulator, "ls", mock_ls):
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
async def test_delete_with_metadata_error(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
mock_backup_files,
) -> None:
"""Test error handling during metadata deletion."""
client = await hass_ws_client(hass)
mock_main, mock_metadata = mock_backup_files
mock_metadata.delete = Mock(side_effect=B2Error("Delete failed"))
def mock_ls(_self, _prefix=""):
return iter([(mock_main, None), (mock_metadata, None)])
with patch.object(BucketSimulator, "ls", mock_ls):
await client.send_json_auto_id(
{"type": "backup/delete", "backup_id": TEST_BACKUP.backup_id}
)
response = await client.receive_json()
assert response["success"]
assert (
f"{DOMAIN}.{mock_config_entry.entry_id}" in response["result"]["agent_errors"]
)
mock_main.delete.assert_called_once()
mock_metadata.delete.assert_called_once()
async def test_download_backup_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test downloading nonexistent backup."""
client = await hass_ws_client(hass)
def mock_ls_empty(_self, _prefix=""):
return iter([])
with patch.object(BucketSimulator, "ls", mock_ls_empty):
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": "nonexistent"}
)
response = await client.receive_json()
assert response["success"]
assert response["result"]["backup"] is None
async def test_metadata_file_invalid_json_during_list(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test invalid metadata handling."""
client = await hass_ws_client(hass)
mock_metadata = Mock()
mock_metadata.file_name = "testprefix/bad.metadata.json"
mock_download = Mock()
mock_response = Mock()
mock_response.content = b"not valid json"
mock_download.response = mock_response
mock_metadata.download = Mock(return_value=mock_download)
mock_tar = Mock()
mock_tar.file_name = "testprefix/bad.tar"
def mock_ls(_self, _prefix=""):
return iter([(mock_metadata, None), (mock_tar, None)])
with (
patch.object(BucketSimulator, "ls", mock_ls),
caplog.at_level(logging.WARNING),
):
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
async def test_upload_with_cleanup_and_logging(
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test upload logging and cleanup."""
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,
caplog.at_level(logging.DEBUG),
):
mocked_open.return_value.read = Mock(side_effect=[b"test", 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 any("Main backup file upload finished" in msg for msg in caplog.messages)
assert any("Metadata file upload finished" in msg for msg in caplog.messages)
assert any("Backup upload complete" in msg for msg in caplog.messages)
caplog.clear()
mock_file_info = Mock()
mock_file_info.delete = Mock()
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,
patch.object(
BucketSimulator,
"upload_bytes",
side_effect=B2Error("Metadata upload failed"),
),
patch.object(
BucketSimulator, "get_file_info_by_name", return_value=mock_file_info
),
caplog.at_level(logging.DEBUG),
):
mocked_open.return_value.read = Mock(side_effect=[b"test", 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
mock_file_info.delete.assert_called_once()
assert any(
"Successfully deleted partially uploaded" in msg for msg in caplog.messages
)
async def test_upload_with_cleanup_failure(
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test upload with cleanup failure when metadata upload fails."""
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,
patch.object(
BucketSimulator,
"upload_bytes",
side_effect=B2Error("Metadata upload failed"),
),
patch.object(
BucketSimulator,
"get_file_info_by_name",
side_effect=B2Error("Cleanup failed"),
),
caplog.at_level(logging.DEBUG),
):
mocked_open.return_value.read = Mock(side_effect=[b"test", 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 any(
"Failed to clean up partially uploaded main backup file" in msg
for msg in caplog.messages
)
async def test_cache_behavior(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test backup list caching."""
client = await hass_ws_client(hass)
call_count = []
original_ls = BucketSimulator.ls
def ls_with_counter(self, prefix=""):
call_count.append(1)
return original_ls(self, prefix)
with patch.object(BucketSimulator, "ls", ls_with_counter):
await client.send_json_auto_id({"type": "backup/info"})
response1 = await client.receive_json()
assert response1["success"]
first_call_count = len(call_count)
assert first_call_count > 0
await client.send_json_auto_id({"type": "backup/info"})
response2 = await client.receive_json()
assert response2["success"]
assert len(call_count) == first_call_count
assert response1["result"]["backups"] == response2["result"]["backups"]
async def test_metadata_processing_errors(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test metadata error handling."""
client = await hass_ws_client(hass)
mock_metadata = Mock()
mock_metadata.file_name = "testprefix/test.metadata.json"
mock_metadata.download = Mock(side_effect=B2Error("Download failed"))
mock_tar = Mock()
mock_tar.file_name = "testprefix/test.tar"
def mock_ls_download_error(_self, _prefix=""):
return iter([(mock_metadata, None), (mock_tar, None)])
with (
patch.object(BucketSimulator, "ls", mock_ls_download_error),
caplog.at_level(logging.WARNING),
):
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
assert "backups" in response["result"]
caplog.clear()
mock_metadata3 = Mock()
mock_metadata3.file_name = f"testprefix/{TEST_BACKUP.backup_id}.metadata.json"
mock_metadata3.download = Mock(side_effect=B2Error("Download failed"))
mock_tar3 = Mock()
mock_tar3.file_name = f"testprefix/{TEST_BACKUP.backup_id}.tar"
def mock_ls_id_error(_self, _prefix=""):
return iter([(mock_metadata3, None), (mock_tar3, None)])
with patch.object(BucketSimulator, "ls", mock_ls_id_error):
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"]["backup"] is None
caplog.clear()
mock_metadata4 = Mock()
mock_metadata4.file_name = f"testprefix/{TEST_BACKUP.backup_id}.metadata.json"
mock_download4 = Mock()
mock_response4 = Mock()
mock_response4.content = b"invalid json"
mock_download4.response = mock_response4
mock_metadata4.download = Mock(return_value=mock_download4)
mock_tar4 = Mock()
mock_tar4.file_name = f"testprefix/{TEST_BACKUP.backup_id}.tar"
def mock_ls_invalid_json(_self, _prefix=""):
return iter([(mock_metadata4, None), (mock_tar4, None)])
with patch.object(BucketSimulator, "ls", mock_ls_invalid_json):
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"]["backup"] is None
async def test_download_triggers_backup_not_found(
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
mock_backup_files,
) -> None:
"""Test race condition where backup disappears during download."""
client = await hass_client()
mock_main, mock_metadata = mock_backup_files
ls_call_count = [0]
def mock_ls_race_condition(_self, _prefix=""):
ls_call_count[0] += 1
if ls_call_count[0] == 1:
return iter([(mock_main, None), (mock_metadata, None)])
return iter([])
with (
patch.object(BucketSimulator, "ls", mock_ls_race_condition),
patch("homeassistant.components.backblaze_b2.backup.CACHE_TTL", 0),
):
resp = await client.get(
f"/api/backup/download/{TEST_BACKUP.backup_id}?agent_id={DOMAIN}.{mock_config_entry.entry_id}"
)
assert resp.status == 404
async def test_get_backup_cache_paths(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test cache hit and update paths."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/info"})
response1 = await client.receive_json()
assert response1["success"]
assert len(response1["result"]["backups"]) > 0
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": TEST_BACKUP.backup_id}
)
response2 = await client.receive_json()
assert response2["success"]
assert response2["result"]["backup"]["backup_id"] == TEST_BACKUP.backup_id
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": TEST_BACKUP.backup_id}
)
response3 = await client.receive_json()
assert response3["success"]
assert response3["result"]["backup"]["backup_id"] == TEST_BACKUP.backup_id
async def test_metadata_json_parse_error(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test ValueError handling when metadata JSON parsing fails."""
client = await hass_ws_client(hass)
mock_metadata = Mock()
mock_metadata.file_name = f"testprefix/{TEST_BACKUP.backup_id}.metadata.json"
mock_download = Mock()
mock_response = Mock()
mock_response.content = b"{ invalid json }"
mock_download.response = mock_response
mock_metadata.download = Mock(return_value=mock_download)
mock_tar = Mock()
mock_tar.file_name = f"testprefix/{TEST_BACKUP.backup_id}.tar"
def mock_ls(_self, _prefix=""):
return iter([(mock_metadata, None), (mock_tar, None)])
with patch.object(BucketSimulator, "ls", mock_ls):
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"]["backup"] is None
async def test_orphaned_metadata_files(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test handling of metadata files without corresponding tar files."""
client = await hass_ws_client(hass)
mock_metadata = Mock()
mock_metadata.file_name = f"testprefix/{TEST_BACKUP.backup_id}.metadata.json"
mock_download = Mock()
mock_response = Mock()
mock_response.content = json.dumps(BACKUP_METADATA).encode()
mock_download.response = mock_response
mock_metadata.download = Mock(return_value=mock_download)
def mock_ls(_self, _prefix=""):
return iter([(mock_metadata, None)])
with (
patch.object(BucketSimulator, "ls", mock_ls),
caplog.at_level(logging.WARNING),
):
await client.send_json_auto_id({"type": "backup/info"})
response1 = await client.receive_json()
assert response1["success"]
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": TEST_BACKUP.backup_id}
)
response2 = await client.receive_json()
assert response2["success"]
assert response2["result"]["backup"] is None
assert any(
"no corresponding backup file" in record.message for record in caplog.records
)
async def test_get_backup_updates_cache(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_backup_files,
) -> None:
"""Test cache update when metadata initially fails then succeeds."""
client = await hass_ws_client(hass)
mock_main, mock_metadata = mock_backup_files
download_call_count = [0]
def mock_download():
download_call_count[0] += 1
mock_download_obj = Mock()
mock_response = Mock()
if download_call_count[0] == 1:
mock_response.content = b"{ invalid json }"
else:
mock_response.content = json.dumps(BACKUP_METADATA).encode()
mock_download_obj.response = mock_response
return mock_download_obj
mock_metadata.download = mock_download
def mock_ls(_self, _prefix=""):
return iter([(mock_main, None), (mock_metadata, None)])
with patch.object(BucketSimulator, "ls", mock_ls):
await client.send_json_auto_id({"type": "backup/info"})
response1 = await client.receive_json()
assert response1["success"]
assert len(response1["result"]["backups"]) == 0
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": TEST_BACKUP.backup_id}
)
response2 = await client.receive_json()
assert response2["success"]
assert response2["result"]["backup"]["backup_id"] == TEST_BACKUP.backup_id
async def test_delete_clears_backup_cache(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_backup_files,
) -> None:
"""Test that deleting a backup clears it from cache."""
client = await hass_ws_client(hass)
mock_main, mock_metadata = mock_backup_files
def mock_ls(_self, _prefix=""):
return iter([(mock_main, None), (mock_metadata, None)])
with patch.object(BucketSimulator, "ls", mock_ls):
await client.send_json_auto_id({"type": "backup/info"})
response1 = await client.receive_json()
assert response1["success"]
assert len(response1["result"]["backups"]) > 0
await client.send_json_auto_id(
{"type": "backup/delete", "backup_id": TEST_BACKUP.backup_id}
)
response2 = await client.receive_json()
assert response2["success"]
mock_main.delete.assert_called_once()
mock_metadata.delete.assert_called_once()
async def test_metadata_downloads_are_sequential(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that metadata downloads are processed sequentially to avoid exhausting executor pool."""
current_concurrent = 0
max_concurrent = 0
lock = threading.Lock()
def mock_download_sync():
nonlocal current_concurrent, max_concurrent
with lock:
current_concurrent += 1
max_concurrent = max(max_concurrent, current_concurrent)
time.sleep(0.05)
with lock:
current_concurrent -= 1
mock_download_obj = Mock()
mock_response = Mock()
mock_response.content = json.dumps(BACKUP_METADATA).encode()
mock_download_obj.response = mock_response
return mock_download_obj
mock_files = []
for i in range(15):
mock_metadata = Mock()
mock_metadata.file_name = f"testprefix/backup{i}.metadata.json"
mock_metadata.download = mock_download_sync
mock_tar = Mock()
mock_tar.file_name = f"testprefix/backup{i}.tar"
mock_tar.size = TEST_BACKUP.size
mock_files.extend([(mock_metadata, None), (mock_tar, None)])
def mock_ls(_self, _prefix=""):
return iter(mock_files)
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
with patch.object(BucketSimulator, "ls", mock_ls):
await setup_integration(hass, mock_config_entry)
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
# Verify downloads were sequential (max 1 at a time)
assert max_concurrent == 1
async def test_upload_timeout(
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test upload timeout handling."""
client = await hass_client()
mock_file_info = Mock()
mock_file_info.delete = Mock()
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,
patch(
"homeassistant.components.backblaze_b2.backup.BackblazeBackupAgent._upload_unbound_stream_sync",
),
patch(
"homeassistant.components.backblaze_b2.backup.asyncio.wait_for",
side_effect=TimeoutError,
),
patch.object(
BucketSimulator,
"get_file_info_by_name",
return_value=mock_file_info,
),
caplog.at_level(logging.ERROR),
):
mocked_open.return_value.read = Mock(side_effect=[b"test", 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 any("timed out" in msg for msg in caplog.messages)
async def test_upload_cancelled(
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test upload cancellation handling."""
client = await hass_client()
mock_file_info = Mock()
mock_file_info.delete = Mock()
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,
patch(
"homeassistant.components.backblaze_b2.backup.BackblazeBackupAgent._upload_unbound_stream_sync",
),
patch(
"homeassistant.components.backblaze_b2.backup.asyncio.wait_for",
side_effect=asyncio.CancelledError,
),
patch.object(
BucketSimulator,
"get_file_info_by_name",
return_value=mock_file_info,
),
caplog.at_level(logging.WARNING),
):
mocked_open.return_value.read = Mock(side_effect=[b"test", b""])
resp = await client.post(
f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.entry_id}",
data={"file": StringIO("test")},
)
# CancelledError propagates up and causes a 500 error
assert resp.status == 500
assert any("cancelled" in msg for msg in caplog.messages)
async def test_metadata_download_timeout_during_list(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that metadata download timeout during list is handled gracefully."""
client = await hass_ws_client(hass)
mock_metadata = Mock()
mock_metadata.file_name = "testprefix/slow.metadata.json"
mock_tar = Mock()
mock_tar.file_name = "testprefix/slow.tar"
mock_tar.size = TEST_BACKUP.size
def mock_ls(_self, _prefix=""):
return iter([(mock_metadata, None), (mock_tar, None)])
with (
patch.object(BucketSimulator, "ls", mock_ls),
patch(
"homeassistant.components.backblaze_b2.backup.asyncio.wait_for",
side_effect=TimeoutError,
),
caplog.at_level(logging.WARNING),
):
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
# The backup should not appear in the list due to timeout
assert len(response["result"]["backups"]) == 0
assert any("Timeout downloading metadata file" in msg for msg in caplog.messages)
async def test_metadata_download_timeout_during_find_by_id(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that metadata download timeout during find by ID is handled gracefully."""
client = await hass_ws_client(hass)
mock_metadata = Mock()
mock_metadata.file_name = f"testprefix/{TEST_BACKUP.backup_id}.metadata.json"
mock_tar = Mock()
mock_tar.file_name = f"testprefix/{TEST_BACKUP.backup_id}.tar"
mock_tar.size = TEST_BACKUP.size
def mock_ls(_self, _prefix=""):
return iter([(mock_metadata, None), (mock_tar, None)])
with (
patch.object(BucketSimulator, "ls", mock_ls),
patch(
"homeassistant.components.backblaze_b2.backup.asyncio.wait_for",
side_effect=TimeoutError,
),
caplog.at_level(logging.WARNING),
):
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": TEST_BACKUP.backup_id}
)
response = await client.receive_json()
assert response["success"]
# The backup should not be found due to timeout
assert response["result"]["backup"] is None
assert any(
"Timeout downloading metadata file" in msg
and "while searching for backup" in msg
for msg in caplog.messages
)
async def test_metadata_timeout_does_not_block_healthy_backups(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that a timed out metadata download doesn't prevent listing other backups."""
client = await hass_ws_client(hass)
mock_hanging_metadata = Mock()
mock_hanging_metadata.file_name = "testprefix/hanging_backup.metadata.json"
mock_hanging_metadata.download = Mock(side_effect=B2Error("SSL failure"))
mock_hanging_tar = Mock()
mock_hanging_tar.file_name = "testprefix/hanging_backup.tar"
mock_hanging_tar.size = 1000
mock_healthy_metadata = Mock()
mock_healthy_metadata.file_name = (
f"testprefix/{TEST_BACKUP.backup_id}.metadata.json"
)
mock_healthy_download = Mock()
mock_healthy_response = Mock()
mock_healthy_response.content = json.dumps(BACKUP_METADATA).encode()
mock_healthy_download.response = mock_healthy_response
mock_healthy_metadata.download = Mock(return_value=mock_healthy_download)
mock_healthy_tar = Mock()
mock_healthy_tar.file_name = f"testprefix/{TEST_BACKUP.backup_id}.tar"
mock_healthy_tar.size = TEST_BACKUP.size
def mock_ls(_self, _prefix=""):
return iter(
[
(mock_hanging_metadata, None),
(mock_hanging_tar, None),
(mock_healthy_metadata, None),
(mock_healthy_tar, None),
]
)
call_count = 0
original_wait_for = asyncio.wait_for
async def wait_for_first_timeout(coro, *, timeout=None):
nonlocal call_count
call_count += 1
if call_count == 1:
raise TimeoutError
return await original_wait_for(coro, timeout=timeout)
with (
patch.object(BucketSimulator, "ls", mock_ls),
patch(
"homeassistant.components.backblaze_b2.backup.asyncio.wait_for",
wait_for_first_timeout,
),
caplog.at_level(logging.WARNING),
):
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
backups = response["result"]["backups"]
assert len(backups) == 1
assert backups[0]["backup_id"] == TEST_BACKUP.backup_id
assert any("Timeout downloading metadata file" in msg for msg in caplog.messages)
async def test_metadata_download_timeout_during_get_backup(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test timeout on metadata re-download after file is found."""
client = await hass_ws_client(hass)
mock_metadata = Mock()
mock_metadata.file_name = f"testprefix/{TEST_BACKUP.backup_id}.metadata.json"
mock_download = Mock()
mock_response = Mock()
mock_response.content = json.dumps(BACKUP_METADATA).encode()
mock_download.response = mock_response
mock_metadata.download = Mock(return_value=mock_download)
mock_tar = Mock()
mock_tar.file_name = f"testprefix/{TEST_BACKUP.backup_id}.tar"
mock_tar.size = TEST_BACKUP.size
def mock_ls(_self, _prefix=""):
return iter([(mock_metadata, None), (mock_tar, None)])
call_count = 0
original_wait_for = asyncio.wait_for
async def wait_for_second_timeout(coro, *, timeout=None):
nonlocal call_count
call_count += 1
if call_count >= 2:
raise TimeoutError
return await original_wait_for(coro, timeout=timeout)
with (
patch.object(BucketSimulator, "ls", mock_ls),
patch(
"homeassistant.components.backblaze_b2.backup.asyncio.wait_for",
wait_for_second_timeout,
),
patch("homeassistant.components.backblaze_b2.backup.CACHE_TTL", 0),
):
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": TEST_BACKUP.backup_id}
)
response = await client.receive_json()
assert response["success"]
assert (
f"{DOMAIN}.{mock_config_entry.entry_id}" in response["result"]["agent_errors"]
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/backblaze_b2/test_backup.py",
"license": "Apache License 2.0",
"lines": 944,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/backblaze_b2/test_config_flow.py | """Backblaze B2 config flow tests."""
from unittest.mock import patch
from b2sdk.v2 import exception
import pytest
from homeassistant.components.backblaze_b2.const import (
CONF_APPLICATION_KEY,
CONF_KEY_ID,
DOMAIN,
)
from homeassistant.config_entries import (
SOURCE_REAUTH,
SOURCE_RECONFIGURE,
SOURCE_USER,
ConfigFlowResult,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import BackblazeFixture
from .const import USER_INPUT
from tests.common import MockConfigEntry
async def _async_start_flow(
hass: HomeAssistant,
key_id: str,
application_key: str,
user_input: dict[str, str] | None = None,
) -> ConfigFlowResult:
"""Initialize the config flow."""
if user_input is None:
user_input = USER_INPUT
user_input[CONF_KEY_ID] = key_id
user_input[CONF_APPLICATION_KEY] = application_key
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "user"
assert result.get("errors") == {}
return await hass.config_entries.flow.async_configure(result["flow_id"], user_input)
async def test_basic_flows(hass: HomeAssistant, b2_fixture: BackblazeFixture) -> None:
"""Test basic successful config flows."""
result = await _async_start_flow(
hass, b2_fixture.key_id, b2_fixture.application_key
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result.get("title") == "testBucket"
assert result.get("data") == USER_INPUT
async def test_prefix_normalization(
hass: HomeAssistant, b2_fixture: BackblazeFixture
) -> None:
"""Test prefix normalization in config flow."""
user_input = {**USER_INPUT, "prefix": "test-prefix/foo"}
result = await _async_start_flow(
hass, b2_fixture.key_id, b2_fixture.application_key, user_input
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result["data"]["prefix"] == "test-prefix/foo/"
async def test_empty_prefix(hass: HomeAssistant, b2_fixture: BackblazeFixture) -> None:
"""Test empty prefix handling."""
user_input_empty = {**USER_INPUT, "prefix": ""}
result = await _async_start_flow(
hass, b2_fixture.key_id, b2_fixture.application_key, user_input_empty
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result["data"]["prefix"] == ""
async def test_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
b2_fixture: BackblazeFixture,
) -> None:
"""Test abort if already configured."""
mock_config_entry.add_to_hass(hass)
result = await _async_start_flow(
hass, b2_fixture.key_id, b2_fixture.application_key
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "already_configured"
@pytest.mark.parametrize(
("error_type", "setup", "expected_error", "expected_field"),
[
(
"invalid_auth",
{"key_id": "invalid", "app_key": "invalid"},
"invalid_credentials",
"base",
),
(
"invalid_bucket",
{"bucket": "invalid-bucket-name"},
"invalid_bucket_name",
"bucket",
),
(
"cannot_connect",
{
"patch": "b2sdk.v2.RawSimulator.authorize_account",
"exception": exception.ConnectionReset,
"args": ["test"],
},
"cannot_connect",
"base",
),
(
"restricted_bucket",
{
"patch": "b2sdk.v2.RawSimulator.get_bucket_by_name",
"exception": exception.RestrictedBucket,
"args": ["testBucket"],
},
"restricted_bucket",
"bucket",
),
(
"missing_account_data",
{
"patch": "b2sdk.v2.RawSimulator.authorize_account",
"exception": exception.MissingAccountData,
"args": ["key"],
},
"invalid_credentials",
"base",
),
(
"invalid_capability",
{"mock_capabilities": ["writeFiles", "listFiles", "deleteFiles"]},
"invalid_capability",
"base",
),
(
"no_allowed_info",
{"mock_allowed": None},
"invalid_capability",
"base",
),
(
"no_capabilities",
{"mock_allowed": {}},
"invalid_capability",
"base",
),
("invalid_prefix", {"mock_prefix": "test/"}, "invalid_prefix", "prefix"),
(
"connection_error",
{
"patch": "b2sdk.v2.RawSimulator.authorize_account",
"exception": exception.B2ConnectionError,
"args": ["Connection error"],
},
"cannot_connect",
"base",
),
(
"timeout_error",
{
"patch": "b2sdk.v2.RawSimulator.authorize_account",
"exception": exception.B2RequestTimeout,
"args": ["Request timed out"],
},
"cannot_connect",
"base",
),
(
"unknown_error",
{
"patch": "b2sdk.v2.RawSimulator.authorize_account",
"exception": RuntimeError,
"args": ["Unexpected error"],
},
"unknown",
"base",
),
],
)
async def test_config_flow_errors(
hass: HomeAssistant,
b2_fixture: BackblazeFixture,
error_type: str,
setup: dict,
expected_error: str,
expected_field: str,
) -> None:
"""Test various config flow error scenarios."""
if error_type == "invalid_auth":
result = await _async_start_flow(hass, setup["key_id"], setup["app_key"])
elif error_type == "invalid_bucket":
invalid_input = {**USER_INPUT, "bucket": setup["bucket"]}
result = await _async_start_flow(
hass, b2_fixture.key_id, b2_fixture.application_key, invalid_input
)
elif "patch" in setup:
with patch(setup["patch"], side_effect=setup["exception"](*setup["args"])):
result = await _async_start_flow(
hass, b2_fixture.key_id, b2_fixture.application_key
)
elif "mock_capabilities" in setup:
with patch(
"b2sdk.v2.RawSimulator.account_info.get_allowed",
return_value={"capabilities": setup["mock_capabilities"]},
):
result = await _async_start_flow(
hass, b2_fixture.key_id, b2_fixture.application_key
)
elif "mock_allowed" in setup:
with patch(
"b2sdk.v2.RawSimulator.account_info.get_allowed",
return_value=setup["mock_allowed"],
):
result = await _async_start_flow(
hass, b2_fixture.key_id, b2_fixture.application_key
)
elif "mock_prefix" in setup:
with patch(
"b2sdk.v2.RawSimulator.account_info.get_allowed",
return_value={
"capabilities": ["writeFiles", "listFiles", "deleteFiles", "readFiles"],
"namePrefix": setup["mock_prefix"],
},
):
result = await _async_start_flow(
hass, b2_fixture.key_id, b2_fixture.application_key
)
assert result.get("type") is FlowResultType.FORM
assert result.get("errors") == {expected_field: expected_error}
if error_type == "restricted_bucket":
assert result.get("description_placeholders") == {
"brand_name": "Backblaze B2",
"restricted_bucket_name": "testBucket",
}
elif error_type == "invalid_prefix":
assert result.get("description_placeholders") == {
"brand_name": "Backblaze B2",
"allowed_prefix": "test/",
}
@pytest.mark.parametrize(
("flow_type", "scenario"),
[
("reauth", "success"),
("reauth", "invalid_credentials"),
("reconfigure", "success"),
("reconfigure", "prefix_normalization"),
("reconfigure", "validation_error"),
],
)
async def test_advanced_flows(
hass: HomeAssistant,
b2_fixture: BackblazeFixture,
mock_config_entry: MockConfigEntry,
flow_type: str,
scenario: str,
) -> None:
"""Test reauthentication and reconfiguration flows."""
mock_config_entry.add_to_hass(hass)
if flow_type == "reauth":
source = SOURCE_REAUTH
step_name = "reauth_confirm"
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": source, "entry_id": mock_config_entry.entry_id},
)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == step_name
if scenario == "success":
config = {
CONF_KEY_ID: b2_fixture.key_id,
CONF_APPLICATION_KEY: b2_fixture.application_key,
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], config
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reauth_successful"
else: # invalid_credentials
config = {CONF_KEY_ID: "invalid", CONF_APPLICATION_KEY: "invalid"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], config
)
assert result.get("type") is FlowResultType.FORM
assert result.get("errors") == {"base": "invalid_credentials"}
elif flow_type == "reconfigure":
source = SOURCE_RECONFIGURE
step_name = "reconfigure"
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": source, "entry_id": mock_config_entry.entry_id},
)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == step_name
if scenario == "success":
config = {
CONF_KEY_ID: b2_fixture.key_id,
CONF_APPLICATION_KEY: b2_fixture.application_key,
"bucket": "testBucket",
"prefix": "new_prefix/",
}
elif scenario == "prefix_normalization":
config = {
CONF_KEY_ID: b2_fixture.key_id,
CONF_APPLICATION_KEY: b2_fixture.application_key,
"bucket": "testBucket",
"prefix": "no_slash_prefix",
}
else: # validation_error
config = {
CONF_KEY_ID: "invalid_key",
CONF_APPLICATION_KEY: "invalid_app_key",
"bucket": "invalid_bucket",
"prefix": "",
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], config
)
if scenario == "validation_error":
assert result.get("type") is FlowResultType.FORM
assert result.get("errors") == {"base": "invalid_credentials"}
else:
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reconfigure_successful"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/backblaze_b2/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 316,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/backblaze_b2/test_diagnostics.py | """Test Backblaze B2 diagnostics."""
from unittest.mock import Mock, patch
from homeassistant.components.backblaze_b2.diagnostics import (
async_get_config_entry_diagnostics,
)
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
async def test_diagnostics_basic(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test basic diagnostics data collection."""
await setup_integration(hass, mock_config_entry)
result = await async_get_config_entry_diagnostics(hass, mock_config_entry)
assert "entry_data" in result
assert "entry_options" in result
assert "bucket_info" in result
assert "account_info" in result
# Check that sensitive data is redacted
assert mock_config_entry.data["key_id"] not in str(result["entry_data"])
assert mock_config_entry.data["application_key"] not in str(result["entry_data"])
async def test_diagnostics_error_handling(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test diagnostics handles errors gracefully."""
mock_config_entry.runtime_data = None
mock_config_entry.add_to_hass(hass)
result = await async_get_config_entry_diagnostics(hass, mock_config_entry)
assert "bucket_info" in result
assert "account_info" in result
async def test_diagnostics_bucket_data_redaction(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test diagnostics redacts bucket-specific sensitive data."""
await setup_integration(hass, mock_config_entry)
mock_bucket = Mock()
mock_bucket.name = "test-bucket"
mock_bucket.id_ = "bucket_id_123"
mock_bucket.type_ = "allPrivate"
mock_bucket.cors_rules = []
mock_bucket.lifecycle_rules = []
mock_bucket.revision = 1
mock_api = Mock()
mock_account_info = Mock()
mock_account_info.get_account_id.return_value = "account123"
mock_account_info.get_api_url.return_value = "https://api.backblazeb2.com"
mock_account_info.get_download_url.return_value = "https://f001.backblazeb2.com"
mock_account_info.get_minimum_part_size.return_value = 5000000
mock_account_info.get_allowed.return_value = {
"capabilities": ["writeFiles", "listFiles", "readFiles"],
"bucketId": "test_bucket_id_123",
"bucketName": "restricted_bucket",
"namePrefix": "restricted/path/",
}
mock_bucket.api = mock_api
mock_api.account_info = mock_account_info
with patch.object(mock_config_entry, "runtime_data", mock_bucket):
result = await async_get_config_entry_diagnostics(hass, mock_config_entry)
account_data = result["account_info"]
assert account_data["allowed"]["capabilities"] == [
"writeFiles",
"listFiles",
"readFiles",
]
assert account_data["allowed"]["bucketId"] == "**REDACTED**"
assert account_data["allowed"]["bucketName"] == "**REDACTED**"
assert account_data["allowed"]["namePrefix"] == "**REDACTED**"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/backblaze_b2/test_diagnostics.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/backblaze_b2/test_init.py | """Test the Backblaze B2 storage integration."""
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, patch
from b2sdk.v2 import exception
import pytest
from homeassistant.components.backblaze_b2.const import CONF_APPLICATION_KEY
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 # type: ignore[comparison-overlap]
async def test_setup_entry_invalid_auth(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setup entry with invalid auth."""
mock_config = MockConfigEntry(
entry_id=mock_config_entry.entry_id,
title=mock_config_entry.title,
domain=mock_config_entry.domain,
data={
**mock_config_entry.data,
CONF_APPLICATION_KEY: "invalid_key_id",
},
)
await setup_integration(hass, mock_config)
assert mock_config.state is ConfigEntryState.SETUP_ERROR
@pytest.mark.parametrize(
("exception", "state"),
[
(exception.Unauthorized("msg", "code"), ConfigEntryState.SETUP_ERROR),
(exception.RestrictedBucket("testBucket"), ConfigEntryState.SETUP_RETRY),
(exception.NonExistentBucket(), ConfigEntryState.SETUP_RETRY),
(exception.ConnectionReset(), ConfigEntryState.SETUP_RETRY),
(exception.MissingAccountData("key"), ConfigEntryState.SETUP_ERROR),
],
)
async def test_setup_entry_restricted_bucket(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
exception: Exception,
state: ConfigEntryState,
) -> None:
"""Test setup entry with restricted bucket."""
with patch(
"b2sdk.v2.RawSimulator.get_bucket_by_name",
side_effect=exception,
):
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is state
async def test_periodic_issue_check(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test periodic issue check functionality."""
captured_callback = None
def capture_callback(hass: HomeAssistant | None, callback, interval):
nonlocal captured_callback
captured_callback = callback
return MagicMock()
with (
patch(
"homeassistant.components.backblaze_b2.async_check_for_repair_issues",
new_callable=AsyncMock,
) as mock_check,
patch(
"homeassistant.components.backblaze_b2.async_track_time_interval",
side_effect=capture_callback,
),
):
await setup_integration(hass, mock_config_entry)
assert captured_callback is not None
await captured_callback(datetime.now())
assert mock_check.call_count == 2 # setup + callback
mock_check.assert_called_with(hass, mock_config_entry)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/backblaze_b2/test_init.py",
"license": "Apache License 2.0",
"lines": 83,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/backblaze_b2/test_repairs.py | """Test Backblaze B2 repairs."""
from unittest.mock import Mock, patch
from b2sdk.v2.exception import (
B2Error,
NonExistentBucket,
RestrictedBucket,
Unauthorized,
)
import pytest
from homeassistant.components.backblaze_b2.repairs import (
async_check_for_repair_issues,
async_create_fix_flow,
)
from homeassistant.components.repairs import ConfirmRepairFlow
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir
from tests.common import MockConfigEntry
@pytest.fixture
def mock_entry():
"""Create a mock config entry with runtime data."""
entry = MockConfigEntry(domain="backblaze_b2", data={"bucket": "test"})
entry.runtime_data = Mock()
return entry
@pytest.mark.parametrize(
("exception", "expected_issues"),
[
(Unauthorized("test", "auth_failed"), 0), # Handled by reauth flow
(RestrictedBucket("test"), 1), # Creates repair issue
(NonExistentBucket("test"), 1), # Creates repair issue
(B2Error("test"), 0), # Just logs, no issue
],
)
async def test_repair_issue_creation(
hass: HomeAssistant,
mock_entry: MockConfigEntry,
exception: Exception,
expected_issues: int,
) -> None:
"""Test repair issue creation for different exception types."""
with patch.object(hass, "async_add_executor_job", side_effect=exception):
await async_check_for_repair_issues(hass, mock_entry)
issues = ir.async_get(hass).issues
assert len(issues) == expected_issues
async def test_async_create_fix_flow(hass: HomeAssistant) -> None:
"""Test creating repair fix flow."""
flow = await async_create_fix_flow(hass, "test_issue", None)
assert isinstance(flow, ConfirmRepairFlow)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/backblaze_b2/test_repairs.py",
"license": "Apache License 2.0",
"lines": 47,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/bang_olufsen/util.py | """Various utilities for Bang & Olufsen testing."""
from inflection import underscore
from homeassistant.components.bang_olufsen.const import (
BEO_REMOTE_CONTROL_KEYS,
BEO_REMOTE_KEYS,
BEO_REMOTE_SUBMENU_CONTROL,
BEO_REMOTE_SUBMENU_LIGHT,
DEVICE_BUTTONS,
)
from .const import (
TEST_BATTERY_CHARGING_BINARY_SENSOR_ENTITY_ID,
TEST_BATTERY_SENSOR_ENTITY_ID,
TEST_MEDIA_PLAYER_ENTITY_ID,
TEST_MEDIA_PLAYER_ENTITY_ID_2,
TEST_MEDIA_PLAYER_ENTITY_ID_3,
TEST_MEDIA_PLAYER_ENTITY_ID_4,
TEST_REMOTE_SERIAL,
TEST_SERIAL_NUMBER,
)
def _get_button_entity_ids(id_prefix: str = "beosound_balance_11111111") -> list[str]:
"""Return a list of button entity_ids that Mozart devices provide.
Beoconnect Core, Beosound A5, Beosound A9 and Beosound Premiere do not have (all of the) physical buttons and need filtering.
"""
return [
f"event.{id_prefix}_{underscore(button_type)}".replace("preset", "favorite_")
for button_type in DEVICE_BUTTONS
]
def get_balance_entity_ids() -> list[str]:
"""Return a list of entity_ids that a Beosound Balance provides."""
return [TEST_MEDIA_PLAYER_ENTITY_ID, *_get_button_entity_ids()]
def get_premiere_entity_ids() -> list[str]:
"""Return a list of entity_ids that a Beosound Premiere provides."""
buttons = [
TEST_MEDIA_PLAYER_ENTITY_ID_3,
*_get_button_entity_ids("beosound_premiere_33333333"),
]
buttons.remove("event.beosound_premiere_33333333_bluetooth")
buttons.remove("event.beosound_premiere_33333333_microphone")
return buttons
def get_a5_entity_ids() -> list[str]:
"""Return a list of entity_ids that a Beosound A5 provides."""
buttons = [
TEST_MEDIA_PLAYER_ENTITY_ID_4,
TEST_BATTERY_SENSOR_ENTITY_ID,
TEST_BATTERY_CHARGING_BINARY_SENSOR_ENTITY_ID,
*_get_button_entity_ids("beosound_a5_44444444"),
]
buttons.remove("event.beosound_a5_44444444_microphone")
return buttons
def get_core_entity_ids() -> list[str]:
"""Return a list of entity_ids that a Beoconnect core provides."""
return [TEST_MEDIA_PLAYER_ENTITY_ID_2]
def get_remote_entity_ids(
remote_serial: str = TEST_REMOTE_SERIAL, device_serial: str = TEST_SERIAL_NUMBER
) -> list[str]:
"""Return a list of entity_ids that the Beoremote One provides."""
entity_ids: list[str] = [
f"sensor.beoremote_one_{remote_serial}_{device_serial}_battery"
]
# Add remote light key Event entity ids
entity_ids.extend(
[
f"event.beoremote_one_{remote_serial}_{device_serial}_{BEO_REMOTE_SUBMENU_LIGHT.lower()}_{key_type.lower()}".replace(
"func", "function_"
).replace("digit", "digit_")
for key_type in BEO_REMOTE_KEYS
]
)
# Add remote control key Event entity ids
entity_ids.extend(
[
f"event.beoremote_one_{remote_serial}_{device_serial}_{BEO_REMOTE_SUBMENU_CONTROL.lower()}_{key_type.lower()}".replace(
"func", "function_"
).replace("digit", "digit_")
for key_type in (*BEO_REMOTE_KEYS, *BEO_REMOTE_CONTROL_KEYS)
]
)
return entity_ids
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/bang_olufsen/util.py",
"license": "Apache License 2.0",
"lines": 78,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/binary_sensor/test_trigger.py | """Test binary sensor trigger."""
from typing import Any
import pytest
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_LABEL_ID,
CONF_ENTITY_ID,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_binary_sensors(hass: HomeAssistant) -> tuple[list[str], list[str]]:
"""Create multiple binary sensor entities associated with different targets."""
return await target_entities(hass, "binary_sensor")
@pytest.mark.parametrize(
"trigger_key",
[
"binary_sensor.occupancy_detected",
"binary_sensor.occupancy_cleared",
],
)
async def test_binary_sensor_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the binary sensor triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("binary_sensor"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="binary_sensor.occupancy_detected",
target_states=[STATE_ON],
other_states=[STATE_OFF],
additional_attributes={ATTR_DEVICE_CLASS: "occupancy"},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="binary_sensor.occupancy_cleared",
target_states=[STATE_OFF],
other_states=[STATE_ON],
additional_attributes={ATTR_DEVICE_CLASS: "occupancy"},
trigger_from_none=False,
),
],
)
async def test_binary_sensor_state_attribute_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_binary_sensors: dict[list[str], list[str]],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the binary sensor state trigger fires when any binary sensor state changes to a specific state."""
other_entity_ids = set(target_binary_sensors["included"]) - {entity_id}
excluded_entity_ids = set(target_binary_sensors["excluded"]) - {entity_id}
# Set all binary sensors, including the tested binary sensor, to the initial state
for eid in target_binary_sensors["included"]:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
for eid in excluded_entity_ids:
set_or_remove_state(hass, eid, states[0]["excluded"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {}, trigger_target_config)
for state in states[1:]:
excluded_state = state["excluded"]
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other binary sensors also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
for excluded_entity_id in excluded_entity_ids:
set_or_remove_state(hass, excluded_entity_id, excluded_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("binary_sensor"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="binary_sensor.occupancy_detected",
target_states=[STATE_ON],
other_states=[STATE_OFF],
additional_attributes={ATTR_DEVICE_CLASS: "occupancy"},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="binary_sensor.occupancy_cleared",
target_states=[STATE_OFF],
other_states=[STATE_ON],
additional_attributes={ATTR_DEVICE_CLASS: "occupancy"},
trigger_from_none=False,
),
],
)
async def test_binary_sensor_state_attribute_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_binary_sensors: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the binary sensor state trigger fires when the first binary sensor state changes to a specific state."""
other_entity_ids = set(target_binary_sensors["included"]) - {entity_id}
excluded_entity_ids = set(target_binary_sensors["excluded"]) - {entity_id}
# Set all binary sensors, including the tested binary sensor, to the initial state
for eid in target_binary_sensors["included"]:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
for eid in excluded_entity_ids:
set_or_remove_state(hass, eid, states[0]["excluded"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config)
for state in states[1:]:
excluded_state = state["excluded"]
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other binary sensors should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, excluded_state)
await hass.async_block_till_done()
for excluded_entity_id in excluded_entity_ids:
set_or_remove_state(hass, excluded_entity_id, excluded_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("binary_sensor"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="binary_sensor.occupancy_detected",
target_states=[STATE_ON],
other_states=[STATE_OFF],
additional_attributes={ATTR_DEVICE_CLASS: "occupancy"},
trigger_from_none=False,
),
*parametrize_trigger_states(
trigger="binary_sensor.occupancy_cleared",
target_states=[STATE_OFF],
other_states=[STATE_ON],
additional_attributes={ATTR_DEVICE_CLASS: "occupancy"},
trigger_from_none=False,
),
],
)
async def test_binary_sensor_state_attribute_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_binary_sensors: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the binary sensor state trigger fires when the last binary sensor state changes to a specific state."""
other_entity_ids = set(target_binary_sensors["included"]) - {entity_id}
excluded_entity_ids = set(target_binary_sensors["excluded"]) - {entity_id}
# Set all binary sensors, including the tested binary sensor, to the initial state
for eid in target_binary_sensors["included"]:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
for eid in excluded_entity_ids:
set_or_remove_state(hass, eid, states[0]["excluded"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config)
for state in states[1:]:
excluded_state = state["excluded"]
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, excluded_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
for excluded_entity_id in excluded_entity_ids:
set_or_remove_state(hass, excluded_entity_id, excluded_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/binary_sensor/test_trigger.py",
"license": "Apache License 2.0",
"lines": 231,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/climate/test_trigger.py | """Test climate trigger."""
from contextlib import AbstractContextManager, nullcontext as does_not_raise
from typing import Any
import pytest
import voluptuous as vol
from homeassistant.components.climate.const import (
ATTR_CURRENT_HUMIDITY,
ATTR_CURRENT_TEMPERATURE,
ATTR_HUMIDITY,
ATTR_HVAC_ACTION,
HVACAction,
HVACMode,
)
from homeassistant.components.climate.trigger import CONF_HVAC_MODE
from homeassistant.const import (
ATTR_LABEL_ID,
ATTR_TEMPERATURE,
CONF_ENTITY_ID,
CONF_OPTIONS,
CONF_TARGET,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers.trigger import async_validate_trigger_config
from tests.components import (
TriggerStateDescription,
arm_trigger,
other_states,
parametrize_numerical_attribute_changed_trigger_states,
parametrize_numerical_attribute_crossed_threshold_trigger_states,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_climates(hass: HomeAssistant) -> list[str]:
"""Create multiple climate entities associated with different targets."""
return (await target_entities(hass, "climate"))["included"]
@pytest.mark.parametrize(
"trigger_key",
[
"climate.current_humidity_changed",
"climate.current_humidity_crossed_threshold",
"climate.current_temperature_changed",
"climate.current_temperature_crossed_threshold",
"climate.hvac_mode_changed",
"climate.target_humidity_changed",
"climate.target_humidity_crossed_threshold",
"climate.target_temperature_changed",
"climate.target_temperature_crossed_threshold",
"climate.turned_off",
"climate.turned_on",
"climate.started_heating",
],
)
async def test_climate_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the climate triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger", "trigger_options", "expected_result"),
[
# Test validating climate.hvac_mode_changed
# Valid configurations
(
"climate.hvac_mode_changed",
{CONF_HVAC_MODE: ["heat", "cool"]},
does_not_raise(),
),
(
"climate.hvac_mode_changed",
{CONF_HVAC_MODE: "heat"},
does_not_raise(),
),
# Invalid configurations
(
"climate.hvac_mode_changed",
# Empty hvac_mode list
{CONF_HVAC_MODE: []},
pytest.raises(vol.Invalid),
),
(
"climate.hvac_mode_changed",
# Missing CONF_HVAC_MODE
{},
pytest.raises(vol.Invalid),
),
(
"climate.hvac_mode_changed",
{CONF_HVAC_MODE: ["invalid_mode"]},
pytest.raises(vol.Invalid),
),
],
)
async def test_climate_trigger_validation(
hass: HomeAssistant,
trigger: str,
trigger_options: dict[str, Any],
expected_result: AbstractContextManager,
) -> None:
"""Test climate trigger config validation."""
with expected_result:
await async_validate_trigger_config(
hass,
[
{
"platform": trigger,
CONF_TARGET: {CONF_ENTITY_ID: "climate.test_climate"},
CONF_OPTIONS: trigger_options,
}
],
)
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("climate"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="climate.hvac_mode_changed",
trigger_options={CONF_HVAC_MODE: ["heat", "cool"]},
target_states=[HVACMode.HEAT, HVACMode.COOL],
other_states=other_states([HVACMode.HEAT, HVACMode.COOL]),
),
*parametrize_trigger_states(
trigger="climate.turned_off",
target_states=[HVACMode.OFF],
other_states=other_states(HVACMode.OFF),
),
*parametrize_trigger_states(
trigger="climate.turned_on",
target_states=[
HVACMode.AUTO,
HVACMode.COOL,
HVACMode.DRY,
HVACMode.FAN_ONLY,
HVACMode.HEAT,
HVACMode.HEAT_COOL,
],
other_states=[
HVACMode.OFF,
],
),
],
)
async def test_climate_state_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_climates: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the climate state trigger fires when any climate state changes to a specific state."""
other_entity_ids = set(target_climates) - {entity_id}
# Set all climates, including the tested climate, to the initial state
for eid in target_climates:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, trigger_options, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other climates also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("climate"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_numerical_attribute_changed_trigger_states(
"climate.current_humidity_changed", HVACMode.AUTO, ATTR_CURRENT_HUMIDITY
),
*parametrize_numerical_attribute_changed_trigger_states(
"climate.current_temperature_changed",
HVACMode.AUTO,
ATTR_CURRENT_TEMPERATURE,
),
*parametrize_numerical_attribute_changed_trigger_states(
"climate.target_humidity_changed", HVACMode.AUTO, ATTR_HUMIDITY
),
*parametrize_numerical_attribute_changed_trigger_states(
"climate.target_temperature_changed", HVACMode.AUTO, ATTR_TEMPERATURE
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.current_humidity_crossed_threshold",
HVACMode.AUTO,
ATTR_CURRENT_HUMIDITY,
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.current_temperature_crossed_threshold",
HVACMode.AUTO,
ATTR_CURRENT_TEMPERATURE,
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.target_humidity_crossed_threshold", HVACMode.AUTO, ATTR_HUMIDITY
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.target_temperature_crossed_threshold",
HVACMode.AUTO,
ATTR_TEMPERATURE,
),
*parametrize_trigger_states(
trigger="climate.started_cooling",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.COOLING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_trigger_states(
trigger="climate.started_drying",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.DRYING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_trigger_states(
trigger="climate.started_heating",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.HEATING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
],
)
async def test_climate_state_attribute_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_climates: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the climate state trigger fires when any climate state changes to a specific state."""
other_entity_ids = set(target_climates) - {entity_id}
# Set all climates, including the tested climate, to the initial state
for eid in target_climates:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, trigger_options, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other climates also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("climate"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="climate.hvac_mode_changed",
trigger_options={CONF_HVAC_MODE: ["heat", "cool"]},
target_states=[HVACMode.HEAT, HVACMode.COOL],
other_states=other_states([HVACMode.HEAT, HVACMode.COOL]),
),
*parametrize_trigger_states(
trigger="climate.turned_off",
target_states=[HVACMode.OFF],
other_states=other_states(HVACMode.OFF),
),
*parametrize_trigger_states(
trigger="climate.turned_on",
target_states=[
HVACMode.AUTO,
HVACMode.COOL,
HVACMode.DRY,
HVACMode.FAN_ONLY,
HVACMode.HEAT,
HVACMode.HEAT_COOL,
],
other_states=[
HVACMode.OFF,
],
),
],
)
async def test_climate_state_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_climates: list[str],
trigger_target_config: dict,
entities_in_target: int,
entity_id: str,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the climate state trigger fires when the first climate changes to a specific state."""
other_entity_ids = set(target_climates) - {entity_id}
# Set all climates, including the tested climate, to the initial state
for eid in target_climates:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "first"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other climates should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("climate"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.current_humidity_crossed_threshold",
HVACMode.AUTO,
ATTR_CURRENT_HUMIDITY,
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.current_temperature_crossed_threshold",
HVACMode.AUTO,
ATTR_CURRENT_TEMPERATURE,
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.target_humidity_crossed_threshold", HVACMode.AUTO, ATTR_HUMIDITY
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.target_temperature_crossed_threshold",
HVACMode.AUTO,
ATTR_TEMPERATURE,
),
*parametrize_trigger_states(
trigger="climate.started_cooling",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.COOLING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_trigger_states(
trigger="climate.started_drying",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.DRYING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_trigger_states(
trigger="climate.started_heating",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.HEATING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
],
)
async def test_climate_state_attribute_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_climates: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[tuple[tuple[str, dict], int]],
) -> None:
"""Test that the climate state trigger fires when the first climate state changes to a specific state."""
other_entity_ids = set(target_climates) - {entity_id}
# Set all climates, including the tested climate, to the initial state
for eid in target_climates:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "first"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other climates should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("climate"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="climate.hvac_mode_changed",
trigger_options={CONF_HVAC_MODE: ["heat", "cool"]},
target_states=[HVACMode.HEAT, HVACMode.COOL],
other_states=other_states([HVACMode.HEAT, HVACMode.COOL]),
),
*parametrize_trigger_states(
trigger="climate.turned_off",
target_states=[HVACMode.OFF],
other_states=other_states(HVACMode.OFF),
),
*parametrize_trigger_states(
trigger="climate.turned_on",
target_states=[
HVACMode.AUTO,
HVACMode.COOL,
HVACMode.DRY,
HVACMode.FAN_ONLY,
HVACMode.HEAT,
HVACMode.HEAT_COOL,
],
other_states=[
HVACMode.OFF,
],
),
],
)
async def test_climate_state_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_climates: list[str],
trigger_target_config: dict,
entities_in_target: int,
entity_id: str,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the climate state trigger fires when the last climate changes to a specific state."""
other_entity_ids = set(target_climates) - {entity_id}
# Set all climates, including the tested climate, to the initial state
for eid in target_climates:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "last"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("climate"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.current_humidity_crossed_threshold",
HVACMode.AUTO,
ATTR_CURRENT_HUMIDITY,
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.current_temperature_crossed_threshold",
HVACMode.AUTO,
ATTR_CURRENT_TEMPERATURE,
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.target_humidity_crossed_threshold", HVACMode.AUTO, ATTR_HUMIDITY
),
*parametrize_numerical_attribute_crossed_threshold_trigger_states(
"climate.target_temperature_crossed_threshold",
HVACMode.AUTO,
ATTR_TEMPERATURE,
),
*parametrize_trigger_states(
trigger="climate.started_cooling",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.COOLING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_trigger_states(
trigger="climate.started_drying",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.DRYING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_trigger_states(
trigger="climate.started_heating",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.HEATING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
],
)
async def test_climate_state_attribute_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_climates: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[tuple[tuple[str, dict], int]],
) -> None:
"""Test that the climate state trigger fires when the last climate state changes to a specific state."""
other_entity_ids = set(target_climates) - {entity_id}
# Set all climates, including the tested climate, to the initial state
for eid in target_climates:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "last"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/climate/test_trigger.py",
"license": "Apache License 2.0",
"lines": 562,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/cloud/test_ai_task.py | """Tests for the Home Assistant Cloud AI Task entity."""
from __future__ import annotations
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
from hass_nabucasa.llm import (
LLMAuthenticationError,
LLMError,
LLMImageAttachment,
LLMRateLimitError,
LLMResponseError,
LLMServiceError,
)
from PIL import Image
import pytest
import voluptuous as vol
from homeassistant.components import ai_task, conversation
from homeassistant.components.cloud.ai_task import (
CloudAITaskEntity,
async_prepare_image_generation_attachments,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from tests.common import MockConfigEntry
@pytest.fixture
def mock_cloud_ai_task_entity(hass: HomeAssistant) -> CloudAITaskEntity:
"""Return a CloudAITaskEntity with a mocked cloud LLM."""
cloud = MagicMock()
cloud.llm = MagicMock(
async_generate_image=AsyncMock(),
async_edit_image=AsyncMock(),
)
cloud.is_logged_in = True
cloud.valid_subscription = True
entry = MockConfigEntry(domain="cloud")
entry.add_to_hass(hass)
entity = CloudAITaskEntity(cloud, entry)
entity.entity_id = "ai_task.cloud_ai_task"
entity.hass = hass
return entity
@pytest.fixture(name="mock_handle_chat_log")
def mock_handle_chat_log_fixture() -> AsyncMock:
"""Patch the chat log handler."""
with patch(
"homeassistant.components.cloud.ai_task.CloudAITaskEntity._async_handle_chat_log",
AsyncMock(),
) as mock:
yield mock
@pytest.fixture(name="mock_prepare_generation_attachments")
def mock_prepare_generation_attachments_fixture() -> AsyncMock:
"""Patch image generation attachment preparation."""
with patch(
"homeassistant.components.cloud.ai_task.async_prepare_image_generation_attachments",
AsyncMock(),
) as mock:
yield mock
async def test_prepare_image_generation_attachments(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test preparing attachments for image generation."""
image_path = tmp_path / "snapshot.jpg"
Image.new("RGB", (2, 2), "red").save(image_path, "JPEG")
attachments = [
conversation.Attachment(
media_content_id="media-source://media/snapshot.jpg",
mime_type="image/jpeg",
path=image_path,
)
]
result = await async_prepare_image_generation_attachments(hass, attachments)
assert len(result) == 1
attachment = result[0]
assert attachment["filename"] == "snapshot.jpg"
assert attachment["mime_type"] == "image/png"
assert attachment["data"].startswith(b"\x89PNG")
async def test_prepare_image_generation_attachments_only_images(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test non image attachments are rejected."""
doc_path = tmp_path / "context.txt"
doc_path.write_text("context")
attachments = [
conversation.Attachment(
media_content_id="media-source://media/context.txt",
mime_type="text/plain",
path=doc_path,
)
]
with pytest.raises(
HomeAssistantError,
match="Only image attachments are supported for image generation",
):
await async_prepare_image_generation_attachments(hass, attachments)
async def test_prepare_image_generation_attachments_missing_file(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test missing attachments raise a helpful error."""
missing_path = tmp_path / "missing.png"
attachments = [
conversation.Attachment(
media_content_id="media-source://media/missing.png",
mime_type="image/png",
path=missing_path,
)
]
with pytest.raises(HomeAssistantError, match="`.*missing.png` does not exist"):
await async_prepare_image_generation_attachments(hass, attachments)
async def test_prepare_image_generation_attachments_processing_error(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test invalid image data raises a processing error."""
broken_path = tmp_path / "broken.png"
broken_path.write_bytes(b"not-an-image")
attachments = [
conversation.Attachment(
media_content_id="media-source://media/broken.png",
mime_type="image/png",
path=broken_path,
)
]
with pytest.raises(
HomeAssistantError,
match="Failed to process image attachment",
):
await async_prepare_image_generation_attachments(hass, attachments)
async def test_generate_data_returns_text(
hass: HomeAssistant,
mock_cloud_ai_task_entity: CloudAITaskEntity,
mock_handle_chat_log: AsyncMock,
) -> None:
"""Test generating plain text data."""
chat_log = conversation.ChatLog(hass, "conversation-id")
chat_log.async_add_user_content(
conversation.UserContent(content="Tell me something")
)
task = ai_task.GenDataTask(name="Task", instructions="Say hi")
async def fake_handle(chat_type, log, task_name, structure):
"""Inject assistant output."""
assert chat_type == "ai_task"
log.async_add_assistant_content_without_tools(
conversation.AssistantContent(
agent_id=mock_cloud_ai_task_entity.entity_id or "",
content="Hello from the cloud",
)
)
mock_handle_chat_log.side_effect = fake_handle
result = await mock_cloud_ai_task_entity._async_generate_data(task, chat_log)
assert result.conversation_id == "conversation-id"
assert result.data == "Hello from the cloud"
async def test_generate_data_returns_json(
hass: HomeAssistant,
mock_cloud_ai_task_entity: CloudAITaskEntity,
mock_handle_chat_log: AsyncMock,
) -> None:
"""Test generating structured data."""
chat_log = conversation.ChatLog(hass, "conversation-id")
chat_log.async_add_user_content(conversation.UserContent(content="List names"))
task = ai_task.GenDataTask(
name="Task",
instructions="Return JSON",
structure=vol.Schema({vol.Required("names"): [str]}),
)
async def fake_handle(chat_type, log, task_name, structure):
log.async_add_assistant_content_without_tools(
conversation.AssistantContent(
agent_id=mock_cloud_ai_task_entity.entity_id or "",
content='{"names": ["A", "B"]}',
)
)
mock_handle_chat_log.side_effect = fake_handle
result = await mock_cloud_ai_task_entity._async_generate_data(task, chat_log)
assert result.data == {"names": ["A", "B"]}
async def test_generate_data_invalid_json(
hass: HomeAssistant,
mock_cloud_ai_task_entity: CloudAITaskEntity,
mock_handle_chat_log: AsyncMock,
) -> None:
"""Test invalid JSON responses raise an error."""
chat_log = conversation.ChatLog(hass, "conversation-id")
chat_log.async_add_user_content(conversation.UserContent(content="List names"))
task = ai_task.GenDataTask(
name="Task",
instructions="Return JSON",
structure=vol.Schema({vol.Required("names"): [str]}),
)
async def fake_handle(chat_type, log, task_name, structure):
log.async_add_assistant_content_without_tools(
conversation.AssistantContent(
agent_id=mock_cloud_ai_task_entity.entity_id or "",
content="not-json",
)
)
mock_handle_chat_log.side_effect = fake_handle
with pytest.raises(
HomeAssistantError, match="Error with OpenAI structured response"
):
await mock_cloud_ai_task_entity._async_generate_data(task, chat_log)
async def test_generate_image_no_attachments(
hass: HomeAssistant, mock_cloud_ai_task_entity: CloudAITaskEntity
) -> None:
"""Test generating an image without attachments."""
mock_cloud_ai_task_entity._cloud.llm.async_generate_image.return_value = {
"mime_type": "image/png",
"image_data": b"IMG",
"model": "mock-image",
"width": 1024,
"height": 768,
"revised_prompt": "Improved prompt",
}
task = ai_task.GenImageTask(name="Task", instructions="Draw something")
chat_log = conversation.ChatLog(hass, "conversation-id")
result = await mock_cloud_ai_task_entity._async_generate_image(task, chat_log)
assert result.image_data == b"IMG"
assert result.mime_type == "image/png"
mock_cloud_ai_task_entity._cloud.llm.async_generate_image.assert_awaited_once_with(
prompt="Draw something"
)
async def test_generate_image_with_attachments(
hass: HomeAssistant,
mock_cloud_ai_task_entity: CloudAITaskEntity,
mock_prepare_generation_attachments: AsyncMock,
) -> None:
"""Test generating an edited image when attachments are provided."""
mock_cloud_ai_task_entity._cloud.llm.async_edit_image.return_value = {
"mime_type": "image/png",
"image_data": b"IMG",
}
task = ai_task.GenImageTask(
name="Task",
instructions="Edit this",
attachments=[
conversation.Attachment(
media_content_id="media-source://media/snapshot.png",
mime_type="image/png",
path=hass.config.path("snapshot.png"),
)
],
)
chat_log = conversation.ChatLog(hass, "conversation-id")
prepared_attachments = [
LLMImageAttachment(filename="snapshot.png", mime_type="image/png", data=b"IMG")
]
mock_prepare_generation_attachments.return_value = prepared_attachments
await mock_cloud_ai_task_entity._async_generate_image(task, chat_log)
mock_cloud_ai_task_entity._cloud.llm.async_edit_image.assert_awaited_once_with(
prompt="Edit this",
attachments=prepared_attachments,
)
@pytest.mark.parametrize(
("err", "expected_exception", "message"),
[
(
LLMAuthenticationError("auth"),
HomeAssistantError,
"Cloud LLM authentication failed",
),
(
LLMRateLimitError("limit"),
HomeAssistantError,
"Cloud LLM is rate limited",
),
(
LLMResponseError("bad response"),
HomeAssistantError,
"bad response",
),
(
LLMServiceError("service"),
HomeAssistantError,
"Error talking to Cloud LLM",
),
(
LLMError("generic"),
HomeAssistantError,
"generic",
),
],
)
async def test_generate_image_error_handling(
hass: HomeAssistant,
mock_cloud_ai_task_entity: CloudAITaskEntity,
err: Exception,
expected_exception: type[Exception],
message: str,
) -> None:
"""Test image generation error handling."""
mock_cloud_ai_task_entity._cloud.llm.async_generate_image.side_effect = err
task = ai_task.GenImageTask(name="Task", instructions="Draw something")
chat_log = conversation.ChatLog(hass, "conversation-id")
with pytest.raises(expected_exception, match=message):
await mock_cloud_ai_task_entity._async_generate_image(task, chat_log)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/cloud/test_ai_task.py",
"license": "Apache License 2.0",
"lines": 290,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/cloud/test_conversation.py | """Tests for the Home Assistant Cloud conversation entity."""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from homeassistant.components import conversation
from homeassistant.components.cloud.const import DOMAIN
from homeassistant.components.cloud.conversation import CloudConversationEntity
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import intent, llm
from tests.common import MockConfigEntry
@pytest.fixture
def cloud_conversation_entity(hass: HomeAssistant) -> CloudConversationEntity:
"""Return a CloudConversationEntity attached to hass."""
cloud = MagicMock()
cloud.llm = MagicMock()
cloud.is_logged_in = True
cloud.valid_subscription = True
entry = MockConfigEntry(domain=DOMAIN)
entry.add_to_hass(hass)
entity = CloudConversationEntity(cloud, entry)
entity.entity_id = "conversation.home_assistant_cloud"
entity.hass = hass
return entity
def test_entity_availability(
cloud_conversation_entity: CloudConversationEntity,
) -> None:
"""Test that availability mirrors the cloud login/subscription state."""
cloud_conversation_entity._cloud.is_logged_in = True
cloud_conversation_entity._cloud.valid_subscription = True
assert cloud_conversation_entity.available
cloud_conversation_entity._cloud.is_logged_in = False
assert not cloud_conversation_entity.available
cloud_conversation_entity._cloud.is_logged_in = True
cloud_conversation_entity._cloud.valid_subscription = False
assert not cloud_conversation_entity.available
async def test_async_handle_message(
hass: HomeAssistant, cloud_conversation_entity: CloudConversationEntity
) -> None:
"""Test that messages are processed through the chat log helper."""
user_input = conversation.ConversationInput(
text="apaga test",
context=Context(),
conversation_id="conversation-id",
device_id="device-id",
satellite_id=None,
language="es",
agent_id=cloud_conversation_entity.entity_id or "",
extra_system_prompt="hazlo",
)
chat_log = conversation.ChatLog(hass, user_input.conversation_id)
chat_log.async_add_user_content(conversation.UserContent(content=user_input.text))
chat_log.async_provide_llm_data = AsyncMock()
async def fake_handle(chat_type, log):
"""Inject assistant output so the result can be built."""
assert chat_type == "conversation"
assert log is chat_log
log.async_add_assistant_content_without_tools(
conversation.AssistantContent(
agent_id=cloud_conversation_entity.entity_id or "",
content="hecho",
)
)
handle_chat_log = AsyncMock(side_effect=fake_handle)
with patch.object(
cloud_conversation_entity, "_async_handle_chat_log", handle_chat_log
):
result = await cloud_conversation_entity._async_handle_message(
user_input, chat_log
)
chat_log.async_provide_llm_data.assert_awaited_once_with(
user_input.as_llm_context(DOMAIN),
llm.LLM_API_ASSIST,
None,
user_input.extra_system_prompt,
)
handle_chat_log.assert_awaited_once_with("conversation", chat_log)
assert result.conversation_id == "conversation-id"
assert result.response.speech["plain"]["speech"] == "hecho"
async def test_async_handle_message_converse_error(
hass: HomeAssistant, cloud_conversation_entity: CloudConversationEntity
) -> None:
"""Test that ConverseError short-circuits message handling."""
user_input = conversation.ConversationInput(
text="hola",
context=Context(),
conversation_id="conversation-id",
device_id=None,
satellite_id=None,
language="es",
agent_id=cloud_conversation_entity.entity_id or "",
)
chat_log = conversation.ChatLog(hass, user_input.conversation_id)
error_response = intent.IntentResponse(language="es")
converse_error = conversation.ConverseError(
"failed", user_input.conversation_id or "", error_response
)
chat_log.async_provide_llm_data = AsyncMock(side_effect=converse_error)
with patch.object(
cloud_conversation_entity, "_async_handle_chat_log", AsyncMock()
) as handle_chat_log:
result = await cloud_conversation_entity._async_handle_message(
user_input, chat_log
)
handle_chat_log.assert_not_called()
assert result.response is error_response
assert result.conversation_id == user_input.conversation_id
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/cloud/test_conversation.py",
"license": "Apache License 2.0",
"lines": 106,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/cloud/test_entity.py | """Tests for helpers in the Home Assistant Cloud conversation entity."""
from __future__ import annotations
import base64
import datetime
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock, patch
from PIL import Image
import pytest
import voluptuous as vol
from homeassistant.components import conversation
from homeassistant.components.cloud.const import AI_TASK_ENTITY_UNIQUE_ID, DOMAIN
from homeassistant.components.cloud.entity import (
BaseCloudLLMEntity,
_convert_content_to_param,
_format_structured_output,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er, llm, selector
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
@pytest.fixture
def cloud_entity(hass: HomeAssistant) -> BaseCloudLLMEntity:
"""Return a CloudLLMTaskEntity attached to hass."""
cloud = MagicMock()
cloud.llm = MagicMock()
cloud.is_logged_in = True
cloud.valid_subscription = True
entry = MockConfigEntry(domain="cloud")
entry.add_to_hass(hass)
entity = BaseCloudLLMEntity(cloud, entry)
entity.entity_id = "ai_task.cloud_ai_task"
entity.hass = hass
return entity
@pytest.fixture
def mock_prepare_files_for_prompt(
cloud_entity: BaseCloudLLMEntity,
) -> AsyncMock:
"""Patch file preparation helper on the entity."""
with patch.object(
cloud_entity,
"_async_prepare_files_for_prompt",
AsyncMock(),
) as mock:
yield mock
class DummyTool(llm.Tool):
"""Simple tool used for schema conversion tests."""
name = "do_something"
description = "Test tool"
parameters = vol.Schema({vol.Required("value"): str})
async def async_call(self, hass: HomeAssistant, tool_input, llm_context):
"""No-op implementation."""
return {"value": "done"}
async def test_format_structured_output() -> None:
"""Test that structured output schemas are normalized."""
schema = vol.Schema(
{
vol.Required("name"): selector.TextSelector(),
vol.Optional("age"): selector.NumberSelector(
config=selector.NumberSelectorConfig(min=0, max=120),
),
vol.Required("stuff"): selector.ObjectSelector(
{
"multiple": True,
"fields": {
"item_name": {"selector": {"text": None}},
"item_value": {"selector": {"text": None}},
},
}
),
}
)
assert _format_structured_output(schema, None) == {
"type": "object",
"properties": {
"name": {"type": "string"},
"age": {"type": "number", "minimum": 0.0, "maximum": 120.0},
"stuff": {
"type": "array",
"items": {
"type": "object",
"properties": {
"item_name": {"type": "string"},
"item_value": {"type": "string"},
},
"additionalProperties": False,
},
},
},
"required": ["name", "stuff"],
"additionalProperties": False,
}
async def test_prepare_files_for_prompt(
cloud_entity: BaseCloudLLMEntity, tmp_path: Path
) -> None:
"""Test that media attachments are converted to the expected payload."""
image_path = tmp_path / "doorbell.jpg"
Image.new("RGB", (2, 2), "blue").save(image_path, "JPEG")
pdf_path = tmp_path / "context.pdf"
pdf_path.write_bytes(b"%PDF-1.3\nmock\n")
attachments = [
conversation.Attachment(
media_content_id="media-source://media/doorbell.jpg",
mime_type="image/jpeg",
path=image_path,
),
conversation.Attachment(
media_content_id="media-source://media/context.pdf",
mime_type="application/pdf",
path=pdf_path,
),
]
files = await cloud_entity._async_prepare_files_for_prompt(attachments)
assert files[0] == {
"type": "input_image",
"image_url": "data:image/jpeg;base64,"
+ base64.b64encode(image_path.read_bytes()).decode(),
"detail": "auto",
}
assert files[1] == {
"type": "input_file",
"filename": "context.pdf",
"file_data": "data:application/pdf;base64,"
+ base64.b64encode(pdf_path.read_bytes()).decode(),
}
async def test_prepare_files_for_prompt_invalid_type(
cloud_entity: BaseCloudLLMEntity, tmp_path: Path
) -> None:
"""Test that unsupported attachments raise an error."""
text_path = tmp_path / "notes.txt"
text_path.write_text("notes")
attachments = [
conversation.Attachment(
media_content_id="media-source://media/notes.txt",
mime_type="text/plain",
path=text_path,
)
]
with pytest.raises(
HomeAssistantError,
match="Only images and PDF are currently supported as attachments",
):
await cloud_entity._async_prepare_files_for_prompt(attachments)
async def test_prepare_chat_for_generation_appends_attachments(
hass: HomeAssistant,
cloud_entity: BaseCloudLLMEntity,
mock_prepare_files_for_prompt: AsyncMock,
) -> None:
"""Test chat preparation adds LLM tools, attachments, and metadata."""
chat_log = conversation.ChatLog(hass, "conversation-id")
attachment = conversation.Attachment(
media_content_id="media-source://media/doorbell.jpg",
mime_type="image/jpeg",
path=Path(hass.config.path("doorbell.jpg")),
)
chat_log.async_add_user_content(
conversation.UserContent(content="Describe the door", attachments=[attachment])
)
chat_log.llm_api = MagicMock(
tools=[DummyTool()],
custom_serializer=None,
)
files = [{"type": "input_image", "image_url": "data://img", "detail": "auto"}]
mock_prepare_files_for_prompt.return_value = files
messages = _convert_content_to_param(chat_log.content)
response = await cloud_entity._prepare_chat_for_generation(
chat_log,
messages,
response_format={"type": "json"},
)
assert response["conversation_id"] == "conversation-id"
assert response["response_format"] == {"type": "json"}
assert response["tool_choice"] == "auto"
assert len(response["tools"]) == 2
assert response["tools"][0]["name"] == "do_something"
assert response["tools"][1]["type"] == "web_search"
assert response["messages"] is messages
mock_prepare_files_for_prompt.assert_awaited_once_with([attachment])
# Verify that files are actually added to the last user message
last_message = messages[-1]
assert last_message["type"] == "message"
assert last_message["role"] == "user"
assert isinstance(last_message["content"], list)
assert last_message["content"][0] == {
"type": "input_text",
"text": "Describe the door",
}
assert last_message["content"][1] == files[0]
async def test_prepare_chat_for_generation_passes_messages_through(
hass: HomeAssistant, cloud_entity: BaseCloudLLMEntity
) -> None:
"""Test that prepared messages are forwarded unchanged."""
chat_log = conversation.ChatLog(hass, "conversation-id")
chat_log.async_add_user_content(
conversation.UserContent(content="What time is it?")
)
chat_log.async_add_assistant_content_without_tools(
conversation.AssistantContent(
agent_id="agent",
tool_calls=[
llm.ToolInput(
tool_name="HassGetCurrentTime",
tool_args={},
id="mock-tool-call-id",
external=True,
)
],
)
)
chat_log.async_add_assistant_content_without_tools(
conversation.ToolResultContent(
agent_id="agent",
tool_call_id="mock-tool-call-id",
tool_name="HassGetCurrentTime",
tool_result={
"speech": {"plain": {"speech": "12:00 PM", "extra_data": None}},
"response_type": "action_done",
"speech_slots": {"time": datetime.time(12, 0)},
"data": {"targets": [], "success": [], "failed": []},
},
)
)
chat_log.async_add_assistant_content_without_tools(
conversation.AssistantContent(agent_id="agent", content="12:00 PM")
)
messages = _convert_content_to_param(chat_log.content)
response = await cloud_entity._prepare_chat_for_generation(chat_log, messages)
assert response["messages"] == messages
assert response["conversation_id"] == "conversation-id"
async def test_async_handle_chat_log_service_sets_structured_output_non_strict(
hass: HomeAssistant,
cloud: MagicMock,
entity_registry: er.EntityRegistry,
mock_cloud_login: None,
) -> None:
"""Ensure structured output requests always disable strict validation via service."""
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
on_start_callback = cloud.register_on_start.call_args[0][0]
await on_start_callback()
await hass.async_block_till_done()
entity_id = entity_registry.async_get_entity_id(
"ai_task", DOMAIN, AI_TASK_ENTITY_UNIQUE_ID
)
assert entity_id is not None
async def _empty_stream():
return
async def _fake_delta_stream(
self: conversation.ChatLog,
agent_id: str,
stream,
):
content = conversation.AssistantContent(
agent_id=agent_id, content='{"value": "ok"}'
)
self.async_add_assistant_content_without_tools(content)
yield content
cloud.llm.async_generate_data = AsyncMock(return_value=_empty_stream())
with patch(
"homeassistant.components.conversation.chat_log.ChatLog.async_add_delta_content_stream",
_fake_delta_stream,
):
await hass.services.async_call(
"ai_task",
"generate_data",
{
"entity_id": entity_id,
"task_name": "Device Report",
"instructions": "Provide value.",
"structure": {
"value": {
"selector": {"text": None},
"required": True,
}
},
},
blocking=True,
return_response=True,
)
cloud.llm.async_generate_data.assert_awaited_once()
_, kwargs = cloud.llm.async_generate_data.call_args
assert kwargs["response_format"]["json_schema"]["strict"] is False
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/cloud/test_entity.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/concord232/test_alarm_control_panel.py | """Tests for the Concord232 alarm control panel platform."""
from __future__ import annotations
from unittest.mock import MagicMock
from freezegun.api import FrozenDateTimeFactory
import pytest
import requests
from homeassistant.components.alarm_control_panel import (
DOMAIN as ALARM_DOMAIN,
SERVICE_ALARM_ARM_AWAY,
SERVICE_ALARM_ARM_HOME,
SERVICE_ALARM_DISARM,
AlarmControlPanelState,
)
from homeassistant.const import (
ATTR_CODE,
ATTR_ENTITY_ID,
CONF_CODE,
CONF_HOST,
CONF_MODE,
CONF_NAME,
CONF_PORT,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import async_fire_time_changed
VALID_CONFIG = {
ALARM_DOMAIN: {
"platform": "concord232",
CONF_HOST: "localhost",
CONF_PORT: 5007,
CONF_NAME: "Test Alarm",
}
}
VALID_CONFIG_WITH_CODE = {
ALARM_DOMAIN: {
"platform": "concord232",
CONF_HOST: "localhost",
CONF_PORT: 5007,
CONF_NAME: "Test Alarm",
CONF_CODE: "1234",
}
}
VALID_CONFIG_SILENT_MODE = {
ALARM_DOMAIN: {
"platform": "concord232",
CONF_HOST: "localhost",
CONF_PORT: 5007,
CONF_NAME: "Test Alarm",
CONF_MODE: "silent",
}
}
async def test_setup_platform(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test platform setup."""
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
state = hass.states.get("alarm_control_panel.test_alarm")
assert state is not None
assert state.state == AlarmControlPanelState.DISARMED
async def test_setup_platform_connection_error(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test platform setup with connection error."""
mock_concord232_client.list_partitions.side_effect = (
requests.exceptions.ConnectionError("Connection failed")
)
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
assert hass.states.get("alarm_control_panel.test_alarm") is None
async def test_alarm_disarm(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test disarm service."""
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_DISARM,
{ATTR_ENTITY_ID: "alarm_control_panel.test_alarm"},
blocking=True,
)
mock_concord232_client.disarm.assert_called_once_with(None)
async def test_alarm_disarm_with_code(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test disarm service with code."""
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG_WITH_CODE)
await hass.async_block_till_done()
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_DISARM,
{
ATTR_ENTITY_ID: "alarm_control_panel.test_alarm",
ATTR_CODE: "1234",
},
blocking=True,
)
mock_concord232_client.disarm.assert_called_once_with("1234")
async def test_alarm_disarm_invalid_code(
hass: HomeAssistant,
mock_concord232_client: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test disarm service with invalid code."""
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG_WITH_CODE)
await hass.async_block_till_done()
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_DISARM,
{
ATTR_ENTITY_ID: "alarm_control_panel.test_alarm",
ATTR_CODE: "9999",
},
blocking=True,
)
mock_concord232_client.disarm.assert_not_called()
assert "Invalid code given" in caplog.text
@pytest.mark.parametrize(
("service", "expected_arm_call"),
[
(SERVICE_ALARM_ARM_HOME, "stay"),
(SERVICE_ALARM_ARM_AWAY, "away"),
],
)
async def test_alarm_arm(
hass: HomeAssistant,
mock_concord232_client: MagicMock,
service: str,
expected_arm_call: str,
) -> None:
"""Test arm service."""
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG_WITH_CODE)
await hass.async_block_till_done()
await hass.services.async_call(
ALARM_DOMAIN,
service,
{
ATTR_ENTITY_ID: "alarm_control_panel.test_alarm",
ATTR_CODE: "1234",
},
blocking=True,
)
mock_concord232_client.arm.assert_called_once_with(expected_arm_call)
async def test_alarm_arm_home_silent_mode(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test arm home service with silent mode."""
config_with_code = VALID_CONFIG_SILENT_MODE.copy()
config_with_code[ALARM_DOMAIN][CONF_CODE] = "1234"
await async_setup_component(hass, ALARM_DOMAIN, config_with_code)
await hass.async_block_till_done()
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_ARM_HOME,
{
ATTR_ENTITY_ID: "alarm_control_panel.test_alarm",
ATTR_CODE: "1234",
},
blocking=True,
)
mock_concord232_client.arm.assert_called_once_with("stay", "silent")
async def test_update_state_disarmed(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test update when alarm is disarmed."""
mock_concord232_client.list_partitions.return_value = [{"arming_level": "Off"}]
mock_concord232_client.list_zones.return_value = [
{"number": 1, "name": "Zone 1", "state": "Normal"},
]
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
state = hass.states.get("alarm_control_panel.test_alarm")
assert state.state == AlarmControlPanelState.DISARMED
@pytest.mark.parametrize(
("arming_level", "expected_state"),
[
("Home", AlarmControlPanelState.ARMED_HOME),
("Away", AlarmControlPanelState.ARMED_AWAY),
],
)
async def test_update_state_armed(
hass: HomeAssistant,
mock_concord232_client: MagicMock,
freezer: FrozenDateTimeFactory,
arming_level: str,
expected_state: str,
) -> None:
"""Test update when alarm is armed."""
mock_concord232_client.list_partitions.return_value = [
{"arming_level": arming_level}
]
mock_concord232_client.partitions = (
mock_concord232_client.list_partitions.return_value
)
mock_concord232_client.list_zones.return_value = [
{"number": 1, "name": "Zone 1", "state": "Normal"},
]
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
# Trigger update
freezer.tick(10)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("alarm_control_panel.test_alarm")
assert state.state == expected_state
async def test_update_connection_error(
hass: HomeAssistant,
mock_concord232_client: MagicMock,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test update with connection error."""
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
mock_concord232_client.list_partitions.side_effect = (
requests.exceptions.ConnectionError("Connection failed")
)
freezer.tick(10)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert "Unable to connect to" in caplog.text
async def test_update_no_partitions(
hass: HomeAssistant,
mock_concord232_client: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test update when no partitions are available."""
mock_concord232_client.list_partitions.return_value = []
await async_setup_component(hass, ALARM_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
assert "Concord232 reports no partitions" in caplog.text
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/concord232/test_alarm_control_panel.py",
"license": "Apache License 2.0",
"lines": 232,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/concord232/test_binary_sensor.py | """Tests for the Concord232 binary sensor platform."""
from __future__ import annotations
import datetime
from unittest.mock import MagicMock
from freezegun.api import FrozenDateTimeFactory
import pytest
import requests
from homeassistant.components.binary_sensor import (
DOMAIN as BINARY_SENSOR_DOMAIN,
BinarySensorDeviceClass,
)
from homeassistant.components.concord232.binary_sensor import (
CONF_EXCLUDE_ZONES,
CONF_ZONE_TYPES,
)
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import async_fire_time_changed
VALID_CONFIG = {
BINARY_SENSOR_DOMAIN: {
"platform": "concord232",
CONF_HOST: "localhost",
CONF_PORT: 5007,
}
}
VALID_CONFIG_WITH_EXCLUDE = {
BINARY_SENSOR_DOMAIN: {
"platform": "concord232",
CONF_HOST: "localhost",
CONF_PORT: 5007,
CONF_EXCLUDE_ZONES: [2],
}
}
VALID_CONFIG_WITH_ZONE_TYPES = {
BINARY_SENSOR_DOMAIN: {
"platform": "concord232",
CONF_HOST: "localhost",
CONF_PORT: 5007,
CONF_ZONE_TYPES: {1: "door", 2: "window"},
}
}
async def test_setup_platform(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test platform setup."""
await async_setup_component(hass, BINARY_SENSOR_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
state1 = hass.states.get("binary_sensor.zone_1")
state2 = hass.states.get("binary_sensor.zone_2")
assert state1 is not None
assert state2 is not None
assert state1.state == "off"
assert state2.state == "off"
async def test_setup_platform_connection_error(
hass: HomeAssistant,
mock_concord232_client: MagicMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test platform setup with connection error."""
mock_concord232_client.list_zones.side_effect = requests.exceptions.ConnectionError(
"Connection failed"
)
await async_setup_component(hass, BINARY_SENSOR_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
assert "Unable to connect to Concord232" in caplog.text
assert hass.states.get("binary_sensor.zone_1") is None
async def test_setup_with_exclude_zones(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test platform setup with excluded zones."""
await async_setup_component(hass, BINARY_SENSOR_DOMAIN, VALID_CONFIG_WITH_EXCLUDE)
await hass.async_block_till_done()
state1 = hass.states.get("binary_sensor.zone_1")
state2 = hass.states.get("binary_sensor.zone_2")
assert state1 is not None
assert state2 is None # Zone 2 should be excluded
async def test_setup_with_zone_types(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test platform setup with custom zone types."""
await async_setup_component(
hass, BINARY_SENSOR_DOMAIN, VALID_CONFIG_WITH_ZONE_TYPES
)
await hass.async_block_till_done()
state1 = hass.states.get("binary_sensor.zone_1")
state2 = hass.states.get("binary_sensor.zone_2")
assert state1 is not None
assert state2 is not None
# Check device class is set correctly
assert state1.attributes.get("device_class") == BinarySensorDeviceClass.DOOR
assert state2.attributes.get("device_class") == BinarySensorDeviceClass.WINDOW
async def test_zone_state_faulted(
hass: HomeAssistant, mock_concord232_client: MagicMock
) -> None:
"""Test zone state when faulted."""
mock_concord232_client.list_zones.return_value = [
{"number": 1, "name": "Zone 1", "state": "Faulted"},
]
mock_concord232_client.zones = mock_concord232_client.list_zones.return_value
await async_setup_component(hass, BINARY_SENSOR_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.zone_1")
assert state.state == "on" # Faulted state means on (faulted)
@pytest.mark.freeze_time("2023-10-21")
async def test_zone_update_refresh(
hass: HomeAssistant,
mock_concord232_client: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that zone updates refresh the client data."""
mock_concord232_client.list_zones.return_value = [
{"number": 1, "name": "Zone 1", "state": "Normal"},
]
mock_concord232_client.zones = mock_concord232_client.list_zones.return_value
await async_setup_component(hass, BINARY_SENSOR_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.zone_1").state == "off"
# Update zone state - need to update both return_value and zones attribute
new_zones = [
{"number": 1, "name": "Zone 1", "state": "Faulted"},
]
mock_concord232_client.list_zones.return_value = new_zones
mock_concord232_client.zones = new_zones
freezer.tick(datetime.timedelta(seconds=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
freezer.tick(datetime.timedelta(seconds=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.zone_1")
assert state.state == "on"
@pytest.mark.parametrize(
("sensor_name", "entity_id", "expected_device_class"),
[
(
"MOTION Sensor",
"binary_sensor.motion_sensor",
BinarySensorDeviceClass.MOTION,
),
("SMOKE Sensor", "binary_sensor.smoke_sensor", BinarySensorDeviceClass.SMOKE),
(
"Unknown Sensor",
"binary_sensor.unknown_sensor",
BinarySensorDeviceClass.OPENING,
),
],
)
async def test_device_class(
hass: HomeAssistant,
mock_concord232_client: MagicMock,
sensor_name: str,
entity_id: str,
expected_device_class: BinarySensorDeviceClass,
) -> None:
"""Test zone type detection for motion sensor."""
mock_concord232_client.list_zones.return_value = [
{"number": 1, "name": sensor_name, "state": "Normal"},
]
mock_concord232_client.zones = mock_concord232_client.list_zones.return_value
await async_setup_component(hass, BINARY_SENSOR_DOMAIN, VALID_CONFIG)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state.attributes.get("device_class") == expected_device_class
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/concord232/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 164,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/duckdns/test_config_flow.py | """Test the Duck DNS config flow."""
from unittest.mock import AsyncMock
import pytest
from homeassistant.components.duckdns import DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_DOMAIN
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import issue_registry as ir
from homeassistant.setup import async_setup_component
from .conftest import NEW_TOKEN, TEST_SUBDOMAIN, TEST_TOKEN
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_update_duckdns")
async def test_form(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: "123e4567-e89b-12d3-a456-426614174000",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"{TEST_SUBDOMAIN}.duckdns.org"
assert result["data"] == {
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: TEST_TOKEN,
}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_update_duckdns")
async def test_form_already_configured(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test we abort if already configured."""
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["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: "123e4567-e89b-12d3-a456-426614174000",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("side_effect", "text_error"),
[
([ValueError, True], "unknown"),
([False, True], "update_failed"),
],
)
async def test_form_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_update_duckdns: AsyncMock,
side_effect: list[Exception | bool],
text_error: str,
) -> None:
"""Test we handle errors."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_update_duckdns.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: TEST_TOKEN,
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: TEST_TOKEN,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"{TEST_SUBDOMAIN}.duckdns.org"
assert result["data"] == {
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: TEST_TOKEN,
}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_update_duckdns")
async def test_import(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test import flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: TEST_TOKEN,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"{TEST_SUBDOMAIN}.duckdns.org"
assert result["data"] == {
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: TEST_TOKEN,
}
assert len(mock_setup_entry.mock_calls) == 1
assert issue_registry.async_get_issue(
domain=HOMEASSISTANT_DOMAIN,
issue_id=f"deprecated_yaml_{DOMAIN}",
)
async def test_import_failed(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
issue_registry: ir.IssueRegistry,
mock_update_duckdns: AsyncMock,
) -> None:
"""Test import flow failed."""
mock_update_duckdns.return_value = False
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: TEST_TOKEN,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "update_failed"
assert len(mock_setup_entry.mock_calls) == 0
assert issue_registry.async_get_issue(
domain=DOMAIN,
issue_id="deprecated_yaml_import_issue_error",
)
async def test_import_exception(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
issue_registry: ir.IssueRegistry,
mock_update_duckdns: AsyncMock,
) -> None:
"""Test import flow failed unknown."""
mock_update_duckdns.side_effect = ValueError
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_DOMAIN: TEST_SUBDOMAIN,
CONF_ACCESS_TOKEN: TEST_TOKEN,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unknown"
assert len(mock_setup_entry.mock_calls) == 0
assert issue_registry.async_get_issue(
domain=DOMAIN,
issue_id="deprecated_yaml_import_issue_error",
)
@pytest.mark.usefixtures("mock_update_duckdns")
async def test_init_import_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
) -> None:
"""Test yaml triggers import flow."""
await async_setup_component(
hass,
DOMAIN,
{"duckdns": {CONF_DOMAIN: TEST_SUBDOMAIN, CONF_ACCESS_TOKEN: TEST_TOKEN}},
)
assert len(mock_setup_entry.mock_calls) == 1
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
@pytest.mark.usefixtures("mock_update_duckdns", "mock_setup_entry")
async def test_flow_reconfigure(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test reconfigure flow."""
config_entry.add_to_hass(hass)
result = await config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: NEW_TOKEN},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert config_entry.data[CONF_ACCESS_TOKEN] == NEW_TOKEN
@pytest.mark.parametrize(
("side_effect", "text_error"),
[
([ValueError, True], "unknown"),
([False, True], "update_failed"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_flow_reconfigure_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_update_duckdns: AsyncMock,
config_entry: MockConfigEntry,
side_effect: list[Exception | bool],
text_error: str,
) -> None:
"""Test we handle errors."""
config_entry.add_to_hass(hass)
result = await config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_update_duckdns.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: NEW_TOKEN},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_ACCESS_TOKEN: NEW_TOKEN},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert config_entry.data[CONF_ACCESS_TOKEN] == NEW_TOKEN
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/duckdns/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 238,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/energy/test_data.py | """Test energy data storage and migration."""
import pytest
import voluptuous as vol
from homeassistant.components.energy.data import (
ENERGY_SOURCE_SCHEMA,
FLOW_FROM_GRID_SOURCE_SCHEMA,
POWER_CONFIG_SCHEMA,
EnergyManager,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import storage
async def test_energy_preferences_no_migration_needed(hass: HomeAssistant) -> None:
"""Test that new data format doesn't get migrated."""
# Create new format data (already has device_consumption_water field)
new_data = {
"energy_sources": [],
"device_consumption": [],
"device_consumption_water": [
{"stat_consumption": "sensor.water_meter", "name": "Water heater"}
],
}
# Save data that already has the new field
old_store = storage.Store(hass, 1, "energy", minor_version=1)
await old_store.async_save(new_data)
# Load it with manager
manager = EnergyManager(hass)
await manager.async_initialize()
# Verify the data is unchanged
assert manager.data is not None
assert manager.data["device_consumption_water"] == [
{"stat_consumption": "sensor.water_meter", "name": "Water heater"}
]
async def test_energy_preferences_default(hass: HomeAssistant) -> None:
"""Test default preferences include device_consumption_water."""
defaults = EnergyManager.default_preferences()
assert "energy_sources" in defaults
assert "device_consumption" in defaults
assert "device_consumption_water" in defaults
assert defaults["device_consumption_water"] == []
async def test_energy_preferences_empty_store(hass: HomeAssistant) -> None:
"""Test loading with no existing data."""
manager = EnergyManager(hass)
await manager.async_initialize()
# Verify data is None when no existing data
assert manager.data is None
async def test_energy_preferences_migration_from_old_version(
hass: HomeAssistant,
) -> None:
"""Test that device_consumption_water is added when migrating from v1.1 to v1.2."""
# Create version 1.1 data without device_consumption_water (old version)
old_data = {
"energy_sources": [],
"device_consumption": [],
}
# Save with old version (1.1) - migration will run to upgrade to 1.2
old_store = storage.Store(hass, 1, "energy", minor_version=1)
await old_store.async_save(old_data)
# Load with manager - should trigger migration
manager = EnergyManager(hass)
await manager.async_initialize()
# Verify the field was added by migration
assert manager.data is not None
assert "device_consumption_water" in manager.data
assert manager.data["device_consumption_water"] == []
async def test_battery_power_config_inverted_sets_stat_rate(
hass: HomeAssistant,
) -> None:
"""Test that battery with inverted power_config sets stat_rate to generated entity_id."""
manager = EnergyManager(hass)
await manager.async_initialize()
manager.data = manager.default_preferences()
await manager.async_update(
{
"energy_sources": [
{
"type": "battery",
"stat_energy_from": "sensor.battery_energy_from",
"stat_energy_to": "sensor.battery_energy_to",
"power_config": {
"stat_rate_inverted": "sensor.battery_power",
},
}
],
}
)
# Verify stat_rate was set to the expected entity_id
assert manager.data is not None
assert len(manager.data["energy_sources"]) == 1
source = manager.data["energy_sources"][0]
assert source["stat_rate"] == "sensor.battery_power_inverted"
# Verify power_config is preserved
assert source["power_config"] == {"stat_rate_inverted": "sensor.battery_power"}
async def test_battery_power_config_two_sensors_sets_stat_rate(
hass: HomeAssistant,
) -> None:
"""Test that battery with two-sensor power_config sets stat_rate."""
manager = EnergyManager(hass)
await manager.async_initialize()
manager.data = manager.default_preferences()
await manager.async_update(
{
"energy_sources": [
{
"type": "battery",
"stat_energy_from": "sensor.battery_energy_from",
"stat_energy_to": "sensor.battery_energy_to",
"power_config": {
"stat_rate_from": "sensor.battery_discharge",
"stat_rate_to": "sensor.battery_charge",
},
}
],
}
)
assert manager.data is not None
source = manager.data["energy_sources"][0]
# Entity ID includes discharge sensor name to avoid collisions
assert (
source["stat_rate"]
== "sensor.energy_battery_battery_discharge_battery_charge_net_power"
)
async def test_grid_power_config_inverted_sets_stat_rate(
hass: HomeAssistant,
) -> None:
"""Test that grid with inverted power_config sets stat_rate."""
manager = EnergyManager(hass)
await manager.async_initialize()
manager.data = manager.default_preferences()
await manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_energy_from": "sensor.grid_import",
"stat_energy_to": None,
"stat_cost": None,
"stat_compensation": None,
"entity_energy_price": None,
"number_energy_price": None,
"entity_energy_price_export": None,
"number_energy_price_export": None,
"power_config": {
"stat_rate_inverted": "sensor.grid_power",
},
"cost_adjustment_day": 0,
}
],
}
)
assert manager.data is not None
grid_source = manager.data["energy_sources"][0]
assert grid_source["stat_rate"] == "sensor.grid_power_inverted"
async def test_power_config_standard_uses_stat_rate_directly(
hass: HomeAssistant,
) -> None:
"""Test that power_config with standard stat_rate uses it directly."""
manager = EnergyManager(hass)
await manager.async_initialize()
manager.data = manager.default_preferences()
await manager.async_update(
{
"energy_sources": [
{
"type": "battery",
"stat_energy_from": "sensor.battery_energy_from",
"stat_energy_to": "sensor.battery_energy_to",
"power_config": {
"stat_rate": "sensor.battery_power",
},
}
],
}
)
assert manager.data is not None
source = manager.data["energy_sources"][0]
# stat_rate should be set directly from power_config.stat_rate
assert source["stat_rate"] == "sensor.battery_power"
async def test_battery_without_power_config_unchanged(hass: HomeAssistant) -> None:
"""Test that battery without power_config is unchanged."""
manager = EnergyManager(hass)
await manager.async_initialize()
manager.data = manager.default_preferences()
await manager.async_update(
{
"energy_sources": [
{
"type": "battery",
"stat_energy_from": "sensor.battery_energy_from",
"stat_energy_to": "sensor.battery_energy_to",
"stat_rate": "sensor.battery_power",
}
],
}
)
assert manager.data is not None
source = manager.data["energy_sources"][0]
assert source["stat_rate"] == "sensor.battery_power"
assert "power_config" not in source
async def test_power_config_takes_precedence_over_stat_rate(
hass: HomeAssistant,
) -> None:
"""Test that power_config takes precedence when both are provided."""
manager = EnergyManager(hass)
await manager.async_initialize()
manager.data = manager.default_preferences()
# Frontend sends both stat_rate and power_config
await manager.async_update(
{
"energy_sources": [
{
"type": "battery",
"stat_energy_from": "sensor.battery_energy_from",
"stat_energy_to": "sensor.battery_energy_to",
"stat_rate": "sensor.battery_power", # This should be ignored
"power_config": {
"stat_rate_inverted": "sensor.battery_power",
},
}
],
}
)
assert manager.data is not None
source = manager.data["energy_sources"][0]
# stat_rate should be overwritten to point to the generated inverted sensor
assert source["stat_rate"] == "sensor.battery_power_inverted"
async def test_power_config_validation_empty() -> None:
"""Test that empty power_config raises validation error."""
with pytest.raises(vol.Invalid, match="power_config must have at least one option"):
POWER_CONFIG_SCHEMA({})
async def test_power_config_validation_multiple_methods() -> None:
"""Test that power_config with multiple methods raises validation error."""
# Both stat_rate and stat_rate_inverted (should fail due to Exclusive)
with pytest.raises(vol.Invalid):
POWER_CONFIG_SCHEMA(
{
"stat_rate": "sensor.power",
"stat_rate_inverted": "sensor.power",
}
)
# Both stat_rate and stat_rate_from/to (should fail due to Exclusive)
with pytest.raises(vol.Invalid):
POWER_CONFIG_SCHEMA(
{
"stat_rate": "sensor.power",
"stat_rate_from": "sensor.discharge",
"stat_rate_to": "sensor.charge",
}
)
# Both stat_rate_inverted and stat_rate_from/to (should fail due to Exclusive)
with pytest.raises(vol.Invalid):
POWER_CONFIG_SCHEMA(
{
"stat_rate_inverted": "sensor.power",
"stat_rate_from": "sensor.discharge",
"stat_rate_to": "sensor.charge",
}
)
async def test_flow_from_validation_multiple_prices() -> None:
"""Test that flow_from validation rejects both entity and number price."""
# Both entity_energy_price and number_energy_price should fail
with pytest.raises(
vol.Invalid, match="Define either an entity or a fixed number for the price"
):
FLOW_FROM_GRID_SOURCE_SCHEMA(
{
"stat_energy_from": "sensor.energy",
"entity_energy_price": "sensor.price",
"number_energy_price": 0.15,
}
)
async def test_energy_sources_validation_multiple_grids() -> None:
"""Test that multiple grid sources are allowed (like batteries)."""
# Multiple grid sources should now pass validation
result = ENERGY_SOURCE_SCHEMA(
[
{
"type": "grid",
"stat_energy_from": "sensor.grid1_import",
"stat_energy_to": "sensor.grid1_export",
"cost_adjustment_day": 0,
},
{
"type": "grid",
"stat_energy_from": "sensor.grid2_import",
"stat_energy_to": None,
"cost_adjustment_day": 0,
},
]
)
assert len(result) == 2
assert result[0]["stat_energy_from"] == "sensor.grid1_import"
assert result[1]["stat_energy_from"] == "sensor.grid2_import"
async def test_power_config_validation_passes() -> None:
"""Test that valid power_config passes validation."""
# Test standard stat_rate
result = POWER_CONFIG_SCHEMA({"stat_rate": "sensor.power"})
assert result == {"stat_rate": "sensor.power"}
# Test inverted
result = POWER_CONFIG_SCHEMA({"stat_rate_inverted": "sensor.power"})
assert result == {"stat_rate_inverted": "sensor.power"}
# Test two-sensor combined
result = POWER_CONFIG_SCHEMA(
{"stat_rate_from": "sensor.discharge", "stat_rate_to": "sensor.charge"}
)
assert result == {
"stat_rate_from": "sensor.discharge",
"stat_rate_to": "sensor.charge",
}
async def test_grid_power_config_standard_stat_rate(hass: HomeAssistant) -> None:
"""Test that grid with power_config using standard stat_rate works correctly."""
manager = EnergyManager(hass)
await manager.async_initialize()
manager.data = manager.default_preferences()
await manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_energy_from": "sensor.grid_import",
"stat_energy_to": None,
"stat_cost": None,
"stat_compensation": None,
"entity_energy_price": None,
"number_energy_price": None,
"entity_energy_price_export": None,
"number_energy_price_export": None,
"power_config": {
"stat_rate": "sensor.grid_power",
},
"cost_adjustment_day": 0,
}
],
}
)
assert manager.data is not None
grid_source = manager.data["energy_sources"][0]
# stat_rate should be set directly from power_config.stat_rate
assert grid_source["stat_rate"] == "sensor.grid_power"
async def test_grid_new_format_validates_correctly() -> None:
"""Test that new unified grid format validates correctly."""
# Valid grid source with import and export
result = ENERGY_SOURCE_SCHEMA(
[
{
"type": "grid",
"stat_energy_from": "sensor.energy_import",
"stat_energy_to": "sensor.energy_export",
"stat_cost": None,
"stat_compensation": None,
"entity_energy_price": None,
"number_energy_price": 0.15,
"entity_energy_price_export": None,
"number_energy_price_export": 0.08,
"cost_adjustment_day": 0,
},
]
)
assert len(result) == 1
assert result[0]["stat_energy_from"] == "sensor.energy_import"
assert result[0]["stat_energy_to"] == "sensor.energy_export"
# Valid grid source with import only (no export)
result = ENERGY_SOURCE_SCHEMA(
[
{
"type": "grid",
"stat_energy_from": "sensor.energy_import",
"stat_energy_to": None,
"cost_adjustment_day": 0,
},
]
)
assert result[0]["stat_energy_to"] is None
async def test_async_update_when_data_is_none(hass: HomeAssistant) -> None:
"""Test async_update when manager.data is None uses default preferences."""
manager = EnergyManager(hass)
await manager.async_initialize()
# Ensure data is None (empty store)
assert manager.data is None
# Call async_update - should use default_preferences as base
await manager.async_update(
{
"energy_sources": [
{
"type": "solar",
"stat_energy_from": "sensor.solar_energy",
"config_entry_solar_forecast": None,
}
],
}
)
# Verify data was created with the update and default fields
assert manager.data is not None
assert len(manager.data["energy_sources"]) == 1
assert manager.data["energy_sources"][0]["type"] == "solar"
# Default fields should be present
assert manager.data["device_consumption"] == []
assert manager.data["device_consumption_water"] == []
async def test_grid_power_without_power_config(hass: HomeAssistant) -> None:
"""Test that grid without power_config is preserved unchanged."""
manager = EnergyManager(hass)
await manager.async_initialize()
manager.data = manager.default_preferences()
await manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_energy_from": "sensor.grid_import",
"stat_energy_to": None,
"stat_cost": None,
"stat_compensation": None,
"entity_energy_price": None,
"number_energy_price": None,
"entity_energy_price_export": None,
"number_energy_price_export": None,
# No power_config, just stat_rate directly
"stat_rate": "sensor.grid_power",
"cost_adjustment_day": 0,
}
],
}
)
assert manager.data is not None
grid_source = manager.data["energy_sources"][0]
# stat_rate should be preserved unchanged
assert grid_source["stat_rate"] == "sensor.grid_power"
assert "power_config" not in grid_source
async def test_grid_migration_single_import_export(hass: HomeAssistant) -> None:
"""Test migration from legacy format with 1 import + 1 export creates 1 grid."""
# Create legacy format data (v1.2) with flow_from/flow_to arrays
old_data = {
"energy_sources": [
{
"type": "grid",
"flow_from": [
{
"stat_energy_from": "sensor.grid_import",
"stat_cost": "sensor.grid_cost",
"entity_energy_price": None,
"number_energy_price": None,
}
],
"flow_to": [
{
"stat_energy_to": "sensor.grid_export",
"stat_compensation": None,
"entity_energy_price": "sensor.sell_price",
"number_energy_price": None,
}
],
"cost_adjustment_day": 0.5,
}
],
"device_consumption": [],
"device_consumption_water": [],
}
# Save with old version (1.2) - migration will run to upgrade to 1.3
old_store = storage.Store(hass, 1, "energy", minor_version=2)
await old_store.async_save(old_data)
# Load with manager - should trigger migration
manager = EnergyManager(hass)
await manager.async_initialize()
# Verify migration created unified grid source
assert manager.data is not None
assert len(manager.data["energy_sources"]) == 1
grid = manager.data["energy_sources"][0]
assert grid["type"] == "grid"
assert grid["stat_energy_from"] == "sensor.grid_import"
assert grid["stat_energy_to"] == "sensor.grid_export"
assert grid["stat_cost"] == "sensor.grid_cost"
assert grid["stat_compensation"] is None
assert grid["entity_energy_price"] is None
assert grid["entity_energy_price_export"] == "sensor.sell_price"
assert grid["cost_adjustment_day"] == 0.5
# Should not have legacy fields
assert "flow_from" not in grid
assert "flow_to" not in grid
async def test_grid_migration_multiple_imports_exports_paired(
hass: HomeAssistant,
) -> None:
"""Test migration with 2 imports + 2 exports creates 2 paired grids."""
old_data = {
"energy_sources": [
{
"type": "grid",
"flow_from": [
{
"stat_energy_from": "sensor.grid_import_1",
"stat_cost": None,
"entity_energy_price": None,
"number_energy_price": 0.15,
},
{
"stat_energy_from": "sensor.grid_import_2",
"stat_cost": None,
"entity_energy_price": None,
"number_energy_price": 0.20,
},
],
"flow_to": [
{
"stat_energy_to": "sensor.grid_export_1",
"stat_compensation": None,
"entity_energy_price": None,
"number_energy_price": 0.08,
},
{
"stat_energy_to": "sensor.grid_export_2",
"stat_compensation": None,
"entity_energy_price": None,
"number_energy_price": 0.05,
},
],
"cost_adjustment_day": 0,
}
],
"device_consumption": [],
"device_consumption_water": [],
}
old_store = storage.Store(hass, 1, "energy", minor_version=2)
await old_store.async_save(old_data)
manager = EnergyManager(hass)
await manager.async_initialize()
assert manager.data is not None
assert len(manager.data["energy_sources"]) == 2
# First grid: paired import_1 with export_1
grid1 = manager.data["energy_sources"][0]
assert grid1["stat_energy_from"] == "sensor.grid_import_1"
assert grid1["stat_energy_to"] == "sensor.grid_export_1"
assert grid1["number_energy_price"] == 0.15
assert grid1["number_energy_price_export"] == 0.08
# Second grid: paired import_2 with export_2
grid2 = manager.data["energy_sources"][1]
assert grid2["stat_energy_from"] == "sensor.grid_import_2"
assert grid2["stat_energy_to"] == "sensor.grid_export_2"
assert grid2["number_energy_price"] == 0.20
assert grid2["number_energy_price_export"] == 0.05
async def test_grid_migration_more_imports_than_exports(hass: HomeAssistant) -> None:
"""Test migration with 3 imports + 1 export creates 3 grids (first has export)."""
old_data = {
"energy_sources": [
{
"type": "grid",
"flow_from": [
{"stat_energy_from": "sensor.import_1"},
{"stat_energy_from": "sensor.import_2"},
{"stat_energy_from": "sensor.import_3"},
],
"flow_to": [
{"stat_energy_to": "sensor.export_1"},
],
"cost_adjustment_day": 0,
}
],
"device_consumption": [],
"device_consumption_water": [],
}
old_store = storage.Store(hass, 1, "energy", minor_version=2)
await old_store.async_save(old_data)
manager = EnergyManager(hass)
await manager.async_initialize()
assert manager.data is not None
assert len(manager.data["energy_sources"]) == 3
# First grid: has both import and export
grid1 = manager.data["energy_sources"][0]
assert grid1["stat_energy_from"] == "sensor.import_1"
assert grid1["stat_energy_to"] == "sensor.export_1"
# Second and third grids: import only
grid2 = manager.data["energy_sources"][1]
assert grid2["stat_energy_from"] == "sensor.import_2"
assert grid2["stat_energy_to"] is None
grid3 = manager.data["energy_sources"][2]
assert grid3["stat_energy_from"] == "sensor.import_3"
assert grid3["stat_energy_to"] is None
async def test_grid_migration_with_power(hass: HomeAssistant) -> None:
"""Test migration preserves power config and stat_rate from first grid.
Note: Migration preserves the original stat_rate value from the legacy power array.
The stat_rate regeneration from power_config only happens during async_update()
for new data submissions, not during storage migration.
"""
old_data = {
"energy_sources": [
{
"type": "grid",
"flow_from": [
{"stat_energy_from": "sensor.grid_import"},
],
"flow_to": [
{"stat_energy_to": "sensor.grid_export"},
],
"power": [
{
"stat_rate": "sensor.grid_power",
"power_config": {"stat_rate_inverted": "sensor.grid_power"},
}
],
"cost_adjustment_day": 0,
}
],
"device_consumption": [],
"device_consumption_water": [],
}
old_store = storage.Store(hass, 1, "energy", minor_version=2)
await old_store.async_save(old_data)
manager = EnergyManager(hass)
await manager.async_initialize()
assert manager.data is not None
grid = manager.data["energy_sources"][0]
# Verify power_config is preserved
assert grid["power_config"] == {"stat_rate_inverted": "sensor.grid_power"}
# Migration preserves the original stat_rate value from the legacy power array
# (stat_rate regeneration from power_config only happens in async_update)
assert grid["stat_rate"] == "sensor.grid_power"
async def test_grid_migration_import_only(hass: HomeAssistant) -> None:
"""Test migration with imports but no exports creates import-only grids."""
old_data = {
"energy_sources": [
{
"type": "grid",
"flow_from": [
{"stat_energy_from": "sensor.grid_import"},
],
"flow_to": [],
"cost_adjustment_day": 0,
}
],
"device_consumption": [],
"device_consumption_water": [],
}
old_store = storage.Store(hass, 1, "energy", minor_version=2)
await old_store.async_save(old_data)
manager = EnergyManager(hass)
await manager.async_initialize()
assert manager.data is not None
assert len(manager.data["energy_sources"]) == 1
grid = manager.data["energy_sources"][0]
assert grid["stat_energy_from"] == "sensor.grid_import"
assert grid["stat_energy_to"] is None
async def test_grid_migration_power_only(hass: HomeAssistant) -> None:
"""Test migration with only power configured (no import/export meters)."""
old_data = {
"energy_sources": [
{
"type": "grid",
"flow_from": [],
"flow_to": [],
"power": [
{"stat_rate": "sensor.grid_power"},
],
"cost_adjustment_day": 0.5,
}
],
"device_consumption": [],
"device_consumption_water": [],
}
old_store = storage.Store(hass, 1, "energy", minor_version=2)
await old_store.async_save(old_data)
manager = EnergyManager(hass)
await manager.async_initialize()
assert manager.data is not None
assert len(manager.data["energy_sources"]) == 1
grid = manager.data["energy_sources"][0]
assert grid["type"] == "grid"
# No import or export meters
assert grid["stat_energy_from"] is None
assert grid["stat_energy_to"] is None
# Power is preserved
assert grid["stat_rate"] == "sensor.grid_power"
assert grid["cost_adjustment_day"] == 0.5
async def test_grid_new_format_no_migration_needed(hass: HomeAssistant) -> None:
"""Test that new format data doesn't get migrated."""
new_data = {
"energy_sources": [
{
"type": "grid",
"stat_energy_from": "sensor.grid_import",
"stat_energy_to": "sensor.grid_export",
"stat_cost": None,
"stat_compensation": None,
"entity_energy_price": None,
"number_energy_price": 0.15,
"entity_energy_price_export": None,
"number_energy_price_export": 0.08,
"cost_adjustment_day": 0,
}
],
"device_consumption": [],
"device_consumption_water": [],
}
# Save with current version (1.3)
old_store = storage.Store(hass, 1, "energy", minor_version=3)
await old_store.async_save(new_data)
manager = EnergyManager(hass)
await manager.async_initialize()
assert manager.data is not None
assert len(manager.data["energy_sources"]) == 1
grid = manager.data["energy_sources"][0]
assert grid["stat_energy_from"] == "sensor.grid_import"
assert grid["stat_energy_to"] == "sensor.grid_export"
async def test_grid_validation_single_import_price() -> None:
"""Test that grid validation rejects both entity and number import price."""
with pytest.raises(
vol.Invalid, match="Define either an entity or a fixed number for import price"
):
ENERGY_SOURCE_SCHEMA(
[
{
"type": "grid",
"stat_energy_from": "sensor.grid_import",
"entity_energy_price": "sensor.price",
"number_energy_price": 0.15,
"cost_adjustment_day": 0,
}
]
)
async def test_grid_validation_single_export_price() -> None:
"""Test that grid validation rejects both entity and number export price."""
with pytest.raises(
vol.Invalid, match="Define either an entity or a fixed number for export price"
):
ENERGY_SOURCE_SCHEMA(
[
{
"type": "grid",
"stat_energy_from": "sensor.grid_import",
"stat_energy_to": "sensor.grid_export",
"entity_energy_price_export": "sensor.sell_price",
"number_energy_price_export": 0.08,
"cost_adjustment_day": 0,
}
]
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/energy/test_data.py",
"license": "Apache License 2.0",
"lines": 732,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/energy/test_validate_power.py | """Test power stat validation."""
import pytest
from homeassistant.components.energy import validate
from homeassistant.components.energy.data import EnergyManager
from homeassistant.const import UnitOfPower
from homeassistant.core import HomeAssistant
POWER_UNITS_STRING = ", ".join(tuple(UnitOfPower))
@pytest.fixture(autouse=True)
async def setup_energy_for_validation(
mock_energy_manager: EnergyManager,
) -> EnergyManager:
"""Ensure energy manager is set up for validation tests."""
return mock_energy_manager
async def test_validation_grid_power_valid(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating grid with valid power sensor."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "sensor.grid_power",
"cost_adjustment_day": 0.0,
}
]
}
)
hass.states.async_set(
"sensor.grid_power",
"1.5",
{
"device_class": "power",
"unit_of_measurement": UnitOfPower.KILO_WATT,
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [[]],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_grid_power_wrong_unit(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating grid with power sensor having wrong unit."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "sensor.grid_power",
"cost_adjustment_day": 0.0,
}
]
}
)
hass.states.async_set(
"sensor.grid_power",
"1.5",
{
"device_class": "power",
"unit_of_measurement": "beers",
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "entity_unexpected_unit_power",
"affected_entities": {("sensor.grid_power", "beers")},
"translation_placeholders": {"power_units": POWER_UNITS_STRING},
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_grid_power_wrong_state_class(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating grid with power sensor having wrong state class."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "sensor.grid_power",
"cost_adjustment_day": 0.0,
}
]
}
)
hass.states.async_set(
"sensor.grid_power",
"1.5",
{
"device_class": "power",
"unit_of_measurement": UnitOfPower.KILO_WATT,
"state_class": "total_increasing",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "entity_unexpected_state_class",
"affected_entities": {("sensor.grid_power", "total_increasing")},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_grid_power_entity_missing(
hass: HomeAssistant, mock_energy_manager
) -> None:
"""Test validating grid with missing power sensor."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "sensor.missing_power",
"cost_adjustment_day": 0.0,
}
]
}
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "statistics_not_defined",
"affected_entities": {("sensor.missing_power", None)},
"translation_placeholders": None,
},
{
"type": "entity_not_defined",
"affected_entities": {("sensor.missing_power", None)},
"translation_placeholders": None,
},
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_grid_power_entity_unavailable(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating grid with unavailable power sensor."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "sensor.unavailable_power",
"cost_adjustment_day": 0.0,
}
]
}
)
hass.states.async_set("sensor.unavailable_power", "unavailable", {})
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "entity_unavailable",
"affected_entities": {("sensor.unavailable_power", "unavailable")},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_grid_power_entity_non_numeric(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating grid with non-numeric power sensor."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "sensor.non_numeric_power",
"cost_adjustment_day": 0.0,
}
]
}
)
hass.states.async_set(
"sensor.non_numeric_power",
"not_a_number",
{
"device_class": "power",
"unit_of_measurement": UnitOfPower.KILO_WATT,
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "entity_state_non_numeric",
"affected_entities": {("sensor.non_numeric_power", "not_a_number")},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_grid_power_wrong_device_class(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating grid with power sensor having wrong device class."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "sensor.wrong_device_class_power",
"cost_adjustment_day": 0.0,
}
]
}
)
hass.states.async_set(
"sensor.wrong_device_class_power",
"1.5",
{
"device_class": "energy",
"unit_of_measurement": "kWh",
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "entity_unexpected_device_class",
"affected_entities": {
("sensor.wrong_device_class_power", "energy")
},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_grid_power_different_units(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating grid with power sensors using different valid units."""
# With unified format, each grid has one power sensor, so we use two grids
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "sensor.power_watt",
"cost_adjustment_day": 0.0,
},
{
"type": "grid",
"stat_rate": "sensor.power_milliwatt",
"cost_adjustment_day": 0.0,
},
]
}
)
hass.states.async_set(
"sensor.power_watt",
"1500",
{
"device_class": "power",
"unit_of_measurement": UnitOfPower.WATT,
"state_class": "measurement",
},
)
hass.states.async_set(
"sensor.power_milliwatt",
"1500000",
{
"device_class": "power",
"unit_of_measurement": UnitOfPower.MILLIWATT,
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [[], []],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_grid_power_external_statistics(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating grid with external power statistics (non-entity)."""
mock_get_metadata["external:power_stat"] = None
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "external:power_stat",
"cost_adjustment_day": 0.0,
}
]
}
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "statistics_not_defined",
"affected_entities": {("external:power_stat", None)},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_grid_power_recorder_untracked(
hass: HomeAssistant, mock_energy_manager, mock_is_entity_recorded, mock_get_metadata
) -> None:
"""Test validating grid with power sensor not tracked by recorder."""
mock_is_entity_recorded["sensor.untracked_power"] = False
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "grid",
"stat_rate": "sensor.untracked_power",
"cost_adjustment_day": 0.0,
}
]
}
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "recorder_untracked",
"affected_entities": {("sensor.untracked_power", None)},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/energy/test_validate_power.py",
"license": "Apache License 2.0",
"lines": 366,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/energyid/test_config_flow.py | """Test EnergyID config flow."""
from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch
from aiohttp import ClientError, ClientResponseError
import pytest
from homeassistant import config_entries
from homeassistant.components.energyid.config_flow import EnergyIDConfigFlow
from homeassistant.components.energyid.const import (
CONF_DEVICE_ID,
CONF_DEVICE_NAME,
CONF_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET,
DOMAIN,
)
from homeassistant.components.energyid.energyid_sensor_mapping_flow import (
EnergyIDSensorMappingFlowHandler,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
# Test constants
TEST_PROVISIONING_KEY = "test_prov_key"
TEST_PROVISIONING_SECRET = "test_prov_secret"
TEST_RECORD_NUMBER = "site_12345"
TEST_RECORD_NAME = "My Test Site"
MAX_POLLING_ATTEMPTS = 60
@pytest.fixture(name="mock_polling_interval", autouse=True)
def mock_polling_interval_fixture() -> Generator[int]:
"""Mock polling interval to 0 for faster tests."""
with patch(
"homeassistant.components.energyid.config_flow.POLLING_INTERVAL", new=0
) as polling_interval:
yield polling_interval
async def test_config_flow_user_step_success_claimed(hass: HomeAssistant) -> None:
"""Test user step where device is already claimed."""
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = TEST_RECORD_NUMBER
mock_client.recordName = TEST_RECORD_NAME
with patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
return_value=mock_client,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == TEST_RECORD_NAME
assert result2["data"][CONF_PROVISIONING_KEY] == TEST_PROVISIONING_KEY
assert result2["data"][CONF_PROVISIONING_SECRET] == TEST_PROVISIONING_SECRET
assert result2["description"] == "add_sensor_mapping_hint"
# Check unique_id is set correctly
entry = hass.config_entries.async_get_entry(result2["result"].entry_id)
# For initially claimed devices, unique_id should be the device_id, not record_number
assert entry.unique_id.startswith("homeassistant_eid_")
assert CONF_DEVICE_ID in entry.data
assert entry.data[CONF_DEVICE_ID] == entry.unique_id
async def test_config_flow_auth_and_claim_step_success(hass: HomeAssistant) -> None:
"""Test auth_and_claim step where the device becomes claimed after polling."""
mock_unclaimed_client = MagicMock()
mock_unclaimed_client.authenticate = AsyncMock(return_value=False)
mock_unclaimed_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
mock_claimed_client = MagicMock()
mock_claimed_client.authenticate = AsyncMock(return_value=True)
mock_claimed_client.recordNumber = TEST_RECORD_NUMBER
mock_claimed_client.recordName = TEST_RECORD_NAME
call_count = 0
def mock_webhook_client(*args, **kwargs):
nonlocal call_count
call_count += 1
if call_count == 1:
return mock_unclaimed_client
return mock_claimed_client
with (
patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
side_effect=mock_webhook_client,
),
patch("homeassistant.components.energyid.config_flow.asyncio.sleep"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result_external = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result_external["type"] is FlowResultType.EXTERNAL_STEP
assert result_external["step_id"] == "auth_and_claim"
result_done = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
assert result_done["type"] is FlowResultType.EXTERNAL_STEP_DONE
final_result = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
await hass.async_block_till_done()
assert final_result["type"] is FlowResultType.CREATE_ENTRY
assert final_result["title"] == TEST_RECORD_NAME
assert final_result["description"] == "add_sensor_mapping_hint"
async def test_config_flow_claim_timeout(hass: HomeAssistant) -> None:
"""Test claim step when polling times out and user continues."""
mock_unclaimed_client = MagicMock()
mock_unclaimed_client.authenticate = AsyncMock(return_value=False)
mock_unclaimed_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
with (
patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
return_value=mock_unclaimed_client,
),
patch(
"homeassistant.components.energyid.config_flow.asyncio.sleep",
) as mock_sleep,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result_external = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result_external["type"] is FlowResultType.EXTERNAL_STEP
# Simulate polling timeout, then user continuing the flow
result_after_timeout = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
await hass.async_block_till_done()
# After timeout, polling stops and user continues - should see external step again
assert result_after_timeout["type"] is FlowResultType.EXTERNAL_STEP
assert result_after_timeout["step_id"] == "auth_and_claim"
# Verify polling actually ran the expected number of times
# Sleep happens at beginning of polling loop, so MAX_POLLING_ATTEMPTS + 1 sleeps
# but only MAX_POLLING_ATTEMPTS authentication attempts
assert mock_sleep.call_count == MAX_POLLING_ATTEMPTS + 1
async def test_duplicate_unique_id_prevented(hass: HomeAssistant) -> None:
"""Test that duplicate device_id (unique_id) is detected and aborted."""
# Create existing entry with a specific device_id as unique_id
# The generated device_id format is: homeassistant_eid_{instance_id}_{timestamp_ms}
# With instance_id="test_instance" and time=123.0, this becomes:
# homeassistant_eid_test_instance_123000
existing_device_id = "homeassistant_eid_test_instance_123000"
entry = MockConfigEntry(
domain=DOMAIN,
unique_id=existing_device_id,
data={
CONF_PROVISIONING_KEY: "old_key",
CONF_PROVISIONING_SECRET: "old_secret",
CONF_DEVICE_ID: existing_device_id,
CONF_DEVICE_NAME: "Existing Device",
},
)
entry.add_to_hass(hass)
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = TEST_RECORD_NUMBER
mock_client.recordName = TEST_RECORD_NAME
# Mock to return the same device_id that already exists
with (
patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
return_value=mock_client,
),
patch(
"homeassistant.components.energyid.config_flow.async_get_instance_id",
return_value="test_instance",
),
patch(
"homeassistant.components.energyid.config_flow.asyncio.get_event_loop"
) as mock_loop,
):
# Force the same device_id to be generated
mock_loop.return_value.time.return_value = 123.0
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
# Should abort because unique_id (device_id) already exists
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "already_configured"
async def test_multiple_different_devices_allowed(hass: HomeAssistant) -> None:
"""Test that multiple config entries with different device_ids are allowed."""
# Create existing entry with one device_id
entry = MockConfigEntry(
domain=DOMAIN,
unique_id="homeassistant_eid_device_1",
data={
CONF_PROVISIONING_KEY: "key1",
CONF_PROVISIONING_SECRET: "secret1",
CONF_DEVICE_ID: "homeassistant_eid_device_1",
CONF_DEVICE_NAME: "Device 1",
},
)
entry.add_to_hass(hass)
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = TEST_RECORD_NUMBER
mock_client.recordName = TEST_RECORD_NAME
with patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
return_value=mock_client,
):
# Check initial result
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
# Configure with different credentials (will create different device_id)
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: "key2",
CONF_PROVISIONING_SECRET: "secret2",
},
)
# Should succeed because device_id will be different
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == TEST_RECORD_NAME
assert result2["data"][CONF_PROVISIONING_KEY] == "key2"
assert result2["data"][CONF_PROVISIONING_SECRET] == "secret2"
assert result2["description"] == "add_sensor_mapping_hint"
# Verify unique_id is set
new_entry = hass.config_entries.async_get_entry(result2["result"].entry_id)
assert new_entry.unique_id is not None
assert new_entry.unique_id != entry.unique_id # Different from first entry
async def test_config_flow_connection_error(hass: HomeAssistant) -> None:
"""Test connection error during authentication."""
with patch(
"homeassistant.components.energyid.config_flow.WebhookClient.authenticate",
side_effect=ClientError("Connection failed"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"]["base"] == "cannot_connect"
async def test_config_flow_unexpected_error(hass: HomeAssistant) -> None:
"""Test unexpected error during authentication."""
with patch(
"homeassistant.components.energyid.config_flow.WebhookClient.authenticate",
side_effect=Exception("Unexpected error"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"]["base"] == "unknown_auth_error"
async def test_config_flow_external_step_claimed_during_display(
hass: HomeAssistant,
) -> None:
"""Test when device gets claimed while external step is being displayed."""
call_count = 0
def create_mock_client(*args, **kwargs):
nonlocal call_count
call_count += 1
mock_client = MagicMock()
if call_count == 1:
mock_client.authenticate = AsyncMock(return_value=False)
mock_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
else:
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = TEST_RECORD_NUMBER
mock_client.recordName = TEST_RECORD_NAME
return mock_client
with patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
side_effect=create_mock_client,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result_external = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result_external["type"] is FlowResultType.EXTERNAL_STEP
# User continues immediately - device is claimed, polling task should be cancelled
result_claimed = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
assert result_claimed["type"] is FlowResultType.EXTERNAL_STEP_DONE
final_result = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
await hass.async_block_till_done()
assert final_result["type"] is FlowResultType.CREATE_ENTRY
async def test_config_flow_auth_and_claim_step_not_claimed(hass: HomeAssistant) -> None:
"""Test auth_and_claim step when device is not claimed after polling."""
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=False)
mock_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
with patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
return_value=mock_client,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: "x",
CONF_PROVISIONING_SECRET: "y",
},
)
assert result2["type"] is FlowResultType.EXTERNAL_STEP
# User continues immediately - device still not claimed, polling task should be cancelled
result3 = await hass.config_entries.flow.async_configure(result2["flow_id"])
assert result3["type"] is FlowResultType.EXTERNAL_STEP
assert result3["step_id"] == "auth_and_claim"
async def test_config_flow_reauth_success(
hass: HomeAssistant,
) -> None:
"""Test the reauthentication flow for EnergyID integration (success path)."""
# Existing config entry
entry = MockConfigEntry(
domain=DOMAIN,
unique_id="site_12345",
data={
CONF_PROVISIONING_KEY: "old_key",
CONF_PROVISIONING_SECRET: "old_secret",
CONF_DEVICE_ID: "existing_device",
CONF_DEVICE_NAME: "Existing Device",
},
)
entry.add_to_hass(hass)
# Mock client for successful reauth
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_12345"
mock_client.recordName = "My Test Site"
with patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
return_value=mock_client,
):
# Start reauth flow
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": "reauth", "entry_id": entry.entry_id},
data=entry.data,
)
assert result["type"] == "form"
assert result["step_id"] == "reauth_confirm"
# Submit new credentials
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: "new_key",
CONF_PROVISIONING_SECRET: "new_secret",
},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.ABORT
# Entry should be updated
updated_entry = hass.config_entries.async_get_entry(entry.entry_id)
assert updated_entry.data[CONF_PROVISIONING_KEY] == "new_key"
assert updated_entry.data[CONF_PROVISIONING_SECRET] == "new_secret"
@pytest.mark.parametrize(
("auth_status", "auth_message", "expected_error"),
[
(401, "Unauthorized", "invalid_auth"),
(500, "Server Error", "cannot_connect"),
],
)
async def test_config_flow_client_response_error(
hass: HomeAssistant,
auth_status: int,
auth_message: str,
expected_error: str,
) -> None:
"""Test config flow with ClientResponseError."""
mock_client = MagicMock()
mock_client.authenticate.side_effect = ClientResponseError(
request_info=MagicMock(),
history=(),
status=auth_status,
message=auth_message,
)
with patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
return_value=mock_client,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"]["base"] == expected_error
async def test_config_flow_reauth_needs_claim(hass: HomeAssistant) -> None:
"""Test reauth flow when device needs to be claimed."""
entry = MockConfigEntry(
domain=DOMAIN,
unique_id="site_12345",
data={
CONF_PROVISIONING_KEY: "old_key",
CONF_PROVISIONING_SECRET: "old_secret",
CONF_DEVICE_ID: "existing_device",
CONF_DEVICE_NAME: "Existing Device",
},
)
entry.add_to_hass(hass)
# Mock client that needs claiming
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=False)
mock_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
with (
patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
return_value=mock_client,
),
patch("homeassistant.components.energyid.config_flow.asyncio.sleep"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": "reauth", "entry_id": entry.entry_id},
data=entry.data,
)
# Check initial reauth form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: "new_key",
CONF_PROVISIONING_SECRET: "new_secret",
},
)
assert result2["type"] is FlowResultType.EXTERNAL_STEP
assert result2["step_id"] == "auth_and_claim"
async def test_async_get_supported_subentry_types(hass: HomeAssistant) -> None:
"""Test async_get_supported_subentry_types returns correct types."""
mock_entry = MockConfigEntry(domain=DOMAIN, data={})
result = EnergyIDConfigFlow.async_get_supported_subentry_types(mock_entry)
assert "sensor_mapping" in result
assert result["sensor_mapping"] == EnergyIDSensorMappingFlowHandler
async def test_polling_stops_on_invalid_auth_error(hass: HomeAssistant) -> None:
"""Test that polling stops when invalid_auth error occurs during auth_and_claim polling."""
mock_unclaimed_client = MagicMock()
mock_unclaimed_client.authenticate = AsyncMock(return_value=False)
mock_unclaimed_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
mock_error_client = MagicMock()
mock_error_client.authenticate = AsyncMock(
side_effect=ClientResponseError(
request_info=MagicMock(),
history=(),
status=401,
)
)
call_count = 0
def mock_webhook_client(*args, **kwargs):
nonlocal call_count
call_count += 1
return mock_unclaimed_client if call_count == 1 else mock_error_client
with (
patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
side_effect=mock_webhook_client,
),
patch("homeassistant.components.energyid.config_flow.asyncio.sleep"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result_external = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result_external["type"] is FlowResultType.EXTERNAL_STEP
result_done = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
assert result_done["type"] is FlowResultType.EXTERNAL_STEP
await hass.async_block_till_done()
async def test_polling_stops_on_cannot_connect_error(hass: HomeAssistant) -> None:
"""Test that polling stops when cannot_connect error occurs during auth_and_claim polling."""
mock_unclaimed_client = MagicMock()
mock_unclaimed_client.authenticate = AsyncMock(return_value=False)
mock_unclaimed_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
mock_error_client = MagicMock()
mock_error_client.authenticate = AsyncMock(
side_effect=ClientError("Connection failed")
)
call_count = 0
def mock_webhook_client(*args, **kwargs):
nonlocal call_count
call_count += 1
return mock_unclaimed_client if call_count == 1 else mock_error_client
with (
patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
side_effect=mock_webhook_client,
),
patch("homeassistant.components.energyid.config_flow.asyncio.sleep"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result_external = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result_external["type"] is FlowResultType.EXTERNAL_STEP
result_done = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
assert result_done["type"] is FlowResultType.EXTERNAL_STEP
await hass.async_block_till_done()
async def test_auth_and_claim_subsequent_auth_error(hass: HomeAssistant) -> None:
"""Test that auth_and_claim step handles authentication errors during polling attempts."""
mock_unclaimed_client = MagicMock()
mock_unclaimed_client.authenticate = AsyncMock(return_value=False)
mock_unclaimed_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
mock_error_client = MagicMock()
mock_error_client.authenticate = AsyncMock(
side_effect=ClientResponseError(
request_info=MagicMock(),
history=(),
status=401,
)
)
call_count = 0
def mock_webhook_client(*args, **kwargs):
nonlocal call_count
call_count += 1
return mock_unclaimed_client if call_count <= 2 else mock_error_client
with (
patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
side_effect=mock_webhook_client,
),
patch("homeassistant.components.energyid.config_flow.asyncio.sleep"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result_external = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result_external["type"] is FlowResultType.EXTERNAL_STEP
result_done = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
assert result_done["type"] is FlowResultType.EXTERNAL_STEP
final_result = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
assert final_result["type"] is FlowResultType.EXTERNAL_STEP
assert final_result["step_id"] == "auth_and_claim"
async def test_reauth_with_error(hass: HomeAssistant) -> None:
"""Test that reauth flow shows error when authentication fails with 401."""
mock_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "old_key",
CONF_PROVISIONING_SECRET: "old_secret",
CONF_DEVICE_ID: "test_device_id",
CONF_DEVICE_NAME: "test_device_name",
},
)
mock_entry.add_to_hass(hass)
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(
side_effect=ClientResponseError(
request_info=MagicMock(),
history=(),
status=401,
)
)
with patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
return_value=mock_client,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURCE_REAUTH,
"entry_id": mock_entry.entry_id,
},
data=mock_entry.data,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: "new_key",
CONF_PROVISIONING_SECRET: "new_secret",
},
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"]["base"] == "invalid_auth"
async def test_polling_cancellation_on_auth_failure(hass: HomeAssistant) -> None:
"""Test that polling is cancelled when authentication fails during auth_and_claim."""
call_count = 0
auth_call_count = 0
def mock_webhook_client(*args, **kwargs):
nonlocal call_count
call_count += 1
if call_count == 1:
# First client for initial claimless auth
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=False)
mock_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
return mock_client
# Subsequent client for polling check - fails authentication
mock_client = MagicMock()
async def auth_with_error():
nonlocal auth_call_count
auth_call_count += 1
raise ClientError("Connection failed")
mock_client.authenticate = auth_with_error
return mock_client
with (
patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
side_effect=mock_webhook_client,
),
patch("homeassistant.components.energyid.config_flow.asyncio.sleep"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
# Start auth_and_claim flow - sets up polling
result_external = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result_external["type"] is FlowResultType.EXTERNAL_STEP
# Wait for polling task to encounter the error and stop
await hass.async_block_till_done()
# Verify polling stopped after the error
# auth_call_count should be 1 (one failed attempt during polling)
initial_auth_count = auth_call_count
assert initial_auth_count == 1
# Trigger user continuing the flow - polling should already be stopped
result_failed = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
assert result_failed["type"] is FlowResultType.EXTERNAL_STEP
assert result_failed["step_id"] == "auth_and_claim"
# Wait a bit and verify no further authentication attempts occurred
await hass.async_block_till_done()
assert (
auth_call_count == initial_auth_count + 1
) # One more for the manual check
async def test_polling_cancellation_on_success(hass: HomeAssistant) -> None:
"""Test that polling is cancelled when device becomes claimed successfully during auth_and_claim."""
call_count = 0
auth_call_count = 0
def mock_webhook_client(*args, **kwargs):
nonlocal call_count
call_count += 1
if call_count == 1:
# First client for initial claimless auth
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=False)
mock_client.get_claim_info.return_value = {"claim_url": "http://claim.me"}
return mock_client
# Subsequent client for polling check - device now claimed
mock_client = MagicMock()
async def auth_success():
nonlocal auth_call_count
auth_call_count += 1
return True
mock_client.authenticate = auth_success
mock_client.recordNumber = TEST_RECORD_NUMBER
mock_client.recordName = TEST_RECORD_NAME
return mock_client
with (
patch(
"homeassistant.components.energyid.config_flow.WebhookClient",
side_effect=mock_webhook_client,
),
patch("homeassistant.components.energyid.config_flow.asyncio.sleep"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Check initial form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
# Start auth_and_claim flow - sets up polling task
result_external = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
},
)
assert result_external["type"] is FlowResultType.EXTERNAL_STEP
# Wait for polling to detect the device is claimed and advance the flow
await hass.async_block_till_done()
# Verify polling made authentication attempt
# auth_call_count should be 1 (polling detected device is claimed)
assert auth_call_count >= 1
claimed_auth_count = auth_call_count
# User continues - device is already claimed, polling should be cancelled
result_done = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
assert result_done["type"] is FlowResultType.EXTERNAL_STEP_DONE
# Verify polling was cancelled - the auth count should only increase by 1
# (for the manual check when user continues, not from polling)
assert auth_call_count == claimed_auth_count + 1
# Final call to create entry
final_result = await hass.config_entries.flow.async_configure(
result_external["flow_id"]
)
assert final_result["type"] is FlowResultType.CREATE_ENTRY
# Wait a bit and verify no further authentication attempts from polling
await hass.async_block_till_done()
final_auth_count = auth_call_count
# Ensure all background tasks have completed and polling really stopped
await hass.async_block_till_done()
# No new auth attempts should have occurred (polling was cancelled)
assert auth_call_count == final_auth_count
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/energyid/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 803,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/energyid/test_energyid_sensor_mapping_flow.py | """Test EnergyID sensor mapping subentry flow (direct handler tests)."""
from typing import Any
from unittest.mock import patch
import pytest
from homeassistant.components.energyid.const import (
CONF_DEVICE_ID,
CONF_ENERGYID_KEY,
CONF_HA_ENTITY_UUID,
CONF_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET,
DOMAIN,
)
from homeassistant.components.energyid.energyid_sensor_mapping_flow import (
EnergyIDSensorMappingFlowHandler,
_get_suggested_entities,
_validate_mapping_input,
)
from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import InvalidData
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
TEST_PROVISIONING_KEY = "test_prov_key"
TEST_PROVISIONING_SECRET = "test_prov_secret"
TEST_RECORD_NUMBER = "site_12345"
TEST_RECORD_NAME = "My Test Site"
@pytest.fixture
def mock_parent_entry(hass: HomeAssistant) -> MockConfigEntry:
"""Return a mock parent config entry."""
entry = MockConfigEntry(
domain=DOMAIN,
title="Mock Title",
data={
"provisioning_key": "test_key",
"provisioning_secret": "test_secret",
"device_id": "test_device",
"device_name": "Test Device",
},
entry_id="parent_entry_id",
)
entry.add_to_hass(hass)
return entry
async def test_user_step_form(
hass: HomeAssistant, mock_parent_entry: MockConfigEntry
) -> None:
"""Test the user step form is shown."""
mock_parent_entry.add_to_hass(hass)
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
assert result["type"] == "form"
assert result["step_id"] == "user"
assert "ha_entity_id" in result["data_schema"].schema
async def test_successful_creation(
hass: HomeAssistant,
mock_parent_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test successful creation of a mapping."""
mock_parent_entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "power_2", suggested_object_id="test_power"
)
hass.states.async_set("sensor.test_power", "50")
# Start the subentry flow
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
assert result["type"] == "form"
# Submit user input
result = await hass.config_entries.subentries.async_configure(
result["flow_id"], {"ha_entity_id": entity_entry.entity_id}
)
assert result["type"] == "create_entry"
assert result["title"] == "test_power connection to EnergyID"
assert result["data"][CONF_HA_ENTITY_UUID] == entity_entry.id
assert result["data"][CONF_ENERGYID_KEY] == "test_power"
async def test_entity_already_mapped(
hass: HomeAssistant,
mock_parent_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test mapping an already mapped entity."""
mock_parent_entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "power_3", suggested_object_id="already_mapped"
)
hass.states.async_set("sensor.already_mapped", "75")
# Add a subentry with this entity UUID
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: entity_entry.id,
CONF_ENERGYID_KEY: "already_mapped",
},
entry_id="sub_entry_1",
)
sub_entry.parent_entry_id = mock_parent_entry.entry_id
sub_entry.add_to_hass(hass)
await hass.async_block_till_done()
# Start the subentry flow
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
assert result["type"] == "form"
# Submit user input
result = await hass.config_entries.subentries.async_configure(
result["flow_id"], {"ha_entity_id": entity_entry.entity_id}
)
# The current flow allows remapping, so expect create_entry
assert result["type"] == "create_entry"
async def test_entity_not_found(
hass: HomeAssistant, mock_parent_entry: MockConfigEntry
) -> None:
"""Test error when entity is not found."""
mock_parent_entry.add_to_hass(hass)
# Start the subentry flow
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
assert result["type"] == "form"
# Submit user input with nonexistent entity
result = await hass.config_entries.subentries.async_configure(
result["flow_id"], {"ha_entity_id": "sensor.nonexistent"}
)
assert result["type"] == "form"
assert result["errors"]["base"] == "entity_not_found"
async def test_no_entity_selected(
hass: HomeAssistant, mock_parent_entry: MockConfigEntry
) -> None:
"""Test error when no entity is selected."""
mock_parent_entry.add_to_hass(hass)
# Start the subentry flow
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
assert result["type"] == "form"
# Submit user input with empty entity, expect InvalidData
with pytest.raises(InvalidData) as excinfo:
await hass.config_entries.subentries.async_configure(
result["flow_id"], {"ha_entity_id": ""}
)
# Only check for the generic schema error message
assert "Schema validation failed" in str(excinfo.value)
async def test_entity_disappears_after_validation(
hass: HomeAssistant,
mock_parent_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test entity disappears after validation but before lookup."""
mock_parent_entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "vanishing", suggested_object_id="vanish"
)
hass.states.async_set("sensor.vanish", "42")
# Start the subentry flow
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
assert result["type"] == "form"
# Remove the entity from the registry after validation but before registry lookup
entity_registry.async_remove(entity_entry.entity_id)
result = await hass.config_entries.subentries.async_configure(
result["flow_id"], {"ha_entity_id": entity_entry.entity_id}
)
assert result["type"] == "form"
assert result["errors"]["base"] == "entity_not_found"
async def test_no_suitable_entities(
hass: HomeAssistant, mock_parent_entry: MockConfigEntry
) -> None:
"""Test form when no suitable entities exist."""
mock_parent_entry.add_to_hass(hass)
# Start the subentry flow with an empty registry
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
assert result["type"] == "form"
# The data_schema should still be present, but the selector will be empty
assert "ha_entity_id" in result["data_schema"].schema
@pytest.mark.parametrize(
("entities_to_create"),
[
([]), # empty case
([("light", "test", "not_sensor", "not_sensor")]), # non-sensor case
],
)
def test_get_suggested_entities_no_suitable_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
entities_to_create: list[tuple[str, str, str, str]],
) -> None:
"""Test _get_suggested_entities returns empty list if no suitable entities."""
for domain, platform, unique_id, suggested_object_id in entities_to_create:
entity_registry.async_get_or_create(
domain, platform, unique_id, suggested_object_id=suggested_object_id
)
assert _get_suggested_entities(hass) == []
def test_energyid_sensor_mapping_flow_handler_repr() -> None:
"""Test instantiating and repr-ing the handler."""
handler = EnergyIDSensorMappingFlowHandler()
assert handler.__class__.__name__ == "EnergyIDSensorMappingFlowHandler"
async def test_duplicate_entity_key(
hass: HomeAssistant,
mock_parent_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test mapping two entities with the same suggested object id."""
mock_parent_entry.add_to_hass(hass)
entity1 = entity_registry.async_get_or_create(
"sensor", "test", "unique1", suggested_object_id="dup"
)
entity2 = entity_registry.async_get_or_create(
"sensor", "test", "unique2", suggested_object_id="dup"
)
hass.states.async_set("sensor.dup", "10")
# Map first entity
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
result = await hass.config_entries.subentries.async_configure(
result["flow_id"], {"ha_entity_id": entity1.entity_id}
)
assert result["type"] == "create_entry"
# Map second entity
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
result = await hass.config_entries.subentries.async_configure(
result["flow_id"], {"ha_entity_id": entity2.entity_id}
)
assert result["type"] == "create_entry"
def test_validate_mapping_input_none_entity(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test that _validate_mapping_input returns 'entity_required' error for None entity."""
errors = _validate_mapping_input(None, set(), entity_registry)
assert errors == {"base": "entity_required"}
def test_validate_mapping_input_empty_string(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test that _validate_mapping_input returns 'entity_required' error for empty string entity."""
errors = _validate_mapping_input("", set(), entity_registry)
assert errors == {"base": "entity_required"}
def test_validate_mapping_input_already_mapped(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test that _validate_mapping_input returns 'entity_already_mapped' error when entity is already mapped."""
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "mapped_entity", suggested_object_id="mapped"
)
current_mappings = {entity_entry.id}
errors = _validate_mapping_input(
entity_entry.entity_id, current_mappings, entity_registry
)
assert errors == {"base": "entity_already_mapped"}
def test_get_suggested_entities_with_state_class(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test that _get_suggested_entities includes sensor entities with measurement state class."""
entity_entry = entity_registry.async_get_or_create(
"sensor",
"test",
"measurement_sensor",
suggested_object_id="measurement",
capabilities={"state_class": SensorStateClass.MEASUREMENT},
)
hass.states.async_set(entity_entry.entity_id, "100")
result = _get_suggested_entities(hass)
assert entity_entry.entity_id in result
@pytest.mark.parametrize(
("test_case"),
[
{
"name": "energy_original_device_class",
"unique_id": "energy_sensor",
"entity_id": "sensor.energy_test",
"original_device_class": SensorDeviceClass.ENERGY,
"device_class": None,
"state_value": "250",
},
{
"name": "power_original_device_class",
"unique_id": "power_sensor",
"entity_id": "sensor.power_test",
"original_device_class": SensorDeviceClass.POWER,
"device_class": None,
"state_value": "1500",
},
{
"name": "energy_user_override_device_class",
"unique_id": "override_sensor",
"entity_id": "sensor.override_test",
"original_device_class": None,
"device_class": SensorDeviceClass.ENERGY,
"state_value": "300",
},
],
ids=lambda x: x["name"],
)
def test_get_suggested_entities_with_device_class(
hass: HomeAssistant, entity_registry: er.EntityRegistry, test_case: dict[str, Any]
) -> None:
"""Test that _get_suggested_entities includes sensor entities with various device class configurations."""
entity_entry = entity_registry.async_get_or_create(
"sensor",
"test",
test_case["unique_id"],
suggested_object_id=test_case["entity_id"].split(".", 1)[-1],
original_device_class=test_case["original_device_class"],
)
if test_case["device_class"] is not None:
entity_registry.async_update_entity(
entity_entry.entity_id, device_class=test_case["device_class"]
)
hass.states.async_set(test_case["entity_id"], test_case["state_value"])
result = _get_suggested_entities(hass)
assert test_case["entity_id"] in result
async def test_subentry_entity_not_found_after_validation(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that subentry flow returns error when entity is validated but disappears before registry lookup."""
mock_parent_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: TEST_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET: TEST_PROVISIONING_SECRET,
CONF_DEVICE_ID: "test_device",
},
)
mock_parent_entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "disappearing", suggested_object_id="disappear"
)
hass.states.async_set(entity_entry.entity_id, "42")
result = await hass.config_entries.subentries.async_init(
(mock_parent_entry.entry_id, "sensor_mapping"),
context={"source": "user"},
)
assert result["type"] == "form"
original_async_get = entity_registry.async_get
def mock_async_get_disappearing(entity_id):
if not hasattr(mock_async_get_disappearing, "call_count"):
mock_async_get_disappearing.call_count = 0
mock_async_get_disappearing.call_count += 1
# First call (validation) succeeds, second call (lookup) fails
return (
None
if mock_async_get_disappearing.call_count > 1
else original_async_get(entity_id)
)
with patch.object(
entity_registry, "async_get", side_effect=mock_async_get_disappearing
):
result = await hass.config_entries.subentries.async_configure(
result["flow_id"], {"ha_entity_id": entity_entry.entity_id}
)
assert result["type"] == "form"
assert result["errors"]["base"] == "entity_not_found"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/energyid/test_energyid_sensor_mapping_flow.py",
"license": "Apache License 2.0",
"lines": 368,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/energyid/test_init.py | """Tests for EnergyID integration initialization."""
from datetime import timedelta
from unittest.mock import ANY, AsyncMock, MagicMock, patch
from aiohttp import ClientError, ClientResponseError
from homeassistant.components.energyid import (
DOMAIN,
_async_handle_state_change,
async_unload_entry,
)
from homeassistant.components.energyid.const import (
CONF_DEVICE_ID,
CONF_DEVICE_NAME,
CONF_ENERGYID_KEY,
CONF_HA_ENTITY_UUID,
CONF_PROVISIONING_KEY,
CONF_PROVISIONING_SECRET,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import Event, EventStateChangedData, HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_successful_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test the integration sets up successfully."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_webhook_client.authenticate.assert_called_once()
async def test_setup_fails_on_timeout(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test setup fails when there is a connection timeout."""
mock_webhook_client.authenticate.side_effect = ConfigEntryNotReady
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_setup_fails_on_auth_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test setup fails when authentication returns an unexpected error."""
mock_webhook_client.authenticate.side_effect = Exception("Unexpected error")
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Unexpected errors cause retry, not reauth (might be temporary network issues)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_setup_fails_when_not_claimed(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test setup fails when device is not claimed and triggers reauth flow."""
mock_webhook_client.authenticate.return_value = False
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Device not claimed raises ConfigEntryAuthFailed, resulting in SETUP_ERROR state
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
# Verify that a reauth flow was initiated (reviewer comment at line 56-81)
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
assert len(flows) == 1
assert flows[0]["context"]["source"] == "reauth"
assert flows[0]["context"]["entry_id"] == mock_config_entry.entry_id
async def test_setup_auth_error_401_triggers_reauth(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test 401 authentication error triggers reauth flow (covers __init__.py lines 85-86)."""
mock_webhook_client.authenticate.side_effect = ClientResponseError(
request_info=MagicMock(),
history=(),
status=401,
message="Unauthorized",
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# 401 error raises ConfigEntryAuthFailed, resulting in SETUP_ERROR state
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
# Verify that a reauth flow was initiated
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
assert len(flows) == 1
assert flows[0]["context"]["source"] == "reauth"
assert flows[0]["context"]["entry_id"] == mock_config_entry.entry_id
async def test_setup_auth_error_403_triggers_reauth(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test 403 authentication error triggers reauth flow (covers __init__.py lines 85-86)."""
mock_webhook_client.authenticate.side_effect = ClientResponseError(
request_info=MagicMock(),
history=(),
status=403,
message="Forbidden",
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# 403 error raises ConfigEntryAuthFailed, resulting in SETUP_ERROR state
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
# Verify that a reauth flow was initiated
flows = hass.config_entries.flow.async_progress_by_handler(DOMAIN)
assert len(flows) == 1
assert flows[0]["context"]["source"] == "reauth"
assert flows[0]["context"]["entry_id"] == mock_config_entry.entry_id
async def test_setup_http_error_triggers_retry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test non-401/403 HTTP error triggers retry (covers __init__.py lines 88-90)."""
mock_webhook_client.authenticate.side_effect = ClientResponseError(
request_info=MagicMock(),
history=(),
status=500,
message="Internal Server Error",
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# 500 error raises ConfigEntryNotReady, resulting in SETUP_RETRY state
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_setup_network_error_triggers_retry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test network/connection error triggers retry (covers __init__.py lines 93-95)."""
mock_webhook_client.authenticate.side_effect = ClientError("Connection refused")
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Network error raises ConfigEntryNotReady, resulting in SETUP_RETRY state
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_state_change_sends_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that a sensor state change is correctly sent to the EnergyID API."""
# ARRANGE: Prepare the config entry with sub-entries BEFORE setup.
entity_entry = entity_registry.async_get_or_create(
"sensor", "test_platform", "power_1", suggested_object_id="power_meter"
)
hass.states.async_set(entity_entry.entity_id, STATE_UNAVAILABLE)
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
# ACT 1: Set up the integration.
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ACT 2: Simulate the sensor reporting a new value.
hass.states.async_set(entity_entry.entity_id, "123.45")
await hass.async_block_till_done()
# ASSERT
mock_webhook_client.get_or_create_sensor.assert_called_with("grid_power")
sensor_mock = mock_webhook_client.get_or_create_sensor.return_value
sensor_mock.update.assert_called_once_with(123.45, ANY)
async def test_state_change_handles_invalid_values(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that invalid state values are handled gracefully."""
entity_entry = entity_registry.async_get_or_create(
"sensor", "test_platform", "power_2", suggested_object_id="invalid_sensor"
)
hass.states.async_set(entity_entry.entity_id, STATE_UNAVAILABLE)
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Reset the mock to clear any calls from setup
sensor_mock = mock_webhook_client.get_or_create_sensor.return_value
sensor_mock.update.reset_mock()
# Act: Send an invalid (non-numeric) value
hass.states.async_set(entity_entry.entity_id, "invalid")
await hass.async_block_till_done()
# ASSERT: No sensor update call should happen for invalid values
sensor_mock.update.assert_not_called()
async def test_state_change_ignores_unavailable(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that unavailable states are ignored."""
entity_entry = entity_registry.async_get_or_create(
"sensor", "test_platform", "power_3", suggested_object_id="unavailable_sensor"
)
hass.states.async_set(entity_entry.entity_id, "100")
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Reset the mock
sensor_mock = mock_webhook_client.get_or_create_sensor.return_value
sensor_mock.update.reset_mock()
# Act: Set to unavailable
hass.states.async_set(entity_entry.entity_id, STATE_UNAVAILABLE)
await hass.async_block_till_done()
# ASSERT: No update for unavailable state
sensor_mock.update.assert_not_called()
async def test_state_change_ignores_unknown(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that unknown states are ignored."""
entity_entry = entity_registry.async_get_or_create(
"sensor", "test_platform", "power_4", suggested_object_id="unknown_sensor"
)
hass.states.async_set(entity_entry.entity_id, "100")
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Reset the mock
sensor_mock = mock_webhook_client.get_or_create_sensor.return_value
sensor_mock.update.reset_mock()
# Act: Set to unknown
hass.states.async_set(entity_entry.entity_id, STATE_UNKNOWN)
await hass.async_block_till_done()
# ASSERT: No update for unknown state
sensor_mock.update.assert_not_called()
async def test_listener_tracks_entity_rename(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that the integration correctly handles a mapped entity being renamed."""
# ARRANGE: Prepare the config entry with sub-entries BEFORE setup.
entity_entry = entity_registry.async_get_or_create(
"sensor", "test_platform", "power_5", suggested_object_id="power_meter"
)
hass.states.async_set(entity_entry.entity_id, "50")
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Reset the mock to clear calls from setup
sensor_mock = mock_webhook_client.get_or_create_sensor.return_value
sensor_mock.update.reset_mock()
# ACT 1: Rename the entity in registry first, then set state for new entity_id
# This avoids the "Entity with this ID is already registered" error
new_entity_id = "sensor.new_and_improved_power_meter"
old_state = hass.states.get(entity_entry.entity_id)
entity_registry.async_update_entity(
entity_entry.entity_id, new_entity_id=new_entity_id
)
# Set state for new entity_id after rename to simulate migration
hass.states.async_set(new_entity_id, old_state.state)
# Clear old state to simulate HA's actual rename behavior
hass.states.async_set(entity_entry.entity_id, None)
await hass.async_block_till_done()
# Reset again after the rename triggers update_listeners
sensor_mock.update.reset_mock()
# ACT 2: Post a new value to the renamed entity
hass.states.async_set(new_entity_id, "1000")
await hass.async_block_till_done()
# ASSERT: The listener should track the new entity ID
sensor_mock.update.assert_called_with(1000.0, ANY)
async def test_listener_tracks_entity_removal(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that the integration handles entity removal."""
entity_entry = entity_registry.async_get_or_create(
"sensor", "test_platform", "power_6", suggested_object_id="removable_meter"
)
hass.states.async_set(entity_entry.entity_id, "100")
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ACT: Remove the entity
entity_registry.async_remove(entity_entry.entity_id)
await hass.async_block_till_done()
# ASSERT: Integration should still be loaded (just no longer tracking that entity)
assert mock_config_entry.state is ConfigEntryState.LOADED
async def test_entity_not_in_state_machine_during_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test entity that exists in registry but not state machine during setup."""
entity_entry = entity_registry.async_get_or_create(
"sensor", "test_platform", "power_7", suggested_object_id="ghost_meter"
)
# Note: NOT setting a state for this entity initially
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ASSERT: Should still load successfully
assert mock_config_entry.state is ConfigEntryState.LOADED
# Reset mock to clear any setup calls
sensor_mock = mock_webhook_client.get_or_create_sensor.return_value
sensor_mock.update.reset_mock()
# Now add the state - entity should be tracked dynamically
hass.states.async_set(entity_entry.entity_id, "200")
await hass.async_block_till_done()
# ASSERT: Entity should now be tracked and update called
sensor_mock.update.assert_called_with(200.0, ANY)
async def test_unload_cleans_up_listeners(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test unloading the integration cleans up properly."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ACT: Unload the integration
result = await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ASSERT: Unload was successful
assert result is True
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
mock_webhook_client.close.assert_called_once()
async def test_no_valid_subentries_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test setup with no valid subentries completes successfully."""
# Set up empty subentries
mock_config_entry.subentries = {}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ASSERT: Still loads successfully but with no mappings
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_webhook_client.authenticate.assert_called_once()
async def test_subentry_with_missing_uuid(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test subentry with missing entity UUID is skipped."""
sub_entry = {
"data": {CONF_ENERGYID_KEY: "grid_power"} # Missing CONF_HA_ENTITY_UUID
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ASSERT: Still loads successfully
assert mock_config_entry.state is ConfigEntryState.LOADED
async def test_subentry_with_nonexistent_entity(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test subentry referencing non-existent entity UUID."""
sub_entry = {
"data": {
CONF_HA_ENTITY_UUID: "nonexistent-uuid-12345",
CONF_ENERGYID_KEY: "grid_power",
}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ASSERT: Still loads successfully (entity is just skipped with warning)
assert mock_config_entry.state is ConfigEntryState.LOADED
async def test_initial_state_queued_for_new_mapping(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that initial state is queued when a new mapping is detected."""
entity_entry = entity_registry.async_get_or_create(
"sensor", "test_platform", "power_8", suggested_object_id="initial_meter"
)
hass.states.async_set(entity_entry.entity_id, "42.5")
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ASSERT: Initial state should have been sent
sensor_mock = mock_webhook_client.get_or_create_sensor.return_value
sensor_mock.update.assert_called_with(42.5, ANY)
async def test_synchronize_sensors_error_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
) -> None:
"""Test that synchronize_sensors errors are handled gracefully."""
mock_webhook_client.synchronize_sensors.side_effect = OSError("Connection failed")
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ASSERT: Integration should still load
assert mock_config_entry.state is ConfigEntryState.LOADED
async def test_setup_timeout_during_authentication(hass: HomeAssistant) -> None:
"""Test ConfigEntryNotReady raised on TimeoutError during authentication."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(
side_effect=TimeoutError("Connection timeout")
)
mock_client_class.return_value = mock_client
result = await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert not result
assert entry.state is ConfigEntryState.SETUP_RETRY
async def test_periodic_sync_error_and_recovery(hass: HomeAssistant) -> None:
"""Test periodic sync error handling and recovery."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
call_count = [0]
def sync_side_effect():
call_count[0] += 1
if call_count[0] == 1:
raise OSError("Connection lost")
# Second and subsequent calls succeed
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = {"uploadInterval": 60}
mock_client.synchronize_sensors = AsyncMock(side_effect=sync_side_effect)
mock_client.close = AsyncMock()
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# First sync call during setup should succeed
assert call_count[0] == 0 # No sync yet
# Trigger periodic sync - first time, should fail
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=60))
await hass.async_block_till_done()
assert call_count[0] == 1 # First periodic call with error
# Trigger periodic sync again - second time, should succeed
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=120))
await hass.async_block_till_done()
assert call_count[0] == 2 # Second periodic call succeeds
async def test_periodic_sync_runtime_error(hass: HomeAssistant) -> None:
"""Test periodic sync handles RuntimeError."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = {"uploadInterval": 60}
mock_client.synchronize_sensors = AsyncMock(
side_effect=RuntimeError("Sync error")
)
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Trigger sync with RuntimeError
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=60))
await hass.async_block_till_done()
async def test_config_entry_update_listener(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test config entry update listener reloads listeners."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "power", suggested_object_id="power"
)
hass.states.async_set(entity_entry.entity_id, "100")
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_client.get_or_create_sensor = MagicMock(return_value=MagicMock())
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Add a subentry to trigger the update listener
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: entity_entry.id,
CONF_ENERGYID_KEY: "power",
},
)
sub_entry.parent_entry_id = entry.entry_id
sub_entry.add_to_hass(hass)
# This should trigger config_entry_update_listener
hass.config_entries.async_update_entry(entry, data=entry.data)
await hass.async_block_till_done()
async def test_initial_state_non_numeric(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test initial state with non-numeric value."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "text_sensor", suggested_object_id="text_sensor"
)
# Set non-numeric state
hass.states.async_set(entity_entry.entity_id, "not_a_number")
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: entity_entry.id,
CONF_ENERGYID_KEY: "text_sensor",
},
)
sub_entry.parent_entry_id = entry.entry_id
sub_entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_sensor = MagicMock()
mock_client.get_or_create_sensor = MagicMock(return_value=mock_sensor)
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Verify update was not called due to non-numeric state
mock_sensor.update.assert_not_called()
# ============================================================================
# LINE 305: Entry unloading during state change
# ============================================================================
async def test_state_change_during_entry_unload(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test state change handler when entry is being unloaded (line 305)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "power", suggested_object_id="power"
)
hass.states.async_set(entity_entry.entity_id, "100")
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: entity_entry.id,
CONF_ENERGYID_KEY: "power",
},
)
sub_entry.parent_entry_id = entry.entry_id
sub_entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_client.get_or_create_sensor = MagicMock(return_value=MagicMock())
mock_client.close = AsyncMock()
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Start unloading
await hass.config_entries.async_unload(entry.entry_id)
# Try to change state after unload started (should hit line 305)
hass.states.async_set(entity_entry.entity_id, "150")
await hass.async_block_till_done()
# ============================================================================
# LINE 324: Missing entity_uuid or energyid_key in subentry
# ============================================================================
async def test_late_appearing_entity_missing_data(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test late-appearing entity with malformed subentry data (line 324)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "power", suggested_object_id="power"
)
# Subentry with missing energyid_key
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: entity_entry.id,
# Missing CONF_ENERGYID_KEY
},
)
sub_entry.parent_entry_id = entry.entry_id
sub_entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Entity appears late - should skip processing due to missing energyid_key
hass.states.async_set(entity_entry.entity_id, "100")
await hass.async_block_till_done()
# ============================================================================
# LINE 340: Untracked entity state change
# ============================================================================
async def test_state_change_for_untracked_entity(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test state change for entity not in any subentry (line 340)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
tracked_entity = entity_registry.async_get_or_create(
"sensor", "test", "tracked", suggested_object_id="tracked"
)
hass.states.async_set(tracked_entity.entity_id, "100")
untracked_entity = entity_registry.async_get_or_create(
"sensor", "test", "untracked", suggested_object_id="untracked"
)
# Only add subentry for tracked entity
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: tracked_entity.id,
CONF_ENERGYID_KEY: "tracked",
},
)
sub_entry.parent_entry_id = entry.entry_id
sub_entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_sensor = MagicMock()
mock_client.get_or_create_sensor = MagicMock(return_value=mock_sensor)
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Change state of untracked entity - should hit line 340
hass.states.async_set(untracked_entity.entity_id, "200")
await hass.async_block_till_done()
# Verify no update was made
assert mock_sensor.update.call_count == 0
# ============================================================================
# LINE 363: Subentry unloading
# ============================================================================
async def test_unload_entry_with_subentries(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test unloading entry with subentries (line 363)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "power", suggested_object_id="power"
)
hass.states.async_set(entity_entry.entity_id, "100")
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: entity_entry.id,
CONF_ENERGYID_KEY: "power",
},
)
sub_entry.parent_entry_id = entry.entry_id
sub_entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_client.get_or_create_sensor = MagicMock(return_value=MagicMock())
mock_client.close = AsyncMock()
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Unload should unload subentry (line 363)
result = await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert result is True
# Check that subentry was unloaded
# Note: subentries are unloaded automatically by HA's config entry system
# ============================================================================
# LINES 379-380: Client close exception
# ============================================================================
async def test_unload_entry_client_close_error(hass: HomeAssistant) -> None:
"""Test error handling when client.close() fails (lines 379-380)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
# Make close() raise an exception
mock_client.close = AsyncMock(side_effect=Exception("Close failed"))
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Unload should handle close() exception gracefully (lines 379-380)
result = await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
# Should still return True despite close error
assert result
# ============================================================================
# LINES 382-384: Unload entry exception
# ============================================================================
async def test_unload_entry_unexpected_exception(hass: HomeAssistant) -> None:
"""Test unexpected exception during unload (lines 382-384)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Mock async_entries to raise an exception
with patch.object(
hass.config_entries,
"async_entries",
side_effect=Exception("Unexpected error"),
):
result = await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
# Should return False due to exception (line 384)
assert not result
# ============================================================================
# Additional Targeted Tests for Final Coverage
# ============================================================================
async def test_config_entry_update_listener_called(hass: HomeAssistant) -> None:
"""Test that config_entry_update_listener is called and logs (lines 133-134)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Update the entry data to trigger config_entry_update_listener
hass.config_entries.async_update_entry(
entry, data={**entry.data, "test": "value"}
)
await hass.async_block_till_done()
async def test_initial_state_conversion_error_valueerror(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test ValueError/TypeError during initial state float conversion (lines 212-213)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
entity_entry = entity_registry.async_get_or_create(
"sensor", "test", "text_sensor", suggested_object_id="text_sensor"
)
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: entity_entry.id,
CONF_ENERGYID_KEY: "test_sensor",
},
)
sub_entry.parent_entry_id = entry.entry_id
sub_entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_client.get_or_create_sensor = MagicMock(return_value=MagicMock())
mock_client_class.return_value = mock_client
# Make the sensor update method throw ValueError/TypeError
sensor_mock = mock_client.get_or_create_sensor.return_value
sensor_mock.update.side_effect = ValueError("Invalid timestamp")
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
async def test_state_change_untracked_entity_explicit(hass: HomeAssistant) -> None:
"""Test state change for explicitly untracked entity (line 340)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_sensor = MagicMock()
mock_client.get_or_create_sensor = MagicMock(return_value=mock_sensor)
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Change state of a completely unrelated entity that doesn't exist in any mapping
hass.states.async_set("sensor.random_unrelated_entity", "100")
await hass.async_block_till_done()
# Verify no update was made
assert mock_sensor.update.call_count == 0
async def test_subentry_missing_keys_continue(hass: HomeAssistant) -> None:
"""Test subentry with missing keys continues processing (line 324)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
# Subentry missing energyid_key (should continue)
sub_entry_missing_key = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: "some-uuid",
# Missing CONF_ENERGYID_KEY
},
)
sub_entry_missing_key.parent_entry_id = entry.entry_id
sub_entry_missing_key.add_to_hass(hass)
# Subentry missing both keys
sub_entry_empty = MockConfigEntry(
domain=DOMAIN,
data={
# Missing both CONF_HA_ENTITY_UUID and CONF_ENERGYID_KEY
},
)
sub_entry_empty.parent_entry_id = entry.entry_id
sub_entry_empty.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
async def test_entry_unloading_flag_state_change(hass: HomeAssistant) -> None:
"""Test entry unloading flag prevents state change processing (line 305)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_sensor = MagicMock()
mock_client.get_or_create_sensor = MagicMock(return_value=mock_sensor)
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Simulate entry being unloaded by removing runtime_data
del entry.runtime_data
# Try to trigger state change handler - should hit the check at line 305
# Since we can't easily trigger the actual callback, we'll just ensure the entry is cleaned up properly
assert not hasattr(entry, "runtime_data")
async def test_unload_subentries_explicit(hass: HomeAssistant) -> None:
"""Test explicit subentry unloading during entry unload (line 363)."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_PROVISIONING_KEY: "test_key",
CONF_PROVISIONING_SECRET: "test_secret",
CONF_DEVICE_ID: "test_device",
CONF_DEVICE_NAME: "Test Device",
},
)
entry.add_to_hass(hass)
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HA_ENTITY_UUID: "test-uuid",
CONF_ENERGYID_KEY: "test_key",
},
)
sub_entry.parent_entry_id = entry.entry_id
sub_entry.add_to_hass(hass)
with patch("homeassistant.components.energyid.WebhookClient") as mock_client_class:
mock_client = MagicMock()
mock_client.authenticate = AsyncMock(return_value=True)
mock_client.recordNumber = "site_123"
mock_client.recordName = "Test Site"
mock_client.webhook_policy = None
mock_client.close = AsyncMock()
mock_client_class.return_value = mock_client
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
# Unload the main entry, which should unload subentries
with patch.object(hass.config_entries, "async_entries") as mock_entries:
mock_entries.return_value = [sub_entry]
result = await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert result is True
async def test_initial_state_conversion_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test ValueError/TypeError during initial state float conversion (lines 212-213)."""
# Create entity with non-numeric state that will cause conversion error
entity_entry = entity_registry.async_get_or_create(
"sensor",
"test_platform",
"invalid_sensor",
suggested_object_id="invalid_sensor",
)
hass.states.async_set(
entity_entry.entity_id, "not_a_number"
) # This will cause ValueError
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
# ACT: Set up the integration - this should trigger the initial state processing
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ASSERT: Integration should still load successfully despite conversion error
assert mock_config_entry.state is ConfigEntryState.LOADED
# The ValueError/TypeError should be caught and logged, but not crash the setup
sensor_mock = mock_webhook_client.get_or_create_sensor.return_value
# No update should be called due to conversion error
sensor_mock.update.assert_not_called()
async def test_state_change_after_entry_unloaded(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_webhook_client: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test state change when entry is being unloaded (line 305)."""
# ARRANGE: Set up entry with a mapped entity
entity_entry = entity_registry.async_get_or_create(
"sensor", "test_platform", "power_sensor", suggested_object_id="power_sensor"
)
hass.states.async_set(entity_entry.entity_id, "100")
sub_entry = {
"data": {CONF_HA_ENTITY_UUID: entity_entry.id, CONF_ENERGYID_KEY: "grid_power"}
}
mock_config_entry.subentries = {"sub_entry_1": MagicMock(**sub_entry)}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ACT: Remove runtime_data to simulate entry being unloaded
del mock_config_entry.runtime_data
# Trigger state change - should hit line 305 and return early
hass.states.async_set(entity_entry.entity_id, "200")
await hass.async_block_till_done()
# ASSERT: No error should occur, state change should be ignored
# The test passes if no exception is raised and we reach this point
async def test_direct_state_change_handler(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Directly test the state change handler for line 324."""
# Setup
entity_entry = entity_registry.async_get_or_create("sensor", "test", "sensor1")
hass.states.async_set(entity_entry.entity_id, "100")
# Create runtime data with a mapping that will trigger the "late entity" path
runtime_data = MagicMock()
runtime_data.mappings = {} # Entity not in mappings initially
runtime_data.client = MagicMock()
runtime_data.client.get_or_create_sensor = MagicMock(return_value=MagicMock())
# Create subentries that will trigger line 324
subentry_mock = MagicMock()
subentry_mock.data = {CONF_HA_ENTITY_UUID: entity_entry.id} # No energyid_key!
mock_config_entry.subentries = {"sub1": subentry_mock}
mock_config_entry.runtime_data = runtime_data
# Create a state change event
event_data: EventStateChangedData = {
"entity_id": entity_entry.entity_id,
"new_state": hass.states.get(entity_entry.entity_id),
"old_state": None,
}
event = Event[EventStateChangedData]("state_changed", event_data)
# Directly call the handler (it's a @callback, not async)
_async_handle_state_change(hass, mock_config_entry.entry_id, event)
async def test_subentry_unload_during_entry_unload(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that subentries are unloaded when the main entry unloads."""
# Setup the entry
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Create a subentry with the correct attribute
sub_entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_HA_ENTITY_UUID: "test", CONF_ENERGYID_KEY: "test"},
)
sub_entry.parent_entry = mock_config_entry.entry_id
sub_entry.add_to_hass(hass)
# Mock the client close to avoid issues
mock_config_entry.runtime_data.client.close = AsyncMock()
# Track if async_unload was called for the subentry
original_async_unload = hass.config_entries.async_unload
subentry_unload_called = False
async def mock_async_unload(entry_id):
nonlocal subentry_unload_called
if entry_id == sub_entry.entry_id:
subentry_unload_called = True
return True
return await original_async_unload(entry_id)
# Replace the async_unload method
hass.config_entries.async_unload = mock_async_unload
# ACT: Directly call the unload function
result = await async_unload_entry(hass, mock_config_entry)
await hass.async_block_till_done()
# ASSERT: Line 363 should have been executed
assert subentry_unload_called, (
"async_unload should have been called for the subentry (line 363)"
)
assert result is True
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/energyid/test_init.py",
"license": "Apache License 2.0",
"lines": 1160,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/esphome/test_websocket_api.py | """Tests for ESPHome websocket API."""
from homeassistant.components.esphome.const import CONF_NOISE_PSK
from homeassistant.components.esphome.websocket_api import ENTRY_ID, TYPE
from tests.common import MockConfigEntry
from tests.typing import WebSocketGenerator
async def test_get_encryption_key(
init_integration: MockConfigEntry,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test get encryption key."""
mock_config_entry = init_integration
websocket_client = await hass_ws_client()
await websocket_client.send_json_auto_id(
{
TYPE: "esphome/get_encryption_key",
ENTRY_ID: mock_config_entry.entry_id,
}
)
response = await websocket_client.receive_json()
assert response["success"] is True
assert response["result"] == {
"encryption_key": mock_config_entry.data.get(CONF_NOISE_PSK)
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/esphome/test_websocket_api.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/essent/test_config_flow.py | """Tests for Essent config flow."""
from unittest.mock import AsyncMock
from essent_dynamic_pricing import (
EssentConnectionError,
EssentDataError,
EssentResponseError,
)
import pytest
from homeassistant.components.essent.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_full_flow(
hass: HomeAssistant,
mock_essent_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test successful config flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Essent"
assert result["data"] == {}
assert len(mock_setup_entry.mock_calls) == 1
async def test_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test abort 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.ABORT
assert result["reason"] == "single_instance_allowed"
@pytest.mark.parametrize(
("exception", "error"),
[
(EssentConnectionError, "cannot_connect"),
(EssentResponseError("bad"), "cannot_connect"),
(EssentDataError("bad"), "invalid_data"),
(Exception, "unknown"),
],
)
async def test_flow_errors(
hass: HomeAssistant,
mock_essent_client: AsyncMock,
mock_setup_entry: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test flow errors."""
mock_essent_client.async_get_prices.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == error
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/essent/test_config_flow.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/essent/test_init.py | """Tests for Essent integration setup."""
from unittest.mock import AsyncMock
from essent_dynamic_pricing import (
EssentConnectionError,
EssentDataError,
EssentError,
EssentResponseError,
)
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.essent.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from . import setup_integration
from tests.common import MockConfigEntry
async def test_load_unload_entry(
hass: HomeAssistant,
mock_essent_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test load and unload entry."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
async def test_device_registry(
hass: HomeAssistant,
mock_essent_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test device is registered correctly."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, mock_config_entry.entry_id)}
)
assert device_entry is not None
assert device_entry == snapshot
@pytest.mark.parametrize(
"exception",
[
EssentConnectionError("fail"),
EssentResponseError("bad"),
EssentDataError("bad"),
EssentError("boom"),
],
)
async def test_setup_retry_on_error(
hass: HomeAssistant,
mock_essent_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
) -> None:
"""Test setup retries on client errors."""
mock_essent_client.async_get_prices.side_effect = exception
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/essent/test_init.py",
"license": "Apache License 2.0",
"lines": 60,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/essent/test_sensor.py | """Tests for Essent sensors."""
from datetime import timedelta
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.essent.const import UPDATE_INTERVAL
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 tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
# Freeze time to match fixture download moment (2025-11-24 at 14:11 CET)
pytestmark = pytest.mark.freeze_time("2025-11-24T14:11:00+01:00")
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_essent_client")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test all sensor entities via snapshot."""
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "mock_essent_client")
async def test_sensor_updates_on_hour_tick(
hass: HomeAssistant,
mock_essent_client: AsyncMock,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test sensors update when hourly listener fires."""
await setup_integration(hass, mock_config_entry)
# Initial fetch on setup
assert mock_essent_client.async_get_prices.call_count == 1
assert (
hass.states.get("sensor.essent_current_electricity_market_price").state
== "0.17595"
)
# Jump exactly to the next hour boundary from the current frozen time
now = dt_util.utcnow()
minutes_until_hour = 60 - now.minute
freezer.tick(timedelta(minutes=minutes_until_hour))
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Hourly tick should not trigger an extra API call
assert mock_essent_client.async_get_prices.call_count == 1
assert (
hass.states.get("sensor.essent_current_electricity_market_price").state
== "0.21181"
)
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert mock_essent_client.async_get_prices.call_count == 2
assert (
hass.states.get("sensor.essent_current_electricity_market_price").state
== "0.24535"
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/essent/test_sensor.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/fan/test_trigger.py | """Test fan trigger."""
from typing import Any
import pytest
from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID, STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_fans(hass: HomeAssistant) -> list[str]:
"""Create multiple fan entities associated with different targets."""
return (await target_entities(hass, "fan"))["included"]
@pytest.mark.parametrize(
"trigger_key",
[
"fan.turned_off",
"fan.turned_on",
],
)
async def test_fan_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the fan triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("fan"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="fan.turned_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_trigger_states(
trigger="fan.turned_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_fan_state_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_fans: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the fan state trigger fires when any fan state changes to a specific state."""
other_entity_ids = set(target_fans) - {entity_id}
# Set all fans, including the tested fan, to the initial state
for eid in target_fans:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other fans also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("fan"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="fan.turned_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_trigger_states(
trigger="fan.turned_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_fan_state_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_fans: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the fan state trigger fires when the first fan changes to a specific state."""
other_entity_ids = set(target_fans) - {entity_id}
# Set all fans, including the tested fan, to the initial state
for eid in target_fans:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other fans should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("fan"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="fan.turned_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_trigger_states(
trigger="fan.turned_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_fan_state_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_fans: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the fan state trigger fires when the last fan changes to a specific state."""
other_entity_ids = set(target_fans) - {entity_id}
# Set all fans, including the tested fan, to the initial state
for eid in target_fans:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/fan/test_trigger.py",
"license": "Apache License 2.0",
"lines": 188,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/go2rtc/test_docker_version.py | """Test that the go2rtc Docker image version matches or exceeds the recommended version.
This test ensures that the go2rtc Docker image SHA pinned in
script/hassfest/docker.py corresponds to a version that is equal to or
greater than the RECOMMENDED_VERSION defined in homeassistant/components/go2rtc/const.py.
The test pulls the Docker image using the pinned SHA and runs the
`go2rtc --version` command inside the container to extract the version,
then compares it against RECOMMENDED_VERSION.
"""
import asyncio
import os
import re
from awesomeversion import AwesomeVersion
import pytest
from homeassistant.components.go2rtc.const import RECOMMENDED_VERSION
from script.hassfest.docker import _GO2RTC_SHA as DOCKER_SHA
async def _get_version_from_docker_sha() -> str:
"""Extract go2rtc version from Docker image using the pinned SHA."""
image = f"ghcr.io/alexxit/go2rtc@sha256:{DOCKER_SHA}"
pull_process = await asyncio.create_subprocess_exec(
"docker",
"pull",
image,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
_, pull_stderr = await pull_process.communicate()
if pull_process.returncode != 0:
raise RuntimeError(f"Failed to pull go2rtc image: {pull_stderr.decode()}")
# Run the container to get version
run_process = await asyncio.create_subprocess_exec(
"docker",
"run",
"--rm",
image,
"go2rtc",
"--version",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
run_stdout, run_stderr = await run_process.communicate()
if run_process.returncode != 0:
raise RuntimeError(f"Failed to run go2rtc --version: {run_stderr.decode()}")
# Parse version from output
# Expected output format: "go2rtc version 1.9.12 (commit) linux/amd64" or similar
output = run_stdout.decode().strip()
version_match = re.search(r"version\s+([\d.]+)", output)
if not version_match:
raise RuntimeError(f"Could not parse version from go2rtc output: {output}")
return version_match.group(1)
@pytest.mark.skipif(
not os.environ.get("CI"),
reason="This test requires Docker and only runs in CI",
)
async def test_docker_version_matches_recommended() -> None:
"""Test that the go2rtc Docker SHA version matches or exceeds RECOMMENDED_VERSION."""
# Extract version from the actual Docker container
docker_version_str = await _get_version_from_docker_sha()
# Parse versions
docker_version = AwesomeVersion(docker_version_str)
recommended_version = AwesomeVersion(RECOMMENDED_VERSION)
# Assert that Docker version is equal to or greater than recommended version
assert docker_version >= recommended_version, (
f"go2rtc Docker version ({docker_version}) is less than "
f"RECOMMENDED_VERSION ({recommended_version}). "
"Please update _GO2RTC_SHA in script/hassfest/docker.py to a newer version"
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/go2rtc/test_docker_version.py",
"license": "Apache License 2.0",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/goodwe/test_init.py | """Test the GoodWe initialization."""
from unittest.mock import MagicMock
from homeassistant.components.goodwe import CONF_MODEL_FAMILY, DOMAIN
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from .conftest import TEST_HOST, TEST_PORT
from tests.common import MockConfigEntry
async def test_migration(
hass: HomeAssistant,
mock_inverter: MagicMock,
) -> None:
"""Test config entry migration."""
config_entry = MockConfigEntry(
version=1,
domain=DOMAIN,
data={
CONF_HOST: TEST_HOST,
CONF_MODEL_FAMILY: "MagicMock",
},
entry_id="3bd2acb0e4f0476d40865546d0d91921",
)
config_entry.add_to_hass(hass)
assert await async_setup_component(hass, DOMAIN, {})
assert config_entry.version == 2
assert config_entry.data[CONF_HOST] == TEST_HOST
assert config_entry.data[CONF_MODEL_FAMILY] == "MagicMock"
assert config_entry.data[CONF_PORT] == TEST_PORT
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/goodwe/test_init.py",
"license": "Apache License 2.0",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_air_quality/test_config_flow.py | """Test the Google Air Quality config flow."""
from unittest.mock import AsyncMock
from google_air_quality_api.exceptions import GoogleAirQualityApiError
import pytest
from homeassistant.components.google_air_quality.const import (
CONF_REFERRER,
DOMAIN,
SECTION_API_KEY_OPTIONS,
)
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import (
CONF_API_KEY,
CONF_LATITUDE,
CONF_LOCATION,
CONF_LONGITUDE,
CONF_NAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry, get_schema_suggested_value
def _assert_create_entry_result(
result: dict, expected_referrer: str | None = None
) -> None:
"""Assert that the result is a create entry result."""
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Google Air Quality"
assert result["data"] == {
CONF_API_KEY: "test-api-key",
CONF_REFERRER: expected_referrer,
}
assert len(result["subentries"]) == 1
subentry = result["subentries"][0]
assert subentry["subentry_type"] == "location"
assert subentry["title"] == "test-name"
assert subentry["data"] == {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
}
async def test_create_entry(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_api: AsyncMock,
) -> 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["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
mock_api.async_get_current_conditions.assert_called_once_with(lat=10.1, lon=20.1)
_assert_create_entry_result(result)
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_with_referrer(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_api: AsyncMock,
) -> None:
"""Test we get the form and optional referrer is specified."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
SECTION_API_KEY_OPTIONS: {
CONF_REFERRER: "test-referrer",
},
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
mock_api.async_get_current_conditions.assert_called_once_with(lat=10.1, lon=20.1)
_assert_create_entry_result(result, expected_referrer="test-referrer")
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("api_exception", "expected_error"),
[
(GoogleAirQualityApiError(), "cannot_connect"),
(ValueError(), "unknown"),
],
)
async def test_form_exceptions(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_api: AsyncMock,
api_exception,
expected_error,
) -> None:
"""Test we handle exceptions."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_api.async_get_current_conditions.side_effect = api_exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": expected_error}
# On error, the form should have the previous user input
data_schema = result["data_schema"].schema
assert get_schema_suggested_value(data_schema, CONF_NAME) == "test-name"
assert get_schema_suggested_value(data_schema, CONF_API_KEY) == "test-api-key"
assert get_schema_suggested_value(data_schema, CONF_LOCATION) == {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
}
# Make sure the config flow tests finish with either an
# FlowResultType.CREATE_ENTRY or FlowResultType.ABORT so
# we can show the config flow is able to recover from an error.
mock_api.async_get_current_conditions.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
_assert_create_entry_result(result)
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_api_key_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api: AsyncMock,
) -> None:
"""Test user input for config_entry with API key that already exists."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.2,
CONF_LONGITUDE: 20.2,
},
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_api.async_get_current_conditions.call_count == 0
async def test_form_location_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api: AsyncMock,
) -> None:
"""Test user input for a location that already exists."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "another-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1001,
CONF_LONGITUDE: 20.0999,
},
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_api.async_get_current_conditions.call_count == 0
async def test_form_not_already_configured(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_api: AsyncMock,
) -> None:
"""Test user input for config_entry different than the existing one."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "new-test-name",
CONF_API_KEY: "new-test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1002,
CONF_LONGITUDE: 20.0998,
},
},
)
mock_api.async_get_current_conditions.assert_called_once_with(
lat=10.1002, lon=20.0998
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Google Air Quality"
assert result["data"] == {
CONF_API_KEY: "new-test-api-key",
CONF_REFERRER: None,
}
assert len(result["subentries"]) == 1
subentry = result["subentries"][0]
assert subentry["subentry_type"] == "location"
assert subentry["title"] == "new-test-name"
assert subentry["data"] == {
CONF_LATITUDE: 10.1002,
CONF_LONGITUDE: 20.0998,
}
assert len(mock_setup_entry.mock_calls) == 2
async def test_subentry_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api: AsyncMock,
) -> None:
"""Test creating a location subentry."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# After initial setup for 1 subentry, each API is called once
assert mock_api.async_get_current_conditions.call_count == 1
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "location"),
context={"source": "user"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "location"
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_NAME: "Work",
CONF_LOCATION: {
CONF_LATITUDE: 30.1,
CONF_LONGITUDE: 40.1,
},
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Work"
assert result["data"] == {
CONF_LATITUDE: 30.1,
CONF_LONGITUDE: 40.1,
}
# Initial setup: 1 of each API call
# Subentry flow validation: 1 current conditions call
# Reload with 2 subentries: 2 of each API call
assert mock_api.async_get_current_conditions.call_count == 1 + 1 + 2
entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert len(entry.subentries) == 2
async def test_subentry_flow_location_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api: AsyncMock,
) -> None:
"""Test user input for a location that already exists."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "location"),
context={"source": "user"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "location"
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_NAME: "Work",
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "location_already_configured"
entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert len(entry.subentries) == 1
async def test_subentry_flow_location_name_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api: AsyncMock,
) -> None:
"""Test user input for a location name that already exists."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "location"),
context={"source": "user"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "location"
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_NAME: "Home",
CONF_LOCATION: {
CONF_LATITUDE: 30.1,
CONF_LONGITUDE: 40.1,
},
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "location_name_already_configured"
entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert len(entry.subentries) == 1
async def test_subentry_flow_entry_not_loaded(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test creating a location subentry when the parent entry is not loaded."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "location"),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "entry_not_loaded"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_air_quality/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 343,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_air_quality/test_init.py | """Tests for Google Air Quality."""
from unittest.mock import AsyncMock
from google_air_quality_api.exceptions import GoogleAirQualityApiError
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api: AsyncMock,
) -> None:
"""Test successful setup and unload."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
async def test_config_not_ready(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_api: AsyncMock,
) -> None:
"""Test for setup failure if an API call fails."""
mock_config_entry.add_to_hass(hass)
mock_api.async_get_current_conditions.side_effect = GoogleAirQualityApiError()
await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_air_quality/test_init.py",
"license": "Apache License 2.0",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_air_quality/test_sensor.py | """Test the Google Air Quality sensor."""
from unittest.mock import AsyncMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
async def test_sensor_snapshot(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_api: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot test of the sensors."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.LOADED
with patch(
"homeassistant.components.google_air_quality.PLATFORMS",
[Platform.SENSOR],
):
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_air_quality/test_sensor.py",
"license": "Apache License 2.0",
"lines": 26,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_weather/test_config_flow.py | """Test the Google Weather config flow."""
from unittest.mock import AsyncMock
from google_weather_api import GoogleWeatherApiError
import pytest
from homeassistant import config_entries
from homeassistant.components.google_weather.const import (
CONF_REFERRER,
DOMAIN,
SECTION_API_KEY_OPTIONS,
)
from homeassistant.const import (
CONF_API_KEY,
CONF_LATITUDE,
CONF_LOCATION,
CONF_LONGITUDE,
CONF_NAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry, get_schema_suggested_value
def _assert_create_entry_result(
result: dict, expected_referrer: str | None = None
) -> None:
"""Assert that the result is a create entry result."""
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Google Weather"
assert result["data"] == {
CONF_API_KEY: "test-api-key",
CONF_REFERRER: expected_referrer,
}
assert len(result["subentries"]) == 1
subentry = result["subentries"][0]
assert subentry["subentry_type"] == "location"
assert subentry["title"] == "test-name"
assert subentry["data"] == {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
}
async def test_create_entry(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test creating a config entry."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
mock_google_weather_api.async_get_current_conditions.assert_called_once_with(
latitude=10.1, longitude=20.1
)
_assert_create_entry_result(result)
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_with_referrer(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test we get the form and optional referrer is specified."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
SECTION_API_KEY_OPTIONS: {
CONF_REFERRER: "test-referrer",
},
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
mock_google_weather_api.async_get_current_conditions.assert_called_once_with(
latitude=10.1, longitude=20.1
)
_assert_create_entry_result(result, expected_referrer="test-referrer")
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("api_exception", "expected_error"),
[
(GoogleWeatherApiError(), "cannot_connect"),
(ValueError(), "unknown"),
],
)
async def test_form_exceptions(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_google_weather_api: AsyncMock,
api_exception,
expected_error,
) -> None:
"""Test we handle exceptions."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
mock_google_weather_api.async_get_current_conditions.side_effect = api_exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": expected_error}
# On error, the form should have the previous user input
data_schema = result["data_schema"].schema
assert get_schema_suggested_value(data_schema, CONF_NAME) == "test-name"
assert get_schema_suggested_value(data_schema, CONF_API_KEY) == "test-api-key"
assert get_schema_suggested_value(data_schema, CONF_LOCATION) == {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
}
# Make sure the config flow tests finish with either an
# FlowResultType.CREATE_ENTRY or FlowResultType.ABORT so
# we can show the config flow is able to recover from an error.
mock_google_weather_api.async_get_current_conditions.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
_assert_create_entry_result(result)
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_api_key_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test user input for config_entry with API key that already exists."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.2,
CONF_LONGITUDE: 20.2,
},
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_google_weather_api.async_get_current_conditions.call_count == 0
async def test_form_location_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test user input for a location that already exists."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "test-name",
CONF_API_KEY: "another-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1001,
CONF_LONGITUDE: 20.0999,
},
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_google_weather_api.async_get_current_conditions.call_count == 0
async def test_form_not_already_configured(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test user input for config_entry different than the existing one."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_NAME: "new-test-name",
CONF_API_KEY: "new-test-api-key",
CONF_LOCATION: {
CONF_LATITUDE: 10.1002,
CONF_LONGITUDE: 20.0998,
},
},
)
mock_google_weather_api.async_get_current_conditions.assert_called_once_with(
latitude=10.1002, longitude=20.0998
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Google Weather"
assert result["data"] == {
CONF_API_KEY: "new-test-api-key",
CONF_REFERRER: None,
}
assert len(result["subentries"]) == 1
subentry = result["subentries"][0]
assert subentry["subentry_type"] == "location"
assert subentry["title"] == "new-test-name"
assert subentry["data"] == {
CONF_LATITUDE: 10.1002,
CONF_LONGITUDE: 20.0998,
}
assert len(mock_setup_entry.mock_calls) == 2
async def test_subentry_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test creating a location subentry."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# After initial setup for 1 subentry, each API is called once
assert mock_google_weather_api.async_get_current_conditions.call_count == 1
assert mock_google_weather_api.async_get_daily_forecast.call_count == 1
assert mock_google_weather_api.async_get_hourly_forecast.call_count == 1
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "location"),
context={"source": "user"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "location"
result2 = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_NAME: "Work",
CONF_LOCATION: {
CONF_LATITUDE: 30.1,
CONF_LONGITUDE: 40.1,
},
},
)
await hass.async_block_till_done()
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["title"] == "Work"
assert result2["data"] == {
CONF_LATITUDE: 30.1,
CONF_LONGITUDE: 40.1,
}
# Initial setup: 1 of each API call
# Subentry flow validation: 1 current conditions call
# Reload with 2 subentries: 2 of each API call
assert mock_google_weather_api.async_get_current_conditions.call_count == 1 + 1 + 2
assert mock_google_weather_api.async_get_daily_forecast.call_count == 1 + 2
assert mock_google_weather_api.async_get_hourly_forecast.call_count == 1 + 2
entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert len(entry.subentries) == 2
async def test_subentry_flow_location_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test user input for a location that already exists."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "location"),
context={"source": "user"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "location"
result2 = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_NAME: "Work",
CONF_LOCATION: {
CONF_LATITUDE: 10.1,
CONF_LONGITUDE: 20.1,
},
},
)
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "already_configured"
entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert len(entry.subentries) == 1
async def test_subentry_flow_entry_not_loaded(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test creating a location subentry when the parent entry is not loaded."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.config_entries.async_unload(mock_config_entry.entry_id)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "location"),
context={"source": "user"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "entry_not_loaded"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_weather/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 319,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_weather/test_init.py | """Test init of Google Weather integration."""
from unittest.mock import AsyncMock
from google_weather_api import GoogleWeatherApiError
import pytest
from homeassistant.components.google_weather.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_async_setup_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test a successful setup entry."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.LOADED
state = hass.states.get("weather.home")
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert state.state == "sunny"
@pytest.mark.parametrize(
"failing_api_method",
[
"async_get_current_conditions",
"async_get_daily_forecast",
"async_get_hourly_forecast",
],
)
async def test_config_not_ready(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
failing_api_method: str,
) -> None:
"""Test for setup failure if an API call fails."""
getattr(
mock_google_weather_api, failing_api_method
).side_effect = GoogleWeatherApiError()
await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_unload_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test successful unload of entry."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert mock_config_entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_weather/test_init.py",
"license": "Apache License 2.0",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_weather/test_sensor.py | """Test sensor of Google Weather integration."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from google_weather_api import GoogleWeatherApiError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.homeassistant import (
DOMAIN as HOMEASSISTANT_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_UNIT_OF_MEASUREMENT,
STATE_UNAVAILABLE,
Platform,
UnitOfLength,
UnitOfPressure,
UnitOfSpeed,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
mock_google_weather_api: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test states of the sensor."""
with patch("homeassistant.components.google_weather._PLATFORMS", [Platform.SENSOR]):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_availability(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Ensure that we mark the entities unavailable correctly when service is offline."""
entity_id = "sensor.home_temperature"
await hass.config_entries.async_setup(mock_config_entry.entry_id)
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "13.7"
mock_google_weather_api.async_get_current_conditions.side_effect = (
GoogleWeatherApiError()
)
freezer.tick(timedelta(minutes=15))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNAVAILABLE
mock_google_weather_api.async_get_current_conditions.side_effect = None
freezer.tick(timedelta(minutes=15))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "13.7"
mock_google_weather_api.async_get_current_conditions.assert_called_with(
latitude=10.1, longitude=20.1
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_manual_update_entity(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test manual update entity via service homeassistant/update_entity."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await async_setup_component(hass, HOMEASSISTANT_DOMAIN, {})
mock_google_weather_api.async_get_current_conditions.assert_called_once_with(
latitude=10.1, longitude=20.1
)
await hass.services.async_call(
HOMEASSISTANT_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: ["sensor.home_temperature"]},
blocking=True,
)
assert mock_google_weather_api.async_get_current_conditions.call_count == 2
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_imperial_units(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test states of the sensor with imperial units."""
hass.config.units = US_CUSTOMARY_SYSTEM
await hass.config_entries.async_setup(mock_config_entry.entry_id)
state = hass.states.get("sensor.home_temperature")
assert state
assert state.state == "56.66"
assert (
state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfTemperature.FAHRENHEIT
)
state = hass.states.get("sensor.home_wind_speed")
assert state
assert float(state.state) == pytest.approx(4.97097)
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfSpeed.MILES_PER_HOUR
state = hass.states.get("sensor.home_visibility")
assert state
assert float(state.state) == pytest.approx(9.94194)
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfLength.MILES
state = hass.states.get("sensor.home_atmospheric_pressure")
assert state
assert float(state.state) == pytest.approx(30.09578)
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfPressure.INHG
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_state_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Ensure the sensor state changes after updating the data."""
entity_id = "sensor.home_temperature"
await hass.config_entries.async_setup(mock_config_entry.entry_id)
state = hass.states.get(entity_id)
assert state
assert state.state == "13.7"
mock_google_weather_api.async_get_current_conditions.return_value.temperature.degrees = 15.0
freezer.tick(timedelta(minutes=15))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "15.0"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_weather/test_sensor.py",
"license": "Apache License 2.0",
"lines": 138,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_weather/test_weather.py | """Test weather of Google Weather integration."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from google_weather_api import GoogleWeatherApiError, WeatherCondition
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.google_weather.weather import _CONDITION_MAP
from homeassistant.components.homeassistant import (
DOMAIN as HOMEASSISTANT_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.weather import (
ATTR_CONDITION_CLEAR_NIGHT,
ATTR_CONDITION_PARTLYCLOUDY,
ATTR_CONDITION_SUNNY,
DOMAIN as WEATHER_DOMAIN,
SERVICE_GET_FORECASTS,
)
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.setup import async_setup_component
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
from tests.typing import WebSocketGenerator
async def test_weather(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test states of the weather."""
with patch(
"homeassistant.components.google_weather._PLATFORMS", [Platform.WEATHER]
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_availability(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Ensure that we mark the entities unavailable correctly when service is offline."""
entity_id = "weather.home"
await hass.config_entries.async_setup(mock_config_entry.entry_id)
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "sunny"
mock_google_weather_api.async_get_current_conditions.side_effect = (
GoogleWeatherApiError()
)
freezer.tick(timedelta(minutes=15))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNAVAILABLE
# Reset side effect, return a valid response again
mock_google_weather_api.async_get_current_conditions.side_effect = None
freezer.tick(timedelta(minutes=15))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "sunny"
mock_google_weather_api.async_get_current_conditions.assert_called_with(
latitude=10.1, longitude=20.1
)
async def test_manual_update_entity(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test manual update entity via service homeassistant/update_entity."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await async_setup_component(hass, HOMEASSISTANT_DOMAIN, {})
assert mock_google_weather_api.async_get_current_conditions.call_count == 1
mock_google_weather_api.async_get_current_conditions.assert_called_with(
latitude=10.1, longitude=20.1
)
await hass.services.async_call(
HOMEASSISTANT_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: ["weather.home"]},
blocking=True,
)
assert mock_google_weather_api.async_get_current_conditions.call_count == 2
@pytest.mark.parametrize(
("api_condition", "is_daytime", "expected_ha_condition"),
[
(WeatherCondition.Type.CLEAR, True, ATTR_CONDITION_SUNNY),
(WeatherCondition.Type.CLEAR, False, ATTR_CONDITION_CLEAR_NIGHT),
(WeatherCondition.Type.PARTLY_CLOUDY, True, ATTR_CONDITION_PARTLYCLOUDY),
(WeatherCondition.Type.PARTLY_CLOUDY, False, ATTR_CONDITION_PARTLYCLOUDY),
(WeatherCondition.Type.TYPE_UNSPECIFIED, True, "unknown"),
],
)
async def test_condition(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_google_weather_api: AsyncMock,
api_condition: WeatherCondition.Type,
is_daytime: bool,
expected_ha_condition: str,
) -> None:
"""Test condition mapping."""
mock_google_weather_api.async_get_current_conditions.return_value.weather_condition.type = api_condition
mock_google_weather_api.async_get_current_conditions.return_value.is_daytime = (
is_daytime
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
state = hass.states.get("weather.home")
assert state.state == expected_ha_condition
def test_all_conditions_mapped() -> None:
"""Ensure all WeatherCondition.Type enum members are in the _CONDITION_MAP."""
for condition_type in WeatherCondition.Type:
assert condition_type in _CONDITION_MAP
@pytest.mark.parametrize(("forecast_type"), ["daily", "hourly", "twice_daily"])
async def test_forecast_service(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
mock_google_weather_api: AsyncMock,
forecast_type,
) -> None:
"""Test forecast service."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
response = await hass.services.async_call(
WEATHER_DOMAIN,
SERVICE_GET_FORECASTS,
{
"entity_id": "weather.home",
"type": forecast_type,
},
blocking=True,
return_response=True,
)
assert response == snapshot
async def test_forecast_subscription(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
hass_ws_client: WebSocketGenerator,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
mock_google_weather_api: AsyncMock,
) -> None:
"""Test multiple forecast."""
client = await hass_ws_client(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await client.send_json_auto_id(
{
"type": "weather/subscribe_forecast",
"forecast_type": "daily",
"entity_id": "weather.home",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] is None
subscription_id = msg["id"]
msg = await client.receive_json()
assert msg["id"] == subscription_id
assert msg["type"] == "event"
forecast1 = msg["event"]["forecast"]
assert forecast1 != []
assert forecast1 == snapshot
freezer.tick(timedelta(hours=1) + timedelta(seconds=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
msg = await client.receive_json()
assert msg["id"] == subscription_id
assert msg["type"] == "event"
forecast2 = msg["event"]["forecast"]
assert forecast2 != []
assert forecast2 == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_weather/test_weather.py",
"license": "Apache License 2.0",
"lines": 179,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hanna/test_config_flow.py | """Tests for the Hanna Instruments integration config flow."""
from unittest.mock import AsyncMock, MagicMock
from hanna_cloud import AuthenticationError
import pytest
from requests.exceptions import ConnectionError as RequestsConnectionError, Timeout
from homeassistant.components.hanna.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_full_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_hanna_client: MagicMock,
) -> 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_EMAIL: "test@example.com",
CONF_PASSWORD: "test-password",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test@example.com"
assert result["data"] == {
CONF_EMAIL: "test@example.com",
CONF_PASSWORD: "test-password",
}
assert result["result"].unique_id == "test@example.com"
@pytest.mark.parametrize(
("exception", "expected_error"),
[
(
AuthenticationError("Authentication failed"),
"invalid_auth",
),
(
Timeout("Connection timeout"),
"cannot_connect",
),
(
RequestsConnectionError("Connection failed"),
"cannot_connect",
),
],
)
async def test_error_scenarios(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_hanna_client: MagicMock,
exception: Exception,
expected_error: str,
) -> None:
"""Test various error scenarios in the config flow."""
mock_hanna_client.authenticate.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_EMAIL: "test@example.com", CONF_PASSWORD: "test-password"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": expected_error}
# Repatch to succeed and complete the flow
mock_hanna_client.authenticate.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_EMAIL: "test@example.com", CONF_PASSWORD: "test-password"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test@example.com"
assert result["data"] == {
CONF_EMAIL: "test@example.com",
CONF_PASSWORD: "test-password",
}
async def test_duplicate_entry(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_hanna_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that duplicate entries are aborted."""
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_EMAIL: "test@example.com", CONF_PASSWORD: "test-password"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hanna/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 108,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hue_ble/test_config_flow.py | """Test the Hue BLE config flow."""
from unittest.mock import AsyncMock, PropertyMock, patch
from habluetooth import BluetoothServiceInfoBleak
from HueBLE import ConnectionError, HueBleError, PairingError
import pytest
from homeassistant.components.hue_ble.config_flow import Error
from homeassistant.components.hue_ble.const import (
DOMAIN,
URL_FACTORY_RESET,
URL_PAIRING_MODE,
)
from homeassistant.config_entries import SOURCE_BLUETOOTH, SOURCE_USER
from homeassistant.const import CONF_MAC, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import device_registry as dr
from . import (
HUE_BLE_SERVICE_INFO,
NOT_HUE_BLE_DISCOVERY_INFO,
TEST_DEVICE_MAC,
TEST_DEVICE_NAME,
)
from tests.common import MockConfigEntry
from tests.components.bluetooth import BLEDevice, generate_ble_device
AUTH_ERROR = ConnectionError()
AUTH_ERROR.__cause__ = PairingError()
async def test_user_form(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
) -> None:
"""Test user form."""
with patch(
"homeassistant.components.hue_ble.config_flow.bluetooth.async_discovered_service_info",
return_value=[NOT_HUE_BLE_DISCOVERY_INFO, HUE_BLE_SERVICE_INFO],
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["data_schema"].schema[CONF_MAC].container == {
HUE_BLE_SERVICE_INFO.address: (
f"{HUE_BLE_SERVICE_INFO.name} ({HUE_BLE_SERVICE_INFO.address})"
),
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_MAC: HUE_BLE_SERVICE_INFO.address},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "confirm"
assert result["description_placeholders"] == {
CONF_NAME: TEST_DEVICE_NAME,
CONF_MAC: TEST_DEVICE_MAC,
"url_pairing_mode": URL_PAIRING_MODE,
"url_factory_reset": URL_FACTORY_RESET,
}
with (
patch(
"homeassistant.components.hue_ble.config_flow.async_ble_device_from_address",
return_value=generate_ble_device(TEST_DEVICE_NAME, TEST_DEVICE_MAC),
),
patch(
"homeassistant.components.hue_ble.config_flow.async_scanner_count",
return_value=1,
),
patch(
"homeassistant.components.hue_ble.config_flow.HueBleLight.connect",
side_effect=[True],
),
patch(
"homeassistant.components.hue_ble.config_flow.HueBleLight.poll_state",
side_effect=[True],
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == TEST_DEVICE_NAME
assert result["result"].unique_id == dr.format_mac(TEST_DEVICE_MAC)
assert result["result"].data == {}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize("discovery_info", [[NOT_HUE_BLE_DISCOVERY_INFO], []])
async def test_user_form_no_device(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
discovery_info: list[BluetoothServiceInfoBleak],
) -> None:
"""Test user form with no devices."""
with patch(
"homeassistant.components.hue_ble.config_flow.bluetooth.async_discovered_service_info",
return_value=discovery_info,
):
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"
@pytest.mark.parametrize(
(
"mock_return_device",
"mock_scanner_count",
"mock_connect",
"mock_support_on_off",
"mock_poll_state",
"error",
),
[
(
None,
0,
None,
True,
None,
Error.NO_SCANNERS,
),
(
None,
1,
None,
True,
None,
Error.NOT_FOUND,
),
(
generate_ble_device(TEST_DEVICE_NAME, TEST_DEVICE_MAC),
1,
AUTH_ERROR,
True,
None,
Error.INVALID_AUTH,
),
(
generate_ble_device(TEST_DEVICE_NAME, TEST_DEVICE_MAC),
1,
ConnectionError,
True,
None,
Error.CANNOT_CONNECT,
),
(
generate_ble_device(TEST_DEVICE_NAME, TEST_DEVICE_MAC),
1,
None,
False,
None,
Error.NOT_SUPPORTED,
),
(
generate_ble_device(TEST_DEVICE_NAME, TEST_DEVICE_MAC),
1,
None,
True,
HueBleError,
Error.UNKNOWN,
),
(
generate_ble_device(TEST_DEVICE_NAME, TEST_DEVICE_MAC),
1,
HueBleError,
None,
None,
Error.UNKNOWN,
),
],
ids=[
"no_scanners",
"not_found",
"invalid_auth",
"cannot_connect",
"not_supported",
"cannot_poll",
"unknown",
],
)
async def test_user_form_exception(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_return_device: BLEDevice | None,
mock_scanner_count: int,
mock_connect: Exception | None,
mock_support_on_off: bool,
mock_poll_state: Exception | None,
error: Error,
) -> None:
"""Test user form with errors."""
with patch(
"homeassistant.components.hue_ble.config_flow.bluetooth.async_discovered_service_info",
return_value=[NOT_HUE_BLE_DISCOVERY_INFO, HUE_BLE_SERVICE_INFO],
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["data_schema"].schema[CONF_MAC].container == {
HUE_BLE_SERVICE_INFO.address: (
f"{HUE_BLE_SERVICE_INFO.name} ({HUE_BLE_SERVICE_INFO.address})"
),
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_MAC: HUE_BLE_SERVICE_INFO.address},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "confirm"
with (
patch(
"homeassistant.components.hue_ble.config_flow.async_ble_device_from_address",
return_value=mock_return_device,
),
patch(
"homeassistant.components.hue_ble.config_flow.async_scanner_count",
return_value=mock_scanner_count,
),
patch(
"homeassistant.components.hue_ble.config_flow.HueBleLight.connect",
side_effect=[mock_connect],
),
patch(
"homeassistant.components.hue_ble.config_flow.HueBleLight.supports_on_off",
new_callable=PropertyMock,
return_value=mock_support_on_off,
),
patch(
"homeassistant.components.hue_ble.config_flow.HueBleLight.poll_state",
side_effect=[mock_poll_state],
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error.value}
with (
patch(
"homeassistant.components.hue_ble.config_flow.async_ble_device_from_address",
return_value=generate_ble_device(TEST_DEVICE_NAME, TEST_DEVICE_MAC),
),
patch(
"homeassistant.components.hue_ble.config_flow.async_scanner_count",
return_value=1,
),
patch(
"homeassistant.components.hue_ble.config_flow.HueBleLight.connect",
side_effect=[True],
),
patch(
"homeassistant.components.hue_ble.config_flow.HueBleLight.poll_state",
side_effect=[True],
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_bluetooth_discovery_aborts(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
) -> None:
"""Test bluetooth form aborts."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_BLUETOOTH},
data=HUE_BLE_SERVICE_INFO,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "discovery_unsupported"
async def test_bluetooth_form_exception_already_set_up(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test bluetooth discovery form when device is already set up."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_BLUETOOTH},
data=HUE_BLE_SERVICE_INFO,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "discovery_unsupported"
async def test_user_form_exception_already_set_up(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test user form when device is already set up."""
mock_config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.hue_ble.config_flow.bluetooth.async_discovered_service_info",
return_value=[NOT_HUE_BLE_DISCOVERY_INFO, HUE_BLE_SERVICE_INFO],
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["data_schema"].schema[CONF_MAC].container == {
HUE_BLE_SERVICE_INFO.address: (
f"{HUE_BLE_SERVICE_INFO.name} ({HUE_BLE_SERVICE_INFO.address})"
),
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_MAC: HUE_BLE_SERVICE_INFO.address},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hue_ble/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 317,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hue_ble/test_init.py | """Test hue_ble setup process."""
from unittest.mock import patch
from bleak.backends.device import BLEDevice
from HueBLE import ConnectionError, HueBleError
import pytest
from homeassistant.components.hue_ble.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import TEST_DEVICE_MAC, TEST_DEVICE_NAME
from tests.common import MockConfigEntry
from tests.components.bluetooth import generate_ble_device
@pytest.mark.parametrize(
(
"ble_device",
"scanner_count",
"connect_result",
"poll_state_result",
"message",
),
[
(
None,
2,
True,
None,
"The light was not found.",
),
(
None,
0,
True,
None,
"No Bluetooth scanners are available to search for the light.",
),
(
generate_ble_device(TEST_DEVICE_MAC, TEST_DEVICE_NAME),
2,
False,
ConnectionError,
"Device found but unable to connect.",
),
(
generate_ble_device(TEST_DEVICE_MAC, TEST_DEVICE_NAME),
2,
True,
HueBleError,
"Device found and connected but unable to poll values from it.",
),
],
ids=["no_device", "no_scanners", "error_connect", "error_poll"],
)
async def test_setup_error(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
ble_device: BLEDevice | None,
scanner_count: int,
connect_result: Exception | None,
poll_state_result: Exception | None,
message: str,
) -> None:
"""Test that ConfigEntryNotReady is raised if there is an error condition."""
entry = MockConfigEntry(domain=DOMAIN, unique_id="abcd", data={})
entry.add_to_hass(hass)
with (
patch(
"homeassistant.components.hue_ble.async_ble_device_from_address",
return_value=ble_device,
),
patch(
"homeassistant.components.hue_ble.async_scanner_count",
return_value=scanner_count,
),
patch(
"homeassistant.components.hue_ble.HueBleLight.connect",
side_effect=[connect_result],
),
patch(
"homeassistant.components.hue_ble.HueBleLight.poll_state",
side_effect=[poll_state_result],
),
):
assert await async_setup_component(hass, DOMAIN, {}) is True
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.SETUP_RETRY
assert message in caplog.text
async def test_setup(
hass: HomeAssistant,
) -> None:
"""Test that the config is loaded if there are no errors."""
entry = MockConfigEntry(domain=DOMAIN, unique_id="abcd", data={})
entry.add_to_hass(hass)
with (
patch(
"homeassistant.components.hue_ble.async_ble_device_from_address",
return_value=generate_ble_device(TEST_DEVICE_MAC, TEST_DEVICE_NAME),
),
patch(
"homeassistant.components.hue_ble.async_scanner_count",
return_value=1,
),
patch(
"homeassistant.components.hue_ble.HueBleLight.connect",
return_value=None,
),
patch(
"homeassistant.components.hue_ble.HueBleLight.poll_state",
return_value=None,
),
):
assert await async_setup_component(hass, DOMAIN, {}) is True
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.LOADED
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hue_ble/test_init.py",
"license": "Apache License 2.0",
"lines": 113,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hue_ble/test_light.py | """Hue BLE light tests."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
async def test_light(
hass: HomeAssistant,
mock_scanner_count: AsyncMock,
mock_light: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test light entity setup."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hue_ble/test_light.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/labs/test_init.py | """Tests for the Home Assistant Labs integration setup."""
from __future__ import annotations
from typing import Any
from unittest.mock import Mock, patch
import pytest
from homeassistant.components.labs import (
EVENT_LABS_UPDATED,
EventLabsUpdatedData,
async_is_preview_feature_enabled,
async_listen,
async_subscribe_preview_feature,
async_update_preview_feature,
)
from homeassistant.components.labs.const import DOMAIN, LABS_DATA
from homeassistant.components.labs.models import LabPreviewFeature
from homeassistant.core import HomeAssistant
from homeassistant.loader import Integration
from homeassistant.setup import async_setup_component
from . import assert_stored_labs_data
from tests.common import async_capture_events
async def test_async_setup(hass: HomeAssistant) -> None:
"""Test the Labs integration setup."""
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
# Verify WebSocket commands are registered
assert "labs/list" in hass.data["websocket_api"]
assert "labs/update" in hass.data["websocket_api"]
async def test_async_is_preview_feature_enabled_not_setup(hass: HomeAssistant) -> None:
"""Test checking if preview feature is enabled before setup returns False."""
# Don't set up labs integration
result = async_is_preview_feature_enabled(hass, "kitchen_sink", "special_repair")
assert result is False
async def test_async_is_preview_feature_enabled_nonexistent(
hass: HomeAssistant,
) -> None:
"""Test checking if non-existent preview feature is enabled."""
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
result = async_is_preview_feature_enabled(
hass, "kitchen_sink", "nonexistent_feature"
)
assert result is False
async def test_async_is_preview_feature_enabled_when_enabled(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test checking if preview feature is enabled."""
# Load kitchen_sink integration so preview feature exists
hass.config.components.add("kitchen_sink")
# Enable a preview feature via storage
hass_storage["core.labs"] = {
"version": 1,
"minor_version": 1,
"key": "core.labs",
"data": {
"preview_feature_status": [
{"domain": "kitchen_sink", "preview_feature": "special_repair"}
]
},
}
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
result = async_is_preview_feature_enabled(hass, "kitchen_sink", "special_repair")
assert result is True
async def test_async_is_preview_feature_enabled_when_disabled(
hass: HomeAssistant,
) -> None:
"""Test checking if preview feature is disabled (not in storage)."""
# Load kitchen_sink integration so preview feature exists
hass.config.components.add("kitchen_sink")
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
result = async_is_preview_feature_enabled(hass, "kitchen_sink", "special_repair")
assert result is False
@pytest.mark.parametrize(
(
"features_to_store",
"expected_enabled",
"expected_cleaned",
"expected_cleaned_store",
),
[
# Single stale feature cleanup
(
[
{"domain": "kitchen_sink", "preview_feature": "special_repair"},
{"domain": "nonexistent_domain", "preview_feature": "fake_feature"},
],
[("kitchen_sink", "special_repair")],
[("nonexistent_domain", "fake_feature")],
[{"domain": "kitchen_sink", "preview_feature": "special_repair"}],
),
# Multiple stale features cleanup
(
[
{"domain": "kitchen_sink", "preview_feature": "special_repair"},
{"domain": "stale_domain_1", "preview_feature": "old_feature"},
{"domain": "stale_domain_2", "preview_feature": "another_old"},
{"domain": "stale_domain_3", "preview_feature": "yet_another"},
],
[("kitchen_sink", "special_repair")],
[
("stale_domain_1", "old_feature"),
("stale_domain_2", "another_old"),
("stale_domain_3", "yet_another"),
],
[{"domain": "kitchen_sink", "preview_feature": "special_repair"}],
),
# All features cleaned (no integrations loaded)
(
[{"domain": "nonexistent", "preview_feature": "fake"}],
[],
[("nonexistent", "fake")],
[],
),
],
)
async def test_storage_cleanup_stale_features(
hass: HomeAssistant,
hass_storage: dict[str, Any],
features_to_store: list[dict[str, str]],
expected_enabled: list[tuple[str, str]],
expected_cleaned: list[tuple[str, str]],
expected_cleaned_store: list[dict[str, str]],
) -> None:
"""Test that stale preview features are removed from storage on setup."""
# Load kitchen_sink only if we expect any features to remain
if expected_enabled:
hass.config.components.add("kitchen_sink")
hass_storage["core.labs"] = {
"version": 1,
"minor_version": 1,
"key": "core.labs",
"data": {"preview_feature_status": features_to_store},
}
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
# Verify expected features are preserved
for domain, feature in expected_enabled:
assert async_is_preview_feature_enabled(hass, domain, feature)
# Verify stale features were cleaned up
for domain, feature in expected_cleaned:
assert not async_is_preview_feature_enabled(hass, domain, feature)
assert_stored_labs_data(hass_storage, expected_cleaned_store)
@pytest.mark.parametrize(
("domain", "preview_feature", "expected"),
[
("kitchen_sink", "special_repair", True),
("other", "nonexistent", False),
("kitchen_sink", "nonexistent", False),
],
)
async def test_async_is_preview_feature_enabled(
hass: HomeAssistant,
hass_storage: dict[str, Any],
domain: str,
preview_feature: str,
expected: bool,
) -> None:
"""Test async_is_preview_feature_enabled."""
# Enable the kitchen_sink.special_repair preview feature via storage
hass_storage["core.labs"] = {
"version": 1,
"minor_version": 1,
"key": "core.labs",
"data": {
"preview_feature_status": [
{"domain": "kitchen_sink", "preview_feature": "special_repair"}
]
},
}
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
result = async_is_preview_feature_enabled(hass, domain, preview_feature)
assert result is expected
async def test_preview_feature_full_key(hass: HomeAssistant) -> None:
"""Test that preview feature full_key property returns correct format."""
feature = LabPreviewFeature(
domain="test_domain",
preview_feature="test_feature",
feedback_url="https://feedback.example.com",
)
assert feature.full_key == "test_domain.test_feature"
async def test_preview_feature_to_dict_with_all_urls(hass: HomeAssistant) -> None:
"""Test LabPreviewFeature.to_dict with all URLs populated."""
feature = LabPreviewFeature(
domain="test_domain",
preview_feature="test_feature",
feedback_url="https://feedback.example.com",
learn_more_url="https://learn.example.com",
report_issue_url="https://issue.example.com",
)
result = feature.to_dict(enabled=True)
assert result == {
"preview_feature": "test_feature",
"domain": "test_domain",
"enabled": True,
"is_built_in": True,
"feedback_url": "https://feedback.example.com",
"learn_more_url": "https://learn.example.com",
"report_issue_url": "https://issue.example.com",
}
async def test_preview_feature_to_dict_with_no_urls(hass: HomeAssistant) -> None:
"""Test LabPreviewFeature.to_dict with no URLs (all None)."""
feature = LabPreviewFeature(
domain="test_domain",
preview_feature="test_feature",
)
result = feature.to_dict(enabled=False)
assert result == {
"preview_feature": "test_feature",
"domain": "test_domain",
"enabled": False,
"is_built_in": True,
"feedback_url": None,
"learn_more_url": None,
"report_issue_url": None,
}
async def test_custom_integration_with_preview_features(
hass: HomeAssistant,
) -> None:
"""Test that custom integrations with preview features are loaded."""
# Create a mock custom integration with preview features
mock_integration = Mock(spec=Integration)
mock_integration.domain = "custom_test"
mock_integration.preview_features = {
"test_feature": {
"feedback_url": "https://feedback.test",
"learn_more_url": "https://learn.test",
}
}
with patch(
"homeassistant.components.labs.async_get_custom_components",
return_value={"custom_test": mock_integration},
):
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
# Verify the custom integration's preview feature can be checked
# (This confirms it was loaded properly)
assert not async_is_preview_feature_enabled(hass, "custom_test", "test_feature")
@pytest.mark.parametrize(
("is_custom", "expected_is_built_in"),
[
(False, True), # Built-in integration
(True, False), # Custom integration
],
)
async def test_preview_feature_is_built_in_flag(
hass: HomeAssistant,
is_custom: bool,
expected_is_built_in: bool,
) -> None:
"""Test that preview features have correct is_built_in flag."""
if is_custom:
# Create a mock custom integration
mock_integration = Mock(spec=Integration)
mock_integration.domain = "custom_test"
mock_integration.preview_features = {
"custom_feature": {"feedback_url": "https://feedback.test"}
}
with patch(
"homeassistant.components.labs.async_get_custom_components",
return_value={"custom_test": mock_integration},
):
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
feature_key = "custom_test.custom_feature"
else:
# Load built-in kitchen_sink integration
hass.config.components.add("kitchen_sink")
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
feature_key = "kitchen_sink.special_repair"
labs_data = hass.data[LABS_DATA]
assert feature_key in labs_data.preview_features
feature = labs_data.preview_features[feature_key]
assert feature.is_built_in is expected_is_built_in
@pytest.mark.parametrize(
("is_built_in", "expected_default"),
[
(True, True),
(False, False),
(None, True), # Default value when not specified
],
)
async def test_preview_feature_to_dict_is_built_in(
hass: HomeAssistant,
is_built_in: bool | None,
expected_default: bool,
) -> None:
"""Test that to_dict correctly handles is_built_in field."""
if is_built_in is None:
# Test default value
feature = LabPreviewFeature(
domain="test_domain",
preview_feature="test_feature",
)
else:
feature = LabPreviewFeature(
domain="test_domain",
preview_feature="test_feature",
is_built_in=is_built_in,
)
assert feature.is_built_in is expected_default
result = feature.to_dict(enabled=True)
assert result["is_built_in"] is expected_default
async def test_async_listen_helper(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test the async_listen helper function for preview feature events."""
# Load kitchen_sink integration
hass.config.components.add("kitchen_sink")
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
# Track listener calls
listener_calls = []
def test_listener() -> None:
"""Test listener callback."""
listener_calls.append("called")
# Subscribe to a specific preview feature
unsub = async_listen(
hass,
domain="kitchen_sink",
preview_feature="special_repair",
listener=test_listener,
)
assert ("calls `async_listen` which is deprecated") in caplog.text
# Fire event for the subscribed feature
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
},
)
await hass.async_block_till_done()
# Verify listener was called
assert len(listener_calls) == 1
# Fire event for a different feature - should not trigger listener
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{
"domain": "kitchen_sink",
"preview_feature": "other_feature",
"enabled": True,
},
)
await hass.async_block_till_done()
# Verify listener was not called again
assert len(listener_calls) == 1
# Fire event for a different domain - should not trigger listener
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{
"domain": "other_domain",
"preview_feature": "special_repair",
"enabled": True,
},
)
await hass.async_block_till_done()
# Verify listener was not called again
assert len(listener_calls) == 1
# Test unsubscribe
unsub()
# Fire event again - should not trigger listener after unsubscribe
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
},
)
await hass.async_block_till_done()
# Verify listener was not called after unsubscribe
assert len(listener_calls) == 1
async def test_async_subscribe_preview_feature_helper(hass: HomeAssistant) -> None:
"""Test async_subscribe_preview_feature helper."""
hass.config.components.add("kitchen_sink")
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
calls: list[EventLabsUpdatedData] = []
async def listener(event_data: EventLabsUpdatedData) -> None:
"""Test listener callback."""
calls.append(event_data)
unsub = async_subscribe_preview_feature(
hass,
domain="kitchen_sink",
preview_feature="special_repair",
listener=listener,
)
# Fire event for the subscribed feature
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
},
)
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0]["enabled"] is True
# Fire event for a different feature - should not trigger listener
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{
"domain": "kitchen_sink",
"preview_feature": "other_feature",
"enabled": True,
},
)
await hass.async_block_till_done()
assert len(calls) == 1
# Fire event for a different domain - should not trigger listener
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{
"domain": "other_domain",
"preview_feature": "special_repair",
"enabled": True,
},
)
await hass.async_block_till_done()
assert len(calls) == 1
# Fire event with enabled=False
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": False,
},
)
await hass.async_block_till_done()
assert len(calls) == 2
assert calls[1]["enabled"] is False
# Test unsubscribe
unsub()
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
},
)
await hass.async_block_till_done()
assert len(calls) == 2
async def test_async_update_preview_feature(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test enabling and disabling a preview feature using the helper function."""
hass.config.components.add("kitchen_sink")
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
events = async_capture_events(hass, EVENT_LABS_UPDATED)
await async_update_preview_feature(
hass, "kitchen_sink", "special_repair", enabled=True
)
await hass.async_block_till_done()
assert async_is_preview_feature_enabled(hass, "kitchen_sink", "special_repair")
assert len(events) == 1
assert events[0].data["domain"] == "kitchen_sink"
assert events[0].data["preview_feature"] == "special_repair"
assert events[0].data["enabled"] is True
assert_stored_labs_data(
hass_storage,
[{"domain": "kitchen_sink", "preview_feature": "special_repair"}],
)
await async_update_preview_feature(
hass, "kitchen_sink", "special_repair", enabled=False
)
await hass.async_block_till_done()
assert not async_is_preview_feature_enabled(hass, "kitchen_sink", "special_repair")
assert len(events) == 2
assert events[1].data["domain"] == "kitchen_sink"
assert events[1].data["preview_feature"] == "special_repair"
assert events[1].data["enabled"] is False
assert_stored_labs_data(hass_storage, [])
async def test_async_update_preview_feature_not_found(hass: HomeAssistant) -> None:
"""Test updating a preview feature that doesn't exist raises."""
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
with pytest.raises(
ValueError, match="Preview feature nonexistent.feature not found"
):
await async_update_preview_feature(hass, "nonexistent", "feature", enabled=True)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/labs/test_init.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:tests/components/labs/test_websocket_api.py | """Tests for the Home Assistant Labs WebSocket API."""
from __future__ import annotations
from typing import Any
from unittest.mock import ANY, AsyncMock, patch
import pytest
from homeassistant.components.labs import (
EVENT_LABS_UPDATED,
async_is_preview_feature_enabled,
async_setup,
)
from homeassistant.core import HomeAssistant
from . import assert_stored_labs_data
from tests.common import MockUser
from tests.typing import WebSocketGenerator
@pytest.mark.parametrize(
("load_integration", "expected_features"),
[
(False, []), # No integration loaded
(
True, # Integration loaded
[
{
"preview_feature": "special_repair",
"domain": "kitchen_sink",
"enabled": False,
"is_built_in": True,
"feedback_url": ANY,
"learn_more_url": ANY,
"report_issue_url": ANY,
}
],
),
],
)
async def test_websocket_list_preview_features(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
load_integration: bool,
expected_features: list,
) -> None:
"""Test listing preview features with different integration states."""
if load_integration:
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "labs/list"})
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {"features": expected_features}
async def test_websocket_update_preview_feature_enable(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_storage: dict[str, Any],
) -> None:
"""Test enabling a preview feature via WebSocket."""
# Load kitchen_sink integration
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
assert "core.labs" not in hass_storage
# Track events
events = []
def event_listener(event):
events.append(event)
hass.bus.async_listen(EVENT_LABS_UPDATED, event_listener)
# Enable the preview feature
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] is None
# Verify event was fired
await hass.async_block_till_done()
assert len(events) == 1
assert events[0].data["domain"] == "kitchen_sink"
assert events[0].data["preview_feature"] == "special_repair"
assert events[0].data["enabled"] is True
# Verify feature is now enabled
assert async_is_preview_feature_enabled(hass, "kitchen_sink", "special_repair")
assert_stored_labs_data(
hass_storage,
[{"domain": "kitchen_sink", "preview_feature": "special_repair"}],
)
async def test_websocket_update_preview_feature_disable(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_storage: dict[str, Any],
) -> None:
"""Test disabling a preview feature via WebSocket."""
# Pre-populate storage with enabled preview feature
hass_storage["core.labs"] = {
"version": 1,
"minor_version": 1,
"key": "core.labs",
"data": {
"preview_feature_status": [
{"domain": "kitchen_sink", "preview_feature": "special_repair"}
]
},
}
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json(
{
"id": 5,
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": False,
}
)
msg = await client.receive_json()
assert msg["success"]
# Verify feature is disabled
assert not async_is_preview_feature_enabled(hass, "kitchen_sink", "special_repair")
assert_stored_labs_data(
hass_storage,
[],
)
async def test_websocket_update_nonexistent_feature(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_storage: dict[str, Any],
) -> None:
"""Test updating a preview feature that doesn't exist."""
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "nonexistent",
"preview_feature": "feature",
"enabled": True,
}
)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "not_found"
assert "not found" in msg["error"]["message"].lower()
assert "core.labs" not in hass_storage
async def test_websocket_update_unavailable_preview_feature(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_storage: dict[str, Any],
) -> None:
"""Test updating a preview feature whose integration is not loaded still works."""
# Don't load kitchen_sink integration
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
# Preview feature is pre-loaded, so update succeeds even though integration isn't loaded
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] is None
assert_stored_labs_data(
hass_storage,
[{"domain": "kitchen_sink", "preview_feature": "special_repair"}],
)
@pytest.mark.parametrize(
"command_type",
["labs/list", "labs/update"],
)
async def test_websocket_requires_admin(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_admin_user: MockUser,
hass_storage: dict[str, Any],
command_type: str,
) -> None:
"""Test that websocket commands require admin privileges."""
# Remove admin privileges
hass_admin_user.groups = []
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
command = {"type": command_type}
if command_type == "labs/update":
command.update(
{
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
await client.send_json_auto_id(command)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "unauthorized"
assert "core.labs" not in hass_storage
async def test_websocket_update_validates_enabled_parameter(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test that enabled parameter must be boolean."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
# Try with string instead of boolean
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": "true",
}
)
msg = await client.receive_json()
assert not msg["success"]
# Validation error from voluptuous
async def test_storage_persists_preview_feature_across_calls(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_storage: dict[str, Any],
) -> None:
"""Test that storage persists preview feature state across multiple calls."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
assert "core.labs" not in hass_storage
# Enable the preview feature
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
msg = await client.receive_json()
assert msg["success"]
assert_stored_labs_data(
hass_storage,
[{"domain": "kitchen_sink", "preview_feature": "special_repair"}],
)
# List preview features - should show enabled
await client.send_json_auto_id({"type": "labs/list"})
msg = await client.receive_json()
assert msg["success"]
assert msg["result"]["features"][0]["enabled"] is True
# Disable preview feature
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": False,
}
)
msg = await client.receive_json()
assert msg["success"]
assert_stored_labs_data(
hass_storage,
[],
)
# List preview features - should show disabled
await client.send_json_auto_id({"type": "labs/list"})
msg = await client.receive_json()
assert msg["success"]
assert msg["result"]["features"][0]["enabled"] is False
async def test_preview_feature_urls_present(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test that preview features include feedback and report URLs."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "labs/list"})
msg = await client.receive_json()
assert msg["success"]
feature = msg["result"]["features"][0]
assert "feedback_url" in feature
assert "learn_more_url" in feature
assert "report_issue_url" in feature
assert feature["feedback_url"] is not None
assert feature["learn_more_url"] is not None
assert feature["report_issue_url"] is not None
@pytest.mark.parametrize(
(
"create_backup",
"backup_fails",
"enabled",
"should_call_backup",
"should_succeed",
),
[
# Enable with successful backup
(True, False, True, True, True),
# Enable with failed backup
(True, True, True, True, False),
# Disable ignores backup flag
(True, False, False, False, True),
],
ids=[
"enable_with_backup_success",
"enable_with_backup_failure",
"disable_ignores_backup",
],
)
async def test_websocket_update_preview_feature_backup_scenarios(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
create_backup: bool,
backup_fails: bool,
enabled: bool,
should_call_backup: bool,
should_succeed: bool,
) -> None:
"""Test various backup scenarios when updating preview features."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
# Mock the backup manager
mock_backup_manager = AsyncMock()
if backup_fails:
mock_backup_manager.async_create_automatic_backup = AsyncMock(
side_effect=Exception("Backup failed")
)
else:
mock_backup_manager.async_create_automatic_backup = AsyncMock()
with patch(
"homeassistant.components.labs.websocket_api.async_get_manager",
return_value=mock_backup_manager,
):
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": enabled,
"create_backup": create_backup,
}
)
msg = await client.receive_json()
if should_succeed:
assert msg["success"]
if should_call_backup:
mock_backup_manager.async_create_automatic_backup.assert_called_once()
else:
mock_backup_manager.async_create_automatic_backup.assert_not_called()
else:
assert not msg["success"]
assert msg["error"]["code"] == "unknown_error"
assert "backup" in msg["error"]["message"].lower()
# Verify preview feature was NOT enabled
assert not async_is_preview_feature_enabled(
hass, "kitchen_sink", "special_repair"
)
async def test_websocket_list_multiple_enabled_features(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_storage: dict[str, Any],
) -> None:
"""Test listing when multiple preview features are enabled."""
# Pre-populate with multiple enabled features
hass_storage["core.labs"] = {
"version": 1,
"data": {
"preview_feature_status": [
{"domain": "kitchen_sink", "preview_feature": "special_repair"},
]
},
}
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "labs/list"})
msg = await client.receive_json()
assert msg["success"]
features = msg["result"]["features"]
assert len(features) >= 1
# Verify at least one is enabled
enabled_features = [f for f in features if f["enabled"]]
assert len(enabled_features) == 1
async def test_websocket_update_rapid_toggle(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test rapid toggling of a preview feature."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
# Enable
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
msg1 = await client.receive_json()
assert msg1["success"]
# Disable immediately
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": False,
}
)
msg2 = await client.receive_json()
assert msg2["success"]
# Enable again
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
msg3 = await client.receive_json()
assert msg3["success"]
# Final state should be enabled
assert async_is_preview_feature_enabled(hass, "kitchen_sink", "special_repair")
async def test_websocket_update_same_state_idempotent(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test that enabling an already-enabled feature is idempotent."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
# Enable feature
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
msg1 = await client.receive_json()
assert msg1["success"]
# Enable again (should be idempotent)
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
msg2 = await client.receive_json()
assert msg2["success"]
# Should still be enabled
assert async_is_preview_feature_enabled(hass, "kitchen_sink", "special_repair")
async def test_websocket_list_filtered_by_loaded_components(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test that list only shows features from loaded integrations."""
# Don't load kitchen_sink - its preview feature shouldn't appear
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "labs/list"})
msg = await client.receive_json()
assert msg["success"]
# Should be empty since kitchen_sink isn't loaded
assert msg["result"]["features"] == []
# Now load kitchen_sink
hass.config.components.add("kitchen_sink")
await client.send_json_auto_id({"type": "labs/list"})
msg = await client.receive_json()
assert msg["success"]
# Now should have kitchen_sink features
assert len(msg["result"]["features"]) >= 1
async def test_websocket_update_with_missing_required_field(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test that missing required fields are rejected."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
# Missing 'enabled' field
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
# enabled is missing
}
)
msg = await client.receive_json()
assert not msg["success"]
# Should get validation error
async def test_websocket_event_data_structure(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test that event data has correct structure."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
events = []
def event_listener(event):
events.append(event)
hass.bus.async_listen(EVENT_LABS_UPDATED, event_listener)
# Enable a feature
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
await client.receive_json()
await hass.async_block_till_done()
assert len(events) == 1
event_data = events[0].data
# Verify all required fields are present
assert "domain" in event_data
assert "preview_feature" in event_data
assert "enabled" in event_data
assert event_data["domain"] == "kitchen_sink"
assert event_data["preview_feature"] == "special_repair"
assert event_data["enabled"] is True
assert isinstance(event_data["enabled"], bool)
async def test_websocket_backup_timeout_handling(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test handling of backup timeout/long-running backup."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
# Mock backup manager with timeout
mock_backup_manager = AsyncMock()
mock_backup_manager.async_create_automatic_backup = AsyncMock(
side_effect=TimeoutError("Backup timed out")
)
with patch(
"homeassistant.components.labs.websocket_api.async_get_manager",
return_value=mock_backup_manager,
):
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
"create_backup": True,
}
)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "unknown_error"
async def test_websocket_subscribe_feature(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test subscribing to a specific preview feature."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "labs/subscribe",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] is None
# Initial state is sent as event
event_msg = await client.receive_json()
assert event_msg["type"] == "event"
assert event_msg["event"] == {
"preview_feature": "special_repair",
"domain": "kitchen_sink",
"enabled": False,
"is_built_in": True,
"feedback_url": ANY,
"learn_more_url": ANY,
"report_issue_url": ANY,
}
async def test_websocket_subscribe_feature_receives_updates(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test that subscription receives updates when feature is toggled."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "labs/subscribe",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
}
)
subscribe_msg = await client.receive_json()
assert subscribe_msg["success"]
subscription_id = subscribe_msg["id"]
# Initial state event
initial_event_msg = await client.receive_json()
assert initial_event_msg["id"] == subscription_id
assert initial_event_msg["type"] == "event"
assert initial_event_msg["event"]["enabled"] is False
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
# Update event arrives before the update result
event_msg = await client.receive_json()
assert event_msg["id"] == subscription_id
assert event_msg["type"] == "event"
assert event_msg["event"] == {
"preview_feature": "special_repair",
"domain": "kitchen_sink",
"enabled": True,
"is_built_in": True,
"feedback_url": ANY,
"learn_more_url": ANY,
"report_issue_url": ANY,
}
update_msg = await client.receive_json()
assert update_msg["success"]
async def test_websocket_subscribe_nonexistent_feature(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test subscribing to a preview feature that doesn't exist."""
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "labs/subscribe",
"domain": "nonexistent",
"preview_feature": "feature",
}
)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "not_found"
assert "not found" in msg["error"]["message"].lower()
async def test_websocket_subscribe_does_not_require_admin(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_admin_user: MockUser,
) -> None:
"""Test that subscribe does not require admin privileges."""
hass_admin_user.groups = []
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "labs/subscribe",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
}
)
msg = await client.receive_json()
assert msg["success"]
# Consume initial state event
await client.receive_json()
async def test_websocket_subscribe_only_receives_subscribed_feature_updates(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test that subscription only receives updates for the subscribed feature."""
hass.config.components.add("kitchen_sink")
assert await async_setup(hass, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "labs/subscribe",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
}
)
subscribe_msg = await client.receive_json()
assert subscribe_msg["success"]
# Consume initial state event
await client.receive_json()
# Fire an event for a different feature
hass.bus.async_fire(
EVENT_LABS_UPDATED,
{"domain": "other_domain", "preview_feature": "other_feature", "enabled": True},
)
await hass.async_block_till_done()
await client.send_json_auto_id(
{
"type": "labs/update",
"domain": "kitchen_sink",
"preview_feature": "special_repair",
"enabled": True,
}
)
# Event message arrives before the update result
# Should only receive event for subscribed feature, not the other one
event_msg = await client.receive_json()
assert event_msg["type"] == "event"
assert event_msg["event"]["domain"] == "kitchen_sink"
assert event_msg["event"]["preview_feature"] == "special_repair"
update_msg = await client.receive_json()
assert update_msg["success"]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/labs/test_websocket_api.py",
"license": "Apache License 2.0",
"lines": 735,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/lawn_mower/test_trigger.py | """Test lawn mower triggers."""
from typing import Any
import pytest
from homeassistant.components.lawn_mower import LawnMowerActivity
from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
other_states,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_lawn_mowers(hass: HomeAssistant) -> list[str]:
"""Create multiple lawn mower entities associated with different targets."""
return (await target_entities(hass, "lawn_mower"))["included"]
@pytest.mark.parametrize(
"trigger_key",
[
"lawn_mower.docked",
"lawn_mower.errored",
"lawn_mower.paused_mowing",
"lawn_mower.started_mowing",
],
)
async def test_lawn_mower_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the lawn mower triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("lawn_mower"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="lawn_mower.docked",
target_states=[LawnMowerActivity.DOCKED],
other_states=other_states(LawnMowerActivity.DOCKED),
),
*parametrize_trigger_states(
trigger="lawn_mower.errored",
target_states=[LawnMowerActivity.ERROR],
other_states=other_states(LawnMowerActivity.ERROR),
),
*parametrize_trigger_states(
trigger="lawn_mower.paused_mowing",
target_states=[LawnMowerActivity.PAUSED],
other_states=other_states(LawnMowerActivity.PAUSED),
),
*parametrize_trigger_states(
trigger="lawn_mower.started_mowing",
target_states=[LawnMowerActivity.MOWING],
other_states=other_states(LawnMowerActivity.MOWING),
),
],
)
async def test_lawn_mower_state_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_lawn_mowers: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the lawn mower state trigger fires when any lawn mower state changes to a specific state."""
other_entity_ids = set(target_lawn_mowers) - {entity_id}
# Set all lawn mowers, including the tested one, to the initial state
for eid in target_lawn_mowers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other lawn mowers also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("lawn_mower"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="lawn_mower.docked",
target_states=[LawnMowerActivity.DOCKED],
other_states=other_states(LawnMowerActivity.DOCKED),
),
*parametrize_trigger_states(
trigger="lawn_mower.errored",
target_states=[LawnMowerActivity.ERROR],
other_states=other_states(LawnMowerActivity.ERROR),
),
*parametrize_trigger_states(
trigger="lawn_mower.paused_mowing",
target_states=[LawnMowerActivity.PAUSED],
other_states=other_states(LawnMowerActivity.PAUSED),
),
*parametrize_trigger_states(
trigger="lawn_mower.started_mowing",
target_states=[LawnMowerActivity.MOWING],
other_states=other_states(LawnMowerActivity.MOWING),
),
],
)
async def test_lawn_mower_state_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_lawn_mowers: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the lawn mower state trigger fires when the first lawn mower changes to a specific state."""
other_entity_ids = set(target_lawn_mowers) - {entity_id}
# Set all lawn mowers, including the tested one, to the initial state
for eid in target_lawn_mowers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other lawn mowers should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("lawn_mower"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="lawn_mower.docked",
target_states=[LawnMowerActivity.DOCKED],
other_states=other_states(LawnMowerActivity.DOCKED),
),
*parametrize_trigger_states(
trigger="lawn_mower.errored",
target_states=[LawnMowerActivity.ERROR],
other_states=other_states(LawnMowerActivity.ERROR),
),
*parametrize_trigger_states(
trigger="lawn_mower.paused_mowing",
target_states=[LawnMowerActivity.PAUSED],
other_states=other_states(LawnMowerActivity.PAUSED),
),
*parametrize_trigger_states(
trigger="lawn_mower.started_mowing",
target_states=[LawnMowerActivity.MOWING],
other_states=other_states(LawnMowerActivity.MOWING),
),
],
)
async def test_lawn_mower_state_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_lawn_mowers: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the lawn_mower state trigger fires when the last lawn_mower changes to a specific state."""
other_entity_ids = set(target_lawn_mowers) - {entity_id}
# Set all lawn mowers, including the tested one, to the initial state
for eid in target_lawn_mowers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/lawn_mower/test_trigger.py",
"license": "Apache License 2.0",
"lines": 222,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/light/test_condition.py | """Test light conditions."""
from typing import Any
import pytest
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from tests.components import (
ConditionStateDescription,
assert_condition_gated_by_labs_flag,
create_target_condition,
parametrize_condition_states_all,
parametrize_condition_states_any,
parametrize_target_entities,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_lights(hass: HomeAssistant) -> list[str]:
"""Create multiple light entities associated with different targets."""
return (await target_entities(hass, "light"))["included"]
@pytest.fixture
async def target_switches(hass: HomeAssistant) -> list[str]:
"""Create multiple switch entities associated with different targets.
Note: The switches are used to ensure that only light entities are considered
in the condition evaluation and not other toggle entities.
"""
return (await target_entities(hass, "switch"))["included"]
@pytest.mark.parametrize(
"condition",
[
"light.is_off",
"light.is_on",
],
)
async def test_light_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the light conditions are gated by the labs flag."""
await assert_condition_gated_by_labs_flag(hass, caplog, condition)
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("condition_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("light"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="light.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_condition_states_any(
condition="light.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_light_state_condition_behavior_any(
hass: HomeAssistant,
target_lights: list[str],
target_switches: list[str],
condition_target_config: dict,
entity_id: str,
entities_in_target: int,
condition: str,
condition_options: dict[str, Any],
states: list[ConditionStateDescription],
) -> None:
"""Test the light state condition with the 'any' behavior."""
other_entity_ids = set(target_lights) - {entity_id}
# Set all lights, including the tested light, to the initial state
for eid in target_lights:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
# Set state for switches to ensure that they don't impact the condition
for state in states:
for eid in target_switches:
set_or_remove_state(hass, eid, state["included"])
await hass.async_block_till_done()
assert condition(hass) is False
for state in states:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert condition(hass) == state["condition_true"]
# Check if changing other lights also passes the condition
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert condition(hass) == state["condition_true"]
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("condition_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("light"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="light.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_condition_states_all(
condition="light.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_light_state_condition_behavior_all(
hass: HomeAssistant,
target_lights: list[str],
condition_target_config: dict,
entity_id: str,
entities_in_target: int,
condition: str,
condition_options: dict[str, Any],
states: list[ConditionStateDescription],
) -> None:
"""Test the light state condition with the 'all' behavior."""
# Set state for two switches to ensure that they don't impact the condition
hass.states.async_set("switch.label_switch_1", STATE_OFF)
hass.states.async_set("switch.label_switch_2", STATE_ON)
other_entity_ids = set(target_lights) - {entity_id}
# Set all lights, including the tested light, to the initial state
for eid in target_lights:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="all",
)
for state in states:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert condition(hass) == state["condition_true_first_entity"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert condition(hass) == state["condition_true"]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/light/test_condition.py",
"license": "Apache License 2.0",
"lines": 151,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/light/test_trigger.py | """Test light trigger."""
from typing import Any
import pytest
from homeassistant.components.light import ATTR_BRIGHTNESS
from homeassistant.const import (
ATTR_LABEL_ID,
CONF_ABOVE,
CONF_BELOW,
CONF_ENTITY_ID,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers.trigger import (
CONF_LOWER_LIMIT,
CONF_THRESHOLD_TYPE,
CONF_UPPER_LIMIT,
ThresholdType,
)
from tests.components import (
TriggerStateDescription,
arm_trigger,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_lights(hass: HomeAssistant) -> list[str]:
"""Create multiple light entities associated with different targets."""
return (await target_entities(hass, "light"))["included"]
def parametrize_brightness_changed_trigger_states(
trigger: str, state: str, attribute: str
) -> list[tuple[str, dict[str, Any], list[TriggerStateDescription]]]:
"""Parametrize states and expected service call counts for brightness changed triggers.
Note: The brightness in the trigger configuration is in percentage (0-100) scale,
the underlying attribute in the state is in uint8 (0-255) scale.
"""
return [
*parametrize_trigger_states(
trigger=trigger,
trigger_options={},
target_states=[
(state, {attribute: 0}),
(state, {attribute: 128}),
(state, {attribute: 255}),
],
other_states=[(state, {attribute: None})],
retrigger_on_target_state=True,
),
*parametrize_trigger_states(
trigger=trigger,
trigger_options={CONF_ABOVE: 10},
target_states=[
(state, {attribute: 128}),
(state, {attribute: 255}),
],
other_states=[
(state, {attribute: None}),
(state, {attribute: 0}),
],
retrigger_on_target_state=True,
),
*parametrize_trigger_states(
trigger=trigger,
trigger_options={CONF_BELOW: 90},
target_states=[
(state, {attribute: 0}),
(state, {attribute: 128}),
],
other_states=[
(state, {attribute: None}),
(state, {attribute: 255}),
],
retrigger_on_target_state=True,
),
]
def parametrize_brightness_crossed_threshold_trigger_states(
trigger: str, state: str, attribute: str
) -> list[tuple[str, dict[str, Any], list[TriggerStateDescription]]]:
"""Parametrize states and expected service call counts for brightness crossed threshold triggers.
Note: The brightness in the trigger configuration is in percentage (0-100) scale,
the underlying attribute in the state is in uint8 (0-255) scale.
"""
return [
*parametrize_trigger_states(
trigger=trigger,
trigger_options={
CONF_THRESHOLD_TYPE: ThresholdType.BETWEEN,
CONF_LOWER_LIMIT: 10,
CONF_UPPER_LIMIT: 90,
},
target_states=[
(state, {attribute: 128}),
(state, {attribute: 153}),
],
other_states=[
(state, {attribute: None}),
(state, {attribute: 0}),
(state, {attribute: 255}),
],
),
*parametrize_trigger_states(
trigger=trigger,
trigger_options={
CONF_THRESHOLD_TYPE: ThresholdType.OUTSIDE,
CONF_LOWER_LIMIT: 10,
CONF_UPPER_LIMIT: 90,
},
target_states=[
(state, {attribute: 0}),
(state, {attribute: 255}),
],
other_states=[
(state, {attribute: None}),
(state, {attribute: 128}),
(state, {attribute: 153}),
],
),
*parametrize_trigger_states(
trigger=trigger,
trigger_options={
CONF_THRESHOLD_TYPE: ThresholdType.ABOVE,
CONF_LOWER_LIMIT: 10,
},
target_states=[
(state, {attribute: 128}),
(state, {attribute: 255}),
],
other_states=[
(state, {attribute: None}),
(state, {attribute: 0}),
],
),
*parametrize_trigger_states(
trigger=trigger,
trigger_options={
CONF_THRESHOLD_TYPE: ThresholdType.BELOW,
CONF_UPPER_LIMIT: 90,
},
target_states=[
(state, {attribute: 0}),
(state, {attribute: 128}),
],
other_states=[
(state, {attribute: None}),
(state, {attribute: 255}),
],
),
]
@pytest.mark.parametrize(
"trigger_key",
[
"light.brightness_changed",
"light.brightness_crossed_threshold",
"light.turned_off",
"light.turned_on",
],
)
async def test_light_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the light triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("light"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="light.turned_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_trigger_states(
trigger="light.turned_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_light_state_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_lights: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the light state trigger fires when any light state changes to a specific state."""
other_entity_ids = set(target_lights) - {entity_id}
# Set all lights, including the tested light, to the initial state
for eid in target_lights:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other lights also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("light"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_brightness_changed_trigger_states(
"light.brightness_changed", STATE_ON, ATTR_BRIGHTNESS
),
*parametrize_brightness_crossed_threshold_trigger_states(
"light.brightness_crossed_threshold", STATE_ON, ATTR_BRIGHTNESS
),
],
)
async def test_light_state_attribute_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_lights: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the light state trigger fires when any light state changes to a specific state."""
other_entity_ids = set(target_lights) - {entity_id}
# Set all lights, including the tested light, to the initial state
for eid in target_lights:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, trigger_options, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other lights also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("light"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="light.turned_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_trigger_states(
trigger="light.turned_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_light_state_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_lights: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the light state trigger fires when the first light changes to a specific state."""
other_entity_ids = set(target_lights) - {entity_id}
# Set all lights, including the tested light, to the initial state
for eid in target_lights:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other lights should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("light"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_brightness_crossed_threshold_trigger_states(
"light.brightness_crossed_threshold", STATE_ON, ATTR_BRIGHTNESS
),
],
)
async def test_light_state_attribute_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_lights: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[tuple[tuple[str, dict], int]],
) -> None:
"""Test that the light state trigger fires when the first light state changes to a specific state."""
other_entity_ids = set(target_lights) - {entity_id}
# Set all lights, including the tested light, to the initial state
for eid in target_lights:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "first"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other lights should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("light"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="light.turned_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_trigger_states(
trigger="light.turned_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_light_state_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_lights: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the light state trigger fires when the last light changes to a specific state."""
other_entity_ids = set(target_lights) - {entity_id}
# Set all lights, including the tested light, to the initial state
for eid in target_lights:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("light"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_brightness_crossed_threshold_trigger_states(
"light.brightness_crossed_threshold", STATE_ON, ATTR_BRIGHTNESS
),
],
)
async def test_light_state_attribute_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_lights: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[tuple[tuple[str, dict], int]],
) -> None:
"""Test that the light state trigger fires when the last light state changes to a specific state."""
other_entity_ids = set(target_lights) - {entity_id}
# Set all lights, including the tested light, to the initial state
for eid in target_lights:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(
hass, trigger, {"behavior": "last"} | trigger_options, trigger_target_config
)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/light/test_trigger.py",
"license": "Apache License 2.0",
"lines": 462,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/media_player/test_trigger.py | """Test media player trigger."""
from typing import Any
import pytest
from homeassistant.components.media_player import MediaPlayerState
from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_media_players(hass: HomeAssistant) -> list[str]:
"""Create multiple media player entities associated with different targets."""
return (await target_entities(hass, "media_player"))["included"]
@pytest.mark.parametrize(
"trigger_key",
[
"media_player.stopped_playing",
],
)
async def test_media_player_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the media player triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("media_player"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="media_player.stopped_playing",
target_states=[
MediaPlayerState.IDLE,
MediaPlayerState.OFF,
MediaPlayerState.ON,
],
other_states=[
MediaPlayerState.BUFFERING,
MediaPlayerState.PAUSED,
MediaPlayerState.PLAYING,
],
),
],
)
async def test_media_player_state_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_media_players: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the media player state trigger fires when any media player state changes to a specific state."""
other_entity_ids = set(target_media_players) - {entity_id}
# Set all media players, including the tested media player, to the initial state
for eid in target_media_players:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other media players also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("media_player"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="media_player.stopped_playing",
target_states=[
MediaPlayerState.IDLE,
MediaPlayerState.OFF,
MediaPlayerState.ON,
],
other_states=[
MediaPlayerState.BUFFERING,
MediaPlayerState.PAUSED,
MediaPlayerState.PLAYING,
],
),
],
)
async def test_media_player_state_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_media_players: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the media player state trigger fires when the first media player changes to a specific state."""
other_entity_ids = set(target_media_players) - {entity_id}
# Set all media players, including the tested media player, to the initial state
for eid in target_media_players:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other media players should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("media_player"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="media_player.stopped_playing",
target_states=[
MediaPlayerState.IDLE,
MediaPlayerState.OFF,
MediaPlayerState.ON,
],
other_states=[
MediaPlayerState.BUFFERING,
MediaPlayerState.PAUSED,
MediaPlayerState.PLAYING,
],
),
],
)
async def test_media_player_state_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_media_players: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the media player state trigger fires when the last media player changes to a specific state."""
other_entity_ids = set(target_media_players) - {entity_id}
# Set all media players, including the tested media player, to the initial state
for eid in target_media_players:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/media_player/test_trigger.py",
"license": "Apache License 2.0",
"lines": 197,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/miele/test_select.py | """Tests for miele select module."""
from unittest.mock import MagicMock, Mock
from aiohttp import ClientResponseError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.select import DOMAIN as SELECT_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, ATTR_OPTION, SERVICE_SELECT_OPTION
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
TEST_PLATFORM = SELECT_DOMAIN
pytestmark = [
pytest.mark.parametrize("platforms", [(TEST_PLATFORM,)]),
pytest.mark.parametrize(
"load_action_file", ["action_freezer.json"], ids=["freezer"]
),
]
ENTITY_ID = "select.freezer_mode"
async def test_select_states(
hass: HomeAssistant,
mock_miele_client: MagicMock,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
setup_platform: MockConfigEntry,
) -> None:
"""Test select entity state."""
await snapshot_platform(hass, entity_registry, snapshot, setup_platform.entry_id)
async def test_selecting(
hass: HomeAssistant,
mock_miele_client: MagicMock,
setup_platform: MockConfigEntry,
) -> None:
"""Test the select service."""
await hass.services.async_call(
TEST_PLATFORM,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_OPTION: "sabbath"},
blocking=True,
)
mock_miele_client.send_action.assert_called_once()
async def test_api_failure(
hass: HomeAssistant,
mock_miele_client: MagicMock,
setup_platform: MockConfigEntry,
) -> 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_SELECT_OPTION,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_OPTION: "sabbath"},
blocking=True,
)
mock_miele_client.send_action.assert_called_once()
async def test_invalid_option(
hass: HomeAssistant,
mock_miele_client: MagicMock,
setup_platform: MockConfigEntry,
) -> None:
"""Test handling of exception from API."""
mock_miele_client.send_action.side_effect = ClientResponseError(Mock(), Mock())
with pytest.raises(
ServiceValidationError, match=f'Invalid option: "normal" on {ENTITY_ID}'
):
await hass.services.async_call(
TEST_PLATFORM,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_OPTION: "normal"},
blocking=True,
)
mock_miele_client.send_action.assert_not_called()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/miele/test_select.py",
"license": "Apache License 2.0",
"lines": 75,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/mobile_app/test_pending_updates.py | """Tests for mobile_app pending updates functionality."""
from http import HTTPStatus
from typing import Any
from aiohttp.test_utils import TestClient
from homeassistant.const import PERCENTAGE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
async def test_pending_update_applied_when_entity_enabled(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
create_registrations: tuple[dict[str, Any], dict[str, Any]],
webhook_client: TestClient,
) -> None:
"""Test that updates sent while disabled are applied when entity is re-enabled."""
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
# Register a sensor
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 100,
"type": "sensor",
"unique_id": "battery_state",
"unit_of_measurement": PERCENTAGE,
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "100"
# Disable the entity
entity_registry.async_update_entity(
"sensor.test_1_battery_state", disabled_by=er.RegistryEntryDisabler.USER
)
await hass.async_block_till_done()
# Send update while disabled
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 50,
"type": "sensor",
"unique_id": "battery_state",
"unit_of_measurement": PERCENTAGE,
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
# Re-enable the entity
entity_registry.async_update_entity("sensor.test_1_battery_state", disabled_by=None)
# Reload the config entry to trigger entity re-creation
config_entry = hass.config_entries.async_entries("mobile_app")[1]
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
# Verify the update sent while disabled was applied
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "50"
async def test_pending_update_with_attributes(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
create_registrations: tuple[dict[str, Any], dict[str, Any]],
webhook_client: TestClient,
) -> None:
"""Test that pending updates preserve all attributes."""
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
# Register a sensor
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 100,
"type": "sensor",
"unique_id": "battery_state",
"attributes": {"charging": True, "voltage": 4.2},
"icon": "mdi:battery-charging",
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
# Disable the entity
entity_registry.async_update_entity(
"sensor.test_1_battery_state", disabled_by=er.RegistryEntryDisabler.USER
)
await hass.async_block_till_done()
# Send update with different attributes while disabled
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 50,
"type": "sensor",
"unique_id": "battery_state",
"attributes": {"charging": False, "voltage": 3.7},
"icon": "mdi:battery-50",
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
# Re-enable the entity
entity_registry.async_update_entity("sensor.test_1_battery_state", disabled_by=None)
# Reload the config entry
config_entry = hass.config_entries.async_entries("mobile_app")[1]
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
# Verify all attributes were applied
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "50"
assert entity.attributes["charging"] is False
assert entity.attributes["voltage"] == 3.7
assert entity.attributes["icon"] == "mdi:battery-50"
async def test_pending_update_overwritten_by_newer_update(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
create_registrations: tuple[dict[str, Any], dict[str, Any]],
webhook_client: TestClient,
) -> None:
"""Test that newer pending updates overwrite older ones."""
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
# Register a sensor
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 100,
"type": "sensor",
"unique_id": "battery_state",
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
# Disable the entity
entity_registry.async_update_entity(
"sensor.test_1_battery_state", disabled_by=er.RegistryEntryDisabler.USER
)
await hass.async_block_till_done()
# Send first update while disabled
await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 75,
"type": "sensor",
"unique_id": "battery_state",
},
},
)
await hass.async_block_till_done()
# Send second update while still disabled - should overwrite
await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 25,
"type": "sensor",
"unique_id": "battery_state",
},
},
)
await hass.async_block_till_done()
# Re-enable the entity
entity_registry.async_update_entity("sensor.test_1_battery_state", disabled_by=None)
# Reload the config entry
config_entry = hass.config_entries.async_entries("mobile_app")[1]
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
# Verify the latest update was applied (25, not 75)
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "25"
async def test_pending_update_not_stored_on_enabled_entities(
hass: HomeAssistant,
create_registrations: tuple[dict[str, Any], dict[str, Any]],
webhook_client: TestClient,
) -> None:
"""Test that enabled entities receive updates immediately."""
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
# Register a sensor
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 100,
"type": "sensor",
"unique_id": "battery_state",
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "100"
# Send update while enabled - should apply immediately
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 50,
"type": "sensor",
"unique_id": "battery_state",
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
# Verify update was applied immediately
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "50"
async def test_pending_update_fallback_to_restore_state(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
create_registrations: tuple[dict[str, Any], dict[str, Any]],
webhook_client: TestClient,
) -> None:
"""Test that restored state is used when no pending update exists."""
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
# Register a sensor
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 100,
"type": "sensor",
"unique_id": "battery_state",
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "100"
# Update to a new state
await webhook_client.post(
webhook_url,
json={
"type": "update_sensor_states",
"data": [
{
"state": 75,
"type": "sensor",
"unique_id": "battery_state",
}
],
},
)
await hass.async_block_till_done()
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "75"
# Reload without pending updates
config_entry = hass.config_entries.async_entries("mobile_app")[1]
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
# Verify restored state was used
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "75"
async def test_multiple_pending_updates_for_different_sensors(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
create_registrations: tuple[dict[str, Any], dict[str, Any]],
webhook_client: TestClient,
) -> None:
"""Test that multiple sensors can be updated while disabled and applied when re-enabled."""
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
# Register two sensors
for unique_id, state in (("battery_state", 100), ("battery_temp", 25)):
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": unique_id.replace("_", " ").title(),
"state": state,
"type": "sensor",
"unique_id": unique_id,
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
# Disable both entities
entity_registry.async_update_entity(
"sensor.test_1_battery_state", disabled_by=er.RegistryEntryDisabler.USER
)
entity_registry.async_update_entity(
"sensor.test_1_battery_temp", disabled_by=er.RegistryEntryDisabler.USER
)
await hass.async_block_till_done()
# Send updates for both while disabled
await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 50,
"type": "sensor",
"unique_id": "battery_state",
},
},
)
await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery Temp",
"state": 30,
"type": "sensor",
"unique_id": "battery_temp",
},
},
)
await hass.async_block_till_done()
# Re-enable both entities
entity_registry.async_update_entity("sensor.test_1_battery_state", disabled_by=None)
entity_registry.async_update_entity("sensor.test_1_battery_temp", disabled_by=None)
# Reload the config entry
config_entry = hass.config_entries.async_entries("mobile_app")[1]
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
# Verify both updates sent while disabled were applied
battery_state = hass.states.get("sensor.test_1_battery_state")
battery_temp = hass.states.get("sensor.test_1_battery_temp")
assert battery_state is not None
assert battery_state.state == "50"
assert battery_temp is not None
assert battery_temp.state == "30"
async def test_update_sensor_states_with_pending_updates(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
create_registrations: tuple[dict[str, Any], dict[str, Any]],
webhook_client: TestClient,
) -> None:
"""Test that update_sensor_states updates are applied when entity is re-enabled."""
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
# Register a sensor
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 100,
"type": "sensor",
"unique_id": "battery_state",
"unit_of_measurement": PERCENTAGE,
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "100"
# Disable the entity
entity_registry.async_update_entity(
"sensor.test_1_battery_state", disabled_by=er.RegistryEntryDisabler.USER
)
await hass.async_block_till_done()
# Use update_sensor_states while disabled
resp = await webhook_client.post(
webhook_url,
json={
"type": "update_sensor_states",
"data": [
{
"state": 75,
"type": "sensor",
"unique_id": "battery_state",
}
],
},
)
assert resp.status == HTTPStatus.OK
await hass.async_block_till_done()
# Re-enable the entity
entity_registry.async_update_entity("sensor.test_1_battery_state", disabled_by=None)
# Reload the config entry to trigger entity re-creation
config_entry = hass.config_entries.async_entries("mobile_app")[1]
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
# Verify the update sent while disabled was applied
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "75"
async def test_update_sensor_states_always_stores_pending(
hass: HomeAssistant,
create_registrations: tuple[dict[str, Any], dict[str, Any]],
webhook_client: TestClient,
) -> None:
"""Test that update_sensor_states applies updates to enabled entities."""
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
# Register a sensor
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Battery State",
"state": 100,
"type": "sensor",
"unique_id": "battery_state",
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "100"
# Use update_sensor_states while enabled
resp = await webhook_client.post(
webhook_url,
json={
"type": "update_sensor_states",
"data": [
{
"state": 50,
"type": "sensor",
"unique_id": "battery_state",
}
],
},
)
assert resp.status == HTTPStatus.OK
await hass.async_block_till_done()
# Verify update was applied
entity = hass.states.get("sensor.test_1_battery_state")
assert entity is not None
assert entity.state == "50"
async def test_binary_sensor_pending_update(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
create_registrations: tuple[dict[str, Any], dict[str, Any]],
webhook_client: TestClient,
) -> None:
"""Test that binary sensor updates are applied when entity is re-enabled."""
webhook_id = create_registrations[1]["webhook_id"]
webhook_url = f"/api/webhook/{webhook_id}"
# Register a binary sensor
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Motion Detected",
"state": False,
"type": "binary_sensor",
"unique_id": "motion_sensor",
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
entity = hass.states.get("binary_sensor.test_1_motion_detected")
assert entity is not None
assert entity.state == "off"
# Disable the entity
entity_registry.async_update_entity(
"binary_sensor.test_1_motion_detected",
disabled_by=er.RegistryEntryDisabler.USER,
)
await hass.async_block_till_done()
# Send update while disabled
reg_resp = await webhook_client.post(
webhook_url,
json={
"type": "register_sensor",
"data": {
"name": "Motion Detected",
"state": True,
"type": "binary_sensor",
"unique_id": "motion_sensor",
},
},
)
assert reg_resp.status == HTTPStatus.CREATED
await hass.async_block_till_done()
# Re-enable the entity
entity_registry.async_update_entity(
"binary_sensor.test_1_motion_detected", disabled_by=None
)
# Reload the config entry
config_entry = hass.config_entries.async_entries("mobile_app")[1]
await hass.config_entries.async_reload(config_entry.entry_id)
await hass.async_block_till_done()
# Verify the update sent while disabled was applied
entity = hass.states.get("binary_sensor.test_1_motion_detected")
assert entity is not None
assert entity.state == "on"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/mobile_app/test_pending_updates.py",
"license": "Apache License 2.0",
"lines": 530,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nederlandse_spoorwegen/test_binary_sensor.py | """Test the Nederlandse Spoorwegen binary sensor."""
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
import pytest
from requests.exceptions import ConnectionError as RequestsConnectionError
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
import homeassistant.helpers.entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture(autouse=True)
def mock_binary_sensor_platform() -> Generator:
"""Override PLATFORMS for NS integration."""
with patch(
"homeassistant.components.nederlandse_spoorwegen.PLATFORMS",
[Platform.BINARY_SENSOR],
) as mock_platform:
yield mock_platform
@pytest.mark.freeze_time("2025-09-15 14:30:00+00:00")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_binary_sensor(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test sensor initialization."""
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.freeze_time("2025-09-15 14:30:00+00:00")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_no_upcoming_trips(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test sensor initialization."""
mock_nsapi.get_trips.return_value = []
await setup_integration(hass, mock_config_entry)
assert (
hass.states.get("binary_sensor.to_work_departure_delayed").state
== STATE_UNKNOWN
)
async def test_sensor_with_api_connection_error(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test sensor behavior when API connection fails."""
# Make API calls fail from the start
mock_nsapi.get_trips.side_effect = RequestsConnectionError("Connection failed")
await setup_integration(hass, mock_config_entry)
await hass.async_block_till_done()
# Sensors should not be created at all if initial API call fails
sensor_states = hass.states.async_all("binary_sensor")
assert len(sensor_states) == 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nederlandse_spoorwegen/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/niko_home_control/test_climate.py | """Tests for the Niko Home Control Climate platform."""
from typing import Any
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.climate import ATTR_HVAC_MODE, ATTR_PRESET_MODE, HVACMode
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import find_update_callback, setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_niko_home_control_connection: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.niko_home_control.PLATFORMS", [Platform.CLIMATE]
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("service", "service_parameters", "api_method", "api_parameters"),
[
("set_temperature", {"temperature": 25}, "set_temperature", (25,)),
("set_preset_mode", {ATTR_PRESET_MODE: "eco"}, "set_mode", (2,)),
("set_hvac_mode", {ATTR_HVAC_MODE: HVACMode.COOL}, "set_mode", (4,)),
("set_hvac_mode", {ATTR_HVAC_MODE: HVACMode.OFF}, "set_mode", (3,)),
("set_hvac_mode", {ATTR_HVAC_MODE: HVACMode.AUTO}, "set_mode", (5,)),
],
)
async def test_set(
hass: HomeAssistant,
mock_niko_home_control_connection: AsyncMock,
mock_config_entry: MockConfigEntry,
climate: AsyncMock,
service: str,
service_parameters: dict[str, Any],
api_method: str,
api_parameters: tuple[Any, ...],
) -> None:
"""Test setting a value on the climate entity."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
"climate",
service,
{ATTR_ENTITY_ID: "climate.thermostat"} | service_parameters,
blocking=True,
)
getattr(
mock_niko_home_control_connection.thermostats["thermostat-5"],
api_method,
).assert_called_once_with(*api_parameters)
async def test_updating(
hass: HomeAssistant,
mock_niko_home_control_connection: AsyncMock,
mock_config_entry: MockConfigEntry,
climate: AsyncMock,
) -> None:
"""Test updating the thermostat."""
await setup_integration(hass, mock_config_entry)
climate.state = 0
await find_update_callback(mock_niko_home_control_connection, 5)(0)
assert hass.states.get("climate.thermostat").attributes.get("preset_mode") == "day"
assert hass.states.get("climate.thermostat").state == "auto"
climate.state = 1
await find_update_callback(mock_niko_home_control_connection, 5)(1)
assert (
hass.states.get("climate.thermostat").attributes.get("preset_mode") == "night"
)
assert hass.states.get("climate.thermostat").state == "auto"
climate.state = 2
await find_update_callback(mock_niko_home_control_connection, 5)(2)
assert hass.states.get("climate.thermostat").state == "auto"
assert hass.states.get("climate.thermostat").attributes["preset_mode"] == "eco"
climate.state = 3
await find_update_callback(mock_niko_home_control_connection, 5)(3)
assert hass.states.get("climate.thermostat").state == "off"
climate.state = 4
await find_update_callback(mock_niko_home_control_connection, 5)(4)
assert hass.states.get("climate.thermostat").state == "cool"
climate.state = 5
await find_update_callback(mock_niko_home_control_connection, 5)(5)
assert hass.states.get("climate.thermostat").state == "auto"
assert hass.states.get("climate.thermostat").attributes["preset_mode"] == "prog1"
climate.state = 6
await find_update_callback(mock_niko_home_control_connection, 5)(6)
assert hass.states.get("climate.thermostat").state == "auto"
assert hass.states.get("climate.thermostat").attributes["preset_mode"] == "prog2"
climate.state = 7
await find_update_callback(mock_niko_home_control_connection, 5)(7)
assert hass.states.get("climate.thermostat").state == "auto"
assert hass.states.get("climate.thermostat").attributes["preset_mode"] == "prog3"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/niko_home_control/test_climate.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/point/test_init.py | """Tests for the Point component."""
from unittest.mock import patch
from homeassistant.components.point import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_entry_oauth2_flow import (
ImplementationUnavailableError,
)
from tests.common import MockConfigEntry
async def test_oauth_implementation_not_available(
hass: HomeAssistant,
) -> None:
"""Test that unavailable OAuth implementation raises ConfigEntryNotReady."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation": DOMAIN,
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
},
)
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.point.async_get_config_entry_implementation",
side_effect=ImplementationUnavailableError,
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/point/test_init.py",
"license": "Apache License 2.0",
"lines": 33,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/pooldose/test_binary_sensor.py | """Test the PoolDose binary sensor platform."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from pooldose.request_status import RequestStatus
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_binary_sensors(
hass: HomeAssistant,
mock_pooldose_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the Pooldose binary sensors."""
with patch("homeassistant.components.pooldose.PLATFORMS", [Platform.BINARY_SENSOR]):
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize("exception", [TimeoutError, ConnectionError, OSError])
async def test_exception_raising(
hass: HomeAssistant,
mock_pooldose_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test the Pooldose binary sensors."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.pool_device_recirculation").state == STATE_ON
mock_pooldose_client.instant_values_structured.side_effect = exception
freezer.tick(timedelta(minutes=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (
hass.states.get("binary_sensor.pool_device_recirculation").state
== STATE_UNAVAILABLE
)
async def test_no_data(
hass: HomeAssistant,
mock_pooldose_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test the Pooldose binary sensors."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.pool_device_recirculation").state == STATE_ON
mock_pooldose_client.instant_values_structured.return_value = (
RequestStatus.SUCCESS,
None,
)
freezer.tick(timedelta(minutes=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (
hass.states.get("binary_sensor.pool_device_recirculation").state
== STATE_UNAVAILABLE
)
async def test_binary_sensor_entity_unavailable_no_coordinator_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pooldose_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test binary sensor entity becomes unavailable when coordinator has no data."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Verify initial working state
pump_state = hass.states.get("binary_sensor.pool_device_recirculation")
assert pump_state.state == STATE_ON
# Set coordinator data to None by making API return empty
mock_pooldose_client.instant_values_structured.return_value = (
RequestStatus.HOST_UNREACHABLE,
None,
)
freezer.tick(timedelta(minutes=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Check binary sensor becomes unavailable
pump_state = hass.states.get("binary_sensor.pool_device_recirculation")
assert pump_state.state == STATE_UNAVAILABLE
async def test_binary_sensor_state_changes(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pooldose_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test binary sensor state changes."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Verify initial states
pump_state = hass.states.get("binary_sensor.pool_device_recirculation")
assert pump_state.state == STATE_ON
ph_level_state = hass.states.get("binary_sensor.pool_device_ph_tank_level")
assert ph_level_state.state == STATE_OFF
# Update data with changed values
current_data = mock_pooldose_client.instant_values_structured.return_value[1]
updated_data = current_data.copy()
updated_data["binary_sensor"]["pump_alarm"]["value"] = False
updated_data["binary_sensor"]["ph_level_alarm"]["value"] = True
mock_pooldose_client.instant_values_structured.return_value = (
RequestStatus.SUCCESS,
updated_data,
)
freezer.tick(timedelta(minutes=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Check states have changed
pump_state = hass.states.get("binary_sensor.pool_device_recirculation")
assert pump_state.state == STATE_OFF
ph_level_state = hass.states.get("binary_sensor.pool_device_ph_tank_level")
assert ph_level_state.state == STATE_ON
async def test_binary_sensor_missing_from_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pooldose_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test binary sensor becomes unavailable when missing from coordinator data."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Verify initial working state
flow_alarm_state = hass.states.get("binary_sensor.pool_device_flow_rate")
assert flow_alarm_state.state == STATE_OFF
# Update data with missing sensor
current_data = mock_pooldose_client.instant_values_structured.return_value[1]
updated_data = current_data.copy()
del updated_data["binary_sensor"]["flow_rate_alarm"]
mock_pooldose_client.instant_values_structured.return_value = (
RequestStatus.SUCCESS,
updated_data,
)
freezer.tick(timedelta(minutes=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Check sensor becomes unavailable when not in coordinator data
flow_alarm_state = hass.states.get("binary_sensor.pool_device_flow_rate")
assert flow_alarm_state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/pooldose/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 151,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/pooldose/test_switch.py | """Tests for the Seko PoolDose switch platform."""
from unittest.mock import AsyncMock
from pooldose.request_status import RequestStatus
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return [Platform.SWITCH]
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_all_switches(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Pooldose switches."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("init_integration")
async def test_switches_created(
hass: HomeAssistant,
) -> None:
"""Test that switch entities are created."""
# Verify all three switches exist
assert hass.states.get("switch.pool_device_pause_dosing") is not None
assert hass.states.get("switch.pool_device_pump_monitoring") is not None
assert hass.states.get("switch.pool_device_frequency_input") is not None
@pytest.mark.usefixtures("init_integration")
async def test_switch_entity_unavailable_no_coordinator_data(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_pooldose_client: AsyncMock,
) -> None:
"""Test switch entity becomes unavailable when coordinator has no data."""
# Verify entity has a state initially
pause_dosing_state = hass.states.get("switch.pool_device_pause_dosing")
assert pause_dosing_state.state == STATE_OFF
# Update coordinator data to None
mock_pooldose_client.instant_values_structured.return_value = (None, None)
coordinator = init_integration.runtime_data
await coordinator.async_refresh()
await hass.async_block_till_done()
# Check entity becomes unavailable
pause_dosing_state = hass.states.get("switch.pool_device_pause_dosing")
assert pause_dosing_state.state == "unavailable"
@pytest.mark.usefixtures("init_integration")
async def test_switch_state_changes(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_pooldose_client: AsyncMock,
) -> None:
"""Test switch state changes when coordinator updates."""
# Initial state
pause_dosing_state = hass.states.get("switch.pool_device_pause_dosing")
assert pause_dosing_state.state == STATE_OFF
# Update coordinator data with switch value changed
current_data = mock_pooldose_client.instant_values_structured.return_value[1]
updated_data = current_data.copy()
updated_data["switch"]["pause_dosing"]["value"] = True
mock_pooldose_client.instant_values_structured.return_value = (
RequestStatus.SUCCESS,
updated_data,
)
coordinator = init_integration.runtime_data
await coordinator.async_refresh()
await hass.async_block_till_done()
# Check state changed
pause_dosing_state = hass.states.get("switch.pool_device_pause_dosing")
assert pause_dosing_state.state == STATE_ON
@pytest.mark.usefixtures("init_integration")
async def test_turn_on_switch(
hass: HomeAssistant,
mock_pooldose_client: AsyncMock,
) -> None:
"""Test turning on a switch."""
# Verify initial state is off
pause_dosing_state = hass.states.get("switch.pool_device_pause_dosing")
assert pause_dosing_state.state == STATE_OFF
# Turn on the switch
await hass.services.async_call(
SWITCH_DOMAIN,
"turn_on",
{ATTR_ENTITY_ID: "switch.pool_device_pause_dosing"},
blocking=True,
)
# Verify API was called
mock_pooldose_client.set_switch.assert_called_once_with("pause_dosing", True)
# Verify state updated immediately
pause_dosing_state = hass.states.get("switch.pool_device_pause_dosing")
assert pause_dosing_state.state == STATE_ON
@pytest.mark.usefixtures("init_integration")
async def test_turn_off_switch(
hass: HomeAssistant,
mock_pooldose_client: AsyncMock,
) -> None:
"""Test turning off a switch."""
# pump_monitoring starts as on in fixture data
pump_monitoring_state = hass.states.get("switch.pool_device_pump_monitoring")
assert pump_monitoring_state.state == STATE_ON
# Turn off the switch
await hass.services.async_call(
SWITCH_DOMAIN,
"turn_off",
{ATTR_ENTITY_ID: "switch.pool_device_pump_monitoring"},
blocking=True,
)
# Verify API was called
mock_pooldose_client.set_switch.assert_called_once_with("pump_monitoring", False)
# Verify state updated immediately
pump_monitoring_state = hass.states.get("switch.pool_device_pump_monitoring")
assert pump_monitoring_state.state == STATE_OFF
@pytest.mark.usefixtures("init_integration")
async def test_actions_cannot_connect_switch(
hass: HomeAssistant,
mock_pooldose_client: AsyncMock,
init_integration: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""When the client write method raises, ServiceValidationError('cannot_connect') is raised."""
client = mock_pooldose_client
entity_id = "switch.pool_device_pause_dosing"
before = hass.states.get(entity_id)
assert before is not None
client.is_connected = False
client.set_switch = AsyncMock(return_value=False)
with pytest.raises(ServiceValidationError) as excinfo:
await hass.services.async_call(
"switch", "turn_on", {"entity_id": entity_id}, blocking=True
)
assert excinfo.value.translation_key == "cannot_connect"
after = hass.states.get(entity_id)
assert after is not None
assert before.state == after.state
@pytest.mark.usefixtures("init_integration")
async def test_actions_write_rejected_switch(
hass: HomeAssistant,
mock_pooldose_client: AsyncMock,
init_integration: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""When the client write method returns False, ServiceValidationError('write_rejected') is raised."""
client = mock_pooldose_client
entity_id = "switch.pool_device_pause_dosing"
before = hass.states.get(entity_id)
assert before is not None
client.set_switch = AsyncMock(return_value=False)
with pytest.raises(ServiceValidationError) as excinfo:
await hass.services.async_call(
"switch", "turn_on", {"entity_id": entity_id}, blocking=True
)
assert excinfo.value.translation_key == "write_rejected"
after = hass.states.get(entity_id)
assert after is not None
assert before.state == after.state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/pooldose/test_switch.py",
"license": "Apache License 2.0",
"lines": 160,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/ridwell/test_calendar.py | """Test Ridwell calendar platform."""
from datetime import date
from aioridwell.model import EventState, RidwellPickup, RidwellPickupEvent
import pytest
from homeassistant.components.calendar import CalendarEvent
from homeassistant.components.ridwell.calendar import (
async_get_calendar_event_from_pickup_event,
)
from homeassistant.components.ridwell.const import (
CALENDAR_TITLE_NONE,
CALENDAR_TITLE_ROTATING,
CALENDAR_TITLE_STATUS,
CONF_CALENDAR_TITLE,
)
from homeassistant.core import HomeAssistant
START_DATE = date(2025, 10, 4)
END_DATE = date(2025, 10, 5)
@pytest.mark.parametrize(
(
"pickup_name",
"event_state",
"summary_style",
"expected_description",
"expected_summary",
),
[
# Valid events that should be converted.
# Pickup name of "Cork" is used to produce PickupCategory.ROTATING,
# and "Plastic Film" is used to generate a PickupCategory.STANDARD pickup.
(
"Cork",
EventState.SCHEDULED,
CALENDAR_TITLE_ROTATING, # Display Rotating Category in summary.
"Pickup types: Cork (quantity: 1)",
"Ridwell Pickup (Cork)",
),
(
"Cork",
EventState.SCHEDULED,
CALENDAR_TITLE_NONE, # Display no extra info in summary.
"Pickup types: Cork (quantity: 1)",
"Ridwell Pickup",
),
(
"Cork",
EventState.INITIALIZED,
CALENDAR_TITLE_ROTATING, # Display Rotating Category in summary.
"Pickup types: Cork (quantity: 1)",
"Ridwell Pickup (Cork)",
),
(
"Cork",
EventState.SKIPPED,
CALENDAR_TITLE_STATUS, # Display pickup state in summary.
"Pickup types: Cork (quantity: 1)",
"Ridwell Pickup (skipped)",
),
(
"Cork",
EventState.INITIALIZED,
CALENDAR_TITLE_STATUS, # Display pickup state in summary.
"Pickup types: Cork (quantity: 1)",
"Ridwell Pickup (initialized)",
),
(
"Cork",
EventState.UNKNOWN,
CALENDAR_TITLE_STATUS, # Display pickup state in summary.
"Pickup types: Cork (quantity: 1)",
"Ridwell Pickup (unknown)",
),
],
)
async def test_calendar_event_varied_states_and_types(
hass: HomeAssistant,
config_entry,
pickup_name: str,
event_state: EventState,
expected_description: str,
expected_summary: str,
summary_style: str,
) -> None:
"""Test CalendarEvent output based on pickup type and event state."""
# Set calendar config to default
hass.config_entries.async_update_entry(
config_entry,
options={CONF_CALENDAR_TITLE: summary_style},
)
await hass.async_block_till_done()
# Create test pickup
pickup = RidwellPickup(
name=pickup_name,
offer_id=f"offer_{pickup_name.lower()}",
quantity=1,
product_id=f"product_{pickup_name.lower()}",
priority=1,
)
# Create test pickup event with the given state
pickup_event = RidwellPickupEvent(
_async_request=None,
event_id=f"event_{pickup_name.lower()}_{event_state.name.lower()}",
pickup_date=START_DATE,
pickups=[pickup],
state=event_state,
)
# Call the function under test
event = async_get_calendar_event_from_pickup_event(pickup_event, config_entry)
assert isinstance(event, CalendarEvent)
assert event.summary == expected_summary
assert event.description == expected_description
assert event.start == START_DATE
assert event.end == END_DATE
async def test_calendar_event_with_no_pickups(
hass: HomeAssistant,
config_entry,
) -> None:
"""Test empty pickups."""
pickup_event = RidwellPickupEvent(
_async_request=None,
event_id="event_empty",
pickup_date=START_DATE,
pickups=[],
state=EventState.SCHEDULED,
)
event = async_get_calendar_event_from_pickup_event(pickup_event, config_entry)
assert event.description == "Pickup types: "
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ridwell/test_calendar.py",
"license": "Apache License 2.0",
"lines": 126,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/satel_integra/test_alarm_control_panel.py | """Test Satel Integra alarm panel."""
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
import pytest
from satel_integra.satel_integra import AlarmState
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.alarm_control_panel import (
DOMAIN as ALARM_DOMAIN,
AlarmControlPanelState,
)
from homeassistant.components.satel_integra.const import DOMAIN
from homeassistant.const import (
ATTR_CODE,
ATTR_ENTITY_ID,
SERVICE_ALARM_ARM_AWAY,
SERVICE_ALARM_ARM_HOME,
SERVICE_ALARM_DISARM,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceRegistry
from homeassistant.helpers.entity_registry import EntityRegistry
from . import MOCK_CODE, MOCK_ENTRY_ID, get_monitor_callbacks, setup_integration
from tests.common import (
MockConfigEntry,
async_capture_events,
async_fire_time_changed,
snapshot_platform,
)
@pytest.fixture(autouse=True)
async def alarm_control_panel_only() -> AsyncGenerator[None]:
"""Enable only the alarm panel platform."""
with patch(
"homeassistant.components.satel_integra.PLATFORMS",
[Platform.ALARM_CONTROL_PANEL],
):
yield
@pytest.mark.usefixtures("mock_satel")
async def test_alarm_control_panel(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry_with_subentries: MockConfigEntry,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
) -> None:
"""Test alarm control panel correctly being set up."""
await setup_integration(hass, mock_config_entry_with_subentries)
await snapshot_platform(hass, entity_registry, snapshot, MOCK_ENTRY_ID)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, "1234567890_alarm_panel_1")}
)
assert device_entry == snapshot(name="device")
async def test_alarm_control_panel_initial_state(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
) -> None:
"""Test alarm control panel has a correct initial state after initialization."""
mock_satel.partition_states = {AlarmState.ARMED_MODE0: [1]}
await setup_integration(hass, mock_config_entry_with_subentries)
assert (
hass.states.get("alarm_control_panel.home").state
== AlarmControlPanelState.ARMED_AWAY
)
@pytest.mark.parametrize(
("source_state", "resulting_state"),
[
(AlarmState.TRIGGERED, AlarmControlPanelState.TRIGGERED),
(AlarmState.TRIGGERED_FIRE, AlarmControlPanelState.TRIGGERED),
(AlarmState.ENTRY_TIME, AlarmControlPanelState.PENDING),
(AlarmState.ARMED_MODE3, AlarmControlPanelState.ARMED_HOME),
(AlarmState.ARMED_MODE2, AlarmControlPanelState.ARMED_HOME),
(AlarmState.ARMED_MODE1, AlarmControlPanelState.ARMED_HOME),
(AlarmState.ARMED_MODE0, AlarmControlPanelState.ARMED_AWAY),
(AlarmState.EXIT_COUNTDOWN_OVER_10, AlarmControlPanelState.ARMING),
(AlarmState.EXIT_COUNTDOWN_UNDER_10, AlarmControlPanelState.ARMING),
],
)
async def test_alarm_status_callback(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
source_state: AlarmState,
resulting_state: AlarmControlPanelState,
) -> None:
"""Test alarm control panel correctly changes state after a callback from the panel."""
await setup_integration(hass, mock_config_entry_with_subentries)
assert (
hass.states.get("alarm_control_panel.home").state
== AlarmControlPanelState.DISARMED
)
alarm_panel_update_method, _, _ = get_monitor_callbacks(mock_satel)
mock_satel.partition_states = {source_state: [1]}
alarm_panel_update_method()
# Trigger coordinator debounce
async_fire_time_changed(hass)
assert hass.states.get("alarm_control_panel.home").state == resulting_state
async def test_alarm_status_callback_debounce(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
) -> None:
"""Test that rapid partition state callbacks are debounced."""
await setup_integration(hass, mock_config_entry_with_subentries)
assert (
hass.states.get("alarm_control_panel.home").state
== AlarmControlPanelState.DISARMED
)
alarm_panel_update_method, _, _ = get_monitor_callbacks(mock_satel)
# Simulate rapid state changes from the alarm panel
mock_satel.partition_states = {AlarmState.EXIT_COUNTDOWN_OVER_10: [1]}
alarm_panel_update_method()
mock_satel.partition_states = {AlarmState.EXIT_COUNTDOWN_UNDER_10: [1]}
alarm_panel_update_method()
mock_satel.partition_states = {AlarmState.ARMED_MODE0: [1]}
alarm_panel_update_method()
mock_satel.partition_states = {AlarmState.ARMED_MODE1: [1]}
alarm_panel_update_method()
# State should still be DISARMED because updates are debounced
assert (
hass.states.get("alarm_control_panel.home").state
== AlarmControlPanelState.DISARMED
)
# Trigger coordinator debounce
async_fire_time_changed(hass)
assert (
hass.states.get("alarm_control_panel.home").state
== AlarmControlPanelState.ARMED_HOME
)
async def test_alarm_control_panel_arming(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
) -> None:
"""Test alarm control panel correctly sending arming commands to the panel."""
await setup_integration(hass, mock_config_entry_with_subentries)
# Test Arm home
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_ARM_HOME,
{ATTR_ENTITY_ID: "alarm_control_panel.home", ATTR_CODE: MOCK_CODE},
blocking=True,
)
mock_satel.arm.assert_awaited_once_with(MOCK_CODE, [1], 1)
mock_satel.arm.reset_mock()
# Test Arm away
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_ARM_AWAY,
{ATTR_ENTITY_ID: "alarm_control_panel.home", ATTR_CODE: MOCK_CODE},
blocking=True,
)
mock_satel.arm.assert_awaited_once_with(MOCK_CODE, [1])
async def test_alarm_control_panel_disarming(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
) -> None:
"""Test alarm panel correctly disarms and dismisses alarm."""
mock_satel.partition_states = {AlarmState.TRIGGERED: [1]}
await setup_integration(hass, mock_config_entry_with_subentries)
await hass.services.async_call(
ALARM_DOMAIN,
SERVICE_ALARM_DISARM,
{ATTR_ENTITY_ID: "alarm_control_panel.home", ATTR_CODE: MOCK_CODE},
blocking=True,
)
mock_satel.disarm.assert_awaited_once_with(MOCK_CODE, [1])
mock_satel.clear_alarm.assert_awaited_once_with(MOCK_CODE, [1])
async def test_alarm_panel_last_reported(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
) -> None:
"""Test alarm panels update last_reported if same state is reported."""
events = async_capture_events(hass, "state_changed")
await setup_integration(hass, mock_config_entry_with_subentries)
first_reported = hass.states.get("alarm_control_panel.home").last_reported
assert first_reported is not None
# Initial state change event
assert len(events) == 1
# Run callbacks with same payload
alarm_panel_update_method, _, _ = get_monitor_callbacks(mock_satel)
alarm_panel_update_method()
# Trigger coordinator debounce
async_fire_time_changed(hass)
assert first_reported != hass.states.get("alarm_control_panel.home").last_reported
assert len(events) == 1 # last_reported shall not fire state_changed
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/satel_integra/test_alarm_control_panel.py",
"license": "Apache License 2.0",
"lines": 188,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/satel_integra/test_binary_sensor.py | """Test Satel Integra Binary Sensor."""
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.satel_integra.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceRegistry
from homeassistant.helpers.entity_registry import EntityRegistry
from . import get_monitor_callbacks, setup_integration
from tests.common import (
MockConfigEntry,
async_capture_events,
async_fire_time_changed,
snapshot_platform,
)
@pytest.fixture(autouse=True)
async def binary_sensor_only() -> AsyncGenerator[None]:
"""Enable only the binary sensor platform."""
with patch(
"homeassistant.components.satel_integra.PLATFORMS",
[Platform.BINARY_SENSOR],
):
yield
@pytest.mark.usefixtures("mock_satel")
async def test_binary_sensors(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry_with_subentries: MockConfigEntry,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
) -> None:
"""Test binary sensors correctly being set up."""
await setup_integration(hass, mock_config_entry_with_subentries)
assert mock_config_entry_with_subentries.state is ConfigEntryState.LOADED
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry_with_subentries.entry_id
)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, "1234567890_zones_1")}
)
assert device_entry == snapshot(name="device-zone")
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, "1234567890_outputs_1")}
)
assert device_entry == snapshot(name="device-output")
@pytest.mark.parametrize(
("violated_entries", "expected_state"),
[
({2: 1}, STATE_UNKNOWN),
({1: 0}, STATE_OFF),
({1: 1}, STATE_ON),
],
)
async def test_binary_sensor_initial_state(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
violated_entries: dict[int, int],
expected_state: str,
) -> None:
"""Test binary sensors have a correct initial state after initialization."""
# Instantly call callback to ensure we have initial data set
async def mock_monitor_callback(
alarm_status_callback, zones_callback, outputs_callback
):
outputs_callback({"outputs": violated_entries})
zones_callback({"zones": violated_entries})
mock_satel.monitor_status = AsyncMock(side_effect=mock_monitor_callback)
await setup_integration(hass, mock_config_entry_with_subentries)
assert hass.states.get("binary_sensor.zone").state == expected_state
assert hass.states.get("binary_sensor.output").state == expected_state
async def test_binary_sensor_callback(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
) -> None:
"""Test binary sensors correctly change state after a callback from the panel."""
await setup_integration(hass, mock_config_entry_with_subentries)
assert hass.states.get("binary_sensor.zone").state == STATE_OFF
assert hass.states.get("binary_sensor.output").state == STATE_OFF
_, zone_update_method, output_update_method = get_monitor_callbacks(mock_satel)
output_update_method({"outputs": {1: 1}})
zone_update_method({"zones": {1: 1}})
assert hass.states.get("binary_sensor.zone").state == STATE_ON
assert hass.states.get("binary_sensor.output").state == STATE_ON
output_update_method({"outputs": {1: 0}})
zone_update_method({"zones": {1: 0}})
assert hass.states.get("binary_sensor.zone").state == STATE_OFF
assert hass.states.get("binary_sensor.output").state == STATE_OFF
# The client library should always report all entries, but test that we set the status correctly if it doesn't
output_update_method({"outputs": {2: 1}})
zone_update_method({"zones": {2: 1}})
assert hass.states.get("binary_sensor.zone").state == STATE_UNKNOWN
assert hass.states.get("binary_sensor.output").state == STATE_UNKNOWN
async def test_binary_sensor_last_reported(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test binary sensors update last_reported if same state is reported."""
events = async_capture_events(hass, "state_changed")
await setup_integration(hass, mock_config_entry_with_subentries)
first_reported = hass.states.get("binary_sensor.zone").last_reported
assert first_reported is not None
# Initial 2 state change events for both zone and output
assert len(events) == 2
freezer.tick(1)
async_fire_time_changed(hass)
# Run callbacks with same payload
_, zone_update_method, output_update_method = get_monitor_callbacks(mock_satel)
output_update_method({"outputs": {1: 0}})
zone_update_method({"zones": {1: 0}})
assert first_reported != hass.states.get("binary_sensor.zone").last_reported
assert len(events) == 2 # last_reported shall not fire state_changed
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/satel_integra/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 119,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/satel_integra/test_switch.py | """Test Satel Integra switch."""
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.satel_integra.const import DOMAIN
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_CODE,
STATE_OFF,
STATE_ON,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.device_registry import DeviceRegistry
from homeassistant.helpers.entity_registry import EntityRegistry
from . import MOCK_CODE, MOCK_ENTRY_ID, get_monitor_callbacks, setup_integration
from tests.common import (
MockConfigEntry,
async_capture_events,
async_fire_time_changed,
snapshot_platform,
)
@pytest.fixture(autouse=True)
async def switches_only() -> AsyncGenerator[None]:
"""Enable only the switch platform."""
with patch(
"homeassistant.components.satel_integra.PLATFORMS",
[Platform.SWITCH],
):
yield
@pytest.mark.usefixtures("mock_satel")
async def test_switches(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry_with_subentries: MockConfigEntry,
entity_registry: EntityRegistry,
device_registry: DeviceRegistry,
) -> None:
"""Test switch correctly being set up."""
await setup_integration(hass, mock_config_entry_with_subentries)
await snapshot_platform(hass, entity_registry, snapshot, MOCK_ENTRY_ID)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, "1234567890_switch_1")}
)
assert device_entry == snapshot(name="device")
@pytest.mark.parametrize(
("violated_outputs", "expected_state"),
[
({2: 1}, STATE_UNKNOWN),
({1: 0}, STATE_OFF),
({1: 1}, STATE_ON),
],
)
async def test_switch_initial_state(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
violated_outputs: dict[int, int],
expected_state: str,
) -> None:
"""Test switch has a correct initial state after initialization."""
# Instantly call callback to ensure we have initial data set
async def mock_monitor_callback(
alarm_status_callback, zones_callback, outputs_callback
):
outputs_callback({"outputs": violated_outputs})
mock_satel.monitor_status = AsyncMock(side_effect=mock_monitor_callback)
await setup_integration(hass, mock_config_entry_with_subentries)
assert hass.states.get("switch.switchable_output").state == expected_state
async def test_switch_callback(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
) -> None:
"""Test switch correctly changes state after a callback from the panel."""
await setup_integration(hass, mock_config_entry_with_subentries)
assert hass.states.get("switch.switchable_output").state == STATE_OFF
_, _, output_update_method = get_monitor_callbacks(mock_satel)
output_update_method({"outputs": {1: 1}})
assert hass.states.get("switch.switchable_output").state == STATE_ON
output_update_method({"outputs": {1: 0}})
assert hass.states.get("switch.switchable_output").state == STATE_OFF
# The client library should always report all entries, but test that we set the status correctly if it doesn't
output_update_method({"outputs": {2: 1}})
assert hass.states.get("switch.switchable_output").state == STATE_UNKNOWN
async def test_switch_change_state(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
) -> None:
"""Test switch correctly changes state after a callback from the panel."""
await setup_integration(hass, mock_config_entry_with_subentries)
assert hass.states.get("switch.switchable_output").state == STATE_OFF
# Test turn on
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.switchable_output"},
blocking=True,
)
assert hass.states.get("switch.switchable_output").state == STATE_ON
mock_satel.set_output.assert_awaited_once_with(MOCK_CODE, 1, True)
mock_satel.set_output.reset_mock()
# Test turn off
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.switchable_output"},
blocking=True,
)
assert hass.states.get("switch.switchable_output").state == STATE_OFF
mock_satel.set_output.assert_awaited_once_with(MOCK_CODE, 1, False)
async def test_switch_last_reported(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test switches update last_reported if same state is reported."""
events = async_capture_events(hass, "state_changed")
await setup_integration(hass, mock_config_entry_with_subentries)
first_reported = hass.states.get("switch.switchable_output").last_reported
assert first_reported is not None
# Initial state change event
assert len(events) == 1
freezer.tick(1)
async_fire_time_changed(hass)
# Run callbacks with same payload
_, _, output_update_method = get_monitor_callbacks(mock_satel)
output_update_method({"outputs": {1: 0}})
assert first_reported != hass.states.get("switch.switchable_output").last_reported
assert len(events) == 1 # last_reported shall not fire state_changed
async def test_switch_actions_require_code(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
) -> None:
"""Test switch actions fail when access code is missing."""
await setup_integration(hass, mock_config_entry_with_subentries)
hass.config_entries.async_update_entry(
mock_config_entry_with_subentries, options={CONF_CODE: None}
)
await hass.async_block_till_done()
# Turning the device on or off should raise ServiceValidationError.
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.switchable_output"},
blocking=True,
)
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.switchable_output"},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/satel_integra/test_switch.py",
"license": "Apache License 2.0",
"lines": 167,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/saunum/test_climate.py | """Test the Saunum climate platform."""
from __future__ import annotations
from dataclasses import replace
from freezegun.api import FrozenDateTimeFactory
from pysaunum import SaunumException
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.climate import (
ATTR_CURRENT_TEMPERATURE,
ATTR_FAN_MODE,
ATTR_HVAC_ACTION,
ATTR_HVAC_MODE,
ATTR_PRESET_MODE,
DOMAIN as CLIMATE_DOMAIN,
FAN_HIGH,
FAN_LOW,
FAN_MEDIUM,
FAN_OFF,
SERVICE_SET_FAN_MODE,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_PRESET_MODE,
SERVICE_SET_TEMPERATURE,
HVACAction,
HVACMode,
)
from homeassistant.components.saunum.const import (
OPT_PRESET_NAME_TYPE_1,
OPT_PRESET_NAME_TYPE_2,
OPT_PRESET_NAME_TYPE_3,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_TEMPERATURE,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return [Platform.CLIMATE]
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("service", "service_data", "client_method", "expected_args"),
[
(
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.HEAT},
"async_start_session",
(),
),
(
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.OFF},
"async_stop_session",
(),
),
(
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: 85},
"async_set_target_temperature",
(85,),
),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_climate_service_calls(
hass: HomeAssistant,
mock_saunum_client,
service: str,
service_data: dict,
client_method: str,
expected_args: tuple,
) -> None:
"""Test climate service calls."""
await hass.services.async_call(
CLIMATE_DOMAIN,
service,
{ATTR_ENTITY_ID: "climate.saunum_leil", **service_data},
blocking=True,
)
getattr(mock_saunum_client, client_method).assert_called_once_with(*expected_args)
async def test_hvac_mode_door_open_validation(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
) -> None:
"""Test HVAC mode validation error when door is open."""
mock_saunum_client.async_get_data.return_value = replace(
mock_saunum_client.async_get_data.return_value, door_open=True
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
with pytest.raises(
ServiceValidationError,
match="Cannot start sauna session when sauna door is open",
):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: "climate.saunum_leil", ATTR_HVAC_MODE: HVACMode.HEAT},
blocking=True,
)
@pytest.mark.parametrize(
("heater_elements_active", "expected_hvac_action"),
[
(3, HVACAction.HEATING),
(0, HVACAction.IDLE),
],
)
async def test_hvac_actions(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
heater_elements_active: int,
expected_hvac_action: HVACAction,
) -> None:
"""Test HVAC actions when session is active."""
mock_saunum_client.async_get_data.return_value = replace(
mock_saunum_client.async_get_data.return_value,
session_active=True,
heater_elements_active=heater_elements_active,
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.saunum_leil")
assert state is not None
assert state.state == HVACMode.HEAT
assert state.attributes.get(ATTR_HVAC_ACTION) == expected_hvac_action
@pytest.mark.parametrize(
(
"current_temperature",
"target_temperature",
"expected_current",
"expected_target",
),
[
(None, 80, None, 80),
(35.0, 30, 35, 30),
],
)
async def test_temperature_attributes(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
current_temperature: float | None,
target_temperature: int,
expected_current: float | None,
expected_target: int,
) -> None:
"""Test temperature attribute handling with edge cases."""
base_data = mock_saunum_client.async_get_data.return_value
mock_saunum_client.async_get_data.return_value = replace(
base_data,
current_temperature=current_temperature,
target_temperature=target_temperature,
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.saunum_leil")
assert state is not None
assert state.attributes.get(ATTR_CURRENT_TEMPERATURE) == expected_current
assert state.attributes.get(ATTR_TEMPERATURE) == expected_target
@pytest.mark.usefixtures("init_integration")
async def test_entity_unavailable_on_update_failure(
hass: HomeAssistant,
mock_saunum_client,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that entity becomes unavailable when coordinator update fails."""
entity_id = "climate.saunum_leil"
# Verify entity is initially available
state = hass.states.get(entity_id)
assert state is not None
assert state.state != STATE_UNAVAILABLE
# Make the next update fail
mock_saunum_client.async_get_data.side_effect = SaunumException("Read error")
# Move time forward to trigger a coordinator update (60 seconds)
freezer.tick(60)
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Entity should now be unavailable
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_UNAVAILABLE
@pytest.mark.parametrize(
("service", "service_data", "mock_method", "side_effect", "translation_key"),
[
(
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.HEAT},
"async_start_session",
SaunumException("Communication error"),
"set_hvac_mode_failed",
),
(
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: 85},
"async_set_target_temperature",
SaunumException("Communication error"),
"set_temperature_failed",
),
(
SERVICE_SET_PRESET_MODE,
{ATTR_PRESET_MODE: "type_2"},
"async_set_sauna_type",
SaunumException("Communication error"),
"set_preset_failed",
),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_service_error_handling(
hass: HomeAssistant,
mock_saunum_client,
service: str,
service_data: dict,
mock_method: str,
side_effect: Exception,
translation_key: str,
) -> None:
"""Test error handling when service calls fail."""
entity_id = "climate.saunum_leil"
getattr(mock_saunum_client, mock_method).side_effect = side_effect
with pytest.raises(HomeAssistantError) as exc_info:
await hass.services.async_call(
CLIMATE_DOMAIN,
service,
{ATTR_ENTITY_ID: entity_id, **service_data},
blocking=True,
)
assert exc_info.value.translation_key == translation_key
assert exc_info.value.translation_domain == "saunum"
async def test_fan_mode_service_call(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
) -> None:
"""Test setting fan mode."""
mock_saunum_client.async_get_data.return_value = replace(
mock_saunum_client.async_get_data.return_value, session_active=True
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: "climate.saunum_leil", ATTR_FAN_MODE: FAN_LOW},
blocking=True,
)
mock_saunum_client.async_set_fan_speed.assert_called_once_with(1)
@pytest.mark.usefixtures("init_integration")
async def test_preset_mode_service_call(
hass: HomeAssistant,
mock_saunum_client,
) -> None:
"""Test setting preset mode."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: "climate.saunum_leil", ATTR_PRESET_MODE: "type_2"},
blocking=True,
)
mock_saunum_client.async_set_sauna_type.assert_called_once_with(1)
@pytest.mark.parametrize(
("fan_speed", "fan_mode"),
[
(0, FAN_OFF),
(1, FAN_LOW),
(2, FAN_MEDIUM),
(3, FAN_HIGH),
(None, None),
],
)
async def test_fan_mode_attributes(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
fan_speed: int | None,
fan_mode: str | None,
) -> None:
"""Test fan mode attribute mapping from device."""
mock_saunum_client.async_get_data.return_value = replace(
mock_saunum_client.async_get_data.return_value,
fan_speed=fan_speed,
session_active=True,
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.saunum_leil")
assert state is not None
assert state.attributes.get(ATTR_FAN_MODE) == fan_mode
@pytest.mark.usefixtures("init_integration")
async def test_fan_mode_validation_error(
hass: HomeAssistant,
) -> None:
"""Test fan mode validation error when session is not active."""
with pytest.raises(
ServiceValidationError,
match="Cannot change fan mode when sauna session is not active",
):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: "climate.saunum_leil", ATTR_FAN_MODE: FAN_LOW},
blocking=True,
)
async def test_preset_mode_validation_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
) -> None:
"""Test preset mode validation error when session is active."""
mock_saunum_client.async_get_data.return_value = replace(
mock_saunum_client.async_get_data.return_value, session_active=True
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
with pytest.raises(ServiceValidationError) as exc_info:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: "climate.saunum_leil", ATTR_PRESET_MODE: "type_2"},
blocking=True,
)
assert exc_info.value.translation_key == "preset_session_active"
assert exc_info.value.translation_domain == "saunum"
@pytest.mark.parametrize(
("sauna_type", "expected_preset"),
[
(0, "type_1"),
(1, "type_2"),
(2, "type_3"),
(None, "type_1"),
],
)
async def test_preset_mode_attributes_default_names(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
sauna_type: int | None,
expected_preset: str,
) -> None:
"""Test preset mode attributes with default names."""
mock_saunum_client.async_get_data.return_value = replace(
mock_saunum_client.async_get_data.return_value, sauna_type=sauna_type
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.saunum_leil")
assert state is not None
assert state.attributes.get(ATTR_PRESET_MODE) == expected_preset
async def test_preset_mode_attributes_custom_names(
hass: HomeAssistant,
mock_saunum_client,
) -> None:
"""Test preset mode attributes with custom names."""
custom_options = {
OPT_PRESET_NAME_TYPE_1: "Finnish Sauna",
OPT_PRESET_NAME_TYPE_2: "Turkish Bath",
OPT_PRESET_NAME_TYPE_3: "Steam Room",
}
mock_config_entry = MockConfigEntry(
domain="saunum",
data={"host": "192.168.1.100"},
options=custom_options,
title="Saunum",
)
mock_saunum_client.async_get_data.return_value = replace(
mock_saunum_client.async_get_data.return_value, sauna_type=1
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.saunum_leil")
assert state is not None
assert state.attributes.get(ATTR_PRESET_MODE) == "Turkish Bath"
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: "climate.saunum_leil", ATTR_PRESET_MODE: "Steam Room"},
blocking=True,
)
mock_saunum_client.async_set_sauna_type.assert_called_once_with(2)
async def test_preset_mode_options_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
) -> None:
"""Test that preset names update when options are changed."""
entity_id = "climate.saunum_leil"
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.saunum_leil")
assert state is not None
assert "type_1" in state.attributes.get("preset_modes", [])
custom_options = {
OPT_PRESET_NAME_TYPE_1: "Custom Type 1",
OPT_PRESET_NAME_TYPE_2: "Custom Type 2",
OPT_PRESET_NAME_TYPE_3: "Custom Type 3",
}
hass.config_entries.async_update_entry(mock_config_entry, options=custom_options)
await hass.async_block_till_done()
state = hass.states.get("climate.saunum_leil")
assert state is not None
assert "Custom Type 1" in state.attributes.get("preset_modes", [])
assert "type_1" not in state.attributes.get("preset_modes", [])
# Try to set fan mode and expect error
with pytest.raises(
ServiceValidationError,
match="Cannot change fan mode when sauna session is not active",
):
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: entity_id, ATTR_FAN_MODE: FAN_LOW},
blocking=True,
)
async def test_fan_mode_error_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
) -> None:
"""Test error handling when setting fan mode fails."""
entity_id = "climate.saunum_leil"
mock_saunum_client.async_get_data.return_value = replace(
mock_saunum_client.async_get_data.return_value, session_active=True
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Make the client method raise an exception
mock_saunum_client.async_set_fan_speed.side_effect = SaunumException(
"Communication error"
)
# Try to call the service and expect HomeAssistantError
with pytest.raises(HomeAssistantError) as exc_info:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: entity_id, ATTR_FAN_MODE: FAN_LOW},
blocking=True,
)
# Verify the exception has the correct translation key
assert exc_info.value.translation_key == "set_fan_mode_failed"
assert exc_info.value.translation_domain == "saunum"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/saunum/test_climate.py",
"license": "Apache License 2.0",
"lines": 465,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/saunum/test_config_flow.py | """Test the Saunum config flow."""
from __future__ import annotations
from unittest.mock import AsyncMock
from pysaunum import SaunumConnectionError, SaunumException
import pytest
from homeassistant.components.saunum.const import (
DOMAIN,
OPT_PRESET_NAME_TYPE_1,
OPT_PRESET_NAME_TYPE_2,
OPT_PRESET_NAME_TYPE_3,
)
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
TEST_USER_INPUT = {CONF_HOST: "192.168.1.100"}
TEST_RECONFIGURE_INPUT = {CONF_HOST: "192.168.1.200"}
@pytest.mark.usefixtures("mock_saunum_client")
async def test_full_flow(hass: HomeAssistant, 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"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Saunum"
assert result["data"] == TEST_USER_INPUT
@pytest.mark.parametrize(
("side_effect", "error_base"),
[
(SaunumConnectionError("Connection failed"), "cannot_connect"),
(SaunumException("Read error"), "cannot_connect"),
(Exception("Unexpected error"), "unknown"),
],
)
async def test_form_errors(
hass: HomeAssistant,
mock_saunum_client_class,
side_effect: Exception,
error_base: str,
mock_setup_entry: AsyncMock,
) -> None:
"""Test error handling and recovery."""
mock_saunum_client_class.create.side_effect = side_effect
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_USER_INPUT,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_base}
# Test recovery - try again without the error
mock_saunum_client_class.create.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Saunum"
assert result["data"] == TEST_USER_INPUT
@pytest.mark.usefixtures("mock_saunum_client")
async def test_form_duplicate(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test duplicate entry handling."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_USER_INPUT,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("mock_saunum_client")
@pytest.mark.parametrize("user_input", [TEST_RECONFIGURE_INPUT, TEST_USER_INPUT])
async def test_reconfigure_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
user_input: dict[str, str],
mock_setup_entry: AsyncMock,
) -> 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"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data == user_input
@pytest.mark.parametrize(
("side_effect", "error_base"),
[
(SaunumConnectionError("Connection failed"), "cannot_connect"),
(SaunumException("Read error"), "cannot_connect"),
(Exception("Unexpected error"), "unknown"),
],
)
async def test_reconfigure_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client_class,
side_effect: Exception,
error_base: str,
mock_setup_entry: AsyncMock,
) -> None:
"""Test reconfigure flow error handling."""
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"] == "user"
mock_saunum_client_class.create.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_RECONFIGURE_INPUT,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_base}
# Test recovery - try again without the error
mock_saunum_client_class.create.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_RECONFIGURE_INPUT,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data == TEST_RECONFIGURE_INPUT
@pytest.mark.usefixtures("mock_saunum_client")
async def test_reconfigure_to_existing_host(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_setup_entry: AsyncMock
) -> None:
"""Test reconfigure flow aborts when changing to a host used by another entry."""
mock_config_entry.add_to_hass(hass)
# Create a second entry with a different host
second_entry = MockConfigEntry(
domain=DOMAIN,
data=TEST_RECONFIGURE_INPUT,
title="Saunum 2",
)
second_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
# Try to reconfigure first entry to use the same host as second entry
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
TEST_RECONFIGURE_INPUT, # Same host as second_entry
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
# Verify the original entry was not changed
assert mock_config_entry.data == TEST_USER_INPUT
@pytest.mark.usefixtures("mock_saunum_client")
async def test_options_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test options flow for configuring preset names."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(mock_config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
# Configure custom preset names
custom_options = {
OPT_PRESET_NAME_TYPE_1: "Finnish Sauna",
OPT_PRESET_NAME_TYPE_2: "Turkish Bath",
OPT_PRESET_NAME_TYPE_3: "Steam Room",
}
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input=custom_options,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == custom_options
assert mock_config_entry.options == custom_options
@pytest.mark.usefixtures("mock_saunum_client")
async def test_options_flow_with_existing_options(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test options flow with existing custom preset names."""
existing_options = {
OPT_PRESET_NAME_TYPE_1: "My Custom Type 1",
OPT_PRESET_NAME_TYPE_2: "My Custom Type 2",
OPT_PRESET_NAME_TYPE_3: "My Custom Type 3",
}
# Set up entry with existing options
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data=TEST_USER_INPUT,
options=existing_options,
title="Saunum",
)
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(mock_config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
# Update one option
updated_options = {
OPT_PRESET_NAME_TYPE_1: "Updated Type 1",
OPT_PRESET_NAME_TYPE_2: "My Custom Type 2",
OPT_PRESET_NAME_TYPE_3: "My Custom Type 3",
}
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input=updated_options,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == updated_options
assert mock_config_entry.options == updated_options
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/saunum/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 228,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/saunum/test_diagnostics.py | """Test Saunum Leil Sauna diagnostics."""
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
init_integration: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry diagnostics."""
assert (
await get_diagnostics_for_config_entry(hass, hass_client, init_integration)
== snapshot
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/saunum/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 17,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/saunum/test_init.py | """Test Saunum Leil integration setup and teardown."""
from unittest.mock import patch
from pysaunum import SaunumConnectionError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.saunum.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry
async def test_setup_and_unload(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
) -> None:
"""Test integration setup and unload."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
async def test_async_setup_entry_connection_failed(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client,
) -> None:
"""Test integration setup fails when connection cannot be established."""
mock_config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.saunum.SaunumClient.create",
side_effect=SaunumConnectionError("Connection failed"),
):
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
@pytest.mark.usefixtures("init_integration")
async def test_device_entry(
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test device registry entry."""
assert (
device_entry := device_registry.async_get_device(
identifiers={(DOMAIN, mock_config_entry.entry_id)}
)
)
assert device_entry == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/saunum/test_init.py",
"license": "Apache License 2.0",
"lines": 47,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/saunum/test_light.py | """Test the Saunum light platform."""
from __future__ import annotations
from dataclasses import replace
from pysaunum import SaunumException
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.light import DOMAIN as LIGHT_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.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return [Platform.LIGHT]
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("service", "expected_state", "client_method", "expected_args"),
[
(SERVICE_TURN_ON, STATE_ON, "async_set_light_control", (True,)),
(SERVICE_TURN_OFF, STATE_OFF, "async_set_light_control", (False,)),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_light_service_calls(
hass: HomeAssistant,
mock_saunum_client,
service: str,
expected_state: str,
client_method: str,
expected_args: tuple,
) -> None:
"""Test light service calls."""
entity_id = "light.saunum_leil_light"
# Mock the client method to update the coordinator data
async def update_light_state(*args):
"""Update the light state in mock data."""
current_data = mock_saunum_client.async_get_data.return_value
mock_saunum_client.async_get_data.return_value = replace(
current_data, light_on=(expected_state == STATE_ON)
)
getattr(mock_saunum_client, client_method).side_effect = update_light_state
await hass.services.async_call(
LIGHT_DOMAIN,
service,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
getattr(mock_saunum_client, client_method).assert_called_once_with(*expected_args)
# Verify state updated
state = hass.states.get(entity_id)
assert state is not None
assert state.state == expected_state
@pytest.mark.parametrize(
("service", "expected_error"),
[
(SERVICE_TURN_ON, "Failed to turn on light"),
(SERVICE_TURN_OFF, "Failed to turn off light"),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_light_service_call_failure(
hass: HomeAssistant,
mock_saunum_client,
service: str,
expected_error: str,
) -> None:
"""Test handling of light service call failures."""
entity_id = "light.saunum_leil_light"
# Make the client method raise an exception
mock_saunum_client.async_set_light_control.side_effect = SaunumException(
"Connection lost"
)
with pytest.raises(HomeAssistantError, match=expected_error):
await hass.services.async_call(
LIGHT_DOMAIN,
service,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/saunum/test_light.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/senz/test_climate.py | """Test Senz climate platform."""
from unittest.mock import MagicMock, patch
from httpx import RequestError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.climate import (
ATTR_HVAC_MODE,
DOMAIN as CLIMATE_DOMAIN,
HVACMode,
)
from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
TEST_DOMAIN = CLIMATE_DOMAIN
TEST_ENTITY_ID = "climate.test_room_1"
SERVICE_SET_TEMPERATURE = "set_temperature"
SERVICE_SET_HVAC_MODE = "set_hvac_mode"
async def test_climate_snapshot(
hass: HomeAssistant,
mock_senz_client: MagicMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test climate setup for cloud connection."""
with patch("homeassistant.components.senz.PLATFORMS", [Platform.CLIMATE]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
async def test_set_target(
hass: HomeAssistant,
mock_senz_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setting of target temperature."""
with (
patch("homeassistant.components.senz.PLATFORMS", [Platform.CLIMATE]),
patch(
"homeassistant.components.senz.Thermostat.manual", return_value=None
) as mock_manual,
):
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
TEST_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: TEST_ENTITY_ID, ATTR_TEMPERATURE: 17},
blocking=True,
)
mock_manual.assert_called_once_with(17.0)
async def test_set_target_fail(
hass: HomeAssistant,
mock_senz_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that failed set_temperature is handled."""
with (
patch("homeassistant.components.senz.PLATFORMS", [Platform.CLIMATE]),
patch(
"homeassistant.components.senz.Thermostat.manual",
side_effect=RequestError("API error"),
) as mock_manual,
):
await setup_integration(hass, mock_config_entry)
with pytest.raises(
HomeAssistantError, match="Failed to set target temperature on the device"
):
await hass.services.async_call(
TEST_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: TEST_ENTITY_ID, ATTR_TEMPERATURE: 17},
blocking=True,
)
mock_manual.assert_called_once()
@pytest.mark.parametrize(
("mode", "manual_count", "auto_count"),
[(HVACMode.HEAT, 1, 0), (HVACMode.AUTO, 0, 1)],
)
async def test_set_hvac_mode(
hass: HomeAssistant,
mock_senz_client: MagicMock,
mock_config_entry: MockConfigEntry,
mode: str,
manual_count: int,
auto_count: int,
) -> None:
"""Test setting of hvac mode."""
with (
patch("homeassistant.components.senz.PLATFORMS", [Platform.CLIMATE]),
patch(
"homeassistant.components.senz.Thermostat.manual", return_value=None
) as mock_manual,
patch(
"homeassistant.components.senz.Thermostat.auto", return_value=None
) as mock_auto,
):
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
TEST_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: TEST_ENTITY_ID, ATTR_HVAC_MODE: mode},
blocking=True,
)
assert mock_manual.call_count == manual_count
assert mock_auto.call_count == auto_count
async def test_set_hvac_mode_fail(
hass: HomeAssistant,
mock_senz_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that failed set_hvac_mode is handled."""
with (
patch("homeassistant.components.senz.PLATFORMS", [Platform.CLIMATE]),
patch(
"homeassistant.components.senz.Thermostat.manual",
side_effect=RequestError("API error"),
) as mock_manual,
):
await setup_integration(hass, mock_config_entry)
with pytest.raises(
HomeAssistantError, match="Failed to set hvac mode on the device"
):
await hass.services.async_call(
TEST_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: TEST_ENTITY_ID, ATTR_HVAC_MODE: HVACMode.HEAT},
blocking=True,
)
mock_manual.assert_called_once()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/senz/test_climate.py",
"license": "Apache License 2.0",
"lines": 132,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/senz/test_diagnostics.py | """Tests for the diagnostics data provided by the senz integration."""
from collections.abc import Generator
from unittest.mock import MagicMock
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import paths
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_diagnostics_config_entry(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_senz_client: Generator[MagicMock],
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics for config entry."""
await setup_integration(hass, mock_config_entry)
result = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
assert result == snapshot(
exclude=paths(
"entry_data.token.expires_at",
)
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/senz/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/senz/test_init.py | """Test init of senz integration."""
from http import HTTPStatus
import time
from unittest.mock import MagicMock, Mock, patch
from httpx import HTTPStatusError, RequestError
from pysenz import TOKEN_ENDPOINT
import pytest
from homeassistant.components.senz.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_entry_oauth2_flow import (
ImplementationUnavailableError,
)
from . import setup_integration
from .const import ENTRY_UNIQUE_ID
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_load_unload_entry(
hass: HomeAssistant,
mock_senz_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test load and unload entry."""
await setup_integration(hass, mock_config_entry)
entry = mock_config_entry
assert entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.NOT_LOADED
async def test_oauth_implementation_not_available(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test that an unavailable OAuth implementation raises ConfigEntryNotReady."""
with patch(
"homeassistant.components.senz.async_get_config_entry_implementation",
side_effect=ImplementationUnavailableError,
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_migrate_config_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_senz_client: MagicMock,
expires_at: float,
access_token: str,
) -> None:
"""Test migration of config entry."""
mock_entry_v1_1 = MockConfigEntry(
version=1,
minor_version=1,
domain=DOMAIN,
title="SENZ test",
data={
"auth_implementation": DOMAIN,
"token": {
"access_token": access_token,
"scope": "rest_api offline_access",
"expires_in": 86399,
"refresh_token": "3012bc9f-7a65-4240-b817-9154ffdcc30f",
"token_type": "Bearer",
"expires_at": expires_at,
},
},
entry_id="senz_test",
)
await setup_integration(hass, mock_entry_v1_1)
assert mock_entry_v1_1.version == 1
assert mock_entry_v1_1.minor_version == 2
assert mock_entry_v1_1.unique_id == ENTRY_UNIQUE_ID
@pytest.mark.parametrize(
("expires_at", "status", "expected_state"),
[
(
time.time() - 3600,
HTTPStatus.UNAUTHORIZED,
ConfigEntryState.SETUP_ERROR,
),
(
time.time() - 3600,
HTTPStatus.INTERNAL_SERVER_ERROR,
ConfigEntryState.SETUP_RETRY,
),
],
ids=["unauthorized", "internal_server_error"],
)
async def test_expired_token_refresh_failure(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
aioclient_mock: AiohttpClientMocker,
status: HTTPStatus,
expected_state: ConfigEntryState,
) -> None:
"""Test failure while refreshing token with a transient error."""
aioclient_mock.clear_requests()
aioclient_mock.post(
TOKEN_ENDPOINT,
status=status,
)
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is expected_state
@pytest.mark.parametrize(
("error", "expected_state"),
[
(
HTTPStatusError(
message="Exception",
request=Mock(),
response=MagicMock(status_code=HTTPStatus.UNAUTHORIZED),
),
ConfigEntryState.SETUP_ERROR,
),
(
HTTPStatusError(
message="Exception",
request=Mock(),
response=MagicMock(status_code=HTTPStatus.FORBIDDEN),
),
ConfigEntryState.SETUP_RETRY,
),
(RequestError("Exception"), ConfigEntryState.SETUP_RETRY),
],
ids=["unauthorized", "forbidden", "request_error"],
)
async def test_setup_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_senz_client: MagicMock,
error: Exception,
expected_state: ConfigEntryState,
) -> None:
"""Test setup failure due to unauthorized error."""
mock_senz_client.get_account.side_effect = error
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is expected_state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/senz/test_init.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/senz/test_sensor.py | """Test Senz sensor platform."""
from unittest.mock import MagicMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_sensor_snapshot(
hass: HomeAssistant,
mock_senz_client: MagicMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test sensor setup for cloud connection."""
with patch("homeassistant.components.senz.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/senz/test_sensor.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/switchbot/test_climate.py | """Tests for the Switchbot climate integration."""
from collections.abc import Callable
from unittest.mock import AsyncMock, patch
import pytest
from switchbot import SwitchbotOperationError
from homeassistant.components.climate import (
DOMAIN as CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_PRESET_MODE,
SERVICE_SET_TEMPERATURE,
HVACMode,
)
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from . import SMART_THERMOSTAT_RADIATOR_SERVICE_INFO
from tests.common import MockConfigEntry
from tests.components.bluetooth import inject_bluetooth_service_info
@pytest.mark.parametrize(
("service", "service_data", "mock_method"),
[
(SERVICE_SET_HVAC_MODE, {"hvac_mode": HVACMode.HEAT}, "set_hvac_mode"),
(SERVICE_SET_PRESET_MODE, {"preset_mode": "manual"}, "set_preset_mode"),
(SERVICE_SET_TEMPERATURE, {"temperature": 22}, "set_target_temperature"),
],
)
async def test_smart_thermostat_radiator_controlling(
hass: HomeAssistant,
mock_entry_encrypted_factory: Callable[[str], MockConfigEntry],
service: str,
service_data: dict,
mock_method: str,
) -> None:
"""Test controlling the smart thermostat radiator with different services."""
inject_bluetooth_service_info(hass, SMART_THERMOSTAT_RADIATOR_SERVICE_INFO)
entry = mock_entry_encrypted_factory("smart_thermostat_radiator")
entity_id = "climate.test_name"
entry.add_to_hass(hass)
mocked_instance = AsyncMock(return_value=True)
mocked_none_instance = AsyncMock(return_value=None)
with patch.multiple(
"homeassistant.components.switchbot.climate.switchbot.SwitchbotSmartThermostatRadiator",
get_basic_info=mocked_none_instance,
update=mocked_none_instance,
**{mock_method: mocked_instance},
):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
CLIMATE_DOMAIN,
service,
{**service_data, ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mocked_instance.assert_awaited_once()
@pytest.mark.parametrize(
("service", "service_data", "mock_method"),
[
(SERVICE_SET_HVAC_MODE, {"hvac_mode": HVACMode.HEAT}, "set_hvac_mode"),
(SERVICE_SET_PRESET_MODE, {"preset_mode": "manual"}, "set_preset_mode"),
(SERVICE_SET_TEMPERATURE, {"temperature": 22}, "set_target_temperature"),
],
)
@pytest.mark.parametrize(
("exception", "error_message"),
[
(
SwitchbotOperationError("Operation failed"),
"An error occurred while performing the action: Operation failed",
),
],
)
async def test_exception_handling_smart_thermostat_radiator_service(
hass: HomeAssistant,
mock_entry_encrypted_factory: Callable[[str], MockConfigEntry],
service: str,
service_data: dict,
mock_method: str,
exception: Exception,
error_message: str,
) -> None:
"""Test exception handling for smart thermostat radiator service with exception."""
inject_bluetooth_service_info(hass, SMART_THERMOSTAT_RADIATOR_SERVICE_INFO)
entry = mock_entry_encrypted_factory("smart_thermostat_radiator")
entry.add_to_hass(hass)
entity_id = "climate.test_name"
mocked_none_instance = AsyncMock(return_value=None)
with patch.multiple(
"homeassistant.components.switchbot.climate.switchbot.SwitchbotSmartThermostatRadiator",
get_basic_info=mocked_none_instance,
update=mocked_none_instance,
**{mock_method: AsyncMock(side_effect=exception)},
):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
with pytest.raises(HomeAssistantError, match=error_message):
await hass.services.async_call(
CLIMATE_DOMAIN,
service,
{**service_data, ATTR_ENTITY_ID: entity_id},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/switchbot/test_climate.py",
"license": "Apache License 2.0",
"lines": 102,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tesla_fleet/test_update.py | """Test the Tesla Fleet update platform."""
import copy
import time
from typing import Any
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.tesla_fleet.coordinator import VEHICLE_INTERVAL
from homeassistant.components.tesla_fleet.update import INSTALLING, SCHEDULED
from homeassistant.components.update import DOMAIN as UPDATE_DOMAIN, SERVICE_INSTALL
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import assert_entities, setup_platform
from .const import COMMAND_OK, VEHICLE_DATA, VEHICLE_DATA_ALT
from tests.common import MockConfigEntry, async_fire_time_changed
def _get_software_update(data: dict[str, Any]) -> dict[str, Any]:
"""Get the software_update dict from vehicle data."""
return data["response"]["vehicle_state"]["software_update"]
async def test_update(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
normal_config_entry: MockConfigEntry,
) -> None:
"""Tests that the update entities are correct."""
await setup_platform(hass, normal_config_entry, [Platform.UPDATE])
assert_entities(hass, normal_config_entry.entry_id, entity_registry, snapshot)
async def test_update_alt(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
normal_config_entry: MockConfigEntry,
mock_vehicle_data: AsyncMock,
) -> None:
"""Tests that the update entities are correct."""
mock_vehicle_data.return_value = VEHICLE_DATA_ALT
await setup_platform(hass, normal_config_entry, [Platform.UPDATE])
assert_entities(hass, normal_config_entry.entry_id, entity_registry, snapshot)
async def test_update_services(
hass: HomeAssistant,
normal_config_entry: MockConfigEntry,
mock_vehicle_data: AsyncMock,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
) -> None:
"""Tests that the update services work."""
await setup_platform(hass, normal_config_entry, [Platform.UPDATE])
entity_id = "update.test_update"
with patch(
"tesla_fleet_api.tesla.VehicleFleet.schedule_software_update",
return_value=COMMAND_OK,
) as call:
await hass.services.async_call(
UPDATE_DOMAIN,
SERVICE_INSTALL,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
call.assert_called_once()
vehicle_installing = copy.deepcopy(VEHICLE_DATA)
_get_software_update(vehicle_installing)["status"] = INSTALLING
mock_vehicle_data.return_value = vehicle_installing
freezer.tick(VEHICLE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state is not None
assert state.attributes["in_progress"] is True
async def test_update_scheduled_far_future_not_in_progress(
hass: HomeAssistant,
normal_config_entry: MockConfigEntry,
mock_vehicle_data: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Tests that a scheduled update far in the future is not shown as in_progress."""
await setup_platform(hass, normal_config_entry, [Platform.UPDATE])
entity_id = "update.test_update"
# Verify initial state (available) is not in_progress
state = hass.states.get(entity_id)
assert state is not None
assert state.attributes["in_progress"] is False
# Simulate update being scheduled for 1 hour in the future
vehicle_scheduled = copy.deepcopy(VEHICLE_DATA)
software_update = _get_software_update(vehicle_scheduled)
software_update["status"] = SCHEDULED
# Set scheduled time to 1 hour from now (well beyond threshold)
software_update["scheduled_time_ms"] = int((time.time() + 3600) * 1000)
mock_vehicle_data.return_value = vehicle_scheduled
freezer.tick(VEHICLE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Scheduled update far in future should NOT be in_progress
state = hass.states.get(entity_id)
assert state is not None
assert state.attributes["in_progress"] is False
async def test_update_scheduled_soon_in_progress(
hass: HomeAssistant,
normal_config_entry: MockConfigEntry,
mock_vehicle_data: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Tests that a scheduled update within threshold is shown as in_progress."""
await setup_platform(hass, normal_config_entry, [Platform.UPDATE])
entity_id = "update.test_update"
# Simulate update being scheduled within threshold (1 minute from now)
vehicle_scheduled = copy.deepcopy(VEHICLE_DATA)
software_update = _get_software_update(vehicle_scheduled)
software_update["status"] = SCHEDULED
# Set scheduled time to 1 minute from now (within 2 minute threshold)
software_update["scheduled_time_ms"] = int((time.time() + 60) * 1000)
mock_vehicle_data.return_value = vehicle_scheduled
freezer.tick(VEHICLE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Scheduled update within threshold should be in_progress
state = hass.states.get(entity_id)
assert state is not None
assert state.attributes["in_progress"] is True
async def test_update_scheduled_no_time_not_in_progress(
hass: HomeAssistant,
normal_config_entry: MockConfigEntry,
mock_vehicle_data: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Tests that a scheduled update without scheduled_time_ms is not in_progress."""
await setup_platform(hass, normal_config_entry, [Platform.UPDATE])
entity_id = "update.test_update"
# Simulate update being scheduled but without scheduled_time_ms
vehicle_scheduled = copy.deepcopy(VEHICLE_DATA)
_get_software_update(vehicle_scheduled)["status"] = SCHEDULED
# No scheduled_time_ms field
mock_vehicle_data.return_value = vehicle_scheduled
freezer.tick(VEHICLE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Scheduled update without time should NOT be in_progress
state = hass.states.get(entity_id)
assert state is not None
assert state.attributes["in_progress"] is False
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tesla_fleet/test_update.py",
"license": "Apache License 2.0",
"lines": 140,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/text/test_trigger.py | """Test text trigger."""
import pytest
from homeassistant.const import (
ATTR_LABEL_ID,
CONF_ENTITY_ID,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
parametrize_target_entities,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_texts(hass: HomeAssistant) -> list[str]:
"""Create multiple text entities associated with different targets."""
return (await target_entities(hass, "text"))["included"]
@pytest.mark.parametrize("trigger_key", ["text.changed"])
async def test_text_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the text triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("text"),
)
@pytest.mark.parametrize(
("trigger", "states"),
[
(
"text.changed",
[
{"included": {"state": None, "attributes": {}}, "count": 0},
{"included": {"state": "bar", "attributes": {}}, "count": 0},
{"included": {"state": "baz", "attributes": {}}, "count": 1},
],
),
(
"text.changed",
[
{"included": {"state": "foo", "attributes": {}}, "count": 0},
{"included": {"state": "bar", "attributes": {}}, "count": 1},
{"included": {"state": "baz", "attributes": {}}, "count": 1},
],
),
(
"text.changed",
[
{"included": {"state": "foo", "attributes": {}}, "count": 0},
# empty string
{"included": {"state": "", "attributes": {}}, "count": 1},
{"included": {"state": "baz", "attributes": {}}, "count": 1},
],
),
(
"text.changed",
[
{
"included": {"state": STATE_UNAVAILABLE, "attributes": {}},
"count": 0,
},
{"included": {"state": "bar", "attributes": {}}, "count": 0},
{"included": {"state": "baz", "attributes": {}}, "count": 1},
{
"included": {"state": STATE_UNAVAILABLE, "attributes": {}},
"count": 0,
},
],
),
(
"text.changed",
[
{"included": {"state": STATE_UNKNOWN, "attributes": {}}, "count": 0},
{"included": {"state": "bar", "attributes": {}}, "count": 0},
{"included": {"state": "baz", "attributes": {}}, "count": 1},
{"included": {"state": STATE_UNKNOWN, "attributes": {}}, "count": 0},
],
),
],
)
async def test_text_state_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_texts: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
states: list[TriggerStateDescription],
) -> None:
"""Test that the text state trigger fires when any text state changes to a specific state."""
other_entity_ids = set(target_texts) - {entity_id}
# Set all texts, including the tested text, to the initial state
for eid in target_texts:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, None, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other texts also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/text/test_trigger.py",
"license": "Apache License 2.0",
"lines": 122,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/toon/test_init.py | """Tests for the Toon component."""
from unittest.mock import patch
from homeassistant.components.toon import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_entry_oauth2_flow import (
ImplementationUnavailableError,
)
from tests.common import MockConfigEntry
async def test_oauth_implementation_not_available(
hass: HomeAssistant,
) -> None:
"""Test that unavailable OAuth implementation raises ConfigEntryNotReady."""
config_entry = MockConfigEntry(
domain=DOMAIN,
version=2,
data={
"auth_implementation": DOMAIN,
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
"agreement_id": "test-agreement-id",
},
)
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.toon.async_get_config_entry_implementation",
side_effect=ImplementationUnavailableError,
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_migrate_entry_minor_version_2_2(hass: HomeAssistant) -> None:
"""Test migrating a 2.1 config entry to 2.2."""
with patch("homeassistant.components.toon.async_setup_entry", return_value=True):
entry = MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation": DOMAIN,
"token": {
"refresh_token": "mock-refresh-token",
"access_token": "mock-access-token",
"type": "Bearer",
"expires_in": 60,
},
"agreement_id": 123,
},
version=2,
minor_version=1,
unique_id=123,
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
assert entry.version == 2
assert entry.minor_version == 2
assert entry.unique_id == "123"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/toon/test_init.py",
"license": "Apache License 2.0",
"lines": 59,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/vacuum/test_trigger.py | """Test vacuum triggers."""
from typing import Any
import pytest
from homeassistant.components.vacuum import VacuumActivity
from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
other_states,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_vacuums(hass: HomeAssistant) -> list[str]:
"""Create multiple vacuum entities associated with different targets."""
return (await target_entities(hass, "vacuum"))["included"]
@pytest.mark.parametrize(
"trigger_key",
[
"vacuum.docked",
"vacuum.errored",
"vacuum.paused_cleaning",
"vacuum.started_cleaning",
"vacuum.started_returning",
],
)
async def test_vacuum_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the vacuum triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("vacuum"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="vacuum.docked",
target_states=[VacuumActivity.DOCKED],
other_states=other_states(VacuumActivity.DOCKED),
),
*parametrize_trigger_states(
trigger="vacuum.errored",
target_states=[VacuumActivity.ERROR],
other_states=other_states(VacuumActivity.ERROR),
),
*parametrize_trigger_states(
trigger="vacuum.paused_cleaning",
target_states=[VacuumActivity.PAUSED],
other_states=other_states(VacuumActivity.PAUSED),
),
*parametrize_trigger_states(
trigger="vacuum.started_cleaning",
target_states=[VacuumActivity.CLEANING],
other_states=other_states(VacuumActivity.CLEANING),
),
*parametrize_trigger_states(
trigger="vacuum.started_returning",
target_states=[VacuumActivity.RETURNING],
other_states=other_states(VacuumActivity.RETURNING),
),
],
)
async def test_vacuum_state_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_vacuums: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the vacuum state trigger fires when any vacuum state changes to a specific state."""
other_entity_ids = set(target_vacuums) - {entity_id}
# Set all vacuums, including the tested one, to the initial state
for eid in target_vacuums:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check if changing other vacuums also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("vacuum"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="vacuum.docked",
target_states=[VacuumActivity.DOCKED],
other_states=other_states(VacuumActivity.DOCKED),
),
*parametrize_trigger_states(
trigger="vacuum.errored",
target_states=[VacuumActivity.ERROR],
other_states=other_states(VacuumActivity.ERROR),
),
*parametrize_trigger_states(
trigger="vacuum.paused_cleaning",
target_states=[VacuumActivity.PAUSED],
other_states=other_states(VacuumActivity.PAUSED),
),
*parametrize_trigger_states(
trigger="vacuum.started_cleaning",
target_states=[VacuumActivity.CLEANING],
other_states=other_states(VacuumActivity.CLEANING),
),
*parametrize_trigger_states(
trigger="vacuum.started_returning",
target_states=[VacuumActivity.RETURNING],
other_states=other_states(VacuumActivity.RETURNING),
),
],
)
async def test_vacuum_state_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_vacuums: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the vacuum state trigger fires when the first vacuum changes to a specific state."""
other_entity_ids = set(target_vacuums) - {entity_id}
# Set all vacuums, including the tested one, to the initial state
for eid in target_vacuums:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Triggering other vacuums should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("vacuum"),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="vacuum.docked",
target_states=[VacuumActivity.DOCKED],
other_states=other_states(VacuumActivity.DOCKED),
),
*parametrize_trigger_states(
trigger="vacuum.errored",
target_states=[VacuumActivity.ERROR],
other_states=other_states(VacuumActivity.ERROR),
),
*parametrize_trigger_states(
trigger="vacuum.paused_cleaning",
target_states=[VacuumActivity.PAUSED],
other_states=other_states(VacuumActivity.PAUSED),
),
*parametrize_trigger_states(
trigger="vacuum.started_cleaning",
target_states=[VacuumActivity.CLEANING],
other_states=other_states(VacuumActivity.CLEANING),
),
*parametrize_trigger_states(
trigger="vacuum.started_returning",
target_states=[VacuumActivity.RETURNING],
other_states=other_states(VacuumActivity.RETURNING),
),
],
)
async def test_vacuum_state_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_vacuums: list[str],
trigger_target_config: dict,
entity_id: str,
entities_in_target: int,
trigger: str,
trigger_options: dict[str, Any],
states: list[TriggerStateDescription],
) -> None:
"""Test that the vacuum state trigger fires when the last vacuum changes to a specific state."""
other_entity_ids = set(target_vacuums) - {entity_id}
# Set all vacuums, including the tested one, to the initial state
for eid in target_vacuums:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/vacuum/test_trigger.py",
"license": "Apache License 2.0",
"lines": 238,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/velux/test_button.py | """Test Velux button entities."""
from unittest.mock import AsyncMock, MagicMock
import pytest
from pyvlx import PyVLXException
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.components.velux import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platform() -> Platform:
"""Fixture to specify platform to test."""
return Platform.BUTTON
@pytest.mark.usefixtures("setup_integration")
async def test_button_snapshot(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot the button entity (registry + state)."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
# Get the button entity setup and test device association
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert len(entity_entries) == 1
entry = entity_entries[0]
assert entry.device_id is not None
device_entry = device_registry.async_get(entry.device_id)
assert device_entry is not None
assert (DOMAIN, f"gateway_{mock_config_entry.entry_id}") in device_entry.identifiers
assert device_entry.via_device_id is None
@pytest.mark.usefixtures("setup_integration")
async def test_button_press_success(
hass: HomeAssistant,
mock_pyvlx: MagicMock,
) -> None:
"""Test successful button press."""
# Configure the mock method to be async and return a coroutine
mock_pyvlx.reboot_gateway.return_value = AsyncMock()()
# Press the button
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.klf_200_gateway_restart"},
blocking=True,
)
# Verify the reboot method was called
mock_pyvlx.reboot_gateway.assert_called_once()
@pytest.mark.usefixtures("setup_integration")
async def test_button_press_failure(
hass: HomeAssistant,
mock_pyvlx: MagicMock,
) -> None:
"""Test button press failure handling."""
# Mock reboot failure
mock_pyvlx.reboot_gateway.side_effect = PyVLXException("Connection failed")
# Press the button and expect HomeAssistantError
with pytest.raises(
HomeAssistantError,
match="Failed to reboot gateway. Try again in a few moments or power cycle the device manually",
):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.klf_200_gateway_restart"},
blocking=True,
)
# Verify the reboot method was called
mock_pyvlx.reboot_gateway.assert_called_once()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/velux/test_button.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/velux/test_light.py | """Test Velux light entities."""
from unittest.mock import AsyncMock, MagicMock
import pytest
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
DOMAIN as LIGHT_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import update_callback_entity
from tests.common import MockConfigEntry, SnapshotAssertion, snapshot_platform
# Apply setup_integration fixture to all tests in this module
pytestmark = pytest.mark.usefixtures("setup_integration")
@pytest.fixture
def platform() -> Platform:
"""Fixture to specify platform to test."""
return Platform.LIGHT
@pytest.mark.parametrize(
"mock_pyvlx", ["mock_light", "mock_onoff_light"], indirect=True
)
async def test_light_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot the entity and validate registry metadata for light entities."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
async def test_light_device_association(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
mock_light: AsyncMock,
) -> None:
"""Test light device association."""
test_entity_id = f"light.{mock_light.name.lower().replace(' ', '_')}"
# Get entity + device entry
entity_entry = entity_registry.async_get(test_entity_id)
assert entity_entry is not None
assert entity_entry.device_id is not None
device_entry = device_registry.async_get(entity_entry.device_id)
assert device_entry is not None
# Verify device has correct identifiers + name
assert ("velux", mock_light.serial_number) in device_entry.identifiers
assert device_entry.name == mock_light.name
# This test is not light specific, it just uses the light platform to test the base entity class.
async def test_entity_callbacks(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_light: AsyncMock,
) -> None:
"""Ensure the entity unregisters its device-updated callback when unloaded."""
# Entity is created by setup_integration; callback should be registered
test_entity_id = f"light.{mock_light.name.lower().replace(' ', '_')}"
state = hass.states.get(test_entity_id)
assert state is not None
# Callback is registered exactly once with a callable
assert mock_light.register_device_updated_cb.call_count == 1
cb = mock_light.register_device_updated_cb.call_args[0][0]
assert callable(cb)
# Unload the config entry to trigger async_will_remove_from_hass
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Callback must be unregistered with the same callable
assert mock_light.unregister_device_updated_cb.call_count == 1
assert mock_light.unregister_device_updated_cb.call_args[0][0] is cb
# Test availability functionality by using the light platform
async def test_entity_availability(
hass: HomeAssistant, mock_light: AsyncMock, caplog: pytest.LogCaptureFixture
) -> None:
"""Test that entity availability updates based on device connection status."""
entity_id = f"light.{mock_light.name.lower().replace(' ', '_')}"
# Initially connected
mock_light.pyvlx.get_connected.return_value = True
await update_callback_entity(hass, mock_light)
state = hass.states.get(entity_id)
assert state is not None
assert state.state != STATE_UNAVAILABLE
# Simulate disconnection
mock_light.pyvlx.get_connected.return_value = False
await update_callback_entity(hass, mock_light)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_UNAVAILABLE
assert caplog.text.count(f"Entity {entity_id} is unavailable") == 1
# Simulate disconnection, check we don't log again
mock_light.pyvlx.get_connected.return_value = False
await update_callback_entity(hass, mock_light)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_UNAVAILABLE
assert caplog.text.count(f"Entity {entity_id} is unavailable") == 1
# Simulate reconnection
mock_light.pyvlx.get_connected.return_value = True
await update_callback_entity(hass, mock_light)
state = hass.states.get(entity_id)
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert caplog.text.count(f"Entity {entity_id} is back online") == 1
# Simulate reconnection, check we don't log again
mock_light.pyvlx.get_connected.return_value = True
await update_callback_entity(hass, mock_light)
state = hass.states.get(entity_id)
assert state is not None
assert state.state != STATE_UNAVAILABLE
assert caplog.text.count(f"Entity {entity_id} is back online") == 1
async def test_light_brightness_and_is_on(
hass: HomeAssistant, mock_light: AsyncMock
) -> None:
"""Validate brightness mapping and on/off state from intensity."""
entity_id = f"light.{mock_light.name.lower().replace(' ', '_')}"
# Set initial intensity values
mock_light.intensity.intensity_percent = 20 # 20% "intensity" -> 20% brightness
mock_light.intensity.off = False
mock_light.intensity.known = True
# Trigger state write
await update_callback_entity(hass, mock_light)
state = hass.states.get(entity_id)
assert state is not None
# brightness = int(20 * 255 / 100) = int(51)
assert state.attributes.get(ATTR_BRIGHTNESS) == 51
assert state.state == STATE_ON
# Mark as off
mock_light.intensity.off = True
await update_callback_entity(hass, mock_light)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_OFF
async def test_light_turn_on_with_brightness_uses_set_intensity(
hass: HomeAssistant, mock_light: AsyncMock
) -> None:
"""Turning on with brightness calls set_intensity with percent."""
entity_id = f"light.{mock_light.name.lower().replace(' ', '_')}"
# Call turn_on with brightness=51 (20% when normalized)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{"entity_id": entity_id, ATTR_BRIGHTNESS: 51},
blocking=True,
)
# set_intensity called once; turn_on should not be used in this path
assert mock_light.set_intensity.await_count == 1
assert mock_light.turn_on.await_count == 0
# Inspect the intensity argument (first positional)
args, kwargs = mock_light.set_intensity.await_args
intensity_obj = args[0]
# brightness 51 -> 20% normalized -> intensity_percent = 20
assert intensity_obj.intensity_percent == 20
assert kwargs.get("wait_for_completion") is True
@pytest.mark.parametrize(
"mock_pyvlx", ["mock_light", "mock_onoff_light"], indirect=True
)
async def test_light_turn_on_without_brightness_calls_turn_on(
hass: HomeAssistant, mock_pyvlx: MagicMock
) -> None:
"""Turning on without brightness uses node.turn_on."""
node = mock_pyvlx.nodes[0]
entity_id = f"light.{node.name.lower().replace(' ', '_')}"
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{"entity_id": entity_id},
blocking=True,
)
node.turn_on.assert_awaited_once_with(wait_for_completion=True)
assert node.set_intensity.await_count == 0
@pytest.mark.parametrize(
"mock_pyvlx", ["mock_light", "mock_onoff_light"], indirect=True
)
async def test_light_turn_off_calls_turn_off(
hass: HomeAssistant, mock_pyvlx: MagicMock
) -> None:
"""Turning off calls device.turn_off with wait_for_completion."""
node = mock_pyvlx.nodes[0]
entity_id = f"light.{node.name.lower().replace(' ', '_')}"
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{"entity_id": entity_id},
blocking=True,
)
node.turn_off.assert_awaited_once_with(wait_for_completion=True)
assert node.set_intensity.await_count == 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/velux/test_light.py",
"license": "Apache License 2.0",
"lines": 191,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/velux/test_scene.py | """Test Velux scene entities."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN, SERVICE_TURN_ON
from homeassistant.components.velux import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import AsyncMock, MockConfigEntry, snapshot_platform
@pytest.fixture
def platform() -> Platform:
"""Fixture to specify platform to test."""
return Platform.SCENE
@pytest.mark.usefixtures("setup_integration")
async def test_scene_snapshot(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot the scene entity (registry + state)."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
# Get the scene entity setup and test device association
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert len(entity_entries) == 1
entry = entity_entries[0]
assert entry.device_id is not None
device_entry = device_registry.async_get(entry.device_id)
assert device_entry is not None
# Scenes are associated with the gateway device
assert (DOMAIN, f"gateway_{mock_config_entry.entry_id}") in device_entry.identifiers
assert device_entry.via_device_id is None
@pytest.mark.usefixtures("setup_integration")
async def test_scene_activation(
hass: HomeAssistant,
mock_scene: AsyncMock,
) -> None:
"""Test successful scene activation."""
# activate the scene via service call
await hass.services.async_call(
SCENE_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "scene.klf_200_gateway_test_scene"},
blocking=True,
)
# Verify the run method was called
mock_scene.run.assert_awaited_once_with(wait_for_completion=False)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/velux/test_scene.py",
"license": "Apache License 2.0",
"lines": 55,
"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.