sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
home-assistant/core:homeassistant/components/qwikswitch/const.py | """Support for Qwikswitch devices."""
from __future__ import annotations
from typing import TYPE_CHECKING
from homeassistant.util.hass_dict import HassKey
if TYPE_CHECKING:
from pyqwikswitch.async_ import QSUsb
DOMAIN = "qwikswitch"
DATA_QUIKSWITCH: HassKey[QSUsb] = HassKey(DOMAIN)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/qwikswitch/const.py",
"license": "Apache License 2.0",
"lines": 8,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/saunum/number.py | """Number platform for Saunum Leil Sauna Control Unit."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING
from pysaunum import (
MAX_DURATION,
MAX_FAN_DURATION,
MIN_DURATION,
MIN_FAN_DURATION,
SaunumClient,
SaunumData,
SaunumException,
)
from homeassistant.components.number import (
NumberDeviceClass,
NumberEntity,
NumberEntityDescription,
)
from homeassistant.const import UnitOfTime
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import LeilSaunaConfigEntry
from .const import DOMAIN
from .entity import LeilSaunaEntity
if TYPE_CHECKING:
from .coordinator import LeilSaunaCoordinator
PARALLEL_UPDATES = 0
# Default values when device returns None or invalid data
DEFAULT_DURATION_MIN = 120
DEFAULT_FAN_DURATION_MIN = 15
@dataclass(frozen=True, kw_only=True)
class LeilSaunaNumberEntityDescription(NumberEntityDescription):
"""Describes Saunum Leil Sauna number entity."""
value_fn: Callable[[SaunumData], int | float | None]
set_value_fn: Callable[[SaunumClient, float], Awaitable[None]]
NUMBERS: tuple[LeilSaunaNumberEntityDescription, ...] = (
LeilSaunaNumberEntityDescription(
key="sauna_duration",
translation_key="sauna_duration",
device_class=NumberDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.MINUTES,
native_min_value=1,
native_max_value=MAX_DURATION,
native_step=1,
value_fn=lambda data: (
duration
if (duration := data.sauna_duration) is not None and duration > MIN_DURATION
else DEFAULT_DURATION_MIN
),
set_value_fn=lambda client, value: client.async_set_sauna_duration(int(value)),
),
LeilSaunaNumberEntityDescription(
key="fan_duration",
translation_key="fan_duration",
device_class=NumberDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.MINUTES,
native_min_value=1,
native_max_value=MAX_FAN_DURATION,
native_step=1,
value_fn=lambda data: (
fan_dur
if (fan_dur := data.fan_duration) is not None and fan_dur > MIN_FAN_DURATION
else DEFAULT_FAN_DURATION_MIN
),
set_value_fn=lambda client, value: client.async_set_fan_duration(int(value)),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: LeilSaunaConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Saunum Leil Sauna number entities."""
coordinator = entry.runtime_data
async_add_entities(
LeilSaunaNumber(coordinator, description) for description in NUMBERS
)
class LeilSaunaNumber(LeilSaunaEntity, NumberEntity):
"""Representation of a Saunum Leil Sauna number entity."""
entity_description: LeilSaunaNumberEntityDescription
def __init__(
self,
coordinator: LeilSaunaCoordinator,
description: LeilSaunaNumberEntityDescription,
) -> None:
"""Initialize the number entity."""
super().__init__(coordinator)
self._attr_unique_id = f"{coordinator.config_entry.entry_id}-{description.key}"
self.entity_description = description
@property
def native_value(self) -> float | None:
"""Return the current value."""
return self.entity_description.value_fn(self.coordinator.data)
async def async_set_native_value(self, value: float) -> None:
"""Set new value."""
# Prevent changing certain settings when session is active
session_active = self.coordinator.data.session_active
if session_active and self.entity_description.key in (
"sauna_duration",
"fan_duration",
):
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key=f"session_active_cannot_change_{self.entity_description.key}",
)
try:
await self.entity_description.set_value_fn(self.coordinator.client, value)
except SaunumException as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key=f"set_{self.entity_description.key}_failed",
) from err
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/saunum/number.py",
"license": "Apache License 2.0",
"lines": 115,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/siren/condition.py | """Provides conditions for sirens."""
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers.condition import Condition, make_entity_state_condition
from . import DOMAIN
CONDITIONS: dict[str, type[Condition]] = {
"is_off": make_entity_state_condition(DOMAIN, STATE_OFF),
"is_on": make_entity_state_condition(DOMAIN, STATE_ON),
}
async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]:
"""Return the siren conditions."""
return CONDITIONS
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/siren/condition.py",
"license": "Apache License 2.0",
"lines": 12,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sunricher_dali/binary_sensor.py | """Platform for Sunricher DALI binary sensor entities."""
from __future__ import annotations
from PySrDaliGateway import CallbackEventType, Device
from PySrDaliGateway.helper import is_motion_sensor
from PySrDaliGateway.types import MotionState, MotionStatus
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN, MANUFACTURER
from .entity import DaliDeviceEntity
from .types import DaliCenterConfigEntry
_OCCUPANCY_ON_STATES = frozenset(
{
MotionState.MOTION,
MotionState.OCCUPANCY,
MotionState.PRESENCE,
}
)
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
entry: DaliCenterConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Sunricher DALI binary sensor entities from config entry."""
devices = entry.runtime_data.devices
entities: list[BinarySensorEntity] = []
for device in devices:
if is_motion_sensor(device.dev_type):
entities.append(SunricherDaliMotionSensor(device))
entities.append(SunricherDaliOccupancySensor(device))
if entities:
async_add_entities(entities)
class SunricherDaliMotionSensor(DaliDeviceEntity, BinarySensorEntity):
"""Instantaneous motion detection sensor."""
_attr_device_class = BinarySensorDeviceClass.MOTION
def __init__(self, device: Device) -> None:
"""Initialize the motion sensor."""
super().__init__(device)
self._device = device
self._attr_unique_id = f"{device.dev_id}_motion"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.dev_id)},
name=device.name,
manufacturer=MANUFACTURER,
model=device.model,
via_device=(DOMAIN, device.gw_sn),
)
async def async_added_to_hass(self) -> None:
"""Handle entity addition to Home Assistant."""
await super().async_added_to_hass()
self.async_on_remove(
self._device.register_listener(
CallbackEventType.MOTION_STATUS, self._handle_motion_status
)
)
self._device.read_status()
@callback
def _handle_motion_status(self, status: MotionStatus) -> None:
"""Handle motion status updates."""
motion_state = status["motion_state"]
if motion_state == MotionState.MOTION:
self._attr_is_on = True
self.schedule_update_ha_state()
elif motion_state == MotionState.NO_MOTION:
self._attr_is_on = False
self.schedule_update_ha_state()
class SunricherDaliOccupancySensor(DaliDeviceEntity, BinarySensorEntity):
"""Persistent occupancy detection sensor."""
_attr_device_class = BinarySensorDeviceClass.OCCUPANCY
def __init__(self, device: Device) -> None:
"""Initialize the occupancy sensor."""
super().__init__(device)
self._device = device
self._attr_unique_id = f"{device.dev_id}_occupancy"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.dev_id)},
name=device.name,
manufacturer=MANUFACTURER,
model=device.model,
via_device=(DOMAIN, device.gw_sn),
)
async def async_added_to_hass(self) -> None:
"""Handle entity addition to Home Assistant."""
await super().async_added_to_hass()
self.async_on_remove(
self._device.register_listener(
CallbackEventType.MOTION_STATUS, self._handle_motion_status
)
)
self._device.read_status()
@callback
def _handle_motion_status(self, status: MotionStatus) -> None:
"""Handle motion status updates."""
motion_state = status["motion_state"]
if motion_state in _OCCUPANCY_ON_STATES:
self._attr_is_on = True
self.schedule_update_ha_state()
elif motion_state == MotionState.VACANT:
self._attr_is_on = False
self.schedule_update_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sunricher_dali/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 105,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sunricher_dali/button.py | """Support for Sunricher DALI device identify button."""
from __future__ import annotations
import logging
from PySrDaliGateway import Device
from PySrDaliGateway.helper import is_light_device
from homeassistant.components.button import ButtonDeviceClass, ButtonEntity
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN, MANUFACTURER
from .entity import DaliDeviceEntity
from .types import DaliCenterConfigEntry
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
entry: DaliCenterConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Sunricher DALI button entities from config entry."""
devices = entry.runtime_data.devices
async_add_entities(
DaliCenterIdentifyButton(device)
for device in devices
if is_light_device(device.dev_type)
)
class DaliCenterIdentifyButton(DaliDeviceEntity, ButtonEntity):
"""Representation of a Sunricher DALI device identify button."""
_attr_device_class = ButtonDeviceClass.IDENTIFY
_attr_entity_category = EntityCategory.CONFIG
_attr_name = None
def __init__(self, device: Device) -> None:
"""Initialize the device identify button."""
super().__init__(device)
self._device = device
self._attr_unique_id = f"{device.unique_id}_identify"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.dev_id)},
name=device.name,
manufacturer=MANUFACTURER,
model=device.model,
via_device=(DOMAIN, device.gw_sn),
)
async def async_press(self) -> None:
"""Handle button press to identify device."""
_LOGGER.debug("Identifying device %s", self._device.dev_id)
self._device.identify()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sunricher_dali/button.py",
"license": "Apache License 2.0",
"lines": 48,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sunricher_dali/sensor.py | """Platform for Sunricher DALI sensor entities."""
from __future__ import annotations
import logging
from PySrDaliGateway import CallbackEventType, Device
from PySrDaliGateway.helper import is_illuminance_sensor, is_light_device
from PySrDaliGateway.types import IlluminanceStatus
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorStateClass,
)
from homeassistant.const import LIGHT_LUX, EntityCategory, UnitOfEnergy
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN, MANUFACTURER
from .entity import DaliDeviceEntity
from .types import DaliCenterConfigEntry
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
entry: DaliCenterConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Sunricher DALI sensor entities from config entry."""
devices = entry.runtime_data.devices
entities: list[SensorEntity] = []
for device in devices:
if is_illuminance_sensor(device.dev_type):
entities.append(SunricherDaliIlluminanceSensor(device))
if is_light_device(device.dev_type):
entities.append(SunricherDaliEnergySensor(device))
if entities:
async_add_entities(entities)
class SunricherDaliIlluminanceSensor(DaliDeviceEntity, SensorEntity):
"""Representation of a Sunricher DALI Illuminance Sensor."""
_attr_device_class = SensorDeviceClass.ILLUMINANCE
_attr_state_class = SensorStateClass.MEASUREMENT
_attr_native_unit_of_measurement = LIGHT_LUX
_attr_name = None
def __init__(self, device: Device) -> None:
"""Initialize the illuminance sensor."""
super().__init__(device)
self._device = device
self._illuminance_value: float | None = None
self._sensor_enabled: bool = True
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.dev_id)},
name=device.name,
manufacturer=MANUFACTURER,
model=device.model,
via_device=(DOMAIN, device.gw_sn),
)
@property
def native_value(self) -> float | None:
"""Return the native value, or None if sensor is disabled."""
if not self._sensor_enabled:
return None
return self._illuminance_value
async def async_added_to_hass(self) -> None:
"""Handle entity addition to Home Assistant."""
await super().async_added_to_hass()
self.async_on_remove(
self._device.register_listener(
CallbackEventType.ILLUMINANCE_STATUS, self._handle_illuminance_status
)
)
self.async_on_remove(
self._device.register_listener(
CallbackEventType.SENSOR_ON_OFF, self._handle_sensor_on_off
)
)
self._device.read_status()
@callback
def _handle_illuminance_status(self, status: IlluminanceStatus) -> None:
"""Handle illuminance status updates."""
illuminance_value = status["illuminance_value"]
is_valid = status["is_valid"]
if not is_valid:
_LOGGER.debug(
"Illuminance value is not valid for device %s: %s lux",
self._device.dev_id,
illuminance_value,
)
return
self._illuminance_value = illuminance_value
self.schedule_update_ha_state()
@callback
def _handle_sensor_on_off(self, on_off: bool) -> None:
"""Handle sensor on/off updates."""
self._sensor_enabled = on_off
_LOGGER.debug(
"Illuminance sensor enable state for device %s updated to: %s",
self._device.dev_id,
on_off,
)
self.schedule_update_ha_state()
class SunricherDaliEnergySensor(DaliDeviceEntity, SensorEntity):
"""Representation of a Sunricher DALI Energy Sensor."""
_attr_device_class = SensorDeviceClass.ENERGY
_attr_state_class = SensorStateClass.TOTAL_INCREASING
_attr_native_unit_of_measurement = UnitOfEnergy.WATT_HOUR
_attr_entity_category = EntityCategory.DIAGNOSTIC
_attr_suggested_display_precision = 2
def __init__(self, device: Device) -> None:
"""Initialize the energy sensor."""
super().__init__(device)
self._device = device
self._attr_unique_id = f"{device.unique_id}_energy"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.dev_id)},
name=device.name,
manufacturer=MANUFACTURER,
model=device.model,
via_device=(DOMAIN, device.gw_sn),
)
async def async_added_to_hass(self) -> None:
"""Register energy report listener."""
await super().async_added_to_hass()
self.async_on_remove(
self._device.register_listener(
CallbackEventType.ENERGY_REPORT, self._handle_energy_update
)
)
@callback
def _handle_energy_update(self, energy_value: float) -> None:
"""Update energy value."""
self._attr_native_value = energy_value
self.schedule_update_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sunricher_dali/sensor.py",
"license": "Apache License 2.0",
"lines": 130,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/switch/condition.py | """Provides conditions for switches."""
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers.condition import Condition, make_entity_state_condition
from .const import DOMAIN
CONDITIONS: dict[str, type[Condition]] = {
"is_off": make_entity_state_condition(DOMAIN, STATE_OFF),
"is_on": make_entity_state_condition(DOMAIN, STATE_ON),
}
async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]:
"""Return the switch conditions."""
return CONDITIONS
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/switch/condition.py",
"license": "Apache License 2.0",
"lines": 12,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/tibber/binary_sensor.py | """Support for Tibber binary sensors."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
import logging
import tibber
from tibber.data_api import TibberDevice
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, TibberConfigEntry
from .coordinator import TibberDataAPICoordinator
_LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True, kw_only=True)
class TibberBinarySensorEntityDescription(BinarySensorEntityDescription):
"""Describes Tibber binary sensor entity."""
is_on_fn: Callable[[str], bool | None]
DATA_API_BINARY_SENSORS: tuple[TibberBinarySensorEntityDescription, ...] = (
TibberBinarySensorEntityDescription(
key="connector.status",
device_class=BinarySensorDeviceClass.PLUG,
is_on_fn={"connected": True, "disconnected": False}.get,
),
TibberBinarySensorEntityDescription(
key="charging.status",
device_class=BinarySensorDeviceClass.BATTERY_CHARGING,
is_on_fn={"charging": True, "idle": False}.get,
),
TibberBinarySensorEntityDescription(
key="onOff",
device_class=BinarySensorDeviceClass.POWER,
is_on_fn={"on": True, "off": False}.get,
),
TibberBinarySensorEntityDescription(
key="isOnline",
device_class=BinarySensorDeviceClass.CONNECTIVITY,
is_on_fn=lambda v: v.lower() == "true",
entity_category=EntityCategory.DIAGNOSTIC,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: TibberConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Tibber binary sensors."""
coordinator = entry.runtime_data.data_api_coordinator
assert coordinator is not None
entities: list[TibberDataAPIBinarySensor] = []
api_binary_sensors = {sensor.key: sensor for sensor in DATA_API_BINARY_SENSORS}
for device in coordinator.data.values():
for sensor in device.sensors:
description: TibberBinarySensorEntityDescription | None = (
api_binary_sensors.get(sensor.id)
)
if description is None:
continue
entities.append(TibberDataAPIBinarySensor(coordinator, device, description))
async_add_entities(entities)
class TibberDataAPIBinarySensor(
CoordinatorEntity[TibberDataAPICoordinator], BinarySensorEntity
):
"""Representation of a Tibber Data API binary sensor."""
_attr_has_entity_name = True
entity_description: TibberBinarySensorEntityDescription
def __init__(
self,
coordinator: TibberDataAPICoordinator,
device: TibberDevice,
entity_description: TibberBinarySensorEntityDescription,
) -> None:
"""Initialize the binary sensor."""
super().__init__(coordinator)
self._device_id: str = device.id
self.entity_description = entity_description
self._attr_unique_id = f"{device.id}_{entity_description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.external_id)},
name=device.name,
manufacturer=device.brand,
model=device.model,
)
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
super().available and self._device_id in self.coordinator.sensors_by_device
)
@property
def device(self) -> dict[str, tibber.data_api.Sensor]:
"""Return the device sensors."""
return self.coordinator.sensors_by_device[self._device_id]
@property
def is_on(self) -> bool | None:
"""Return the state of the binary sensor."""
return self.entity_description.is_on_fn(
str(self.device[self.entity_description.key].value)
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/tibber/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 105,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/todoist/util.py | """Utility functions for the Todoist integration."""
from __future__ import annotations
from datetime import date, datetime
from todoist_api_python.models import Due
from homeassistant.util import dt as dt_util
def parse_due_date(task_due: Due | None) -> date | datetime | None:
"""Parse due date from Todoist task due object.
The due.date field contains either a date object (for date-only tasks)
or a datetime object (for tasks with a specific time). When deserialized
from the API via from_dict(), these are already proper Python date/datetime
objects.
Args:
task_due: The Due object from a Todoist task, or None.
Returns:
A date object for date-only due dates, a localized datetime for
datetime due dates, or None if no due date is set.
"""
if task_due is None or not (due_date := task_due.date):
return None
if isinstance(due_date, datetime):
return dt_util.as_local(due_date)
if isinstance(due_date, date):
return due_date
return None
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/todoist/util.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | documentation |
home-assistant/core:homeassistant/components/uhoo/config_flow.py | """Custom uhoo config flow setup."""
from typing import Any
from uhooapi import Client
from uhooapi.errors import UhooError, UnauthorizedError
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_API_KEY
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from homeassistant.helpers.selector import (
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from .const import DOMAIN, LOGGER
USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_API_KEY): TextSelector(
TextSelectorConfig(
type=TextSelectorType.PASSWORD,
autocomplete="current-password",
)
),
}
)
class UhooConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for uHoo."""
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the start of the config flow."""
errors = {}
if user_input is not None:
self._async_abort_entries_match(user_input)
session = async_create_clientsession(self.hass)
client = Client(user_input[CONF_API_KEY], session, debug=True)
try:
await client.login()
except UnauthorizedError:
errors["base"] = "invalid_auth"
except UhooError:
errors["base"] = "cannot_connect"
except Exception: # noqa: BLE001
LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
key_snippet = user_input[CONF_API_KEY][-5:]
return self.async_create_entry(
title=f"uHoo ({key_snippet})", data=user_input
)
return self.async_show_form(
step_id="user",
data_schema=self.add_suggested_values_to_schema(
USER_DATA_SCHEMA, user_input
),
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uhoo/config_flow.py",
"license": "Apache License 2.0",
"lines": 57,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/uhoo/const.py | """Static consts for uhoo integration."""
from datetime import timedelta
import logging
DOMAIN = "uhoo"
PLATFORMS = ["sensor"]
LOGGER = logging.getLogger(__package__)
NAME = "uHoo Integration"
MODEL = "uHoo Indoor Air Monitor"
MANUFACTURER = "uHoo Pte. Ltd."
UPDATE_INTERVAL = timedelta(seconds=300)
API_VIRUS = "virus_index"
API_MOLD = "mold_index"
API_TEMP = "temperature"
API_HUMIDITY = "humidity"
API_PM25 = "pm25"
API_TVOC = "tvoc"
API_CO2 = "co2"
API_CO = "co"
API_PRESSURE = "air_pressure"
API_OZONE = "ozone"
API_NO2 = "no2"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uhoo/const.py",
"license": "Apache License 2.0",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/uhoo/coordinator.py | """Custom uhoo data update coordinator."""
from uhooapi import Client, Device
from uhooapi.errors import UhooError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN, LOGGER, UPDATE_INTERVAL
type UhooConfigEntry = ConfigEntry[UhooDataUpdateCoordinator]
class UhooDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Device]]):
"""Class to manage fetching data from the uHoo API."""
def __init__(
self, hass: HomeAssistant, client: Client, entry: UhooConfigEntry
) -> None:
"""Initialize DataUpdateCoordinator."""
self.client = client
super().__init__(
hass,
LOGGER,
name=DOMAIN,
config_entry=entry,
update_interval=UPDATE_INTERVAL,
)
async def _async_update_data(self) -> dict[str, Device]:
try:
await self.client.login()
if self.client.devices:
for device_id in self.client.devices:
await self.client.get_latest_data(device_id)
except UhooError as error:
raise UpdateFailed(f"The device is unavailable: {error}") from error
else:
return self.client.devices
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uhoo/coordinator.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/uhoo/sensor.py | """Custom uhoo sensors setup."""
from collections.abc import Callable
from dataclasses import dataclass
from uhooapi import Device
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import (
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
CONCENTRATION_PARTS_PER_BILLION,
CONCENTRATION_PARTS_PER_MILLION,
PERCENTAGE,
UnitOfPressure,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import (
API_CO,
API_CO2,
API_HUMIDITY,
API_MOLD,
API_NO2,
API_OZONE,
API_PM25,
API_PRESSURE,
API_TEMP,
API_TVOC,
API_VIRUS,
DOMAIN,
MANUFACTURER,
MODEL,
)
from .coordinator import UhooConfigEntry, UhooDataUpdateCoordinator
PARALLEL_UPDATES = 1
@dataclass(frozen=True, kw_only=True)
class UhooSensorEntityDescription(SensorEntityDescription):
"""Extended SensorEntityDescription with a type-safe value function."""
value_fn: Callable[[Device], float | None]
SENSOR_TYPES: tuple[UhooSensorEntityDescription, ...] = (
UhooSensorEntityDescription(
key=API_CO,
device_class=SensorDeviceClass.CO,
native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.co,
),
UhooSensorEntityDescription(
key=API_CO2,
device_class=SensorDeviceClass.CO2,
native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.co2,
),
UhooSensorEntityDescription(
key=API_PM25,
device_class=SensorDeviceClass.PM25,
native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.pm25,
),
UhooSensorEntityDescription(
key=API_HUMIDITY,
device_class=SensorDeviceClass.HUMIDITY,
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.humidity,
),
UhooSensorEntityDescription(
key=API_TEMP,
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS, # Base unit
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.temperature,
),
UhooSensorEntityDescription(
key=API_PRESSURE,
device_class=SensorDeviceClass.PRESSURE,
native_unit_of_measurement=UnitOfPressure.HPA,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.air_pressure,
),
UhooSensorEntityDescription(
key=API_TVOC,
translation_key="volatile_organic_compounds",
device_class=SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS,
native_unit_of_measurement=CONCENTRATION_PARTS_PER_BILLION,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.tvoc,
),
UhooSensorEntityDescription(
key=API_NO2,
translation_key="nitrogen_dioxide",
native_unit_of_measurement=CONCENTRATION_PARTS_PER_BILLION,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.no2,
),
UhooSensorEntityDescription(
key=API_OZONE,
translation_key="ozone",
native_unit_of_measurement=CONCENTRATION_PARTS_PER_BILLION,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.ozone,
),
UhooSensorEntityDescription(
key=API_VIRUS,
translation_key=API_VIRUS,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.virus_index,
),
UhooSensorEntityDescription(
key=API_MOLD,
translation_key=API_MOLD,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.mold_index,
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: UhooConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Setup sensor platform."""
coordinator = config_entry.runtime_data
async_add_entities(
UhooSensorEntity(description, serial_number, coordinator)
for serial_number in coordinator.data
for description in SENSOR_TYPES
)
class UhooSensorEntity(CoordinatorEntity[UhooDataUpdateCoordinator], SensorEntity):
"""Uhoo Sensor Object with init and methods."""
entity_description: UhooSensorEntityDescription
_attr_has_entity_name = True
def __init__(
self,
description: UhooSensorEntityDescription,
serial_number: str,
coordinator: UhooDataUpdateCoordinator,
) -> None:
"""Initialize Uhoo Sensor."""
super().__init__(coordinator)
self.entity_description = description
self._serial_number = serial_number
self._attr_unique_id = f"{serial_number}_{description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, serial_number)},
name=self.device.device_name,
model=MODEL,
manufacturer=MANUFACTURER,
serial_number=serial_number,
)
@property
def device(self) -> Device:
"""Return the device object for this sensor's serial number."""
return self.coordinator.data[self._serial_number]
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and self._serial_number in self.coordinator.data
@property
def native_value(self) -> StateType:
"""State of the sensor."""
return self.entity_description.value_fn(self.device)
@property
def native_unit_of_measurement(self) -> str | None:
"""Return unit of measurement."""
if self.entity_description.key == API_TEMP:
if self.device.user_settings["temp"] == "f":
return UnitOfTemperature.FAHRENHEIT
return UnitOfTemperature.CELSIUS
return super().native_unit_of_measurement
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uhoo/sensor.py",
"license": "Apache License 2.0",
"lines": 177,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/utility_meter/services.py | """Support for tracking consumption over given periods of time."""
import logging
import voluptuous as vol
from homeassistant.components.select import DOMAIN as SELECT_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall, callback, split_entity_id
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from .const import DOMAIN, SERVICE_RESET, SIGNAL_RESET_METER
_LOGGER = logging.getLogger(__name__)
async def async_reset_meters(service_call: ServiceCall) -> None:
"""Reset all sensors of a meter."""
meters = service_call.data["entity_id"]
for meter in meters:
_LOGGER.debug("resetting meter %s", meter)
domain, entity = split_entity_id(meter)
# backward compatibility up to 2022.07:
if domain == DOMAIN:
async_dispatcher_send(
service_call.hass, SIGNAL_RESET_METER, f"{SELECT_DOMAIN}.{entity}"
)
else:
async_dispatcher_send(service_call.hass, SIGNAL_RESET_METER, meter)
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up the services."""
hass.services.async_register(
DOMAIN,
SERVICE_RESET,
async_reset_meters,
vol.Schema({ATTR_ENTITY_ID: vol.All(cv.ensure_list, [cv.entity_id])}),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/utility_meter/services.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/vacuum/condition.py | """Provides conditions for vacuum cleaners."""
from homeassistant.core import HomeAssistant
from homeassistant.helpers.condition import Condition, make_entity_state_condition
from .const import DOMAIN, VacuumActivity
CONDITIONS: dict[str, type[Condition]] = {
"is_cleaning": make_entity_state_condition(DOMAIN, VacuumActivity.CLEANING),
"is_docked": make_entity_state_condition(DOMAIN, VacuumActivity.DOCKED),
"is_encountering_an_error": make_entity_state_condition(
DOMAIN, VacuumActivity.ERROR
),
"is_paused": make_entity_state_condition(DOMAIN, VacuumActivity.PAUSED),
"is_returning": make_entity_state_condition(DOMAIN, VacuumActivity.RETURNING),
}
async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]:
"""Return the conditions for vacuum cleaners."""
return CONDITIONS
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vacuum/condition.py",
"license": "Apache License 2.0",
"lines": 16,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/vodafone_station/image.py | """Vodafone Station image."""
from __future__ import annotations
from io import BytesIO
from typing import Final, cast
from aiovodafone.const import WIFI_DATA
from homeassistant.components.image import ImageEntity, ImageEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import dt as dt_util
from .const import _LOGGER
from .coordinator import VodafoneConfigEntry, VodafoneStationRouter
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
IMAGE_TYPES: Final = (
ImageEntityDescription(
key="guest",
translation_key="guest",
),
ImageEntityDescription(
key="guest_5g",
translation_key="guest_5g",
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: VodafoneConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Guest WiFi QR code for device."""
_LOGGER.debug("Setting up Vodafone Station images")
coordinator = entry.runtime_data
wifi = coordinator.data.wifi
async_add_entities(
VodafoneGuestWifiQRImage(hass, coordinator, image_desc)
for image_desc in IMAGE_TYPES
if image_desc.key in wifi[WIFI_DATA]
and "qr_code" in wifi[WIFI_DATA][image_desc.key]
)
class VodafoneGuestWifiQRImage(
CoordinatorEntity[VodafoneStationRouter],
ImageEntity,
):
"""Implementation of the Guest wifi QR code image entity."""
_attr_content_type = "image/png"
_attr_entity_category = EntityCategory.DIAGNOSTIC
_attr_has_entity_name = True
def __init__(
self,
hass: HomeAssistant,
coordinator: VodafoneStationRouter,
description: ImageEntityDescription,
) -> None:
"""Initialize QR code image entity."""
super().__init__(coordinator)
ImageEntity.__init__(self, hass)
self.entity_description = description
self._attr_device_info = coordinator.device_info
self._attr_unique_id = f"{coordinator.serial_number}-{description.key}-qr-code"
self._cached_qr_code: bytes | None = None
@property
def _qr_code(self) -> bytes:
"""Return QR code bytes."""
qr_code = cast(
BytesIO,
self.coordinator.data.wifi[WIFI_DATA][self.entity_description.key][
"qr_code"
],
)
return qr_code.getvalue()
async def async_added_to_hass(self) -> None:
"""Set the update time."""
self._attr_image_last_updated = dt_util.utcnow()
await super().async_added_to_hass()
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator.
If the coordinator has updated the QR code, we can update the image.
"""
qr_code = self._qr_code
if self._cached_qr_code != qr_code:
self._cached_qr_code = qr_code
self._attr_image_last_updated = dt_util.utcnow()
super()._handle_coordinator_update()
async def async_image(self) -> bytes | None:
"""Return QR code image."""
return self._qr_code
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vodafone_station/image.py",
"license": "Apache License 2.0",
"lines": 87,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/vodafone_station/switch.py | """Support for switches."""
from __future__ import annotations
from dataclasses import dataclass
from json.decoder import JSONDecodeError
from typing import Any, Final
from aiovodafone.const import WIFI_DATA, WifiBand, WifiType
from aiovodafone.exceptions import (
AlreadyLogged,
CannotAuthenticate,
CannotConnect,
GenericLoginError,
GenericResponseError,
)
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import VodafoneConfigEntry, VodafoneStationRouter
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class VodafoneStationEntityDescription(SwitchEntityDescription):
"""Vodafone Station entity description."""
band: WifiBand
typology: WifiType
SWITCHES: Final = (
VodafoneStationEntityDescription(
key="main",
translation_key="main",
band=WifiBand.BAND_2_4_GHZ,
typology=WifiType.MAIN,
),
VodafoneStationEntityDescription(
key="guest",
translation_key="guest",
band=WifiBand.BAND_2_4_GHZ,
typology=WifiType.GUEST,
),
VodafoneStationEntityDescription(
key="main_5g",
translation_key="main_5g",
band=WifiBand.BAND_5_GHZ,
typology=WifiType.MAIN,
),
VodafoneStationEntityDescription(
key="guest_5g",
translation_key="guest_5g",
band=WifiBand.BAND_5_GHZ,
typology=WifiType.GUEST,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: VodafoneConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Vodafone Station switches based on a config entry."""
coordinator = entry.runtime_data
wifi = coordinator.data.wifi
async_add_entities(
VodafoneSwitchEntity(coordinator, switch_desc)
for switch_desc in SWITCHES
if switch_desc.key in wifi[WIFI_DATA]
)
class VodafoneSwitchEntity(CoordinatorEntity[VodafoneStationRouter], SwitchEntity):
"""Switch device."""
_attr_has_entity_name = True
entity_description: VodafoneStationEntityDescription
def __init__(
self,
coordinator: VodafoneStationRouter,
description: VodafoneStationEntityDescription,
) -> None:
"""Initialize switch device."""
super().__init__(coordinator)
self.entity_description = description
self._attr_device_info = coordinator.device_info
self._attr_unique_id = f"{coordinator.serial_number}_{description.key}"
async def _set_wifi_status(self, status: bool) -> None:
"""Set the wifi status."""
try:
await self.coordinator.api.set_wifi_status(
status, self.entity_description.typology, self.entity_description.band
)
except CannotAuthenticate as err:
self.coordinator.config_entry.async_start_reauth(self.hass)
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="cannot_authenticate",
translation_placeholders={"error": repr(err)},
) from err
except (
CannotConnect,
AlreadyLogged,
GenericLoginError,
GenericResponseError,
JSONDecodeError,
) as err:
self.coordinator.last_update_success = False
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="cannot_execute_action",
translation_placeholders={"error": repr(err)},
) from err
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
await self._set_wifi_status(True)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
await self._set_wifi_status(False)
@property
def is_on(self) -> bool:
"""Return True if switch is on."""
return bool(
self.coordinator.data.wifi[WIFI_DATA][self.entity_description.key]["on"]
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vodafone_station/switch.py",
"license": "Apache License 2.0",
"lines": 117,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/waterfurnace/config_flow.py | """Config flow for WaterFurnace integration."""
from __future__ import annotations
import logging
from typing import Any
import voluptuous as vol
from waterfurnace.waterfurnace import WaterFurnace, WFCredentialError, WFException
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_USERNAME): str,
vol.Required(CONF_PASSWORD): str,
}
)
class WaterFurnaceConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for WaterFurnace."""
VERSION = 1
MINOR_VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
username = user_input[CONF_USERNAME]
password = user_input[CONF_PASSWORD]
client = WaterFurnace(username, password)
try:
# Login is a blocking call, run in executor
await self.hass.async_add_executor_job(client.login)
except WFCredentialError:
errors["base"] = "invalid_auth"
except WFException:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected error connecting to WaterFurnace")
errors["base"] = "unknown"
gwid = client.gwid
if not gwid:
errors["base"] = "cannot_connect"
if not errors:
# Set unique ID based on GWID
await self.async_set_unique_id(gwid)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"WaterFurnace {username}",
data=user_input,
)
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
)
async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
"""Handle import from YAML configuration."""
username = import_data[CONF_USERNAME]
password = import_data[CONF_PASSWORD]
client = WaterFurnace(username, password)
try:
# Login is a blocking call, run in executor
await self.hass.async_add_executor_job(client.login)
except WFCredentialError:
return self.async_abort(reason="invalid_auth")
except WFException:
return self.async_abort(reason="cannot_connect")
except Exception:
_LOGGER.exception("Unexpected error importing WaterFurnace configuration")
return self.async_abort(reason="unknown")
gwid = client.gwid
if not gwid:
# This likely indicates a server-side change, or an implementation bug
return self.async_abort(reason="cannot_connect")
# Set unique ID based on GWID
await self.async_set_unique_id(gwid)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"WaterFurnace {username}",
data=import_data,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/waterfurnace/config_flow.py",
"license": "Apache License 2.0",
"lines": 81,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/waterfurnace/const.py | """Constants for the WaterFurnace integration."""
from datetime import timedelta
from typing import Final
DOMAIN: Final = "waterfurnace"
INTEGRATION_TITLE: Final = "WaterFurnace"
UPDATE_INTERVAL: Final = timedelta(seconds=10)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/waterfurnace/const.py",
"license": "Apache License 2.0",
"lines": 6,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/yardian/sensor.py | """Sensors for Yardian integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory, UnitOfTime
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import dt as dt_util
from .const import DOMAIN
from .coordinator import YardianUpdateCoordinator
# Values above this threshold indicate the API returned an absolute
# timestamp instead of a relative delay, so convert to a remaining delta.
_OPER_INFO_ABSOLUTE_THRESHOLD = 365 * 24 * 3600
@dataclass(kw_only=True, frozen=True)
class YardianSensorEntityDescription(SensorEntityDescription):
"""Entity description for Yardian sensors."""
value_fn: Callable[[YardianUpdateCoordinator], StateType]
def _zone_delay_value(coordinator: YardianUpdateCoordinator) -> StateType:
"""Return zone delay duration in seconds."""
val = coordinator.data.oper_info.get("iSensorDelay")
if not isinstance(val, int):
return None
delay = val
if delay > _OPER_INFO_ABSOLUTE_THRESHOLD:
now = int(dt_util.utcnow().timestamp())
return max(0, delay - now)
return max(0, delay)
SENSOR_DESCRIPTIONS: tuple[YardianSensorEntityDescription, ...] = (
YardianSensorEntityDescription(
key="rain_delay",
translation_key="rain_delay",
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.SECONDS,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda coordinator: coordinator.data.oper_info.get("iRainDelay"),
),
YardianSensorEntityDescription(
key="active_zone_count",
translation_key="active_zone_count",
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda coordinator: len(coordinator.data.active_zones),
),
YardianSensorEntityDescription(
key="zone_delay",
translation_key="zone_delay",
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.SECONDS,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
value_fn=_zone_delay_value,
),
YardianSensorEntityDescription(
key="water_hammer_duration",
translation_key="water_hammer_duration",
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.SECONDS,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
value_fn=lambda coordinator: coordinator.data.oper_info.get(
"iWaterHammerDuration"
),
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Yardian sensors."""
coordinator: YardianUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
async_add_entities(
YardianSensor(coordinator, description) for description in SENSOR_DESCRIPTIONS
)
class YardianSensor(CoordinatorEntity[YardianUpdateCoordinator], SensorEntity):
"""Representation of a Yardian sensor defined by description."""
entity_description: YardianSensorEntityDescription
_attr_has_entity_name = True
def __init__(
self,
coordinator: YardianUpdateCoordinator,
description: YardianSensorEntityDescription,
) -> None:
"""Initialize the Yardian sensor."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.yid}_{description.key}"
self._attr_device_info = coordinator.device_info
@property
def native_value(self) -> StateType:
"""Return the value provided by the description."""
return self.entity_description.value_fn(self.coordinator)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/yardian/sensor.py",
"license": "Apache License 2.0",
"lines": 100,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/airobot/test_button.py | """Tests for the Airobot button platform."""
from unittest.mock import AsyncMock
from pyairobotrest.exceptions import (
AirobotConnectionError,
AirobotError,
AirobotTimeoutError,
)
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.const import ATTR_ENTITY_ID, 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.BUTTON]
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_buttons(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the button entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("init_integration")
async def test_restart_button(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
) -> None:
"""Test restart button."""
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.test_thermostat_restart"},
blocking=True,
)
mock_airobot_client.reboot_thermostat.assert_called_once()
@pytest.mark.usefixtures("init_integration")
async def test_restart_button_error(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
) -> None:
"""Test restart button error handling for unexpected errors."""
mock_airobot_client.reboot_thermostat.side_effect = AirobotError("Test error")
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.test_thermostat_restart"},
blocking=True,
)
mock_airobot_client.reboot_thermostat.assert_called_once()
@pytest.mark.usefixtures("init_integration")
@pytest.mark.parametrize(
"exception",
[AirobotConnectionError("Connection lost"), AirobotTimeoutError("Timeout")],
)
async def test_restart_button_connection_errors(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
exception: Exception,
) -> None:
"""Test restart button handles connection/timeout errors gracefully."""
mock_airobot_client.reboot_thermostat.side_effect = exception
# Should not raise an error - connection errors during reboot are expected
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.test_thermostat_restart"},
blocking=True,
)
mock_airobot_client.reboot_thermostat.assert_called_once()
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_recalibrate_co2_button(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
) -> None:
"""Test recalibrate CO2 sensor button."""
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.test_thermostat_recalibrate_co2_sensor"},
blocking=True,
)
mock_airobot_client.recalibrate_co2_sensor.assert_called_once()
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_recalibrate_co2_button_error(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
) -> None:
"""Test recalibrate CO2 sensor button error handling."""
mock_airobot_client.recalibrate_co2_sensor.side_effect = AirobotError("Test error")
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.test_thermostat_recalibrate_co2_sensor"},
blocking=True,
)
mock_airobot_client.recalibrate_co2_sensor.assert_called_once()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/airobot/test_button.py",
"license": "Apache License 2.0",
"lines": 104,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/airobot/test_switch.py | """Tests for the Airobot switch platform."""
from unittest.mock import AsyncMock
from pyairobotrest.exceptions import AirobotError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.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.SWITCH]
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_switches(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the switch entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
@pytest.mark.parametrize(
("entity_id", "method_name"),
[
("switch.test_thermostat_child_lock", "set_child_lock"),
(
"switch.test_thermostat_actuator_exercise_disabled",
"toggle_actuator_exercise",
),
],
)
async def test_switch_turn_on_off(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
entity_id: str,
method_name: str,
) -> None:
"""Test switch turn on/off functionality."""
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
mock_method = getattr(mock_airobot_client, method_name)
# Turn on
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_method.assert_called_once_with(True)
mock_method.reset_mock()
# Turn off
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_method.assert_called_once_with(False)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_switch_state_updates(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
mock_settings,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that switch state updates when coordinator refreshes."""
# Initial state - both switches off
child_lock = hass.states.get("switch.test_thermostat_child_lock")
assert child_lock is not None
assert child_lock.state == STATE_OFF
actuator_disabled = hass.states.get(
"switch.test_thermostat_actuator_exercise_disabled"
)
assert actuator_disabled is not None
assert actuator_disabled.state == STATE_OFF
# Update settings to enable both
mock_settings.setting_flags.childlock_enabled = True
mock_settings.setting_flags.actuator_exercise_disabled = True
mock_airobot_client.get_settings.return_value = mock_settings
# Trigger coordinator update
await mock_config_entry.runtime_data.async_refresh()
await hass.async_block_till_done()
# Verify states updated
child_lock = hass.states.get("switch.test_thermostat_child_lock")
assert child_lock is not None
assert child_lock.state == STATE_ON
actuator_disabled = hass.states.get(
"switch.test_thermostat_actuator_exercise_disabled"
)
assert actuator_disabled is not None
assert actuator_disabled.state == STATE_ON
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
@pytest.mark.parametrize(
("entity_id", "method_name", "service", "expected_key"),
[
(
"switch.test_thermostat_child_lock",
"set_child_lock",
SERVICE_TURN_ON,
"child_lock",
),
(
"switch.test_thermostat_child_lock",
"set_child_lock",
SERVICE_TURN_OFF,
"child_lock",
),
(
"switch.test_thermostat_actuator_exercise_disabled",
"toggle_actuator_exercise",
SERVICE_TURN_ON,
"actuator_exercise_disabled",
),
(
"switch.test_thermostat_actuator_exercise_disabled",
"toggle_actuator_exercise",
SERVICE_TURN_OFF,
"actuator_exercise_disabled",
),
],
)
async def test_switch_error_handling(
hass: HomeAssistant,
mock_airobot_client: AsyncMock,
entity_id: str,
method_name: str,
service: str,
expected_key: str,
) -> None:
"""Test switch error handling for turn on/off operations."""
mock_method = getattr(mock_airobot_client, method_name)
mock_method.side_effect = AirobotError("Test error")
with pytest.raises(HomeAssistantError, match=expected_key):
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
expected_value = service == SERVICE_TURN_ON
mock_method.assert_called_once_with(expected_value)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/airobot/test_switch.py",
"license": "Apache License 2.0",
"lines": 153,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/alarm_control_panel/test_condition.py | """Test alarm_control_panel conditions."""
from typing import Any
import pytest
from homeassistant.components.alarm_control_panel import (
AlarmControlPanelEntityFeature,
AlarmControlPanelState,
)
from homeassistant.const import ATTR_SUPPORTED_FEATURES
from homeassistant.core import HomeAssistant
from tests.components import (
ConditionStateDescription,
assert_condition_gated_by_labs_flag,
create_target_condition,
other_states,
parametrize_condition_states_all,
parametrize_condition_states_any,
parametrize_target_entities,
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(
"condition",
[
"alarm_control_panel.is_armed",
"alarm_control_panel.is_armed_away",
"alarm_control_panel.is_armed_home",
"alarm_control_panel.is_armed_night",
"alarm_control_panel.is_armed_vacation",
"alarm_control_panel.is_disarmed",
"alarm_control_panel.is_triggered",
],
)
async def test_alarm_control_panel_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the alarm_control_panel 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("alarm_control_panel"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="alarm_control_panel.is_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_condition_states_any(
condition="alarm_control_panel.is_armed_away",
target_states=[AlarmControlPanelState.ARMED_AWAY],
other_states=other_states(AlarmControlPanelState.ARMED_AWAY),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_AWAY
},
),
*parametrize_condition_states_any(
condition="alarm_control_panel.is_armed_home",
target_states=[AlarmControlPanelState.ARMED_HOME],
other_states=other_states(AlarmControlPanelState.ARMED_HOME),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_HOME
},
),
*parametrize_condition_states_any(
condition="alarm_control_panel.is_armed_night",
target_states=[AlarmControlPanelState.ARMED_NIGHT],
other_states=other_states(AlarmControlPanelState.ARMED_NIGHT),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_NIGHT
},
),
*parametrize_condition_states_any(
condition="alarm_control_panel.is_armed_vacation",
target_states=[AlarmControlPanelState.ARMED_VACATION],
other_states=other_states(AlarmControlPanelState.ARMED_VACATION),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_VACATION
},
),
*parametrize_condition_states_any(
condition="alarm_control_panel.is_disarmed",
target_states=[AlarmControlPanelState.DISARMED],
other_states=other_states(AlarmControlPanelState.DISARMED),
),
*parametrize_condition_states_any(
condition="alarm_control_panel.is_triggered",
target_states=[AlarmControlPanelState.TRIGGERED],
other_states=other_states(AlarmControlPanelState.TRIGGERED),
),
],
)
async def test_alarm_control_panel_state_condition_behavior_any(
hass: HomeAssistant,
target_alarm_control_panels: 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 alarm_control_panel state condition with the 'any' behavior."""
other_entity_ids = set(target_alarm_control_panels) - {entity_id}
# Set all alarm_control_panels, including the tested alarm_control_panel, 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()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
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 alarm_control_panels 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("alarm_control_panel"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="alarm_control_panel.is_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_condition_states_all(
condition="alarm_control_panel.is_armed_away",
target_states=[AlarmControlPanelState.ARMED_AWAY],
other_states=other_states(AlarmControlPanelState.ARMED_AWAY),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_AWAY
},
),
*parametrize_condition_states_all(
condition="alarm_control_panel.is_armed_home",
target_states=[AlarmControlPanelState.ARMED_HOME],
other_states=other_states(AlarmControlPanelState.ARMED_HOME),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_HOME
},
),
*parametrize_condition_states_all(
condition="alarm_control_panel.is_armed_night",
target_states=[AlarmControlPanelState.ARMED_NIGHT],
other_states=other_states(AlarmControlPanelState.ARMED_NIGHT),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_NIGHT
},
),
*parametrize_condition_states_all(
condition="alarm_control_panel.is_armed_vacation",
target_states=[AlarmControlPanelState.ARMED_VACATION],
other_states=other_states(AlarmControlPanelState.ARMED_VACATION),
additional_attributes={
ATTR_SUPPORTED_FEATURES: AlarmControlPanelEntityFeature.ARM_VACATION
},
),
*parametrize_condition_states_all(
condition="alarm_control_panel.is_disarmed",
target_states=[AlarmControlPanelState.DISARMED],
other_states=other_states(AlarmControlPanelState.DISARMED),
),
*parametrize_condition_states_all(
condition="alarm_control_panel.is_triggered",
target_states=[AlarmControlPanelState.TRIGGERED],
other_states=other_states(AlarmControlPanelState.TRIGGERED),
),
],
)
async def test_alarm_control_panel_state_condition_behavior_all(
hass: HomeAssistant,
target_alarm_control_panels: 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 alarm_control_panel state condition with the 'all' behavior."""
other_entity_ids = set(target_alarm_control_panels) - {entity_id}
# Set all alarm_control_panels, including the tested alarm_control_panel, 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()
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/alarm_control_panel/test_condition.py",
"license": "Apache License 2.0",
"lines": 242,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/anthropic/test_repairs.py | """Tests for the Anthropic repairs flow."""
from __future__ import annotations
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
from homeassistant.components.anthropic.const import CONF_CHAT_MODEL, DOMAIN
from homeassistant.config_entries import ConfigEntryState, ConfigSubentry
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import issue_registry as ir
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
from tests.components.repairs import (
async_process_repairs_platforms,
process_repair_fix_flow,
start_repair_fix_flow,
)
from tests.typing import ClientSessionGenerator
def _make_entry(
hass: HomeAssistant,
*,
title: str,
api_key: str,
subentries_data: list[dict[str, Any]],
) -> MockConfigEntry:
"""Create a config entry with subentries and runtime data."""
entry = MockConfigEntry(
domain=DOMAIN,
title=title,
data={"api_key": api_key},
version=2,
subentries_data=subentries_data,
)
entry.add_to_hass(hass)
object.__setattr__(entry, "state", ConfigEntryState.LOADED)
entry.runtime_data = MagicMock()
return entry
def _get_subentry(
entry: MockConfigEntry,
subentry_type: str,
) -> ConfigSubentry:
"""Return the first subentry of a type."""
return next(
subentry
for subentry in entry.subentries.values()
if subentry.subentry_type == subentry_type
)
async def _setup_repairs(hass: HomeAssistant) -> None:
hass.config.components.add(DOMAIN)
assert await async_setup_component(hass, "repairs", {})
await async_process_repairs_platforms(hass)
async def test_repair_flow_iterates_subentries(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test the repair flow iterates across deprecated subentries."""
entry_one: MockConfigEntry = _make_entry(
hass,
title="Entry One",
api_key="key-one",
subentries_data=[
{
"data": {CONF_CHAT_MODEL: "claude-3-5-haiku-20241022"},
"subentry_type": "conversation",
"title": "Conversation One",
"unique_id": None,
},
{
"data": {CONF_CHAT_MODEL: "claude-3-5-sonnet-20241022"},
"subentry_type": "ai_task_data",
"title": "AI task One",
"unique_id": None,
},
],
)
entry_two: MockConfigEntry = _make_entry(
hass,
title="Entry Two",
api_key="key-two",
subentries_data=[
{
"data": {CONF_CHAT_MODEL: "claude-3-opus-20240229"},
"subentry_type": "conversation",
"title": "Conversation Two",
"unique_id": None,
},
],
)
ir.async_create_issue(
hass,
DOMAIN,
"model_deprecated",
is_fixable=True,
is_persistent=False,
severity=ir.IssueSeverity.WARNING,
translation_key="model_deprecated",
)
await _setup_repairs(hass)
client = await hass_client()
model_options: list[dict[str, str]] = [
{"label": "Claude Haiku 4.5", "value": "claude-haiku-4-5"},
{"label": "Claude Sonnet 4.6", "value": "claude-sonnet-4-6"},
{"label": "Claude Opus 4.6", "value": "claude-opus-4-6"},
]
with patch(
"homeassistant.components.anthropic.repairs.get_model_list",
new_callable=AsyncMock,
return_value=model_options,
):
result = await start_repair_fix_flow(client, DOMAIN, "model_deprecated")
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "init"
placeholders = result["description_placeholders"]
assert placeholders["entry_name"] == entry_one.title
assert placeholders["subentry_name"] == "Conversation One"
assert placeholders["subentry_type"] == "Conversation agent"
flow_id = result["flow_id"]
result = await process_repair_fix_flow(
client,
flow_id,
json={CONF_CHAT_MODEL: "claude-haiku-4-5"},
)
assert result["type"] == FlowResultType.FORM
assert (
_get_subentry(entry_one, "conversation").data[CONF_CHAT_MODEL]
== "claude-haiku-4-5"
)
placeholders = result["description_placeholders"]
assert placeholders["entry_name"] == entry_one.title
assert placeholders["subentry_name"] == "AI task One"
assert placeholders["subentry_type"] == "AI task"
result = await process_repair_fix_flow(
client,
flow_id,
json={CONF_CHAT_MODEL: "claude-sonnet-4-6"},
)
assert result["type"] == FlowResultType.FORM
assert (
_get_subentry(entry_one, "ai_task_data").data[CONF_CHAT_MODEL]
== "claude-sonnet-4-6"
)
assert (
_get_subentry(entry_one, "conversation").data[CONF_CHAT_MODEL]
== "claude-haiku-4-5"
)
placeholders = result["description_placeholders"]
assert placeholders["entry_name"] == entry_two.title
assert placeholders["subentry_name"] == "Conversation Two"
assert placeholders["subentry_type"] == "Conversation agent"
result = await process_repair_fix_flow(
client,
flow_id,
json={CONF_CHAT_MODEL: "claude-opus-4-6"},
)
assert result["type"] == FlowResultType.CREATE_ENTRY
assert (
_get_subentry(entry_two, "conversation").data[CONF_CHAT_MODEL]
== "claude-opus-4-6"
)
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is None
async def test_repair_flow_no_deprecated_models(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test the repair flow completes when everything was fixed."""
_make_entry(
hass,
title="Entry One",
api_key="key-one",
subentries_data=[
{
"data": {CONF_CHAT_MODEL: "claude-sonnet-4-5"},
"subentry_type": "conversation",
"title": "Conversation One",
"unique_id": None,
}
],
)
ir.async_create_issue(
hass,
DOMAIN,
"model_deprecated",
is_fixable=True,
is_persistent=False,
severity=ir.IssueSeverity.WARNING,
translation_key="model_deprecated",
)
await _setup_repairs(hass)
client = await hass_client()
result = await start_repair_fix_flow(client, DOMAIN, "model_deprecated")
assert result["type"] == FlowResultType.CREATE_ENTRY
assert issue_registry.async_get_issue(DOMAIN, "model_deprecated") is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/anthropic/test_repairs.py",
"license": "Apache License 2.0",
"lines": 193,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/assist_satellite/test_condition.py | """Test assist satellite conditions."""
from typing import Any
import pytest
from homeassistant.components.assist_satellite.entity import AssistSatelliteState
from homeassistant.core import HomeAssistant
from tests.components import (
ConditionStateDescription,
assert_condition_gated_by_labs_flag,
create_target_condition,
other_states,
parametrize_condition_states_all,
parametrize_condition_states_any,
parametrize_target_entities,
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(
"condition",
[
"assist_satellite.is_idle",
"assist_satellite.is_listening",
"assist_satellite.is_processing",
"assist_satellite.is_responding",
],
)
async def test_assist_satellite_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the assist satellite 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("assist_satellite"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="assist_satellite.is_idle",
target_states=[AssistSatelliteState.IDLE],
other_states=other_states(AssistSatelliteState.IDLE),
),
*parametrize_condition_states_any(
condition="assist_satellite.is_listening",
target_states=[AssistSatelliteState.LISTENING],
other_states=other_states(AssistSatelliteState.LISTENING),
),
*parametrize_condition_states_any(
condition="assist_satellite.is_processing",
target_states=[AssistSatelliteState.PROCESSING],
other_states=other_states(AssistSatelliteState.PROCESSING),
),
*parametrize_condition_states_any(
condition="assist_satellite.is_responding",
target_states=[AssistSatelliteState.RESPONDING],
other_states=other_states(AssistSatelliteState.RESPONDING),
),
],
)
async def test_assist_satellite_state_condition_behavior_any(
hass: HomeAssistant,
target_assist_satellites: 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 assist satellite state condition with the 'any' behavior."""
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()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
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 assist satellites 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("assist_satellite"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="assist_satellite.is_idle",
target_states=[AssistSatelliteState.IDLE],
other_states=other_states(AssistSatelliteState.IDLE),
),
*parametrize_condition_states_all(
condition="assist_satellite.is_listening",
target_states=[AssistSatelliteState.LISTENING],
other_states=other_states(AssistSatelliteState.LISTENING),
),
*parametrize_condition_states_all(
condition="assist_satellite.is_processing",
target_states=[AssistSatelliteState.PROCESSING],
other_states=other_states(AssistSatelliteState.PROCESSING),
),
*parametrize_condition_states_all(
condition="assist_satellite.is_responding",
target_states=[AssistSatelliteState.RESPONDING],
other_states=other_states(AssistSatelliteState.RESPONDING),
),
],
)
async def test_assist_satellite_state_condition_behavior_all(
hass: HomeAssistant,
target_assist_satellites: 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 assist satellite state condition with the 'all' behavior."""
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()
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/assist_satellite/test_condition.py",
"license": "Apache License 2.0",
"lines": 157,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/bang_olufsen/test_binary_sensor.py | """Test the bang_olufsen binary sensor entities."""
from unittest.mock import AsyncMock
from mozart_api.models import BatteryState
from homeassistant.const import STATE_OFF, STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import EntityRegistry
from .conftest import mock_websocket_connection
from .const import TEST_BATTERY, TEST_BATTERY_CHARGING_BINARY_SENSOR_ENTITY_ID
from tests.common import MockConfigEntry
async def test_battery_charging(
hass: HomeAssistant,
entity_registry: EntityRegistry,
mock_mozart_client: AsyncMock,
mock_config_entry_a5: MockConfigEntry,
) -> None:
"""Test the battery charging time entity."""
# Ensure battery entities are created
mock_mozart_client.get_battery_state.return_value = TEST_BATTERY
# Load entry
mock_config_entry_a5.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry_a5.entry_id)
await mock_websocket_connection(hass, mock_mozart_client)
await hass.async_block_till_done()
# Initial state is False
assert (states := hass.states.get(TEST_BATTERY_CHARGING_BINARY_SENSOR_ENTITY_ID))
assert states.state == STATE_OFF
# Check binary sensor reacts as expected to WebSocket events
battery_callback = mock_mozart_client.get_battery_notifications.call_args[0][0]
battery_callback(BatteryState(is_charging=True))
await hass.async_block_till_done()
assert (states := hass.states.get(TEST_BATTERY_CHARGING_BINARY_SENSOR_ENTITY_ID))
assert states.state == STATE_ON
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/bang_olufsen/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/bang_olufsen/test_sensor.py | """Test the bang_olufsen sensor entities."""
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
from mozart_api.models import PairedRemote, PairedRemoteResponse
from homeassistant.components.bang_olufsen.sensor import SCAN_INTERVAL
from homeassistant.const import STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from .conftest import mock_websocket_connection
from .const import (
TEST_BATTERY,
TEST_BATTERY_SENSOR_ENTITY_ID,
TEST_REMOTE_BATTERY_LEVEL_SENSOR_ENTITY_ID,
TEST_REMOTE_SERIAL,
)
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_battery_level(
hass: HomeAssistant,
mock_mozart_client: AsyncMock,
mock_config_entry_a5: MockConfigEntry,
) -> None:
"""Test the battery level entity."""
# Ensure battery entities are created
mock_mozart_client.get_battery_state.return_value = TEST_BATTERY
# Load entry
mock_config_entry_a5.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry_a5.entry_id)
# Deliberately avoid triggering a battery notification
assert (states := hass.states.get(TEST_BATTERY_SENSOR_ENTITY_ID))
assert states.state is STATE_UNKNOWN
# Check sensor reacts as expected to WebSocket events
await mock_websocket_connection(hass, mock_mozart_client)
assert (states := hass.states.get(TEST_BATTERY_SENSOR_ENTITY_ID))
assert states.state == str(TEST_BATTERY.battery_level)
async def test_remote_battery_level(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
integration: None,
mock_config_entry: MockConfigEntry,
mock_mozart_client: AsyncMock,
) -> None:
"""Test the remote battery level entity."""
# Check the default value is set
assert (states := hass.states.get(TEST_REMOTE_BATTERY_LEVEL_SENSOR_ENTITY_ID))
assert states.state == "50"
# Change battery level
mock_mozart_client.get_bluetooth_remotes.return_value = PairedRemoteResponse(
items=[
PairedRemote(
address="",
app_version="1.0.0",
battery_level=45,
connected=True,
serial_number=TEST_REMOTE_SERIAL,
name="BEORC",
)
]
)
# Trigger poll update
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (states := hass.states.get(TEST_REMOTE_BATTERY_LEVEL_SENSOR_ENTITY_ID))
assert states.state == "45"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/bang_olufsen/test_sensor.py",
"license": "Apache License 2.0",
"lines": 63,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/climate/test_condition.py | """Test climate conditions."""
from typing import Any
import pytest
from homeassistant.components.climate.const import (
ATTR_HVAC_ACTION,
HVACAction,
HVACMode,
)
from homeassistant.core import HomeAssistant
from tests.components import (
ConditionStateDescription,
assert_condition_gated_by_labs_flag,
create_target_condition,
other_states,
parametrize_condition_states_all,
parametrize_condition_states_any,
parametrize_target_entities,
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(
"condition",
[
"climate.is_off",
"climate.is_on",
"climate.is_cooling",
"climate.is_drying",
"climate.is_heating",
],
)
async def test_climate_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the climate 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("climate"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="climate.is_off",
target_states=[HVACMode.OFF],
other_states=other_states(HVACMode.OFF),
),
*parametrize_condition_states_any(
condition="climate.is_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_condition_behavior_any(
hass: HomeAssistant,
target_climates: 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 climate state condition with the 'any' behavior."""
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()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
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 climates 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("climate"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="climate.is_off",
target_states=[HVACMode.OFF],
other_states=other_states(HVACMode.OFF),
),
*parametrize_condition_states_all(
condition="climate.is_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_condition_behavior_all(
hass: HomeAssistant,
target_climates: 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 climate state condition with the 'all' behavior."""
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()
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"]
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("condition_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("climate"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="climate.is_cooling",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.COOLING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_condition_states_any(
condition="climate.is_drying",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.DRYING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_condition_states_any(
condition="climate.is_heating",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.HEATING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
],
)
async def test_climate_attribute_condition_behavior_any(
hass: HomeAssistant,
target_climates: 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 climate attribute condition with the 'any' behavior."""
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()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
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 climates 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("climate"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="climate.is_cooling",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.COOLING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_condition_states_all(
condition="climate.is_drying",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.DRYING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
*parametrize_condition_states_all(
condition="climate.is_heating",
target_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.HEATING})],
other_states=[(HVACMode.AUTO, {ATTR_HVAC_ACTION: HVACAction.IDLE})],
),
],
)
async def test_climate_attribute_condition_behavior_all(
hass: HomeAssistant,
target_climates: 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 climate attribute condition with the 'all' behavior."""
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()
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/climate/test_condition.py",
"license": "Apache License 2.0",
"lines": 269,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/cloudflare_r2/const.py | """Consts for Cloudflare R2 tests."""
from homeassistant.components.cloudflare_r2.const import (
CONF_ACCESS_KEY_ID,
CONF_BUCKET,
CONF_ENDPOINT_URL,
CONF_SECRET_ACCESS_KEY,
)
USER_INPUT = {
CONF_ACCESS_KEY_ID: "R2AccessKeyIdExample",
CONF_SECRET_ACCESS_KEY: "R2SecretAccessKeyExampleExample",
CONF_ENDPOINT_URL: "https://1234567890abcdef.r2.cloudflarestorage.com",
CONF_BUCKET: "test",
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/cloudflare_r2/const.py",
"license": "Apache License 2.0",
"lines": 13,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/cloudflare_r2/test_backup.py | """Test the Cloudflare R2 backup platform."""
from collections.abc import AsyncGenerator, AsyncIterator
from io import StringIO
import json
from time import time
from unittest.mock import AsyncMock, Mock, patch
from botocore.exceptions import BotoCoreError, ConnectTimeoutError
import pytest
from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN, AgentBackup
from homeassistant.components.cloudflare_r2.backup import (
MULTIPART_MIN_PART_SIZE_BYTES,
R2BackupAgent,
async_register_backup_agents_listener,
suggested_filenames,
)
from homeassistant.components.cloudflare_r2.const import (
CONF_ENDPOINT_URL,
DATA_BACKUP_AGENT_LISTENERS,
DOMAIN,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import setup_integration
from .const import USER_INPUT
from tests.common import MockConfigEntry
from tests.typing import ClientSessionGenerator, MagicMock, WebSocketGenerator
@pytest.fixture(autouse=True)
async def setup_backup_integration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> AsyncGenerator[None]:
"""Set up R2 integration."""
with (
patch("homeassistant.components.backup.is_hassio", return_value=False),
patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0),
):
assert await async_setup_component(hass, BACKUP_DOMAIN, {})
await setup_integration(hass, mock_config_entry)
await hass.async_block_till_done()
yield
async def test_suggested_filenames() -> None:
"""Test the suggested_filenames function."""
backup = AgentBackup(
backup_id="a1b2c3",
date="2021-01-01T01:02:03+00:00",
addons=[],
database_included=False,
extra_metadata={},
folders=[],
homeassistant_included=False,
homeassistant_version=None,
name="my_pretty_backup",
protected=False,
size=0,
)
tar_filename, metadata_filename = suggested_filenames(backup)
assert tar_filename == "my_pretty_backup_2021-01-01_01.02_03000000.tar"
assert (
metadata_filename == "my_pretty_backup_2021-01-01_01.02_03000000.metadata.json"
)
async def test_agents_info(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test backup agent info."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/agents/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
"agents": [
{"agent_id": "backup.local", "name": "local"},
{
"agent_id": f"{DOMAIN}.{mock_config_entry.entry_id}",
"name": mock_config_entry.title,
},
],
}
async def test_agents_list_backups(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test agent list backups."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backups"] == [
{
"addons": test_backup.addons,
"agents": {
f"{DOMAIN}.{mock_config_entry.entry_id}": {
"protected": test_backup.protected,
"size": test_backup.size,
}
},
"backup_id": test_backup.backup_id,
"database_included": test_backup.database_included,
"date": test_backup.date,
"extra_metadata": test_backup.extra_metadata,
"failed_addons": [],
"failed_agent_ids": [],
"failed_folders": [],
"folders": test_backup.folders,
"homeassistant_included": test_backup.homeassistant_included,
"homeassistant_version": test_backup.homeassistant_version,
"name": test_backup.name,
"with_automatic_settings": None,
}
]
async def test_agents_get_backup(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test agent get backup."""
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "backup/details", "backup_id": test_backup.backup_id}
)
response = await client.receive_json()
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backup"] == {
"addons": test_backup.addons,
"agents": {
f"{DOMAIN}.{mock_config_entry.entry_id}": {
"protected": test_backup.protected,
"size": test_backup.size,
}
},
"backup_id": test_backup.backup_id,
"database_included": test_backup.database_included,
"date": test_backup.date,
"extra_metadata": test_backup.extra_metadata,
"failed_addons": [],
"failed_agent_ids": [],
"failed_folders": [],
"folders": test_backup.folders,
"homeassistant_included": test_backup.homeassistant_included,
"homeassistant_version": test_backup.homeassistant_version,
"name": test_backup.name,
"with_automatic_settings": None,
}
async def test_agents_get_backup_does_not_throw_on_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_client: MagicMock,
) -> None:
"""Test agent get backup does not throw on a backup not found."""
mock_client.list_objects_v2.return_value = {"Contents": []}
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/details", "backup_id": "random"})
response = await client.receive_json()
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backup"] is None
async def test_agents_list_backups_with_corrupted_metadata(
hass: HomeAssistant,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
test_backup: AgentBackup,
) -> None:
"""Test listing backups when one metadata file is corrupted."""
# Create agent
agent = R2BackupAgent(hass, mock_config_entry)
# Set up mock responses for both valid and corrupted metadata files
mock_client.list_objects_v2.return_value = {
"Contents": [
{
"Key": "valid_backup.metadata.json",
"LastModified": "2023-01-01T00:00:00+00:00",
},
{
"Key": "corrupted_backup.metadata.json",
"LastModified": "2023-01-01T00:00:00+00:00",
},
]
}
# Mock responses for get_object calls
valid_metadata = json.dumps(test_backup.as_dict())
corrupted_metadata = "{invalid json content"
async def mock_get_object(**kwargs):
"""Mock get_object with different responses based on the key."""
key = kwargs.get("Key", "")
if "valid_backup" in key:
mock_body = AsyncMock()
mock_body.read.return_value = valid_metadata.encode()
return {"Body": mock_body}
# Corrupted metadata
mock_body = AsyncMock()
mock_body.read.return_value = corrupted_metadata.encode()
return {"Body": mock_body}
mock_client.get_object.side_effect = mock_get_object
backups = await agent.async_list_backups()
assert len(backups) == 1
assert backups[0].backup_id == test_backup.backup_id
assert "Failed to process metadata file" in caplog.text
async def test_agents_delete(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_client: MagicMock,
) -> None:
"""Test agent delete backup."""
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": "23e64aec",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {"agent_errors": {}}
# Should delete both the tar and the metadata file
assert mock_client.delete_object.call_count == 2
async def test_agents_delete_not_throwing_on_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_client: MagicMock,
) -> None:
"""Test agent delete backup does not throw on a backup not found."""
mock_client.list_objects_v2.return_value = {"Contents": []}
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": "random",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {"agent_errors": {}}
assert mock_client.delete_object.call_count == 0
async def test_agents_upload(
hass_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test agent upload backup."""
client = await hass_client()
with (
patch(
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
return_value=test_backup,
),
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=test_backup,
),
patch("pathlib.Path.open") as mocked_open,
):
# we must emit at least two chunks
# the "appendix" chunk triggers the upload of the final buffer part
mocked_open.return_value.read = Mock(
side_effect=[
b"a" * test_backup.size,
b"appendix",
b"",
]
)
resp = await client.post(
f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.entry_id}",
data={"file": StringIO("test")},
)
assert resp.status == 201
assert f"Uploading backup {test_backup.backup_id}" in caplog.text
if test_backup.size < MULTIPART_MIN_PART_SIZE_BYTES:
# single part + metadata both as regular upload (no multiparts)
assert mock_client.create_multipart_upload.await_count == 0
assert mock_client.put_object.await_count == 2
else:
assert "Uploading final part" in caplog.text
# 2 parts as multipart + metadata as regular upload
assert mock_client.create_multipart_upload.await_count == 1
assert mock_client.upload_part.await_count == 2
assert mock_client.complete_multipart_upload.await_count == 1
assert mock_client.put_object.await_count == 1
async def test_agents_upload_network_failure(
hass_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test agent upload backup with network failure."""
client = await hass_client()
with (
patch(
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
return_value=test_backup,
),
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=test_backup,
),
patch("pathlib.Path.open") as mocked_open,
):
mocked_open.return_value.read = Mock(side_effect=[b"test", b""])
# simulate network failure
mock_client.put_object.side_effect = mock_client.upload_part.side_effect = (
mock_client.abort_multipart_upload.side_effect
) = ConnectTimeoutError(endpoint_url=USER_INPUT[CONF_ENDPOINT_URL])
resp = await client.post(
f"/api/backup/upload?agent_id={DOMAIN}.{mock_config_entry.entry_id}",
data={"file": StringIO("test")},
)
assert resp.status == 201
assert "Upload failed for cloudflare_r2" in caplog.text
async def test_multipart_upload_consistent_part_sizes(
hass: HomeAssistant,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that multipart upload uses consistent part sizes.
S3/R2 requires all non-trailing parts to have the same size. This test
verifies that varying chunk sizes still result in consistent part sizes.
"""
agent = R2BackupAgent(hass, mock_config_entry)
# simulate varying chunk data sizes
# total data: 12 + 12 + 10 + 12 + 5 = 51 MiB
chunk_sizes = [12, 12, 10, 12, 5] # in units of 1 MiB
mib = 2**20
async def mock_stream():
for size in chunk_sizes:
yield b"x" * (size * mib)
async def open_stream():
return mock_stream()
# Record the sizes of each uploaded part
uploaded_part_sizes: list[int] = []
async def record_upload_part(**kwargs):
body = kwargs.get("Body", b"")
uploaded_part_sizes.append(len(body))
return {"ETag": f"etag-{len(uploaded_part_sizes)}"}
mock_client.upload_part.side_effect = record_upload_part
await agent._upload_multipart("test.tar", open_stream)
# Verify that all non-trailing parts have the same size
assert len(uploaded_part_sizes) >= 2, "Expected at least 2 parts"
non_trailing_parts = uploaded_part_sizes[:-1]
assert all(size == MULTIPART_MIN_PART_SIZE_BYTES for size in non_trailing_parts), (
f"All non-trailing parts should be {MULTIPART_MIN_PART_SIZE_BYTES} bytes, got {non_trailing_parts}"
)
# Verify the trailing part contains the remainder
total_data = sum(chunk_sizes) * mib
expected_trailing = total_data % MULTIPART_MIN_PART_SIZE_BYTES
if expected_trailing == 0:
expected_trailing = MULTIPART_MIN_PART_SIZE_BYTES
assert uploaded_part_sizes[-1] == expected_trailing
async def test_agents_download(
hass_client: ClientSessionGenerator,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test agent download backup."""
client = await hass_client()
backup_id = "23e64aec"
resp = await client.get(
f"/api/backup/download/{backup_id}?agent_id={DOMAIN}.{mock_config_entry.entry_id}"
)
assert resp.status == 200
assert await resp.content.read() == b"backup data"
assert mock_client.get_object.call_count == 2 # One for metadata, one for tar file
async def test_error_during_delete(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_client: MagicMock,
mock_config_entry: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test the error wrapper."""
mock_client.delete_object.side_effect = BotoCoreError
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": test_backup.backup_id,
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
"agent_errors": {
f"{DOMAIN}.{mock_config_entry.entry_id}": "Failed during async_delete_backup"
}
}
async def test_cache_expiration(
hass: HomeAssistant,
mock_client: MagicMock,
test_backup: AgentBackup,
) -> None:
"""Test that the cache expires correctly."""
# Mock the entry
mock_entry = MockConfigEntry(
domain=DOMAIN,
data={"bucket": "test-bucket"},
unique_id="test-unique-id",
title="Test R2",
)
mock_entry.runtime_data = mock_client
# Create agent
agent = R2BackupAgent(hass, mock_entry)
# Mock metadata response
metadata_content = json.dumps(test_backup.as_dict())
mock_body = AsyncMock()
mock_body.read.return_value = metadata_content.encode()
mock_client.list_objects_v2.return_value = {
"Contents": [
{"Key": "test.metadata.json", "LastModified": "2023-01-01T00:00:00+00:00"}
]
}
# First call should query R2 (S3 API)
await agent.async_list_backups()
assert mock_client.list_objects_v2.call_count == 1
assert mock_client.get_object.call_count == 1
# Second call should use cache
await agent.async_list_backups()
assert mock_client.list_objects_v2.call_count == 1
assert mock_client.get_object.call_count == 1
# Set cache to expire
agent._cache_expiration = time() - 1
# Third call should query again
await agent.async_list_backups()
assert mock_client.list_objects_v2.call_count == 2
assert mock_client.get_object.call_count == 2
async def test_listeners_get_cleaned_up(hass: HomeAssistant) -> None:
"""Test listener gets cleaned up."""
listener = MagicMock()
remove_listener = async_register_backup_agents_listener(hass, listener=listener)
hass.data[DATA_BACKUP_AGENT_LISTENERS] = [
listener
] # make sure it's the last listener
remove_listener()
assert DATA_BACKUP_AGENT_LISTENERS not in hass.data
async def test_multipart_upload_uses_prefix_for_all_calls(
hass: HomeAssistant,
mock_client: MagicMock,
mock_config_entry_with_prefix: MockConfigEntry,
) -> None:
"""Test multipart upload uses the configured prefix for all S3 calls."""
mock_config_entry_with_prefix.runtime_data = mock_client
agent = R2BackupAgent(hass, mock_config_entry_with_prefix)
async def stream() -> AsyncIterator[bytes]:
# Force multipart: > MIN_PART_SIZE
yield b"x" * (MULTIPART_MIN_PART_SIZE_BYTES + 1)
async def open_stream():
return stream()
await agent._upload_multipart("test.tar", open_stream)
prefixed_key = "ha/backups/test.tar"
assert mock_client.create_multipart_upload.await_args.kwargs["Key"] == prefixed_key
for call in mock_client.upload_part.await_args_list:
assert call.kwargs["Key"] == prefixed_key
assert (
mock_client.complete_multipart_upload.await_args.kwargs["Key"] == prefixed_key
)
async def test_list_backups_passes_prefix_to_list_objects(
hass: HomeAssistant,
mock_client: MagicMock,
mock_config_entry_with_prefix: MockConfigEntry,
test_backup: AgentBackup,
) -> None:
"""Test list_objects_v2 is called with Prefix when configured."""
mock_config_entry_with_prefix.runtime_data = mock_client
agent = R2BackupAgent(hass, mock_config_entry_with_prefix)
# Make the listing for a prefixed bucket
tar_filename, metadata_filename = suggested_filenames(test_backup)
mock_client.list_objects_v2.return_value = {
"Contents": [
{"Key": f"ha/backups/{metadata_filename}"},
{"Key": f"ha/backups/{tar_filename}"},
]
}
await agent.async_list_backups()
assert mock_client.list_objects_v2.call_args.kwargs["Prefix"] == "ha/backups/"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/cloudflare_r2/test_backup.py",
"license": "Apache License 2.0",
"lines": 481,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/cloudflare_r2/test_config_flow.py | """Test the Cloudflare R2 config flow."""
from unittest.mock import AsyncMock, patch
from botocore.exceptions import (
ClientError,
EndpointConnectionError,
ParamValidationError,
)
import pytest
from homeassistant import config_entries
from homeassistant.components.cloudflare_r2.const import (
CONF_BUCKET,
CONF_ENDPOINT_URL,
DOMAIN,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import USER_INPUT
from tests.common import MockConfigEntry
async def _async_start_flow(
hass: HomeAssistant,
user_input: dict[str, str] | None = None,
) -> FlowResultType:
"""Initialize the config flow."""
if user_input is None:
user_input = USER_INPUT
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
return await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input,
)
async def test_flow(hass: HomeAssistant) -> None:
"""Test config flow."""
result = await _async_start_flow(hass)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test"
assert result["data"] == USER_INPUT
@pytest.mark.parametrize(
("exception", "errors"),
[
(
ParamValidationError(report="Invalid bucket name"),
{CONF_BUCKET: "invalid_bucket_name"},
),
(ValueError(), {CONF_ENDPOINT_URL: "invalid_endpoint_url"}),
(
EndpointConnectionError(endpoint_url="http://example.com"),
{CONF_ENDPOINT_URL: "cannot_connect"},
),
],
)
async def test_flow_create_client_errors(
hass: HomeAssistant,
exception: Exception,
errors: dict[str, str],
) -> None:
"""Test config flow errors."""
with patch(
"aiobotocore.session.AioSession.create_client",
side_effect=exception,
):
result = await _async_start_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == errors
# Fix and finish the test
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test"
assert result["data"] == USER_INPUT
async def test_flow_head_bucket_error(
hass: HomeAssistant,
mock_client: AsyncMock,
) -> None:
"""Test setup_entry error when calling head_bucket."""
mock_client.head_bucket.side_effect = ClientError(
error_response={"Error": {"Code": "InvalidAccessKeyId"}},
operation_name="head_bucket",
)
result = await _async_start_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "invalid_credentials"}
# Fix and finish the test
mock_client.head_bucket.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test"
assert result["data"] == USER_INPUT
async def test_abort_if_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test we abort if the account is already configured."""
mock_config_entry.add_to_hass(hass)
result = await _async_start_flow(hass)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_flow_create_not_r2_endpoint(
hass: HomeAssistant,
) -> None:
"""Test config flow with a not R2 endpoint should raise an error."""
result = await _async_start_flow(
hass, USER_INPUT | {CONF_ENDPOINT_URL: "http://example.com"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {CONF_ENDPOINT_URL: "invalid_endpoint_url"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test"
assert result["data"] == USER_INPUT
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/cloudflare_r2/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/cloudflare_r2/test_init.py | """Test the Cloudflare R2 storage integration."""
from unittest.mock import AsyncMock, patch
from botocore.exceptions import (
ClientError,
EndpointConnectionError,
ParamValidationError,
)
import pytest
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
async def test_load_unload_config_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test loading and unloading the integration."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
("exception", "state"),
[
(
ParamValidationError(report="Invalid bucket name"),
ConfigEntryState.SETUP_ERROR,
),
(ValueError(), ConfigEntryState.SETUP_ERROR),
(
EndpointConnectionError(endpoint_url="https://example.com"),
ConfigEntryState.SETUP_RETRY,
),
],
)
async def test_setup_entry_create_client_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
exception: Exception,
state: ConfigEntryState,
) -> None:
"""Test various setup errors."""
with patch(
"aiobotocore.session.AioSession.create_client",
side_effect=exception,
):
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is state
async def test_setup_entry_head_bucket_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_client: AsyncMock,
) -> None:
"""Test setup_entry error when calling head_bucket."""
mock_client.head_bucket.side_effect = ClientError(
error_response={"Error": {"Code": "InvalidAccessKeyId"}},
operation_name="head_bucket",
)
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/cloudflare_r2/test_init.py",
"license": "Apache License 2.0",
"lines": 61,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/compit/test_select.py | """Tests for the Compit select platform."""
from typing import Any
from unittest.mock import MagicMock
from compit_inext_api.consts import CompitParameter
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from . import setup_integration, snapshot_compit_entities
from tests.common import MockConfigEntry
async def test_select_entities_snapshot(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_connector: MagicMock,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot test for select entities creation, unique IDs, and device info."""
await setup_integration(hass, mock_config_entry)
snapshot_compit_entities(hass, entity_registry, snapshot, Platform.SELECT)
@pytest.mark.parametrize(
"mock_return_value",
[
None,
1,
"invalid",
],
)
async def test_select_unknown_device_parameters(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connector: MagicMock,
mock_return_value: Any,
) -> None:
"""Test that select entity shows unknown when get_current_option returns various invalid values."""
mock_connector.get_current_option.side_effect = lambda device_id, parameter_code: (
mock_return_value
)
await setup_integration(hass, mock_config_entry)
state = hass.states.get("select.nano_color_2_language")
assert state is not None
assert state.state == "unknown"
async def test_select_option(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock
) -> None:
"""Test selecting an option."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
"select",
"select_option",
{"entity_id": "select.nano_color_2_language", "option": "polish"},
blocking=True,
)
mock_connector.select_device_option.assert_called_once()
assert mock_connector.get_current_option(2, CompitParameter.LANGUAGE) == "polish"
async def test_select_invalid_option(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_connector: MagicMock
) -> None:
"""Test selecting an invalid option."""
await setup_integration(hass, mock_config_entry)
with pytest.raises(
ServiceValidationError,
match=r"Option invalid is not valid for entity select\.nano_color_2_language",
):
await hass.services.async_call(
"select",
"select_option",
{"entity_id": "select.nano_color_2_language", "option": "invalid"},
blocking=True,
)
mock_connector.select_device_option.assert_not_called()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/compit/test_select.py",
"license": "Apache License 2.0",
"lines": 73,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/device_tracker/test_condition.py | """Test device tracker conditions."""
from typing import Any
import pytest
from homeassistant.const import STATE_HOME, STATE_NOT_HOME
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_device_trackers(hass: HomeAssistant) -> list[str]:
"""Create multiple device tracker entities associated with different targets."""
return (await target_entities(hass, "device_tracker"))["included"]
@pytest.mark.parametrize(
"condition",
[
"device_tracker.is_home",
"device_tracker.is_not_home",
],
)
async def test_device_tracker_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the device tracker 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("device_tracker"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="device_tracker.is_home",
target_states=[STATE_HOME],
other_states=[STATE_NOT_HOME],
),
*parametrize_condition_states_any(
condition="device_tracker.is_not_home",
target_states=[STATE_NOT_HOME],
other_states=[STATE_HOME],
),
],
)
async def test_device_tracker_state_condition_behavior_any(
hass: HomeAssistant,
target_device_trackers: 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 device tracker state condition with the 'any' behavior."""
other_entity_ids = set(target_device_trackers) - {entity_id}
# Set all device trackers, including the tested one, to the initial state
for eid in target_device_trackers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
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 device trackers 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("device_tracker"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="device_tracker.is_home",
target_states=[STATE_HOME],
other_states=[STATE_NOT_HOME],
),
*parametrize_condition_states_all(
condition="device_tracker.is_not_home",
target_states=[STATE_NOT_HOME],
other_states=[STATE_HOME],
),
],
)
async def test_device_tracker_state_condition_behavior_all(
hass: HomeAssistant,
target_device_trackers: 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 device tracker state condition with the 'all' behavior."""
other_entity_ids = set(target_device_trackers) - {entity_id}
# Set all device trackers, including the tested one, to the initial state
for eid in target_device_trackers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
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/device_tracker/test_condition.py",
"license": "Apache License 2.0",
"lines": 134,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/energy/test_helpers.py | """Test the Energy helpers."""
import pytest
from homeassistant.components.energy.helpers import (
generate_power_sensor_entity_id,
generate_power_sensor_unique_id,
)
def test_generate_power_sensor_unique_id_inverted() -> None:
"""Test unique ID generation for inverted power config."""
config = {"stat_rate_inverted": "sensor.battery_power"}
unique_id = generate_power_sensor_unique_id("battery", config)
assert unique_id == "energy_power_battery_inverted_sensor_battery_power"
def test_generate_power_sensor_unique_id_combined() -> None:
"""Test unique ID generation for combined power config."""
config = {
"stat_rate_from": "sensor.battery_discharge",
"stat_rate_to": "sensor.battery_charge",
}
unique_id = generate_power_sensor_unique_id("battery", config)
assert (
unique_id
== "energy_power_battery_combined_sensor_battery_discharge_sensor_battery_charge"
)
def test_generate_power_sensor_unique_id_standard() -> None:
"""Test unique ID generation raises for standard config (schema-invalid)."""
config = {"stat_rate": "sensor.battery_power"}
with pytest.raises(RuntimeError, match="Invalid power config"):
generate_power_sensor_unique_id("battery", config)
def test_generate_power_sensor_unique_id_empty() -> None:
"""Test unique ID generation raises for empty config (schema-invalid)."""
config = {}
with pytest.raises(RuntimeError, match="Invalid power config"):
generate_power_sensor_unique_id("battery", config)
def test_generate_power_sensor_unique_id_grid() -> None:
"""Test unique ID generation for grid source type."""
config = {"stat_rate_inverted": "sensor.grid_power"}
unique_id = generate_power_sensor_unique_id("grid", config)
assert unique_id == "energy_power_grid_inverted_sensor_grid_power"
def test_generate_power_sensor_entity_id_inverted_with_prefix() -> None:
"""Test entity ID generation for inverted config with sensor prefix."""
config = {"stat_rate_inverted": "sensor.battery_power"}
entity_id = generate_power_sensor_entity_id("battery", config)
assert entity_id == "sensor.battery_power_inverted"
def test_generate_power_sensor_entity_id_inverted_without_prefix() -> None:
"""Test entity ID generation for inverted config without sensor prefix."""
config = {"stat_rate_inverted": "custom.battery_power"}
entity_id = generate_power_sensor_entity_id("battery", config)
assert entity_id == "sensor.custom_battery_power_inverted"
def test_generate_power_sensor_entity_id_combined() -> None:
"""Test entity ID generation for combined power config."""
config = {
"stat_rate_from": "sensor.battery_discharge",
"stat_rate_to": "sensor.battery_charge",
}
entity_id = generate_power_sensor_entity_id("battery", config)
assert (
entity_id == "sensor.energy_battery_battery_discharge_battery_charge_net_power"
)
def test_generate_power_sensor_entity_id_combined_without_prefix() -> None:
"""Test entity ID generation for combined config without sensor prefix."""
config = {
"stat_rate_from": "battery_discharge",
"stat_rate_to": "battery_charge",
}
entity_id = generate_power_sensor_entity_id("battery", config)
assert (
entity_id == "sensor.energy_battery_battery_discharge_battery_charge_net_power"
)
def test_generate_power_sensor_entity_id_standard() -> None:
"""Test entity ID generation raises for standard config (schema-invalid)."""
config = {"stat_rate": "sensor.battery_power"}
with pytest.raises(RuntimeError, match="Invalid power config"):
generate_power_sensor_entity_id("battery", config)
def test_generate_power_sensor_entity_id_empty() -> None:
"""Test entity ID generation raises for empty config (schema-invalid)."""
config = {}
with pytest.raises(RuntimeError, match="Invalid power config"):
generate_power_sensor_entity_id("battery", config)
def test_generate_power_sensor_entity_id_grid() -> None:
"""Test entity ID generation for grid source type."""
config = {
"stat_rate_from": "sensor.grid_import",
"stat_rate_to": "sensor.grid_export",
}
entity_id = generate_power_sensor_entity_id("grid", config)
assert entity_id == "sensor.energy_grid_grid_import_grid_export_net_power"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/energy/test_helpers.py",
"license": "Apache License 2.0",
"lines": 85,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/esphome/test_water_heater.py | """Test ESPHome water heaters."""
from unittest.mock import call
from aioesphomeapi import APIClient, WaterHeaterInfo, WaterHeaterMode, WaterHeaterState
from homeassistant.components.water_heater import (
ATTR_OPERATION_LIST,
DOMAIN as WATER_HEATER_DOMAIN,
SERVICE_SET_OPERATION_MODE,
SERVICE_SET_TEMPERATURE,
)
from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE
from homeassistant.core import HomeAssistant
from .conftest import MockGenericDeviceEntryType
async def test_water_heater_entity(
hass: HomeAssistant,
mock_client: APIClient,
mock_generic_device_entry: MockGenericDeviceEntryType,
) -> None:
"""Test a generic water heater entity."""
entity_info = [
WaterHeaterInfo(
object_id="my_boiler",
key=1,
name="My Boiler",
min_temperature=10.0,
max_temperature=85.0,
supported_modes=[
WaterHeaterMode.ECO,
WaterHeaterMode.GAS,
],
)
]
states = [
WaterHeaterState(
key=1,
mode=WaterHeaterMode.ECO,
current_temperature=45.0,
target_temperature=50.0,
)
]
await mock_generic_device_entry(
mock_client=mock_client,
entity_info=entity_info,
states=states,
)
state = hass.states.get("water_heater.test_my_boiler")
assert state is not None
assert state.state == "eco"
assert state.attributes["current_temperature"] == 45.0
assert state.attributes["temperature"] == 50.0
assert state.attributes["min_temp"] == 10.0
assert state.attributes["max_temp"] == 85.0
assert state.attributes["operation_list"] == ["eco", "gas"]
async def test_water_heater_entity_no_modes(
hass: HomeAssistant,
mock_client: APIClient,
mock_generic_device_entry: MockGenericDeviceEntryType,
) -> None:
"""Test a water heater entity without operation modes."""
entity_info = [
WaterHeaterInfo(
object_id="my_boiler",
key=1,
name="My Boiler",
min_temperature=10.0,
max_temperature=85.0,
)
]
states = [
WaterHeaterState(
key=1,
current_temperature=45.0,
target_temperature=50.0,
)
]
await mock_generic_device_entry(
mock_client=mock_client,
entity_info=entity_info,
states=states,
)
state = hass.states.get("water_heater.test_my_boiler")
assert state is not None
assert state.attributes["min_temp"] == 10.0
assert state.attributes["max_temp"] == 85.0
assert state.attributes.get(ATTR_OPERATION_LIST) is None
async def test_water_heater_set_temperature(
hass: HomeAssistant,
mock_client: APIClient,
mock_generic_device_entry: MockGenericDeviceEntryType,
) -> None:
"""Test setting the target temperature."""
entity_info = [
WaterHeaterInfo(
object_id="my_boiler",
key=1,
name="My Boiler",
min_temperature=10.0,
max_temperature=85.0,
)
]
states = [
WaterHeaterState(
key=1,
mode=WaterHeaterMode.ECO,
target_temperature=45.0,
)
]
await mock_generic_device_entry(
mock_client=mock_client,
entity_info=entity_info,
states=states,
)
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "water_heater.test_my_boiler",
ATTR_TEMPERATURE: 55,
},
blocking=True,
)
mock_client.water_heater_command.assert_has_calls(
[call(key=1, target_temperature=55.0, device_id=0)]
)
async def test_water_heater_set_operation_mode(
hass: HomeAssistant,
mock_client: APIClient,
mock_generic_device_entry: MockGenericDeviceEntryType,
) -> None:
"""Test setting the operation mode."""
entity_info = [
WaterHeaterInfo(
object_id="my_boiler",
key=1,
name="My Boiler",
supported_modes=[
WaterHeaterMode.ECO,
WaterHeaterMode.GAS,
],
)
]
states = [
WaterHeaterState(
key=1,
mode=WaterHeaterMode.ECO,
)
]
await mock_generic_device_entry(
mock_client=mock_client,
entity_info=entity_info,
states=states,
)
await hass.services.async_call(
WATER_HEATER_DOMAIN,
SERVICE_SET_OPERATION_MODE,
{
ATTR_ENTITY_ID: "water_heater.test_my_boiler",
"operation_mode": "gas",
},
blocking=True,
)
mock_client.water_heater_command.assert_has_calls(
[call(key=1, mode=WaterHeaterMode.GAS, device_id=0)]
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/esphome/test_water_heater.py",
"license": "Apache License 2.0",
"lines": 163,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/fan/test_condition.py | """Test fan 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_fans(hass: HomeAssistant) -> list[str]:
"""Create multiple fan entities associated with different targets."""
return (await target_entities(hass, "fan"))["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 fan entities are considered
in the condition evaluation and not other toggle entities.
"""
return (await target_entities(hass, "switch"))["included"]
@pytest.mark.parametrize(
"condition",
[
"fan.is_off",
"fan.is_on",
],
)
async def test_fan_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the fan 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("fan"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="fan.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_condition_states_any(
condition="fan.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_fan_state_condition_behavior_any(
hass: HomeAssistant,
target_fans: 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 fan state condition with the 'any' behavior."""
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()
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 fans 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("fan"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="fan.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_condition_states_all(
condition="fan.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_fan_state_condition_behavior_all(
hass: HomeAssistant,
target_fans: 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 fan 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_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()
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/fan/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/fritz/test_binary_sensor.py | """Tests for Fritz!Tools binary sensor platform."""
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.binary_sensor import STATE_ON
from homeassistant.components.fritz.const import DOMAIN, SCAN_INTERVAL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .const import MOCK_USER_DATA
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_binary_sensor_setup(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
fc_class_mock,
fh_class_mock,
snapshot: SnapshotAssertion,
) -> None:
"""Test Fritz!Tools binary_sensor setup."""
entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
entry.add_to_hass(hass)
with patch("homeassistant.components.fritz.PLATFORMS", [Platform.BINARY_SENSOR]):
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
async def test_binary_sensor_missing_state(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
fc_class_mock,
fh_class_mock,
) -> None:
"""Test missing Fritz!Tools state for binary_sensor."""
entity_id = "binary_sensor.mock_title_connection"
entry = MockConfigEntry(domain=DOMAIN, data=MOCK_USER_DATA)
entry.add_to_hass(hass)
with patch("homeassistant.components.fritz.PLATFORMS", [Platform.BINARY_SENSOR]):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.LOADED
assert (state := hass.states.get(entity_id))
assert state.state == STATE_ON
with patch(
"homeassistant.components.fritz.coordinator.FritzBoxTools._async_update_data",
return_value={"entity_states": {}},
):
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNKNOWN
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/fritz/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/green_planet_energy/test_config_flow.py | """Test the Green Planet Energy config flow."""
from unittest.mock import AsyncMock, MagicMock
from greenplanet_energy_api import (
GreenPlanetEnergyAPIError,
GreenPlanetEnergyConnectionError,
)
import pytest
from homeassistant.components.green_planet_energy.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_form_create_entry(
hass: HomeAssistant, mock_api: MagicMock, mock_setup_entry: AsyncMock
) -> None:
"""Test creating an entry."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Green Planet Energy"
assert result["data"] == {}
@pytest.mark.parametrize(
("exception", "error_base"),
[
(GreenPlanetEnergyConnectionError("Connection failed"), "cannot_connect"),
(GreenPlanetEnergyAPIError("API error"), "invalid_auth"),
(Exception("Unknown error"), "unknown"),
],
)
async def test_form_errors_and_recovery(
hass: HomeAssistant,
mock_api: MagicMock,
mock_setup_entry: AsyncMock,
exception: Exception,
error_base: str,
) -> None:
"""Test handling errors and recovery."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
# Set the mock to raise an error
mock_api.get_electricity_prices.side_effect = exception
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_base}
# Reset the mock to not raise an error and test recovery
mock_api.get_electricity_prices.side_effect = None
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_form_already_configured(
hass: HomeAssistant,
mock_api: MagicMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test we abort if 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"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/green_planet_energy/test_config_flow.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/green_planet_energy/test_init.py | """Test Green Planet Energy setup."""
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_setup_entry(
hass: HomeAssistant, init_integration: MockConfigEntry
) -> None:
"""Test setting up config entry."""
assert init_integration.state is ConfigEntryState.LOADED
async def test_unload_entry(
hass: HomeAssistant, init_integration: MockConfigEntry
) -> None:
"""Test unloading config entry."""
assert init_integration.state is ConfigEntryState.LOADED
result = await hass.config_entries.async_unload(init_integration.entry_id)
await hass.async_block_till_done()
assert result
assert init_integration.state is ConfigEntryState.NOT_LOADED
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/green_planet_energy/test_init.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/green_planet_energy/test_sensor.py | """Test the Green Planet Energy sensor."""
from freezegun.api import FrozenDateTimeFactory
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
async def test_sensors(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
init_integration: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test sensors."""
freezer.move_to("2024-01-01 13:00:00")
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id)
async def test_sensor_device_info(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
init_integration: MockConfigEntry,
) -> None:
"""Test sensor device info."""
entry = entity_registry.async_get("sensor.green_planet_energy_highest_price_today")
assert entry is not None
assert entry.device_id is not None
device = device_registry.async_get(entry.device_id)
assert device is not None
assert device.name == "Green Planet Energy"
assert device.entry_type is dr.DeviceEntryType.SERVICE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/green_planet_energy/test_sensor.py",
"license": "Apache License 2.0",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hdfury/test_button.py | """Tests for the HDFury button platform."""
from unittest.mock import AsyncMock
from hdfury import HDFuryError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_button_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test HDFury button entities."""
await setup_integration(hass, mock_config_entry, [Platform.BUTTON])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("entity_id", "method"),
[
("button.hdfury_vrroom_02_restart", "issue_reboot"),
("button.hdfury_vrroom_02_issue_hotplug", "issue_hotplug"),
],
)
async def test_button_presses(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
method: str,
) -> None:
"""Test pressing the device buttons."""
await setup_integration(hass, mock_config_entry, [Platform.BUTTON])
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
getattr(mock_hdfury_client, method).assert_awaited_once()
async def test_button_press_error(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test button press raises HomeAssistantError on API failure."""
mock_hdfury_client.issue_reboot.side_effect = HDFuryError()
await setup_integration(hass, mock_config_entry, [Platform.BUTTON])
with pytest.raises(
HomeAssistantError,
match="An error occurred while communicating with HDFury device",
):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.hdfury_vrroom_02_restart"},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hdfury/test_button.py",
"license": "Apache License 2.0",
"lines": 62,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hdfury/test_config_flow.py | """Test the HDFury config flow."""
from ipaddress import ip_address
from unittest.mock import AsyncMock
from hdfury import HDFuryError
from homeassistant.components.hdfury.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from tests.common import MockConfigEntry
ZEROCONF_DISCOVERY = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.123"),
ip_addresses=[ip_address("192.168.1.123")],
hostname="VRROOM-02.local.",
name="VRROOM-02._http._tcp.local.",
port=80,
type="_http._tcp.local.",
properties={
"path": "/",
},
)
async def test_async_step_user_gets_form_and_creates_entry(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test that the we can view the form and that the config flow creates an entry."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "192.168.1.123"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_HOST: "192.168.1.123",
}
assert result["result"].unique_id == "000123456789"
async def test_abort_if_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test that we abort if we attempt to submit the same entry twice."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "192.168.1.123"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_successful_recovery_after_connection_error(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test error shown when connection fails."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
# Simulate a connection error by raising a HDFuryError
mock_hdfury_client.get_board.side_effect = HDFuryError()
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "192.168.1.123"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
# Simulate successful connection on retry
mock_hdfury_client.get_board.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "192.168.1.123"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_HOST: "192.168.1.123",
}
assert result["result"].unique_id == "000123456789"
async def test_zeroconf_flow(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test zeroconf flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_HOST: "192.168.1.123",
}
assert result["result"].unique_id == "000123456789"
async def test_zeroconf_flow_failure(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test zeroconf flow failure."""
# Simulate a connection error by raising a HDFuryError
mock_hdfury_client.get_board.side_effect = HDFuryError()
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_zeroconf_flow_abort_duplicate(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test zeroconf flow aborts with duplicate."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reconfigure_flow(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {}
# Original entry
assert mock_config_entry.data[CONF_HOST] == "192.168.1.123"
assert mock_config_entry.unique_id == "000123456789"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.124",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
# Changed entry
assert mock_config_entry.data[CONF_HOST] == "192.168.1.124"
assert mock_config_entry.unique_id == "000123456789"
async def test_reconfigure_flow_no_change(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration without changing values."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {}
# Original entry
assert mock_config_entry.data[CONF_HOST] == "192.168.1.123"
assert mock_config_entry.unique_id == "000123456789"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.123",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
# Changed entry
assert mock_config_entry.data[CONF_HOST] == "192.168.1.123"
assert mock_config_entry.unique_id == "000123456789"
async def test_reconfigure_flow_abort_incorrect_device(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test ip of other device with different serial."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {}
# Simulate different serial number, as if user entered wrong IP
mock_hdfury_client.get_board.return_value = {
"hostname": "VRROOM-21",
"ipaddress": "192.168.1.124",
"serial": "000987654321",
"pcbv": "3",
"version": "FW: 0.61",
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.124",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "incorrect_device"
# Entry should still be original entry
assert mock_config_entry.data[CONF_HOST] == "192.168.1.123"
assert mock_config_entry.unique_id == "000123456789"
async def test_reconfigure_flow_cannot_connect(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration fails with cannot connect."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {}
# Simulate a connection error by raising a HDFuryError
mock_hdfury_client.get_board.side_effect = HDFuryError()
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.124",
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
assert result["data_schema"]({}) == {CONF_HOST: "192.168.1.123"}
# Attempt with valid IP should work
mock_hdfury_client.get_board.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.124",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
# Changed entry
assert mock_config_entry.data[CONF_HOST] == "192.168.1.124"
assert mock_config_entry.unique_id == "000123456789"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hdfury/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 259,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hdfury/test_diagnostics.py | """Tests for the HDFury diagnostics."""
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.hdfury import PLATFORMS
from homeassistant.core import HomeAssistant
import homeassistant.helpers.entity_registry as er
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(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test HDFury diagnostics."""
await setup_integration(hass, mock_config_entry, PLATFORMS)
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
assert diagnostics == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hdfury/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hdfury/test_select.py | """Tests for the HDFury select platform."""
from datetime import timedelta
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
from hdfury import HDFuryError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.select import (
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
)
from homeassistant.const import ATTR_ENTITY_ID, ATTR_OPTION, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_select_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test HDFury select entities."""
await setup_integration(hass, mock_config_entry, [Platform.SELECT])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_select_operation_mode(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test selecting operation mode."""
await setup_integration(hass, mock_config_entry, [Platform.SELECT])
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: "select.hdfury_vrroom_02_operation_mode",
ATTR_OPTION: "1",
},
blocking=True,
)
mock_hdfury_client.set_operation_mode.assert_awaited_once_with("1")
@pytest.mark.parametrize(
("entity_id"),
[
("select.hdfury_vrroom_02_port_select_tx0"),
("select.hdfury_vrroom_02_port_select_tx1"),
],
)
async def test_select_tx_ports(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
) -> None:
"""Test selecting TX ports."""
await setup_integration(hass, mock_config_entry, [Platform.SELECT])
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: "1",
},
blocking=True,
)
mock_hdfury_client.set_port_selection.assert_awaited()
async def test_select_operation_mode_error(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test operation mode select raises HomeAssistantError."""
mock_hdfury_client.set_operation_mode.side_effect = HDFuryError()
await setup_integration(hass, mock_config_entry, [Platform.SELECT])
with pytest.raises(
HomeAssistantError,
match="An error occurred while communicating with HDFury device",
):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: "select.hdfury_vrroom_02_operation_mode",
ATTR_OPTION: "1",
},
blocking=True,
)
async def test_select_ports_missing_state(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test TX port selection fails when TX state is incomplete."""
mock_hdfury_client.get_info.return_value = {
"portseltx0": "0",
"portseltx1": None,
"opmode": "0",
}
await setup_integration(hass, mock_config_entry, [Platform.SELECT])
with pytest.raises(
HomeAssistantError,
match="An error occurred while validating TX states",
):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: "select.hdfury_vrroom_02_port_select_tx0",
ATTR_OPTION: "0",
},
blocking=True,
)
async def test_select_entities_unavailable_on_error(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test API error causes entities to become unavailable."""
await setup_integration(hass, mock_config_entry, [Platform.SELECT])
mock_hdfury_client.get_info.side_effect = HDFuryError()
freezer.tick(timedelta(seconds=61))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (
hass.states.get("select.hdfury_vrroom_02_port_select_tx0").state
== STATE_UNAVAILABLE
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hdfury/test_select.py",
"license": "Apache License 2.0",
"lines": 130,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hdfury/test_sensor.py | """Tests for the HDFury sensor platform."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import 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.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test HDFury sensor entities."""
await setup_integration(hass, mock_config_entry, [Platform.SENSOR])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hdfury/test_sensor.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hdfury/test_switch.py | """Tests for the HDFury switch platform."""
from datetime import timedelta
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
from hdfury import HDFuryError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_switch_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test HDFury switch entities."""
await setup_integration(hass, mock_config_entry, [Platform.SWITCH])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("entity_id", "method", "service"),
[
("switch.hdfury_vrroom_02_cec", "set_cec", SERVICE_TURN_ON),
("switch.hdfury_vrroom_02_cec", "set_cec", SERVICE_TURN_OFF),
(
"switch.hdfury_vrroom_02_auto_switch_inputs",
"set_auto_switch_inputs",
SERVICE_TURN_ON,
),
(
"switch.hdfury_vrroom_02_auto_switch_inputs",
"set_auto_switch_inputs",
SERVICE_TURN_OFF,
),
("switch.hdfury_vrroom_02_oled_display", "set_oled", SERVICE_TURN_ON),
("switch.hdfury_vrroom_02_oled_display", "set_oled", SERVICE_TURN_OFF),
("switch.hdfury_vrroom_02_tx0_force_5v", "set_tx0_force_5v", SERVICE_TURN_ON),
("switch.hdfury_vrroom_02_tx0_force_5v", "set_tx0_force_5v", SERVICE_TURN_OFF),
("switch.hdfury_vrroom_02_tx1_force_5v", "set_tx1_force_5v", SERVICE_TURN_ON),
("switch.hdfury_vrroom_02_tx1_force_5v", "set_tx1_force_5v", SERVICE_TURN_OFF),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_switch_turn_on_off(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
method: str,
service: str,
) -> None:
"""Test turning device switches on and off."""
await setup_integration(hass, mock_config_entry, [Platform.SWITCH])
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
getattr(mock_hdfury_client, method).assert_awaited_once()
@pytest.mark.parametrize(
("service", "method"),
[
(SERVICE_TURN_ON, "set_auto_switch_inputs"),
(SERVICE_TURN_OFF, "set_auto_switch_inputs"),
],
)
async def test_switch_turn_error(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
service: str,
method: str,
) -> None:
"""Test switch turn on/off raises HomeAssistantError on API failure."""
getattr(mock_hdfury_client, method).side_effect = HDFuryError()
await setup_integration(hass, mock_config_entry, [Platform.SWITCH])
with pytest.raises(
HomeAssistantError,
match="An error occurred while communicating with HDFury device",
):
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: "switch.hdfury_vrroom_02_auto_switch_inputs"},
blocking=True,
)
async def test_switch_entities_unavailable_on_error(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test API error causes entities to become unavailable."""
await setup_integration(hass, mock_config_entry, [Platform.SWITCH])
mock_hdfury_client.get_info.side_effect = HDFuryError()
freezer.tick(timedelta(seconds=61))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (
hass.states.get("switch.hdfury_vrroom_02_auto_switch_inputs").state
== STATE_UNAVAILABLE
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hdfury/test_switch.py",
"license": "Apache License 2.0",
"lines": 114,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hikvision/test_camera.py | """Test Hikvision cameras."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.camera import async_get_image, async_get_stream_source
from homeassistant.components.hikvision.const import DOMAIN
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import setup_integration
from .conftest import TEST_DEVICE_ID, TEST_DEVICE_NAME, TEST_HOST
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Return platforms to load during test."""
return [Platform.CAMERA]
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hikcamera: MagicMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test all camera entities."""
with patch("random.SystemRandom.getrandbits", return_value=123123123123):
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")
@pytest.mark.parametrize("amount_of_channels", [2])
async def test_nvr_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hikcamera: MagicMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test NVR camera entities with multiple channels."""
mock_hikcamera.return_value.get_type = "NVR"
with patch("random.SystemRandom.getrandbits", return_value=123123123123):
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")
@pytest.mark.parametrize("amount_of_channels", [2])
async def test_nvr_entities_with_channel_names(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hikcamera: MagicMock,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test NVR camera entities use custom channel names when available."""
mock_hikcamera.return_value.get_type = "NVR"
with patch("random.SystemRandom.getrandbits", return_value=123123123123):
await setup_integration(hass, mock_config_entry)
# Verify device names use channel names instead of "Channel N"
device_1 = device_registry.async_get_device(
identifiers={(DOMAIN, f"{TEST_DEVICE_ID}_1")}
)
assert device_1 is not None
assert device_1.name == "Front Camera channel 1"
device_2 = device_registry.async_get_device(
identifiers={(DOMAIN, f"{TEST_DEVICE_ID}_2")}
)
assert device_2 is not None
assert device_2.name == "Front Camera channel 2"
async def test_camera_device_info(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hikcamera: MagicMock,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test camera is linked to device."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, TEST_DEVICE_ID)}
)
assert device_entry is not None
assert device_entry.name == TEST_DEVICE_NAME
assert device_entry.manufacturer == "Hikvision"
assert device_entry.model == "Camera"
async def test_camera_no_channels_creates_single_camera(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hikcamera: MagicMock,
) -> None:
"""Test camera created when device returns no channels."""
mock_hikcamera.return_value.get_channels.return_value = []
await setup_integration(hass, mock_config_entry)
# Single camera should be created for channel 1
states = hass.states.async_entity_ids("camera")
assert len(states) == 1
state = hass.states.get("camera.front_camera")
assert state is not None
async def test_camera_image(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hikcamera: MagicMock,
) -> None:
"""Test getting camera image."""
await setup_integration(hass, mock_config_entry)
image = await async_get_image(hass, "camera.front_camera")
assert image.content == b"fake_image_data"
# Verify get_snapshot was called with channel 1
mock_hikcamera.return_value.get_snapshot.assert_called_with(1)
async def test_camera_image_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hikcamera: MagicMock,
) -> None:
"""Test camera image error handling."""
mock_hikcamera.return_value.get_snapshot.side_effect = Exception("Connection error")
await setup_integration(hass, mock_config_entry)
with pytest.raises(HomeAssistantError, match="Error getting image"):
await async_get_image(hass, "camera.front_camera")
async def test_camera_stream_source(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_hikcamera: MagicMock,
) -> None:
"""Test camera stream source URL."""
await setup_integration(hass, mock_config_entry)
stream_url = await async_get_stream_source(hass, "camera.front_camera")
# Verify RTSP URL from library
assert stream_url is not None
assert stream_url.startswith("rtsp://")
assert f"@{TEST_HOST}:554/Streaming/Channels/1" in stream_url
# Verify get_stream_url was called with channel 1
mock_hikcamera.return_value.get_stream_url.assert_called_with(1)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hikvision/test_camera.py",
"license": "Apache License 2.0",
"lines": 129,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/humidifier/test_condition.py | """Test humidifier conditions."""
from typing import Any
import pytest
from homeassistant.components.humidifier.const import ATTR_ACTION, HumidifierAction
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_humidifiers(hass: HomeAssistant) -> list[str]:
"""Create multiple humidifier entities associated with different targets."""
return (await target_entities(hass, "humidifier"))["included"]
@pytest.mark.parametrize(
"condition",
[
"humidifier.is_off",
"humidifier.is_on",
"humidifier.is_drying",
"humidifier.is_humidifying",
],
)
async def test_humidifier_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the humidifier 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("humidifier"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="humidifier.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
*parametrize_condition_states_any(
condition="humidifier.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
],
)
async def test_humidifier_state_condition_behavior_any(
hass: HomeAssistant,
target_humidifiers: 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 humidifier state condition with the 'any' behavior."""
other_entity_ids = set(target_humidifiers) - {entity_id}
# Set all humidifiers, including the tested humidifier, to the initial state
for eid in target_humidifiers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
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 humidifiers 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("humidifier"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="humidifier.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
*parametrize_condition_states_all(
condition="humidifier.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
],
)
async def test_humidifier_state_condition_behavior_all(
hass: HomeAssistant,
target_humidifiers: 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 humidifier state condition with the 'all' behavior."""
other_entity_ids = set(target_humidifiers) - {entity_id}
# Set all humidifiers, including the tested humidifier, to the initial state
for eid in target_humidifiers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
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"]
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("condition_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities("humidifier"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="humidifier.is_drying",
target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.DRYING})],
other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})],
),
*parametrize_condition_states_any(
condition="humidifier.is_humidifying",
target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.HUMIDIFYING})],
other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})],
),
],
)
async def test_humidifier_attribute_condition_behavior_any(
hass: HomeAssistant,
target_humidifiers: 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 humidifier attribute condition with the 'any' behavior."""
other_entity_ids = set(target_humidifiers) - {entity_id}
# Set all humidifiers, including the tested humidifier, to the initial state
for eid in target_humidifiers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
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 humidifiers 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("humidifier"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="humidifier.is_drying",
target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.DRYING})],
other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})],
),
*parametrize_condition_states_all(
condition="humidifier.is_humidifying",
target_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.HUMIDIFYING})],
other_states=[(STATE_ON, {ATTR_ACTION: HumidifierAction.IDLE})],
),
],
)
async def test_humidifier_attribute_condition_behavior_all(
hass: HomeAssistant,
target_humidifiers: 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 humidifier attribute condition with the 'all' behavior."""
other_entity_ids = set(target_humidifiers) - {entity_id}
# Set all humidifiers, including the tested humidifier, to the initial state
for eid in target_humidifiers:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
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/humidifier/test_condition.py",
"license": "Apache License 2.0",
"lines": 240,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/izone/test_climate.py | """Tests for iZone climate platform."""
from unittest.mock import AsyncMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.climate import ClimateEntityFeature
from homeassistant.core import HomeAssistant
import homeassistant.helpers.entity_registry as er
from . import setup_controller, setup_integration
from .conftest import create_mock_controller, create_mock_zone
from tests.common import MockConfigEntry, snapshot_platform
async def test_basic_controller_properties(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_discovery: AsyncMock,
mock_controller: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test basic properties of ControllerDevice."""
await setup_integration(hass, mock_config_entry)
await setup_controller(hass, mock_discovery, mock_controller)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
entity_id = "climate.izone_controller_test_controller_123"
entity = hass.states.get(entity_id)
assert entity is not None
assert (
entity.attributes["supported_features"]
& ClimateEntityFeature.TARGET_TEMPERATURE
) != ClimateEntityFeature.TARGET_TEMPERATURE
@pytest.mark.parametrize(
"mock_controller",
[
create_mock_controller(
ras_mode="RAS",
)
],
)
async def test_target_temperature_feature_ras_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_discovery: AsyncMock,
mock_controller: AsyncMock,
) -> None:
"""Test TARGET_TEMPERATURE feature enabled in RAS mode."""
await setup_integration(hass, mock_config_entry)
await setup_controller(hass, mock_discovery, mock_controller)
entity_id = "climate.izone_controller_test_controller_123"
entity = hass.states.get(entity_id)
assert entity is not None
assert (
entity.attributes["supported_features"]
& ClimateEntityFeature.TARGET_TEMPERATURE
) == ClimateEntityFeature.TARGET_TEMPERATURE
@pytest.mark.parametrize(
"mock_controller",
[
create_mock_controller(
zone_ctrl=13, # Greater than zones_total (4)
zones_total=4,
)
],
)
async def test_target_temperature_feature_master_mode_invalid_zone(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_discovery: AsyncMock,
mock_controller: AsyncMock,
) -> None:
"""Test TARGET_TEMPERATURE feature enabled when control zone is invalid."""
await setup_integration(hass, mock_config_entry)
await setup_controller(hass, mock_discovery, mock_controller)
entity_id = "climate.izone_controller_test_controller_123"
entity = hass.states.get(entity_id)
assert entity is not None
assert (
entity.attributes["supported_features"]
& ClimateEntityFeature.TARGET_TEMPERATURE
) == ClimateEntityFeature.TARGET_TEMPERATURE
@pytest.mark.parametrize(
("mock_controller", "mock_zones"),
[
(
create_mock_controller(
zone_ctrl=1, # Valid zone
zones_total=2,
),
[
create_mock_zone(index=0, name="Living Room", temp_current=22.5),
create_mock_zone(
index=1, name="Bedroom", temp_current=None
), # No sensor
],
)
],
)
async def test_target_temperature_feature_zone_without_sensor(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_discovery: AsyncMock,
mock_controller: AsyncMock,
) -> None:
"""Test TARGET_TEMPERATURE feature enabled when any zone lacks temperature sensor."""
await setup_integration(hass, mock_config_entry)
await setup_controller(hass, mock_discovery, mock_controller)
entity_id = "climate.izone_controller_test_controller_123"
entity = hass.states.get(entity_id)
assert entity is not None
assert (
entity.attributes["supported_features"]
& ClimateEntityFeature.TARGET_TEMPERATURE
) == ClimateEntityFeature.TARGET_TEMPERATURE
@pytest.mark.parametrize(
("mock_controller", "mock_zones"),
[
(
create_mock_controller(
zones_total=3,
),
[
create_mock_zone(index=0, name="Zone 1", temp_current=22.5),
create_mock_zone(index=1, name="Zone 2", temp_current=23.0),
create_mock_zone(index=2, name="Zone 3", temp_current=21.5),
],
)
],
)
async def test_target_temperature_feature_all_zones_with_sensors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_discovery: AsyncMock,
mock_controller: AsyncMock,
) -> None:
"""Test TARGET_TEMPERATURE feature NOT enabled when all zones have sensors."""
await setup_integration(hass, mock_config_entry)
await setup_controller(hass, mock_discovery, mock_controller)
entity_id = "climate.izone_controller_test_controller_123"
entity = hass.states.get(entity_id)
assert entity is not None
# Should NOT have TARGET_TEMPERATURE feature
assert (
entity.attributes["supported_features"]
& ClimateEntityFeature.TARGET_TEMPERATURE
) != ClimateEntityFeature.TARGET_TEMPERATURE
@pytest.mark.parametrize(
("mock_controller", "mock_zones"),
[
(
create_mock_controller(
zones_total=3,
),
[
create_mock_zone(index=0, name="Zone 1", temp_current=22.5),
create_mock_zone(index=1, name="Zone 2", temp_current=None),
create_mock_zone(index=2, name="Zone 3", temp_current=21.5),
],
)
],
)
async def test_target_temperature_feature_multiple_zones_one_without_sensor(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_discovery: AsyncMock,
mock_controller: AsyncMock,
) -> None:
"""Test TARGET_TEMPERATURE feature enabled with multiple zones when one lacks sensor."""
await setup_integration(hass, mock_config_entry)
await setup_controller(hass, mock_discovery, mock_controller)
entity_id = "climate.izone_controller_test_controller_123"
entity = hass.states.get(entity_id)
assert entity is not None
assert (
entity.attributes["supported_features"]
& ClimateEntityFeature.TARGET_TEMPERATURE
) == ClimateEntityFeature.TARGET_TEMPERATURE
@pytest.mark.parametrize(
"mock_controller",
[
create_mock_controller(
ras_mode="slave",
)
],
)
async def test_target_temperature_feature_slave_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_discovery: AsyncMock,
mock_controller: AsyncMock,
) -> None:
"""Test TARGET_TEMPERATURE feature NOT enabled in slave mode."""
await setup_integration(hass, mock_config_entry)
await setup_controller(hass, mock_discovery, mock_controller)
entity_id = "climate.izone_controller_test_controller_123"
entity = hass.states.get(entity_id)
assert entity is not None
# Should NOT have TARGET_TEMPERATURE feature
assert (
entity.attributes["supported_features"]
& ClimateEntityFeature.TARGET_TEMPERATURE
) != ClimateEntityFeature.TARGET_TEMPERATURE
@pytest.mark.parametrize(
"mock_controller",
[
create_mock_controller(
zone_ctrl=13,
zones_total=4,
)
],
)
async def test_target_temperature_feature_master_mode_zone_13(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_discovery: AsyncMock,
mock_controller: AsyncMock,
) -> None:
"""Test TARGET_TEMPERATURE feature enabled when control zone is 13 (master unit)."""
await setup_integration(hass, mock_config_entry)
await setup_controller(hass, mock_discovery, mock_controller)
entity_id = "climate.izone_controller_test_controller_123"
entity = hass.states.get(entity_id)
assert entity is not None
assert (
entity.attributes["supported_features"]
& ClimateEntityFeature.TARGET_TEMPERATURE
) == ClimateEntityFeature.TARGET_TEMPERATURE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/izone/test_climate.py",
"license": "Apache License 2.0",
"lines": 224,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/lawn_mower/test_condition.py | """Test lawn mower conditions."""
from typing import Any
import pytest
from homeassistant.components.lawn_mower.const import LawnMowerActivity
from homeassistant.core import HomeAssistant
from tests.components import (
ConditionStateDescription,
assert_condition_gated_by_labs_flag,
create_target_condition,
other_states,
parametrize_condition_states_all,
parametrize_condition_states_any,
parametrize_target_entities,
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(
"condition",
[
"lawn_mower.is_docked",
"lawn_mower.is_encountering_an_error",
"lawn_mower.is_mowing",
"lawn_mower.is_paused",
"lawn_mower.is_returning",
],
)
async def test_lawn_mower_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the lawn mower 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("lawn_mower"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="lawn_mower.is_docked",
target_states=[LawnMowerActivity.DOCKED],
other_states=other_states(LawnMowerActivity.DOCKED),
),
*parametrize_condition_states_any(
condition="lawn_mower.is_encountering_an_error",
target_states=[LawnMowerActivity.ERROR],
other_states=other_states(LawnMowerActivity.ERROR),
),
*parametrize_condition_states_any(
condition="lawn_mower.is_mowing",
target_states=[LawnMowerActivity.MOWING],
other_states=other_states(LawnMowerActivity.MOWING),
),
*parametrize_condition_states_any(
condition="lawn_mower.is_paused",
target_states=[LawnMowerActivity.PAUSED],
other_states=other_states(LawnMowerActivity.PAUSED),
),
*parametrize_condition_states_any(
condition="lawn_mower.is_returning",
target_states=[LawnMowerActivity.RETURNING],
other_states=other_states(LawnMowerActivity.RETURNING),
),
],
)
async def test_lawn_mower_state_condition_behavior_any(
hass: HomeAssistant,
target_lawn_mowers: 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 lawn mower state condition with the 'any' behavior."""
other_entity_ids = set(target_lawn_mowers) - {entity_id}
# Set all lawn mowers, including the tested lawn mower, 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()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
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 lawn mowers 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("lawn_mower"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="lawn_mower.is_docked",
target_states=[LawnMowerActivity.DOCKED],
other_states=other_states(LawnMowerActivity.DOCKED),
),
*parametrize_condition_states_all(
condition="lawn_mower.is_encountering_an_error",
target_states=[LawnMowerActivity.ERROR],
other_states=other_states(LawnMowerActivity.ERROR),
),
*parametrize_condition_states_all(
condition="lawn_mower.is_mowing",
target_states=[LawnMowerActivity.MOWING],
other_states=other_states(LawnMowerActivity.MOWING),
),
*parametrize_condition_states_all(
condition="lawn_mower.is_paused",
target_states=[LawnMowerActivity.PAUSED],
other_states=other_states(LawnMowerActivity.PAUSED),
),
*parametrize_condition_states_all(
condition="lawn_mower.is_returning",
target_states=[LawnMowerActivity.RETURNING],
other_states=other_states(LawnMowerActivity.RETURNING),
),
],
)
async def test_lawn_mower_state_condition_behavior_all(
hass: HomeAssistant,
target_lawn_mowers: 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 lawn mower state condition with the 'all' behavior."""
other_entity_ids = set(target_lawn_mowers) - {entity_id}
# Set all lawn mowers, including the tested lawn mower, 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()
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/lawn_mower/test_condition.py",
"license": "Apache License 2.0",
"lines": 168,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/lg_thinq/test_humidifier.py | """Tests for the LG ThinQ humidifier platform."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize("device_fixture", ["dehumidifier"])
async def test_humidifier_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
devices: AsyncMock,
mock_thinq_api: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.lg_thinq.PLATFORMS", [Platform.HUMIDIFIER]):
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/lg_thinq/test_humidifier.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/lock/test_condition.py | """Test lock conditions."""
from typing import Any
import pytest
from homeassistant.components.lock.const import LockState
from homeassistant.core import HomeAssistant
from tests.components import (
ConditionStateDescription,
assert_condition_gated_by_labs_flag,
create_target_condition,
other_states,
parametrize_condition_states_all,
parametrize_condition_states_any,
parametrize_target_entities,
set_or_remove_state,
target_entities,
)
@pytest.fixture
async def target_locks(hass: HomeAssistant) -> list[str]:
"""Create multiple lock entities associated with different targets."""
return (await target_entities(hass, "lock"))["included"]
@pytest.mark.parametrize(
"condition",
[
"lock.is_jammed",
"lock.is_locked",
"lock.is_open",
"lock.is_unlocked",
],
)
async def test_lock_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the lock 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("lock"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="lock.is_jammed",
target_states=[LockState.JAMMED],
other_states=other_states(LockState.JAMMED),
),
*parametrize_condition_states_any(
condition="lock.is_locked",
target_states=[LockState.LOCKED],
other_states=other_states(LockState.LOCKED),
),
*parametrize_condition_states_any(
condition="lock.is_open",
target_states=[LockState.OPEN],
other_states=other_states(LockState.OPEN),
),
*parametrize_condition_states_any(
condition="lock.is_unlocked",
target_states=[LockState.UNLOCKED],
other_states=other_states(LockState.UNLOCKED),
),
],
)
async def test_lock_state_condition_behavior_any(
hass: HomeAssistant,
target_locks: 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 lock state condition with the 'any' behavior."""
other_entity_ids = set(target_locks) - {entity_id}
# Set all locks, including the tested lock, to the initial state
for eid in target_locks:
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",
)
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 locks 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("lock"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="lock.is_jammed",
target_states=[LockState.JAMMED],
other_states=other_states(LockState.JAMMED),
),
*parametrize_condition_states_all(
condition="lock.is_locked",
target_states=[LockState.LOCKED],
other_states=other_states(LockState.LOCKED),
),
*parametrize_condition_states_all(
condition="lock.is_open",
target_states=[LockState.OPEN],
other_states=other_states(LockState.OPEN),
),
*parametrize_condition_states_all(
condition="lock.is_unlocked",
target_states=[LockState.UNLOCKED],
other_states=other_states(LockState.UNLOCKED),
),
],
)
async def test_lock_state_condition_behavior_all(
hass: HomeAssistant,
target_locks: 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 lock state condition with the 'all' behavior."""
other_entity_ids = set(target_locks) - {entity_id}
# Set all locks, including the tested lock, to the initial state
for eid in target_locks:
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/lock/test_condition.py",
"license": "Apache License 2.0",
"lines": 157,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/mastodon/test_binary_sensor.py | """Tests for the Mastodon binary sensors."""
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("mock_mastodon_client", "entity_registry_enabled_by_default")
async def test_binary_sensors(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the binary sensor entities."""
with patch("homeassistant.components.mastodon.PLATFORMS", [Platform.BINARY_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/mastodon/test_binary_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/media_player/test_condition.py | """Test media player conditions."""
from typing import Any
import pytest
from homeassistant.components.media_player.const import MediaPlayerState
from homeassistant.core import HomeAssistant
from tests.components import (
ConditionStateDescription,
assert_condition_gated_by_labs_flag,
create_target_condition,
other_states,
parametrize_condition_states_all,
parametrize_condition_states_any,
parametrize_target_entities,
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(
"condition",
[
"media_player.is_off",
"media_player.is_on",
"media_player.is_not_playing",
"media_player.is_paused",
"media_player.is_playing",
],
)
async def test_media_player_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the media player 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("media_player"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="media_player.is_off",
target_states=[MediaPlayerState.OFF],
other_states=other_states(MediaPlayerState.OFF),
),
*parametrize_condition_states_any(
condition="media_player.is_on",
target_states=[
MediaPlayerState.BUFFERING,
MediaPlayerState.IDLE,
MediaPlayerState.ON,
MediaPlayerState.PAUSED,
MediaPlayerState.PLAYING,
],
other_states=[MediaPlayerState.OFF],
),
*parametrize_condition_states_any(
condition="media_player.is_not_playing",
target_states=[
MediaPlayerState.BUFFERING,
MediaPlayerState.IDLE,
MediaPlayerState.OFF,
MediaPlayerState.ON,
MediaPlayerState.PAUSED,
],
other_states=[MediaPlayerState.PLAYING],
),
*parametrize_condition_states_any(
condition="media_player.is_paused",
target_states=[MediaPlayerState.PAUSED],
other_states=other_states(MediaPlayerState.PAUSED),
),
*parametrize_condition_states_any(
condition="media_player.is_playing",
target_states=[MediaPlayerState.PLAYING],
other_states=other_states(MediaPlayerState.PLAYING),
),
],
)
async def test_media_player_state_condition_behavior_any(
hass: HomeAssistant,
target_media_players: 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 media player state condition with the 'any' behavior."""
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()
condition = await create_target_condition(
hass,
condition=condition,
target=condition_target_config,
behavior="any",
)
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 media players 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("media_player"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="media_player.is_off",
target_states=[MediaPlayerState.OFF],
other_states=other_states(MediaPlayerState.OFF),
),
*parametrize_condition_states_all(
condition="media_player.is_on",
target_states=[
MediaPlayerState.BUFFERING,
MediaPlayerState.IDLE,
MediaPlayerState.ON,
MediaPlayerState.PAUSED,
MediaPlayerState.PLAYING,
],
other_states=[MediaPlayerState.OFF],
),
*parametrize_condition_states_all(
condition="media_player.is_not_playing",
target_states=[
MediaPlayerState.BUFFERING,
MediaPlayerState.IDLE,
MediaPlayerState.OFF,
MediaPlayerState.ON,
MediaPlayerState.PAUSED,
],
other_states=[MediaPlayerState.PLAYING],
),
*parametrize_condition_states_all(
condition="media_player.is_paused",
target_states=[MediaPlayerState.PAUSED],
other_states=other_states(MediaPlayerState.PAUSED),
),
*parametrize_condition_states_all(
condition="media_player.is_playing",
target_states=[MediaPlayerState.PLAYING],
other_states=other_states(MediaPlayerState.PLAYING),
),
],
)
async def test_media_player_state_condition_behavior_all(
hass: HomeAssistant,
target_media_players: 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 media player state condition with the 'all' behavior."""
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()
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/media_player/test_condition.py",
"license": "Apache License 2.0",
"lines": 192,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/mill/test_climate.py | """Tests for Mill climate."""
import contextlib
from contextlib import nullcontext
from unittest.mock import MagicMock, call, patch
from mill import Heater
from mill_local import OperationMode
import pytest
from homeassistant.components import mill
from homeassistant.components.climate import (
ATTR_HVAC_MODE,
DOMAIN as CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_TEMPERATURE,
HVACMode,
)
from homeassistant.components.mill.const import DOMAIN
from homeassistant.components.recorder import Recorder
from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from tests.common import MockConfigEntry
HEATER_ID = "dev_id"
HEATER_NAME = "heater_name"
ENTITY_CLIMATE = f"climate.{HEATER_NAME}"
TEST_SET_TEMPERATURE = 25
TEST_AMBIENT_TEMPERATURE = 20
NULL_EFFECT = nullcontext()
## MILL AND LOCAL MILL FIXTURES
@pytest.fixture
async def mock_mill():
"""Mock the mill.Mill object.
It is imported and initialized only in /homeassistant/components/mill/__init__.py
"""
with (
patch(
"homeassistant.components.mill.Mill",
autospec=True,
) as mock_mill_class,
):
mill = mock_mill_class.return_value
mill.connect.return_value = True
mill.fetch_heater_and_sensor_data.return_value = {}
mill.fetch_historic_energy_usage.return_value = {}
yield mill
@pytest.fixture
async def mock_mill_local():
"""Mock the mill_local.Mill object."""
with (
patch(
"homeassistant.components.mill.MillLocal",
autospec=True,
) as mock_mill_local_class,
):
milllocal = mock_mill_local_class.return_value
milllocal.url = "http://dummy.url"
milllocal.name = HEATER_NAME
milllocal.mac_address = "dead:beef"
milllocal.version = "0x210927"
milllocal.connect.return_value = {
"name": milllocal.name,
"mac_address": milllocal.mac_address,
"version": milllocal.version,
"operation_key": "",
"status": "ok",
}
status = {
"ambient_temperature": TEST_AMBIENT_TEMPERATURE,
"set_temperature": TEST_AMBIENT_TEMPERATURE,
"current_power": 0,
"control_signal": 0,
"raw_ambient_temperature": TEST_AMBIENT_TEMPERATURE,
"operation_mode": OperationMode.OFF.value,
}
milllocal.fetch_heater_and_sensor_data.return_value = status
milllocal._status = status
yield milllocal
## CLOUD HEATER INTEGRATION
@pytest.fixture
async def cloud_heater(hass: HomeAssistant, mock_mill: MagicMock) -> Heater:
"""Load Mill integration and creates one cloud heater."""
heater = Heater(
name=HEATER_NAME,
device_id=HEATER_ID,
available=True,
is_heating=False,
power_status=False,
current_temp=float(TEST_AMBIENT_TEMPERATURE),
set_temp=float(TEST_AMBIENT_TEMPERATURE),
)
devices = {HEATER_ID: heater}
mock_mill.fetch_heater_and_sensor_data.return_value = devices
mock_mill.devices = devices
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
mill.CONF_USERNAME: "user",
mill.CONF_PASSWORD: "pswd",
mill.CONNECTION_TYPE: mill.CLOUD,
},
)
config_entry.add_to_hass(hass)
# We just need to load the climate component.
with patch("homeassistant.components.mill.PLATFORMS", [Platform.CLIMATE]):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return heater
@pytest.fixture
async def cloud_heater_set_temp(mock_mill: MagicMock, cloud_heater: MagicMock):
"""Gets mock for the cloud heater `set_heater_temp` method."""
return mock_mill.set_heater_temp
@pytest.fixture
async def cloud_heater_control(mock_mill: MagicMock, cloud_heater: MagicMock):
"""Gets mock for the cloud heater `heater_control` method."""
return mock_mill.heater_control
@pytest.fixture
async def functional_cloud_heater(
cloud_heater: MagicMock,
cloud_heater_set_temp: MagicMock,
cloud_heater_control: MagicMock,
) -> Heater:
"""Make sure the cloud heater is "functional".
This will create a pseudo-functional cloud heater,
meaning that function calls will edit the original cloud heater
in a similar way that the API would.
"""
def calculate_heating():
if (
cloud_heater.power_status
and cloud_heater.set_temp > cloud_heater.current_temp
):
cloud_heater.is_heating = True
def set_temperature(device_id: str, set_temp: float):
assert device_id == HEATER_ID, "set_temperature called with wrong device_id"
cloud_heater.set_temp = set_temp
calculate_heating()
def heater_control(device_id: str, power_status: bool):
assert device_id == HEATER_ID, "set_temperature called with wrong device_id"
# power_status gives the "do we want to heat, Y/N", while is_heating is based on temperature and internal state and whatnot.
cloud_heater.power_status = power_status
calculate_heating()
cloud_heater_set_temp.side_effect = set_temperature
cloud_heater_control.side_effect = heater_control
return cloud_heater
## LOCAL HEATER INTEGRATION
@pytest.fixture
async def local_heater(hass: HomeAssistant, mock_mill_local: MagicMock) -> dict:
"""Local Mill Heater.
This returns a by-reference status dict
with which this heater's information is organised and updated.
"""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
mill.CONF_IP_ADDRESS: "192.168.1.59",
mill.CONNECTION_TYPE: mill.LOCAL,
},
)
config_entry.add_to_hass(hass)
# We just need to load the climate component.
with patch("homeassistant.components.mill.PLATFORMS", [Platform.CLIMATE]):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return mock_mill_local._status
@pytest.fixture
async def local_heater_set_target_temperature(
mock_mill_local: MagicMock, local_heater: MagicMock
):
"""Gets mock for the local heater `set_target_temperature` method."""
return mock_mill_local.set_target_temperature
@pytest.fixture
async def local_heater_set_mode_control_individually(
mock_mill_local: MagicMock, local_heater: MagicMock
):
"""Gets mock for the local heater `set_operation_mode_control_individually` method."""
return mock_mill_local.set_operation_mode_control_individually
@pytest.fixture
async def local_heater_set_mode_off(
mock_mill_local: MagicMock, local_heater: MagicMock
):
"""Gets mock for the local heater `set_operation_mode_off` method."""
return mock_mill_local.set_operation_mode_off
@pytest.fixture
async def functional_local_heater(
mock_mill_local: MagicMock,
local_heater_set_target_temperature: MagicMock,
local_heater_set_mode_control_individually: MagicMock,
local_heater_set_mode_off: MagicMock,
local_heater: MagicMock,
) -> None:
"""Make sure the local heater is "functional".
This will create a pseudo-functional local heater,
meaning that function calls will edit the original local heater
in a similar way that the API would.
"""
def set_temperature(target_temperature: float):
local_heater["set_temperature"] = target_temperature
def set_operation_mode(operation_mode: OperationMode):
local_heater["operation_mode"] = operation_mode.value
def mode_control_individually():
set_operation_mode(OperationMode.CONTROL_INDIVIDUALLY)
def mode_off():
set_operation_mode(OperationMode.OFF)
local_heater_set_target_temperature.side_effect = set_temperature
local_heater_set_mode_control_individually.side_effect = mode_control_individually
local_heater_set_mode_off.side_effect = mode_off
### CLOUD
@pytest.mark.parametrize(
(
"before_state",
"before_attrs",
"service_name",
"service_params",
"effect",
"heater_control_calls",
"heater_set_temp_calls",
"after_state",
"after_attrs",
),
[
# set_hvac_mode
(
HVACMode.OFF,
{},
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.HEAT},
NULL_EFFECT,
[call(HEATER_ID, power_status=True)],
[],
HVACMode.HEAT,
{},
),
(
HVACMode.OFF,
{},
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.OFF},
NULL_EFFECT,
[call(HEATER_ID, power_status=False)],
[],
HVACMode.OFF,
{},
),
(
HVACMode.OFF,
{},
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.COOL},
pytest.raises(HomeAssistantError),
[],
[],
HVACMode.OFF,
{},
),
# set_temperature (with hvac mode)
(
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE, ATTR_HVAC_MODE: HVACMode.HEAT},
NULL_EFFECT,
[call(HEATER_ID, power_status=True)],
[call(HEATER_ID, float(TEST_SET_TEMPERATURE))],
HVACMode.HEAT,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE},
),
(
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE, ATTR_HVAC_MODE: HVACMode.OFF},
NULL_EFFECT,
[call(HEATER_ID, power_status=False)],
[call(HEATER_ID, float(TEST_SET_TEMPERATURE))],
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE},
),
(
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE},
NULL_EFFECT,
[],
[call(HEATER_ID, float(TEST_SET_TEMPERATURE))],
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE},
),
(
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE, ATTR_HVAC_MODE: HVACMode.COOL},
pytest.raises(HomeAssistantError),
# MillHeater will set the temperature before calling async_handle_set_hvac_mode,
# meaning an invalid HVAC mode will raise only after the temperature is set.
[],
[call(HEATER_ID, float(TEST_SET_TEMPERATURE))],
HVACMode.OFF,
# likewise, in this test, it hasn't had the chance to update its ambient temperature,
# because the exception is raised before a refresh can be requested from the coordinator
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
),
],
)
async def test_cloud_heater(
recorder_mock: Recorder,
hass: HomeAssistant,
functional_cloud_heater: MagicMock,
cloud_heater_control: MagicMock,
cloud_heater_set_temp: MagicMock,
before_state: HVACMode,
before_attrs: dict,
service_name: str,
service_params: dict,
effect: contextlib.AbstractContextManager,
heater_control_calls: list,
heater_set_temp_calls: list,
after_state: HVACMode,
after_attrs: dict,
) -> None:
"""Tests setting HVAC mode (directly or through set_temperature) for a cloud heater."""
state = hass.states.get(ENTITY_CLIMATE)
assert state is not None
assert state.state == before_state
for attr, value in before_attrs.items():
assert state.attributes.get(attr) == value
with effect:
await hass.services.async_call(
CLIMATE_DOMAIN,
service_name,
service_params | {ATTR_ENTITY_ID: ENTITY_CLIMATE},
blocking=True,
)
await hass.async_block_till_done()
cloud_heater_control.assert_has_calls(heater_control_calls)
cloud_heater_set_temp.assert_has_calls(heater_set_temp_calls)
state = hass.states.get(ENTITY_CLIMATE)
assert state is not None
assert state.state == after_state
for attr, value in after_attrs.items():
assert state.attributes.get(attr) == value
### LOCAL
@pytest.mark.parametrize(
(
"before_state",
"before_attrs",
"service_name",
"service_params",
"effect",
"heater_mode_set_individually_calls",
"heater_mode_set_off_calls",
"heater_set_target_temperature_calls",
"after_state",
"after_attrs",
),
[
# set_hvac_mode
(
HVACMode.OFF,
{},
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.HEAT},
NULL_EFFECT,
[call()],
[],
[],
HVACMode.HEAT,
{},
),
(
HVACMode.OFF,
{},
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.OFF},
NULL_EFFECT,
[],
[call()],
[],
HVACMode.OFF,
{},
),
(
HVACMode.OFF,
{},
SERVICE_SET_HVAC_MODE,
{ATTR_HVAC_MODE: HVACMode.COOL},
pytest.raises(HomeAssistantError),
[],
[],
[],
HVACMode.OFF,
{},
),
# set_temperature (with hvac mode)
(
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE, ATTR_HVAC_MODE: HVACMode.HEAT},
NULL_EFFECT,
[call()],
[],
[call(float(TEST_SET_TEMPERATURE))],
HVACMode.HEAT,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE},
),
(
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE, ATTR_HVAC_MODE: HVACMode.OFF},
NULL_EFFECT,
[],
[call()],
[call(float(TEST_SET_TEMPERATURE))],
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE},
),
(
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE},
NULL_EFFECT,
[],
[],
[call(float(TEST_SET_TEMPERATURE))],
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE},
),
(
HVACMode.OFF,
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
SERVICE_SET_TEMPERATURE,
{ATTR_TEMPERATURE: TEST_SET_TEMPERATURE, ATTR_HVAC_MODE: HVACMode.COOL},
pytest.raises(HomeAssistantError),
# LocalMillHeater will set the temperature before calling async_handle_set_hvac_mode,
# meaning an invalid HVAC mode will raise only after the temperature is set.
[],
[],
[call(float(TEST_SET_TEMPERATURE))],
HVACMode.OFF,
# likewise, in this test, it hasn't had the chance to update its ambient temperature,
# because the exception is raised before a refresh can be requested from the coordinator
{ATTR_TEMPERATURE: TEST_AMBIENT_TEMPERATURE},
),
],
)
async def test_local_heater(
hass: HomeAssistant,
functional_local_heater: MagicMock,
local_heater_set_mode_control_individually: MagicMock,
local_heater_set_mode_off: MagicMock,
local_heater_set_target_temperature: MagicMock,
before_state: HVACMode,
before_attrs: dict,
service_name: str,
service_params: dict,
effect: contextlib.AbstractContextManager,
heater_mode_set_individually_calls: list,
heater_mode_set_off_calls: list,
heater_set_target_temperature_calls: list,
after_state: HVACMode,
after_attrs: dict,
) -> None:
"""Tests setting HVAC mode (directly or through set_temperature) for a local heater."""
state = hass.states.get(ENTITY_CLIMATE)
assert state is not None
assert state.state == before_state
for attr, value in before_attrs.items():
assert state.attributes.get(attr) == value
with effect:
await hass.services.async_call(
CLIMATE_DOMAIN,
service_name,
service_params | {ATTR_ENTITY_ID: ENTITY_CLIMATE},
blocking=True,
)
await hass.async_block_till_done()
local_heater_set_mode_control_individually.assert_has_calls(
heater_mode_set_individually_calls
)
local_heater_set_mode_off.assert_has_calls(heater_mode_set_off_calls)
local_heater_set_target_temperature.assert_has_calls(
heater_set_target_temperature_calls
)
state = hass.states.get(ENTITY_CLIMATE)
assert state is not None
assert state.state == after_state
for attr, value in after_attrs.items():
assert state.attributes.get(attr) == value
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/mill/test_climate.py",
"license": "Apache License 2.0",
"lines": 491,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/namecheapdns/test_config_flow.py | """Test the Namecheap DynamicDNS config flow."""
from unittest.mock import AsyncMock
from aiohttp import ClientError
import pytest
from homeassistant.components.namecheapdns.const import DOMAIN, UPDATE_URL
from homeassistant.components.namecheapdns.helpers import AuthFailed
from homeassistant.config_entries import (
SOURCE_IMPORT,
SOURCE_REAUTH,
SOURCE_USER,
ConfigEntryState,
)
from homeassistant.const import CONF_PASSWORD
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 TEST_USER_INPUT
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.mark.usefixtures("mock_namecheap")
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"], TEST_USER_INPUT
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "home.example.com"
assert result["data"] == TEST_USER_INPUT
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("side_effect", "text_error"),
[
(ValueError, "unknown"),
(False, "update_failed"),
(ClientError, "cannot_connect"),
],
)
async def test_form_errors(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_namecheap: AsyncMock,
side_effect: Exception | bool,
text_error: str,
) -> None:
"""Test we handle errors."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_namecheap.side_effect = [side_effect]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_USER_INPUT
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
mock_namecheap.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], TEST_USER_INPUT
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "home.example.com"
assert result["data"] == TEST_USER_INPUT
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_namecheap")
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=TEST_USER_INPUT,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "home.example.com"
assert result["data"] == TEST_USER_INPUT
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_exception(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
issue_registry: ir.IssueRegistry,
mock_namecheap: AsyncMock,
) -> None:
"""Test import flow failed."""
mock_namecheap.side_effect = [False]
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=TEST_USER_INPUT,
)
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",
)
@pytest.mark.usefixtures("mock_namecheap")
async def test_init_import_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
) -> None:
"""Test yaml triggers import flow."""
await async_setup_component(
hass,
DOMAIN,
{DOMAIN: TEST_USER_INPUT},
)
assert len(mock_setup_entry.mock_calls) == 1
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
@pytest.mark.usefixtures("mock_namecheap")
async def test_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_PASSWORD: "new-password"}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert config_entry.data[CONF_PASSWORD] == "new-password"
@pytest.mark.parametrize(
("side_effect", "text_error"),
[
(ValueError, "unknown"),
(False, "update_failed"),
(ClientError, "cannot_connect"),
(AuthFailed, "invalid_auth"),
],
)
async def test_reconfigure_errors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_namecheap: AsyncMock,
side_effect: 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_namecheap.side_effect = [side_effect]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "new-password"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
mock_namecheap.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"] == "reconfigure_successful"
assert config_entry.data[CONF_PASSWORD] == "new-password"
@pytest.mark.usefixtures("mock_namecheap")
async def test_reauth(
hass: HomeAssistant,
config_entry: MockConfigEntry,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test reauth flow."""
aioclient_mock.get(
UPDATE_URL,
params=TEST_USER_INPUT,
text="<interface-response><ErrCount>0</ErrCount></interface-response>",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "new-password"}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert config_entry.data[CONF_PASSWORD] == "new-password"
@pytest.mark.parametrize(
("side_effect", "text_error"),
[
(ValueError, "unknown"),
(False, "update_failed"),
(ClientError, "cannot_connect"),
(AuthFailed, "invalid_auth"),
],
)
async def test_reauth_errors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_namecheap: AsyncMock,
side_effect: Exception | bool,
text_error: str,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test we handle errors."""
aioclient_mock.get(
UPDATE_URL,
params=TEST_USER_INPUT,
text="<interface-response><ErrCount>0</ErrCount></interface-response>",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
mock_namecheap.side_effect = [side_effect]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "new-password"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
mock_namecheap.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 config_entry.data[CONF_PASSWORD] == "new-password"
async def test_initiate_reauth_flow(
hass: HomeAssistant,
config_entry: MockConfigEntry,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test authentication error initiates reauth flow."""
aioclient_mock.get(
UPDATE_URL,
params=TEST_USER_INPUT,
text="<interface-response><ErrCount>1</ErrCount><errors><Err1>Passwords do not match</Err1></errors></interface-response>",
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
flow = flows[0]
assert flow.get("step_id") == "reauth_confirm"
assert flow.get("handler") == DOMAIN
assert "context" in flow
assert flow["context"].get("source") == SOURCE_REAUTH
assert flow["context"].get("entry_id") == config_entry.entry_id
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/namecheapdns/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 266,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nina/const.py | """Common constants for NINA tests."""
from copy import deepcopy
from typing import Any
from homeassistant.components.nina.const import (
CONF_AREA_FILTER,
CONF_FILTERS,
CONF_HEADLINE_FILTER,
CONF_MESSAGE_SLOTS,
CONF_REGIONS,
CONST_REGION_A_TO_D,
CONST_REGION_E_TO_H,
CONST_REGION_I_TO_L,
CONST_REGION_M_TO_Q,
CONST_REGION_R_TO_U,
CONST_REGION_V_TO_Z,
)
DUMMY_USER_INPUT: dict[str, Any] = {
CONF_MESSAGE_SLOTS: 5,
CONST_REGION_A_TO_D: ["095760000000_0", "095760000000_1"],
CONST_REGION_E_TO_H: ["160650000000_14", "146260000000_0"],
CONST_REGION_I_TO_L: ["083370000000_22", "055660000000_5"],
CONST_REGION_M_TO_Q: ["010590000000_25", "032510000000_40"],
CONST_REGION_R_TO_U: ["010560000000_16", "010590000000_94"],
CONST_REGION_V_TO_Z: ["010610000000_73", "010610000000_74"],
CONF_FILTERS: {
CONF_HEADLINE_FILTER: ".*corona.*",
CONF_AREA_FILTER: ".*",
},
}
DUMMY_CONFIG_ENTRY: dict[str, Any] = {
CONF_FILTERS: deepcopy(DUMMY_USER_INPUT[CONF_FILTERS]),
CONF_MESSAGE_SLOTS: deepcopy(DUMMY_USER_INPUT[CONF_MESSAGE_SLOTS]),
CONST_REGION_A_TO_D: deepcopy(DUMMY_USER_INPUT[CONST_REGION_A_TO_D]),
CONF_REGIONS: {"095760000000": "Aach"},
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nina/const.py",
"license": "Apache License 2.0",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nrgkick/test_config_flow.py | """Tests for the NRGkick config flow."""
from __future__ import annotations
from ipaddress import ip_address
from typing import Any
from unittest.mock import AsyncMock
from nrgkick_api import (
NRGkickAPIDisabledError,
NRGkickAuthenticationError,
NRGkickConnectionError,
)
import pytest
from homeassistant.components.nrgkick.api import (
NRGkickApiClientError,
NRGkickApiClientInvalidResponseError,
)
from homeassistant.components.nrgkick.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from tests.common import MockConfigEntry
ZEROCONF_DISCOVERY_INFO = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.101"),
ip_addresses=[ip_address("192.168.1.101")],
hostname="nrgkick.local.",
name="NRGkick Test._nrgkick._tcp.local.",
port=80,
properties={
"serial_number": "TEST123456",
"device_name": "NRGkick Test",
"model_type": "NRGkick Gen2",
"json_api_enabled": "1",
"json_api_version": "v1",
},
type="_nrgkick._tcp.local.",
)
ZEROCONF_DISCOVERY_INFO_DISABLED_JSON_API = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.101"),
ip_addresses=[ip_address("192.168.1.101")],
hostname="nrgkick.local.",
name="NRGkick Test._nrgkick._tcp.local.",
port=80,
properties={
"serial_number": "TEST123456",
"device_name": "NRGkick Test",
"model_type": "NRGkick Gen2",
"json_api_enabled": "0",
"json_api_version": "v1",
},
type="_nrgkick._tcp.local.",
)
ZEROCONF_DISCOVERY_INFO_NO_SERIAL = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.101"),
ip_addresses=[ip_address("192.168.1.101")],
hostname="nrgkick.local.",
name="NRGkick Test._nrgkick._tcp.local.",
port=80,
properties={
"device_name": "NRGkick Test",
"model_type": "NRGkick Gen2",
"json_api_enabled": "1",
"json_api_version": "v1",
},
type="_nrgkick._tcp.local.",
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_user_flow(hass: HomeAssistant, mock_nrgkick_api: AsyncMock) -> None:
"""Test we can set up successfully without credentials."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "NRGkick Test"
assert result["data"] == {CONF_HOST: "192.168.1.100"}
assert result["result"].unique_id == "TEST123456"
async def test_user_flow_with_credentials(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test we can setup when authentication is required."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
mock_nrgkick_api.test_connection.side_effect = NRGkickAuthenticationError
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user_auth"
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_USERNAME: "test_user", CONF_PASSWORD: "test_pass"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "NRGkick Test"
assert result["data"] == {
CONF_HOST: "192.168.1.100",
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_pass",
}
assert result["result"].unique_id == "TEST123456"
mock_setup_entry.assert_called_once()
@pytest.mark.parametrize("url", ["http://", ""])
async def test_form_invalid_host_input(
hass: HomeAssistant,
mock_nrgkick_api: AsyncMock,
mock_setup_entry: AsyncMock,
url: str,
) -> None:
"""Test we handle invalid host input during normalization."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: url}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.usefixtures("mock_setup_entry")
async def test_form_fallback_title_when_device_name_missing(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock
) -> None:
"""Test we fall back to a default title when device name is missing."""
mock_nrgkick_api.get_info.return_value = {"general": {"serial_number": "ABC"}}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "NRGkick"
assert result["data"] == {CONF_HOST: "192.168.1.100"}
@pytest.mark.usefixtures("mock_setup_entry")
async def test_form_invalid_response_when_serial_missing(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock, mock_info_data: dict[str, Any]
) -> None:
"""Test we handle invalid device info response."""
mock_nrgkick_api.get_info.return_value = {"general": {"device_name": "NRGkick"}}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.100"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "invalid_response"}
mock_nrgkick_api.get_info.return_value = mock_info_data
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.100"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
("exception", "error"),
[
(NRGkickAPIDisabledError, "json_api_disabled"),
(NRGkickApiClientInvalidResponseError, "invalid_response"),
(NRGkickConnectionError, "cannot_connect"),
(NRGkickApiClientError, "unknown"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_user_flow_errors(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock, exception: Exception, error: str
) -> None:
"""Test errors are handled and the flow can recover to CREATE_ENTRY."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_nrgkick_api.test_connection.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": error}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
("exception", "error"),
[
(NRGkickAPIDisabledError, "json_api_disabled"),
(NRGkickAuthenticationError, "invalid_auth"),
(NRGkickApiClientInvalidResponseError, "invalid_response"),
(NRGkickConnectionError, "cannot_connect"),
(NRGkickApiClientError, "unknown"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_user_flow_auth_errors(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock, exception: Exception, error: str
) -> None:
"""Test errors are handled and the flow can recover to CREATE_ENTRY."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_nrgkick_api.test_connection.side_effect = NRGkickAuthenticationError
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user_auth"
assert result["errors"] == {}
mock_nrgkick_api.test_connection.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "user", CONF_PASSWORD: "pass"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user_auth"
assert result["errors"] == {"base": error}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "user", CONF_PASSWORD: "pass"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_user_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_nrgkick_api: AsyncMock
) -> None:
"""Test we handle already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_user_auth_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_nrgkick_api: AsyncMock
) -> None:
"""Test we handle already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_nrgkick_api.test_connection.side_effect = NRGkickAuthenticationError
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user_auth"
assert result["errors"] == {}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "user", CONF_PASSWORD: "pass"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("mock_setup_entry")
async def test_zeroconf_discovery(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock
) -> None:
"""Test zeroconf discovery without credentials."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_confirm"
assert result["description_placeholders"] == {
"name": "NRGkick Test",
"device_ip": "192.168.1.101",
}
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {CONF_HOST: "192.168.1.101"}
assert result["result"].unique_id == "TEST123456"
async def test_zeroconf_discovery_with_credentials(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test zeroconf discovery flow (auth required)."""
mock_nrgkick_api.test_connection.side_effect = NRGkickAuthenticationError
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user_auth"
assert result["description_placeholders"] == {"device_ip": "192.168.1.101"}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "test_user", CONF_PASSWORD: "test_pass"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "NRGkick Test"
assert result["data"] == {
CONF_HOST: "192.168.1.101",
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_pass",
}
assert result["result"].unique_id == "TEST123456"
mock_setup_entry.assert_called_once()
@pytest.mark.parametrize(
("exception", "reason"),
[
(NRGkickConnectionError, "cannot_connect"),
(NRGkickApiClientInvalidResponseError, "cannot_connect"),
(NRGkickApiClientError, "unknown"),
],
)
async def test_zeroconf_errors(
hass: HomeAssistant,
mock_nrgkick_api: AsyncMock,
exception: Exception,
reason: str,
) -> None:
"""Test zeroconf confirm step reports errors."""
mock_nrgkick_api.test_connection.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == reason
async def test_zeroconf_already_configured(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test zeroconf discovery when device is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_DISCOVERY_INFO
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_config_entry.data[CONF_HOST] == "192.168.1.101"
@pytest.mark.usefixtures("mock_setup_entry")
async def test_zeroconf_json_api_disabled(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock
) -> None:
"""Test zeroconf discovery when JSON API is disabled."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO_DISABLED_JSON_API,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_enable_json_api"
assert result["description_placeholders"] == {
"name": "NRGkick Test",
"device_ip": "192.168.1.101",
}
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "NRGkick Test"
assert result["data"] == {CONF_HOST: "192.168.1.101"}
assert result["result"].unique_id == "TEST123456"
@pytest.mark.usefixtures("mock_setup_entry")
async def test_zeroconf_json_api_disabled_stale_mdns(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock
) -> None:
"""Test zeroconf discovery when JSON API is disabled."""
mock_nrgkick_api.test_connection.side_effect = NRGkickAPIDisabledError
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_enable_json_api"
assert result["description_placeholders"] == {
"name": "NRGkick Test",
"device_ip": "192.168.1.101",
}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "NRGkick Test"
assert result["data"] == {CONF_HOST: "192.168.1.101"}
assert result["result"].unique_id == "TEST123456"
@pytest.mark.parametrize(
("exception", "error"),
[
(NRGkickAPIDisabledError, "json_api_disabled"),
(NRGkickApiClientInvalidResponseError, "invalid_response"),
(NRGkickConnectionError, "cannot_connect"),
(NRGkickApiClientError, "unknown"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_zeroconf_json_api_disabled_errors(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock, exception: Exception, error: str
) -> None:
"""Test zeroconf discovery when JSON API is disabled."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO_DISABLED_JSON_API,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_enable_json_api"
assert result["description_placeholders"] == {
"name": "NRGkick Test",
"device_ip": "192.168.1.101",
}
mock_nrgkick_api.test_connection.side_effect = exception
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_enable_json_api"
assert result["errors"] == {"base": error}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "NRGkick Test"
assert result["data"] == {CONF_HOST: "192.168.1.101"}
assert result["result"].unique_id == "TEST123456"
@pytest.mark.usefixtures("mock_setup_entry")
async def test_zeroconf_json_api_disabled_with_credentials(
hass: HomeAssistant, mock_nrgkick_api: AsyncMock
) -> None:
"""Test JSON API disabled flow that requires authentication afterwards."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO_DISABLED_JSON_API,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_enable_json_api"
mock_nrgkick_api.test_connection.side_effect = NRGkickAuthenticationError
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user_auth"
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_USERNAME: "user", CONF_PASSWORD: "pass"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_HOST: "192.168.1.101",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
}
@pytest.mark.parametrize(
("exception", "error"),
[
(NRGkickAPIDisabledError, "json_api_disabled"),
(NRGkickAuthenticationError, "invalid_auth"),
(NRGkickConnectionError, "cannot_connect"),
(NRGkickApiClientError, "unknown"),
],
)
async def test_zeroconf_enable_json_api_auth_errors(
hass: HomeAssistant, mock_nrgkick_api, exception: Exception, error: str
) -> None:
"""Test JSON API enable auth step reports errors."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO_DISABLED_JSON_API,
)
mock_nrgkick_api.test_connection.side_effect = NRGkickAuthenticationError
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user_auth"
assert result["errors"] == {}
mock_nrgkick_api.test_connection.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_USERNAME: "user", CONF_PASSWORD: "pass"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_USERNAME: "user", CONF_PASSWORD: "pass"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
("exception", "error"),
[
(NRGkickAuthenticationError, "invalid_auth"),
(NRGkickConnectionError, "cannot_connect"),
(NRGkickAPIDisabledError, "json_api_disabled"),
(NRGkickApiClientError, "unknown"),
],
)
async def test_zeroconf_auth_errors(
hass: HomeAssistant,
mock_nrgkick_api: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test zeroconf auth step reports errors."""
mock_nrgkick_api.test_connection.side_effect = NRGkickAuthenticationError
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user_auth"
mock_nrgkick_api.test_connection.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_USERNAME: "user", CONF_PASSWORD: "pass"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_USERNAME: "user", CONF_PASSWORD: "pass"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_zeroconf_no_serial_number(hass: HomeAssistant) -> None:
"""Test zeroconf discovery without serial number."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY_INFO_NO_SERIAL,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_serial_number"
@pytest.mark.usefixtures("mock_setup_entry")
async def test_reauth_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test reauthentication flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "new_user", CONF_PASSWORD: "new_pass"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_HOST] == "192.168.1.100"
assert mock_config_entry.data[CONF_USERNAME] == "new_user"
assert mock_config_entry.data[CONF_PASSWORD] == "new_pass"
@pytest.mark.parametrize(
("exception", "error"),
[
(NRGkickAPIDisabledError, "json_api_disabled"),
(NRGkickAuthenticationError, "invalid_auth"),
(NRGkickApiClientInvalidResponseError, "invalid_response"),
(NRGkickConnectionError, "cannot_connect"),
(NRGkickApiClientError, "unknown"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_reauth_flow_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test reauthentication flow error handling and recovery."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
mock_nrgkick_api.test_connection.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "user", CONF_PASSWORD: "pass"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": error}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "user", CONF_PASSWORD: "pass"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
@pytest.mark.usefixtures("mock_setup_entry")
async def test_reauth_flow_unique_id_mismatch(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test reauthentication aborts on unique ID mismatch."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
mock_nrgkick_api.get_info.return_value = {
"general": {"serial_number": "DIFFERENT123", "device_name": "Other"}
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "user", CONF_PASSWORD: "pass"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
@pytest.mark.usefixtures("mock_setup_entry")
async def test_reconfigure_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test reconfiguration flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: ""}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {"base": "cannot_connect"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.200"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "192.168.1.200"
@pytest.mark.usefixtures("mock_setup_entry")
async def test_reconfigure_flow_with_credentials(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test reconfiguration flow when authentication is required."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_nrgkick_api.test_connection.side_effect = NRGkickAuthenticationError
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.200"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure_auth"
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "new_user", CONF_PASSWORD: "new_pass"},
)
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] == "new_user"
assert mock_config_entry.data[CONF_PASSWORD] == "new_pass"
@pytest.mark.parametrize(
("exception", "error"),
[
(NRGkickAPIDisabledError, "json_api_disabled"),
(NRGkickApiClientInvalidResponseError, "invalid_response"),
(NRGkickConnectionError, "cannot_connect"),
(NRGkickApiClientError, "unknown"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_reconfigure_flow_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test reconfiguration flow errors and recovery."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
mock_nrgkick_api.test_connection.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.200"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {"base": error}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.200"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
@pytest.mark.parametrize(
("exception", "error"),
[
(NRGkickAPIDisabledError, "json_api_disabled"),
(NRGkickAuthenticationError, "invalid_auth"),
(NRGkickApiClientInvalidResponseError, "invalid_response"),
(NRGkickConnectionError, "cannot_connect"),
(NRGkickApiClientError, "unknown"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_reconfigure_flow_auth_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test reconfiguration auth step errors and recovery."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
mock_nrgkick_api.test_connection.side_effect = NRGkickAuthenticationError
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.200"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure_auth"
mock_nrgkick_api.test_connection.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "user", CONF_PASSWORD: "pass"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure_auth"
assert result["errors"] == {"base": error}
mock_nrgkick_api.test_connection.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "user", CONF_PASSWORD: "pass"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
@pytest.mark.usefixtures("mock_setup_entry")
async def test_reconfigure_flow_unique_id_mismatch(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test reconfiguration aborts on unique ID mismatch."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_nrgkick_api.get_info.return_value = {
"general": {"serial_number": "DIFFERENT123", "device_name": "Other"}
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.200"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nrgkick/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 762,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nrgkick/test_init.py | """Tests for the NRGkick integration initialization."""
from __future__ import annotations
from unittest.mock import AsyncMock
from nrgkick_api import (
NRGkickAPIDisabledError,
NRGkickAuthenticationError,
NRGkickConnectionError,
)
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.nrgkick.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_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test successful load and unload of 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
@pytest.mark.parametrize(
("exception", "state"),
[
(NRGkickAuthenticationError, ConfigEntryState.SETUP_ERROR),
(NRGkickAPIDisabledError, ConfigEntryState.SETUP_ERROR),
(NRGkickConnectionError, ConfigEntryState.SETUP_RETRY),
(TimeoutError, ConfigEntryState.SETUP_RETRY),
(OSError, ConfigEntryState.SETUP_RETRY),
],
)
async def test_entry_setup_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
exception: Exception,
state: ConfigEntryState,
) -> None:
"""Test setup entry with failed connection."""
mock_nrgkick_api.get_info.side_effect = exception
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is state
async def test_device(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test successful load and unload of entry."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(
identifiers={(DOMAIN, mock_config_entry.unique_id)}
)
assert device is not None
assert device == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nrgkick/test_init.py",
"license": "Apache License 2.0",
"lines": 62,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nrgkick/test_sensor.py | """Tests for the NRGkick sensor platform."""
from __future__ import annotations
from unittest.mock import AsyncMock
from nrgkick_api import ChargingStatus, ConnectorType
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import STATE_UNKNOWN, 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
pytestmark = pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.freeze_time("2023-10-21")
async def test_sensor_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test sensor entities."""
await setup_integration(hass, mock_config_entry, platforms=[Platform.SENSOR])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_mapped_unknown_values_become_state_unknown(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test that enum-like UNKNOWN values map to HA's unknown state."""
mock_nrgkick_api.get_info.return_value["connector"]["type"] = ConnectorType.UNKNOWN
mock_nrgkick_api.get_values.return_value["general"]["status"] = (
ChargingStatus.UNKNOWN
)
await setup_integration(hass, mock_config_entry, platforms=[Platform.SENSOR])
assert (state := hass.states.get("sensor.nrgkick_test_connector_type"))
assert state.state == STATE_UNKNOWN
assert (state := hass.states.get("sensor.nrgkick_test_status"))
assert state.state == STATE_UNKNOWN
async def test_cellular_and_gps_entities_are_gated_by_model_type(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test that cellular entities are only created for SIM-capable models."""
mock_nrgkick_api.get_info.return_value["general"]["model_type"] = "NRGkick Gen2"
await setup_integration(hass, mock_config_entry, platforms=[Platform.SENSOR])
assert hass.states.get("sensor.nrgkick_test_cellular_mode") is None
assert hass.states.get("sensor.nrgkick_test_cellular_signal_strength") is None
assert hass.states.get("sensor.nrgkick_test_cellular_operator") is None
async def test_vehicle_connected_since_none_when_standby(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test vehicle connected since is unknown when vehicle is not connected."""
mock_nrgkick_api.get_values.return_value["general"]["status"] = (
ChargingStatus.STANDBY
)
await setup_integration(hass, mock_config_entry, platforms=[Platform.SENSOR])
assert (state := hass.states.get("sensor.nrgkick_test_vehicle_connected_since"))
assert state.state == STATE_UNKNOWN
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nrgkick/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/openevse/test_config_flow.py | """Tests for the OpenEVSE sensor platform."""
from ipaddress import ip_address
from unittest.mock import AsyncMock, MagicMock
from openevsehttp.exceptions import AuthenticationError, MissingSerial
from homeassistant.components.openevse.const import DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from tests.common import MockConfigEntry
async def test_user_flow(
hass: HomeAssistant,
mock_charger: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test user flow create entry with bad charger."""
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_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "OpenEVSE 10.0.0.131"
assert result["data"] == {CONF_HOST: "10.0.0.131"}
assert result["result"].unique_id == "deadbeeffeed"
async def test_user_flow_flaky(
hass: HomeAssistant,
mock_charger: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test user flow create entry with flaky charger."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
mock_charger.test_and_get.side_effect = TimeoutError
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
mock_charger.test_and_get.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "OpenEVSE 10.0.0.131"
assert result["data"] == {CONF_HOST: "10.0.0.131"}
assert result["result"].unique_id == "deadbeeffeed"
async def test_user_flow_duplicate(
hass: HomeAssistant,
mock_config_entry: MagicMock,
mock_charger: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test user flow aborts when config entry already exists."""
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_HOST: "192.168.1.100"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_user_flow_no_serial(
hass: HomeAssistant,
mock_charger: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test user flow handles missing serial gracefully."""
mock_charger.test_and_get.side_effect = [{}, MissingSerial]
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "OpenEVSE 10.0.0.131"
assert result["result"].unique_id is None
async def test_import_flow_no_serial(
hass: HomeAssistant,
mock_charger: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test import flow handles missing serial gracefully."""
mock_charger.test_and_get.side_effect = [{}, MissingSerial]
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_HOST: "10.0.0.131"}
)
# Assert the flow continued to create the entry
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "OpenEVSE 10.0.0.131"
assert result["result"].unique_id is None
async def test_user_flow_with_auth(
hass: HomeAssistant,
mock_charger: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test user flow create entry with authentication."""
mock_charger.test_and_get.side_effect = [
AuthenticationError,
{"serial": "deadbeeffeed"},
]
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_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "fakeuser", CONF_PASSWORD: "muchpassword"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "OpenEVSE 10.0.0.131"
assert result["data"] == {
CONF_HOST: "10.0.0.131",
CONF_USERNAME: "fakeuser",
CONF_PASSWORD: "muchpassword",
}
assert result["result"].unique_id == "deadbeeffeed"
async def test_user_flow_with_auth_error(
hass: HomeAssistant, mock_charger: MagicMock
) -> None:
"""Test user flow create entry with authentication error."""
mock_charger.test_and_get.side_effect = [
AuthenticationError,
AuthenticationError,
{},
]
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_HOST: "10.0.0.131"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "fakeuser", CONF_PASSWORD: "muchpassword"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "invalid_auth"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "fakeuser", CONF_PASSWORD: "muchpassword"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_user_flow_with_missing_serial(
hass: HomeAssistant, mock_charger: MagicMock
) -> None:
"""Test user flow create entry with authentication error."""
mock_charger.test_and_get.side_effect = [AuthenticationError, MissingSerial]
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_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "fakeuser", CONF_PASSWORD: "muchpassword"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "OpenEVSE 10.0.0.131"
assert result["data"] == {
CONF_HOST: "10.0.0.131",
CONF_USERNAME: "fakeuser",
CONF_PASSWORD: "muchpassword",
}
assert result["result"].unique_id is None
async def test_import_flow(
hass: HomeAssistant,
mock_charger: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test import flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "OpenEVSE 10.0.0.131"
assert result["data"] == {CONF_HOST: "10.0.0.131"}
assert result["result"].unique_id == "deadbeeffeed"
async def test_import_flow_bad(
hass: HomeAssistant,
mock_charger: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test import flow with bad charger."""
mock_charger.test_and_get.side_effect = TimeoutError
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unavailable_host"
async def test_import_flow_duplicate(
hass: HomeAssistant,
mock_config_entry: MagicMock,
mock_charger: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test import flow aborts when config entry already exists."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_HOST: "192.168.1.100"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_zeroconf_discovery(
hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_charger: MagicMock
) -> None:
"""Test zeroconf discovery."""
discovery_info = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.123"),
ip_addresses=[ip_address("192.168.1.123")],
hostname="openevse-deadbeeffeed.local.",
name="openevse-deadbeeffeed._openevse._tcp.local.",
port=80,
properties={"id": "deadbeeffeed", "type": "openevse"},
type="_openevse._tcp.local.",
)
# Trigger the zeroconf step
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
# Should present a confirmation form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
assert result["description_placeholders"] == {
"name": "OpenEVSE openevse-deadbeeffeed"
}
# Confirm the discovery
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
# Should create the entry
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "OpenEVSE openevse-deadbeeffeed"
assert result["data"] == {CONF_HOST: "192.168.1.123"}
assert result["result"].unique_id == "deadbeeffeed"
async def test_zeroconf_already_configured_unique_id(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_charger: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test zeroconf discovery updates info if unique_id is already configured."""
mock_config_entry.add_to_hass(hass)
discovery_info = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.124"),
ip_addresses=[ip_address("192.168.1.124"), ip_address("2001:db8::1")],
hostname="openevse-deadbeeffeed.local.",
name="openevse-deadbeeffeed._openevse._tcp.local.",
port=80,
properties={"id": "deadbeeffeed", "type": "openevse"},
type="_openevse._tcp.local.",
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
# Should abort because unique_id matches, but it updates the config entry
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
# Verify the entry IP was updated to the new discovery IP
assert mock_config_entry.data["host"] == "192.168.1.124"
async def test_zeroconf_connection_error(
hass: HomeAssistant, mock_charger: MagicMock
) -> None:
"""Test zeroconf discovery with connection failure."""
mock_charger.test_and_get.side_effect = TimeoutError
discovery_info = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.123"),
ip_addresses=[ip_address("192.168.1.123"), ip_address("2001:db8::1")],
hostname="openevse-deadbeeffeed.local.",
name="openevse-deadbeeffeed._openevse._tcp.local.",
port=80,
properties={"id": "deadbeeffeed", "type": "openevse"},
type="_openevse._tcp.local.",
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unavailable_host"
async def test_zeroconf_auth(hass: HomeAssistant, mock_charger: MagicMock) -> None:
"""Test zeroconf discovery with connection failure."""
mock_charger.test_and_get.side_effect = [AuthenticationError, {}]
discovery_info = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.123"),
ip_addresses=[ip_address("192.168.1.123"), ip_address("2001:db8::1")],
hostname="openevse-deadbeeffeed.local.",
name="openevse-deadbeeffeed._openevse._tcp.local.",
port=80,
properties={"id": "deadbeeffeed", "type": "openevse"},
type="_openevse._tcp.local.",
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "fakeuser", CONF_PASSWORD: "muchpassword"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_HOST: "192.168.1.123",
CONF_USERNAME: "fakeuser",
CONF_PASSWORD: "muchpassword",
}
async def test_zeroconf_auth_failure(
hass: HomeAssistant, mock_charger: MagicMock
) -> None:
"""Test zeroconf discovery with connection failure."""
mock_charger.test_and_get.side_effect = [
AuthenticationError,
AuthenticationError,
{},
]
discovery_info = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.123"),
ip_addresses=[ip_address("192.168.1.123"), ip_address("2001:db8::1")],
hostname="openevse-deadbeeffeed.local.",
name="openevse-deadbeeffeed._openevse._tcp.local.",
port=80,
properties={"id": "deadbeeffeed", "type": "openevse"},
type="_openevse._tcp.local.",
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "fakeuser", CONF_PASSWORD: "muchpassword"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "auth"
assert result["errors"] == {"base": "invalid_auth"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "fakeuser", CONF_PASSWORD: "muchpassword"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_HOST: "192.168.1.123",
CONF_USERNAME: "fakeuser",
CONF_PASSWORD: "muchpassword",
}
async def test_zeroconf_already_configured_host(
hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test zeroconf discovery aborts if host is already configured."""
mock_config_entry.add_to_hass(hass)
discovery_info = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.100"),
ip_addresses=[ip_address("192.168.1.100"), ip_address("2001:db8::1")],
hostname="openevse-deadbeeffeed.local.",
name="openevse-deadbeeffeed._openevse._tcp.local.",
port=80,
properties={"id": "deadbeeffeed", "type": "openevse"},
type="_openevse._tcp.local.",
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=discovery_info,
)
# Should abort because the host matches an existing entry
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openevse/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 412,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/openevse/test_init.py | """Tests for the OpenEVSE integration."""
from unittest.mock import MagicMock
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_setup_entry_timeout(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test setup entry raises ConfigEntryNotReady on timeout."""
mock_charger.test_and_get.side_effect = TimeoutError
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_unload_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test unload entry."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openevse/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/openevse/test_number.py | """Tests for the OpenEVSE number platform."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test the sensor entities."""
with patch("homeassistant.components.openevse.PLATFORMS", [Platform.NUMBER]):
mock_config_entry.add_to_hass(hass)
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_set_value(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test the disabled by default sensor entities."""
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(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: "number.openevse_mock_config_charge_rate", ATTR_VALUE: 32.0},
blocking=True,
)
mock_charger.set_current.assert_called_once_with(32.0)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openevse/test_number.py",
"license": "Apache License 2.0",
"lines": 42,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/openevse/test_sensor.py | """Tests for the OpenEVSE sensor platform."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.openevse.const import DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import CONF_HOST, STATE_UNAVAILABLE, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test the sensor entities."""
with patch("homeassistant.components.openevse.PLATFORMS", [Platform.SENSOR]):
mock_config_entry.add_to_hass(hass)
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_disabled_by_default_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test the disabled by default sensor entities."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
state = hass.states.get("sensor.openevse_mock_config_ir_temperature")
assert state is None
entry = entity_registry.async_get("sensor.openevse_mock_config_ir_temperature")
assert entry
assert entry.disabled
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
state = hass.states.get("sensor.openevse_mock_config_rtc_temperature")
assert state is None
entry = entity_registry.async_get("sensor.openevse_mock_config_rtc_temperature")
assert entry
assert entry.disabled
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
async def test_missing_sensor_graceful_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test that missing sensor attributes are handled gracefully."""
mock_charger.vehicle_soc = None
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
# The sensor with missing attribute should be unknown
state = hass.states.get("sensor.openevse_mock_config_vehicle_state_of_charge")
assert state is not None
assert state.state == STATE_UNKNOWN
# Other sensors should still work
state = hass.states.get("sensor.openevse_mock_config_charging_status")
assert state is not None
assert state.state == "Charging"
async def test_sensor_unavailable_on_coordinator_timeout(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
) -> None:
"""Test sensors become unavailable when coordinator times out."""
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("sensor.openevse_mock_config_charging_status")
assert state
assert state.state != STATE_UNAVAILABLE
mock_charger.update.side_effect = TimeoutError("Connection timed out")
await mock_config_entry.runtime_data.async_refresh()
await hass.async_block_till_done()
state = hass.states.get("sensor.openevse_mock_config_charging_status")
assert state
assert state.state == STATE_UNAVAILABLE
async def test_yaml_import_success(
hass: HomeAssistant,
mock_charger: MagicMock,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test successful YAML import creates deprecated_yaml issue."""
assert await async_setup_component(
hass,
SENSOR_DOMAIN,
{SENSOR_DOMAIN: {"platform": DOMAIN, CONF_HOST: "192.168.1.100"}},
)
await hass.async_block_till_done()
issue = issue_registry.async_get_issue("homeassistant", "deprecated_yaml")
assert issue is not None
assert issue.issue_domain == DOMAIN
async def test_yaml_import_unavailable_host(
hass: HomeAssistant,
mock_charger: MagicMock,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test YAML import with unavailable host creates domain-specific issue."""
mock_charger.test_and_get.side_effect = TimeoutError("Connection timed out")
assert await async_setup_component(
hass,
SENSOR_DOMAIN,
{SENSOR_DOMAIN: {"platform": DOMAIN, CONF_HOST: "192.168.1.100"}},
)
await hass.async_block_till_done()
issue = issue_registry.async_get_issue(
DOMAIN, "deprecated_yaml_import_issue_unavailable_host"
)
assert issue is not None
async def test_yaml_import_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_charger: MagicMock,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test YAML import when already configured creates deprecated_yaml issue."""
# Only add the entry, don't set it up - this allows the YAML platform setup
# to run while the config flow will still see the existing entry
mock_config_entry.add_to_hass(hass)
assert await async_setup_component(
hass,
SENSOR_DOMAIN,
{SENSOR_DOMAIN: {"platform": DOMAIN, CONF_HOST: "192.168.1.100"}},
)
await hass.async_block_till_done()
# When already configured, it should still create deprecated_yaml issue
issue = issue_registry.async_get_issue("homeassistant", "deprecated_yaml")
assert issue is not None
assert issue.issue_domain == DOMAIN
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openevse/test_sensor.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/person/test_condition.py | """Test person conditions."""
from typing import Any
import pytest
from homeassistant.const import STATE_HOME, STATE_NOT_HOME
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_persons(hass: HomeAssistant) -> list[str]:
"""Create multiple person entities associated with different targets."""
return (await target_entities(hass, "person"))["included"]
@pytest.mark.parametrize(
"condition",
[
"person.is_home",
"person.is_not_home",
],
)
async def test_person_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the person 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("person"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="person.is_home",
target_states=[STATE_HOME],
other_states=[STATE_NOT_HOME],
),
*parametrize_condition_states_any(
condition="person.is_not_home",
target_states=[STATE_NOT_HOME],
other_states=[STATE_HOME],
),
],
)
async def test_person_state_condition_behavior_any(
hass: HomeAssistant,
target_persons: 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 person state condition with the 'any' behavior."""
other_entity_ids = set(target_persons) - {entity_id}
# Set all persons, including the tested person, to the initial state
for eid in target_persons:
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",
)
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 persons 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("person"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="person.is_home",
target_states=[STATE_HOME],
other_states=[STATE_NOT_HOME],
),
*parametrize_condition_states_all(
condition="person.is_not_home",
target_states=[STATE_NOT_HOME],
other_states=[STATE_HOME],
),
],
)
async def test_person_state_condition_behavior_all(
hass: HomeAssistant,
target_persons: 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 person state condition with the 'all' behavior."""
other_entity_ids = set(target_persons) - {entity_id}
# Set all persons, including the tested person, to the initial state
for eid in target_persons:
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/person/test_condition.py",
"license": "Apache License 2.0",
"lines": 134,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/person/test_trigger.py | """Test person trigger."""
from typing import Any
import pytest
from homeassistant.components.person.const import DOMAIN
from homeassistant.const import (
ATTR_LABEL_ID,
CONF_ENTITY_ID,
STATE_HOME,
STATE_NOT_HOME,
)
from homeassistant.core import HomeAssistant, ServiceCall
from tests.components import (
TriggerStateDescription,
arm_trigger,
parametrize_target_entities,
parametrize_trigger_states,
set_or_remove_state,
target_entities,
)
STATE_WORK_ZONE = "work"
@pytest.fixture
async def target_persons(hass: HomeAssistant) -> list[str]:
"""Create multiple persons entities associated with different targets."""
return (await target_entities(hass, DOMAIN))["included"]
@pytest.mark.parametrize(
"trigger_key",
["person.entered_home", "person.left_home"],
)
async def test_person_triggers_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str
) -> None:
"""Test the person triggers are gated by the labs flag."""
await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"})
assert (
"Unnamed automation failed to setup triggers and has been disabled: Trigger "
f"'{trigger_key}' requires the experimental 'New triggers and conditions' "
"feature to be enabled in Home Assistant Labs settings (feature flag: "
"'new_triggers_conditions')"
) in caplog.text
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities(DOMAIN),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="person.entered_home",
target_states=[STATE_HOME],
other_states=[STATE_NOT_HOME, STATE_WORK_ZONE],
),
*parametrize_trigger_states(
trigger="person.left_home",
target_states=[STATE_NOT_HOME, STATE_WORK_ZONE],
other_states=[STATE_HOME],
),
],
)
async def test_person_home_trigger_behavior_any(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_persons: 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 person home triggers when any person changes to a specific state."""
other_entity_ids = set(target_persons) - {entity_id}
# Set all persons, including the tested person, to the initial state
for eid in target_persons:
set_or_remove_state(hass, eid, states[0]["included"])
await hass.async_block_till_done()
await arm_trigger(hass, trigger, {}, trigger_target_config)
for state in states[1:]:
included_state = state["included"]
set_or_remove_state(hass, entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == state["count"]
for service_call in service_calls:
assert service_call.data[CONF_ENTITY_ID] == entity_id
service_calls.clear()
# Check that changing other persons also triggers
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == (entities_in_target - 1) * state["count"]
service_calls.clear()
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities(DOMAIN),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="person.entered_home",
target_states=[STATE_HOME],
other_states=[STATE_NOT_HOME, STATE_WORK_ZONE],
),
*parametrize_trigger_states(
trigger="person.left_home",
target_states=[STATE_NOT_HOME, STATE_WORK_ZONE],
other_states=[STATE_HOME],
),
],
)
async def test_person_state_trigger_behavior_first(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_persons: 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 person home triggers when the first person changes to a specific state."""
other_entity_ids = set(target_persons) - {entity_id}
# Set all persons, including the tested person, to the initial state
for eid in target_persons:
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 persons should not cause the trigger to fire again
for other_entity_id in other_entity_ids:
set_or_remove_state(hass, other_entity_id, included_state)
await hass.async_block_till_done()
assert len(service_calls) == 0
@pytest.mark.usefixtures("enable_labs_preview_features")
@pytest.mark.parametrize(
("trigger_target_config", "entity_id", "entities_in_target"),
parametrize_target_entities(DOMAIN),
)
@pytest.mark.parametrize(
("trigger", "trigger_options", "states"),
[
*parametrize_trigger_states(
trigger="person.entered_home",
target_states=[STATE_HOME],
other_states=[STATE_NOT_HOME, STATE_WORK_ZONE],
),
*parametrize_trigger_states(
trigger="person.left_home",
target_states=[STATE_NOT_HOME, STATE_WORK_ZONE],
other_states=[STATE_HOME],
),
],
)
async def test_person_state_trigger_behavior_last(
hass: HomeAssistant,
service_calls: list[ServiceCall],
target_persons: 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 person home triggers when the last person changes to a specific state."""
other_entity_ids = set(target_persons) - {entity_id}
# Set all persons, including the tested person, to the initial state
for eid in target_persons:
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/person/test_trigger.py",
"license": "Apache License 2.0",
"lines": 192,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/pooldose/test_diagnostics.py | """Test Pooldose diagnostics."""
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
init_integration: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry diagnostics."""
result = await get_diagnostics_for_config_entry(hass, hass_client, init_integration)
assert result == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/pooldose/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/prana/test_config_flow.py | """Tests for the Prana config flow."""
from types import SimpleNamespace
from prana_local_api_client.exceptions import (
PranaApiCommunicationError as PranaCommunicationError,
)
from homeassistant.components.prana.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from tests.common import load_json_object_fixture
ZEROCONF_INFO = ZeroconfServiceInfo(
ip_address="192.168.1.30",
ip_addresses=["192.168.1.30"],
hostname="prana.local",
name="TestNew._prana._tcp.local.",
type="_prana._tcp.local.",
port=1234,
properties={},
)
async def async_load_fixture(hass: HomeAssistant, filename: str) -> dict:
"""Load a fixture file."""
return await hass.async_add_executor_job(load_json_object_fixture, filename, DOMAIN)
async def test_zeroconf_new_device_and_confirm(
hass: HomeAssistant, mock_prana_api
) -> None:
"""Zeroconf discovery shows confirm form and creates a config entry."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_INFO
)
device_info = await async_load_fixture(hass, "device_info.json")
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == device_info["label"]
assert result["result"].unique_id == device_info["manufactureId"]
assert result["result"].data == {CONF_HOST: "192.168.1.30"}
async def test_user_flow_with_manual_entry(hass: HomeAssistant, mock_prana_api) -> None:
"""User flow accepts manual host and creates entry after confirmation."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
device_info = await async_load_fixture(hass, "device_info.json")
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: "192.168.1.40"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == device_info["label"]
assert result["result"].unique_id == device_info["manufactureId"]
assert result["result"].data == {CONF_HOST: "192.168.1.40"}
async def test_communication_error_on_device_info(
hass: HomeAssistant, mock_prana_api
) -> None:
"""Communication errors when fetching device info surface as form errors."""
# Setting an invalid device info, for abort the flow
device_info_invalid = await async_load_fixture(hass, "device_info_invalid.json")
mock_prana_api.get_device_info.return_value = SimpleNamespace(**device_info_invalid)
mock_prana_api.get_device_info.side_effect = None
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: "192.168.1.50"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "invalid_device"
# Simulating a communication error
device_info = await async_load_fixture(hass, "device_info.json")
mock_prana_api.get_device_info.return_value = SimpleNamespace(**device_info)
mock_prana_api.get_device_info.side_effect = PranaCommunicationError(
"Network error"
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: "192.168.1.50"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert "invalid_device_or_unreachable" in result["errors"].values()
# Now simulating a successful fetch, without aborting
mock_prana_api.get_device_info.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: "192.168.1.50"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == device_info["label"]
assert result["result"].unique_id == device_info["manufactureId"]
assert result["result"].data == {CONF_HOST: "192.168.1.50"}
async def test_user_flow_already_configured(
hass: HomeAssistant, mock_prana_api, mock_config_entry
) -> None:
"""Second configuration for the same device should be aborted."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_HOST: "192.168.1.40"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_zeroconf_already_configured(
hass: HomeAssistant, mock_prana_api, mock_config_entry
) -> None:
"""Zeroconf discovery of an already configured device should be aborted."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_INFO
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_zeroconf_invalid_device(hass: HomeAssistant, mock_prana_api) -> None:
"""Zeroconf discovery of an invalid device should be aborted."""
mock_prana_api.get_device_info.side_effect = PranaCommunicationError(
"Network error"
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=ZEROCONF_INFO
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "invalid_device_or_unreachable"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/prana/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 131,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/prana/test_init.py | """Tests for Prana integration entry points (async_setup_entry / async_unload_entry)."""
from homeassistant.components.prana.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from . import async_init_integration
from tests.common import SnapshotAssertion
async def test_async_setup_entry_and_unload_entry(
hass: HomeAssistant, mock_config_entry, mock_prana_api
) -> None:
"""async_setup_entry should create coordinator, refresh it, store runtime_data and forward setups."""
await async_init_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_info_registered(
hass: HomeAssistant,
mock_config_entry,
mock_prana_api,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Device info from the API should be registered on the device registry."""
await async_init_integration(hass, mock_config_entry)
device = device_registry.async_get_device(
identifiers={(DOMAIN, mock_config_entry.unique_id)}
)
assert device is not None
assert snapshot == device
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/prana/test_init.py",
"license": "Apache License 2.0",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/prana/test_switch.py | """Integration-style tests for Prana switches."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import async_init_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_switches(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
mock_prana_api: MagicMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test the Prana switches snapshot."""
with patch("homeassistant.components.prana.PLATFORMS", [Platform.SWITCH]):
await async_init_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("type_key", "entity_suffix"),
[
("winter", "_winter"),
("heater", "_heater"),
("auto", "_auto"),
("bound", "_bound"),
("auto_plus", "_auto_plus"),
],
)
async def test_switches_actions(
hass: HomeAssistant,
mock_prana_api: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
type_key: str,
entity_suffix: str,
) -> None:
"""Test turning switches on and off calls the API through the coordinator."""
await async_init_integration(hass, mock_config_entry)
entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert entries
target = f"switch.prana_recuperator{entity_suffix}"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: target},
blocking=True,
)
mock_prana_api.set_switch.assert_called()
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: target},
blocking=True,
)
assert mock_prana_api.set_switch.call_count >= 2
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/prana/test_switch.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/proxmoxve/test_binary_sensor.py | """Test the Proxmox VE binary sensor platform."""
from unittest.mock import MagicMock, patch
from freezegun.api import FrozenDateTimeFactory
from proxmoxer import AuthenticationError
from proxmoxer.core import ResourceException
import pytest
import requests
from requests.exceptions import ConnectTimeout, SSLError
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.proxmoxve.coordinator import DEFAULT_UPDATE_INTERVAL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
import homeassistant.helpers.entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.fixture(autouse=True)
def enable_all_entities(entity_registry_enabled_by_default: None) -> None:
"""Make sure all entities are enabled."""
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.proxmoxve.PLATFORMS",
[Platform.BINARY_SENSOR],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
@pytest.mark.parametrize(
("exception"),
[
(AuthenticationError("Invalid credentials")),
(SSLError("SSL handshake failed")),
(ConnectTimeout("Connection timed out")),
(ResourceException("404", "status_message", "content")),
(requests.exceptions.ConnectionError("Connection error")),
],
ids=[
"auth_error",
"ssl_error",
"connect_timeout",
"resource_exception",
"connection_error",
],
)
async def test_refresh_exceptions(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
exception: Exception,
) -> None:
"""Test entities go unavailable after coordinator refresh failures."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_proxmox_client.nodes.get.side_effect = exception
freezer.tick(DEFAULT_UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("binary_sensor.ct_nginx_status")
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/proxmoxve/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 68,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/proxmoxve/test_config_flow.py | """Test the config flow for Proxmox VE."""
from __future__ import annotations
from unittest.mock import MagicMock
from proxmoxer import AuthenticationError
from proxmoxer.core import ResourceException
import pytest
import requests
from requests.exceptions import ConnectTimeout, SSLError
from homeassistant.components.proxmoxve import CONF_HOST, CONF_REALM
from homeassistant.components.proxmoxve.const import CONF_NODES, DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER, ConfigEntryState
from homeassistant.const import CONF_PASSWORD, CONF_PORT, CONF_USERNAME, CONF_VERIFY_SSL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import MOCK_TEST_CONFIG
from tests.common import MockConfigEntry
MOCK_USER_STEP = {
CONF_HOST: "127.0.0.1",
CONF_USERNAME: "test_user@pam",
CONF_PASSWORD: "test_password",
CONF_VERIFY_SSL: True,
CONF_PORT: 8006,
CONF_REALM: "pam",
}
MOCK_USER_SETUP = {CONF_NODES: ["pve1"]}
MOCK_USER_FINAL = {
**MOCK_USER_STEP,
**MOCK_USER_SETUP,
}
async def test_form(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
) -> 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["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_STEP
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "127.0.0.1"
assert result["data"] == MOCK_TEST_CONFIG
@pytest.mark.parametrize(
("exception", "reason"),
[
(
AuthenticationError("Invalid credentials"),
"invalid_auth",
),
(
SSLError("SSL handshake failed"),
"ssl_error",
),
(
ConnectTimeout("Connection timed out"),
"connect_timeout",
),
(
ResourceException("404", "status_message", "content"),
"no_nodes_found",
),
(
requests.exceptions.ConnectionError("Connection error"),
"cannot_connect",
),
],
)
async def test_form_exceptions(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
exception: Exception,
reason: str,
) -> None:
"""Test we handle all exceptions."""
mock_proxmox_client.nodes.get.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"],
user_input=MOCK_USER_STEP,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
mock_proxmox_client.nodes.get.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_STEP
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_form_no_nodes_exception(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
) -> None:
"""Test we handle no nodes found 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"
mock_proxmox_client.nodes.get.side_effect = ResourceException(
"404", "status_message", "content"
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_STEP
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "no_nodes_found"}
mock_proxmox_client.nodes.get.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_STEP
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_duplicate_entry(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test we handle duplicate entries."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_USER_STEP
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_import_flow(
hass: HomeAssistant,
mock_setup_entry: MagicMock,
mock_proxmox_client: MagicMock,
) -> None:
"""Test importing from YAML creates a config entry and sets it up."""
MOCK_IMPORT_CONFIG = {
DOMAIN: {
**MOCK_USER_STEP,
**MOCK_USER_SETUP,
}
}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_IMPORT_CONFIG[DOMAIN]
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "127.0.0.1"
assert result["data"][CONF_HOST] == "127.0.0.1"
assert len(mock_setup_entry.mock_calls) == 1
assert result["result"].state is ConfigEntryState.LOADED
@pytest.mark.parametrize(
("exception", "reason"),
[
(
AuthenticationError("Invalid credentials"),
"invalid_auth",
),
(
SSLError("SSL handshake failed"),
"ssl_error",
),
(
ConnectTimeout("Connection timed out"),
"connect_timeout",
),
(
ResourceException("404", "status_message", "content"),
"no_nodes_found",
),
(
requests.exceptions.ConnectionError("Connection error"),
"cannot_connect",
),
],
)
async def test_import_flow_exceptions(
hass: HomeAssistant,
mock_setup_entry: MagicMock,
mock_proxmox_client: MagicMock,
exception: Exception,
reason: str,
) -> None:
"""Test importing from YAML creates a config entry and sets it up."""
MOCK_IMPORT_CONFIG = {
DOMAIN: {
**MOCK_USER_STEP,
**MOCK_USER_SETUP,
}
}
mock_proxmox_client.nodes.get.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=MOCK_IMPORT_CONFIG[DOMAIN]
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == reason
assert len(mock_setup_entry.mock_calls) == 0
assert len(hass.config_entries.async_entries(DOMAIN)) == 0
async def test_full_flow_reconfigure(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full flow of the config flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_STEP,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data == MOCK_TEST_CONFIG
async def test_full_flow_reconfigure_match_entries(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full flow of the config flow, this time matching existing entries."""
mock_config_entry.add_to_hass(hass)
# Adding a second entry with a different host, since configuring the same host should work
second_entry = MockConfigEntry(
domain=DOMAIN,
title="Second ProxmoxVE",
data={
**MOCK_TEST_CONFIG,
CONF_HOST: "192.168.1.1",
},
)
second_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
**MOCK_USER_STEP,
CONF_HOST: "192.168.1.1",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_config_entry.data == MOCK_TEST_CONFIG
assert len(mock_setup_entry.mock_calls) == 0
@pytest.mark.parametrize(
("exception", "reason"),
[
(
AuthenticationError("Invalid credentials"),
"invalid_auth",
),
(
SSLError("SSL handshake failed"),
"ssl_error",
),
(
ConnectTimeout("Connection timed out"),
"connect_timeout",
),
(
ResourceException("404", "status_message", "content"),
"no_nodes_found",
),
(
requests.exceptions.ConnectionError("Connection error"),
"cannot_connect",
),
],
)
async def test_full_flow_reconfigure_exceptions(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test the full flow of the config flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_proxmox_client.nodes.get.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_STEP,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
mock_proxmox_client.nodes.get.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_STEP,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data == MOCK_TEST_CONFIG
async def test_full_flow_reauth(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full flow of the config flow."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
# There is no user input
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_PASSWORD: "new_password"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_PASSWORD] == "new_password"
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("exception", "reason"),
[
(
AuthenticationError("Invalid credentials"),
"invalid_auth",
),
(
SSLError("SSL handshake failed"),
"ssl_error",
),
(
ConnectTimeout("Connection timed out"),
"connect_timeout",
),
(
ResourceException("404", "status_message", "content"),
"no_nodes_found",
),
(
requests.exceptions.ConnectionError("Connection error"),
"cannot_connect",
),
],
)
async def test_full_flow_reauth_exceptions(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test we handle all exceptions in the reauth flow."""
mock_config_entry.add_to_hass(hass)
mock_proxmox_client.nodes.get.side_effect = exception
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_PASSWORD: "new_password"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
# Now test that we can recover from the error
mock_proxmox_client.nodes.get.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_PASSWORD: "new_password"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_PASSWORD] == "new_password"
assert len(mock_setup_entry.mock_calls) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/proxmoxve/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 387,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/proxmoxve/test_init.py | """Tests for the Proxmox VE integration initialization."""
from unittest.mock import MagicMock
from proxmoxer import AuthenticationError
from proxmoxer.core import ResourceException
import pytest
import requests
from requests.exceptions import ConnectTimeout, SSLError
from homeassistant.components.proxmoxve.const import (
CONF_CONTAINERS,
CONF_NODE,
CONF_NODES,
CONF_REALM,
CONF_VMS,
DOMAIN,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
import homeassistant.helpers.issue_registry as ir
from homeassistant.setup import async_setup_component
from . import setup_integration
from tests.common import MockConfigEntry
async def test_config_import(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_setup_entry: MagicMock,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test sensor initialization."""
await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: [
{
CONF_HOST: "127.0.0.1",
CONF_PORT: 8006,
CONF_REALM: "pam",
CONF_USERNAME: "test_user@pam",
CONF_PASSWORD: "test_password",
CONF_VERIFY_SSL: True,
CONF_NODES: [
{
CONF_NODE: "pve1",
CONF_VMS: [100, 101],
CONF_CONTAINERS: [200, 201],
},
],
}
]
},
)
await hass.async_block_till_done()
assert len(issue_registry.issues) == 1
assert (HOMEASSISTANT_DOMAIN, "deprecated_yaml") in issue_registry.issues
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
@pytest.mark.parametrize(
("exception", "expected_state"),
[
(
AuthenticationError("Invalid credentials"),
ConfigEntryState.SETUP_ERROR,
),
(
SSLError("SSL handshake failed"),
ConfigEntryState.SETUP_ERROR,
),
(ConnectTimeout("Connection timed out"), ConfigEntryState.SETUP_RETRY),
(
ResourceException(500, "Internal Server Error", ""),
ConfigEntryState.SETUP_ERROR,
),
(
requests.exceptions.ConnectionError("Connection refused"),
ConfigEntryState.SETUP_ERROR,
),
],
ids=[
"auth_error",
"ssl_error",
"connect_timeout",
"resource_exception",
"connection_error",
],
)
async def test_setup_exceptions(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
expected_state: ConfigEntryState,
) -> None:
"""Test the _async_setup."""
mock_proxmox_client.nodes.get.side_effect = exception
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state == expected_state
async def test_migration_v1_to_v2(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test migration from version 1 to 2."""
entry = MockConfigEntry(
domain=DOMAIN,
version=1,
unique_id="1",
data={
CONF_HOST: "http://test_host",
CONF_PORT: 8006,
CONF_REALM: "pam",
CONF_USERNAME: "test_user@pam",
CONF_PASSWORD: "test_password",
CONF_VERIFY_SSL: True,
},
)
entry.add_to_hass(hass)
assert entry.version == 1
device_registry = dr.async_get(hass)
entity_registry = er.async_get(hass)
vm_device = device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, f"{entry.entry_id}_vm_100")},
name="Test VM",
)
container_device = device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, f"{entry.entry_id}_container_200")},
name="Test Container",
)
vm_entity = entity_registry.async_get_or_create(
domain="binary_sensor",
platform=DOMAIN,
unique_id="proxmox_pve1_100_running",
config_entry=entry,
device_id=vm_device.id,
original_name="Test VM Binary Sensor",
)
container_entity = entity_registry.async_get_or_create(
domain="binary_sensor",
platform=DOMAIN,
unique_id="proxmox_pve1_200_running",
config_entry=entry,
device_id=container_device.id,
original_name="Test Container Binary Sensor",
)
assert vm_entity.unique_id == "proxmox_pve1_100_running"
assert container_entity.unique_id == "proxmox_pve1_200_running"
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.version == 2
vm_entity_after = entity_registry.async_get(vm_entity.entity_id)
container_entity_after = entity_registry.async_get(container_entity.entity_id)
assert vm_entity_after.unique_id == f"{entry.entry_id}_100_status"
assert container_entity_after.unique_id == f"{entry.entry_id}_200_status"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/proxmoxve/test_init.py",
"license": "Apache License 2.0",
"lines": 161,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/saunum/test_number.py | """Test the Saunum number platform."""
from __future__ import annotations
from dataclasses import replace
from unittest.mock import MagicMock
from pysaunum import SaunumException
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, 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.NUMBER]
@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.usefixtures("init_integration")
async def test_set_sauna_duration(
hass: HomeAssistant,
mock_saunum_client: MagicMock,
) -> None:
"""Test setting sauna duration."""
entity_id = "number.saunum_leil_sauna_duration"
# Verify initial state
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "120"
# Set new duration
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 180},
blocking=True,
)
# Verify the client method was called
mock_saunum_client.async_set_sauna_duration.assert_called_once_with(180)
@pytest.mark.usefixtures("init_integration")
async def test_set_fan_duration(
hass: HomeAssistant,
mock_saunum_client: MagicMock,
) -> None:
"""Test setting fan duration."""
entity_id = "number.saunum_leil_fan_duration"
# Verify initial state
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "10"
# Set new duration
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 15},
blocking=True,
)
# Verify the client method was called
mock_saunum_client.async_set_fan_duration.assert_called_once_with(15)
@pytest.mark.usefixtures("init_integration")
async def test_set_value_failure(
hass: HomeAssistant,
mock_saunum_client: MagicMock,
) -> None:
"""Test error handling when setting value fails."""
entity_id = "number.saunum_leil_sauna_duration"
# Make the set operation fail
mock_saunum_client.async_set_sauna_duration.side_effect = SaunumException(
"Write error"
)
# Attempt to set value should raise HomeAssistantError
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 180},
blocking=True,
)
@pytest.mark.usefixtures("init_integration")
async def test_set_value_while_session_active(
hass: HomeAssistant,
mock_saunum_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test error when trying to change duration while session is active."""
entity_id = "number.saunum_leil_sauna_duration"
# Update mock data to have session active
base_data = mock_saunum_client.async_get_data.return_value
mock_saunum_client.async_get_data.return_value = replace(
base_data,
session_active=True,
)
# Trigger coordinator update
coordinator = mock_config_entry.runtime_data
await coordinator.async_refresh()
await hass.async_block_till_done()
# Attempt to set value should raise ServiceValidationError
with pytest.raises(
ServiceValidationError,
match="Cannot change sauna duration while sauna session is active",
):
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 180},
blocking=True,
)
async def test_number_with_default_duration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client: MagicMock,
) -> None:
"""Test number entities use default when device returns None."""
# Set duration to None (device hasn't set it yet)
base_data = mock_saunum_client.async_get_data.return_value
mock_saunum_client.async_get_data.return_value = replace(
base_data,
sauna_duration=None,
fan_duration=None,
)
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Should show default values
sauna_duration_state = hass.states.get("number.saunum_leil_sauna_duration")
assert sauna_duration_state is not None
assert sauna_duration_state.state == "120" # DEFAULT_DURATION_MIN
fan_duration_state = hass.states.get("number.saunum_leil_fan_duration")
assert fan_duration_state is not None
assert fan_duration_state.state == "15" # DEFAULT_FAN_DURATION_MIN
async def test_number_with_valid_duration_from_device(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_saunum_client: MagicMock,
) -> None:
"""Test number entities use actual values from device when valid."""
base_data = mock_saunum_client.async_get_data.return_value
mock_saunum_client.async_get_data.return_value = replace(
base_data,
sauna_duration=90,
fan_duration=20,
)
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()
# Should show actual device values
sauna_duration_state = hass.states.get("number.saunum_leil_sauna_duration")
assert sauna_duration_state is not None
assert sauna_duration_state.state == "90"
fan_duration_state = hass.states.get("number.saunum_leil_fan_duration")
assert fan_duration_state is not None
assert fan_duration_state.state == "20"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/saunum/test_number.py",
"license": "Apache License 2.0",
"lines": 163,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/siren/test_condition.py | """Test siren 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_sirens(hass: HomeAssistant) -> list[str]:
"""Create multiple siren entities associated with different targets."""
return (await target_entities(hass, "siren"))["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 siren entities are considered
in the condition evaluation and not other toggle entities.
"""
return (await target_entities(hass, "switch"))["included"]
@pytest.mark.parametrize(
"condition",
[
"siren.is_off",
"siren.is_on",
],
)
async def test_siren_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the siren 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("siren"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="siren.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_condition_states_any(
condition="siren.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_siren_state_condition_behavior_any(
hass: HomeAssistant,
target_sirens: 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 siren state condition with the 'any' behavior."""
other_entity_ids = set(target_sirens) - {entity_id}
# Set all sirens, including the tested siren, to the initial state
for eid in target_sirens:
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 sirens 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("siren"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="siren.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_condition_states_all(
condition="siren.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_siren_state_condition_behavior_all(
hass: HomeAssistant,
target_sirens: 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 siren 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_sirens) - {entity_id}
# Set all sirens, including the tested siren, to the initial state
for eid in target_sirens:
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/siren/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/sunricher_dali/test_binary_sensor.py | """Test the Sunricher DALI binary sensor platform."""
from unittest.mock import MagicMock
from PySrDaliGateway import CallbackEventType
from PySrDaliGateway.types import MotionState
import pytest
from homeassistant.const import (
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import find_device_listener, trigger_availability_callback
from tests.common import MockConfigEntry, SnapshotAssertion, snapshot_platform
TEST_MOTION_ENTITY_ID = "binary_sensor.motion_sensor_0000_10_motion"
TEST_OCCUPANCY_ENTITY_ID = "binary_sensor.motion_sensor_0000_10_occupancy"
@pytest.fixture
def mock_devices(mock_motion_sensor_device: MagicMock) -> list[MagicMock]:
"""Override mock_devices to use motion sensor device only."""
return [mock_motion_sensor_device]
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify which platforms to test."""
return [Platform.BINARY_SENSOR]
@pytest.mark.usefixtures("init_integration")
async def test_setup_entry(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test that async_setup_entry correctly creates binary sensor entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert len(entity_entries) == 2
entity_ids = [entry.entity_id for entry in entity_entries]
assert TEST_MOTION_ENTITY_ID in entity_ids
assert TEST_OCCUPANCY_ENTITY_ID in entity_ids
@pytest.mark.usefixtures("init_integration")
async def test_occupancy_sensor_initial_state(
hass: HomeAssistant,
) -> None:
"""Test occupancy sensor initial state is OFF."""
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNKNOWN
@pytest.mark.usefixtures("init_integration")
async def test_occupancy_sensor_motion_detected(
hass: HomeAssistant,
mock_motion_sensor_device: MagicMock,
) -> None:
"""Test occupancy sensor turns ON when motion is detected."""
motion_device = mock_motion_sensor_device
callback = find_device_listener(motion_device, CallbackEventType.MOTION_STATUS)
callback({"motion_state": MotionState.MOTION})
await hass.async_block_till_done()
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state == STATE_ON
@pytest.mark.usefixtures("init_integration")
async def test_occupancy_sensor_presence_detected(
hass: HomeAssistant,
mock_motion_sensor_device: MagicMock,
) -> None:
"""Test occupancy sensor turns ON when presence is detected."""
motion_device = mock_motion_sensor_device
callback = find_device_listener(motion_device, CallbackEventType.MOTION_STATUS)
callback({"motion_state": MotionState.PRESENCE})
await hass.async_block_till_done()
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state == STATE_ON
@pytest.mark.usefixtures("init_integration")
async def test_occupancy_sensor_occupancy_detected(
hass: HomeAssistant,
mock_motion_sensor_device: MagicMock,
) -> None:
"""Test occupancy sensor turns ON when occupancy is detected."""
motion_device = mock_motion_sensor_device
callback = find_device_listener(motion_device, CallbackEventType.MOTION_STATUS)
callback({"motion_state": MotionState.OCCUPANCY})
await hass.async_block_till_done()
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state == STATE_ON
@pytest.mark.usefixtures("init_integration")
async def test_occupancy_sensor_ignores_no_motion(
hass: HomeAssistant,
mock_motion_sensor_device: MagicMock,
) -> None:
"""Test occupancy sensor stays ON after NO_MOTION (only VACANT turns it off)."""
motion_device = mock_motion_sensor_device
callback = find_device_listener(motion_device, CallbackEventType.MOTION_STATUS)
callback({"motion_state": MotionState.MOTION})
await hass.async_block_till_done()
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state == STATE_ON
callback({"motion_state": MotionState.NO_MOTION})
await hass.async_block_till_done()
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state == STATE_ON # Still ON - NO_MOTION does not affect occupancy
@pytest.mark.usefixtures("init_integration")
async def test_occupancy_sensor_vacant(
hass: HomeAssistant,
mock_motion_sensor_device: MagicMock,
) -> None:
"""Test occupancy sensor turns OFF when vacant."""
motion_device = mock_motion_sensor_device
callback = find_device_listener(motion_device, CallbackEventType.MOTION_STATUS)
callback({"motion_state": MotionState.OCCUPANCY})
await hass.async_block_till_done()
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state == STATE_ON
callback({"motion_state": MotionState.VACANT})
await hass.async_block_till_done()
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state == STATE_OFF
@pytest.mark.usefixtures("init_integration")
async def test_occupancy_sensor_availability(
hass: HomeAssistant,
mock_motion_sensor_device: MagicMock,
) -> None:
"""Test availability changes are reflected in binary sensor entity state."""
motion_device = mock_motion_sensor_device
trigger_availability_callback(motion_device, False)
await hass.async_block_till_done()
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNAVAILABLE
trigger_availability_callback(motion_device, True)
await hass.async_block_till_done()
state = hass.states.get(TEST_OCCUPANCY_ENTITY_ID)
assert state is not None
assert state.state != STATE_UNAVAILABLE
# MotionSensor tests
@pytest.mark.usefixtures("init_integration")
async def test_motion_sensor_initial_state(
hass: HomeAssistant,
) -> None:
"""Test motion sensor initial state is OFF."""
state = hass.states.get(TEST_MOTION_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNKNOWN
@pytest.mark.usefixtures("init_integration")
async def test_motion_sensor_on_motion(
hass: HomeAssistant,
mock_motion_sensor_device: MagicMock,
) -> None:
"""Test motion sensor turns ON when motion is detected."""
motion_device = mock_motion_sensor_device
callback = find_device_listener(motion_device, CallbackEventType.MOTION_STATUS)
callback({"motion_state": MotionState.MOTION})
await hass.async_block_till_done()
state = hass.states.get(TEST_MOTION_ENTITY_ID)
assert state is not None
assert state.state == STATE_ON
@pytest.mark.usefixtures("init_integration")
async def test_motion_sensor_off_no_motion(
hass: HomeAssistant,
mock_motion_sensor_device: MagicMock,
) -> None:
"""Test motion sensor turns OFF when no motion."""
motion_device = mock_motion_sensor_device
callback = find_device_listener(motion_device, CallbackEventType.MOTION_STATUS)
callback({"motion_state": MotionState.MOTION})
await hass.async_block_till_done()
state = hass.states.get(TEST_MOTION_ENTITY_ID)
assert state.state == STATE_ON
callback({"motion_state": MotionState.NO_MOTION})
await hass.async_block_till_done()
state = hass.states.get(TEST_MOTION_ENTITY_ID)
assert state is not None
assert state.state == STATE_OFF
@pytest.mark.usefixtures("init_integration")
async def test_motion_sensor_ignores_occupancy_events(
hass: HomeAssistant,
mock_motion_sensor_device: MagicMock,
) -> None:
"""Test motion sensor ignores OCCUPANCY, PRESENCE, VACANT events."""
motion_device = mock_motion_sensor_device
callback = find_device_listener(motion_device, CallbackEventType.MOTION_STATUS)
# Start with motion ON
callback({"motion_state": MotionState.MOTION})
await hass.async_block_till_done()
state = hass.states.get(TEST_MOTION_ENTITY_ID)
assert state.state == STATE_ON
# OCCUPANCY should not change motion sensor
callback({"motion_state": MotionState.OCCUPANCY})
await hass.async_block_till_done()
state = hass.states.get(TEST_MOTION_ENTITY_ID)
assert state.state == STATE_ON
# PRESENCE should not change motion sensor
callback({"motion_state": MotionState.PRESENCE})
await hass.async_block_till_done()
state = hass.states.get(TEST_MOTION_ENTITY_ID)
assert state.state == STATE_ON
# VACANT should not change motion sensor
callback({"motion_state": MotionState.VACANT})
await hass.async_block_till_done()
state = hass.states.get(TEST_MOTION_ENTITY_ID)
assert state.state == STATE_ON
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sunricher_dali/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 209,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/sunricher_dali/test_button.py | """Test the Sunricher DALI button platform."""
from unittest.mock import MagicMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.const import ATTR_ENTITY_ID, 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 which platforms to test."""
return [Platform.BUTTON]
@pytest.mark.usefixtures("init_integration")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the button entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("init_integration")
async def test_identify_button_press(
hass: HomeAssistant,
mock_devices: list[MagicMock],
) -> None:
"""Test pressing the identify button calls device.identify()."""
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.dimmer_0000_02"},
blocking=True,
)
mock_devices[0].identify.assert_called_once()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sunricher_dali/test_button.py",
"license": "Apache License 2.0",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/sunricher_dali/test_sensor.py | """Test the Sunricher DALI sensor platform."""
from unittest.mock import MagicMock
from PySrDaliGateway import CallbackEventType
import pytest
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import find_device_listener, trigger_availability_callback
from tests.common import MockConfigEntry, SnapshotAssertion, snapshot_platform
ENTITY_ID = "sensor.illuminance_sensor_0000_20"
@pytest.fixture
def mock_devices(
mock_illuminance_device: MagicMock, mock_light_device: MagicMock
) -> list[MagicMock]:
"""Override mock_devices to use illuminance sensor and light device."""
return [mock_illuminance_device, mock_light_device]
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify which platforms to test."""
return [Platform.SENSOR]
ENERGY_ENTITY_ID = "sensor.dimmer_0000_02_energy"
@pytest.mark.usefixtures("init_integration")
async def test_setup_entry(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test that async_setup_entry correctly creates sensor entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
# Should have illuminance sensor and energy sensor
assert len(entity_entries) == 2
entity_ids = {entry.entity_id for entry in entity_entries}
assert ENTITY_ID in entity_ids
assert ENERGY_ENTITY_ID in entity_ids
@pytest.mark.usefixtures("init_integration")
async def test_illuminance_callback(
hass: HomeAssistant,
mock_illuminance_device: MagicMock,
) -> None:
"""Test IlluminanceSensor handles valid and invalid values correctly."""
callback = find_device_listener(
mock_illuminance_device, CallbackEventType.ILLUMINANCE_STATUS
)
# Valid value should update state
callback({"illuminance_value": 500.0, "is_valid": True})
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state is not None
assert float(state.state) == 500.0
# Invalid value should be ignored
callback({"illuminance_value": 9999.0, "is_valid": False})
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state is not None
assert float(state.state) == 500.0
@pytest.mark.usefixtures("init_integration")
async def test_sensor_on_off(
hass: HomeAssistant,
mock_illuminance_device: MagicMock,
) -> None:
"""Test IlluminanceSensor handles sensor on/off callback correctly."""
illuminance_callback = find_device_listener(
mock_illuminance_device, CallbackEventType.ILLUMINANCE_STATUS
)
illuminance_callback({"illuminance_value": 250.0, "is_valid": True})
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state is not None
assert float(state.state) == 250.0
on_off_callback = find_device_listener(
mock_illuminance_device, CallbackEventType.SENSOR_ON_OFF
)
# Turn off sensor -> state becomes unknown
on_off_callback(False)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == STATE_UNKNOWN
# Turn on sensor -> restore previous value
on_off_callback(True)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state is not None
assert float(state.state) == 250.0
@pytest.mark.usefixtures("init_integration")
async def test_availability(
hass: HomeAssistant,
mock_illuminance_device: MagicMock,
) -> None:
"""Test availability changes are reflected in sensor entity state."""
trigger_availability_callback(mock_illuminance_device, False)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == STATE_UNAVAILABLE
trigger_availability_callback(mock_illuminance_device, True)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state != STATE_UNAVAILABLE
@pytest.mark.usefixtures("init_integration")
async def test_energy_callback(
hass: HomeAssistant,
mock_light_device: MagicMock,
) -> None:
"""Test EnergySensor handles energy report callback correctly."""
callback = find_device_listener(mock_light_device, CallbackEventType.ENERGY_REPORT)
# Update energy value
callback(123.45)
await hass.async_block_till_done()
state = hass.states.get(ENERGY_ENTITY_ID)
assert state is not None
assert float(state.state) == 123.45
# Update to new value
callback(200.0)
await hass.async_block_till_done()
state = hass.states.get(ENERGY_ENTITY_ID)
assert state is not None
assert float(state.state) == 200.0
@pytest.mark.usefixtures("init_integration")
async def test_energy_initial_state(
hass: HomeAssistant,
) -> None:
"""Test EnergySensor initial state is unknown."""
state = hass.states.get(ENERGY_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNKNOWN
@pytest.mark.usefixtures("init_integration")
async def test_energy_availability(
hass: HomeAssistant,
mock_light_device: MagicMock,
) -> None:
"""Test availability changes are reflected in energy sensor state."""
trigger_availability_callback(mock_light_device, False)
await hass.async_block_till_done()
state = hass.states.get(ENERGY_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNAVAILABLE
trigger_availability_callback(mock_light_device, True)
await hass.async_block_till_done()
state = hass.states.get(ENERGY_ENTITY_ID)
assert state is not None
assert state.state != STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sunricher_dali/test_sensor.py",
"license": "Apache License 2.0",
"lines": 147,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/switch/test_condition.py | """Test switch 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.
Note: The lights are used to ensure that only switch entities are considered
in the condition evaluation and not other toggle entities.
"""
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."""
return (await target_entities(hass, "switch"))["included"]
@pytest.mark.parametrize(
"condition",
[
"switch.is_off",
"switch.is_on",
],
)
async def test_switch_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the switch 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("switch"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="switch.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_condition_states_any(
condition="switch.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_switch_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 switch state condition with the 'any' behavior."""
other_entity_ids = set(target_switches) - {entity_id}
# Set all switches, including the tested switch, to the initial state
for eid in target_switches:
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 lights to ensure that they don't impact the condition
for state in states:
for eid in target_lights:
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("switch"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="switch.is_on",
target_states=[STATE_ON],
other_states=[STATE_OFF],
),
*parametrize_condition_states_all(
condition="switch.is_off",
target_states=[STATE_OFF],
other_states=[STATE_ON],
),
],
)
async def test_switch_state_condition_behavior_all(
hass: HomeAssistant,
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 switch 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_switches) - {entity_id}
# Set all switches, including the tested switch, to the initial state
for eid in target_switches:
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/switch/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/tailscale/test_coordinator.py | """Tests for the Tailscale coordinator."""
from datetime import timedelta
from unittest.mock import MagicMock
from freezegun.api import FrozenDateTimeFactory
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry
async def test_remove_stale_devices(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_tailscale: MagicMock,
device_registry: dr.DeviceRegistry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that devices removed from Tailscale are removed from device registry."""
# Verify initial devices exist (should be 3 from fixture)
devices = dr.async_entries_for_config_entry(
device_registry, init_integration.entry_id
)
assert len(devices) == 3
# Store device IDs for later verification
device_ids = [list(device.identifiers)[0][1] for device in devices]
assert "123456" in device_ids
assert "123457" in device_ids
assert "123458" in device_ids
# Simulate device removal in Tailscale (only device 123456 remains)
# Get the original device data from the mock
original_devices = mock_tailscale.devices.return_value
mock_tailscale.devices.return_value = {"123456": original_devices["123456"]}
# Trigger natural refresh by advancing time
freezer.tick(timedelta(seconds=60))
await hass.async_block_till_done()
# Verify devices 123457 and 123458 were removed
remaining_devices = dr.async_entries_for_config_entry(
device_registry, init_integration.entry_id
)
assert len(remaining_devices) == 1
remaining_device = remaining_devices[0]
remaining_id = list(remaining_device.identifiers)[0][1]
assert remaining_id == "123456"
assert remaining_device.name == "frencks-iphone"
async def test_no_devices_removed_when_all_present(
hass: HomeAssistant,
init_integration: MockConfigEntry,
device_registry: dr.DeviceRegistry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that no devices are removed when all Tailscale devices still exist."""
# Verify initial devices exist (should be 3 from fixture)
initial_devices = dr.async_entries_for_config_entry(
device_registry, init_integration.entry_id
)
assert len(initial_devices) == 3
# Trigger natural refresh (devices unchanged)
freezer.tick(timedelta(seconds=60))
await hass.async_block_till_done()
# Verify no devices were removed
final_devices = dr.async_entries_for_config_entry(
device_registry, init_integration.entry_id
)
assert len(final_devices) == 3
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tailscale/test_coordinator.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/telegram_bot/test_init.py | """Init tests for the Telegram Bot integration."""
from homeassistant.components.telegram_bot.const import (
ATTR_PARSER,
CONF_API_ENDPOINT,
DEFAULT_API_ENDPOINT,
DOMAIN,
PARSER_MD,
PLATFORM_BROADCAST,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_API_KEY, CONF_PLATFORM
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_migration_error(
hass: HomeAssistant,
mock_external_calls: None,
) -> None:
"""Test migrate config entry from 1.1 to 1.2."""
mock_config_entry = MockConfigEntry(
unique_id="mock api key",
domain=DOMAIN,
data={
CONF_PLATFORM: PLATFORM_BROADCAST,
CONF_API_KEY: "mock api key",
},
options={ATTR_PARSER: PARSER_MD},
version=99,
)
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.MIGRATION_ERROR
async def test_migrate_entry_from_1_1(
hass: HomeAssistant,
mock_external_calls: None,
) -> None:
"""Test migrate config entry from 1.1 to 1.2."""
mock_config_entry = MockConfigEntry(
unique_id="mock api key",
domain=DOMAIN,
data={
CONF_PLATFORM: PLATFORM_BROADCAST,
CONF_API_KEY: "mock api key",
},
options={ATTR_PARSER: PARSER_MD},
)
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
assert mock_config_entry.version == 1
assert mock_config_entry.minor_version == 2
assert mock_config_entry.data == {
CONF_PLATFORM: PLATFORM_BROADCAST,
CONF_API_KEY: "mock api key",
CONF_API_ENDPOINT: DEFAULT_API_ENDPOINT,
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/telegram_bot/test_init.py",
"license": "Apache License 2.0",
"lines": 57,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tibber/test_binary_sensor.py | """Tests for the Tibber binary sensors."""
from __future__ import annotations
from unittest.mock import AsyncMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.recorder import Recorder
from homeassistant.const import STATE_OFF, STATE_ON, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .conftest import create_tibber_device
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return [Platform.BINARY_SENSOR]
async def test_binary_sensor_snapshot(
recorder_mock: Recorder,
hass: HomeAssistant,
config_entry: MockConfigEntry,
data_api_client_mock: AsyncMock,
setup_credentials: None,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test binary sensor entities against snapshot."""
device = create_tibber_device(
connector_status="connected",
charging_status="charging",
device_status="on",
is_online="true",
)
data_api_client_mock.get_all_devices = AsyncMock(return_value={"device-id": device})
data_api_client_mock.update_devices = AsyncMock(return_value={"device-id": device})
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize(
(
"entity_suffix",
"connector_status",
"charging_status",
"device_status",
"is_online",
"expected_state",
),
[
("plug", "connected", None, None, None, STATE_ON),
("plug", "disconnected", None, None, None, STATE_OFF),
("charging", None, "charging", None, None, STATE_ON),
("charging", None, "idle", None, None, STATE_OFF),
("power", None, None, "on", None, STATE_ON),
("power", None, None, "off", None, STATE_OFF),
("connectivity", None, None, None, "true", STATE_ON),
("connectivity", None, None, None, "True", STATE_ON),
("connectivity", None, None, None, "false", STATE_OFF),
("connectivity", None, None, None, "False", STATE_OFF),
],
)
async def test_binary_sensor_states(
recorder_mock: Recorder,
hass: HomeAssistant,
config_entry: MockConfigEntry,
data_api_client_mock: AsyncMock,
setup_credentials: None,
entity_suffix: str,
connector_status: str | None,
charging_status: str | None,
device_status: str | None,
is_online: str | None,
expected_state: str,
) -> None:
"""Test binary sensor state values."""
device = create_tibber_device(
connector_status=connector_status,
charging_status=charging_status,
device_status=device_status,
is_online=is_online,
)
data_api_client_mock.get_all_devices = AsyncMock(return_value={"device-id": device})
data_api_client_mock.update_devices = AsyncMock(return_value={"device-id": device})
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
entity_id = f"binary_sensor.test_device_{entity_suffix}"
state = hass.states.get(entity_id)
assert state is not None
assert state.state == expected_state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tibber/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 86,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/uhoo/test_config_flow.py | """Test the Uhoo config flow."""
from unittest.mock import AsyncMock
import pytest
from uhooapi.errors import UhooError, UnauthorizedError
from homeassistant.components.uhoo.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_user_flow(
hass: HomeAssistant, mock_uhoo_client: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test a complete user flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: "valid-api-key-12345"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "uHoo (12345)"
assert result["data"] == {CONF_API_KEY: "valid-api-key-12345"}
mock_setup_entry.assert_called_once()
async def test_user_duplicate_entry(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test duplicate entry aborts."""
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_API_KEY: "valid-api-key-12345"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("exception", "error_type"),
[
(UhooError("asd"), "cannot_connect"),
(UnauthorizedError("Invalid credentials"), "invalid_auth"),
(Exception(), "unknown"),
],
)
async def test_user_flow_exceptions(
hass: HomeAssistant,
mock_uhoo_client: AsyncMock,
exception: Exception,
error_type: str,
) -> None:
"""Test form when client raises various exceptions."""
mock_uhoo_client.login.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_KEY: "test-api-key"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": error_type}
mock_uhoo_client.login.assert_called_once()
mock_uhoo_client.login.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "test-api-key"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/uhoo/test_config_flow.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/uhoo/test_init.py | """Tests for __init__.py with coordinator."""
from unittest.mock import AsyncMock
from aiodns.error import DNSError
from aiohttp.client_exceptions import ClientConnectionError
import pytest
from uhooapi.errors import UhooError, UnauthorizedError
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_entry(
hass: HomeAssistant,
mock_uhoo_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_remove(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
"field",
[
"login",
"setup_devices",
],
)
@pytest.mark.parametrize(
("exc", "state"),
[
(ClientConnectionError, ConfigEntryState.SETUP_RETRY),
(DNSError, ConfigEntryState.SETUP_RETRY),
(UhooError, ConfigEntryState.SETUP_RETRY),
(UnauthorizedError, ConfigEntryState.SETUP_ERROR),
],
)
async def test_setup_failure(
hass: HomeAssistant,
mock_uhoo_client: AsyncMock,
mock_config_entry: MockConfigEntry,
field: str,
exc: Exception,
state: ConfigEntryState,
) -> None:
"""Test setup failure."""
# Set the exception on the specified field
getattr(mock_uhoo_client, field).side_effect = exc
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/uhoo/test_init.py",
"license": "Apache License 2.0",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/uhoo/test_sensor.py | """Tests for sensor.py with Uhoo sensors."""
from unittest.mock import AsyncMock, MagicMock
from freezegun.api import FrozenDateTimeFactory
from syrupy.assertion import SnapshotAssertion
from uhooapi.errors import UhooError
from homeassistant.components.uhoo.const import UPDATE_INTERVAL
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
STATE_UNAVAILABLE,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_sensor_snapshot(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_uhoo_client: AsyncMock,
mock_device: AsyncMock,
) -> None:
"""Test sensor setup with snapshot."""
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_async_setup_entry_multiple_devices(
hass: HomeAssistant,
mock_uhoo_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_device: MagicMock,
mock_device2: MagicMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test setting up sensor entities for multiple devices."""
# Update the mock to return data for two devices
mock_uhoo_client.get_latest_data.return_value = [
{
"serialNumber": "23f9239m92m3ffkkdkdd",
"deviceName": "Test Device",
"humidity": 45.5,
"temperature": 22.0,
"co": 1.5,
"co2": 450.0,
"pm25": 12.3,
"airPressure": 1013.25,
"tvoc": 150.0,
"no2": 20.0,
"ozone": 30.0,
"virusIndex": 2.0,
"moldIndex": 1.5,
"userSettings": {"temp": "c"},
},
{
"serialNumber": "13e2r2fi2ii2i3993822",
"deviceName": "Test Device 2",
"humidity": 50.0,
"temperature": 21.0,
"co": 1.0,
"co2": 400.0,
"pm25": 10.0,
"airPressure": 1010.0,
"tvoc": 100.0,
"no2": 15.0,
"ozone": 25.0,
"virusIndex": 1.0,
"moldIndex": 1.0,
"userSettings": {"temp": "c"},
},
]
mock_uhoo_client.devices = {
"23f9239m92m3ffkkdkdd": mock_device,
"13e2r2fi2ii2i3993822": mock_device2,
}
# Setup the integration with the updated mock data
await setup_integration(hass, mock_config_entry)
assert len(entity_registry.entities) == 22
async def test_sensor_availability_changes_with_connection_errors(
hass: HomeAssistant,
mock_uhoo_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test sensor availability changes over time with different connection errors."""
await setup_integration(hass, mock_config_entry)
state = hass.states.get("sensor.test_device_carbon_dioxide")
assert state.state != STATE_UNAVAILABLE
mock_uhoo_client.get_latest_data.side_effect = UhooError(
"The device is unavailable"
)
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("sensor.test_device_carbon_dioxide")
assert state.state == STATE_UNAVAILABLE
mock_uhoo_client.get_latest_data.side_effect = None
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("sensor.test_device_carbon_dioxide")
assert state.state != STATE_UNAVAILABLE
async def test_different_unit(
hass: HomeAssistant,
mock_uhoo_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_device: MagicMock,
) -> None:
"""Test sensor interprets value correctly with different unit settings."""
mock_device.user_settings = {"temp": "f"}
await setup_integration(hass, mock_config_entry)
state = hass.states.get("sensor.test_device_temperature")
assert state.state == "-5.55555555555556"
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == UnitOfTemperature.CELSIUS
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/uhoo/test_sensor.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/vacuum/test_condition.py | """Test vacuum conditions."""
from typing import Any
import pytest
from homeassistant.components.vacuum import VacuumActivity
from homeassistant.core import HomeAssistant
from tests.components import (
ConditionStateDescription,
assert_condition_gated_by_labs_flag,
create_target_condition,
other_states,
parametrize_condition_states_all,
parametrize_condition_states_any,
parametrize_target_entities,
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(
"condition",
[
"vacuum.is_cleaning",
"vacuum.is_docked",
"vacuum.is_encountering_an_error",
"vacuum.is_paused",
"vacuum.is_returning",
],
)
async def test_vacuum_conditions_gated_by_labs_flag(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture, condition: str
) -> None:
"""Test the vacuum 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("vacuum"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_any(
condition="vacuum.is_cleaning",
target_states=[VacuumActivity.CLEANING],
other_states=other_states(VacuumActivity.CLEANING),
),
*parametrize_condition_states_any(
condition="vacuum.is_docked",
target_states=[VacuumActivity.DOCKED],
other_states=other_states(VacuumActivity.DOCKED),
),
*parametrize_condition_states_any(
condition="vacuum.is_encountering_an_error",
target_states=[VacuumActivity.ERROR],
other_states=other_states(VacuumActivity.ERROR),
),
*parametrize_condition_states_any(
condition="vacuum.is_paused",
target_states=[VacuumActivity.PAUSED],
other_states=other_states(VacuumActivity.PAUSED),
),
*parametrize_condition_states_any(
condition="vacuum.is_returning",
target_states=[VacuumActivity.RETURNING],
other_states=other_states(VacuumActivity.RETURNING),
),
],
)
async def test_vacuum_state_condition_behavior_any(
hass: HomeAssistant,
target_vacuums: 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 vacuum state condition with the 'any' behavior."""
other_entity_ids = set(target_vacuums) - {entity_id}
# Set all vacuums, including the tested vacuum, to the initial state
for eid in target_vacuums:
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",
)
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 vacuums 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("vacuum"),
)
@pytest.mark.parametrize(
("condition", "condition_options", "states"),
[
*parametrize_condition_states_all(
condition="vacuum.is_cleaning",
target_states=[VacuumActivity.CLEANING],
other_states=other_states(VacuumActivity.CLEANING),
),
*parametrize_condition_states_all(
condition="vacuum.is_docked",
target_states=[VacuumActivity.DOCKED],
other_states=other_states(VacuumActivity.DOCKED),
),
*parametrize_condition_states_all(
condition="vacuum.is_encountering_an_error",
target_states=[VacuumActivity.ERROR],
other_states=other_states(VacuumActivity.ERROR),
),
*parametrize_condition_states_all(
condition="vacuum.is_paused",
target_states=[VacuumActivity.PAUSED],
other_states=other_states(VacuumActivity.PAUSED),
),
*parametrize_condition_states_all(
condition="vacuum.is_returning",
target_states=[VacuumActivity.RETURNING],
other_states=other_states(VacuumActivity.RETURNING),
),
],
)
async def test_vacuum_state_condition_behavior_all(
hass: HomeAssistant,
target_vacuums: 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 vacuum state condition with the 'all' behavior."""
other_entity_ids = set(target_vacuums) - {entity_id}
# Set all vacuums, including the tested vacuum, to the initial state
for eid in target_vacuums:
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/vacuum/test_condition.py",
"license": "Apache License 2.0",
"lines": 168,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/vodafone_station/test_image.py | """Tests for Vodafone Station image platform."""
from http import HTTPStatus
from io import BytesIO
from unittest.mock import AsyncMock, patch
from aiovodafone.const import WIFI_DATA
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.image import DOMAIN as IMAGE_DOMAIN
from homeassistant.components.vodafone_station.const import SCAN_INTERVAL
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 homeassistant.util import dt as dt_util
from . import setup_integration
from .const import TEST_SERIAL_NUMBER
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
from tests.typing import ClientSessionGenerator
@pytest.mark.freeze_time("2026-01-05T15:00:00+00:00")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_vodafone_station_router: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.vodafone_station.PLATFORMS", [Platform.IMAGE]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.freeze_time("2023-12-02T13:00:00+00:00")
async def test_image_entity(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_vodafone_station_router: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test image entity."""
entity_id = f"image.vodafone_station_{TEST_SERIAL_NUMBER}_guest_network"
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
# test image entities are generated as expected
states = hass.states.async_all(IMAGE_DOMAIN)
assert len(states) == 2
state = states[0]
assert state.name == f"Vodafone Station ({TEST_SERIAL_NUMBER}) Guest network"
assert state.entity_id == entity_id
access_token = state.attributes["access_token"]
assert state.attributes == {
"access_token": access_token,
"entity_picture": f"/api/image_proxy/{entity_id}?token={access_token}",
"friendly_name": f"Vodafone Station ({TEST_SERIAL_NUMBER}) Guest network",
}
entity_entry = entity_registry.async_get(entity_id)
assert entity_entry is not None
assert entity_entry.unique_id == f"{TEST_SERIAL_NUMBER}-guest-qr-code"
# test image download
client = await hass_client()
resp = await client.get(f"/api/image_proxy/{entity_id}")
assert resp.status == HTTPStatus.OK
body = await resp.read()
assert body == snapshot
assert (state := hass.states.async_all(IMAGE_DOMAIN)[0])
assert state.state == "2023-12-02T13:00:00+00:00"
@pytest.mark.freeze_time("2023-12-02T13:00:00+00:00")
async def test_image_update(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
freezer: FrozenDateTimeFactory,
mock_vodafone_station_router: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test image update."""
entity_id = f"image.vodafone_station_{TEST_SERIAL_NUMBER}_guest_network"
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
client = await hass_client()
resp = await client.get(f"/api/image_proxy/{entity_id}")
assert resp.status == HTTPStatus.OK
resp_body = await resp.read()
assert (state := hass.states.get(entity_id))
assert state.state == "2023-12-02T13:00:00+00:00"
mock_vodafone_station_router.get_wifi_data.return_value = {
WIFI_DATA: {
"guest": {
"on": 1,
"ssid": "Wifi-Guest",
"qr_code": BytesIO(b"fake-qr-code-guest-updated"),
},
"guest_5g": {
"on": 0,
"ssid": "Wifi-Guest-5Ghz",
"qr_code": BytesIO(b"fake-qr-code-guest-5ghz-updated"),
},
}
}
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
new_time = dt_util.utcnow()
resp = await client.get(f"/api/image_proxy/{entity_id}")
assert resp.status == HTTPStatus.OK
resp_body_new = await resp.read()
assert resp_body != resp_body_new
assert (state := hass.states.get(entity_id))
assert state.state == new_time.isoformat()
async def test_no_wifi_data(
hass: HomeAssistant,
mock_vodafone_station_router: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test image entity."""
mock_vodafone_station_router.get_wifi_data.return_value = {WIFI_DATA: {}}
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
# test image entities are not generated
states = hass.states.async_all(IMAGE_DOMAIN)
assert len(states) == 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/vodafone_station/test_image.py",
"license": "Apache License 2.0",
"lines": 121,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/vodafone_station/test_switch.py | """Tests for Vodafone Station switch platform."""
from unittest.mock import AsyncMock, patch
from aiovodafone.const import WIFI_DATA
from aiovodafone.exceptions import (
AlreadyLogged,
CannotAuthenticate,
CannotConnect,
GenericLoginError,
)
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SERVICE_TOGGLE
from homeassistant.components.vodafone_station.const import DOMAIN
from homeassistant.components.vodafone_station.coordinator import SCAN_INTERVAL
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from homeassistant.util import slugify
from . import setup_integration
from .const import TEST_SERIAL_NUMBER
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_vodafone_station_router: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.vodafone_station.PLATFORMS", [Platform.SWITCH]
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("wifi_key", "wifi_name", "wifi_state"),
[
("guest", "guest_network", "on"),
("guest_5g", "guest_5ghz_network", "off"),
],
)
async def test_switch(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_vodafone_station_router: AsyncMock,
mock_config_entry: MockConfigEntry,
wifi_key: str,
wifi_name: str,
wifi_state: str,
) -> None:
"""Test switch."""
mock_vodafone_station_router.get_wifi_data.return_value = {
WIFI_DATA: {
f"{wifi_key}": {
"on": 1 if wifi_state == "on" else 0,
"ssid": f"{wifi_name}",
}
}
}
await setup_integration(hass, mock_config_entry)
entity_id = f"switch.vodafone_station_{TEST_SERIAL_NUMBER}_{slugify(wifi_name)}"
assert (state := hass.states.get(entity_id))
assert state.state == wifi_state
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TOGGLE,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert mock_vodafone_station_router.set_wifi_status.call_count == 1
mock_vodafone_station_router.get_wifi_data.return_value = {
WIFI_DATA: {
f"{wifi_key}": {
"on": 0 if wifi_state == "on" else 1,
"ssid": f"{wifi_name}",
}
}
}
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state == ("off" if wifi_state == "on" else "on")
@pytest.mark.parametrize(
("side_effect", "key", "error"),
[
(CannotConnect, "cannot_execute_action", "CannotConnect()"),
(AlreadyLogged, "cannot_execute_action", "AlreadyLogged()"),
(GenericLoginError, "cannot_execute_action", "GenericLoginError()"),
(CannotAuthenticate, "cannot_authenticate", "CannotAuthenticate()"),
],
)
async def test_switch_fails(
hass: HomeAssistant,
mock_vodafone_station_router: AsyncMock,
mock_config_entry: MockConfigEntry,
side_effect: Exception,
key: str,
error: str,
) -> None:
"""Test switch action fails."""
await setup_integration(hass, mock_config_entry)
mock_vodafone_station_router.set_wifi_status.side_effect = side_effect
with pytest.raises(HomeAssistantError) as exc_info:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TOGGLE,
{
ATTR_ENTITY_ID: f"switch.vodafone_station_{TEST_SERIAL_NUMBER}_guest_5ghz_network"
},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == key
assert exc_info.value.translation_placeholders == {"error": error}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/vodafone_station/test_switch.py",
"license": "Apache License 2.0",
"lines": 117,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/waterfurnace/test_config_flow.py | """Test the WaterFurnace config flow."""
from unittest.mock import AsyncMock, Mock
import pytest
from waterfurnace.waterfurnace import WFCredentialError, WFException
from homeassistant.components.waterfurnace.const import DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_user_flow_success(
hass: HomeAssistant, mock_waterfurnace_client: Mock, mock_setup_entry: AsyncMock
) -> None:
"""Test successful user flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "test_user", CONF_PASSWORD: "test_password"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "WaterFurnace test_user"
assert result["data"] == {
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
}
assert result["result"].unique_id == "TEST_GWID_12345"
# Verify login was called (once during config flow, once during setup)
assert mock_waterfurnace_client.login.called
@pytest.mark.parametrize(
("exception", "error"),
[
(WFCredentialError("Invalid credentials"), "invalid_auth"),
(WFException("Connection failed"), "cannot_connect"),
(Exception("Unexpected error"), "unknown"),
],
)
async def test_user_flow_exceptions(
hass: HomeAssistant,
mock_waterfurnace_client: Mock,
mock_setup_entry: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test user flow with invalid credentials."""
mock_waterfurnace_client.login.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "bad_user", CONF_PASSWORD: "bad_password"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error}
# Verify we can recover from the error
mock_waterfurnace_client.login.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_USERNAME: "test_user", CONF_PASSWORD: "test_password"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_user_flow_no_gwid(
hass: HomeAssistant, mock_waterfurnace_client: Mock, mock_setup_entry: AsyncMock
) -> None:
"""Test user flow with invalid credentials."""
mock_waterfurnace_client.gwid = None
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: "bad_user",
CONF_PASSWORD: "bad_password",
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
mock_waterfurnace_client.gwid = "TEST_GWID_12345"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_user_flow_already_configured(
hass: HomeAssistant,
mock_waterfurnace_client: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test user flow when device is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_import_flow_success(
hass: HomeAssistant, mock_waterfurnace_client: Mock, mock_setup_entry: AsyncMock
) -> None:
"""Test successful import flow from YAML."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_USERNAME: "test_user", CONF_PASSWORD: "test_password"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "WaterFurnace test_user"
assert result["data"] == {
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
}
assert result["result"].unique_id == "TEST_GWID_12345"
async def test_import_flow_already_configured(
hass: HomeAssistant,
mock_waterfurnace_client: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test import flow when device is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_USERNAME: "test_user", CONF_PASSWORD: "test_password"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("exception", "reason"),
[
(WFCredentialError("Invalid credentials"), "invalid_auth"),
(WFException("Connection failed"), "cannot_connect"),
(Exception("Unexpected error"), "unknown"),
],
)
async def test_import_flow_exceptions(
hass: HomeAssistant,
mock_waterfurnace_client: Mock,
exception: Exception,
reason: str,
) -> None:
"""Test import flow with connection error."""
mock_waterfurnace_client.login.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_USERNAME: "test_user", CONF_PASSWORD: "test_password"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == reason
async def test_import_flow_no_gwid(
hass: HomeAssistant, mock_waterfurnace_client: Mock
) -> None:
"""Test import flow with connection error."""
mock_waterfurnace_client.gwid = None
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_USERNAME: "test_user", CONF_PASSWORD: "test_password"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/waterfurnace/test_config_flow.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/yardian/test_sensor.py | """Tests for Yardian sensors."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
import pytest
from pyyardian import OperationInfo
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.yardian.const import DOMAIN
from homeassistant.components.yardian.coordinator import SCAN_INTERVAL
from homeassistant.const import STATE_UNKNOWN
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
pytestmark = pytest.mark.usefixtures("sensor_platform_only")
def _make_oper_info(**overrides: object) -> OperationInfo:
base = {
"iRainDelay": 3600,
"iSensorDelay": 5,
"iWaterHammerDuration": 2,
"iStandby": 1,
"fFreezePrevent": 1,
}
base.update(overrides)
return OperationInfo(**base)
async def _async_trigger_refresh(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
) -> None:
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_yardian_client: object,
) -> None:
"""Snapshot all Yardian sensor entities."""
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_diagnostic_sensors(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_yardian_client: object,
) -> None:
"""Diagnostic sensors are disabled by default."""
await setup_integration(hass, mock_config_entry)
for entity_id in (
"sensor.yardian_smart_sprinkler_zone_delay",
"sensor.yardian_smart_sprinkler_water_hammer_reduction",
):
reg_entry = entity_registry.async_get(entity_id)
assert reg_entry is not None
assert reg_entry.disabled
assert reg_entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_zone_delay_sensor_interprets_timestamp_and_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_yardian_client: AsyncMock,
freezer: FrozenDateTimeFactory,
entity_registry: er.EntityRegistry,
) -> None:
"""Zone delay interprets timestamps and guards against invalid values."""
freezer.move_to(datetime(2024, 1, 1, tzinfo=UTC))
await setup_integration(hass, mock_config_entry)
entity_id = entity_registry.async_get_entity_id(
"sensor", DOMAIN, "yid123_zone_delay"
)
assert entity_id is not None
assert hass.states.get(entity_id).state == "5"
absolute_delay = int(
(dt_util.utcnow() + SCAN_INTERVAL + timedelta(minutes=2)).timestamp()
)
mock_yardian_client.fetch_oper_info.return_value = _make_oper_info(
iSensorDelay=absolute_delay
)
await _async_trigger_refresh(hass, freezer)
assert hass.states.get(entity_id).state == "120"
mock_yardian_client.fetch_oper_info.return_value = _make_oper_info(
iSensorDelay="invalid"
)
await _async_trigger_refresh(hass, freezer)
assert hass.states.get(entity_id).state == STATE_UNKNOWN
mock_yardian_client.fetch_oper_info.return_value = _make_oper_info(
iSensorDelay=None
)
await _async_trigger_refresh(hass, freezer)
assert hass.states.get(entity_id).state == STATE_UNKNOWN
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/yardian/test_sensor.py",
"license": "Apache License 2.0",
"lines": 95,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/neato/services.py | """Neato services."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.vacuum import DOMAIN as VACUUM_DOMAIN
from homeassistant.const import ATTR_MODE
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, service
from .const import DOMAIN
ATTR_NAVIGATION = "navigation"
ATTR_CATEGORY = "category"
ATTR_ZONE = "zone"
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up services."""
# Vacuum Services
service.async_register_platform_entity_service(
hass,
DOMAIN,
"custom_cleaning",
entity_domain=VACUUM_DOMAIN,
schema={
vol.Optional(ATTR_MODE, default=2): cv.positive_int,
vol.Optional(ATTR_NAVIGATION, default=1): cv.positive_int,
vol.Optional(ATTR_CATEGORY, default=4): cv.positive_int,
vol.Optional(ATTR_ZONE): cv.string,
},
func="neato_custom_cleaning",
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/neato/services.py",
"license": "Apache License 2.0",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sharkiq/services.py | """Shark IQ services."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.vacuum import DOMAIN as VACUUM_DOMAIN
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, service
from .const import ATTR_ROOMS, DOMAIN
SERVICE_CLEAN_ROOM = "clean_room"
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up services."""
# Vacuum Services
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_CLEAN_ROOM,
entity_domain=VACUUM_DOMAIN,
schema={
vol.Required(ATTR_ROOMS): vol.All(
cv.ensure_list, vol.Length(min=1), [cv.string]
),
},
func="async_clean_room",
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sharkiq/services.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/xiaomi_miio/services.py | """Xiaomi services."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.vacuum import DOMAIN as VACUUM_DOMAIN
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, service
from .const import DOMAIN
ATTR_RC_DURATION = "duration"
ATTR_RC_ROTATION = "rotation"
ATTR_RC_VELOCITY = "velocity"
ATTR_ZONE_ARRAY = "zone"
ATTR_ZONE_REPEATER = "repeats"
# Vacuum Services
SERVICE_MOVE_REMOTE_CONTROL = "vacuum_remote_control_move"
SERVICE_MOVE_REMOTE_CONTROL_STEP = "vacuum_remote_control_move_step"
SERVICE_START_REMOTE_CONTROL = "vacuum_remote_control_start"
SERVICE_STOP_REMOTE_CONTROL = "vacuum_remote_control_stop"
SERVICE_CLEAN_SEGMENT = "vacuum_clean_segment"
SERVICE_CLEAN_ZONE = "vacuum_clean_zone"
SERVICE_GOTO = "vacuum_goto"
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up services."""
# Vacuum Services
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_START_REMOTE_CONTROL,
entity_domain=VACUUM_DOMAIN,
schema=None,
func="async_remote_control_start",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_STOP_REMOTE_CONTROL,
entity_domain=VACUUM_DOMAIN,
schema=None,
func="async_remote_control_stop",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_MOVE_REMOTE_CONTROL,
entity_domain=VACUUM_DOMAIN,
schema={
vol.Optional(ATTR_RC_VELOCITY): vol.All(
vol.Coerce(float), vol.Clamp(min=-0.29, max=0.29)
),
vol.Optional(ATTR_RC_ROTATION): vol.All(
vol.Coerce(int), vol.Clamp(min=-179, max=179)
),
vol.Optional(ATTR_RC_DURATION): cv.positive_int,
},
func="async_remote_control_move",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_MOVE_REMOTE_CONTROL_STEP,
entity_domain=VACUUM_DOMAIN,
schema={
vol.Optional(ATTR_RC_VELOCITY): vol.All(
vol.Coerce(float), vol.Clamp(min=-0.29, max=0.29)
),
vol.Optional(ATTR_RC_ROTATION): vol.All(
vol.Coerce(int), vol.Clamp(min=-179, max=179)
),
vol.Optional(ATTR_RC_DURATION): cv.positive_int,
},
func="async_remote_control_move_step",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_CLEAN_ZONE,
entity_domain=VACUUM_DOMAIN,
schema={
vol.Required(ATTR_ZONE_ARRAY): vol.All(
list,
[
vol.ExactSequence(
[
vol.Coerce(int),
vol.Coerce(int),
vol.Coerce(int),
vol.Coerce(int),
]
)
],
),
vol.Required(ATTR_ZONE_REPEATER): vol.All(
vol.Coerce(int), vol.Clamp(min=1, max=3)
),
},
func="async_clean_zone",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_GOTO,
entity_domain=VACUUM_DOMAIN,
schema={
vol.Required("x_coord"): vol.Coerce(int),
vol.Required("y_coord"): vol.Coerce(int),
},
func="async_goto",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_CLEAN_SEGMENT,
entity_domain=VACUUM_DOMAIN,
schema={vol.Required("segments"): vol.Any(vol.Coerce(int), [vol.Coerce(int)])},
func="async_clean_segment",
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/xiaomi_miio/services.py",
"license": "Apache License 2.0",
"lines": 116,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ecovacs/services.py | """Ecovacs services."""
from __future__ import annotations
from homeassistant.components.vacuum import DOMAIN as VACUUM_DOMAIN
from homeassistant.core import HomeAssistant, SupportsResponse, callback
from homeassistant.helpers import service
from .const import DOMAIN
SERVICE_RAW_GET_POSITIONS = "raw_get_positions"
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up services."""
# Vacuum Services
service.async_register_platform_entity_service(
hass,
DOMAIN,
SERVICE_RAW_GET_POSITIONS,
entity_domain=VACUUM_DOMAIN,
schema=None,
func="async_raw_get_positions",
supports_response=SupportsResponse.ONLY,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ecovacs/services.py",
"license": "Apache License 2.0",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/huum/sensor.py | """Sensor platform for Huum sauna integration."""
from __future__ import annotations
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorStateClass,
)
from homeassistant.const import UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import HuumConfigEntry, HuumDataUpdateCoordinator
from .entity import HuumBaseEntity
async def async_setup_entry(
hass: HomeAssistant,
config_entry: HuumConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Huum sensors from a config entry."""
async_add_entities([HuumTemperatureSensor(config_entry.runtime_data)])
class HuumTemperatureSensor(HuumBaseEntity, SensorEntity):
"""Representation of a Huum temperature sensor."""
_attr_device_class = SensorDeviceClass.TEMPERATURE
_attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
_attr_state_class = SensorStateClass.MEASUREMENT
def __init__(self, coordinator: HuumDataUpdateCoordinator) -> None:
"""Initialize the temperature sensor."""
super().__init__(coordinator)
self._attr_unique_id = f"{coordinator.config_entry.entry_id}_temperature"
@property
def native_value(self) -> int | None:
"""Return the current temperature."""
return self.coordinator.data.temperature
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/huum/sensor.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/huum/test_sensor.py | """Tests for the Huum sensor entity."""
from unittest.mock import AsyncMock
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_with_selected_platforms
from tests.common import MockConfigEntry, snapshot_platform
async def test_sensor(
hass: HomeAssistant,
mock_huum: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the temperature sensor."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.SENSOR])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/huum/test_sensor.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/radarr/helpers.py | """Helper functions for Radarr."""
from typing import Any
from aiopyarr import RadarrMovie, RadarrQueue
def format_queue_item(item: Any, base_url: str | None = None) -> dict[str, Any]:
"""Format a single queue item."""
remaining = 1 if item.size == 0 else item.sizeleft / item.size
remaining_pct = 100 * (1 - remaining)
movie = item.movie
result: dict[str, Any] = {
"id": item.id,
"movie_id": item.movieId,
"title": movie["title"],
"download_title": item.title,
"progress": f"{remaining_pct:.2f}%",
"size": item.size,
"size_left": item.sizeleft,
"status": item.status,
"tracked_download_status": getattr(item, "trackedDownloadStatus", None),
"tracked_download_state": getattr(item, "trackedDownloadState", None),
"download_client": getattr(item, "downloadClient", None),
"download_id": getattr(item, "downloadId", None),
"indexer": getattr(item, "indexer", None),
"protocol": str(getattr(item, "protocol", None)),
"estimated_completion_time": str(
getattr(item, "estimatedCompletionTime", None)
),
"time_left": str(getattr(item, "timeleft", None)),
}
if quality := getattr(item, "quality", None):
result["quality"] = quality.quality.name
if languages := getattr(item, "languages", None):
result["languages"] = [lang.name for lang in languages]
if custom_format_score := getattr(item, "customFormatScore", None):
result["custom_format_score"] = custom_format_score
# Add movie images if available
# Note: item.movie is a dict (not object), so images are also dicts
if images := movie.get("images"):
result["images"] = {}
for image in images:
cover_type = image.get("coverType")
# Prefer remoteUrl (public TMDB URL) over local path
if remote_url := image.get("remoteUrl"):
result["images"][cover_type] = remote_url
elif base_url and (url := image.get("url")):
result["images"][cover_type] = f"{base_url.rstrip('/')}{url}"
return result
def format_queue(
queue: RadarrQueue, base_url: str | None = None
) -> dict[str, dict[str, Any]]:
"""Format queue for service response."""
movies = {}
for item in queue.records:
movies[item.title] = format_queue_item(item, base_url)
return movies
def format_movie_item(
movie: RadarrMovie, base_url: str | None = None
) -> dict[str, Any]:
"""Format a single movie item."""
result: dict[str, Any] = {
"id": movie.id,
"title": movie.title,
"year": movie.year,
"tmdb_id": movie.tmdbId,
"imdb_id": getattr(movie, "imdbId", None),
"status": movie.status,
"monitored": movie.monitored,
"has_file": movie.hasFile,
"size_on_disk": getattr(movie, "sizeOnDisk", None),
}
# Add path if available
if path := getattr(movie, "path", None):
result["path"] = path
# Add movie statistics if available
if statistics := getattr(movie, "statistics", None):
result["movie_file_count"] = getattr(statistics, "movieFileCount", None)
result["size_on_disk"] = getattr(statistics, "sizeOnDisk", None)
# Add movie images if available
if images := getattr(movie, "images", None):
images_dict: dict[str, str] = {}
for image in images:
cover_type = image.coverType
# Prefer remoteUrl (public TMDB URL) over local path
if remote_url := getattr(image, "remoteUrl", None):
images_dict[cover_type] = remote_url
elif base_url and (url := getattr(image, "url", None)):
images_dict[cover_type] = f"{base_url.rstrip('/')}{url}"
result["images"] = images_dict
return result
def format_movies(
movies: list[RadarrMovie], base_url: str | None = None
) -> dict[str, dict[str, Any]]:
"""Format movies list for service response."""
formatted_movies = {}
for movie in movies:
formatted_movies[movie.title] = format_movie_item(movie, base_url)
return formatted_movies
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/radarr/helpers.py",
"license": "Apache License 2.0",
"lines": 96,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/radarr/services.py | """Define services for the Radarr integration."""
from collections.abc import Awaitable, Callable
from typing import Any, Final, cast
from aiopyarr import exceptions
import voluptuous as vol
from homeassistant.const import CONF_URL
from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import selector, service
from .const import DOMAIN
from .coordinator import RadarrConfigEntry
from .helpers import format_movies, format_queue
# Service names
SERVICE_GET_MOVIES: Final = "get_movies"
SERVICE_GET_QUEUE: Final = "get_queue"
# Service attributes
ATTR_MOVIES: Final = "movies"
ATTR_ENTRY_ID: Final = "entry_id"
# Service parameter constants
CONF_MAX_ITEMS = "max_items"
# Default values - 0 means no limit
DEFAULT_MAX_ITEMS = 0
SERVICE_BASE_SCHEMA = vol.Schema(
{
vol.Required(ATTR_ENTRY_ID): selector.ConfigEntrySelector(
{"integration": DOMAIN}
),
}
)
SERVICE_GET_MOVIES_SCHEMA = SERVICE_BASE_SCHEMA
SERVICE_GET_QUEUE_SCHEMA = SERVICE_BASE_SCHEMA.extend(
{
vol.Optional(CONF_MAX_ITEMS, default=DEFAULT_MAX_ITEMS): vol.All(
vol.Coerce(int), vol.Range(min=0, max=500)
),
}
)
async def _handle_api_errors[_T](func: Callable[[], Awaitable[_T]]) -> _T:
"""Handle API errors and raise HomeAssistantError with user-friendly messages."""
try:
return await func()
except exceptions.ArrAuthenticationException as ex:
raise HomeAssistantError("Authentication failed for Radarr") from ex
except exceptions.ArrConnectionException as ex:
raise HomeAssistantError("Failed to connect to Radarr") from ex
except exceptions.ArrException as ex:
raise HomeAssistantError(f"Radarr API error: {ex}") from ex
async def _async_get_movies(call: ServiceCall) -> dict[str, Any]:
"""Get all Radarr movies."""
entry: RadarrConfigEntry = service.async_get_config_entry(
call.hass, DOMAIN, call.data[ATTR_ENTRY_ID]
)
api_client = entry.runtime_data.status.api_client
movies_list = await _handle_api_errors(api_client.async_get_movies)
# Get base URL from config entry for image URLs
base_url = entry.data[CONF_URL]
movies = format_movies(cast(list, movies_list), base_url)
return {
ATTR_MOVIES: movies,
}
async def _async_get_queue(call: ServiceCall) -> dict[str, Any]:
"""Get Radarr queue."""
entry: RadarrConfigEntry = service.async_get_config_entry(
call.hass, DOMAIN, call.data[ATTR_ENTRY_ID]
)
max_items: int = call.data[CONF_MAX_ITEMS]
api_client = entry.runtime_data.status.api_client
if max_items > 0:
page_size = max_items
else:
# Get total count first, then fetch all items
queue_preview = await _handle_api_errors(
lambda: api_client.async_get_queue(page_size=1)
)
total = queue_preview.totalRecords
page_size = total if total > 0 else 1
queue = await _handle_api_errors(
lambda: api_client.async_get_queue(page_size=page_size, include_movie=True)
)
# Get base URL from config entry for image URLs
base_url = entry.data[CONF_URL]
movies = format_queue(queue, base_url)
return {ATTR_MOVIES: movies}
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Register services for the Radarr integration."""
hass.services.async_register(
DOMAIN,
SERVICE_GET_MOVIES,
_async_get_movies,
schema=SERVICE_GET_MOVIES_SCHEMA,
supports_response=SupportsResponse.ONLY,
)
hass.services.async_register(
DOMAIN,
SERVICE_GET_QUEUE,
_async_get_queue,
schema=SERVICE_GET_QUEUE_SCHEMA,
supports_response=SupportsResponse.ONLY,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/radarr/services.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:tests/components/radarr/test_services.py | """Test Radarr services."""
from unittest.mock import patch
from aiopyarr import ArrAuthenticationException, ArrConnectionException
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.radarr.const import DOMAIN
from homeassistant.components.radarr.services import (
ATTR_ENTRY_ID,
SERVICE_GET_MOVIES,
SERVICE_GET_QUEUE,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from . import create_entry, setup_integration
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_get_queue_service(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
snapshot: SnapshotAssertion,
) -> None:
"""Test the get_queue service."""
entry = await setup_integration(hass, aioclient_mock)
response = await hass.services.async_call(
DOMAIN,
SERVICE_GET_QUEUE,
{ATTR_ENTRY_ID: entry.entry_id},
blocking=True,
return_response=True,
)
# Explicit assertion for specific behavior
assert len(response["movies"]) == 2
# Snapshot for full structure validation
assert response == snapshot
async def test_get_movies_service(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
snapshot: SnapshotAssertion,
) -> None:
"""Test the get_movies service."""
entry = await setup_integration(hass, aioclient_mock)
response = await hass.services.async_call(
DOMAIN,
SERVICE_GET_MOVIES,
{ATTR_ENTRY_ID: entry.entry_id},
blocking=True,
return_response=True,
)
# Explicit assertion for specific behavior
assert len(response["movies"]) == 2
# Snapshot for full structure validation
assert response == snapshot
@pytest.mark.parametrize(
("service", "method"),
[(SERVICE_GET_QUEUE, "async_get_queue"), (SERVICE_GET_MOVIES, "async_get_movies")],
)
async def test_services_api_connection_error(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
service: str,
method: str,
) -> None:
"""Test services with API connection error."""
entry = await setup_integration(hass, aioclient_mock)
with (
patch(
f"homeassistant.components.radarr.coordinator.RadarrClient.{method}",
side_effect=ArrConnectionException(None, "Connection failed"),
),
pytest.raises(HomeAssistantError, match="Failed to connect to Radarr"),
):
await hass.services.async_call(
DOMAIN,
service,
{ATTR_ENTRY_ID: entry.entry_id},
blocking=True,
return_response=True,
)
@pytest.mark.parametrize(
("service", "method"),
[(SERVICE_GET_QUEUE, "async_get_queue"), (SERVICE_GET_MOVIES, "async_get_movies")],
)
async def test_get_movies_service_api_auth_error(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
service: str,
method: str,
) -> None:
"""Test services with API authentication error."""
entry = await setup_integration(hass, aioclient_mock)
with (
patch(
f"homeassistant.components.radarr.coordinator.RadarrClient.{method}",
side_effect=ArrAuthenticationException(None, "Authentication failed"),
),
pytest.raises(HomeAssistantError, match="Authentication failed for Radarr"),
):
await hass.services.async_call(
DOMAIN,
service,
{ATTR_ENTRY_ID: entry.entry_id},
blocking=True,
return_response=True,
)
@pytest.mark.parametrize(
"service",
[SERVICE_GET_QUEUE, SERVICE_GET_MOVIES],
)
async def test_services_invalid_entry(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
service: str,
) -> None:
"""Test get_queue with invalid entry id."""
# Set up at least one entry so the service gets registered
await setup_integration(hass, aioclient_mock)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
service,
{ATTR_ENTRY_ID: "invalid_id"},
blocking=True,
return_response=True,
)
assert err.value.translation_key == "service_config_entry_not_found"
@pytest.mark.parametrize(
"service",
[SERVICE_GET_QUEUE, SERVICE_GET_MOVIES],
)
async def test_services_entry_not_loaded(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
service: str,
) -> None:
"""Test get_queue with entry that's not loaded."""
# First set up one entry to register the service
await setup_integration(hass, aioclient_mock)
# Now create a second entry that isn't loaded
unloaded_entry = create_entry(hass)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
service,
{ATTR_ENTRY_ID: unloaded_entry.entry_id},
blocking=True,
return_response=True,
)
assert err.value.translation_key == "service_config_entry_not_loaded"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/radarr/test_services.py",
"license": "Apache License 2.0",
"lines": 147,
"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.