sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
home-assistant/core:homeassistant/components/linkplay/select.py | """Support for LinkPlay select."""
from __future__ import annotations
from collections.abc import Awaitable, Callable, Coroutine
from dataclasses import dataclass
import logging
from typing import Any
from linkplay.bridge import LinkPlayBridge, LinkPlayPlayer
from linkplay.consts import AudioOutputHwMode
from linkplay.manufacturers import MANUFACTURER_WIIM
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import LinkPlayConfigEntry
from .entity import LinkPlayBaseEntity, exception_wrap
_LOGGER = logging.getLogger(__name__)
AUDIO_OUTPUT_HW_MODE_MAP: dict[AudioOutputHwMode, str] = {
AudioOutputHwMode.OPTICAL: "optical",
AudioOutputHwMode.LINE_OUT: "line_out",
AudioOutputHwMode.COAXIAL: "coaxial",
AudioOutputHwMode.HEADPHONES: "headphones",
}
AUDIO_OUTPUT_HW_MODE_MAP_INV: dict[str, AudioOutputHwMode] = {
v: k for k, v in AUDIO_OUTPUT_HW_MODE_MAP.items()
}
async def _get_current_option(bridge: LinkPlayBridge) -> str:
"""Get the current hardware mode."""
modes = await bridge.player.get_audio_output_hw_mode()
return AUDIO_OUTPUT_HW_MODE_MAP[modes.hardware]
@dataclass(frozen=True, kw_only=True)
class LinkPlaySelectEntityDescription(SelectEntityDescription):
"""Class describing LinkPlay select entities."""
set_option_fn: Callable[[LinkPlayPlayer, str], Coroutine[Any, Any, None]]
current_option_fn: Callable[[LinkPlayPlayer], Awaitable[str]]
SELECT_TYPES_WIIM: tuple[LinkPlaySelectEntityDescription, ...] = (
LinkPlaySelectEntityDescription(
key="audio_output_hardware_mode",
translation_key="audio_output_hardware_mode",
current_option_fn=_get_current_option,
set_option_fn=(
lambda linkplay_bridge, option: (
linkplay_bridge.player.set_audio_output_hw_mode(
AUDIO_OUTPUT_HW_MODE_MAP_INV[option]
)
)
),
options=list(AUDIO_OUTPUT_HW_MODE_MAP_INV),
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: LinkPlayConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the LinkPlay select from config entry."""
# add entities
if config_entry.runtime_data.bridge.device.manufacturer == MANUFACTURER_WIIM:
async_add_entities(
LinkPlaySelect(config_entry.runtime_data.bridge, description)
for description in SELECT_TYPES_WIIM
)
class LinkPlaySelect(LinkPlayBaseEntity, SelectEntity):
"""Representation of LinkPlay select."""
entity_description: LinkPlaySelectEntityDescription
def __init__(
self,
bridge: LinkPlayPlayer,
description: LinkPlaySelectEntityDescription,
) -> None:
"""Initialize LinkPlay select."""
super().__init__(bridge)
self.entity_description = description
self._attr_unique_id = f"{bridge.device.uuid}-{description.key}"
async def async_update(self) -> None:
"""Get the current value from the device."""
try:
# modes = await self.entity_description.current_option_fn(self._bridge)
self._attr_current_option = await self.entity_description.current_option_fn(
self._bridge
)
except ValueError as ex:
_LOGGER.debug(
"Cannot retrieve hardware mode value from device with error:, %s", ex
)
self._attr_current_option = None
@exception_wrap
async def async_select_option(self, option: str) -> None:
"""Set the option."""
await self.entity_description.set_option_fn(self._bridge, option)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/linkplay/select.py",
"license": "Apache License 2.0",
"lines": 88,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/medcom_ble/coordinator.py | """The Medcom BLE integration."""
from __future__ import annotations
from datetime import timedelta
import logging
from bleak import BleakError
from medcom_ble import MedcomBleDevice, MedcomBleDeviceData
from homeassistant.components import bluetooth
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util.unit_system import METRIC_SYSTEM
from .const import DEFAULT_SCAN_INTERVAL, DOMAIN
_LOGGER = logging.getLogger(__name__)
class MedcomBleUpdateCoordinator(DataUpdateCoordinator[MedcomBleDevice]):
"""Coordinator for Medcom BLE radiation monitor data."""
config_entry: ConfigEntry
def __init__(self, hass: HomeAssistant, entry: ConfigEntry, address: str) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=entry,
name=DOMAIN,
update_interval=timedelta(seconds=DEFAULT_SCAN_INTERVAL),
)
self._address = address
self._elevation = hass.config.elevation
self._is_metric = hass.config.units is METRIC_SYSTEM
async def _async_update_data(self) -> MedcomBleDevice:
"""Get data from Medcom BLE radiation monitor."""
ble_device = bluetooth.async_ble_device_from_address(self.hass, self._address)
inspector = MedcomBleDeviceData(_LOGGER, self._elevation, self._is_metric)
try:
data = await inspector.update_device(ble_device)
except BleakError as err:
raise UpdateFailed(f"Unable to fetch data: {err}") from err
return data
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/medcom_ble/coordinator.py",
"license": "Apache License 2.0",
"lines": 37,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/met_eireann/coordinator.py | """The met_eireann component."""
from __future__ import annotations
from collections.abc import Mapping
from datetime import timedelta
import logging
from typing import Any, Self
import meteireann
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ELEVATION, CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from homeassistant.util import dt as dt_util
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
UPDATE_INTERVAL = timedelta(minutes=60)
class MetEireannWeatherData:
"""Keep data for Met Éireann weather entities."""
def __init__(
self, config: Mapping[str, Any], weather_data: meteireann.WeatherData
) -> None:
"""Initialise the weather entity data."""
self._config = config
self._weather_data = weather_data
self.current_weather_data: dict[str, Any] = {}
self.daily_forecast: list[dict[str, Any]] = []
self.hourly_forecast: list[dict[str, Any]] = []
async def fetch_data(self) -> Self:
"""Fetch data from API - (current weather and forecast)."""
await self._weather_data.fetching_data()
self.current_weather_data = self._weather_data.get_current_weather()
time_zone = dt_util.get_default_time_zone()
self.daily_forecast = self._weather_data.get_forecast(time_zone, False)
self.hourly_forecast = self._weather_data.get_forecast(time_zone, True)
return self
class MetEireannUpdateCoordinator(DataUpdateCoordinator[MetEireannWeatherData]):
"""Coordinator for Met Éireann weather data."""
config_entry: ConfigEntry
def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name=DOMAIN,
update_interval=UPDATE_INTERVAL,
)
raw_weather_data = meteireann.WeatherData(
async_get_clientsession(hass),
latitude=config_entry.data[CONF_LATITUDE],
longitude=config_entry.data[CONF_LONGITUDE],
altitude=config_entry.data[CONF_ELEVATION],
)
self._weather_data = MetEireannWeatherData(config_entry.data, raw_weather_data)
async def _async_update_data(self) -> MetEireannWeatherData:
"""Fetch data from Met Éireann."""
try:
return await self._weather_data.fetch_data()
except Exception as err:
raise UpdateFailed(f"Update failed: {err}") from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/met_eireann/coordinator.py",
"license": "Apache License 2.0",
"lines": 60,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/meteoclimatic/coordinator.py | """Support for Meteoclimatic weather data."""
import logging
from typing import Any
from meteoclimatic import MeteoclimaticClient
from meteoclimatic.exceptions import MeteoclimaticError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_STATION_CODE, SCAN_INTERVAL
_LOGGER = logging.getLogger(__name__)
class MeteoclimaticUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""Coordinator for Meteoclimatic weather data."""
config_entry: ConfigEntry
def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Initialize the coordinator."""
self._station_code = entry.data[CONF_STATION_CODE]
super().__init__(
hass,
_LOGGER,
config_entry=entry,
name=f"Meteoclimatic weather for {entry.title} ({self._station_code})",
update_interval=SCAN_INTERVAL,
)
self._meteoclimatic_client = MeteoclimaticClient()
async def _async_update_data(self) -> dict[str, Any]:
"""Obtain the latest data from Meteoclimatic."""
try:
data = await self.hass.async_add_executor_job(
self._meteoclimatic_client.weather_at_station, self._station_code
)
except MeteoclimaticError as err:
raise UpdateFailed(f"Error while retrieving data: {err}") from err
return data.__dict__
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/meteoclimatic/coordinator.py",
"license": "Apache License 2.0",
"lines": 33,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/miele/services.py | """Services for Miele integration."""
from datetime import timedelta
import logging
from typing import cast
from aiohttp import ClientResponseError
import voluptuous as vol
from homeassistant.const import ATTR_DEVICE_ID, ATTR_TEMPERATURE
from homeassistant.core import (
HomeAssistant,
ServiceCall,
ServiceResponse,
SupportsResponse,
)
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import config_validation as cv, device_registry as dr
from homeassistant.helpers.service import async_extract_config_entry_ids
from .const import DOMAIN
from .coordinator import MieleConfigEntry
ATTR_PROGRAM_ID = "program_id"
ATTR_DURATION = "duration"
SERVICE_SET_PROGRAM = "set_program"
SERVICE_SET_PROGRAM_SCHEMA = vol.Schema(
{
vol.Required(ATTR_DEVICE_ID): str,
vol.Required(ATTR_PROGRAM_ID): cv.positive_int,
},
)
SERVICE_SET_PROGRAM_OVEN = "set_program_oven"
SERVICE_SET_PROGRAM_OVEN_SCHEMA = vol.Schema(
{
vol.Required(ATTR_DEVICE_ID): str,
vol.Required(ATTR_PROGRAM_ID): cv.positive_int,
vol.Optional(ATTR_TEMPERATURE): cv.positive_int,
vol.Optional(ATTR_DURATION): vol.All(
cv.time_period,
vol.Range(min=timedelta(minutes=1), max=timedelta(hours=12)),
),
},
)
SERVICE_GET_PROGRAMS = "get_programs"
SERVICE_GET_PROGRAMS_SCHEMA = vol.Schema(
{
vol.Required(ATTR_DEVICE_ID): str,
},
)
_LOGGER = logging.getLogger(__name__)
async def _extract_config_entry(service_call: ServiceCall) -> MieleConfigEntry:
"""Extract config entry from the service call."""
target_entry_ids = await async_extract_config_entry_ids(service_call)
target_entries: list[MieleConfigEntry] = [
loaded_entry
for loaded_entry in service_call.hass.config_entries.async_loaded_entries(
DOMAIN
)
if loaded_entry.entry_id in target_entry_ids
]
if not target_entries:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_target",
)
return target_entries[0]
async def _get_serial_number(call: ServiceCall) -> str:
"""Extract the serial number from the device identifier."""
device_reg = dr.async_get(call.hass)
device = call.data[ATTR_DEVICE_ID]
device_entry = device_reg.async_get(device)
serial_number = next(
(
identifier[1]
for identifier in cast(dr.DeviceEntry, device_entry).identifiers
if identifier[0] == DOMAIN
),
None,
)
if serial_number is None:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_target",
)
return serial_number
async def set_program(call: ServiceCall) -> None:
"""Set a program on a Miele appliance."""
_LOGGER.debug("Set program call: %s", call)
config_entry = await _extract_config_entry(call)
api = config_entry.runtime_data.api
serial_number = await _get_serial_number(call)
data = {"programId": call.data[ATTR_PROGRAM_ID]}
try:
await api.set_program(serial_number, data)
except ClientResponseError as ex:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="set_program_error",
translation_placeholders={
"status": str(ex.status),
"message": ex.message,
},
) from ex
async def set_program_oven(call: ServiceCall) -> None:
"""Set a program on a Miele oven."""
_LOGGER.debug("Set program call: %s", call)
config_entry = await _extract_config_entry(call)
api = config_entry.runtime_data.api
serial_number = await _get_serial_number(call)
data = {"programId": call.data[ATTR_PROGRAM_ID]}
if call.data.get(ATTR_DURATION) is not None:
td = call.data[ATTR_DURATION]
data["duration"] = [
td.seconds // 3600, # hours
(td.seconds // 60) % 60, # minutes
]
if call.data.get(ATTR_TEMPERATURE) is not None:
data["temperature"] = call.data[ATTR_TEMPERATURE]
try:
await api.set_program(serial_number, data)
except ClientResponseError as ex:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="set_program_oven_error",
translation_placeholders={
"status": str(ex.status),
"message": ex.message,
},
) from ex
async def get_programs(call: ServiceCall) -> ServiceResponse:
"""Get available programs from appliance."""
config_entry = await _extract_config_entry(call)
api = config_entry.runtime_data.api
serial_number = await _get_serial_number(call)
try:
programs = await api.get_programs(serial_number)
except ClientResponseError as ex:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="get_programs_error",
translation_placeholders={
"status": str(ex.status),
"message": ex.message,
},
) from ex
return {
"programs": [
{
"program_id": item["programId"],
"program": item["program"].strip(),
"parameters": (
{
"temperature": (
{
"min": item["parameters"]["temperature"]["min"],
"max": item["parameters"]["temperature"]["max"],
"step": item["parameters"]["temperature"]["step"],
"mandatory": item["parameters"]["temperature"][
"mandatory"
],
}
if "temperature" in item["parameters"]
else {}
),
"duration": (
{
"min": {
"hours": item["parameters"]["duration"]["min"][0],
"minutes": item["parameters"]["duration"]["min"][1],
},
"max": {
"hours": item["parameters"]["duration"]["max"][0],
"minutes": item["parameters"]["duration"]["max"][1],
},
"mandatory": item["parameters"]["duration"][
"mandatory"
],
}
if "duration" in item["parameters"]
else {}
),
}
if item.get("parameters")
else {}
),
}
for item in programs
],
}
async def async_setup_services(hass: HomeAssistant) -> None:
"""Set up services."""
hass.services.async_register(
DOMAIN,
SERVICE_SET_PROGRAM,
set_program,
SERVICE_SET_PROGRAM_SCHEMA,
)
hass.services.async_register(
DOMAIN,
SERVICE_SET_PROGRAM_OVEN,
set_program_oven,
SERVICE_SET_PROGRAM_OVEN_SCHEMA,
)
hass.services.async_register(
DOMAIN,
SERVICE_GET_PROGRAMS,
get_programs,
SERVICE_GET_PROGRAMS_SCHEMA,
supports_response=SupportsResponse.ONLY,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/miele/services.py",
"license": "Apache License 2.0",
"lines": 206,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/mqtt/repairs.py | """Repairs for MQTT."""
from __future__ import annotations
from typing import TYPE_CHECKING
import voluptuous as vol
from homeassistant import data_entry_flow
from homeassistant.components.repairs import RepairsFlow
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from .const import DOMAIN
class MQTTDeviceEntryMigration(RepairsFlow):
"""Handler to remove subentry for migrated MQTT device."""
def __init__(self, entry_id: str, subentry_id: str, name: str) -> None:
"""Initialize the flow."""
self.entry_id = entry_id
self.subentry_id = subentry_id
self.name = name
async def async_step_init(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the first step of a fix flow."""
return await self.async_step_confirm()
async def async_step_confirm(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the confirm step of a fix flow."""
if user_input is not None:
device_registry = dr.async_get(self.hass)
subentry_device = device_registry.async_get_device(
identifiers={(DOMAIN, self.subentry_id)}
)
entry = self.hass.config_entries.async_get_entry(self.entry_id)
if TYPE_CHECKING:
assert entry is not None
assert subentry_device is not None
self.hass.config_entries.async_remove_subentry(entry, self.subentry_id)
return self.async_create_entry(data={})
return self.async_show_form(
step_id="confirm",
data_schema=vol.Schema({}),
description_placeholders={"name": self.name},
)
async def async_create_fix_flow(
hass: HomeAssistant,
issue_id: str,
data: dict[str, str | int | float | None] | None,
) -> RepairsFlow:
"""Create flow."""
if TYPE_CHECKING:
assert data is not None
entry_id = data["entry_id"]
subentry_id = data["subentry_id"]
name = data["name"]
if TYPE_CHECKING:
assert isinstance(entry_id, str)
assert isinstance(subentry_id, str)
assert isinstance(name, str)
return MQTTDeviceEntryMigration(
entry_id=entry_id,
subentry_id=subentry_id,
name=name,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/mqtt/repairs.py",
"license": "Apache License 2.0",
"lines": 61,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/nasweb/sensor.py | """Platform for NASweb sensors."""
from __future__ import annotations
import logging
import time
from webio_api import Input as NASwebInput, TempSensor
from webio_api.const import (
STATE_INPUT_ACTIVE,
STATE_INPUT_NORMAL,
STATE_INPUT_PROBLEM,
STATE_INPUT_TAMPER,
STATE_INPUT_UNDEFINED,
)
from homeassistant.components.sensor import (
DOMAIN as SENSOR_DOMAIN,
SensorDeviceClass,
SensorEntity,
SensorStateClass,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
import homeassistant.helpers.entity_registry as er
from homeassistant.helpers.typing import DiscoveryInfoType
from homeassistant.helpers.update_coordinator import (
BaseCoordinatorEntity,
BaseDataUpdateCoordinatorProtocol,
)
from . import NASwebConfigEntry
from .const import DOMAIN, KEY_TEMP_SENSOR, STATUS_UPDATE_MAX_TIME_INTERVAL
SENSOR_INPUT_TRANSLATION_KEY = "sensor_input"
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config: NASwebConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up Sensor platform."""
coordinator = config.runtime_data
current_inputs: set[int] = set()
@callback
def _check_entities() -> None:
received_inputs: dict[int, NASwebInput] = {
entry.index: entry for entry in coordinator.webio_api.inputs
}
added = {i for i in received_inputs if i not in current_inputs}
removed = {i for i in current_inputs if i not in received_inputs}
entities_to_add: list[InputStateSensor] = []
for index in added:
webio_input = received_inputs[index]
if not isinstance(webio_input, NASwebInput):
_LOGGER.error("Cannot create InputStateSensor without NASwebInput")
continue
new_input = InputStateSensor(coordinator, webio_input)
entities_to_add.append(new_input)
current_inputs.add(index)
async_add_entities(entities_to_add)
entity_registry = er.async_get(hass)
for index in removed:
unique_id = f"{DOMAIN}.{config.unique_id}.input.{index}"
if entity_id := entity_registry.async_get_entity_id(
SENSOR_DOMAIN, DOMAIN, unique_id
):
entity_registry.async_remove(entity_id)
current_inputs.remove(index)
else:
_LOGGER.warning("Failed to remove old input: no entity_id")
coordinator.async_add_listener(_check_entities)
_check_entities()
nasweb_temp_sensor = coordinator.data[KEY_TEMP_SENSOR]
temp_sensor = TemperatureSensor(coordinator, nasweb_temp_sensor)
async_add_entities([temp_sensor])
class BaseSensorEntity(SensorEntity, BaseCoordinatorEntity):
"""Base class providing common functionality."""
def __init__(self, coordinator: BaseDataUpdateCoordinatorProtocol) -> None:
"""Initialize base sensor."""
super().__init__(coordinator)
self._attr_available = False
self._attr_has_entity_name = True
self._attr_should_poll = False
async def async_added_to_hass(self) -> None:
"""When entity is added to hass."""
await super().async_added_to_hass()
self._handle_coordinator_update()
def _set_attr_available(
self, entity_last_update: float, available: bool | None
) -> None:
if (
self.coordinator.last_update is None
or time.time() - entity_last_update >= STATUS_UPDATE_MAX_TIME_INTERVAL
):
self._attr_available = False
else:
self._attr_available = available if available is not None else False
async def async_update(self) -> None:
"""Update the entity.
Only used by the generic entity update service.
Scheduling updates is not necessary, the coordinator takes care of updates via push notifications.
"""
class InputStateSensor(BaseSensorEntity):
"""Entity representing NASweb input."""
_attr_device_class = SensorDeviceClass.ENUM
_attr_options: list[str] = [
STATE_INPUT_ACTIVE,
STATE_INPUT_NORMAL,
STATE_INPUT_PROBLEM,
STATE_INPUT_TAMPER,
STATE_INPUT_UNDEFINED,
]
_attr_translation_key = SENSOR_INPUT_TRANSLATION_KEY
def __init__(
self,
coordinator: BaseDataUpdateCoordinatorProtocol,
nasweb_input: NASwebInput,
) -> None:
"""Initialize InputStateSensor entity."""
super().__init__(coordinator)
self._input = nasweb_input
self._attr_native_value: str | None = None
self._attr_translation_placeholders = {"index": f"{nasweb_input.index:2d}"}
self._attr_unique_id = (
f"{DOMAIN}.{self._input.webio_serial}.input.{self._input.index}"
)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, self._input.webio_serial)},
)
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
if self._input.state is None or self._input.state in self._attr_options:
self._attr_native_value = self._input.state
else:
_LOGGER.warning("Received unrecognized input state: %s", self._input.state)
self._attr_native_value = None
self._set_attr_available(self._input.last_update, self._input.available)
self.async_write_ha_state()
class TemperatureSensor(BaseSensorEntity):
"""Entity representing NASweb temperature sensor."""
_attr_device_class = SensorDeviceClass.TEMPERATURE
_attr_state_class = SensorStateClass.MEASUREMENT
_attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
def __init__(
self,
coordinator: BaseDataUpdateCoordinatorProtocol,
nasweb_temp_sensor: TempSensor,
) -> None:
"""Initialize TemperatureSensor entity."""
super().__init__(coordinator)
self._temp_sensor = nasweb_temp_sensor
self._attr_unique_id = f"{DOMAIN}.{self._temp_sensor.webio_serial}.temp_sensor"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, self._temp_sensor.webio_serial)}
)
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
self._attr_native_value = self._temp_sensor.value
self._set_attr_available(
self._temp_sensor.last_update, self._temp_sensor.available
)
self.async_write_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/nasweb/sensor.py",
"license": "Apache License 2.0",
"lines": 162,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/ollama/ai_task.py | """AI Task integration for Ollama."""
from __future__ import annotations
from json import JSONDecodeError
import logging
from homeassistant.components import ai_task, conversation
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.json import json_loads
from .entity import OllamaBaseLLMEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up AI Task entities."""
for subentry in config_entry.subentries.values():
if subentry.subentry_type != "ai_task_data":
continue
async_add_entities(
[OllamaTaskEntity(config_entry, subentry)],
config_subentry_id=subentry.subentry_id,
)
class OllamaTaskEntity(
ai_task.AITaskEntity,
OllamaBaseLLMEntity,
):
"""Ollama AI Task entity."""
_attr_supported_features = (
ai_task.AITaskEntityFeature.GENERATE_DATA
| ai_task.AITaskEntityFeature.SUPPORT_ATTACHMENTS
)
async def _async_generate_data(
self,
task: ai_task.GenDataTask,
chat_log: conversation.ChatLog,
) -> ai_task.GenDataTaskResult:
"""Handle a generate data task."""
await self._async_handle_chat_log(chat_log, task.structure)
if not isinstance(chat_log.content[-1], conversation.AssistantContent):
raise HomeAssistantError(
"Last content in chat log is not an AssistantContent"
)
text = chat_log.content[-1].content or ""
if not task.structure:
return ai_task.GenDataTaskResult(
conversation_id=chat_log.conversation_id,
data=text,
)
try:
data = json_loads(text)
except JSONDecodeError as err:
_LOGGER.error(
"Failed to parse JSON response: %s. Response: %s",
err,
text,
)
raise HomeAssistantError("Error with Ollama structured response") from err
return ai_task.GenDataTaskResult(
conversation_id=chat_log.conversation_id,
data=data,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ollama/ai_task.py",
"license": "Apache License 2.0",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/onkyo/util.py | """Utils for Onkyo."""
from .const import InputSource, ListeningMode
def get_meaning(param: InputSource | ListeningMode) -> str:
"""Get param meaning."""
return " ··· ".join(param.meanings)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/onkyo/util.py",
"license": "Apache License 2.0",
"lines": 5,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/open_router/ai_task.py | """AI Task integration for OpenRouter."""
from __future__ import annotations
from json import JSONDecodeError
import logging
from homeassistant.components import ai_task, conversation
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.json import json_loads
from . import OpenRouterConfigEntry
from .entity import OpenRouterEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: OpenRouterConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up AI Task entities."""
for subentry in config_entry.subentries.values():
if subentry.subentry_type != "ai_task_data":
continue
async_add_entities(
[OpenRouterAITaskEntity(config_entry, subentry)],
config_subentry_id=subentry.subentry_id,
)
class OpenRouterAITaskEntity(
ai_task.AITaskEntity,
OpenRouterEntity,
):
"""OpenRouter AI Task entity."""
_attr_name = None
_attr_supported_features = (
ai_task.AITaskEntityFeature.GENERATE_DATA
| ai_task.AITaskEntityFeature.SUPPORT_ATTACHMENTS
)
async def _async_generate_data(
self,
task: ai_task.GenDataTask,
chat_log: conversation.ChatLog,
) -> ai_task.GenDataTaskResult:
"""Handle a generate data task."""
await self._async_handle_chat_log(chat_log, task.name, task.structure)
if not isinstance(chat_log.content[-1], conversation.AssistantContent):
raise HomeAssistantError(
"Last content in chat log is not an AssistantContent"
)
text = chat_log.content[-1].content or ""
if not task.structure:
return ai_task.GenDataTaskResult(
conversation_id=chat_log.conversation_id,
data=text,
)
try:
data = json_loads(text)
except JSONDecodeError as err:
raise HomeAssistantError(
"Error with OpenRouter structured response"
) from err
return ai_task.GenDataTaskResult(
conversation_id=chat_log.conversation_id,
data=data,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/open_router/ai_task.py",
"license": "Apache License 2.0",
"lines": 62,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/open_router/config_flow.py | """Config flow for OpenRouter integration."""
from __future__ import annotations
import logging
from typing import Any
from python_open_router import (
Model,
OpenRouterClient,
OpenRouterError,
SupportedParameter,
)
import voluptuous as vol
from homeassistant.config_entries import (
SOURCE_USER,
ConfigEntry,
ConfigEntryState,
ConfigFlow,
ConfigFlowResult,
ConfigSubentryFlow,
SubentryFlowResult,
)
from homeassistant.const import CONF_API_KEY, CONF_LLM_HASS_API, CONF_MODEL
from homeassistant.core import callback
from homeassistant.helpers import llm
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.selector import (
SelectOptionDict,
SelectSelector,
SelectSelectorConfig,
SelectSelectorMode,
TemplateSelector,
)
from .const import CONF_PROMPT, DOMAIN, RECOMMENDED_CONVERSATION_OPTIONS
_LOGGER = logging.getLogger(__name__)
class OpenRouterConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for OpenRouter."""
VERSION = 1
@classmethod
@callback
def async_get_supported_subentry_types(
cls, config_entry: ConfigEntry
) -> dict[str, type[ConfigSubentryFlow]]:
"""Return subentries supported by this handler."""
return {
"conversation": ConversationFlowHandler,
"ai_task_data": AITaskDataFlowHandler,
}
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors = {}
if user_input is not None:
self._async_abort_entries_match(user_input)
client = OpenRouterClient(
user_input[CONF_API_KEY], async_get_clientsession(self.hass)
)
try:
await client.get_key_data()
except OpenRouterError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(
title="OpenRouter",
data=user_input,
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_API_KEY): str,
}
),
errors=errors,
)
class OpenRouterSubentryFlowHandler(ConfigSubentryFlow):
"""Handle subentry flow for OpenRouter."""
def __init__(self) -> None:
"""Initialize the subentry flow."""
self.models: dict[str, Model] = {}
async def _get_models(self) -> None:
"""Fetch models from OpenRouter."""
entry = self._get_entry()
client = OpenRouterClient(
entry.data[CONF_API_KEY], async_get_clientsession(self.hass)
)
models = await client.get_models()
self.models = {model.id: model for model in models}
class ConversationFlowHandler(OpenRouterSubentryFlowHandler):
"""Handle subentry flow."""
def __init__(self) -> None:
"""Initialize the subentry flow."""
super().__init__()
self.options: dict[str, Any] = {}
@property
def _is_new(self) -> bool:
"""Return if this is a new subentry."""
return self.source == SOURCE_USER
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""User flow to create a conversation agent."""
self.options = RECOMMENDED_CONVERSATION_OPTIONS.copy()
return await self.async_step_init(user_input)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""Handle reconfiguration of a conversation agent."""
self.options = self._get_reconfigure_subentry().data.copy()
return await self.async_step_init(user_input)
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""Manage conversation agent configuration."""
if self._get_entry().state != ConfigEntryState.LOADED:
return self.async_abort(reason="entry_not_loaded")
if user_input is not None:
if not user_input.get(CONF_LLM_HASS_API):
user_input.pop(CONF_LLM_HASS_API, None)
if self._is_new:
return self.async_create_entry(
title=self.models[user_input[CONF_MODEL]].name, data=user_input
)
return self.async_update_and_abort(
self._get_entry(),
self._get_reconfigure_subentry(),
data=user_input,
)
try:
await self._get_models()
except OpenRouterError:
return self.async_abort(reason="cannot_connect")
except Exception:
_LOGGER.exception("Unexpected exception")
return self.async_abort(reason="unknown")
options = [
SelectOptionDict(value=model.id, label=model.name)
for model in self.models.values()
]
hass_apis: list[SelectOptionDict] = [
SelectOptionDict(
label=api.name,
value=api.id,
)
for api in llm.async_get_apis(self.hass)
]
if suggested_llm_apis := self.options.get(CONF_LLM_HASS_API):
valid_api_ids = {api["value"] for api in hass_apis}
self.options[CONF_LLM_HASS_API] = [
api for api in suggested_llm_apis if api in valid_api_ids
]
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(
CONF_MODEL, default=self.options.get(CONF_MODEL)
): SelectSelector(
SelectSelectorConfig(
options=options, mode=SelectSelectorMode.DROPDOWN, sort=True
),
),
vol.Optional(
CONF_PROMPT,
description={
"suggested_value": self.options.get(
CONF_PROMPT,
RECOMMENDED_CONVERSATION_OPTIONS[CONF_PROMPT],
)
},
): TemplateSelector(),
vol.Optional(
CONF_LLM_HASS_API,
default=self.options.get(
CONF_LLM_HASS_API,
RECOMMENDED_CONVERSATION_OPTIONS[CONF_LLM_HASS_API],
),
): SelectSelector(
SelectSelectorConfig(options=hass_apis, multiple=True)
),
}
),
)
class AITaskDataFlowHandler(OpenRouterSubentryFlowHandler):
"""Handle subentry flow."""
def __init__(self) -> None:
"""Initialize the subentry flow."""
super().__init__()
self.options: dict[str, Any] = {}
@property
def _is_new(self) -> bool:
"""Return if this is a new subentry."""
return self.source == SOURCE_USER
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""User flow to create an AI task."""
self.options = {}
return await self.async_step_init(user_input)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""Handle reconfiguration of an AI task."""
self.options = self._get_reconfigure_subentry().data.copy()
return await self.async_step_init(user_input)
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""Manage AI task configuration."""
if self._get_entry().state != ConfigEntryState.LOADED:
return self.async_abort(reason="entry_not_loaded")
if user_input is not None:
if self._is_new:
return self.async_create_entry(
title=self.models[user_input[CONF_MODEL]].name, data=user_input
)
return self.async_update_and_abort(
self._get_entry(),
self._get_reconfigure_subentry(),
data=user_input,
)
try:
await self._get_models()
except OpenRouterError:
return self.async_abort(reason="cannot_connect")
except Exception:
_LOGGER.exception("Unexpected exception")
return self.async_abort(reason="unknown")
options = [
SelectOptionDict(value=model.id, label=model.name)
for model in self.models.values()
if SupportedParameter.STRUCTURED_OUTPUTS in model.supported_parameters
]
return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(
CONF_MODEL, default=self.options.get(CONF_MODEL)
): SelectSelector(
SelectSelectorConfig(
options=options, mode=SelectSelectorMode.DROPDOWN, sort=True
),
),
}
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/open_router/config_flow.py",
"license": "Apache License 2.0",
"lines": 249,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/open_router/const.py | """Constants for the OpenRouter integration."""
import logging
from homeassistant.const import CONF_LLM_HASS_API, CONF_PROMPT
from homeassistant.helpers import llm
DOMAIN = "open_router"
LOGGER = logging.getLogger(__package__)
CONF_RECOMMENDED = "recommended"
RECOMMENDED_CONVERSATION_OPTIONS = {
CONF_RECOMMENDED: True,
CONF_LLM_HASS_API: [llm.LLM_API_ASSIST],
CONF_PROMPT: llm.DEFAULT_INSTRUCTIONS_PROMPT,
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/open_router/const.py",
"license": "Apache License 2.0",
"lines": 12,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/open_router/conversation.py | """Conversation support for OpenRouter."""
from typing import Literal
from homeassistant.components import conversation
from homeassistant.config_entries import ConfigSubentry
from homeassistant.const import CONF_LLM_HASS_API, CONF_PROMPT, MATCH_ALL
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import OpenRouterConfigEntry
from .const import DOMAIN
from .entity import OpenRouterEntity
async def async_setup_entry(
hass: HomeAssistant,
config_entry: OpenRouterConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up conversation entities."""
for subentry_id, subentry in config_entry.subentries.items():
if subentry.subentry_type != "conversation":
continue
async_add_entities(
[OpenRouterConversationEntity(config_entry, subentry)],
config_subentry_id=subentry_id,
)
class OpenRouterConversationEntity(OpenRouterEntity, conversation.ConversationEntity):
"""OpenRouter conversation agent."""
_attr_name = None
def __init__(self, entry: OpenRouterConfigEntry, subentry: ConfigSubentry) -> None:
"""Initialize the agent."""
super().__init__(entry, subentry)
if self.subentry.data.get(CONF_LLM_HASS_API):
self._attr_supported_features = (
conversation.ConversationEntityFeature.CONTROL
)
@property
def supported_languages(self) -> list[str] | Literal["*"]:
"""Return a list of supported languages."""
return MATCH_ALL
async def _async_handle_message(
self,
user_input: conversation.ConversationInput,
chat_log: conversation.ChatLog,
) -> conversation.ConversationResult:
"""Process the user input and call the API."""
options = self.subentry.data
try:
await chat_log.async_provide_llm_data(
user_input.as_llm_context(DOMAIN),
options.get(CONF_LLM_HASS_API),
options.get(CONF_PROMPT),
user_input.extra_system_prompt,
)
except conversation.ConverseError as err:
return err.as_conversation_result()
await self._async_handle_chat_log(chat_log)
return conversation.async_get_result_from_chat_log(user_input, chat_log)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/open_router/conversation.py",
"license": "Apache License 2.0",
"lines": 55,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/open_router/entity.py | """Base entity for Open Router."""
from __future__ import annotations
import base64
from collections.abc import AsyncGenerator, Callable
import json
from mimetypes import guess_file_type
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal
import openai
from openai.types.chat import (
ChatCompletionAssistantMessageParam,
ChatCompletionContentPartImageParam,
ChatCompletionFunctionToolParam,
ChatCompletionMessage,
ChatCompletionMessageFunctionToolCallParam,
ChatCompletionMessageParam,
ChatCompletionSystemMessageParam,
ChatCompletionToolMessageParam,
ChatCompletionUserMessageParam,
)
from openai.types.chat.chat_completion_message_function_tool_call_param import Function
from openai.types.shared_params import FunctionDefinition, ResponseFormatJSONSchema
from openai.types.shared_params.response_format_json_schema import JSONSchema
import voluptuous as vol
from voluptuous_openapi import convert
from homeassistant.components import conversation
from homeassistant.config_entries import ConfigSubentry
from homeassistant.const import CONF_MODEL
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, llm
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.json import json_dumps
from . import OpenRouterConfigEntry
from .const import DOMAIN, LOGGER
# Max number of back and forth with the LLM to generate a response
MAX_TOOL_ITERATIONS = 10
def _adjust_schema(schema: dict[str, Any]) -> None:
"""Adjust the schema to be compatible with OpenRouter API."""
if schema["type"] == "object":
if "properties" not in schema:
return
if "required" not in schema:
schema["required"] = []
# Ensure all properties are required
for prop, prop_info in schema["properties"].items():
_adjust_schema(prop_info)
if prop not in schema["required"]:
prop_info["type"] = [prop_info["type"], "null"]
schema["required"].append(prop)
elif schema["type"] == "array":
if "items" not in schema:
return
_adjust_schema(schema["items"])
def _format_structured_output(
name: str, schema: vol.Schema, llm_api: llm.APIInstance | None
) -> JSONSchema:
"""Format the schema to be compatible with OpenRouter API."""
result: JSONSchema = {
"name": name,
"strict": True,
}
result_schema = convert(
schema,
custom_serializer=(
llm_api.custom_serializer if llm_api else llm.selector_serializer
),
)
_adjust_schema(result_schema)
result["schema"] = result_schema
return result
def _format_tool(
tool: llm.Tool,
custom_serializer: Callable[[Any], Any] | None,
) -> ChatCompletionFunctionToolParam:
"""Format tool specification."""
tool_spec = FunctionDefinition(
name=tool.name,
parameters=convert(tool.parameters, custom_serializer=custom_serializer),
)
if tool.description:
tool_spec["description"] = tool.description
return ChatCompletionFunctionToolParam(type="function", function=tool_spec)
def _convert_content_to_chat_message(
content: conversation.Content,
) -> ChatCompletionMessageParam | None:
"""Convert any native chat message for this agent to the native format."""
LOGGER.debug("_convert_content_to_chat_message=%s", content)
if isinstance(content, conversation.ToolResultContent):
return ChatCompletionToolMessageParam(
role="tool",
tool_call_id=content.tool_call_id,
content=json_dumps(content.tool_result),
)
role: Literal["user", "assistant", "system"] = content.role
if role == "system" and content.content:
return ChatCompletionSystemMessageParam(role="system", content=content.content)
if role == "user" and content.content:
return ChatCompletionUserMessageParam(role="user", content=content.content)
if role == "assistant":
param = ChatCompletionAssistantMessageParam(
role="assistant",
content=content.content,
)
if isinstance(content, conversation.AssistantContent) and content.tool_calls:
param["tool_calls"] = [
ChatCompletionMessageFunctionToolCallParam(
type="function",
id=tool_call.id,
function=Function(
arguments=json_dumps(tool_call.tool_args),
name=tool_call.tool_name,
),
)
for tool_call in content.tool_calls
]
return param
LOGGER.warning("Could not convert message to Completions API: %s", content)
return None
def _decode_tool_arguments(arguments: str) -> Any:
"""Decode tool call arguments."""
try:
return json.loads(arguments)
except json.JSONDecodeError as err:
raise HomeAssistantError(f"Unexpected tool argument response: {err}") from err
async def _transform_response(
message: ChatCompletionMessage,
) -> AsyncGenerator[conversation.AssistantContentDeltaDict]:
"""Transform the OpenRouter message to a ChatLog format."""
data: conversation.AssistantContentDeltaDict = {
"role": message.role,
"content": message.content,
}
if message.tool_calls:
data["tool_calls"] = [
llm.ToolInput(
id=tool_call.id,
tool_name=tool_call.function.name,
tool_args=_decode_tool_arguments(tool_call.function.arguments),
)
for tool_call in message.tool_calls
if tool_call.type == "function"
]
yield data
async def async_prepare_files_for_prompt(
hass: HomeAssistant, files: list[tuple[Path, str | None]]
) -> list[ChatCompletionContentPartImageParam]:
"""Append files to a prompt.
Caller needs to ensure that the files are allowed.
"""
def append_files_to_content() -> list[ChatCompletionContentPartImageParam]:
content: list[ChatCompletionContentPartImageParam] = []
for file_path, mime_type in files:
if not file_path.exists():
raise HomeAssistantError(f"`{file_path}` does not exist")
if mime_type is None:
mime_type = guess_file_type(file_path)[0]
if not mime_type or not mime_type.startswith(("image/", "application/pdf")):
raise HomeAssistantError(
"Only images and PDF are supported by the OpenRouter API, "
f"`{file_path}` is not an image file or PDF"
)
base64_file = base64.b64encode(file_path.read_bytes()).decode("utf-8")
content.append(
{
"type": "image_url",
"image_url": {"url": f"data:{mime_type};base64,{base64_file}"},
}
)
return content
return await hass.async_add_executor_job(append_files_to_content)
class OpenRouterEntity(Entity):
"""Base entity for Open Router."""
_attr_has_entity_name = True
def __init__(self, entry: OpenRouterConfigEntry, subentry: ConfigSubentry) -> None:
"""Initialize the entity."""
self.entry = entry
self.subentry = subentry
self.model = subentry.data[CONF_MODEL]
self._attr_unique_id = subentry.subentry_id
self._attr_device_info = dr.DeviceInfo(
identifiers={(DOMAIN, subentry.subentry_id)},
name=subentry.title,
entry_type=dr.DeviceEntryType.SERVICE,
)
async def _async_handle_chat_log(
self,
chat_log: conversation.ChatLog,
structure_name: str | None = None,
structure: vol.Schema | None = None,
) -> None:
"""Generate an answer for the chat log."""
model_args = {
"model": self.model,
"user": chat_log.conversation_id,
"extra_headers": {
"X-Title": "Home Assistant",
"HTTP-Referer": "https://www.home-assistant.io/integrations/open_router",
},
"extra_body": {"require_parameters": True},
}
tools: list[ChatCompletionFunctionToolParam] | None = None
if chat_log.llm_api:
tools = [
_format_tool(tool, chat_log.llm_api.custom_serializer)
for tool in chat_log.llm_api.tools
]
if tools:
model_args["tools"] = tools
model_args["messages"] = [
m
for content in chat_log.content
if (m := _convert_content_to_chat_message(content))
]
last_content = chat_log.content[-1]
# Handle attachments by adding them to the last user message
if last_content.role == "user" and last_content.attachments:
last_message: ChatCompletionMessageParam = model_args["messages"][-1]
assert last_message["role"] == "user" and isinstance(
last_message["content"], str
)
# Encode files with base64 and append them to the text prompt
files = await async_prepare_files_for_prompt(
self.hass,
[(a.path, a.mime_type) for a in last_content.attachments],
)
last_message["content"] = [
{"type": "text", "text": last_message["content"]},
*files,
]
if structure:
if TYPE_CHECKING:
assert structure_name is not None
model_args["response_format"] = ResponseFormatJSONSchema(
type="json_schema",
json_schema=_format_structured_output(
structure_name, structure, chat_log.llm_api
),
)
client = self.entry.runtime_data
for _iteration in range(MAX_TOOL_ITERATIONS):
try:
result = await client.chat.completions.create(**model_args)
except openai.OpenAIError as err:
LOGGER.error("Error talking to API: %s", err)
raise HomeAssistantError("Error talking to API") from err
result_message = result.choices[0].message
model_args["messages"].extend(
[
msg
async for content in chat_log.async_add_delta_content_stream(
self.entity_id, _transform_response(result_message)
)
if (msg := _convert_content_to_chat_message(content))
]
)
if not chat_log.unresponded_tool_results:
break
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/open_router/entity.py",
"license": "Apache License 2.0",
"lines": 258,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/openai_conversation/ai_task.py | """AI Task integration for OpenAI."""
from __future__ import annotations
import base64
from json import JSONDecodeError
import logging
from typing import TYPE_CHECKING
from openai.types.responses.response_output_item import ImageGenerationCall
from homeassistant.components import ai_task, conversation
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.json import json_loads
from .const import (
CONF_CHAT_MODEL,
CONF_IMAGE_MODEL,
RECOMMENDED_CHAT_MODEL,
RECOMMENDED_IMAGE_MODEL,
UNSUPPORTED_IMAGE_MODELS,
)
from .entity import OpenAIBaseLLMEntity
if TYPE_CHECKING:
from homeassistant.config_entries import ConfigSubentry
from . import OpenAIConfigEntry
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: OpenAIConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up AI Task entities."""
for subentry in config_entry.subentries.values():
if subentry.subentry_type != "ai_task_data":
continue
async_add_entities(
[OpenAITaskEntity(config_entry, subentry)],
config_subentry_id=subentry.subentry_id,
)
class OpenAITaskEntity(
ai_task.AITaskEntity,
OpenAIBaseLLMEntity,
):
"""OpenAI AI Task entity."""
def __init__(self, entry: OpenAIConfigEntry, subentry: ConfigSubentry) -> None:
"""Initialize the entity."""
super().__init__(entry, subentry)
self._attr_supported_features = (
ai_task.AITaskEntityFeature.GENERATE_DATA
| ai_task.AITaskEntityFeature.SUPPORT_ATTACHMENTS
)
model = self.subentry.data.get(CONF_CHAT_MODEL, RECOMMENDED_CHAT_MODEL)
if not model.startswith(tuple(UNSUPPORTED_IMAGE_MODELS)):
self._attr_supported_features |= ai_task.AITaskEntityFeature.GENERATE_IMAGE
async def _async_generate_data(
self,
task: ai_task.GenDataTask,
chat_log: conversation.ChatLog,
) -> ai_task.GenDataTaskResult:
"""Handle a generate data task."""
await self._async_handle_chat_log(
chat_log, task.name, task.structure, max_iterations=1000
)
if not isinstance(chat_log.content[-1], conversation.AssistantContent):
raise HomeAssistantError(
"Last content in chat log is not an AssistantContent"
)
text = chat_log.content[-1].content or ""
if not task.structure:
return ai_task.GenDataTaskResult(
conversation_id=chat_log.conversation_id,
data=text,
)
try:
data = json_loads(text)
except JSONDecodeError as err:
_LOGGER.error(
"Failed to parse JSON response: %s. Response: %s",
err,
text,
)
raise HomeAssistantError("Error with OpenAI structured response") from err
return ai_task.GenDataTaskResult(
conversation_id=chat_log.conversation_id,
data=data,
)
async def _async_generate_image(
self,
task: ai_task.GenImageTask,
chat_log: conversation.ChatLog,
) -> ai_task.GenImageTaskResult:
"""Handle a generate image task."""
await self._async_handle_chat_log(chat_log, task.name, force_image=True)
if not isinstance(chat_log.content[-1], conversation.AssistantContent):
raise HomeAssistantError(
"Last content in chat log is not an AssistantContent"
)
image_call: ImageGenerationCall | None = None
for content in reversed(chat_log.content):
if not isinstance(content, conversation.AssistantContent):
break
if isinstance(content.native, ImageGenerationCall):
if image_call is None or image_call.result is None:
image_call = content.native
else: # Remove image data from chat log to save memory
content.native.result = None
if image_call is None or image_call.result is None:
raise HomeAssistantError("No image returned")
image_data = base64.b64decode(image_call.result)
image_call.result = None
if hasattr(image_call, "output_format") and (
output_format := image_call.output_format
):
mime_type = f"image/{output_format}"
else:
mime_type = "image/png"
if hasattr(image_call, "size") and (size := image_call.size):
width, height = tuple(size.split("x"))
else:
width, height = None, None
return ai_task.GenImageTaskResult(
image_data=image_data,
conversation_id=chat_log.conversation_id,
mime_type=mime_type,
width=int(width) if width else None,
height=int(height) if height else None,
model=self.subentry.data.get(CONF_IMAGE_MODEL, RECOMMENDED_IMAGE_MODEL),
revised_prompt=image_call.revised_prompt
if hasattr(image_call, "revised_prompt")
else None,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/openai_conversation/ai_task.py",
"license": "Apache License 2.0",
"lines": 129,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/openai_conversation/entity.py | """Base entity for OpenAI."""
from __future__ import annotations
import base64
from collections.abc import AsyncGenerator, Callable, Iterable
import json
from mimetypes import guess_file_type
from pathlib import Path
import re
from typing import TYPE_CHECKING, Any, Literal, cast
import openai
from openai._streaming import AsyncStream
from openai.types.responses import (
EasyInputMessageParam,
FunctionToolParam,
ResponseCodeInterpreterToolCall,
ResponseCompletedEvent,
ResponseErrorEvent,
ResponseFailedEvent,
ResponseFunctionCallArgumentsDeltaEvent,
ResponseFunctionCallArgumentsDoneEvent,
ResponseFunctionToolCall,
ResponseFunctionToolCallParam,
ResponseFunctionWebSearch,
ResponseFunctionWebSearchParam,
ResponseIncompleteEvent,
ResponseInputFileParam,
ResponseInputImageParam,
ResponseInputMessageContentListParam,
ResponseInputParam,
ResponseInputTextParam,
ResponseOutputItemAddedEvent,
ResponseOutputItemDoneEvent,
ResponseOutputMessage,
ResponseReasoningItem,
ResponseReasoningItemParam,
ResponseReasoningSummaryTextDeltaEvent,
ResponseStreamEvent,
ResponseTextDeltaEvent,
ToolChoiceTypesParam,
ToolParam,
WebSearchToolParam,
)
from openai.types.responses.response_create_params import ResponseCreateParamsStreaming
from openai.types.responses.response_input_param import (
FunctionCallOutput,
ImageGenerationCall as ImageGenerationCallParam,
)
from openai.types.responses.response_output_item import ImageGenerationCall
from openai.types.responses.tool_param import (
CodeInterpreter,
CodeInterpreterContainerCodeInterpreterToolAuto,
ImageGeneration,
)
from openai.types.responses.web_search_tool_param import UserLocation
import voluptuous as vol
from voluptuous_openapi import convert
from homeassistant.components import conversation
from homeassistant.config_entries import ConfigSubentry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, issue_registry as ir, llm
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.json import json_dumps
from homeassistant.util import slugify
from .const import (
CONF_CHAT_MODEL,
CONF_CODE_INTERPRETER,
CONF_IMAGE_MODEL,
CONF_MAX_TOKENS,
CONF_REASONING_EFFORT,
CONF_REASONING_SUMMARY,
CONF_TEMPERATURE,
CONF_TOP_P,
CONF_VERBOSITY,
CONF_WEB_SEARCH,
CONF_WEB_SEARCH_CITY,
CONF_WEB_SEARCH_CONTEXT_SIZE,
CONF_WEB_SEARCH_COUNTRY,
CONF_WEB_SEARCH_INLINE_CITATIONS,
CONF_WEB_SEARCH_REGION,
CONF_WEB_SEARCH_TIMEZONE,
CONF_WEB_SEARCH_USER_LOCATION,
DOMAIN,
LOGGER,
RECOMMENDED_CHAT_MODEL,
RECOMMENDED_IMAGE_MODEL,
RECOMMENDED_MAX_TOKENS,
RECOMMENDED_REASONING_EFFORT,
RECOMMENDED_REASONING_SUMMARY,
RECOMMENDED_STT_MODEL,
RECOMMENDED_TEMPERATURE,
RECOMMENDED_TOP_P,
RECOMMENDED_VERBOSITY,
RECOMMENDED_WEB_SEARCH_CONTEXT_SIZE,
RECOMMENDED_WEB_SEARCH_INLINE_CITATIONS,
UNSUPPORTED_EXTENDED_CACHE_RETENTION_MODELS,
)
if TYPE_CHECKING:
from . import OpenAIConfigEntry
# Max number of back and forth with the LLM to generate a response
MAX_TOOL_ITERATIONS = 10
def _adjust_schema(schema: dict[str, Any]) -> None:
"""Adjust the schema to be compatible with OpenAI API."""
if schema["type"] == "object":
schema.setdefault("strict", True)
schema.setdefault("additionalProperties", False)
if "properties" not in schema:
return
if "required" not in schema:
schema["required"] = []
# Ensure all properties are required
for prop, prop_info in schema["properties"].items():
_adjust_schema(prop_info)
if prop not in schema["required"]:
prop_info["type"] = [prop_info["type"], "null"]
schema["required"].append(prop)
elif schema["type"] == "array":
if "items" not in schema:
return
_adjust_schema(schema["items"])
def _format_structured_output(
schema: vol.Schema, llm_api: llm.APIInstance | None
) -> dict[str, Any]:
"""Format the schema to be compatible with OpenAI API."""
result: dict[str, Any] = convert(
schema,
custom_serializer=(
llm_api.custom_serializer if llm_api else llm.selector_serializer
),
)
_adjust_schema(result)
return result
def _format_tool(
tool: llm.Tool, custom_serializer: Callable[[Any], Any] | None
) -> FunctionToolParam:
"""Format tool specification."""
return FunctionToolParam(
type="function",
name=tool.name,
parameters=convert(tool.parameters, custom_serializer=custom_serializer),
description=tool.description,
strict=False,
)
def _convert_content_to_param(
chat_content: Iterable[conversation.Content],
) -> ResponseInputParam:
"""Convert any native chat message for this agent to the native format."""
messages: ResponseInputParam = []
reasoning_summary: list[str] = []
web_search_calls: dict[str, ResponseFunctionWebSearchParam] = {}
for content in chat_content:
if isinstance(content, conversation.ToolResultContent):
if (
content.tool_name == "web_search_call"
and content.tool_call_id in web_search_calls
):
web_search_call = web_search_calls.pop(content.tool_call_id)
web_search_call["status"] = content.tool_result.get( # type: ignore[typeddict-item]
"status", "completed"
)
messages.append(web_search_call)
else:
messages.append(
FunctionCallOutput(
type="function_call_output",
call_id=content.tool_call_id,
output=json_dumps(content.tool_result),
)
)
continue
if content.content:
role: Literal["user", "assistant", "system", "developer"] = content.role
if role == "system":
role = "developer"
messages.append(
EasyInputMessageParam(
type="message", role=role, content=content.content
)
)
if isinstance(content, conversation.AssistantContent):
if content.tool_calls:
for tool_call in content.tool_calls:
if (
tool_call.external
and tool_call.tool_name == "web_search_call"
and "action" in tool_call.tool_args
):
web_search_calls[tool_call.id] = ResponseFunctionWebSearchParam(
type="web_search_call",
id=tool_call.id,
action=tool_call.tool_args["action"],
status="completed",
)
else:
messages.append(
ResponseFunctionToolCallParam(
type="function_call",
name=tool_call.tool_name,
arguments=json_dumps(tool_call.tool_args),
call_id=tool_call.id,
)
)
if content.thinking_content:
reasoning_summary.append(content.thinking_content)
if isinstance(content.native, ResponseReasoningItem):
messages.append(
ResponseReasoningItemParam(
type="reasoning",
id=content.native.id,
summary=(
[
{
"type": "summary_text",
"text": summary,
}
for summary in reasoning_summary
]
if content.thinking_content
else []
),
encrypted_content=content.native.encrypted_content,
)
)
reasoning_summary = []
elif isinstance(content.native, ImageGenerationCall):
messages.append(
cast(ImageGenerationCallParam, content.native.to_dict())
)
return messages
async def _transform_stream( # noqa: C901 - This is complex, but better to have it in one place
chat_log: conversation.ChatLog,
stream: AsyncStream[ResponseStreamEvent],
remove_citations: bool = False,
) -> AsyncGenerator[
conversation.AssistantContentDeltaDict | conversation.ToolResultContentDeltaDict
]:
"""Transform an OpenAI delta stream into HA format."""
last_summary_index = None
last_role: Literal["assistant", "tool_result"] | None = None
# Non-reasoning models don't follow our request to remove citations, so we remove
# them manually here. They always follow the same pattern: the citation is always
# in parentheses in Markdown format, the citation is always in a single delta event,
# and sometimes the closing parenthesis is split into a separate delta event.
remove_parentheses: bool = False
citation_regexp = re.compile(r"\(\[([^\]]+)\]\((https?:\/\/[^\)]+)\)")
async for event in stream:
LOGGER.debug("Received event: %s", event)
if isinstance(event, ResponseOutputItemAddedEvent):
if isinstance(event.item, ResponseFunctionToolCall):
# OpenAI has tool calls as individual events
# while HA puts tool calls inside the assistant message.
# We turn them into individual assistant content for HA
# to ensure that tools are called as soon as possible.
yield {"role": "assistant"}
last_role = "assistant"
last_summary_index = None
current_tool_call = event.item
elif (
isinstance(event.item, ResponseOutputMessage)
or (
isinstance(event.item, ResponseReasoningItem)
and last_summary_index is not None
) # Subsequent ResponseReasoningItem
or last_role != "assistant"
):
yield {"role": "assistant"}
last_role = "assistant"
last_summary_index = None
elif isinstance(event, ResponseOutputItemDoneEvent):
if isinstance(event.item, ResponseReasoningItem):
yield {
"native": ResponseReasoningItem(
type="reasoning",
id=event.item.id,
summary=[], # Remove summaries
encrypted_content=event.item.encrypted_content,
)
}
last_summary_index = len(event.item.summary) - 1
elif isinstance(event.item, ResponseCodeInterpreterToolCall):
yield {
"tool_calls": [
llm.ToolInput(
id=event.item.id,
tool_name="code_interpreter",
tool_args={
"code": event.item.code,
"container": event.item.container_id,
},
external=True,
)
]
}
yield {
"role": "tool_result",
"tool_call_id": event.item.id,
"tool_name": "code_interpreter",
"tool_result": {
"output": (
[output.to_dict() for output in event.item.outputs] # type: ignore[misc]
if event.item.outputs is not None
else None
)
},
}
last_role = "tool_result"
elif isinstance(event.item, ResponseFunctionWebSearch):
yield {
"tool_calls": [
llm.ToolInput(
id=event.item.id,
tool_name="web_search_call",
tool_args={
"action": event.item.action.to_dict(),
},
external=True,
)
]
}
yield {
"role": "tool_result",
"tool_call_id": event.item.id,
"tool_name": "web_search_call",
"tool_result": {"status": event.item.status},
}
last_role = "tool_result"
elif isinstance(event.item, ImageGenerationCall):
yield {"native": event.item}
last_summary_index = -1 # Trigger new assistant message on next turn
elif isinstance(event, ResponseTextDeltaEvent):
data = event.delta
if remove_parentheses:
data = data.removeprefix(")")
remove_parentheses = False
elif remove_citations and (match := citation_regexp.search(data)):
match_start, match_end = match.span()
# remove leading space if any
if data[match_start - 1 : match_start] == " ":
match_start -= 1
# remove closing parenthesis:
if data[match_end : match_end + 1] == ")":
match_end += 1
else:
remove_parentheses = True
data = data[:match_start] + data[match_end:]
if data:
yield {"content": data}
elif isinstance(event, ResponseReasoningSummaryTextDeltaEvent):
# OpenAI can output several reasoning summaries
# in a single ResponseReasoningItem. We split them as separate
# AssistantContent messages. Only last of them will have
# the reasoning `native` field set.
if (
last_summary_index is not None
and event.summary_index != last_summary_index
):
yield {"role": "assistant"}
last_role = "assistant"
last_summary_index = event.summary_index
yield {"thinking_content": event.delta}
elif isinstance(event, ResponseFunctionCallArgumentsDeltaEvent):
current_tool_call.arguments += event.delta
elif isinstance(event, ResponseFunctionCallArgumentsDoneEvent):
current_tool_call.status = "completed"
yield {
"tool_calls": [
llm.ToolInput(
id=current_tool_call.call_id,
tool_name=current_tool_call.name,
tool_args=json.loads(current_tool_call.arguments),
)
]
}
elif isinstance(event, ResponseCompletedEvent):
if event.response.usage is not None:
chat_log.async_trace(
{
"stats": {
"input_tokens": event.response.usage.input_tokens,
"output_tokens": event.response.usage.output_tokens,
}
}
)
elif isinstance(event, ResponseIncompleteEvent):
if event.response.usage is not None:
chat_log.async_trace(
{
"stats": {
"input_tokens": event.response.usage.input_tokens,
"output_tokens": event.response.usage.output_tokens,
}
}
)
if (
event.response.incomplete_details
and event.response.incomplete_details.reason
):
reason: str = event.response.incomplete_details.reason
else:
reason = "unknown reason"
if reason == "max_output_tokens":
reason = "max output tokens reached"
elif reason == "content_filter":
reason = "content filter triggered"
raise HomeAssistantError(f"OpenAI response incomplete: {reason}")
elif isinstance(event, ResponseFailedEvent):
if event.response.usage is not None:
chat_log.async_trace(
{
"stats": {
"input_tokens": event.response.usage.input_tokens,
"output_tokens": event.response.usage.output_tokens,
}
}
)
reason = "unknown reason"
if event.response.error is not None:
reason = event.response.error.message
raise HomeAssistantError(f"OpenAI response failed: {reason}")
elif isinstance(event, ResponseErrorEvent):
raise HomeAssistantError(f"OpenAI response error: {event.message}")
class OpenAIBaseLLMEntity(Entity):
"""OpenAI conversation agent."""
_attr_has_entity_name = True
_attr_name: str | None = None
def __init__(self, entry: OpenAIConfigEntry, subentry: ConfigSubentry) -> None:
"""Initialize the entity."""
self.entry = entry
self.subentry = subentry
self._attr_unique_id = subentry.subentry_id
self._attr_device_info = dr.DeviceInfo(
identifiers={(DOMAIN, subentry.subentry_id)},
name=subentry.title,
manufacturer="OpenAI",
model=subentry.data.get(
CONF_CHAT_MODEL,
RECOMMENDED_CHAT_MODEL
if subentry.subentry_type != "stt"
else RECOMMENDED_STT_MODEL,
),
entry_type=dr.DeviceEntryType.SERVICE,
)
async def _async_handle_chat_log(
self,
chat_log: conversation.ChatLog,
structure_name: str | None = None,
structure: vol.Schema | None = None,
force_image: bool = False,
max_iterations: int = MAX_TOOL_ITERATIONS,
) -> None:
"""Generate an answer for the chat log."""
options = self.subentry.data
messages = _convert_content_to_param(chat_log.content)
model_args = ResponseCreateParamsStreaming(
model=options.get(CONF_CHAT_MODEL, RECOMMENDED_CHAT_MODEL),
input=messages,
max_output_tokens=options.get(CONF_MAX_TOKENS, RECOMMENDED_MAX_TOKENS),
user=chat_log.conversation_id,
store=False,
stream=True,
)
if model_args["model"].startswith(("o", "gpt-5")):
model_args["reasoning"] = {
"effort": options.get(
CONF_REASONING_EFFORT, RECOMMENDED_REASONING_EFFORT
)
if not model_args["model"].startswith("gpt-5-pro")
else "high", # GPT-5 pro only supports reasoning.effort: high
"summary": options.get(
CONF_REASONING_SUMMARY, RECOMMENDED_REASONING_SUMMARY
),
}
model_args["include"] = ["reasoning.encrypted_content"]
if (
not model_args["model"].startswith("gpt-5")
or model_args["reasoning"]["effort"] == "none" # type: ignore[index]
):
model_args["top_p"] = options.get(CONF_TOP_P, RECOMMENDED_TOP_P)
model_args["temperature"] = options.get(
CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE
)
if model_args["model"].startswith("gpt-5"):
model_args["text"] = {
"verbosity": options.get(CONF_VERBOSITY, RECOMMENDED_VERBOSITY)
}
if not model_args["model"].startswith(
tuple(UNSUPPORTED_EXTENDED_CACHE_RETENTION_MODELS)
):
model_args["prompt_cache_retention"] = "24h"
tools: list[ToolParam] = []
if chat_log.llm_api:
tools = [
_format_tool(tool, chat_log.llm_api.custom_serializer)
for tool in chat_log.llm_api.tools
]
remove_citations = False
if options.get(CONF_WEB_SEARCH):
web_search = WebSearchToolParam(
type="web_search",
search_context_size=options.get(
CONF_WEB_SEARCH_CONTEXT_SIZE, RECOMMENDED_WEB_SEARCH_CONTEXT_SIZE
),
)
if options.get(CONF_WEB_SEARCH_USER_LOCATION):
web_search["user_location"] = UserLocation(
type="approximate",
city=options.get(CONF_WEB_SEARCH_CITY, ""),
region=options.get(CONF_WEB_SEARCH_REGION, ""),
country=options.get(CONF_WEB_SEARCH_COUNTRY, ""),
timezone=options.get(CONF_WEB_SEARCH_TIMEZONE, ""),
)
if not options.get(
CONF_WEB_SEARCH_INLINE_CITATIONS,
RECOMMENDED_WEB_SEARCH_INLINE_CITATIONS,
):
system_message = cast(EasyInputMessageParam, messages[0])
content = system_message["content"]
if isinstance(content, str):
system_message["content"] = [
ResponseInputTextParam(type="input_text", text=content)
]
system_message["content"].append( # type: ignore[union-attr]
ResponseInputTextParam(
type="input_text",
text="When doing a web search, do not include source citations",
)
)
if "reasoning" not in model_args:
# Reasoning models handle this correctly with just a prompt
remove_citations = True
tools.append(web_search)
if options.get(CONF_CODE_INTERPRETER):
tools.append(
CodeInterpreter(
type="code_interpreter",
container=CodeInterpreterContainerCodeInterpreterToolAuto(
type="auto"
),
)
)
model_args.setdefault("include", []).append("code_interpreter_call.outputs") # type: ignore[union-attr]
if force_image:
image_model = options.get(CONF_IMAGE_MODEL, RECOMMENDED_IMAGE_MODEL)
image_tool = ImageGeneration(
type="image_generation",
model=image_model,
output_format="png",
)
if image_model != "gpt-image-1-mini":
image_tool["input_fidelity"] = "high"
tools.append(image_tool)
model_args["tool_choice"] = ToolChoiceTypesParam(type="image_generation")
model_args["store"] = True # Avoid sending image data back and forth
if tools:
model_args["tools"] = tools
last_content = chat_log.content[-1]
# Handle attachments by adding them to the last user message
if last_content.role == "user" and last_content.attachments:
files = await async_prepare_files_for_prompt(
self.hass,
[(a.path, a.mime_type) for a in last_content.attachments],
)
last_message = messages[-1]
assert (
last_message["type"] == "message"
and last_message["role"] == "user"
and isinstance(last_message["content"], str)
)
last_message["content"] = [
{"type": "input_text", "text": last_message["content"]}, # type: ignore[list-item]
*files, # type: ignore[list-item]
]
if structure and structure_name:
model_args["text"] = {
"format": {
"type": "json_schema",
"name": slugify(structure_name),
"schema": _format_structured_output(structure, chat_log.llm_api),
},
}
client = self.entry.runtime_data
# To prevent infinite loops, we limit the number of iterations
for _iteration in range(max_iterations):
try:
stream = await client.responses.create(**model_args)
messages.extend(
_convert_content_to_param(
[
content
async for content in chat_log.async_add_delta_content_stream(
self.entity_id,
_transform_stream(chat_log, stream, remove_citations),
)
]
)
)
except openai.RateLimitError as err:
LOGGER.error("Rate limited by OpenAI: %s", err)
raise HomeAssistantError("Rate limited or insufficient funds") from err
except openai.OpenAIError as err:
if (
isinstance(err, openai.APIError)
and err.type == "insufficient_quota"
):
LOGGER.error("Insufficient funds for OpenAI: %s", err)
raise HomeAssistantError("Insufficient funds for OpenAI") from err
if "Verify Organization" in str(err):
ir.async_create_issue(
self.hass,
DOMAIN,
"organization_verification_required",
is_fixable=False,
is_persistent=False,
learn_more_url="https://help.openai.com/en/articles/10910291-api-organization-verification",
severity=ir.IssueSeverity.WARNING,
translation_key="organization_verification_required",
translation_placeholders={
"platform_settings": "https://platform.openai.com/settings/organization/general"
},
)
LOGGER.error("Error talking to OpenAI: %s", err)
raise HomeAssistantError("Error talking to OpenAI") from err
if not chat_log.unresponded_tool_results:
break
async def async_prepare_files_for_prompt(
hass: HomeAssistant, files: list[tuple[Path, str | None]]
) -> ResponseInputMessageContentListParam:
"""Append files to a prompt.
Caller needs to ensure that the files are allowed.
"""
def append_files_to_content() -> ResponseInputMessageContentListParam:
content: ResponseInputMessageContentListParam = []
for file_path, mime_type in files:
if not file_path.exists():
raise HomeAssistantError(f"`{file_path}` does not exist")
if mime_type is None:
mime_type = guess_file_type(file_path)[0]
if not mime_type or not mime_type.startswith(("image/", "application/pdf")):
raise HomeAssistantError(
"Only images and PDF are supported by the OpenAI API,"
f"`{file_path}` is not an image file or PDF"
)
base64_file = base64.b64encode(file_path.read_bytes()).decode("utf-8")
if mime_type.startswith("image/"):
content.append(
ResponseInputImageParam(
type="input_image",
image_url=f"data:{mime_type};base64,{base64_file}",
detail="auto",
)
)
elif mime_type.startswith("application/pdf"):
content.append(
ResponseInputFileParam(
type="input_file",
filename=str(file_path),
file_data=f"data:{mime_type};base64,{base64_file}",
)
)
return content
return await hass.async_add_executor_job(append_files_to_content)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/openai_conversation/entity.py",
"license": "Apache License 2.0",
"lines": 661,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/playstation_network/binary_sensor.py | """Binary Sensor platform for PlayStation Network integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from enum import StrEnum
from homeassistant.components.binary_sensor import (
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import (
PlaystationNetworkConfigEntry,
PlaystationNetworkData,
PlaystationNetworkUserDataCoordinator,
)
from .entity import PlaystationNetworkServiceEntity
PARALLEL_UPDATES = 0
@dataclass(kw_only=True, frozen=True)
class PlaystationNetworkBinarySensorEntityDescription(BinarySensorEntityDescription):
"""PlayStation Network binary sensor description."""
is_on_fn: Callable[[PlaystationNetworkData], bool]
class PlaystationNetworkBinarySensor(StrEnum):
"""PlayStation Network binary sensors."""
PS_PLUS_STATUS = "ps_plus_status"
BINARY_SENSOR_DESCRIPTIONS: tuple[
PlaystationNetworkBinarySensorEntityDescription, ...
] = (
PlaystationNetworkBinarySensorEntityDescription(
key=PlaystationNetworkBinarySensor.PS_PLUS_STATUS,
translation_key=PlaystationNetworkBinarySensor.PS_PLUS_STATUS,
is_on_fn=lambda psn: psn.profile["isPlus"],
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: PlaystationNetworkConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the binary sensor platform."""
coordinator = config_entry.runtime_data.user_data
async_add_entities(
PlaystationNetworkBinarySensorEntity(coordinator, description)
for description in BINARY_SENSOR_DESCRIPTIONS
)
class PlaystationNetworkBinarySensorEntity(
PlaystationNetworkServiceEntity,
BinarySensorEntity,
):
"""Representation of a PlayStation Network binary sensor entity."""
entity_description: PlaystationNetworkBinarySensorEntityDescription
coordinator: PlaystationNetworkUserDataCoordinator
@property
def is_on(self) -> bool:
"""Return the state of the binary sensor."""
return self.entity_description.is_on_fn(self.coordinator.data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 56,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/playstation_network/entity.py | """Base entity for PlayStation Network Integration."""
from typing import TYPE_CHECKING
from homeassistant.config_entries import ConfigSubentry
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import PlayStationNetworkBaseCoordinator
from .helpers import PlaystationNetworkData
class PlaystationNetworkServiceEntity(
CoordinatorEntity[PlayStationNetworkBaseCoordinator]
):
"""Common entity class for PlayStationNetwork Service entities."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: PlayStationNetworkBaseCoordinator,
entity_description: EntityDescription,
subentry: ConfigSubentry | None = None,
) -> None:
"""Initialize PlayStation Network Service Entity."""
super().__init__(coordinator)
if TYPE_CHECKING:
assert coordinator.config_entry.unique_id
self.entity_description = entity_description
self.subentry = subentry
unique_id = (
subentry.unique_id
if subentry is not None and subentry.unique_id
else coordinator.config_entry.unique_id
)
self._attr_unique_id = f"{unique_id}_{entity_description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, unique_id)},
name=(
coordinator.data.username
if isinstance(coordinator.data, PlaystationNetworkData)
else coordinator.psn.user.online_id
),
entry_type=DeviceEntryType.SERVICE,
manufacturer="Sony Interactive Entertainment",
)
if subentry:
self._attr_device_info.update(
DeviceInfo(via_device=(DOMAIN, coordinator.config_entry.unique_id))
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/entity.py",
"license": "Apache License 2.0",
"lines": 46,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/playstation_network/image.py | """Image platform for PlayStation Network."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from enum import StrEnum
from typing import TYPE_CHECKING
from homeassistant.components.image import ImageEntity, ImageEntityDescription
from homeassistant.config_entries import ConfigSubentry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util import dt as dt_util
from .coordinator import (
PlayStationNetworkBaseCoordinator,
PlaystationNetworkConfigEntry,
PlaystationNetworkData,
PlaystationNetworkFriendDataCoordinator,
PlaystationNetworkUserDataCoordinator,
)
from .entity import PlaystationNetworkServiceEntity
from .helpers import get_game_title_info
PARALLEL_UPDATES = 0
class PlaystationNetworkImage(StrEnum):
"""PlayStation Network images."""
AVATAR = "avatar"
SHARE_PROFILE = "share_profile"
NOW_PLAYING_IMAGE = "now_playing_image"
@dataclass(kw_only=True, frozen=True)
class PlaystationNetworkImageEntityDescription(ImageEntityDescription):
"""Image entity description."""
image_url_fn: Callable[[PlaystationNetworkData], str | None]
IMAGE_DESCRIPTIONS_ME: tuple[PlaystationNetworkImageEntityDescription, ...] = (
PlaystationNetworkImageEntityDescription(
key=PlaystationNetworkImage.SHARE_PROFILE,
translation_key=PlaystationNetworkImage.SHARE_PROFILE,
image_url_fn=lambda data: data.shareable_profile_link["shareImageUrl"],
),
)
IMAGE_DESCRIPTIONS_ALL: tuple[PlaystationNetworkImageEntityDescription, ...] = (
PlaystationNetworkImageEntityDescription(
key=PlaystationNetworkImage.AVATAR,
translation_key=PlaystationNetworkImage.AVATAR,
image_url_fn=(
lambda data: next(
(
pic.get("url")
for pic in data.profile["avatars"]
if pic.get("size") == "xl"
),
None,
)
),
),
PlaystationNetworkImageEntityDescription(
key=PlaystationNetworkImage.NOW_PLAYING_IMAGE,
translation_key=PlaystationNetworkImage.NOW_PLAYING_IMAGE,
image_url_fn=(
lambda data: (
get_game_title_info(data.presence).get("conceptIconUrl")
or get_game_title_info(data.presence).get("npTitleIconUrl")
)
),
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: PlaystationNetworkConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up image platform."""
coordinator = config_entry.runtime_data.user_data
async_add_entities(
[
PlaystationNetworkImageEntity(hass, coordinator, description)
for description in IMAGE_DESCRIPTIONS_ME + IMAGE_DESCRIPTIONS_ALL
]
)
for (
subentry_id,
friend_data_coordinator,
) in config_entry.runtime_data.friends.items():
async_add_entities(
[
PlaystationNetworkFriendImageEntity(
hass,
friend_data_coordinator,
description,
config_entry.subentries[subentry_id],
)
for description in IMAGE_DESCRIPTIONS_ALL
],
config_subentry_id=subentry_id,
)
class PlaystationNetworkImageBaseEntity(PlaystationNetworkServiceEntity, ImageEntity):
"""An image entity."""
entity_description: PlaystationNetworkImageEntityDescription
coordinator: PlayStationNetworkBaseCoordinator
def __init__(
self,
hass: HomeAssistant,
coordinator: PlayStationNetworkBaseCoordinator,
entity_description: PlaystationNetworkImageEntityDescription,
subentry: ConfigSubentry | None = None,
) -> None:
"""Initialize the image entity."""
super().__init__(coordinator, entity_description, subentry)
ImageEntity.__init__(self, hass)
self._attr_image_url = self.entity_description.image_url_fn(coordinator.data)
self._attr_image_last_updated = dt_util.utcnow()
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
if TYPE_CHECKING:
assert isinstance(self.coordinator.data, PlaystationNetworkData)
url = self.entity_description.image_url_fn(self.coordinator.data)
if url != self._attr_image_url:
self._attr_image_url = url
self._cached_image = None
self._attr_image_last_updated = dt_util.utcnow()
super()._handle_coordinator_update()
class PlaystationNetworkImageEntity(PlaystationNetworkImageBaseEntity):
"""An image entity."""
coordinator: PlaystationNetworkUserDataCoordinator
class PlaystationNetworkFriendImageEntity(PlaystationNetworkImageBaseEntity):
"""An image entity."""
coordinator: PlaystationNetworkFriendDataCoordinator
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/image.py",
"license": "Apache License 2.0",
"lines": 124,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/playstation_network/notify.py | """Notify platform for PlayStation Network."""
from __future__ import annotations
from enum import StrEnum
from typing import TYPE_CHECKING
from psnawp_api.core.psnawp_exceptions import (
PSNAWPClientError,
PSNAWPForbiddenError,
PSNAWPNotFoundError,
PSNAWPServerError,
)
from psnawp_api.models.group.group import Group
from homeassistant.components.notify import (
DOMAIN as NOTIFY_DOMAIN,
NotifyEntity,
NotifyEntityDescription,
)
from homeassistant.const import CONF_NAME
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN
from .coordinator import (
PlaystationNetworkConfigEntry,
PlaystationNetworkFriendlistCoordinator,
PlaystationNetworkGroupsUpdateCoordinator,
)
from .entity import PlaystationNetworkServiceEntity
PARALLEL_UPDATES = 20
class PlaystationNetworkNotify(StrEnum):
"""PlayStation Network sensors."""
GROUP_MESSAGE = "group_message"
DIRECT_MESSAGE = "direct_message"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: PlaystationNetworkConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the notify entity platform."""
coordinator = config_entry.runtime_data.groups
friends_list = config_entry.runtime_data.friends_list
groups_added: set[str] = set()
friends_added: set[str] = set()
entity_registry = er.async_get(hass)
@callback
def add_entities() -> None:
nonlocal groups_added
new_groups = set(coordinator.data.keys()) - groups_added
if new_groups:
async_add_entities(
PlaystationNetworkNotifyEntity(coordinator, group_id)
for group_id in new_groups
)
groups_added |= new_groups
deleted_groups = groups_added - set(coordinator.data.keys())
for group_id in deleted_groups:
if entity_id := entity_registry.async_get_entity_id(
NOTIFY_DOMAIN,
DOMAIN,
f"{coordinator.config_entry.unique_id}_{group_id}",
):
entity_registry.async_remove(entity_id)
coordinator.async_add_listener(add_entities)
add_entities()
@callback
def add_dm_entities() -> None:
nonlocal friends_added
new_friends = set(friends_list.psn.friends_list.keys()) - friends_added
if new_friends:
async_add_entities(
[
PlaystationNetworkDirectMessageNotifyEntity(
friends_list, account_id
)
for account_id in new_friends
],
)
friends_added |= new_friends
deleted_friends = friends_added - set(coordinator.psn.friends_list.keys())
for account_id in deleted_friends:
if entity_id := entity_registry.async_get_entity_id(
NOTIFY_DOMAIN,
DOMAIN,
f"{coordinator.config_entry.unique_id}_{account_id}_{PlaystationNetworkNotify.DIRECT_MESSAGE}",
):
entity_registry.async_remove(entity_id)
friends_list.async_add_listener(add_dm_entities)
add_dm_entities()
class PlaystationNetworkNotifyBaseEntity(PlaystationNetworkServiceEntity, NotifyEntity):
"""Base class of PlayStation Network notify entity."""
psn_group: Group | None = None
def _send_message(self, message: str) -> None:
"""Send message."""
if TYPE_CHECKING:
assert self.psn_group
self.psn_group.send_message(message)
def send_message(self, message: str, title: str | None = None) -> None:
"""Send a message."""
try:
self._send_message(message)
except PSNAWPNotFoundError as e:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="group_invalid",
translation_placeholders=dict(self.translation_placeholders),
) from e
except PSNAWPForbiddenError as e:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="send_message_forbidden",
translation_placeholders=dict(self.translation_placeholders),
) from e
except (PSNAWPServerError, PSNAWPClientError) as e:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="send_message_failed",
translation_placeholders=dict(self.translation_placeholders),
) from e
class PlaystationNetworkNotifyEntity(PlaystationNetworkNotifyBaseEntity):
"""Representation of a PlayStation Network notify entity."""
coordinator: PlaystationNetworkGroupsUpdateCoordinator
def __init__(
self,
coordinator: PlaystationNetworkGroupsUpdateCoordinator,
group_id: str,
) -> None:
"""Initialize a notification entity."""
self.psn_group = coordinator.psn.psn.group(group_id=group_id)
group_details = coordinator.data[group_id]
self.entity_description = NotifyEntityDescription(
key=group_id,
translation_key=PlaystationNetworkNotify.GROUP_MESSAGE,
translation_placeholders={
CONF_NAME: group_details["groupName"]["value"]
or ", ".join(
member["onlineId"]
for member in group_details["members"]
if member["accountId"] != coordinator.psn.user.account_id
)
},
)
super().__init__(coordinator, self.entity_description)
class PlaystationNetworkDirectMessageNotifyEntity(PlaystationNetworkNotifyBaseEntity):
"""Representation of a PlayStation Network notify entity for sending direct messages."""
coordinator: PlaystationNetworkFriendlistCoordinator
def __init__(
self,
coordinator: PlaystationNetworkFriendlistCoordinator,
account_id: str,
) -> None:
"""Initialize a notification entity."""
self.account_id = account_id
self.entity_description = NotifyEntityDescription(
key=f"{account_id}_{PlaystationNetworkNotify.DIRECT_MESSAGE}",
translation_key=PlaystationNetworkNotify.DIRECT_MESSAGE,
translation_placeholders={
CONF_NAME: coordinator.psn.friends_list[account_id].online_id
},
entity_registry_enabled_default=False,
)
super().__init__(coordinator, self.entity_description)
def _send_message(self, message: str) -> None:
if not self.psn_group:
self.psn_group = self.coordinator.psn.psn.group(
users_list=[self.coordinator.psn.friends_list[self.account_id]]
)
super()._send_message(message)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/playstation_network/notify.py",
"license": "Apache License 2.0",
"lines": 167,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/smartthings/vacuum.py | """SmartThings vacuum platform."""
from __future__ import annotations
import logging
from typing import Any
from pysmartthings import Attribute, Command, SmartThings
from pysmartthings.capability import Capability
from homeassistant.components.vacuum import (
StateVacuumEntity,
VacuumActivity,
VacuumEntityFeature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import FullDevice, SmartThingsConfigEntry
from .const import MAIN
from .entity import SmartThingsEntity
_LOGGER = logging.getLogger(__name__)
TURBO_MODE_TO_FAN_SPEED = {
"silence": "normal",
"on": "maximum",
"off": "smart",
"extraSilence": "quiet",
}
FAN_SPEED_TO_TURBO_MODE = {v: k for k, v in TURBO_MODE_TO_FAN_SPEED.items()}
async def async_setup_entry(
hass: HomeAssistant,
entry: SmartThingsConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up vacuum entities from SmartThings devices."""
entry_data = entry.runtime_data
async_add_entities(
SamsungJetBotVacuum(entry_data.client, device)
for device in entry_data.devices.values()
if Capability.SAMSUNG_CE_ROBOT_CLEANER_OPERATING_STATE in device.status[MAIN]
)
class SamsungJetBotVacuum(SmartThingsEntity, StateVacuumEntity):
"""Representation of a Vacuum."""
_attr_name = None
_attr_translation_key = "vacuum"
def __init__(self, client: SmartThings, device: FullDevice) -> None:
"""Initialize the Samsung robot cleaner vacuum entity."""
super().__init__(
client,
device,
{
Capability.SAMSUNG_CE_ROBOT_CLEANER_OPERATING_STATE,
Capability.ROBOT_CLEANER_TURBO_MODE,
},
)
self._attr_supported_features = (
VacuumEntityFeature.START
| VacuumEntityFeature.RETURN_HOME
| VacuumEntityFeature.PAUSE
| VacuumEntityFeature.STATE
)
if self.supports_capability(Capability.ROBOT_CLEANER_TURBO_MODE):
self._attr_supported_features |= VacuumEntityFeature.FAN_SPEED
@property
def activity(self) -> VacuumActivity | None:
"""Return the current vacuum activity based on operating state."""
status = self.get_attribute_value(
Capability.SAMSUNG_CE_ROBOT_CLEANER_OPERATING_STATE,
Attribute.OPERATING_STATE,
)
return {
"cleaning": VacuumActivity.CLEANING,
"homing": VacuumActivity.RETURNING,
"idle": VacuumActivity.IDLE,
"paused": VacuumActivity.PAUSED,
"docked": VacuumActivity.DOCKED,
"error": VacuumActivity.ERROR,
"charging": VacuumActivity.DOCKED,
}.get(status)
@property
def fan_speed_list(self) -> list[str]:
"""Return the list of available fan speeds."""
if not self.supports_capability(Capability.ROBOT_CLEANER_TURBO_MODE):
return []
return list(TURBO_MODE_TO_FAN_SPEED.values())
@property
def fan_speed(self) -> str | None:
"""Return the current fan speed."""
if not self.supports_capability(Capability.ROBOT_CLEANER_TURBO_MODE):
return None
turbo_mode = self.get_attribute_value(
Capability.ROBOT_CLEANER_TURBO_MODE, Attribute.ROBOT_CLEANER_TURBO_MODE
)
return TURBO_MODE_TO_FAN_SPEED.get(turbo_mode)
async def async_start(self) -> None:
"""Start the vacuum's operation."""
await self.execute_device_command(
Capability.SAMSUNG_CE_ROBOT_CLEANER_OPERATING_STATE,
Command.START,
)
async def async_pause(self) -> None:
"""Pause the vacuum's current operation."""
await self.execute_device_command(
Capability.SAMSUNG_CE_ROBOT_CLEANER_OPERATING_STATE, Command.PAUSE
)
async def async_return_to_base(self, **kwargs: Any) -> None:
"""Return the vacuum to its base."""
await self.execute_device_command(
Capability.SAMSUNG_CE_ROBOT_CLEANER_OPERATING_STATE,
Command.RETURN_TO_HOME,
)
async def async_set_fan_speed(self, fan_speed: str, **kwargs: Any) -> None:
"""Set the fan speed."""
turbo_mode = FAN_SPEED_TO_TURBO_MODE[fan_speed]
await self.execute_device_command(
Capability.ROBOT_CLEANER_TURBO_MODE,
Command.SET_ROBOT_CLEANER_TURBO_MODE,
turbo_mode,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/smartthings/vacuum.py",
"license": "Apache License 2.0",
"lines": 114,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/smhi/sensor.py | """Sensor platform for SMHI integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import (
CONF_LATITUDE,
CONF_LOCATION,
CONF_LONGITUDE,
PERCENTAGE,
UnitOfSpeed,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .coordinator import (
SMHIConfigEntry,
SMHIDataUpdateCoordinator,
SMHIFireDataUpdateCoordinator,
)
from .entity import SmhiFireEntity, SmhiWeatherEntity
PARALLEL_UPDATES = 0
FWI_INDEX_MAP = {
"1": "very_low",
"2": "low",
"3": "moderate",
"4": "high",
"5": "very_high",
"6": "extreme",
}
GRASSFIRE_MAP = {
"1": "snow_cover",
"2": "season_over",
"3": "low",
"4": "moderate",
"5": "high",
"6": "very_high",
}
FORESTDRY_MAP = {
"1": "very_wet",
"2": "wet",
"3": "moderate_wet",
"4": "dry",
"5": "very_dry",
"6": "extremely_dry",
}
def get_percentage_values(entity: SMHIWeatherSensor, key: str) -> int | None:
"""Return percentage values in correct range."""
value: int | None = entity.coordinator.current.get(key) # type: ignore[assignment]
if value is not None and 0 <= value <= 100:
return value
if value is not None:
return 0
return None
def get_fire_index_value(entity: SMHIFireSensor, key: str) -> str:
"""Return index value as string."""
value: int | None = entity.coordinator.fire_current.get(key) # type: ignore[assignment]
if value is not None and value > 0:
return str(int(value))
return "0"
@dataclass(frozen=True, kw_only=True)
class SMHIWeatherEntityDescription(SensorEntityDescription):
"""Describes SMHI weather entity."""
value_fn: Callable[[SMHIWeatherSensor], StateType | datetime]
@dataclass(frozen=True, kw_only=True)
class SMHIFireEntityDescription(SensorEntityDescription):
"""Describes SMHI fire entity."""
value_fn: Callable[[SMHIFireSensor], StateType | datetime]
WEATHER_SENSOR_DESCRIPTIONS: tuple[SMHIWeatherEntityDescription, ...] = (
SMHIWeatherEntityDescription(
key="thunder",
translation_key="thunder",
value_fn=lambda entity: get_percentage_values(entity, "thunder"),
native_unit_of_measurement=PERCENTAGE,
),
SMHIWeatherEntityDescription(
key="total_cloud",
translation_key="total_cloud",
value_fn=lambda entity: get_percentage_values(entity, "total_cloud"),
native_unit_of_measurement=PERCENTAGE,
entity_registry_enabled_default=False,
),
SMHIWeatherEntityDescription(
key="low_cloud",
translation_key="low_cloud",
value_fn=lambda entity: get_percentage_values(entity, "low_cloud"),
native_unit_of_measurement=PERCENTAGE,
entity_registry_enabled_default=False,
),
SMHIWeatherEntityDescription(
key="medium_cloud",
translation_key="medium_cloud",
value_fn=lambda entity: get_percentage_values(entity, "medium_cloud"),
native_unit_of_measurement=PERCENTAGE,
entity_registry_enabled_default=False,
),
SMHIWeatherEntityDescription(
key="high_cloud",
translation_key="high_cloud",
value_fn=lambda entity: get_percentage_values(entity, "high_cloud"),
native_unit_of_measurement=PERCENTAGE,
entity_registry_enabled_default=False,
),
SMHIWeatherEntityDescription(
key="precipitation_category",
translation_key="precipitation_category",
value_fn=lambda entity: str(
get_percentage_values(entity, "precipitation_category")
),
device_class=SensorDeviceClass.ENUM,
options=["0", "1", "2", "3", "4", "5", "6"],
),
SMHIWeatherEntityDescription(
key="frozen_precipitation",
translation_key="frozen_precipitation",
value_fn=lambda entity: get_percentage_values(entity, "frozen_precipitation"),
native_unit_of_measurement=PERCENTAGE,
),
)
FIRE_SENSOR_DESCRIPTIONS: tuple[SMHIFireEntityDescription, ...] = (
SMHIFireEntityDescription(
key="fwiindex",
translation_key="fwiindex",
value_fn=(
lambda entity: FWI_INDEX_MAP.get(get_fire_index_value(entity, "fwiindex"))
),
device_class=SensorDeviceClass.ENUM,
options=[*FWI_INDEX_MAP.values()],
entity_registry_enabled_default=False,
),
SMHIFireEntityDescription(
key="fire_weather_index",
translation_key="fire_weather_index",
value_fn=lambda entity: entity.coordinator.fire_current.get("fwi"),
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
),
SMHIFireEntityDescription(
key="initial_spread_index",
translation_key="initial_spread_index",
value_fn=lambda entity: entity.coordinator.fire_current.get("isi"),
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
),
SMHIFireEntityDescription(
key="build_up_index",
translation_key="build_up_index",
value_fn=(
lambda entity: entity.coordinator.fire_current.get(
"bui" # codespell:ignore bui
)
),
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
),
SMHIFireEntityDescription(
key="fine_fuel_moisture_code",
translation_key="fine_fuel_moisture_code",
value_fn=lambda entity: entity.coordinator.fire_current.get("ffmc"),
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
),
SMHIFireEntityDescription(
key="duff_moisture_code",
translation_key="duff_moisture_code",
value_fn=lambda entity: entity.coordinator.fire_current.get("dmc"),
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
),
SMHIFireEntityDescription(
key="drought_code",
translation_key="drought_code",
value_fn=lambda entity: entity.coordinator.fire_current.get("dc"),
state_class=SensorStateClass.MEASUREMENT,
entity_registry_enabled_default=False,
),
SMHIFireEntityDescription(
key="grassfire",
translation_key="grassfire",
value_fn=(
lambda entity: GRASSFIRE_MAP.get(get_fire_index_value(entity, "grassfire"))
),
device_class=SensorDeviceClass.ENUM,
options=[*GRASSFIRE_MAP.values()],
entity_registry_enabled_default=False,
),
SMHIFireEntityDescription(
key="rate_of_spread",
translation_key="rate_of_spread",
value_fn=lambda entity: entity.coordinator.fire_current.get("rn"),
device_class=SensorDeviceClass.SPEED,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=UnitOfSpeed.METERS_PER_MINUTE,
entity_registry_enabled_default=False,
),
SMHIFireEntityDescription(
key="forestdry",
translation_key="forestdry",
value_fn=(
lambda entity: FORESTDRY_MAP.get(get_fire_index_value(entity, "forestdry"))
),
device_class=SensorDeviceClass.ENUM,
options=[*FORESTDRY_MAP.values()],
entity_registry_enabled_default=False,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: SMHIConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up SMHI sensor platform."""
coordinator = entry.runtime_data[0]
fire_coordinator = entry.runtime_data[1]
location = entry.data
entities: list[SMHIWeatherSensor | SMHIFireSensor] = []
entities.extend(
SMHIWeatherSensor(
location[CONF_LOCATION][CONF_LATITUDE],
location[CONF_LOCATION][CONF_LONGITUDE],
coordinator=coordinator,
entity_description=description,
)
for description in WEATHER_SENSOR_DESCRIPTIONS
)
entities.extend(
SMHIFireSensor(
location[CONF_LOCATION][CONF_LATITUDE],
location[CONF_LOCATION][CONF_LONGITUDE],
coordinator=fire_coordinator,
entity_description=description,
)
for description in FIRE_SENSOR_DESCRIPTIONS
)
async_add_entities(entities)
class SMHIWeatherSensor(SmhiWeatherEntity, SensorEntity):
"""Representation of a SMHI Weather Sensor."""
entity_description: SMHIWeatherEntityDescription
def __init__(
self,
latitude: str,
longitude: str,
coordinator: SMHIDataUpdateCoordinator,
entity_description: SMHIWeatherEntityDescription,
) -> None:
"""Initiate SMHI Sensor."""
self.entity_description = entity_description
super().__init__(
latitude,
longitude,
coordinator,
)
self._attr_unique_id = f"{latitude}, {longitude}-{entity_description.key}"
def update_entity_data(self) -> None:
"""Refresh the entity data."""
if self.coordinator.data.daily:
self._attr_native_value = self.entity_description.value_fn(self)
class SMHIFireSensor(SmhiFireEntity, SensorEntity):
"""Representation of a SMHI Weather Sensor."""
entity_description: SMHIFireEntityDescription
def __init__(
self,
latitude: str,
longitude: str,
coordinator: SMHIFireDataUpdateCoordinator,
entity_description: SMHIFireEntityDescription,
) -> None:
"""Initiate SMHI Sensor."""
self.entity_description = entity_description
super().__init__(
latitude,
longitude,
coordinator,
)
self._attr_unique_id = f"{latitude}, {longitude}-{entity_description.key}"
def update_entity_data(self) -> None:
"""Refresh the entity data."""
if self.coordinator.data.fire_daily:
self._attr_native_value = self.entity_description.value_fn(self)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/smhi/sensor.py",
"license": "Apache License 2.0",
"lines": 285,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/stookwijzer/services.py | """Define services for the Stookwijzer integration."""
from typing import Required, TypedDict, cast
import voluptuous as vol
from homeassistant.const import ATTR_CONFIG_ENTRY_ID
from homeassistant.core import (
HomeAssistant,
ServiceCall,
ServiceResponse,
SupportsResponse,
callback,
)
from homeassistant.helpers import service
from .const import DOMAIN, SERVICE_GET_FORECAST
from .coordinator import StookwijzerConfigEntry
SERVICE_GET_FORECAST_SCHEMA = vol.Schema(
{
vol.Required(ATTR_CONFIG_ENTRY_ID): str,
}
)
class Forecast(TypedDict):
"""Typed Stookwijzer forecast dict."""
datetime: Required[str]
advice: str | None
final: bool | None
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up the services for the Stookwijzer integration."""
async def async_get_forecast(call: ServiceCall) -> ServiceResponse:
"""Get the forecast from API endpoint."""
entry: StookwijzerConfigEntry = service.async_get_config_entry(
call.hass, DOMAIN, call.data[ATTR_CONFIG_ENTRY_ID]
)
client = entry.runtime_data.client
return cast(
ServiceResponse,
{
"forecast": cast(
list[Forecast], await client.async_get_forecast() or []
),
},
)
hass.services.async_register(
DOMAIN,
SERVICE_GET_FORECAST,
async_get_forecast,
schema=SERVICE_GET_FORECAST_SCHEMA,
supports_response=SupportsResponse.ONLY,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/stookwijzer/services.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/switchbot_cloud/fan.py | """Support for the Switchbot Battery Circulator fan."""
import asyncio
import logging
from typing import Any
from switchbot_api import (
AirPurifierCommands,
BatteryCirculatorFanCommands,
BatteryCirculatorFanMode,
CommonCommands,
SwitchBotAPI,
)
from homeassistant.components.fan import FanEntity, FanEntityFeature
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_ON
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import SwitchbotCloudData
from .const import AFTER_COMMAND_REFRESH, DOMAIN, AirPurifierMode
from .entity import SwitchBotCloudEntity
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
config: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up SwitchBot Cloud entry."""
data: SwitchbotCloudData = hass.data[DOMAIN][config.entry_id]
for device, coordinator in data.devices.fans:
if device.device_type.startswith("Air Purifier"):
async_add_entities(
[SwitchBotAirPurifierEntity(data.api, device, coordinator)]
)
else:
async_add_entities([SwitchBotCloudFan(data.api, device, coordinator)])
class SwitchBotCloudFan(SwitchBotCloudEntity, FanEntity):
"""Representation of a SwitchBot Battery Circulator Fan."""
_attr_name = None
_api: SwitchBotAPI
_attr_supported_features = (
FanEntityFeature.SET_SPEED
| FanEntityFeature.PRESET_MODE
| FanEntityFeature.TURN_OFF
| FanEntityFeature.TURN_ON
)
_attr_preset_modes = list(BatteryCirculatorFanMode)
_attr_is_on: bool | None = None
@property
def is_on(self) -> bool | None:
"""Return true if the entity is on."""
return self._attr_is_on
def _set_attributes(self) -> None:
"""Set attributes from coordinator data."""
if self.coordinator.data is None:
return
power: str = self.coordinator.data["power"]
mode: str = self.coordinator.data["mode"]
fan_speed: str = self.coordinator.data["fanSpeed"]
self._attr_is_on = power == "on"
self._attr_preset_mode = mode
self._attr_percentage = int(fan_speed)
self._attr_supported_features = (
FanEntityFeature.PRESET_MODE
| FanEntityFeature.TURN_OFF
| FanEntityFeature.TURN_ON
)
if self.is_on and self.preset_mode == BatteryCirculatorFanMode.DIRECT.value:
self._attr_supported_features |= FanEntityFeature.SET_SPEED
async def async_turn_on(
self,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn on the fan."""
await self.send_api_command(CommonCommands.ON)
await self.send_api_command(
command=BatteryCirculatorFanCommands.SET_WIND_MODE,
parameters=str(self.preset_mode),
)
if self.preset_mode == BatteryCirculatorFanMode.DIRECT.value:
await self.send_api_command(
command=BatteryCirculatorFanCommands.SET_WIND_SPEED,
parameters=str(self.percentage),
)
await asyncio.sleep(AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the fan."""
await self.send_api_command(CommonCommands.OFF)
await asyncio.sleep(AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_set_percentage(self, percentage: int) -> None:
"""Set the speed of the fan, as a percentage."""
await self.send_api_command(
command=BatteryCirculatorFanCommands.SET_WIND_MODE,
parameters=str(BatteryCirculatorFanMode.DIRECT.value),
)
await self.send_api_command(
command=BatteryCirculatorFanCommands.SET_WIND_SPEED,
parameters=str(percentage),
)
await asyncio.sleep(AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set new preset mode."""
await self.send_api_command(
command=BatteryCirculatorFanCommands.SET_WIND_MODE,
parameters=preset_mode,
)
await asyncio.sleep(AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
class SwitchBotAirPurifierEntity(SwitchBotCloudEntity, FanEntity):
"""Representation of a Switchbot air purifier."""
_api: SwitchBotAPI
_attr_supported_features = (
FanEntityFeature.PRESET_MODE
| FanEntityFeature.TURN_OFF
| FanEntityFeature.TURN_ON
)
_attr_preset_modes = AirPurifierMode.get_modes()
_attr_translation_key = "air_purifier"
_attr_name = None
_attr_is_on: bool | None = None
@property
def is_on(self) -> bool | None:
"""Return true if device is on."""
return self._attr_is_on
def _set_attributes(self) -> None:
"""Set attributes from coordinator data."""
if self.coordinator.data is None:
return
self._attr_is_on = self.coordinator.data.get("power") == STATE_ON.upper()
mode = self.coordinator.data.get("mode")
self._attr_preset_mode = (
AirPurifierMode(mode).name.lower() if mode is not None else None
)
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the air purifier."""
_LOGGER.debug(
"Switchbot air purifier to set preset mode %s %s",
preset_mode,
self._attr_unique_id,
)
await self.send_api_command(
AirPurifierCommands.SET_MODE,
parameters={"mode": AirPurifierMode[preset_mode.upper()].value},
)
await asyncio.sleep(AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_turn_on(
self,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn on the air purifier."""
_LOGGER.debug(
"Switchbot air purifier to set turn on %s %s %s",
percentage,
preset_mode,
self._attr_unique_id,
)
await self.send_api_command(CommonCommands.ON)
await asyncio.sleep(AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the air purifier."""
_LOGGER.debug("Switchbot air purifier to set turn off %s", self._attr_unique_id)
await self.send_api_command(CommonCommands.OFF)
await asyncio.sleep(AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/switchbot_cloud/fan.py",
"license": "Apache License 2.0",
"lines": 172,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/switchbot_cloud/light.py | """Support for the Switchbot Light."""
import asyncio
from typing import Any
from switchbot_api import (
CeilingLightCommands,
CommonCommands,
Device,
Remote,
RGBWLightCommands,
RGBWWLightCommands,
SwitchBotAPI,
)
from homeassistant.components.light import ColorMode, LightEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import SwitchbotCloudData, SwitchBotCoordinator
from .const import AFTER_COMMAND_REFRESH, DOMAIN
from .entity import SwitchBotCloudEntity
def value_map_brightness(value: int) -> int:
"""Return value for brightness map."""
return int(value / 255 * 100)
def brightness_map_value(value: int) -> int:
"""Return brightness from map value."""
return int(value * 255 / 100)
async def async_setup_entry(
hass: HomeAssistant,
config: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up SwitchBot Cloud entry."""
data: SwitchbotCloudData = hass.data[DOMAIN][config.entry_id]
async_add_entities(
_async_make_entity(data.api, device, coordinator)
for device, coordinator in data.devices.lights
)
class SwitchBotCloudLight(SwitchBotCloudEntity, LightEntity):
"""Base Class for SwitchBot Light."""
_attr_is_on: bool | None = None
_attr_name: str | None = None
_attr_color_mode = ColorMode.UNKNOWN
def _get_default_color_mode(self) -> ColorMode:
"""Return the default color mode."""
if not self.supported_color_modes:
return ColorMode.UNKNOWN
if ColorMode.RGB in self.supported_color_modes:
return ColorMode.RGB
if ColorMode.COLOR_TEMP in self.supported_color_modes:
return ColorMode.COLOR_TEMP
return ColorMode.UNKNOWN
def _set_attributes(self) -> None:
"""Set attributes from coordinator data."""
if self.coordinator.data is None:
return
power: str | None = self.coordinator.data.get("power")
brightness: int | None = self.coordinator.data.get("brightness")
color: str | None = self.coordinator.data.get("color")
color_temperature: int | None = self.coordinator.data.get("colorTemperature")
self._attr_is_on = power == "on" if power else None
self._attr_brightness: int | None = (
brightness_map_value(brightness) if brightness else None
)
self._attr_rgb_color: tuple | None = (
(tuple(int(i) for i in color.split(":"))) if color else None
)
self._attr_color_temp_kelvin: int | None = color_temperature or None
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the light off."""
await self.send_api_command(CommonCommands.OFF)
await asyncio.sleep(AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the light on."""
brightness: int | None = kwargs.get("brightness")
rgb_color: tuple[int, int, int] | None = kwargs.get("rgb_color")
color_temp_kelvin: int | None = kwargs.get("color_temp_kelvin")
if brightness is not None:
self._attr_color_mode = self._get_default_color_mode()
await self._send_brightness_command(brightness)
elif rgb_color is not None:
self._attr_color_mode = ColorMode.RGB
await self._send_rgb_color_command(rgb_color)
elif color_temp_kelvin is not None:
self._attr_color_mode = ColorMode.COLOR_TEMP
await self._send_color_temperature_command(color_temp_kelvin)
else:
self._attr_color_mode = self._get_default_color_mode()
await self.send_api_command(CommonCommands.ON)
await asyncio.sleep(AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def _send_brightness_command(self, brightness: int) -> None:
"""Send a brightness command."""
await self.send_api_command(
RGBWLightCommands.SET_BRIGHTNESS,
parameters=str(value_map_brightness(brightness)),
)
async def _send_rgb_color_command(self, rgb_color: tuple) -> None:
"""Send an RGB command."""
await self.send_api_command(
RGBWLightCommands.SET_COLOR,
parameters=f"{rgb_color[2]}:{rgb_color[1]}:{rgb_color[0]}",
)
async def _send_color_temperature_command(self, color_temp_kelvin: int) -> None:
"""Send a color temperature command."""
await self.send_api_command(
RGBWWLightCommands.SET_COLOR_TEMPERATURE,
parameters=str(color_temp_kelvin),
)
class SwitchBotCloudCandleWarmerLamp(SwitchBotCloudLight):
"""Representation of a SwitchBotCloud CandleWarmerLamp."""
# Brightness adjustment
_attr_supported_color_modes = {ColorMode.BRIGHTNESS}
class SwitchBotCloudStripLight(SwitchBotCloudLight):
"""Representation of a SwitchBot Strip Light."""
# Brightness adjustment
# RGB color control
_attr_supported_color_modes = {ColorMode.RGB}
class SwitchBotCloudRGBICLight(SwitchBotCloudLight):
"""Representation of a SwitchBotCloudRGBICLight."""
# Brightness adjustment
# RGB color control
_attr_supported_color_modes = {ColorMode.RGB}
async def _send_rgb_color_command(self, rgb_color: tuple) -> None:
"""Send an RGB command."""
await self.send_api_command(
RGBWLightCommands.SET_COLOR,
parameters=f"{rgb_color[0]}:{rgb_color[1]}:{rgb_color[2]}",
)
class SwitchBotCloudRGBWWLight(SwitchBotCloudLight):
"""Representation of SwitchBot |Strip Light|Floor Lamp|Color Bulb."""
# Brightness adjustment
# RGB color control
# Color temperature control
_attr_max_color_temp_kelvin = 6500
_attr_min_color_temp_kelvin = 2700
_attr_supported_color_modes = {ColorMode.RGB, ColorMode.COLOR_TEMP}
async def _send_brightness_command(self, brightness: int) -> None:
"""Send a brightness command."""
await self.send_api_command(
RGBWWLightCommands.SET_BRIGHTNESS,
parameters=str(value_map_brightness(brightness)),
)
async def _send_rgb_color_command(self, rgb_color: tuple) -> None:
"""Send an RGB command."""
await self.send_api_command(
RGBWWLightCommands.SET_COLOR,
parameters=f"{rgb_color[0]}:{rgb_color[1]}:{rgb_color[2]}",
)
class SwitchBotCloudCeilingLight(SwitchBotCloudLight):
"""Representation of SwitchBot Ceiling Light."""
# Brightness adjustment
# Color temperature control
_attr_max_color_temp_kelvin = 6500
_attr_min_color_temp_kelvin = 2700
_attr_supported_color_modes = {ColorMode.COLOR_TEMP}
async def _send_brightness_command(self, brightness: int) -> None:
"""Send a brightness command."""
await self.send_api_command(
CeilingLightCommands.SET_BRIGHTNESS,
parameters=str(value_map_brightness(brightness)),
)
async def _send_color_temperature_command(self, color_temp_kelvin: int) -> None:
"""Send a color temperature command."""
await self.send_api_command(
CeilingLightCommands.SET_COLOR_TEMPERATURE,
parameters=str(color_temp_kelvin),
)
@callback
def _async_make_entity(
api: SwitchBotAPI, device: Device | Remote, coordinator: SwitchBotCoordinator
) -> SwitchBotCloudLight:
"""Make a SwitchBotCloudLight."""
if device.device_type == "Strip Light":
return SwitchBotCloudStripLight(api, device, coordinator)
if device.device_type in ["Ceiling Light", "Ceiling Light Pro"]:
return SwitchBotCloudCeilingLight(api, device, coordinator)
if device.device_type == "Candle Warmer Lamp":
return SwitchBotCloudCandleWarmerLamp(api, device, coordinator)
if device.device_type in ["RGBIC Neon Rope Light", "RGBIC Neon Wire Rope Light"]:
return SwitchBotCloudRGBICLight(api, device, coordinator)
return SwitchBotCloudRGBWWLight(api, device, coordinator)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/switchbot_cloud/light.py",
"license": "Apache License 2.0",
"lines": 181,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/uptime_kuma/config_flow.py | """Config flow for the Uptime Kuma integration."""
from __future__ import annotations
from collections.abc import Mapping
import logging
from typing import Any
from pythonkuma import (
UptimeKuma,
UptimeKumaAuthenticationException,
UptimeKumaException,
UptimeKumaParseException,
)
import voluptuous as vol
from yarl import URL
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.selector import (
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from homeassistant.helpers.service_info.hassio import HassioServiceInfo
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_URL): TextSelector(
TextSelectorConfig(
type=TextSelectorType.URL,
autocomplete="url",
),
),
vol.Required(CONF_VERIFY_SSL, default=True): bool,
vol.Optional(CONF_API_KEY, default=""): str,
}
)
STEP_REAUTH_DATA_SCHEMA = vol.Schema({vol.Optional(CONF_API_KEY, default=""): str})
PLACEHOLDER = {"example_url": "https://uptime.example.com:3001"}
async def validate_connection(
hass: HomeAssistant,
url: URL | str,
verify_ssl: bool,
api_key: str | None,
) -> dict[str, str]:
"""Validate Uptime Kuma connectivity."""
errors: dict[str, str] = {}
session = async_get_clientsession(hass, verify_ssl)
uptime_kuma = UptimeKuma(session, url, api_key)
try:
await uptime_kuma.metrics()
except UptimeKumaAuthenticationException:
errors["base"] = "invalid_auth"
except UptimeKumaParseException:
errors["base"] = "invalid_data"
except UptimeKumaException:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
return errors
class UptimeKumaConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Uptime Kuma."""
_hassio_discovery: HassioServiceInfo | None = None
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
url = URL(user_input[CONF_URL])
self._async_abort_entries_match({CONF_URL: url.human_repr()})
if not (
errors := await validate_connection(
self.hass,
url,
user_input[CONF_VERIFY_SSL],
user_input[CONF_API_KEY],
)
):
return self.async_create_entry(
title=url.host or "",
data={**user_input, CONF_URL: url.human_repr()},
)
return self.async_show_form(
step_id="user",
data_schema=self.add_suggested_values_to_schema(
data_schema=STEP_USER_DATA_SCHEMA, suggested_values=user_input
),
errors=errors,
description_placeholders=PLACEHOLDER,
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauth upon an API authentication error."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauthentication dialog."""
errors: dict[str, str] = {}
entry = self._get_reauth_entry()
if user_input is not None:
if not (
errors := await validate_connection(
self.hass,
entry.data[CONF_URL],
entry.data[CONF_VERIFY_SSL],
user_input[CONF_API_KEY],
)
):
return self.async_update_reload_and_abort(
entry,
data_updates=user_input,
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=self.add_suggested_values_to_schema(
data_schema=STEP_REAUTH_DATA_SCHEMA, suggested_values=user_input
),
errors=errors,
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reconfigure flow."""
errors: dict[str, str] = {}
entry = self._get_reconfigure_entry()
if user_input is not None:
url = URL(user_input[CONF_URL])
self._async_abort_entries_match({CONF_URL: url.human_repr()})
if not (
errors := await validate_connection(
self.hass,
url,
user_input[CONF_VERIFY_SSL],
user_input[CONF_API_KEY],
)
):
return self.async_update_reload_and_abort(
entry,
data_updates={**user_input, CONF_URL: url.human_repr()},
)
return self.async_show_form(
step_id="reconfigure",
data_schema=self.add_suggested_values_to_schema(
data_schema=STEP_USER_DATA_SCHEMA,
suggested_values=user_input or entry.data,
),
errors=errors,
description_placeholders=PLACEHOLDER,
)
async def async_step_hassio(
self, discovery_info: HassioServiceInfo
) -> ConfigFlowResult:
"""Prepare configuration for Uptime Kuma app.
This flow is triggered by the discovery component.
"""
self._async_abort_entries_match({CONF_URL: discovery_info.config[CONF_URL]})
await self.async_set_unique_id(discovery_info.uuid)
self._abort_if_unique_id_configured(
updates={CONF_URL: discovery_info.config[CONF_URL]}
)
self._hassio_discovery = discovery_info
return await self.async_step_hassio_confirm()
async def async_step_hassio_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm Supervisor discovery."""
assert self._hassio_discovery
errors: dict[str, str] = {}
api_key = user_input[CONF_API_KEY] if user_input else None
if not (
errors := await validate_connection(
self.hass,
self._hassio_discovery.config[CONF_URL],
True,
api_key,
)
):
if user_input is None:
self._set_confirm_only()
return self.async_show_form(
step_id="hassio_confirm",
description_placeholders={
"addon": self._hassio_discovery.config["addon"]
},
)
return self.async_create_entry(
title=self._hassio_discovery.slug,
data={
CONF_URL: self._hassio_discovery.config[CONF_URL],
CONF_VERIFY_SSL: True,
CONF_API_KEY: api_key,
},
)
return self.async_show_form(
step_id="hassio_confirm",
data_schema=self.add_suggested_values_to_schema(
data_schema=STEP_REAUTH_DATA_SCHEMA, suggested_values=user_input
),
description_placeholders={"addon": self._hassio_discovery.config["addon"]},
errors=errors if user_input is not None else None,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uptime_kuma/config_flow.py",
"license": "Apache License 2.0",
"lines": 205,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/uptime_kuma/const.py | """Constants for the Uptime Kuma integration."""
from pythonkuma import MonitorType
DOMAIN = "uptime_kuma"
HAS_CERT = {
MonitorType.HTTP,
MonitorType.KEYWORD,
MonitorType.JSON_QUERY,
}
HAS_URL = HAS_CERT | {MonitorType.REAL_BROWSER}
HAS_PORT = {
MonitorType.PORT,
MonitorType.STEAM,
MonitorType.GAMEDIG,
MonitorType.MQTT,
MonitorType.RADIUS,
MonitorType.SNMP,
MonitorType.SMTP,
}
HAS_HOST = HAS_PORT | {
MonitorType.PING,
MonitorType.TAILSCALE_PING,
MonitorType.DNS,
}
LOCAL_INSTANCE = ("127.0.0.1", "localhost", "a0d7b954-uptime-kuma")
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uptime_kuma/const.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/uptime_kuma/coordinator.py | """Coordinator for the Uptime Kuma integration."""
from __future__ import annotations
from datetime import timedelta
import logging
from pythonkuma import (
UpdateException,
UptimeKuma,
UptimeKumaAuthenticationException,
UptimeKumaException,
UptimeKumaMonitor,
UptimeKumaParseException,
UptimeKumaVersion,
)
from pythonkuma.update import LatestRelease, UpdateChecker
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=30)
SCAN_INTERVAL_UPDATES = timedelta(hours=3)
type UptimeKumaConfigEntry = ConfigEntry[UptimeKumaDataUpdateCoordinator]
class UptimeKumaDataUpdateCoordinator(
DataUpdateCoordinator[dict[str | int, UptimeKumaMonitor]]
):
"""Update coordinator for Uptime Kuma."""
config_entry: UptimeKumaConfigEntry
def __init__(
self, hass: HomeAssistant, config_entry: UptimeKumaConfigEntry
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name=DOMAIN,
update_interval=SCAN_INTERVAL,
)
session = async_get_clientsession(hass, config_entry.data[CONF_VERIFY_SSL])
self.api = UptimeKuma(
session, config_entry.data[CONF_URL], config_entry.data[CONF_API_KEY]
)
self.version: UptimeKumaVersion | None = None
async def _async_update_data(self) -> dict[str | int, UptimeKumaMonitor]:
"""Fetch the latest data from Uptime Kuma."""
try:
metrics = await self.api.metrics()
except UptimeKumaAuthenticationException as e:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="auth_failed_exception",
) from e
except UptimeKumaParseException as e:
_LOGGER.debug("Full exception", exc_info=True)
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="parsing_failed_exception",
) from e
except UptimeKumaException as e:
_LOGGER.debug("Full exception", exc_info=True)
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="request_failed_exception",
) from e
else:
async_migrate_entities_unique_ids(self.hass, self, metrics)
self.version = self.api.version
return metrics
@callback
def async_migrate_entities_unique_ids(
hass: HomeAssistant,
coordinator: UptimeKumaDataUpdateCoordinator,
metrics: dict[str | int, UptimeKumaMonitor],
) -> None:
"""Migrate unique_ids in the entity registry after updating Uptime Kuma."""
if (
coordinator.version is None
or coordinator.version.version == coordinator.api.version.version
or int(coordinator.api.version.major) < 2
):
return
entity_registry = er.async_get(hass)
registry_entries = er.async_entries_for_config_entry(
entity_registry, coordinator.config_entry.entry_id
)
for registry_entry in registry_entries:
name = registry_entry.unique_id.removeprefix(
f"{registry_entry.config_entry_id}_"
).removesuffix(f"_{registry_entry.translation_key}")
if monitor := next(
(
m
for m in metrics.values()
if m.monitor_name == name and m.monitor_id is not None
),
None,
):
entity_registry.async_update_entity(
registry_entry.entity_id,
new_unique_id=f"{registry_entry.config_entry_id}_{monitor.monitor_id!s}_{registry_entry.translation_key}",
)
# migrate device identifiers and update version
device_reg = dr.async_get(hass)
for monitor in metrics.values():
if device := device_reg.async_get_device(
{(DOMAIN, f"{coordinator.config_entry.entry_id}_{monitor.monitor_name!s}")}
):
new_identifier = {
(DOMAIN, f"{coordinator.config_entry.entry_id}_{monitor.monitor_id!s}")
}
device_reg.async_update_device(
device.id,
new_identifiers=new_identifier,
sw_version=coordinator.api.version.version,
)
if device := device_reg.async_get_device(
{(DOMAIN, f"{coordinator.config_entry.entry_id}_update")}
):
device_reg.async_update_device(
device.id,
sw_version=coordinator.api.version.version,
)
hass.async_create_task(
hass.config_entries.async_reload(coordinator.config_entry.entry_id)
)
class UptimeKumaSoftwareUpdateCoordinator(DataUpdateCoordinator[LatestRelease]):
"""Uptime Kuma coordinator for retrieving update information."""
def __init__(self, hass: HomeAssistant, update_checker: UpdateChecker) -> None:
"""Initialize coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=None,
name=DOMAIN,
update_interval=SCAN_INTERVAL_UPDATES,
)
self.update_checker = update_checker
async def _async_update_data(self) -> LatestRelease:
"""Fetch data."""
try:
return await self.update_checker.latest_release()
except UpdateException as e:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_check_failed",
) from e
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uptime_kuma/coordinator.py",
"license": "Apache License 2.0",
"lines": 150,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/uptime_kuma/diagnostics.py | """Diagnostics platform for Uptime Kuma."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.core import HomeAssistant
from .coordinator import UptimeKumaConfigEntry
TO_REDACT = {"monitor_url", "monitor_hostname"}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: UptimeKumaConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return async_redact_data(
{k: asdict(v) for k, v in entry.runtime_data.data.items()}, TO_REDACT
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uptime_kuma/diagnostics.py",
"license": "Apache License 2.0",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/uptime_kuma/sensor.py | """Sensor platform for the Uptime Kuma integration."""
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from pythonkuma import MonitorType, UptimeKumaMonitor
from pythonkuma.models import MonitorStatus
from yarl import URL
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import CONF_URL, PERCENTAGE, EntityCategory, UnitOfTime
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, HAS_CERT, HAS_HOST, HAS_PORT, HAS_URL, LOCAL_INSTANCE
from .coordinator import UptimeKumaConfigEntry, UptimeKumaDataUpdateCoordinator
PARALLEL_UPDATES = 0
class UptimeKumaSensor(StrEnum):
"""Uptime Kuma sensors."""
CERT_DAYS_REMAINING = "cert_days_remaining"
RESPONSE_TIME = "response_time"
STATUS = "status"
TYPE = "type"
URL = "url"
HOSTNAME = "hostname"
PORT = "port"
UPTIME_RATIO_1D = "uptime_1d"
UPTIME_RATIO_30D = "uptime_30d"
UPTIME_RATIO_365D = "uptime_365d"
AVG_RESPONSE_TIME_1D = "avg_response_time_1d"
AVG_RESPONSE_TIME_30D = "avg_response_time_30d"
AVG_RESPONSE_TIME_365D = "avg_response_time_365d"
TAGS = "tags"
@dataclass(kw_only=True, frozen=True)
class UptimeKumaSensorEntityDescription(SensorEntityDescription):
"""Uptime Kuma sensor description."""
value_fn: Callable[[UptimeKumaMonitor], StateType]
create_entity: Callable[[MonitorType], bool]
attributes_fn: Callable[[UptimeKumaMonitor], Mapping[str, Any]] | None = None
SENSOR_DESCRIPTIONS: tuple[UptimeKumaSensorEntityDescription, ...] = (
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.CERT_DAYS_REMAINING,
translation_key=UptimeKumaSensor.CERT_DAYS_REMAINING,
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.DAYS,
value_fn=lambda m: m.monitor_cert_days_remaining,
create_entity=lambda t: t in HAS_CERT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.RESPONSE_TIME,
translation_key=UptimeKumaSensor.RESPONSE_TIME,
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.MILLISECONDS,
value_fn=(
lambda m: m.monitor_response_time if m.monitor_response_time > -1 else None
),
create_entity=lambda _: True,
state_class=SensorStateClass.MEASUREMENT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.STATUS,
translation_key=UptimeKumaSensor.STATUS,
device_class=SensorDeviceClass.ENUM,
options=[m.name.lower() for m in MonitorStatus],
value_fn=lambda m: m.monitor_status.name.lower(),
create_entity=lambda _: True,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.TYPE,
translation_key=UptimeKumaSensor.TYPE,
device_class=SensorDeviceClass.ENUM,
options=[m.name.lower() for m in MonitorType],
value_fn=lambda m: m.monitor_type.name.lower(),
entity_category=EntityCategory.DIAGNOSTIC,
create_entity=lambda _: True,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.URL,
translation_key=UptimeKumaSensor.URL,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda m: m.monitor_url,
create_entity=lambda t: t in HAS_URL,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.HOSTNAME,
translation_key=UptimeKumaSensor.HOSTNAME,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda m: m.monitor_hostname,
create_entity=lambda t: t in HAS_HOST,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.PORT,
translation_key=UptimeKumaSensor.PORT,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda m: m.monitor_port,
create_entity=lambda t: t in HAS_PORT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.PORT,
translation_key=UptimeKumaSensor.PORT,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda m: m.monitor_port,
create_entity=lambda t: t in HAS_PORT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.UPTIME_RATIO_1D,
translation_key=UptimeKumaSensor.UPTIME_RATIO_1D,
value_fn=lambda m: (
m.monitor_uptime_ratio_1d * 100
if m.monitor_uptime_ratio_1d is not None
else None
),
native_unit_of_measurement=PERCENTAGE,
suggested_display_precision=2,
create_entity=lambda t: True,
state_class=SensorStateClass.MEASUREMENT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.UPTIME_RATIO_30D,
translation_key=UptimeKumaSensor.UPTIME_RATIO_30D,
value_fn=lambda m: (
m.monitor_uptime_ratio_30d * 100
if m.monitor_uptime_ratio_30d is not None
else None
),
native_unit_of_measurement=PERCENTAGE,
suggested_display_precision=2,
create_entity=lambda t: True,
state_class=SensorStateClass.MEASUREMENT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.UPTIME_RATIO_365D,
translation_key=UptimeKumaSensor.UPTIME_RATIO_365D,
value_fn=lambda m: (
m.monitor_uptime_ratio_365d * 100
if m.monitor_uptime_ratio_365d is not None
else None
),
native_unit_of_measurement=PERCENTAGE,
suggested_display_precision=2,
create_entity=lambda t: True,
state_class=SensorStateClass.MEASUREMENT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.AVG_RESPONSE_TIME_1D,
translation_key=UptimeKumaSensor.AVG_RESPONSE_TIME_1D,
value_fn=lambda m: m.monitor_response_time_seconds_1d,
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.SECONDS,
suggested_unit_of_measurement=UnitOfTime.MILLISECONDS,
create_entity=lambda t: True,
state_class=SensorStateClass.MEASUREMENT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.AVG_RESPONSE_TIME_30D,
translation_key=UptimeKumaSensor.AVG_RESPONSE_TIME_30D,
value_fn=lambda m: m.monitor_response_time_seconds_30d,
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.SECONDS,
suggested_unit_of_measurement=UnitOfTime.MILLISECONDS,
create_entity=lambda t: True,
state_class=SensorStateClass.MEASUREMENT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.AVG_RESPONSE_TIME_365D,
translation_key=UptimeKumaSensor.AVG_RESPONSE_TIME_365D,
value_fn=lambda m: m.monitor_response_time_seconds_365d,
device_class=SensorDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.SECONDS,
suggested_unit_of_measurement=UnitOfTime.MILLISECONDS,
create_entity=lambda t: True,
state_class=SensorStateClass.MEASUREMENT,
),
UptimeKumaSensorEntityDescription(
key=UptimeKumaSensor.TAGS,
translation_key=UptimeKumaSensor.TAGS,
value_fn=lambda m: len(m.monitor_tags),
create_entity=lambda t: True,
entity_category=EntityCategory.DIAGNOSTIC,
attributes_fn=lambda m: {"tags": m.monitor_tags or None},
entity_registry_enabled_default=False,
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: UptimeKumaConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the sensor platform."""
coordinator = config_entry.runtime_data
monitor_added: set[str | int] = set()
@callback
def add_entities() -> None:
"""Add sensor entities."""
nonlocal monitor_added
if new_monitor := set(coordinator.data.keys()) - monitor_added:
async_add_entities(
UptimeKumaSensorEntity(coordinator, monitor, description)
for description in SENSOR_DESCRIPTIONS
for monitor in new_monitor
if description.create_entity(coordinator.data[monitor].monitor_type)
)
monitor_added |= new_monitor
coordinator.async_add_listener(add_entities)
add_entities()
class UptimeKumaSensorEntity(
CoordinatorEntity[UptimeKumaDataUpdateCoordinator], SensorEntity
):
"""An Uptime Kuma sensor entity."""
entity_description: UptimeKumaSensorEntityDescription
_attr_has_entity_name = True
def __init__(
self,
coordinator: UptimeKumaDataUpdateCoordinator,
monitor: str | int,
entity_description: UptimeKumaSensorEntityDescription,
) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
self.monitor = monitor
self.entity_description = entity_description
self._attr_unique_id = (
f"{coordinator.config_entry.entry_id}_{monitor!s}_{entity_description.key}"
)
url = URL(coordinator.config_entry.data[CONF_URL]) / "dashboard"
if url.host in LOCAL_INSTANCE:
configuration_url = None
elif isinstance(monitor, int):
configuration_url = url / str(monitor)
else:
configuration_url = url
self._attr_device_info = DeviceInfo(
entry_type=DeviceEntryType.SERVICE,
name=coordinator.data[monitor].monitor_name,
identifiers={(DOMAIN, f"{coordinator.config_entry.entry_id}_{monitor!s}")},
manufacturer="Uptime Kuma",
configuration_url=configuration_url,
sw_version=coordinator.api.version.version,
)
@property
def native_value(self) -> StateType:
"""Return the state of the sensor."""
return self.entity_description.value_fn(self.coordinator.data[self.monitor])
@property
def available(self) -> bool:
"""Return True if entity is available."""
return super().available and self.monitor in self.coordinator.data
@property
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return entity specific state attributes."""
if (fn := self.entity_description.attributes_fn) is not None:
return fn(self.coordinator.data[self.monitor])
return super().extra_state_attributes
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uptime_kuma/sensor.py",
"license": "Apache License 2.0",
"lines": 260,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/uptime_kuma/update.py | """Update platform for the Uptime Kuma integration."""
from __future__ import annotations
from enum import StrEnum
from yarl import URL
from homeassistant.components.update import (
UpdateEntity,
UpdateEntityDescription,
UpdateEntityFeature,
)
from homeassistant.const import CONF_URL, EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import UPTIME_KUMA_KEY
from .const import DOMAIN, LOCAL_INSTANCE
from .coordinator import (
UptimeKumaConfigEntry,
UptimeKumaDataUpdateCoordinator,
UptimeKumaSoftwareUpdateCoordinator,
)
PARALLEL_UPDATES = 0
class UptimeKumaUpdate(StrEnum):
"""Uptime Kuma update."""
UPDATE = "update"
async def async_setup_entry(
hass: HomeAssistant,
entry: UptimeKumaConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up update platform."""
coordinator = entry.runtime_data
async_add_entities(
[UptimeKumaUpdateEntity(coordinator, hass.data[UPTIME_KUMA_KEY])]
)
class UptimeKumaUpdateEntity(
CoordinatorEntity[UptimeKumaDataUpdateCoordinator], UpdateEntity
):
"""Representation of an update entity."""
entity_description = UpdateEntityDescription(
key=UptimeKumaUpdate.UPDATE,
translation_key=UptimeKumaUpdate.UPDATE,
entity_category=EntityCategory.DIAGNOSTIC,
)
_attr_supported_features = UpdateEntityFeature.RELEASE_NOTES
_attr_has_entity_name = True
def __init__(
self,
coordinator: UptimeKumaDataUpdateCoordinator,
update_coordinator: UptimeKumaSoftwareUpdateCoordinator,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self.update_checker = update_coordinator
url = URL(coordinator.config_entry.data[CONF_URL]) / "dashboard"
configuration_url = None if url.host in LOCAL_INSTANCE else url
self._attr_device_info = DeviceInfo(
entry_type=DeviceEntryType.SERVICE,
name=coordinator.config_entry.title,
identifiers={(DOMAIN, coordinator.config_entry.entry_id)},
manufacturer="Uptime Kuma",
configuration_url=configuration_url,
sw_version=coordinator.api.version.version,
)
self._attr_unique_id = (
f"{coordinator.config_entry.entry_id}_{self.entity_description.key}"
)
@property
def installed_version(self) -> str | None:
"""Current version."""
return self.coordinator.api.version.version
@property
def title(self) -> str | None:
"""Title of the release."""
return f"Uptime Kuma {self.update_checker.data.name}"
@property
def release_url(self) -> str | None:
"""URL to the full release notes."""
return self.update_checker.data.html_url
@property
def latest_version(self) -> str | None:
"""Latest version."""
return self.update_checker.data.tag_name
async def async_release_notes(self) -> str | None:
"""Return the release notes."""
return self.update_checker.data.body
async def async_added_to_hass(self) -> None:
"""When entity is added to hass.
Register extra update listener for the software update coordinator.
"""
await super().async_added_to_hass()
self.async_on_remove(
self.update_checker.async_add_listener(self._handle_coordinator_update)
)
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and self.update_checker.last_update_success
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/uptime_kuma/update.py",
"license": "Apache License 2.0",
"lines": 98,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/velux/binary_sensor.py | """Support for rain sensors built into some Velux windows."""
from __future__ import annotations
from datetime import timedelta
from pyvlx.exception import PyVLXException
from pyvlx.opening_device import OpeningDevice, Window
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import VeluxConfigEntry
from .const import LOGGER
from .entity import VeluxEntity
PARALLEL_UPDATES = 1
SCAN_INTERVAL = timedelta(minutes=5) # Use standard polling
async def async_setup_entry(
hass: HomeAssistant,
config_entry: VeluxConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up rain sensor(s) for Velux platform."""
pyvlx = config_entry.runtime_data
async_add_entities(
VeluxRainSensor(node, config_entry.entry_id)
for node in pyvlx.nodes
if isinstance(node, Window) and node.rain_sensor
)
class VeluxRainSensor(VeluxEntity, BinarySensorEntity):
"""Representation of a Velux rain sensor."""
node: Window
_attr_should_poll = True # the rain sensor / opening limitations needs polling unlike the rest of the Velux devices
_attr_entity_registry_enabled_default = False
_attr_device_class = BinarySensorDeviceClass.MOISTURE
_attr_translation_key = "rain_sensor"
_unavailable_logged = False
def __init__(self, node: OpeningDevice, config_entry_id: str) -> None:
"""Initialize VeluxRainSensor."""
super().__init__(node, config_entry_id)
self._attr_unique_id = f"{self._attr_unique_id}_rain_sensor"
async def async_update(self) -> None:
"""Fetch the latest state from the device."""
try:
limitation = await self.node.get_limitation()
except (OSError, PyVLXException) as err:
if not self._unavailable_logged:
LOGGER.warning(
"Rain sensor %s is unavailable: %s",
self.entity_id,
err,
)
self._unavailable_logged = True
self._attr_available = False
return
# Log when entity comes back online after being unavailable
if self._unavailable_logged:
LOGGER.info("Rain sensor %s is back online", self.entity_id)
self._unavailable_logged = False
self._attr_available = True
# Velux windows with rain sensors report an opening limitation when rain is detected.
# So far we've seen 89, 91, 93 (most cases) or 100 (Velux GPU). It probably makes sense to
# assume that any large enough limitation (we use >=89) means rain is detected.
# Documentation on this is non-existent AFAIK.
self._attr_is_on = limitation.min_value >= 89
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/velux/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/volvo/api.py | """API for Volvo bound to Home Assistant OAuth."""
import logging
from typing import cast
from aiohttp import ClientSession
from volvocarsapi.auth import AccessTokenManager
from homeassistant.helpers.config_entry_oauth2_flow import OAuth2Session
from homeassistant.helpers.redact import async_redact_data
_LOGGER = logging.getLogger(__name__)
_TO_REDACT = ["access_token", "id_token", "refresh_token"]
class VolvoAuth(AccessTokenManager):
"""Provide Volvo authentication tied to an OAuth2 based config entry."""
def __init__(self, websession: ClientSession, oauth_session: OAuth2Session) -> None:
"""Initialize Volvo auth."""
super().__init__(websession)
self._oauth_session = oauth_session
async def async_get_access_token(self) -> str:
"""Return a valid access token."""
current_access_token = self._oauth_session.token["access_token"]
current_refresh_token = self._oauth_session.token["refresh_token"]
await self._oauth_session.async_ensure_token_valid()
_LOGGER.debug(
"Token: %s", async_redact_data(self._oauth_session.token, _TO_REDACT)
)
_LOGGER.debug(
"Token changed: access %s, refresh %s",
current_access_token != self._oauth_session.token["access_token"],
current_refresh_token != self._oauth_session.token["refresh_token"],
)
return cast(str, self._oauth_session.token["access_token"])
class ConfigFlowVolvoAuth(AccessTokenManager):
"""Provide Volvo authentication before a ConfigEntry exists.
This implementation directly provides the token without supporting refresh.
"""
def __init__(self, websession: ClientSession, token: str) -> None:
"""Initialize ConfigFlowVolvoAuth."""
super().__init__(websession)
self._token = token
async def async_get_access_token(self) -> str:
"""Return the token for the Volvo API."""
return self._token
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/volvo/api.py",
"license": "Apache License 2.0",
"lines": 40,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/volvo/application_credentials.py | """Application credentials platform for the Volvo integration."""
from __future__ import annotations
from volvocarsapi.auth import AUTHORIZE_URL, TOKEN_URL
from volvocarsapi.scopes import ALL_SCOPES
from homeassistant.components.application_credentials import ClientCredential
from homeassistant.core import HomeAssistant
from homeassistant.helpers.config_entry_oauth2_flow import (
LocalOAuth2ImplementationWithPkce,
)
async def async_get_auth_implementation(
hass: HomeAssistant, auth_domain: str, credential: ClientCredential
) -> VolvoOAuth2Implementation:
"""Return auth implementation for a custom auth implementation."""
return VolvoOAuth2Implementation(
hass,
auth_domain,
credential.client_id,
AUTHORIZE_URL,
TOKEN_URL,
credential.client_secret,
)
class VolvoOAuth2Implementation(LocalOAuth2ImplementationWithPkce):
"""Volvo oauth2 implementation."""
@property
def extra_authorize_data(self) -> dict:
"""Extra data that needs to be appended to the authorize url."""
return super().extra_authorize_data | {
"scope": " ".join(ALL_SCOPES),
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/volvo/application_credentials.py",
"license": "Apache License 2.0",
"lines": 29,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/volvo/config_flow.py | """Config flow for Volvo."""
from __future__ import annotations
from collections.abc import Mapping
import logging
from typing import Any
import voluptuous as vol
from volvocarsapi.api import VolvoCarsApi
from volvocarsapi.models import VolvoApiException, VolvoCarsVehicle
from volvocarsapi.scopes import ALL_SCOPES
from homeassistant.config_entries import (
SOURCE_REAUTH,
SOURCE_RECONFIGURE,
ConfigFlowResult,
)
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_API_KEY, CONF_NAME, CONF_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.config_entry_oauth2_flow import AbstractOAuth2FlowHandler
from homeassistant.helpers.selector import (
SelectOptionDict,
SelectSelector,
SelectSelectorConfig,
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from .api import ConfigFlowVolvoAuth
from .const import CONF_VIN, DOMAIN, MANUFACTURER
_LOGGER = logging.getLogger(__name__)
def _create_volvo_cars_api(
hass: HomeAssistant, access_token: str, api_key: str
) -> VolvoCarsApi:
web_session = aiohttp_client.async_get_clientsession(hass)
auth = ConfigFlowVolvoAuth(web_session, access_token)
return VolvoCarsApi(web_session, auth, api_key)
class VolvoOAuth2FlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN):
"""Config flow to handle Volvo OAuth2 authentication."""
DOMAIN = DOMAIN
def __init__(self) -> None:
"""Initialize Volvo config flow."""
super().__init__()
self._vehicles: list[VolvoCarsVehicle] = []
self._config_data: dict = {}
@property
def extra_authorize_data(self) -> dict:
"""Extra data that needs to be appended to the authorize url."""
return super().extra_authorize_data | {
"scope": " ".join(ALL_SCOPES),
}
@property
def logger(self) -> logging.Logger:
"""Return logger."""
return _LOGGER
async def async_oauth_create_entry(self, data: dict) -> ConfigFlowResult:
"""Create an entry for the flow."""
self._config_data |= (self.init_data or {}) | data
return await self.async_step_api_key()
async def async_step_reauth(self, _: Mapping[str, Any]) -> ConfigFlowResult:
"""Perform reauth upon an API authentication error."""
return await self.async_step_reauth_confirm()
async def async_step_reconfigure(
self, data: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Reconfigure the entry."""
return await self.async_step_api_key()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauth dialog."""
if user_input is None:
return self.async_show_form(
step_id="reauth_confirm",
description_placeholders={CONF_NAME: self._get_reauth_entry().title},
)
return await self.async_step_user()
async def async_step_api_key(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the API key step."""
errors: dict[str, str] = {}
if user_input is not None:
api = _create_volvo_cars_api(
self.hass,
self._config_data[CONF_TOKEN][CONF_ACCESS_TOKEN],
user_input[CONF_API_KEY],
)
# Try to load all vehicles on the account. If it succeeds
# it means that the given API key is correct. The vehicle info
# is used in the VIN step.
try:
await self._async_load_vehicles(api)
except VolvoApiException:
_LOGGER.exception("Unable to retrieve vehicles")
errors["base"] = "cannot_load_vehicles"
if not errors:
self._config_data |= user_input
return await self.async_step_vin()
if user_input is None:
if self.source == SOURCE_REAUTH:
user_input = self._config_data
api = _create_volvo_cars_api(
self.hass,
self._config_data[CONF_TOKEN][CONF_ACCESS_TOKEN],
self._config_data[CONF_API_KEY],
)
# Test if the configured API key is still valid. If not, show this
# form. If it is, skip this step and go directly to the next step.
try:
await self._async_load_vehicles(api)
return await self.async_step_vin()
except VolvoApiException:
pass
elif self.source == SOURCE_RECONFIGURE:
user_input = self._config_data = dict(
self._get_reconfigure_entry().data
)
else:
user_input = {}
schema = self.add_suggested_values_to_schema(
vol.Schema(
{
vol.Required(CONF_API_KEY): TextSelector(
TextSelectorConfig(
type=TextSelectorType.TEXT, autocomplete="password"
)
),
}
),
{
CONF_API_KEY: user_input.get(CONF_API_KEY, ""),
},
)
return self.async_show_form(
step_id="api_key",
data_schema=schema,
errors=errors,
description_placeholders={
"volvo_dev_portal": "https://developer.volvocars.com/account/#your-api-applications"
},
)
async def async_step_vin(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the VIN step."""
errors: dict[str, str] = {}
if len(self._vehicles) == 1:
# If there is only one VIN, take that as value and
# immediately create the entry. No need to show
# the VIN step.
self._config_data[CONF_VIN] = self._vehicles[0].vin
return await self._async_create_or_update()
if self.source in (SOURCE_REAUTH, SOURCE_RECONFIGURE):
# Don't let users change the VIN. The entry should be
# recreated if they want to change the VIN.
return await self._async_create_or_update()
if user_input is not None:
self._config_data |= user_input
return await self._async_create_or_update()
if len(self._vehicles) == 0:
errors[CONF_VIN] = "no_vehicles"
schema = vol.Schema(
{
vol.Required(CONF_VIN): SelectSelector(
SelectSelectorConfig(
options=[
SelectOptionDict(
value=v.vin,
label=f"{v.description.model} ({v.vin})",
)
for v in self._vehicles
],
multiple=False,
)
),
},
)
return self.async_show_form(step_id="vin", data_schema=schema, errors=errors)
async def _async_create_or_update(self) -> ConfigFlowResult:
vin = self._config_data[CONF_VIN]
await self.async_set_unique_id(vin)
if self.source == SOURCE_REAUTH:
self._abort_if_unique_id_mismatch()
return self.async_update_reload_and_abort(
self._get_reauth_entry(),
data_updates=self._config_data,
)
if self.source == SOURCE_RECONFIGURE:
self._abort_if_unique_id_mismatch()
return self.async_update_reload_and_abort(
self._get_reconfigure_entry(),
data_updates=self._config_data,
reload_even_if_entry_is_unchanged=False,
)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"{MANUFACTURER} {vin}",
data=self._config_data,
)
async def _async_load_vehicles(self, api: VolvoCarsApi) -> None:
self._vehicles = []
vins = await api.async_get_vehicles()
for vin in vins:
vehicle = await api.async_get_vehicle_details(vin)
if vehicle:
self._vehicles.append(vehicle)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/volvo/config_flow.py",
"license": "Apache License 2.0",
"lines": 205,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/volvo/const.py | """Constants for the Volvo integration."""
from homeassistant.const import Platform
DOMAIN = "volvo"
PLATFORMS: list[Platform] = [
Platform.BINARY_SENSOR,
Platform.BUTTON,
Platform.DEVICE_TRACKER,
Platform.LOCK,
Platform.SENSOR,
]
API_NONE_VALUE = "UNSPECIFIED"
CONF_VIN = "vin"
DATA_BATTERY_CAPACITY = "battery_capacity_kwh"
MANUFACTURER = "Volvo"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/volvo/const.py",
"license": "Apache License 2.0",
"lines": 14,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/volvo/coordinator.py | """Volvo coordinators."""
from __future__ import annotations
from abc import abstractmethod
import asyncio
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from datetime import timedelta
import logging
from typing import Any, cast
from volvocarsapi.api import VolvoCarsApi
from volvocarsapi.models import (
VolvoApiException,
VolvoAuthException,
VolvoCarsApiBaseModel,
VolvoCarsValue,
VolvoCarsValueStatusField,
VolvoCarsVehicle,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DATA_BATTERY_CAPACITY, DOMAIN
VERY_SLOW_INTERVAL = 30
SLOW_INTERVAL = 15
MEDIUM_INTERVAL = 2
FAST_INTERVAL = 1
_LOGGER = logging.getLogger(__name__)
@dataclass
class VolvoContext:
"""Volvo context."""
api: VolvoCarsApi
vehicle: VolvoCarsVehicle
supported_commands: list[str]
@dataclass
class VolvoRuntimeData:
"""Volvo runtime data."""
interval_coordinators: tuple[VolvoBaseCoordinator, ...]
context: VolvoContext
type VolvoConfigEntry = ConfigEntry[VolvoRuntimeData]
type CoordinatorData = dict[str, VolvoCarsApiBaseModel | None]
def _is_invalid_api_field(field: VolvoCarsApiBaseModel | None) -> bool:
if not field:
return True
if isinstance(field, VolvoCarsValueStatusField) and field.status == "ERROR":
return True
return False
class VolvoBaseCoordinator(DataUpdateCoordinator[CoordinatorData]):
"""Volvo base interval coordinator."""
config_entry: VolvoConfigEntry
def __init__(
self,
hass: HomeAssistant,
entry: VolvoConfigEntry,
context: VolvoContext,
update_interval: timedelta,
name: str,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=entry,
name=name,
update_interval=update_interval,
)
self._api_calls: list[Callable[[], Coroutine[Any, Any, Any]]] = []
self.context = context
async def _async_setup(self) -> None:
try:
self._api_calls = await self._async_determine_api_calls()
except VolvoAuthException as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="unauthorized",
translation_placeholders={"message": err.message},
) from err
except VolvoApiException as err:
raise ConfigEntryNotReady from err
if not self._api_calls:
self.update_interval = None
async def _async_update_data(self) -> CoordinatorData:
"""Fetch data from API."""
data: CoordinatorData = {}
if not self._api_calls:
return data
valid = False
exception: Exception | None = None
results = await asyncio.gather(
*(call() for call in self._api_calls), return_exceptions=True
)
for result in results:
if isinstance(result, VolvoAuthException):
# If one result is a VolvoAuthException, then probably all requests
# will fail. In this case we can cancel everything to
# reauthenticate.
#
# Raising ConfigEntryAuthFailed will cancel future updates
# and start a config flow with SOURCE_REAUTH (async_step_reauth)
_LOGGER.debug(
"%s - Authentication failed. %s",
self.config_entry.entry_id,
result.message,
)
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="unauthorized",
translation_placeholders={"message": result.message},
) from result
if isinstance(result, VolvoApiException):
# Maybe it's just one call that fails. Log the error and
# continue processing the other calls.
_LOGGER.debug(
"%s - Error during data update: %s",
self.config_entry.entry_id,
result.message,
)
exception = exception or result
continue
if isinstance(result, Exception):
# Something bad happened, raise immediately.
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_failed",
) from result
api_data = cast(CoordinatorData, result)
data |= {
key: field
for key, field in api_data.items()
if not _is_invalid_api_field(field)
}
valid = True
# Raise an error if not a single API call succeeded
if not valid:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_failed",
) from exception
return data
def get_api_field(self, api_field: str | None) -> VolvoCarsApiBaseModel | None:
"""Get the API field based on the entity description."""
return self.data.get(api_field) if api_field else None
@abstractmethod
async def _async_determine_api_calls(
self,
) -> list[Callable[[], Coroutine[Any, Any, Any]]]:
raise NotImplementedError
class VolvoVerySlowIntervalCoordinator(VolvoBaseCoordinator):
"""Volvo coordinator with very slow update rate."""
def __init__(
self,
hass: HomeAssistant,
entry: VolvoConfigEntry,
context: VolvoContext,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
entry,
context,
timedelta(minutes=VERY_SLOW_INTERVAL),
"Volvo very slow interval coordinator",
)
async def _async_determine_api_calls(
self,
) -> list[Callable[[], Coroutine[Any, Any, Any]]]:
api = self.context.api
return [
api.async_get_command_accessibility,
api.async_get_diagnostics,
api.async_get_tyre_states,
api.async_get_warnings,
]
async def _async_update_data(self) -> CoordinatorData:
data = await super()._async_update_data()
# Add static values
if self.context.vehicle.has_battery_engine():
data[DATA_BATTERY_CAPACITY] = VolvoCarsValue.from_dict(
{
"value": self.context.vehicle.battery_capacity_kwh,
}
)
return data
class VolvoSlowIntervalCoordinator(VolvoBaseCoordinator):
"""Volvo coordinator with slow update rate."""
def __init__(
self,
hass: HomeAssistant,
entry: VolvoConfigEntry,
context: VolvoContext,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
entry,
context,
timedelta(minutes=SLOW_INTERVAL),
"Volvo slow interval coordinator",
)
async def _async_determine_api_calls(
self,
) -> list[Callable[[], Coroutine[Any, Any, Any]]]:
api = self.context.api
api_calls: list[Any] = [
api.async_get_brakes_status,
api.async_get_engine_warnings,
api.async_get_odometer,
]
location = await api.async_get_location()
if location.get("location") is not None:
api_calls.append(api.async_get_location)
return api_calls
class VolvoMediumIntervalCoordinator(VolvoBaseCoordinator):
"""Volvo coordinator with medium update rate."""
def __init__(
self,
hass: HomeAssistant,
entry: VolvoConfigEntry,
context: VolvoContext,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
entry,
context,
timedelta(minutes=MEDIUM_INTERVAL),
"Volvo medium interval coordinator",
)
self._supported_capabilities: list[str] = []
async def _async_determine_api_calls(
self,
) -> list[Callable[[], Coroutine[Any, Any, Any]]]:
api = self.context.api
vehicle = self.context.vehicle
api_calls: list[Any] = [
api.async_get_engine_status,
api.async_get_statistics,
]
if vehicle.has_battery_engine():
capabilities = await api.async_get_energy_capabilities()
if capabilities.get("isSupported", False):
def _normalize_key(key: str) -> str:
return "chargingStatus" if key == "chargingSystemStatus" else key
self._supported_capabilities = [
_normalize_key(key)
for key, value in capabilities.items()
if isinstance(value, dict) and value.get("isSupported", False)
]
api_calls.append(self._async_get_energy_state)
if self.context.vehicle.has_combustion_engine():
api_calls.append(api.async_get_fuel_status)
return api_calls
async def _async_get_energy_state(
self,
) -> dict[str, VolvoCarsValueStatusField | None]:
def _mark_ok(
field: VolvoCarsValueStatusField | None,
) -> VolvoCarsValueStatusField | None:
if field:
field.status = "OK"
return field
energy_state = await self.context.api.async_get_energy_state()
return {
key: _mark_ok(value)
for key, value in energy_state.items()
if key in self._supported_capabilities
}
class VolvoFastIntervalCoordinator(VolvoBaseCoordinator):
"""Volvo coordinator with fast update rate."""
def __init__(
self,
hass: HomeAssistant,
entry: VolvoConfigEntry,
context: VolvoContext,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
entry,
context,
timedelta(minutes=FAST_INTERVAL),
"Volvo fast interval coordinator",
)
async def _async_determine_api_calls(
self,
) -> list[Callable[[], Coroutine[Any, Any, Any]]]:
api = self.context.api
return [
api.async_get_doors_status,
api.async_get_window_states,
]
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/volvo/coordinator.py",
"license": "Apache License 2.0",
"lines": 291,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/volvo/entity.py | """Volvo entity classes."""
from abc import abstractmethod
from dataclasses import dataclass
from volvocarsapi.models import VolvoCarsApiBaseModel
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.core import callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import Entity, EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, MANUFACTURER
from .coordinator import VolvoBaseCoordinator, VolvoConfigEntry
def get_unique_id(vin: str, key: str) -> str:
"""Get the unique ID."""
return f"{vin}_{key}".lower()
def value_to_translation_key(value: str) -> str:
"""Make sure the translation key is valid."""
return value.lower()
@dataclass(frozen=True, kw_only=True)
class VolvoEntityDescription(EntityDescription):
"""Describes a Volvo entity."""
api_field: str | None = None
class VolvoBaseEntity(Entity):
"""Volvo base entity."""
_attr_has_entity_name = True
def __init__(
self,
entry: VolvoConfigEntry,
description: VolvoEntityDescription,
) -> None:
"""Initialize entity."""
self.entity_description: VolvoEntityDescription = description
self.entry = entry
if description.device_class != SensorDeviceClass.BATTERY:
self._attr_translation_key = description.key
vehicle = entry.runtime_data.context.vehicle
self._attr_unique_id = get_unique_id(vehicle.vin, description.key)
model = (
f"{vehicle.description.model} ({vehicle.model_year})"
if vehicle.fuel_type == "NONE"
else f"{vehicle.description.model} {vehicle.fuel_type} ({vehicle.model_year})"
)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, vehicle.vin)},
manufacturer=MANUFACTURER,
model=model,
model_id=f"{vehicle.description.model} ({vehicle.model_year})",
name=f"{MANUFACTURER} {vehicle.description.model}",
serial_number=vehicle.vin,
)
class VolvoEntity(CoordinatorEntity[VolvoBaseCoordinator], VolvoBaseEntity):
"""Volvo base coordinator entity."""
def __init__(
self,
coordinator: VolvoBaseCoordinator,
description: VolvoEntityDescription,
) -> None:
"""Initialize entity."""
CoordinatorEntity.__init__(self, coordinator)
VolvoBaseEntity.__init__(self, coordinator.config_entry, description)
self._update_state(coordinator.get_api_field(description.api_field))
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
api_field = self.coordinator.get_api_field(self.entity_description.api_field)
self._update_state(api_field)
super()._handle_coordinator_update()
@property
def available(self) -> bool:
"""Return if entity is available."""
if self.entity_description.api_field:
api_field = self.coordinator.get_api_field(
self.entity_description.api_field
)
return super().available and api_field is not None
return super().available
@abstractmethod
def _update_state(self, api_field: VolvoCarsApiBaseModel | None) -> None:
"""Update the state of the entity."""
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/volvo/entity.py",
"license": "Apache License 2.0",
"lines": 78,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/volvo/sensor.py | """Volvo sensors."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
import logging
from typing import cast
from volvocarsapi.models import (
VolvoCarsApiBaseModel,
VolvoCarsLocation,
VolvoCarsValue,
VolvoCarsValueField,
VolvoCarsValueStatusField,
)
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import (
DEGREE,
PERCENTAGE,
EntityCategory,
UnitOfElectricCurrent,
UnitOfEnergy,
UnitOfEnergyDistance,
UnitOfLength,
UnitOfPower,
UnitOfSpeed,
UnitOfTime,
UnitOfVolume,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .const import API_NONE_VALUE, DATA_BATTERY_CAPACITY
from .coordinator import VolvoConfigEntry
from .entity import VolvoEntity, VolvoEntityDescription, value_to_translation_key
PARALLEL_UPDATES = 0
_LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True, kw_only=True)
class VolvoSensorDescription(VolvoEntityDescription, SensorEntityDescription):
"""Describes a Volvo sensor entity."""
value_fn: Callable[[VolvoCarsApiBaseModel], StateType] | None = None
def _availability_status(field: VolvoCarsApiBaseModel) -> str:
reason = field.get("unavailable_reason")
if reason:
return str(reason)
if isinstance(field, VolvoCarsValue):
return str(field.value)
return ""
def _calculate_time_to_service(field: VolvoCarsApiBaseModel) -> int:
if not isinstance(field, VolvoCarsValueField):
return 0
value = int(field.value)
# Always express value in days
return value * 30 if field.unit == "months" else value
def _charging_power_value(field: VolvoCarsApiBaseModel) -> int:
return (
field.value
if isinstance(field, VolvoCarsValueStatusField) and isinstance(field.value, int)
else 0
)
def _charging_power_status_value(field: VolvoCarsApiBaseModel) -> str | None:
status = cast(str, field.value) if isinstance(field, VolvoCarsValue) else ""
if status.lower() in _CHARGING_POWER_STATUS_OPTIONS:
return status
_LOGGER.warning(
"Unknown value '%s' for charging_power_status. Please report it at https://github.com/home-assistant/core/issues/new?template=bug_report.yml",
status,
)
return None
def _direction_value(field: VolvoCarsApiBaseModel) -> str | None:
return field.properties.heading if isinstance(field, VolvoCarsLocation) else None
_CHARGING_POWER_STATUS_OPTIONS = [
"fault",
"power_available_but_not_activated",
"providing_power",
"no_power_available",
]
_DESCRIPTIONS: tuple[VolvoSensorDescription, ...] = (
# command-accessibility endpoint
VolvoSensorDescription(
key="availability",
api_field="availabilityStatus",
device_class=SensorDeviceClass.ENUM,
options=[
"available",
"car_in_use",
"no_internet",
"ota_installation_in_progress",
"power_saving_mode",
],
value_fn=_availability_status,
entity_category=EntityCategory.DIAGNOSTIC,
),
# statistics endpoint
VolvoSensorDescription(
key="average_energy_consumption",
api_field="averageEnergyConsumption",
native_unit_of_measurement=UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
),
# statistics endpoint
VolvoSensorDescription(
key="average_energy_consumption_automatic",
api_field="averageEnergyConsumptionAutomatic",
native_unit_of_measurement=UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
),
# statistics endpoint
VolvoSensorDescription(
key="average_energy_consumption_charge",
api_field="averageEnergyConsumptionSinceCharge",
native_unit_of_measurement=UnitOfEnergyDistance.KILO_WATT_HOUR_PER_100_KM,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
),
# statistics endpoint
VolvoSensorDescription(
key="average_fuel_consumption",
api_field="averageFuelConsumption",
native_unit_of_measurement="L/100 km",
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
),
# statistics endpoint
VolvoSensorDescription(
key="average_fuel_consumption_automatic",
api_field="averageFuelConsumptionAutomatic",
native_unit_of_measurement="L/100 km",
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
),
# statistics endpoint
VolvoSensorDescription(
key="average_speed",
api_field="averageSpeed",
native_unit_of_measurement=UnitOfSpeed.KILOMETERS_PER_HOUR,
device_class=SensorDeviceClass.SPEED,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=0,
),
# statistics endpoint
VolvoSensorDescription(
key="average_speed_automatic",
api_field="averageSpeedAutomatic",
native_unit_of_measurement=UnitOfSpeed.KILOMETERS_PER_HOUR,
device_class=SensorDeviceClass.SPEED,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=0,
),
# vehicle endpoint
VolvoSensorDescription(
key="battery_capacity",
api_field=DATA_BATTERY_CAPACITY,
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
device_class=SensorDeviceClass.ENERGY_STORAGE,
entity_category=EntityCategory.DIAGNOSTIC,
),
# fuel & energy state endpoint
VolvoSensorDescription(
key="battery_charge_level",
api_field="batteryChargeLevel",
native_unit_of_measurement=PERCENTAGE,
device_class=SensorDeviceClass.BATTERY,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=0,
),
# energy state endpoint
VolvoSensorDescription(
key="charger_connection_status",
api_field="chargerConnectionStatus",
device_class=SensorDeviceClass.ENUM,
options=[
"connected",
"disconnected",
"fault",
],
),
# energy state endpoint
VolvoSensorDescription(
key="charging_current_limit",
api_field="chargingCurrentLimit",
device_class=SensorDeviceClass.CURRENT,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=UnitOfElectricCurrent.AMPERE,
),
# energy state endpoint
VolvoSensorDescription(
key="charging_power",
api_field="chargingPower",
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=UnitOfPower.WATT,
value_fn=_charging_power_value,
),
# energy state endpoint
VolvoSensorDescription(
key="charging_power_status",
api_field="chargerPowerStatus",
device_class=SensorDeviceClass.ENUM,
options=_CHARGING_POWER_STATUS_OPTIONS,
value_fn=_charging_power_status_value,
),
# energy state endpoint
VolvoSensorDescription(
key="charging_status",
api_field="chargingStatus",
device_class=SensorDeviceClass.ENUM,
options=[
"charging",
"discharging",
"done",
"error",
"idle",
"scheduled",
],
),
# energy state endpoint
VolvoSensorDescription(
key="charging_type",
api_field="chargingType",
device_class=SensorDeviceClass.ENUM,
options=[
"ac",
"dc",
"none",
],
),
# location endpoint
VolvoSensorDescription(
key="direction",
api_field="location",
native_unit_of_measurement=DEGREE,
suggested_display_precision=0,
value_fn=_direction_value,
),
# statistics endpoint
# We're not using `electricRange` from the energy state endpoint because
# the official app seems to use `distanceToEmptyBattery`.
# In issue #150213, a user described the behavior as follows:
# - For a `distanceToEmptyBattery` of 250km, the `electricRange` was 150mi
# - For a `distanceToEmptyBattery` of 260km, the `electricRange` was 160mi
VolvoSensorDescription(
key="distance_to_empty_battery",
api_field="distanceToEmptyBattery",
native_unit_of_measurement=UnitOfLength.KILOMETERS,
device_class=SensorDeviceClass.DISTANCE,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=0,
),
# statistics endpoint
VolvoSensorDescription(
key="distance_to_empty_tank",
api_field="distanceToEmptyTank",
native_unit_of_measurement=UnitOfLength.KILOMETERS,
device_class=SensorDeviceClass.DISTANCE,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=0,
),
# diagnostics endpoint
VolvoSensorDescription(
key="distance_to_service",
api_field="distanceToService",
native_unit_of_measurement=UnitOfLength.KILOMETERS,
device_class=SensorDeviceClass.DISTANCE,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=0,
),
# diagnostics endpoint
VolvoSensorDescription(
key="engine_time_to_service",
api_field="engineHoursToService",
native_unit_of_measurement=UnitOfTime.HOURS,
device_class=SensorDeviceClass.DURATION,
state_class=SensorStateClass.MEASUREMENT,
),
# energy state endpoint
VolvoSensorDescription(
key="estimated_charging_time",
api_field="estimatedChargingTimeToTargetBatteryChargeLevel",
native_unit_of_measurement=UnitOfTime.MINUTES,
device_class=SensorDeviceClass.DURATION,
state_class=SensorStateClass.MEASUREMENT,
),
# fuel endpoint
VolvoSensorDescription(
key="fuel_amount",
api_field="fuelAmount",
native_unit_of_measurement=UnitOfVolume.LITERS,
device_class=SensorDeviceClass.VOLUME_STORAGE,
state_class=SensorStateClass.MEASUREMENT,
suggested_display_precision=1,
),
# odometer endpoint
VolvoSensorDescription(
key="odometer",
api_field="odometer",
native_unit_of_measurement=UnitOfLength.KILOMETERS,
device_class=SensorDeviceClass.DISTANCE,
state_class=SensorStateClass.TOTAL_INCREASING,
suggested_display_precision=1,
),
# diagnostics endpoint
VolvoSensorDescription(
key="service_warning",
api_field="serviceWarning",
device_class=SensorDeviceClass.ENUM,
options=[
"distance_driven_almost_time_for_service",
"distance_driven_overdue_for_service",
"distance_driven_time_for_service",
"engine_hours_almost_time_for_service",
"engine_hours_overdue_for_service",
"engine_hours_time_for_service",
"no_warning",
"regular_maintenance_almost_time_for_service",
"regular_maintenance_overdue_for_service",
"regular_maintenance_time_for_service",
"unknown_warning",
],
),
# energy state endpoint
VolvoSensorDescription(
key="target_battery_charge_level",
api_field="targetBatteryChargeLevel",
native_unit_of_measurement=PERCENTAGE,
suggested_display_precision=0,
),
# diagnostics endpoint
VolvoSensorDescription(
key="time_to_service",
api_field="timeToService",
native_unit_of_measurement=UnitOfTime.DAYS,
device_class=SensorDeviceClass.DURATION,
state_class=SensorStateClass.MEASUREMENT,
value_fn=_calculate_time_to_service,
),
# statistics endpoint
VolvoSensorDescription(
key="trip_meter_automatic",
api_field="tripMeterAutomatic",
native_unit_of_measurement=UnitOfLength.KILOMETERS,
device_class=SensorDeviceClass.DISTANCE,
state_class=SensorStateClass.TOTAL_INCREASING,
suggested_display_precision=0,
),
# statistics endpoint
VolvoSensorDescription(
key="trip_meter_manual",
api_field="tripMeterManual",
native_unit_of_measurement=UnitOfLength.KILOMETERS,
device_class=SensorDeviceClass.DISTANCE,
state_class=SensorStateClass.TOTAL_INCREASING,
suggested_display_precision=0,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: VolvoConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up sensors."""
entities: dict[str, VolvoSensor] = {}
coordinators = entry.runtime_data.interval_coordinators
for coordinator in coordinators:
for description in _DESCRIPTIONS:
if description.key in entities:
continue
if description.api_field in coordinator.data:
entities[description.key] = VolvoSensor(coordinator, description)
async_add_entities(entities.values())
class VolvoSensor(VolvoEntity, SensorEntity):
"""Volvo sensor."""
entity_description: VolvoSensorDescription
def _update_state(self, api_field: VolvoCarsApiBaseModel | None) -> None:
"""Update the state of the entity."""
if api_field is None:
self._attr_native_value = None
return
native_value = None
if self.entity_description.value_fn:
native_value = self.entity_description.value_fn(api_field)
elif isinstance(api_field, VolvoCarsValue):
native_value = api_field.value
if self.device_class == SensorDeviceClass.ENUM and native_value:
# Entities having an "unknown" value should report None as the state
native_value = str(native_value)
native_value = (
value_to_translation_key(native_value)
if native_value.upper() != API_NONE_VALUE
else None
)
self._attr_native_value = native_value
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/volvo/sensor.py",
"license": "Apache License 2.0",
"lines": 397,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/wiz/fan.py | """WiZ integration fan platform."""
from __future__ import annotations
import math
from typing import Any, ClassVar
from pywizlight.bulblibrary import BulbType, Features
from homeassistant.components.fan import (
DIRECTION_FORWARD,
DIRECTION_REVERSE,
FanEntity,
FanEntityFeature,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity import ToggleEntity
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.percentage import (
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from . import WizConfigEntry
from .entity import WizEntity
from .models import WizData
PRESET_MODE_BREEZE = "breeze"
async def async_setup_entry(
hass: HomeAssistant,
entry: WizConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the WiZ Platform from config_flow."""
if entry.runtime_data.bulb.bulbtype.features.fan:
async_add_entities([WizFanEntity(entry.runtime_data, entry.title)])
class WizFanEntity(WizEntity, FanEntity):
"""Representation of WiZ Light bulb."""
_attr_name = None
# We want the implementation of is_on to be the same as in ToggleEntity,
# but it is being overridden in FanEntity, so we need to restore it here.
is_on: ClassVar = ToggleEntity.is_on
def __init__(self, wiz_data: WizData, name: str) -> None:
"""Initialize a WiZ fan."""
super().__init__(wiz_data, name)
bulb_type: BulbType = self._device.bulbtype
features: Features = bulb_type.features
supported_features = (
FanEntityFeature.TURN_ON
| FanEntityFeature.TURN_OFF
| FanEntityFeature.SET_SPEED
)
if features.fan_reverse:
supported_features |= FanEntityFeature.DIRECTION
if features.fan_breeze_mode:
supported_features |= FanEntityFeature.PRESET_MODE
self._attr_preset_modes = [PRESET_MODE_BREEZE]
self._attr_supported_features = supported_features
self._attr_speed_count = bulb_type.fan_speed_range
self._async_update_attrs()
@callback
def _async_update_attrs(self) -> None:
"""Handle updating _attr values."""
state = self._device.state
self._attr_is_on = state.get_fan_state() > 0
self._attr_percentage = ranged_value_to_percentage(
(1, self.speed_count), state.get_fan_speed()
)
if FanEntityFeature.PRESET_MODE in self.supported_features:
fan_mode = state.get_fan_mode()
self._attr_preset_mode = PRESET_MODE_BREEZE if fan_mode == 2 else None
if FanEntityFeature.DIRECTION in self.supported_features:
fan_reverse = state.get_fan_reverse()
self._attr_current_direction = None
if fan_reverse == 0:
self._attr_current_direction = DIRECTION_FORWARD
elif fan_reverse == 1:
self._attr_current_direction = DIRECTION_REVERSE
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the fan."""
# preset_mode == PRESET_MODE_BREEZE
await self._device.fan_set_state(mode=2)
await self.coordinator.async_request_refresh()
async def async_set_percentage(self, percentage: int) -> None:
"""Set the speed percentage of the fan."""
if percentage == 0:
await self.async_turn_off()
return
speed = math.ceil(percentage_to_ranged_value((1, self.speed_count), percentage))
await self._device.fan_set_state(mode=1, speed=speed)
await self.coordinator.async_request_refresh()
async def async_turn_on(
self,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn on the fan."""
mode: int | None = None
speed: int | None = None
if preset_mode is not None:
self._valid_preset_mode_or_raise(preset_mode)
if preset_mode == PRESET_MODE_BREEZE:
mode = 2
if percentage is not None:
speed = math.ceil(
percentage_to_ranged_value((1, self.speed_count), percentage)
)
if mode is None:
mode = 1
await self._device.fan_turn_on(mode=mode, speed=speed)
await self.coordinator.async_request_refresh()
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the fan."""
await self._device.fan_turn_off(**kwargs)
await self.coordinator.async_request_refresh()
async def async_set_direction(self, direction: str) -> None:
"""Set the direction of the fan."""
reverse = 1 if direction == DIRECTION_REVERSE else 0
await self._device.fan_set_state(reverse=reverse)
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/wiz/fan.py",
"license": "Apache License 2.0",
"lines": 115,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/zone/condition.py | """Offer zone automation rules."""
from __future__ import annotations
from typing import Any, Unpack, cast
import voluptuous as vol
from homeassistant.const import (
ATTR_GPS_ACCURACY,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_ENTITY_ID,
CONF_OPTIONS,
CONF_ZONE,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant, State
from homeassistant.exceptions import ConditionErrorContainer, ConditionErrorMessage
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.automation import move_top_level_schema_fields_to_options
from homeassistant.helpers.condition import (
Condition,
ConditionChecker,
ConditionCheckParams,
ConditionConfig,
)
from homeassistant.helpers.typing import ConfigType
from . import in_zone
_OPTIONS_SCHEMA_DICT: dict[vol.Marker, Any] = {
vol.Required(CONF_ENTITY_ID): cv.entity_ids,
vol.Required("zone"): cv.entity_ids,
}
_CONDITION_SCHEMA = vol.Schema({CONF_OPTIONS: _OPTIONS_SCHEMA_DICT})
def zone(
hass: HomeAssistant,
zone_ent: str | State | None,
entity: str | State | None,
) -> bool:
"""Test if zone-condition matches.
Async friendly.
"""
if zone_ent is None:
raise ConditionErrorMessage("zone", "no zone specified")
if isinstance(zone_ent, str):
zone_ent_id = zone_ent
if (zone_ent := hass.states.get(zone_ent)) is None:
raise ConditionErrorMessage("zone", f"unknown zone {zone_ent_id}")
if entity is None:
raise ConditionErrorMessage("zone", "no entity specified")
if isinstance(entity, str):
entity_id = entity
if (entity := hass.states.get(entity)) is None:
raise ConditionErrorMessage("zone", f"unknown entity {entity_id}")
else:
entity_id = entity.entity_id
if entity.state in (
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
return False
latitude = entity.attributes.get(ATTR_LATITUDE)
longitude = entity.attributes.get(ATTR_LONGITUDE)
if latitude is None:
raise ConditionErrorMessage(
"zone", f"entity {entity_id} has no 'latitude' attribute"
)
if longitude is None:
raise ConditionErrorMessage(
"zone", f"entity {entity_id} has no 'longitude' attribute"
)
return in_zone(
zone_ent, latitude, longitude, entity.attributes.get(ATTR_GPS_ACCURACY, 0)
)
class ZoneCondition(Condition):
"""Zone condition."""
_options: dict[str, Any]
@classmethod
async def async_validate_complete_config(
cls, hass: HomeAssistant, complete_config: ConfigType
) -> ConfigType:
"""Validate complete config."""
complete_config = move_top_level_schema_fields_to_options(
complete_config, _OPTIONS_SCHEMA_DICT
)
return await super().async_validate_complete_config(hass, complete_config)
@classmethod
async def async_validate_config(
cls, hass: HomeAssistant, config: ConfigType
) -> ConfigType:
"""Validate config."""
return cast(ConfigType, _CONDITION_SCHEMA(config))
def __init__(self, hass: HomeAssistant, config: ConditionConfig) -> None:
"""Initialize condition."""
super().__init__(hass, config)
assert config.options is not None
self._options = config.options
async def async_get_checker(self) -> ConditionChecker:
"""Wrap action method with zone based condition."""
entity_ids = self._options.get(CONF_ENTITY_ID, [])
zone_entity_ids = self._options.get(CONF_ZONE, [])
def if_in_zone(**kwargs: Unpack[ConditionCheckParams]) -> bool:
"""Test if condition."""
errors = []
all_ok = True
for entity_id in entity_ids:
entity_ok = False
for zone_entity_id in zone_entity_ids:
try:
if zone(self._hass, zone_entity_id, entity_id):
entity_ok = True
except ConditionErrorMessage as ex:
errors.append(
ConditionErrorMessage(
"zone",
(
f"error matching {entity_id} with {zone_entity_id}:"
f" {ex.message}"
),
)
)
if not entity_ok:
all_ok = False
# Raise the errors only if no definitive result was found
if errors and not all_ok:
raise ConditionErrorContainer("zone", errors=errors)
return all_ok
return if_in_zone
CONDITIONS: dict[str, type[Condition]] = {
"_": ZoneCondition,
}
async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]:
"""Return the sun conditions."""
return CONDITIONS
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zone/condition.py",
"license": "Apache License 2.0",
"lines": 131,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/zwave_js/models.py | """Provide models for the Z-Wave integration."""
from __future__ import annotations
from collections.abc import Iterable
from dataclasses import asdict, dataclass, field
from enum import StrEnum
from typing import TYPE_CHECKING, Any
from awesomeversion import AwesomeVersion
from zwave_js_server.const import LogLevel
from zwave_js_server.model.node import Node as ZwaveNode
from zwave_js_server.model.value import (
ConfigurationValue as ZwaveConfigurationValue,
Value as ZwaveValue,
get_value_id_str,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory, Platform
from homeassistant.helpers.entity import EntityDescription
if TYPE_CHECKING:
from _typeshed import DataclassInstance
from zwave_js_server.client import Client as ZwaveClient
from . import DriverEvents
@dataclass
class ZwaveJSData:
"""Data for zwave_js runtime data."""
client: ZwaveClient
driver_events: DriverEvents
old_server_log_level: LogLevel | None = None
type ZwaveJSConfigEntry = ConfigEntry[ZwaveJSData]
@dataclass
class ZwaveValueID:
"""Class to represent a value ID."""
property_: str | int
command_class: int
endpoint: int | None = None
property_key: str | int | None = None
class ValueType(StrEnum):
"""Enum with all value types."""
ANY = "any"
BOOLEAN = "boolean"
NUMBER = "number"
STRING = "string"
class DataclassMustHaveAtLeastOne:
"""A dataclass that must have at least one input parameter that is not None."""
def __post_init__(self: DataclassInstance) -> None:
"""Post dataclass initialization."""
if all(val is None for val in asdict(self).values()):
raise ValueError("At least one input parameter must not be None")
@dataclass
class FirmwareVersionRange(DataclassMustHaveAtLeastOne):
"""Firmware version range dictionary."""
min: str | None = None
max: str | None = None
min_ver: AwesomeVersion | None = field(default=None, init=False)
max_ver: AwesomeVersion | None = field(default=None, init=False)
def __post_init__(self) -> None:
"""Post dataclass initialization."""
super().__post_init__()
if self.min:
self.min_ver = AwesomeVersion(self.min)
if self.max:
self.max_ver = AwesomeVersion(self.max)
@dataclass
class PlatformZwaveDiscoveryInfo:
"""Info discovered from (primary) ZWave Value to create entity."""
# node to which the value(s) belongs
node: ZwaveNode
# the value object itself for primary value
primary_value: ZwaveValue
# bool to specify whether state is assumed and events should be fired on value
# update
assumed_state: bool
# the home assistant platform for which an entity should be created
platform: Platform
# additional values that need to be watched by entity
additional_value_ids_to_watch: set[str]
@dataclass
class ZwaveDiscoveryInfo(PlatformZwaveDiscoveryInfo):
"""Info discovered from (primary) ZWave Value to create entity."""
# helper data to use in platform setup
platform_data: Any = None
# data template to use in platform logic
platform_data_template: BaseDiscoverySchemaDataTemplate | None = None
# hint for the platform about this discovered entity
platform_hint: str | None = ""
# bool to specify whether entity should be enabled by default
entity_registry_enabled_default: bool = True
# the entity category for the discovered entity
entity_category: EntityCategory | None = None
@dataclass
class ZWaveValueDiscoverySchema(DataclassMustHaveAtLeastOne):
"""Z-Wave Value discovery schema.
The Z-Wave Value must match these conditions.
Use the Z-Wave specifications to find out the values for these parameters:
https://github.com/zwave-js/specs/tree/master
"""
# [optional] the value's command class must match ANY of these values
command_class: set[int] | None = None
# [optional] the value's endpoint must match ANY of these values
endpoint: set[int] | None = None
# [optional] the value's property must match ANY of these values
property: set[str | int] | None = None
# [optional] the value's property name must match ANY of these values
property_name: set[str] | None = None
# [optional] the value's property key must match ANY of these values
property_key: set[str | int | None] | None = None
# [optional] the value's property key must NOT match ANY of these values
not_property_key: set[str | int | None] | None = None
# [optional] the value's metadata_type must match ANY of these values
type: set[str] | None = None
# [optional] the value's metadata_readable must match this value
readable: bool | None = None
# [optional] the value's metadata_writeable must match this value
writeable: bool | None = None
# [optional] the value's states map must include ANY of these key/value pairs
any_available_states: set[tuple[int, str]] | None = None
# [optional] the value's states map must include ANY of these keys
any_available_states_keys: set[int] | None = None
# [optional] the value's cc specific map must include ANY of these key/value pairs
any_available_cc_specific: set[tuple[Any, Any]] | None = None
# [optional] the value's value must match this value
value: Any | None = None
# [optional] the value's metadata_stateful must match this value
stateful: bool | None = None
@dataclass
class NewZWaveDiscoverySchema:
"""Z-Wave discovery schema.
The Z-Wave node and it's (primary) value for an entity must match these conditions.
Use the Z-Wave specifications to find out the values for these parameters:
https://github.com/zwave-js/node-zwave-js/tree/master/specs
"""
# specify the hass platform for which this scheme applies (e.g. light, sensor)
platform: Platform
# platform-specific entity description
entity_description: EntityDescription
# entity class to use to instantiate the entity
entity_class: type
# primary value belonging to this discovery scheme
primary_value: ZWaveValueDiscoverySchema
# [optional] template to generate platform specific data to use in setup
data_template: BaseDiscoverySchemaDataTemplate | None = None
# [optional] the node's manufacturer_id must match ANY of these values
manufacturer_id: set[int] | None = None
# [optional] the node's product_id must match ANY of these values
product_id: set[int] | None = None
# [optional] the node's product_type must match ANY of these values
product_type: set[int] | None = None
# [optional] the node's firmware_version must be within this range
firmware_version_range: FirmwareVersionRange | None = None
# [optional] the node's firmware_version must match ANY of these values
firmware_version: set[str] | None = None
# [optional] the node's basic device class must match ANY of these values
device_class_basic: set[str | int] | None = None
# [optional] the node's generic device class must match ANY of these values
device_class_generic: set[str | int] | None = None
# [optional] the node's specific device class must match ANY of these values
device_class_specific: set[str | int] | None = None
# [optional] additional values that ALL need to be present
# on the node for this scheme to pass
required_values: list[ZWaveValueDiscoverySchema] | None = None
# [optional] additional values that MAY NOT be present
# on the node for this scheme to pass
absent_values: list[ZWaveValueDiscoverySchema] | None = None
# [optional] bool to specify if this primary value may be discovered
# by multiple platforms
allow_multi: bool = False
# [optional] bool to specify whether state is assumed
# and events should be fired on value update
assumed_state: bool = False
@dataclass
class BaseDiscoverySchemaDataTemplate:
"""Base class for discovery schema data templates."""
static_data: Any | None = None
def resolve_data(self, value: ZwaveValue) -> Any:
"""Resolve helper class data for a discovered value.
Can optionally be implemented by subclasses if input data needs to be
transformed once discovered Value is available.
"""
return {}
def values_to_watch(self, resolved_data: Any) -> Iterable[ZwaveValue | None]:
"""Return list of all ZwaveValues resolved by helper that should be watched.
Should be implemented by subclasses only if there are values to watch.
"""
return []
def value_ids_to_watch(self, resolved_data: Any) -> set[str]:
"""Return list of all Value IDs resolved by helper that should be watched.
Not to be overwritten by subclasses.
"""
return {val.value_id for val in self.values_to_watch(resolved_data) if val}
@staticmethod
def _get_value_from_id(
node: ZwaveNode, value_id_obj: ZwaveValueID
) -> ZwaveValue | ZwaveConfigurationValue | None:
"""Get a ZwaveValue from a node using a ZwaveValueDict."""
value_id = get_value_id_str(
node,
value_id_obj.command_class,
value_id_obj.property_,
endpoint=value_id_obj.endpoint,
property_key=value_id_obj.property_key,
)
return node.values.get(value_id)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zwave_js/models.py",
"license": "Apache License 2.0",
"lines": 201,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/helpers/target.py | """Helpers for dealing with entity targets."""
from __future__ import annotations
import abc
from collections.abc import Callable
import dataclasses
import logging
from logging import Logger
from typing import Any, TypeGuard
from homeassistant.const import (
ATTR_AREA_ID,
ATTR_DEVICE_ID,
ATTR_ENTITY_ID,
ATTR_FLOOR_ID,
ATTR_LABEL_ID,
ENTITY_MATCH_NONE,
)
from homeassistant.core import (
CALLBACK_TYPE,
Event,
EventStateChangedData,
HomeAssistant,
callback,
)
from homeassistant.exceptions import HomeAssistantError
from . import (
area_registry as ar,
config_validation as cv,
device_registry as dr,
entity_registry as er,
floor_registry as fr,
group,
label_registry as lr,
)
from .deprecation import deprecated_class
from .event import async_track_state_change_event
from .typing import ConfigType
_LOGGER = logging.getLogger(__name__)
@dataclasses.dataclass(slots=True, frozen=True)
class TargetStateChangedData:
"""Data for state change events related to targets."""
state_change_event: Event[EventStateChangedData]
targeted_entity_ids: set[str]
def _has_match(ids: str | list[str] | None) -> TypeGuard[str | list[str]]:
"""Check if ids can match anything."""
return ids not in (None, ENTITY_MATCH_NONE)
class TargetSelection:
"""Class to represent target selection."""
__slots__ = ("area_ids", "device_ids", "entity_ids", "floor_ids", "label_ids")
def __init__(self, config: ConfigType) -> None:
"""Extract ids from the config."""
entity_ids: str | list | None = config.get(ATTR_ENTITY_ID)
device_ids: str | list | None = config.get(ATTR_DEVICE_ID)
area_ids: str | list | None = config.get(ATTR_AREA_ID)
floor_ids: str | list | None = config.get(ATTR_FLOOR_ID)
label_ids: str | list | None = config.get(ATTR_LABEL_ID)
self.entity_ids = (
set(cv.ensure_list(entity_ids)) if _has_match(entity_ids) else set()
)
self.device_ids = (
set(cv.ensure_list(device_ids)) if _has_match(device_ids) else set()
)
self.area_ids = set(cv.ensure_list(area_ids)) if _has_match(area_ids) else set()
self.floor_ids = (
set(cv.ensure_list(floor_ids)) if _has_match(floor_ids) else set()
)
self.label_ids = (
set(cv.ensure_list(label_ids)) if _has_match(label_ids) else set()
)
@property
def has_any_target(self) -> bool:
"""Determine if any target is present."""
return bool(
self.entity_ids
or self.device_ids
or self.area_ids
or self.floor_ids
or self.label_ids
)
@deprecated_class("TargetSelection", breaks_in_ha_version="2026.12.0")
class TargetSelectorData(TargetSelection):
"""Class to represent target selector data."""
@property
def has_any_selector(self) -> bool:
"""Determine if any selectors are present."""
return super().has_any_target
@dataclasses.dataclass(slots=True)
class SelectedEntities:
"""Class to hold the selected entities."""
# Entity IDs of entities that were explicitly mentioned.
referenced: set[str] = dataclasses.field(default_factory=set)
# Entity IDs of entities that were referenced via device/area/floor/label ID.
# Should not trigger a warning when they don't exist.
indirectly_referenced: set[str] = dataclasses.field(default_factory=set)
# Referenced items that could not be found.
missing_devices: set[str] = dataclasses.field(default_factory=set)
missing_areas: set[str] = dataclasses.field(default_factory=set)
missing_floors: set[str] = dataclasses.field(default_factory=set)
missing_labels: set[str] = dataclasses.field(default_factory=set)
referenced_devices: set[str] = dataclasses.field(default_factory=set)
referenced_areas: set[str] = dataclasses.field(default_factory=set)
def log_missing(self, missing_entities: set[str], logger: Logger) -> None:
"""Log about missing items."""
parts = []
for label, items in (
("floors", self.missing_floors),
("areas", self.missing_areas),
("devices", self.missing_devices),
("entities", missing_entities),
("labels", self.missing_labels),
):
if items:
parts.append(f"{label} {', '.join(sorted(items))}")
if not parts:
return
logger.warning(
"Referenced %s are missing or not currently available",
", ".join(parts),
)
def async_extract_referenced_entity_ids(
hass: HomeAssistant, target_selection: TargetSelection, expand_group: bool = True
) -> SelectedEntities:
"""Extract referenced entity IDs from a target selection."""
selected = SelectedEntities()
if not target_selection.has_any_target:
return selected
entity_ids: set[str] | list[str] = target_selection.entity_ids
if expand_group:
entity_ids = group.expand_entity_ids(hass, entity_ids)
selected.referenced.update(entity_ids)
if (
not target_selection.device_ids
and not target_selection.area_ids
and not target_selection.floor_ids
and not target_selection.label_ids
):
return selected
entities = er.async_get(hass).entities
dev_reg = dr.async_get(hass)
area_reg = ar.async_get(hass)
if target_selection.floor_ids:
floor_reg = fr.async_get(hass)
for floor_id in target_selection.floor_ids:
if floor_id not in floor_reg.floors:
selected.missing_floors.add(floor_id)
for area_id in target_selection.area_ids:
if area_id not in area_reg.areas:
selected.missing_areas.add(area_id)
for device_id in target_selection.device_ids:
if device_id not in dev_reg.devices:
selected.missing_devices.add(device_id)
if target_selection.label_ids:
label_reg = lr.async_get(hass)
for label_id in target_selection.label_ids:
if label_id not in label_reg.labels:
selected.missing_labels.add(label_id)
for entity_entry in entities.get_entries_for_label(label_id):
if entity_entry.hidden_by is None:
selected.indirectly_referenced.add(entity_entry.entity_id)
for device_entry in dev_reg.devices.get_devices_for_label(label_id):
selected.referenced_devices.add(device_entry.id)
for area_entry in area_reg.areas.get_areas_for_label(label_id):
selected.referenced_areas.add(area_entry.id)
# Find areas for targeted floors
if target_selection.floor_ids:
selected.referenced_areas.update(
area_entry.id
for floor_id in target_selection.floor_ids
for area_entry in area_reg.areas.get_areas_for_floor(floor_id)
)
selected.referenced_areas.update(target_selection.area_ids)
selected.referenced_devices.update(target_selection.device_ids)
if not selected.referenced_areas and not selected.referenced_devices:
return selected
# Add indirectly referenced by device
selected.indirectly_referenced.update(
entry.entity_id
for device_id in selected.referenced_devices
for entry in entities.get_entries_for_device_id(device_id)
# Do not add entities which are hidden or which are config
# or diagnostic entities.
if (entry.entity_category is None and entry.hidden_by is None)
)
# Find devices for targeted areas
referenced_devices_by_area: set[str] = set()
if selected.referenced_areas:
for area_id in selected.referenced_areas:
referenced_devices_by_area.update(
device_entry.id
for device_entry in dev_reg.devices.get_devices_for_area_id(area_id)
)
selected.referenced_devices.update(referenced_devices_by_area)
# Add indirectly referenced by area
selected.indirectly_referenced.update(
entry.entity_id
for area_id in selected.referenced_areas
# The entity's area matches a targeted area
for entry in entities.get_entries_for_area_id(area_id)
# Do not add entities which are hidden or which are config
# or diagnostic entities.
if entry.entity_category is None and entry.hidden_by is None
)
# Add indirectly referenced by area through device
selected.indirectly_referenced.update(
entry.entity_id
for device_id in referenced_devices_by_area
for entry in entities.get_entries_for_device_id(device_id)
# Do not add entities which are hidden or which are config
# or diagnostic entities.
if (
entry.entity_category is None
and entry.hidden_by is None
and (
# The entity's device matches a device referenced
# by an area and the entity
# has no explicitly set area
not entry.area_id
)
)
)
return selected
class TargetEntityChangeTracker(abc.ABC):
"""Helper class to manage entity change tracking for targets."""
def __init__(
self,
hass: HomeAssistant,
target_selection: TargetSelection,
entity_filter: Callable[[set[str]], set[str]],
) -> None:
"""Initialize the state change tracker."""
self._hass = hass
self._target_selection = target_selection
self._entity_filter = entity_filter
self._registry_unsubs: list[CALLBACK_TYPE] = []
def async_setup(self) -> Callable[[], None]:
"""Set up the state change tracking."""
self._setup_registry_listeners()
self._handle_target_update()
return self._unsubscribe
@abc.abstractmethod
@callback
def _handle_entities_update(self, tracked_entities: set[str]) -> None:
"""Called when there's an update to the list of entities of the tracked targets."""
@callback
def _handle_target_update(self, event: Event[Any] | None = None) -> None:
"""Handle updates in the tracked targets."""
selected = async_extract_referenced_entity_ids(
self._hass, self._target_selection, expand_group=False
)
filtered_entities = self._entity_filter(
selected.referenced | selected.indirectly_referenced
)
self._handle_entities_update(filtered_entities)
def _setup_registry_listeners(self) -> None:
"""Set up listeners for registry changes that require resubscription."""
# Subscribe to registry updates that can change the entities to track:
# - Entity registry: entity added/removed; entity labels changed; entity area changed.
# - Device registry: device labels changed; device area changed.
# - Area registry: area floor changed.
#
# We don't track other registries (like floor or label registries) because their
# changes don't affect which entities are tracked.
self._registry_unsubs = [
self._hass.bus.async_listen(
er.EVENT_ENTITY_REGISTRY_UPDATED, self._handle_target_update
),
self._hass.bus.async_listen(
dr.EVENT_DEVICE_REGISTRY_UPDATED, self._handle_target_update
),
self._hass.bus.async_listen(
ar.EVENT_AREA_REGISTRY_UPDATED, self._handle_target_update
),
]
def _unsubscribe(self) -> None:
"""Unsubscribe from all events."""
for registry_unsub in self._registry_unsubs:
registry_unsub()
self._registry_unsubs.clear()
class TargetStateChangeTracker(TargetEntityChangeTracker):
"""Helper class to manage state change tracking for targets."""
def __init__(
self,
hass: HomeAssistant,
target_selection: TargetSelection,
action: Callable[[TargetStateChangedData], Any],
entity_filter: Callable[[set[str]], set[str]],
) -> None:
"""Initialize the state change tracker."""
super().__init__(hass, target_selection, entity_filter)
self._action = action
self._state_change_unsub: CALLBACK_TYPE | None = None
def _handle_entities_update(self, tracked_entities: set[str]) -> None:
"""Handle the tracked entities."""
@callback
def state_change_listener(event: Event[EventStateChangedData]) -> None:
"""Handle state change events."""
if event.data["entity_id"] in tracked_entities:
self._action(TargetStateChangedData(event, tracked_entities))
_LOGGER.debug("Tracking state changes for entities: %s", tracked_entities)
if self._state_change_unsub:
self._state_change_unsub()
self._state_change_unsub = async_track_state_change_event(
self._hass, tracked_entities, state_change_listener
)
def _unsubscribe(self) -> None:
"""Unsubscribe from all events."""
super()._unsubscribe()
if self._state_change_unsub:
self._state_change_unsub()
self._state_change_unsub = None
def async_track_target_selector_state_change_event(
hass: HomeAssistant,
target_selector_config: ConfigType,
action: Callable[[TargetStateChangedData], Any],
entity_filter: Callable[[set[str]], set[str]] = lambda x: x,
) -> CALLBACK_TYPE:
"""Track state changes for entities referenced directly or indirectly in a target selector."""
target_selection = TargetSelection(target_selector_config)
if not target_selection.has_any_target:
raise HomeAssistantError(
f"Target selector {target_selector_config} does not have any selectors defined"
)
tracker = TargetStateChangeTracker(hass, target_selection, action, entity_filter)
return tracker.async_setup()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/helpers/target.py",
"license": "Apache License 2.0",
"lines": 323,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/util/resource.py | """Resource management utilities for Home Assistant."""
from __future__ import annotations
import logging
import os
import resource
from typing import Final
_LOGGER = logging.getLogger(__name__)
# Default soft file descriptor limit to set
DEFAULT_SOFT_FILE_LIMIT: Final = 2048
def set_open_file_descriptor_limit() -> None:
"""Set the maximum open file descriptor soft limit."""
try:
# Check environment variable first, then use default
soft_limit = int(os.environ.get("SOFT_FILE_LIMIT", DEFAULT_SOFT_FILE_LIMIT))
# Get current limits
current_soft, current_hard = resource.getrlimit(resource.RLIMIT_NOFILE)
_LOGGER.debug(
"Current file descriptor limits: soft=%d, hard=%d",
current_soft,
current_hard,
)
# Don't increase if already at or above the desired limit
if current_soft >= soft_limit:
_LOGGER.debug(
"Current soft limit (%d) is already >= desired limit (%d), skipping",
current_soft,
soft_limit,
)
return
# Don't set soft limit higher than hard limit
if soft_limit > current_hard:
_LOGGER.warning(
"Requested soft limit (%d) exceeds hard limit (%d), "
"setting to hard limit",
soft_limit,
current_hard,
)
soft_limit = current_hard
# Set the new soft limit
resource.setrlimit(resource.RLIMIT_NOFILE, (soft_limit, current_hard))
# Verify the change
new_soft, new_hard = resource.getrlimit(resource.RLIMIT_NOFILE)
_LOGGER.info(
"File descriptor limits updated: soft=%d->%d, hard=%d",
current_soft,
new_soft,
new_hard,
)
except OSError as err:
_LOGGER.error("Failed to set file descriptor limit: %s", err)
except ValueError as err:
_LOGGER.error("Invalid file descriptor limit value: %s", err)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/util/resource.py",
"license": "Apache License 2.0",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:pylint/plugins/hass_async_load_fixtures.py | """Plugin for logger invocations."""
from __future__ import annotations
from astroid import nodes
from pylint.checkers import BaseChecker
from pylint.lint import PyLinter
FUNCTION_NAMES = (
"load_fixture",
"load_json_array_fixture",
"load_json_object_fixture",
)
class HassLoadFixturesChecker(BaseChecker):
"""Checker for I/O load fixtures."""
name = "hass_async_load_fixtures"
priority = -1
msgs = {
"W7481": (
"Test fixture files should be loaded asynchronously",
"hass-async-load-fixtures",
"Used when a test fixture file is loaded synchronously",
),
}
options = ()
_decorators_queue: list[nodes.Decorators]
_function_queue: list[nodes.FunctionDef | nodes.AsyncFunctionDef]
_in_test_module: bool
def visit_module(self, node: nodes.Module) -> None:
"""Visit a module definition."""
self._in_test_module = node.name.startswith("tests.")
self._decorators_queue = []
self._function_queue = []
def visit_decorators(self, node: nodes.Decorators) -> None:
"""Visit a function definition."""
self._decorators_queue.append(node)
def leave_decorators(self, node: nodes.Decorators) -> None:
"""Leave a function definition."""
self._decorators_queue.pop()
def visit_functiondef(self, node: nodes.FunctionDef) -> None:
"""Visit a function definition."""
self._function_queue.append(node)
def leave_functiondef(self, node: nodes.FunctionDef) -> None:
"""Leave a function definition."""
self._function_queue.pop()
visit_asyncfunctiondef = visit_functiondef
leave_asyncfunctiondef = leave_functiondef
def visit_call(self, node: nodes.Call) -> None:
"""Check for sync I/O in load_fixture."""
if (
# Ensure we are in a test module
not self._in_test_module
# Ensure we are in an async function context
or not self._function_queue
or not isinstance(self._function_queue[-1], nodes.AsyncFunctionDef)
# Ensure we are not in the decorators
or self._decorators_queue
# Check function name
or not isinstance(node.func, nodes.Name)
or node.func.name not in FUNCTION_NAMES
):
return
self.add_message("hass-async-load-fixtures", node=node)
def register(linter: PyLinter) -> None:
"""Register the checker."""
linter.register_checker(HassLoadFixturesChecker(linter))
| {
"repo_id": "home-assistant/core",
"file_path": "pylint/plugins/hass_async_load_fixtures.py",
"license": "Apache License 2.0",
"lines": 63,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:script/hassfest/conditions.py | """Validate conditions."""
from __future__ import annotations
import contextlib
import json
import pathlib
import re
from typing import Any
import voluptuous as vol
from voluptuous.humanize import humanize_error
from homeassistant.const import CONF_SELECTOR
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import condition, config_validation as cv, selector
from homeassistant.util.yaml import load_yaml_dict
from .model import Config, Integration
def exists(value: Any) -> Any:
"""Check if value exists."""
if value is None:
raise vol.Invalid("Value cannot be None")
return value
FIELD_SCHEMA = vol.Schema(
{
vol.Optional("example"): exists,
vol.Optional("default"): exists,
vol.Optional("required"): bool,
vol.Optional(CONF_SELECTOR): selector.validate_selector,
}
)
CONDITION_SCHEMA = vol.Any(
vol.Schema(
{
vol.Optional("target"): selector.TargetSelector.CONFIG_SCHEMA,
vol.Optional("fields"): vol.Schema({str: FIELD_SCHEMA}),
}
),
None,
)
CONDITIONS_SCHEMA = vol.Schema(
{
vol.Remove(vol.All(str, condition.starts_with_dot)): object,
cv.underscore_slug: CONDITION_SCHEMA,
}
)
NON_MIGRATED_INTEGRATIONS = {
"device_automation",
"sun",
"zone",
}
def grep_dir(path: pathlib.Path, glob_pattern: str, search_pattern: str) -> bool:
"""Recursively go through a dir and it's children and find the regex."""
pattern = re.compile(search_pattern)
for fil in path.glob(glob_pattern):
if not fil.is_file():
continue
if pattern.search(fil.read_text()):
return True
return False
def validate_conditions(config: Config, integration: Integration) -> None: # noqa: C901
"""Validate conditions."""
try:
data = load_yaml_dict(str(integration.path / "conditions.yaml"))
except FileNotFoundError:
# Find if integration uses conditions
has_conditions = grep_dir(
integration.path,
"**/condition.py",
r"async_get_conditions",
)
if has_conditions and integration.domain not in NON_MIGRATED_INTEGRATIONS:
integration.add_error(
"conditions", "Registers conditions but has no conditions.yaml"
)
return
except HomeAssistantError:
integration.add_error("conditions", "Invalid conditions.yaml")
return
try:
conditions = CONDITIONS_SCHEMA(data)
except vol.Invalid as err:
integration.add_error(
"conditions", f"Invalid conditions.yaml: {humanize_error(data, err)}"
)
return
icons_file = integration.path / "icons.json"
icons = {}
if icons_file.is_file():
with contextlib.suppress(ValueError):
icons = json.loads(icons_file.read_text())
condition_icons = icons.get("conditions", {})
# Try loading translation strings
if integration.core:
strings_file = integration.path / "strings.json"
else:
# For custom integrations, use the en.json file
strings_file = integration.path / "translations/en.json"
strings = {}
if strings_file.is_file():
with contextlib.suppress(ValueError):
strings = json.loads(strings_file.read_text())
error_msg_suffix = "in the translations file"
if not integration.core:
error_msg_suffix = f"and is not {error_msg_suffix}"
# For each condition in the integration:
# 1. Check if the condition description is set, if not,
# check if it's in the strings file else add an error.
# 2. Check if the condition has an icon set in icons.json.
# raise an error if not.,
for condition_name, condition_schema in conditions.items():
if integration.core and condition_name not in condition_icons:
# This is enforced for Core integrations only
integration.add_error(
"conditions",
f"Condition {condition_name} has no icon in icons.json.",
)
if condition_schema is None:
continue
if "name" not in condition_schema and integration.core:
try:
strings["conditions"][condition_name]["name"]
except KeyError:
integration.add_error(
"conditions",
f"Condition {condition_name} has no name {error_msg_suffix}",
)
if "description" not in condition_schema and integration.core:
try:
strings["conditions"][condition_name]["description"]
except KeyError:
integration.add_error(
"conditions",
f"Condition {condition_name} has no description {error_msg_suffix}",
)
# The same check is done for the description in each of the fields of the
# condition schema.
for field_name, field_schema in condition_schema.get("fields", {}).items():
if "fields" in field_schema:
# This is a section
continue
if "name" not in field_schema and integration.core:
try:
strings["conditions"][condition_name]["fields"][field_name]["name"]
except KeyError:
integration.add_error(
"conditions",
(
f"Condition {condition_name} has a field {field_name} with no "
f"name {error_msg_suffix}"
),
)
if "description" not in field_schema and integration.core:
try:
strings["conditions"][condition_name]["fields"][field_name][
"description"
]
except KeyError:
integration.add_error(
"conditions",
(
f"Condition {condition_name} has a field {field_name} with no "
f"description {error_msg_suffix}"
),
)
if "selector" in field_schema:
with contextlib.suppress(KeyError):
translation_key = field_schema["selector"]["select"][
"translation_key"
]
try:
strings["selector"][translation_key]
except KeyError:
integration.add_error(
"conditions",
f"Condition {condition_name} has a field {field_name} with a selector with a translation key {translation_key} that is not in the translations file",
)
# The same check is done for the description in each of the sections of the
# condition schema.
for section_name, section_schema in condition_schema.get("fields", {}).items():
if "fields" not in section_schema:
# This is not a section
continue
if "name" not in section_schema and integration.core:
try:
strings["conditions"][condition_name]["sections"][section_name][
"name"
]
except KeyError:
integration.add_error(
"conditions",
f"Condition {condition_name} has a section {section_name} with no name {error_msg_suffix}",
)
def validate(integrations: dict[str, Integration], config: Config) -> None:
"""Handle dependencies for integrations."""
# check conditions.yaml is valid
for integration in integrations.values():
validate_conditions(config, integration)
| {
"repo_id": "home-assistant/core",
"file_path": "script/hassfest/conditions.py",
"license": "Apache License 2.0",
"lines": 194,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/airos/test_config_flow.py | """Test the Ubiquiti airOS config flow."""
from typing import Any
from unittest.mock import AsyncMock, patch
from airos.exceptions import (
AirOSConnectionAuthenticationError,
AirOSConnectionSetupError,
AirOSDeviceConnectionError,
AirOSEndpointError,
AirOSKeyDataMissingError,
AirOSListenerError,
)
from airos.helpers import DetectDeviceData
import pytest
import voluptuous as vol
from homeassistant.components.airos.const import (
DEFAULT_USERNAME,
DOMAIN,
HOSTNAME,
IP_ADDRESS,
MAC_ADDRESS,
SECTION_ADVANCED_SETTINGS,
)
from homeassistant.config_entries import (
SOURCE_DHCP,
SOURCE_REAUTH,
SOURCE_RECONFIGURE,
SOURCE_USER,
)
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_SSL,
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo
from . import AirOSData
from tests.common import MockConfigEntry
NEW_PASSWORD = "new_password"
REAUTH_STEP = "reauth_confirm"
RECONFIGURE_STEP = "reconfigure"
MOCK_ADVANCED_SETTINGS = {
CONF_SSL: True,
CONF_VERIFY_SSL: False,
}
MOCK_CONFIG = {
CONF_HOST: "1.1.1.1",
CONF_USERNAME: DEFAULT_USERNAME,
CONF_PASSWORD: "test-password",
SECTION_ADVANCED_SETTINGS: MOCK_ADVANCED_SETTINGS,
}
MOCK_CONFIG_REAUTH = {
CONF_HOST: "1.1.1.1",
CONF_USERNAME: DEFAULT_USERNAME,
CONF_PASSWORD: "wrong-password",
}
MOCK_DISC_DEV1 = {
MAC_ADDRESS: "00:11:22:33:44:55",
IP_ADDRESS: "192.168.1.100",
HOSTNAME: "Test-Device-1",
}
MOCK_DISC_DEV2 = {
MAC_ADDRESS: "AA:BB:CC:DD:EE:FF",
IP_ADDRESS: "192.168.1.101",
HOSTNAME: "Test-Device-2",
}
MOCK_DISC_EXISTS = {
MAC_ADDRESS: "01:23:45:67:89:AB",
IP_ADDRESS: "192.168.1.102",
HOSTNAME: "Existing-Device",
}
async def test_manual_flow_creates_entry(
hass: HomeAssistant,
ap_fixture: dict[str, Any],
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test we get the user form and create the appropriate entry."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.MENU
assert "manual" in result["menu_options"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": "manual"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "manual"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], MOCK_CONFIG
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "NanoStation 5AC ap name"
assert result["result"].unique_id == "01:23:45:67:89:AB"
assert result["data"] == MOCK_CONFIG
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_duplicate_entry(
hass: HomeAssistant,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
) -> None:
"""Test the form does not allow duplicate entries."""
mock_entry = MockConfigEntry(
domain=DOMAIN,
unique_id="01:23:45:67:89:AB",
data=MOCK_CONFIG,
)
mock_entry.add_to_hass(hass)
flow_start = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
menu = await hass.config_entries.flow.async_configure(
flow_start["flow_id"], {"next_step_id": "manual"}
)
result = await hass.config_entries.flow.async_configure(
menu["flow_id"], MOCK_CONFIG
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("exception", "error"),
[
(AirOSConnectionAuthenticationError, "invalid_auth"),
(AirOSConnectionSetupError, "cannot_connect"),
(AirOSDeviceConnectionError, "cannot_connect"),
(AirOSKeyDataMissingError, "key_data_missing"),
(Exception, "unknown"),
],
)
async def test_form_exception_handling(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
ap_fixture: dict[str, Any],
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test we handle exceptions."""
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
side_effect=exception,
):
flow_start = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
menu = await hass.config_entries.flow.async_configure(
flow_start["flow_id"], {"next_step_id": "manual"}
)
result = await hass.config_entries.flow.async_configure(
menu["flow_id"], MOCK_CONFIG
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error}
fw_major = int(ap_fixture.host.fwversion.lstrip("v").split(".", 1)[0])
valid_data = DetectDeviceData(
fw_major=fw_major,
mac=ap_fixture.derived.mac,
hostname=ap_fixture.host.hostname,
)
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
return_value=valid_data,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_CONFIG,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "NanoStation 5AC ap name"
assert result["data"] == MOCK_CONFIG
assert len(mock_setup_entry.mock_calls) == 1
async def test_reauth_flow_scenario(
hass: HomeAssistant,
ap_fixture: AirOSData,
mock_airos_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test successful reauthentication."""
mock_config_entry.add_to_hass(hass)
mock_airos_client.login.side_effect = AirOSConnectionAuthenticationError
await hass.config_entries.async_setup(mock_config_entry.entry_id)
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
side_effect=AirOSConnectionAuthenticationError,
):
flow = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_REAUTH, "entry_id": mock_config_entry.entry_id},
data=mock_config_entry.data,
)
assert flow["type"] == FlowResultType.FORM
assert flow["step_id"] == REAUTH_STEP
fw_major = int(ap_fixture.host.fwversion.lstrip("v").split(".", 1)[0])
valid_data = DetectDeviceData(
fw_major=fw_major,
mac=ap_fixture.derived.mac,
hostname=ap_fixture.host.hostname,
)
mock_firmware = AsyncMock(return_value=valid_data)
with (
patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
new=mock_firmware,
),
patch(
"homeassistant.components.airos.async_get_firmware_data",
new=mock_firmware,
),
):
result = await hass.config_entries.flow.async_configure(
flow["flow_id"],
user_input={CONF_PASSWORD: NEW_PASSWORD},
)
await hass.async_block_till_done(wait_background_tasks=True)
# Always test resolution
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
updated_entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert updated_entry.data[CONF_PASSWORD] == NEW_PASSWORD
@pytest.mark.parametrize(
("reauth_exception", "expected_error"),
[
(AirOSConnectionAuthenticationError, "invalid_auth"),
(AirOSDeviceConnectionError, "cannot_connect"),
(AirOSKeyDataMissingError, "key_data_missing"),
(Exception, "unknown"),
],
ids=[
"invalid_auth",
"cannot_connect",
"key_data_missing",
"unknown",
],
)
async def test_reauth_flow_scenarios(
hass: HomeAssistant,
ap_fixture: AirOSData,
expected_error: str,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_config_entry: MockConfigEntry,
reauth_exception: Exception,
) -> None:
"""Test reauthentication from start (failure) to finish (success)."""
mock_config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
side_effect=AirOSConnectionAuthenticationError,
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
flow = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_REAUTH, "entry_id": mock_config_entry.entry_id},
data=mock_config_entry.data,
)
assert flow["type"] == FlowResultType.FORM
assert flow["step_id"] == REAUTH_STEP
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
side_effect=reauth_exception,
):
result = await hass.config_entries.flow.async_configure(
flow["flow_id"],
user_input={CONF_PASSWORD: NEW_PASSWORD},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == REAUTH_STEP
assert result["errors"] == {"base": expected_error}
fw_major = int(ap_fixture.host.fwversion.lstrip("v").split(".", 1)[0])
valid_data = DetectDeviceData(
fw_major=fw_major,
mac=ap_fixture.derived.mac,
hostname=ap_fixture.host.hostname,
)
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
new=AsyncMock(return_value=valid_data),
):
result = await hass.config_entries.flow.async_configure(
flow["flow_id"],
user_input={CONF_PASSWORD: NEW_PASSWORD},
)
assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
updated_entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert updated_entry.data[CONF_PASSWORD] == NEW_PASSWORD
async def test_reauth_unique_id_mismatch(
hass: HomeAssistant,
ap_fixture: AirOSData,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reauthentication failure when the unique ID changes."""
mock_config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
side_effect=AirOSConnectionAuthenticationError,
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
flow = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_REAUTH, "entry_id": mock_config_entry.entry_id},
data=mock_config_entry.data,
)
fw_major = int(ap_fixture.host.fwversion.lstrip("v").split(".", 1)[0])
valid_data = DetectDeviceData(
fw_major=fw_major,
mac="FF:23:45:67:89:AB",
hostname=ap_fixture.host.hostname,
)
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
new=AsyncMock(return_value=valid_data),
):
result = await hass.config_entries.flow.async_configure(
flow["flow_id"],
user_input={CONF_PASSWORD: NEW_PASSWORD},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
updated_entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert updated_entry.data[CONF_PASSWORD] != NEW_PASSWORD
async def test_successful_reconfigure(
hass: HomeAssistant,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test successful reconfigure."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_RECONFIGURE, "entry_id": mock_config_entry.entry_id},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == RECONFIGURE_STEP
user_input = {
CONF_PASSWORD: NEW_PASSWORD,
SECTION_ADVANCED_SETTINGS: {
CONF_SSL: True,
CONF_VERIFY_SSL: True,
},
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=user_input,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
updated_entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert updated_entry.data[CONF_PASSWORD] == NEW_PASSWORD
assert updated_entry.data[SECTION_ADVANCED_SETTINGS][CONF_SSL] is True
assert updated_entry.data[SECTION_ADVANCED_SETTINGS][CONF_VERIFY_SSL] is True
assert updated_entry.data[CONF_HOST] == MOCK_CONFIG[CONF_HOST]
assert updated_entry.data[CONF_USERNAME] == MOCK_CONFIG[CONF_USERNAME]
@pytest.mark.parametrize(
("reconfigure_exception", "expected_error"),
[
(AirOSConnectionAuthenticationError, "invalid_auth"),
(AirOSDeviceConnectionError, "cannot_connect"),
(AirOSKeyDataMissingError, "key_data_missing"),
(Exception, "unknown"),
],
ids=[
"invalid_auth",
"cannot_connect",
"key_data_missing",
"unknown",
],
)
async def test_reconfigure_flow_failure(
hass: HomeAssistant,
expected_error: str,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_config_entry: MockConfigEntry,
reconfigure_exception: Exception,
) -> None:
"""Test reconfigure from start (failure) to finish (success)."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_RECONFIGURE, "entry_id": mock_config_entry.entry_id},
)
user_input = {
CONF_PASSWORD: NEW_PASSWORD,
SECTION_ADVANCED_SETTINGS: {
CONF_SSL: True,
CONF_VERIFY_SSL: True,
},
}
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
side_effect=reconfigure_exception,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=user_input,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == RECONFIGURE_STEP
assert result["errors"] == {"base": expected_error}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=user_input,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
updated_entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert updated_entry.data[CONF_PASSWORD] == NEW_PASSWORD
async def test_reconfigure_unique_id_mismatch(
hass: HomeAssistant,
ap_fixture: AirOSData,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration failure when the unique ID changes."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_RECONFIGURE, "entry_id": mock_config_entry.entry_id},
)
flow_id = result["flow_id"]
fw_major = int(ap_fixture.host.fwversion.lstrip("v").split(".", 1)[0])
mismatched_data = DetectDeviceData(
fw_major=fw_major,
mac="FF:23:45:67:89:AB",
hostname=ap_fixture.host.hostname,
)
user_input = {
CONF_PASSWORD: NEW_PASSWORD,
SECTION_ADVANCED_SETTINGS: {
CONF_SSL: True,
CONF_VERIFY_SSL: True,
},
}
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
new=AsyncMock(return_value=mismatched_data),
):
result = await hass.config_entries.flow.async_configure(
flow_id,
user_input=user_input,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
updated_entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id)
assert updated_entry.data[CONF_PASSWORD] == MOCK_CONFIG[CONF_PASSWORD]
assert (
updated_entry.data[SECTION_ADVANCED_SETTINGS][CONF_SSL]
== MOCK_CONFIG[SECTION_ADVANCED_SETTINGS][CONF_SSL]
)
async def test_discover_flow_no_devices_found(
hass: HomeAssistant,
mock_discovery_method: AsyncMock,
) -> None:
"""Test discovery flow aborts when no devices are found."""
mock_discovery_method.return_value = {}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": "discovery"}
)
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "discovery"
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"
async def test_discover_flow_one_device_found(
hass: HomeAssistant,
mock_airos_client: AsyncMock,
mock_discovery_method: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test discovery flow goes straight to credentials when one device is found."""
mock_discovery_method.return_value = {MOCK_DISC_DEV1[MAC_ADDRESS]: MOCK_DISC_DEV1}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": "discovery"}
)
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# With only one device, the flow should skip the select step and
# go directly to configure_device.
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "configure_device"
assert result["description_placeholders"]["device_name"] == MOCK_DISC_DEV1[HOSTNAME]
valid_data = DetectDeviceData(
fw_major=8,
mac=MOCK_DISC_DEV1[MAC_ADDRESS],
hostname=MOCK_DISC_DEV1[HOSTNAME],
)
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
new=AsyncMock(return_value=valid_data),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: DEFAULT_USERNAME,
CONF_PASSWORD: "test-password",
SECTION_ADVANCED_SETTINGS: MOCK_ADVANCED_SETTINGS,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == MOCK_DISC_DEV1[HOSTNAME]
assert result["data"][CONF_HOST] == MOCK_DISC_DEV1[IP_ADDRESS]
async def test_discover_flow_multiple_devices_found(
hass: HomeAssistant,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_discovery_method: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test discovery flow with multiple devices found, requiring a selection step."""
mock_discovery_method.return_value = {
MOCK_DISC_DEV1[MAC_ADDRESS]: MOCK_DISC_DEV1,
MOCK_DISC_DEV2[MAC_ADDRESS]: MOCK_DISC_DEV2,
}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
assert "discovery" in result["menu_options"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": "discovery"}
)
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "discovery"
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "select_device"
expected_options = {
MOCK_DISC_DEV1[MAC_ADDRESS]: (
f"{MOCK_DISC_DEV1[HOSTNAME]} ({MOCK_DISC_DEV1[IP_ADDRESS]})"
),
MOCK_DISC_DEV2[MAC_ADDRESS]: (
f"{MOCK_DISC_DEV2[HOSTNAME]} ({MOCK_DISC_DEV2[IP_ADDRESS]})"
),
}
actual_options = result["data_schema"].schema[vol.Required(MAC_ADDRESS)].container
assert actual_options == expected_options
# Select one of the devices
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {MAC_ADDRESS: MOCK_DISC_DEV1[MAC_ADDRESS]}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "configure_device"
assert result["description_placeholders"]["device_name"] == MOCK_DISC_DEV1[HOSTNAME]
valid_data = DetectDeviceData(
fw_major=8,
mac=MOCK_DISC_DEV1[MAC_ADDRESS],
hostname=MOCK_DISC_DEV1[HOSTNAME],
)
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
new=AsyncMock(return_value=valid_data),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: DEFAULT_USERNAME,
CONF_PASSWORD: "test-password",
SECTION_ADVANCED_SETTINGS: MOCK_ADVANCED_SETTINGS,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == MOCK_DISC_DEV1[HOSTNAME]
assert result["data"][CONF_HOST] == MOCK_DISC_DEV1[IP_ADDRESS]
async def test_discover_flow_with_existing_device(
hass: HomeAssistant,
mock_discovery_method: AsyncMock,
mock_airos_client: AsyncMock,
) -> None:
"""Test that discovery ignores devices that are already configured."""
# Add a mock config entry for an existing device
mock_entry = MockConfigEntry(
domain=DOMAIN,
unique_id=MOCK_DISC_EXISTS[MAC_ADDRESS],
data=MOCK_CONFIG,
)
mock_entry.add_to_hass(hass)
# Mock discovery to find both a new device and the existing one
mock_discovery_method.return_value = {
MOCK_DISC_DEV1[MAC_ADDRESS]: MOCK_DISC_DEV1,
MOCK_DISC_EXISTS[MAC_ADDRESS]: MOCK_DISC_EXISTS,
}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": "discovery"}
)
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# The flow should proceed with only the new device
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "configure_device"
assert result["description_placeholders"]["device_name"] == MOCK_DISC_DEV1[HOSTNAME]
@pytest.mark.parametrize(
("exception", "reason"),
[
(AirOSEndpointError, "detect_error"),
(AirOSListenerError, "listen_error"),
(Exception, "discovery_failed"),
],
)
async def test_discover_flow_discovery_exceptions(
hass: HomeAssistant,
mock_discovery_method,
exception: Exception,
reason: str,
) -> None:
"""Test discovery flow aborts on various discovery exceptions."""
mock_discovery_method.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": "discovery"}
)
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == reason
async def test_configure_device_flow_exceptions(
hass: HomeAssistant,
mock_discovery_method: AsyncMock,
mock_airos_client: AsyncMock,
) -> None:
"""Test configure_device step handles authentication and connection exceptions."""
mock_discovery_method.return_value = {MOCK_DISC_DEV1[MAC_ADDRESS]: MOCK_DISC_DEV1}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"next_step_id": "discovery"}
)
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
side_effect=AirOSConnectionAuthenticationError,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: "wrong-user",
CONF_PASSWORD: "wrong-password",
SECTION_ADVANCED_SETTINGS: MOCK_ADVANCED_SETTINGS,
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "invalid_auth"}
with patch(
"homeassistant.components.airos.config_flow.async_get_firmware_data",
side_effect=AirOSDeviceConnectionError,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_USERNAME: DEFAULT_USERNAME,
CONF_PASSWORD: "some-password",
SECTION_ADVANCED_SETTINGS: MOCK_ADVANCED_SETTINGS,
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
async def test_dhcp_ip_changed_updates_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""DHCP event with new IP should update the config entry and reload."""
mock_config_entry.add_to_hass(hass)
macaddress = mock_config_entry.unique_id.lower().replace(":", "").replace("-", "")
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_DHCP},
data=DhcpServiceInfo(
ip="1.1.1.2",
hostname="airos",
macaddress=macaddress,
),
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_config_entry.data[CONF_HOST] == "1.1.1.2"
async def test_dhcp_mac_mismatch(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""DHCP event with non-matching MAC should abort."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_DHCP},
data=DhcpServiceInfo(
ip="1.1.1.2",
hostname="airos",
macaddress="aabbccddeeff",
),
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unreachable"
async def test_dhcp_ip_unchanged(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""DHCP event with same IP should abort."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_DHCP},
data=DhcpServiceInfo(
ip=mock_config_entry.data[CONF_HOST],
hostname="airos",
macaddress=mock_config_entry.unique_id.lower()
.replace(":", "")
.replace("-", ""),
),
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/airos/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 734,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/airos/test_diagnostics.py | """Diagnostic tests for airOS."""
from unittest.mock import AsyncMock, MagicMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.airos.coordinator import AirOS8Data
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_airos_client: MagicMock,
mock_config_entry: MockConfigEntry,
ap_fixture: AirOS8Data,
snapshot: SnapshotAssertion,
mock_async_get_firmware_data: AsyncMock,
) -> None:
"""Test diagnostics."""
await setup_integration(hass, mock_config_entry)
assert (
await get_diagnostics_for_config_entry(hass, hass_client, mock_config_entry)
== snapshot
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/airos/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/airos/test_sensor.py | """Test the Ubiquiti airOS sensors."""
from datetime import timedelta
from unittest.mock import AsyncMock
from airos.exceptions import AirOSDataMissingError, AirOSDeviceConnectionError
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.airos.const import SCAN_INTERVAL
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
) -> None:
"""Test all entities."""
await setup_integration(hass, mock_config_entry, [Platform.SENSOR])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("exception"),
[
TimeoutError,
AirOSDeviceConnectionError,
AirOSDataMissingError,
],
)
async def test_sensor_update_exception_handling(
hass: HomeAssistant,
mock_airos_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
freezer: FrozenDateTimeFactory,
mock_async_get_firmware_data: AsyncMock,
) -> None:
"""Test entity update data handles exceptions."""
await setup_integration(hass, mock_config_entry, [Platform.SENSOR])
expected_entity_id = "sensor.nanostation_5ac_ap_name_antenna_gain"
signal_state = hass.states.get(expected_entity_id)
assert signal_state.state == "13", f"Expected state 13, got {signal_state.state}"
assert signal_state.attributes.get("unit_of_measurement") == "dB", (
f"Expected unit 'dB', got {signal_state.attributes.get('unit_of_measurement')}"
)
mock_airos_client.login.side_effect = exception
freezer.tick(timedelta(seconds=SCAN_INTERVAL.total_seconds()))
async_fire_time_changed(hass)
await hass.async_block_till_done()
signal_state = hass.states.get(expected_entity_id)
assert signal_state.state == STATE_UNAVAILABLE, (
f"Expected state {STATE_UNAVAILABLE}, got {signal_state.state}"
)
mock_airos_client.login.side_effect = None
freezer.tick(timedelta(seconds=SCAN_INTERVAL.total_seconds()))
async_fire_time_changed(hass)
await hass.async_block_till_done()
signal_state = hass.states.get(expected_entity_id)
assert signal_state.state == "13", f"Expected state 13, got {signal_state.state}"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/airos/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/airthings/test_sensor.py | """Test the Airthings sensors."""
from airthings import Airthings
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_all_device_types(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
mock_airthings_client: Airthings,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all device types."""
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/airthings/test_sensor.py",
"license": "Apache License 2.0",
"lines": 17,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/alexa_devices/test_services.py | """Tests for Alexa Devices services."""
from unittest.mock import AsyncMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.alexa_devices.const import DOMAIN
from homeassistant.components.alexa_devices.services import (
ATTR_INFO_SKILL,
ATTR_SOUND,
ATTR_TEXT_COMMAND,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_DEVICE_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import device_registry as dr
from . import setup_integration
from .const import TEST_DEVICE_1_ID, TEST_DEVICE_1_SN
from tests.common import MockConfigEntry, mock_device_registry
async def test_setup_services(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setup of Alexa Devices services."""
await setup_integration(hass, mock_config_entry)
assert (services := hass.services.async_services_for_domain(DOMAIN))
assert "send_text_command" in services
assert "send_sound" in services
assert "send_info_skill" in services
async def test_info_skill_service(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test info skill service."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, TEST_DEVICE_1_SN)}
)
assert device_entry
await hass.services.async_call(
DOMAIN,
"send_info_skill",
{
ATTR_INFO_SKILL: "tell_joke",
ATTR_DEVICE_ID: device_entry.id,
},
blocking=True,
)
assert mock_amazon_devices_client.call_alexa_info_skill.call_count == 1
assert mock_amazon_devices_client.call_alexa_info_skill.call_args == snapshot
async def test_send_sound_service(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test send sound service."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, TEST_DEVICE_1_SN)}
)
assert device_entry
await hass.services.async_call(
DOMAIN,
"send_sound",
{
ATTR_SOUND: "bell_02",
ATTR_DEVICE_ID: device_entry.id,
},
blocking=True,
)
assert mock_amazon_devices_client.call_alexa_sound.call_count == 1
assert mock_amazon_devices_client.call_alexa_sound.call_args == snapshot
async def test_send_text_service(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test send text service."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, TEST_DEVICE_1_SN)}
)
assert device_entry
await hass.services.async_call(
DOMAIN,
"send_text_command",
{
ATTR_TEXT_COMMAND: "Play B.B.C. radio on TuneIn",
ATTR_DEVICE_ID: device_entry.id,
},
blocking=True,
)
assert mock_amazon_devices_client.call_alexa_text_command.call_count == 1
assert mock_amazon_devices_client.call_alexa_text_command.call_args == snapshot
@pytest.mark.parametrize(
("sound", "device_id", "translation_key", "translation_placeholders"),
[
(
"bell_02",
"fake_device_id",
"invalid_device_id",
{"device_id": "fake_device_id"},
),
(
"wrong_sound_name",
TEST_DEVICE_1_ID,
"invalid_sound_value",
{
"sound": "wrong_sound_name",
},
),
],
)
async def test_invalid_parameters(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
sound: str,
device_id: str,
translation_key: str,
translation_placeholders: dict[str, str],
) -> None:
"""Test invalid service parameters."""
device_entry = dr.DeviceEntry(
id=TEST_DEVICE_1_ID, identifiers={(DOMAIN, TEST_DEVICE_1_SN)}
)
mock_device_registry(
hass,
{device_entry.id: device_entry},
)
await setup_integration(hass, mock_config_entry)
# Call Service
with pytest.raises(ServiceValidationError) as exc_info:
await hass.services.async_call(
DOMAIN,
"send_sound",
{
ATTR_SOUND: sound,
ATTR_DEVICE_ID: device_id,
},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == translation_key
assert exc_info.value.translation_placeholders == translation_placeholders
@pytest.mark.parametrize(
("info_skill", "device_id", "translation_key", "translation_placeholders"),
[
(
"tell_joke",
"fake_device_id",
"invalid_device_id",
{"device_id": "fake_device_id"},
),
(
"wrong_info_skill_name",
TEST_DEVICE_1_ID,
"invalid_info_skill_value",
{
"info_skill": "wrong_info_skill_name",
},
),
],
)
async def test_invalid_info_skillparameters(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
info_skill: str,
device_id: str,
translation_key: str,
translation_placeholders: dict[str, str],
) -> None:
"""Test invalid info skill service parameters."""
device_entry = dr.DeviceEntry(
id=TEST_DEVICE_1_ID, identifiers={(DOMAIN, TEST_DEVICE_1_SN)}
)
mock_device_registry(
hass,
{device_entry.id: device_entry},
)
await setup_integration(hass, mock_config_entry)
# Call Service
with pytest.raises(ServiceValidationError) as exc_info:
await hass.services.async_call(
DOMAIN,
"send_info_skill",
{
ATTR_INFO_SKILL: info_skill,
ATTR_DEVICE_ID: device_id,
},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == translation_key
assert exc_info.value.translation_placeholders == translation_placeholders
async def test_config_entry_not_loaded(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test config entry not loaded."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, TEST_DEVICE_1_SN)}
)
assert device_entry
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
# Call Service
with pytest.raises(ServiceValidationError) as exc_info:
await hass.services.async_call(
DOMAIN,
"send_sound",
{
ATTR_SOUND: "bell_02",
ATTR_DEVICE_ID: device_entry.id,
},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == "entry_not_loaded"
assert exc_info.value.translation_placeholders == {"entry": mock_config_entry.title}
async def test_invalid_config_entry(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test invalid config entry."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, TEST_DEVICE_1_SN)}
)
assert device_entry
device_entry.config_entries.add("non_existing_entry_id")
await hass.async_block_till_done()
# Call Service
await hass.services.async_call(
DOMAIN,
"send_sound",
{
ATTR_SOUND: "bell_02",
ATTR_DEVICE_ID: device_entry.id,
},
blocking=True,
)
# No exception should be raised
assert mock_amazon_devices_client.call_alexa_sound.call_count == 1
async def test_missing_config_entry(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test missing config entry."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, TEST_DEVICE_1_SN)}
)
assert device_entry
device_entry.config_entries.clear()
# Call Service
with pytest.raises(ServiceValidationError) as exc_info:
await hass.services.async_call(
DOMAIN,
"send_sound",
{
ATTR_SOUND: "bell_02",
ATTR_DEVICE_ID: device_entry.id,
},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == "config_entry_not_found"
assert exc_info.value.translation_placeholders == {"device_id": device_entry.id}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/test_services.py",
"license": "Apache License 2.0",
"lines": 285,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/amberelectric/test_helpers.py | """Test formatters."""
from amberelectric.models.price_descriptor import PriceDescriptor
from homeassistant.components.amberelectric.helpers import normalize_descriptor
def test_normalize_descriptor() -> None:
"""Test normalizing descriptors works correctly."""
assert normalize_descriptor(None) is None
assert normalize_descriptor(PriceDescriptor.NEGATIVE) == "negative"
assert normalize_descriptor(PriceDescriptor.EXTREMELYLOW) == "extremely_low"
assert normalize_descriptor(PriceDescriptor.VERYLOW) == "very_low"
assert normalize_descriptor(PriceDescriptor.LOW) == "low"
assert normalize_descriptor(PriceDescriptor.NEUTRAL) == "neutral"
assert normalize_descriptor(PriceDescriptor.HIGH) == "high"
assert normalize_descriptor(PriceDescriptor.SPIKE) == "spike"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/amberelectric/test_helpers.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/amberelectric/test_services.py | """Test the Amber Service object."""
import re
import pytest
import voluptuous as vol
from homeassistant.components.amberelectric.const import DOMAIN
from homeassistant.components.amberelectric.services import ATTR_CHANNEL_TYPE
from homeassistant.const import ATTR_CONFIG_ENTRY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from . import setup_integration
from .helpers import (
GENERAL_AND_CONTROLLED_SITE_ID,
GENERAL_AND_FEED_IN_SITE_ID,
GENERAL_ONLY_SITE_ID,
)
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_amber_client_forecasts")
async def test_get_general_forecasts(
hass: HomeAssistant,
general_channel_config_entry: MockConfigEntry,
) -> None:
"""Test fetching general forecasts."""
await setup_integration(hass, general_channel_config_entry)
result = await hass.services.async_call(
DOMAIN,
"get_forecasts",
{ATTR_CONFIG_ENTRY_ID: GENERAL_ONLY_SITE_ID, ATTR_CHANNEL_TYPE: "general"},
blocking=True,
return_response=True,
)
assert len(result["forecasts"]) == 3
first = result["forecasts"][0]
assert first["duration"] == 30
assert first["date"] == "2021-09-21"
assert first["nem_date"] == "2021-09-21T09:00:00+10:00"
assert first["per_kwh"] == 0.09
assert first["spot_per_kwh"] == 0.01
assert first["start_time"] == "2021-09-21T08:30:00+10:00"
assert first["end_time"] == "2021-09-21T09:00:00+10:00"
assert first["renewables"] == 50
assert first["spike_status"] == "none"
assert first["descriptor"] == "very_low"
@pytest.mark.usefixtures("mock_amber_client_forecasts")
async def test_get_controlled_load_forecasts(
hass: HomeAssistant,
general_channel_and_controlled_load_config_entry: MockConfigEntry,
) -> None:
"""Test fetching general forecasts."""
await setup_integration(hass, general_channel_and_controlled_load_config_entry)
result = await hass.services.async_call(
DOMAIN,
"get_forecasts",
{
ATTR_CONFIG_ENTRY_ID: GENERAL_AND_CONTROLLED_SITE_ID,
ATTR_CHANNEL_TYPE: "controlled_load",
},
blocking=True,
return_response=True,
)
assert len(result["forecasts"]) == 3
first = result["forecasts"][0]
assert first["duration"] == 30
assert first["date"] == "2021-09-21"
assert first["nem_date"] == "2021-09-21T09:00:00+10:00"
assert first["per_kwh"] == 0.04
assert first["spot_per_kwh"] == 0.01
assert first["start_time"] == "2021-09-21T08:30:00+10:00"
assert first["end_time"] == "2021-09-21T09:00:00+10:00"
assert first["renewables"] == 50
assert first["spike_status"] == "none"
assert first["descriptor"] == "very_low"
@pytest.mark.usefixtures("mock_amber_client_forecasts")
async def test_get_feed_in_forecasts(
hass: HomeAssistant,
general_channel_and_feed_in_config_entry: MockConfigEntry,
) -> None:
"""Test fetching general forecasts."""
await setup_integration(hass, general_channel_and_feed_in_config_entry)
result = await hass.services.async_call(
DOMAIN,
"get_forecasts",
{
ATTR_CONFIG_ENTRY_ID: GENERAL_AND_FEED_IN_SITE_ID,
ATTR_CHANNEL_TYPE: "feed_in",
},
blocking=True,
return_response=True,
)
assert len(result["forecasts"]) == 3
first = result["forecasts"][0]
assert first["duration"] == 30
assert first["date"] == "2021-09-21"
assert first["nem_date"] == "2021-09-21T09:00:00+10:00"
assert first["per_kwh"] == -0.01
assert first["spot_per_kwh"] == 0.01
assert first["start_time"] == "2021-09-21T08:30:00+10:00"
assert first["end_time"] == "2021-09-21T09:00:00+10:00"
assert first["renewables"] == 50
assert first["spike_status"] == "none"
assert first["descriptor"] == "very_low"
@pytest.mark.usefixtures("mock_amber_client_forecasts")
async def test_incorrect_channel_type(
hass: HomeAssistant,
general_channel_config_entry: MockConfigEntry,
) -> None:
"""Test error when the channel type is incorrect."""
await setup_integration(hass, general_channel_config_entry)
with pytest.raises(
vol.error.MultipleInvalid,
match=re.escape(
"value must be one of ['controlled_load', 'feed_in', 'general'] for dictionary value @ data['channel_type']"
),
):
await hass.services.async_call(
DOMAIN,
"get_forecasts",
{
ATTR_CONFIG_ENTRY_ID: GENERAL_ONLY_SITE_ID,
ATTR_CHANNEL_TYPE: "incorrect",
},
blocking=True,
return_response=True,
)
@pytest.mark.usefixtures("mock_amber_client_general_forecasts")
async def test_unavailable_channel_type(
hass: HomeAssistant,
general_channel_config_entry: MockConfigEntry,
) -> None:
"""Test error when the channel type is not found."""
await setup_integration(hass, general_channel_config_entry)
with pytest.raises(
ServiceValidationError, match="There is no controlled_load channel at this site"
):
await hass.services.async_call(
DOMAIN,
"get_forecasts",
{
ATTR_CONFIG_ENTRY_ID: GENERAL_ONLY_SITE_ID,
ATTR_CHANNEL_TYPE: "controlled_load",
},
blocking=True,
return_response=True,
)
@pytest.mark.usefixtures("mock_amber_client_forecasts")
async def test_service_entry_availability(
hass: HomeAssistant,
general_channel_config_entry: MockConfigEntry,
) -> None:
"""Test the services without valid entry."""
general_channel_config_entry.add_to_hass(hass)
mock_config_entry2 = MockConfigEntry(domain=DOMAIN)
mock_config_entry2.add_to_hass(hass)
await hass.config_entries.async_setup(general_channel_config_entry.entry_id)
await hass.async_block_till_done()
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
"get_forecasts",
{
ATTR_CONFIG_ENTRY_ID: mock_config_entry2.entry_id,
ATTR_CHANNEL_TYPE: "general",
},
blocking=True,
return_response=True,
)
assert err.value.translation_key == "service_config_entry_not_loaded"
assert err.value.translation_placeholders["entry_title"] == "Mock Title"
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
"get_forecasts",
{ATTR_CONFIG_ENTRY_ID: "bad-config_id", ATTR_CHANNEL_TYPE: "general"},
blocking=True,
return_response=True,
)
assert err.value.translation_key == "service_config_entry_not_found"
assert err.value.translation_placeholders["entry_id"] == "bad-config_id"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/amberelectric/test_services.py",
"license": "Apache License 2.0",
"lines": 177,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/blue_current/test_switch.py | """The tests for Bluecurrent switches."""
from homeassistant.components.blue_current import CHARGEPOINT_SETTINGS, PLUG_AND_CHARGE
from homeassistant.components.blue_current.const import (
ACTIVITY,
CHARGEPOINT_STATUS,
PUBLIC_CHARGING,
UNAVAILABLE,
)
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_registry import EntityRegistry
from . import DEFAULT_CHARGE_POINT, init_integration
from tests.common import MockConfigEntry
async def test_switches(
hass: HomeAssistant, config_entry: MockConfigEntry, entity_registry: EntityRegistry
) -> None:
"""Test the underlying switches."""
await init_integration(hass, config_entry, Platform.SWITCH)
entity_entries = er.async_entries_for_config_entry(
entity_registry, config_entry.entry_id
)
for switch in entity_entries:
state = hass.states.get(switch.entity_id)
assert state and state.state == STATE_OFF
entry = entity_registry.async_get(switch.entity_id)
assert entry and entry.unique_id == switch.unique_id
async def test_switches_offline(
hass: HomeAssistant, config_entry: MockConfigEntry, entity_registry: EntityRegistry
) -> None:
"""Test if switches are disabled when needed."""
charge_point = DEFAULT_CHARGE_POINT.copy()
charge_point[ACTIVITY] = "offline"
await init_integration(hass, config_entry, Platform.SWITCH, charge_point)
entity_entries = er.async_entries_for_config_entry(
entity_registry, config_entry.entry_id
)
for switch in entity_entries:
state = hass.states.get(switch.entity_id)
assert state and state.state == UNAVAILABLE
entry = entity_registry.async_get(switch.entity_id)
assert entry and entry.entity_id == switch.entity_id
async def test_block_switch_availability(
hass: HomeAssistant, config_entry: MockConfigEntry, entity_registry: EntityRegistry
) -> None:
"""Test if the block switch is unavailable when charging."""
charge_point = DEFAULT_CHARGE_POINT.copy()
charge_point[ACTIVITY] = "charging"
await init_integration(hass, config_entry, Platform.SWITCH, charge_point)
state = hass.states.get("switch.101_block_charge_point")
assert state and state.state == UNAVAILABLE
async def test_toggle(
hass: HomeAssistant, config_entry: MockConfigEntry, entity_registry: EntityRegistry
) -> None:
"""Test the on / off methods and if the switch gets updated."""
await init_integration(hass, config_entry, Platform.SWITCH)
entity_entries = er.async_entries_for_config_entry(
entity_registry, config_entry.entry_id
)
for switch in entity_entries:
state = hass.states.get(switch.entity_id)
assert state and state.state == STATE_OFF
await hass.services.async_call(
"switch",
"turn_on",
{"entity_id": switch.entity_id},
blocking=True,
)
state = hass.states.get(switch.entity_id)
assert state and state.state == STATE_ON
await hass.services.async_call(
"switch",
"turn_off",
{"entity_id": switch.entity_id},
blocking=True,
)
state = hass.states.get(switch.entity_id)
assert state and state.state == STATE_OFF
async def test_setting_change(
hass: HomeAssistant, config_entry: MockConfigEntry, entity_registry: EntityRegistry
) -> None:
"""Test if the state of the switches are updated when an update message from the websocket comes in."""
integration = await init_integration(hass, config_entry, Platform.SWITCH)
client_mock = integration[0]
entity_entries = er.async_entries_for_config_entry(
entity_registry, config_entry.entry_id
)
for switch in entity_entries:
state = hass.states.get(switch.entity_id)
assert state.state == STATE_OFF
await client_mock.update_charge_point(
"101",
CHARGEPOINT_SETTINGS,
{
PLUG_AND_CHARGE: True,
PUBLIC_CHARGING: {"value": False, "permission": "write"},
},
)
charge_cards_only_switch = hass.states.get("switch.101_linked_charging_cards_only")
assert charge_cards_only_switch.state == STATE_ON
plug_and_charge_switch = hass.states.get("switch.101_plug_charge")
assert plug_and_charge_switch.state == STATE_ON
plug_and_charge_switch = hass.states.get("switch.101_block_charge_point")
assert plug_and_charge_switch.state == STATE_OFF
await client_mock.update_charge_point(
"101", CHARGEPOINT_STATUS, {ACTIVITY: UNAVAILABLE}
)
charge_cards_only_switch = hass.states.get("switch.101_linked_charging_cards_only")
assert charge_cards_only_switch.state == STATE_UNAVAILABLE
plug_and_charge_switch = hass.states.get("switch.101_plug_charge")
assert plug_and_charge_switch.state == STATE_UNAVAILABLE
switch = hass.states.get("switch.101_block_charge_point")
assert switch.state == STATE_ON
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/blue_current/test_switch.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/bring/test_services.py | """Test actions of Bring! integration."""
from unittest.mock import AsyncMock
from bring_api import (
ActivityType,
BringActivityResponse,
BringNotificationType,
BringRequestException,
ReactionType,
)
import pytest
from homeassistant.components.bring.const import DOMAIN
from homeassistant.components.bring.services import (
ATTR_REACTION,
SERVICE_ACTIVITY_STREAM_REACTION,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
("reaction", "call_arg"),
[
("drooling", ReactionType.DROOLING),
("heart", ReactionType.HEART),
("monocle", ReactionType.MONOCLE),
("thumbs_up", ReactionType.THUMBS_UP),
],
)
async def test_send_reaction(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
mock_bring_client: AsyncMock,
reaction: str,
call_arg: ReactionType,
) -> None:
"""Test send activity stream reaction."""
bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()
assert bring_config_entry.state is ConfigEntryState.LOADED
await hass.services.async_call(
DOMAIN,
SERVICE_ACTIVITY_STREAM_REACTION,
service_data={
ATTR_ENTITY_ID: "event.einkauf_activities",
ATTR_REACTION: reaction,
},
blocking=True,
)
mock_bring_client.notify.assert_called_once_with(
"e542eef6-dba7-4c31-a52c-29e6ab9d83a5",
BringNotificationType.LIST_ACTIVITY_STREAM_REACTION,
receiver="9a21fdfc-63a4-441a-afc1-ef3030605a9d",
activity="673594a9-f92d-4cb6-adf1-d2f7a83207a4",
activity_type=ActivityType.LIST_ITEMS_CHANGED,
reaction=call_arg,
)
async def test_send_reaction_exception(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
mock_bring_client: AsyncMock,
) -> None:
"""Test send activity stream reaction with exception."""
bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()
assert bring_config_entry.state is ConfigEntryState.LOADED
mock_bring_client.notify.side_effect = BringRequestException
with pytest.raises(HomeAssistantError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_ACTIVITY_STREAM_REACTION,
service_data={
ATTR_ENTITY_ID: "event.einkauf_activities",
ATTR_REACTION: "heart",
},
blocking=True,
)
assert err.value.translation_key == "reaction_request_failed"
@pytest.mark.usefixtures("mock_bring_client")
async def test_send_reaction_config_entry_not_loaded(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
) -> None:
"""Test send activity stream reaction config entry not loaded exception."""
bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()
assert await hass.config_entries.async_unload(bring_config_entry.entry_id)
assert bring_config_entry.state is ConfigEntryState.NOT_LOADED
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_ACTIVITY_STREAM_REACTION,
service_data={
ATTR_ENTITY_ID: "event.einkauf_activities",
ATTR_REACTION: "heart",
},
blocking=True,
)
assert err.value.translation_key == "service_config_entry_not_loaded"
assert err.value.translation_placeholders["entry_title"] == "Mock Title"
@pytest.mark.usefixtures("mock_bring_client")
async def test_send_reaction_unknown_entity(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test send activity stream reaction unknown entity exception."""
bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()
assert bring_config_entry.state is ConfigEntryState.LOADED
entity_registry.async_update_entity(
"event.einkauf_activities", disabled_by=er.RegistryEntryDisabler.USER
)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_ACTIVITY_STREAM_REACTION,
service_data={
ATTR_ENTITY_ID: "event.einkauf_activities",
ATTR_REACTION: "heart",
},
blocking=True,
)
assert err.value.translation_key == "entity_not_found"
assert err.value.translation_placeholders == {
"entity_id": "event.einkauf_activities"
}
async def test_send_reaction_not_found(
hass: HomeAssistant,
bring_config_entry: MockConfigEntry,
mock_bring_client: AsyncMock,
) -> None:
"""Test send activity stream reaction not found validation error."""
mock_bring_client.get_activity.return_value = BringActivityResponse.from_dict(
{"timeline": [], "timestamp": "2025-01-01T03:09:33.036Z", "totalEvents": 0}
)
bring_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(bring_config_entry.entry_id)
await hass.async_block_till_done()
assert bring_config_entry.state is ConfigEntryState.LOADED
with pytest.raises(HomeAssistantError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_ACTIVITY_STREAM_REACTION,
service_data={
ATTR_ENTITY_ID: "event.einkauf_activities",
ATTR_REACTION: "heart",
},
blocking=True,
)
assert err.value.translation_key == "activity_not_found"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/bring/test_services.py",
"license": "Apache License 2.0",
"lines": 156,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/datadog/common.py | """Common helpers for the datetime entity component tests."""
from unittest import mock
MOCK_DATA = {
"host": "localhost",
"port": 8125,
}
MOCK_OPTIONS = {
"prefix": "hass",
"rate": 1,
}
MOCK_CONFIG = {**MOCK_DATA, **MOCK_OPTIONS}
CONNECTION_TEST_METRIC = "connection_test"
def create_mock_state(entity_id, state, attributes=None):
"""Helper to create a mock state object."""
mock_state = mock.MagicMock()
mock_state.entity_id = entity_id
mock_state.state = state
mock_state.domain = entity_id.split(".")[0]
mock_state.attributes = attributes or {}
return mock_state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/datadog/common.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/datadog/test_config_flow.py | """Tests for the Datadog config flow."""
from unittest.mock import MagicMock, patch
from homeassistant.components.datadog.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .common import MOCK_CONFIG, MOCK_DATA, MOCK_OPTIONS
from tests.common import MockConfigEntry
async def test_user_flow_success(hass: HomeAssistant) -> None:
"""Test user-initiated config flow."""
with patch(
"homeassistant.components.datadog.config_flow.DogStatsd"
) as mock_dogstatsd:
mock_instance = MagicMock()
mock_dogstatsd.return_value = mock_instance
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
)
assert result2["title"] == f"Datadog {MOCK_CONFIG['host']}"
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["data"] == MOCK_DATA
assert result2["options"] == MOCK_OPTIONS
async def test_user_flow_retry_after_connection_fail(hass: HomeAssistant) -> None:
"""Test connection failure."""
with patch(
"homeassistant.components.datadog.config_flow.DogStatsd",
side_effect=OSError("Connection failed"),
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "cannot_connect"}
with patch(
"homeassistant.components.datadog.config_flow.DogStatsd",
):
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
)
assert result3["type"] is FlowResultType.CREATE_ENTRY
assert result3["data"] == MOCK_DATA
assert result3["options"] == MOCK_OPTIONS
async def test_user_flow_abort_already_configured_service(
hass: HomeAssistant,
) -> None:
"""Abort user-initiated config flow if the same host/port is already configured."""
existing_entry = MockConfigEntry(
domain=DOMAIN,
data=MOCK_DATA,
options=MOCK_OPTIONS,
)
existing_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=MOCK_CONFIG
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_options_flow_cannot_connect(hass: HomeAssistant) -> None:
"""Test that the options flow shows an error when connection fails."""
mock_entry = MockConfigEntry(
domain=DOMAIN,
data=MOCK_DATA,
options=MOCK_OPTIONS,
)
mock_entry.add_to_hass(hass)
with patch(
"homeassistant.components.datadog.config_flow.DogStatsd",
side_effect=OSError("connection failed"),
):
result = await hass.config_entries.options.async_init(mock_entry.entry_id)
assert result["type"] is FlowResultType.FORM
result2 = await hass.config_entries.options.async_configure(
result["flow_id"], user_input=MOCK_OPTIONS
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "cannot_connect"}
with patch(
"homeassistant.components.datadog.config_flow.DogStatsd",
):
result3 = await hass.config_entries.options.async_configure(
result["flow_id"], user_input=MOCK_OPTIONS
)
assert result3["type"] is FlowResultType.CREATE_ENTRY
assert result3["data"] == MOCK_OPTIONS
async def test_options_flow(hass: HomeAssistant) -> None:
"""Test updating options after setup."""
mock_entry = MockConfigEntry(
domain=DOMAIN,
data=MOCK_DATA,
options=MOCK_OPTIONS,
)
mock_entry.add_to_hass(hass)
new_options = {
"prefix": "updated",
"rate": 5,
}
# OSError Case
with patch(
"homeassistant.components.datadog.config_flow.DogStatsd",
side_effect=OSError,
):
result = await hass.config_entries.options.async_init(mock_entry.entry_id)
assert result["type"] is FlowResultType.FORM
result2 = await hass.config_entries.options.async_configure(
result["flow_id"], user_input=new_options
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "cannot_connect"}
# ValueError Case
with patch(
"homeassistant.components.datadog.config_flow.DogStatsd",
side_effect=ValueError,
):
result = await hass.config_entries.options.async_init(mock_entry.entry_id)
assert result["type"] is FlowResultType.FORM
result2 = await hass.config_entries.options.async_configure(
result["flow_id"], user_input=new_options
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "cannot_connect"}
# Success Case
with patch(
"homeassistant.components.datadog.config_flow.DogStatsd"
) as mock_dogstatsd:
mock_instance = MagicMock()
mock_dogstatsd.return_value = mock_instance
result = await hass.config_entries.options.async_configure(
result["flow_id"], user_input=new_options
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == new_options
mock_instance.increment.assert_called_once_with("connection_test")
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/datadog/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 146,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/downloader/test_services.py | """Test downloader services."""
import asyncio
from contextlib import AbstractContextManager, nullcontext as does_not_raise
import pytest
from requests_mock import Mocker
import voluptuous as vol
from homeassistant.components.downloader.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
@pytest.mark.usefixtures("setup_integration")
@pytest.mark.parametrize(
("subdir", "expected_result"),
[
("test", does_not_raise()),
("test/path", does_not_raise()),
("~test/path", pytest.raises(ServiceValidationError)),
("~/../test/path", pytest.raises(ServiceValidationError)),
("../test/path", pytest.raises(ServiceValidationError)),
(".../test/path", pytest.raises(ServiceValidationError)),
("/test/path", pytest.raises(ServiceValidationError)),
],
)
async def test_download_invalid_subdir(
hass: HomeAssistant,
download_completed: asyncio.Event,
download_failed: asyncio.Event,
download_url: str,
subdir: str,
expected_result: AbstractContextManager,
) -> None:
"""Test service invalid subdirectory."""
async def call_service() -> None:
"""Call the download service."""
completed = hass.async_create_task(download_completed.wait())
failed = hass.async_create_task(download_failed.wait())
await hass.services.async_call(
DOMAIN,
"download_file",
{
"url": download_url,
"subdir": subdir,
"filename": "file.txt",
"overwrite": True,
},
blocking=True,
)
await asyncio.wait((completed, failed), return_when=asyncio.FIRST_COMPLETED)
with expected_result:
await call_service()
@pytest.mark.usefixtures("setup_integration")
async def test_download_headers_passed_through(
hass: HomeAssistant,
requests_mock: Mocker,
download_completed: asyncio.Event,
download_url: str,
) -> None:
"""Test that custom headers are passed to the HTTP request."""
await hass.services.async_call(
DOMAIN,
"download_file",
{
"url": download_url,
"headers": {"Authorization": "Bearer token123", "X-Custom": "value"},
},
blocking=True,
)
await download_completed.wait()
assert requests_mock.last_request.headers["Authorization"] == "Bearer token123"
assert requests_mock.last_request.headers["X-Custom"] == "value"
@pytest.mark.usefixtures("setup_integration")
@pytest.mark.parametrize(
("headers", "expected_result"),
[
(1, pytest.raises(vol.error.Invalid)), # Not a dictionary
({"Accept": "application/json"}, does_not_raise()),
({123: 456.789}, does_not_raise()), # Convert numbers to strings
(
{"Accept": ["application/json"]},
pytest.raises(vol.error.MultipleInvalid),
), # Value is not a string
({1: None}, pytest.raises(vol.error.MultipleInvalid)), # Value is None
(
{None: "application/json"},
pytest.raises(vol.error.MultipleInvalid),
), # Key is None
],
)
async def test_download_headers_schema(
hass: HomeAssistant,
download_completed: asyncio.Event,
download_failed: asyncio.Event,
download_url: str,
headers: dict[str, str],
expected_result: AbstractContextManager,
) -> None:
"""Test service with headers."""
async def call_service() -> None:
"""Call the download service."""
completed = hass.async_create_task(download_completed.wait())
failed = hass.async_create_task(download_failed.wait())
await hass.services.async_call(
DOMAIN,
"download_file",
{
"url": download_url,
"headers": headers,
"subdir": "test",
"filename": "file.txt",
"overwrite": True,
},
blocking=True,
)
await asyncio.wait((completed, failed), return_when=asyncio.FIRST_COMPLETED)
with expected_result:
await call_service()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/downloader/test_services.py",
"license": "Apache License 2.0",
"lines": 115,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/esphome/test_dynamic_encryption.py | """Tests for ESPHome dynamic encryption key generation."""
from __future__ import annotations
import base64
from homeassistant.components.esphome.encryption_key_storage import (
ESPHomeEncryptionKeyStorage,
async_get_encryption_key_storage,
)
from homeassistant.core import HomeAssistant
async def test_dynamic_encryption_key_generation_mock(hass: HomeAssistant) -> None:
"""Test that encryption key generation works with mocked storage."""
storage = await async_get_encryption_key_storage(hass)
# Store a key
mac_address = "11:22:33:44:55:aa"
test_key = base64.b64encode(b"test_key_32_bytes_long_exactly!").decode()
await storage.async_store_key(mac_address, test_key)
# Retrieve a key
retrieved_key = await storage.async_get_key(mac_address)
assert retrieved_key == test_key
async def test_encryption_key_storage_remove_key(hass: HomeAssistant) -> None:
"""Test ESPHomeEncryptionKeyStorage async_remove_key method."""
# Create storage instance
storage = ESPHomeEncryptionKeyStorage(hass)
# Test removing a key that exists
mac_address = "11:22:33:44:55:aa"
test_key = "test_encryption_key_32_bytes_long"
# First store a key
await storage.async_store_key(mac_address, test_key)
# Verify key exists
retrieved_key = await storage.async_get_key(mac_address)
assert retrieved_key == test_key
# Remove the key
await storage.async_remove_key(mac_address)
# Verify key no longer exists
retrieved_key = await storage.async_get_key(mac_address)
assert retrieved_key is None
# Test removing a key that doesn't exist (should not raise an error)
non_existent_mac = "aa:bb:cc:dd:ee:ff"
await storage.async_remove_key(non_existent_mac) # Should not raise
# Test case insensitive removal
upper_mac = "22:33:44:55:66:77"
await storage.async_store_key(upper_mac, test_key)
# Remove using lowercase MAC address
await storage.async_remove_key(upper_mac.lower())
# Verify key was removed
retrieved_key = await storage.async_get_key(upper_mac)
assert retrieved_key is None
async def test_encryption_key_basic_storage(
hass: HomeAssistant,
) -> None:
"""Test basic encryption key storage functionality."""
storage = await async_get_encryption_key_storage(hass)
mac_address = "11:22:33:44:55:aa"
key = "test_encryption_key_32_bytes_long"
# Store key
await storage.async_store_key(mac_address, key)
# Retrieve key
retrieved_key = await storage.async_get_key(mac_address)
assert retrieved_key == key
async def test_retrieve_key_from_storage(
hass: HomeAssistant,
) -> None:
"""Test config flow can retrieve encryption key from storage for new device."""
# Test that the encryption key storage integration works with config flow
storage = await async_get_encryption_key_storage(hass)
mac_address = "11:22:33:44:55:aa"
stored_key = "test_encryption_key_32_bytes_long"
# Store encryption key for a device
await storage.async_store_key(mac_address, stored_key)
# Verify the key can be retrieved (simulating config flow behavior)
retrieved_key = await storage.async_get_key(mac_address)
assert retrieved_key == stored_key
# Test case insensitive retrieval (since config flows might use different case)
retrieved_key_upper = await storage.async_get_key(mac_address.upper())
assert retrieved_key_upper == stored_key
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/esphome/test_dynamic_encryption.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/google_assistant_sdk/test_application_credentials.py | """Test the Google Assistant SDK application_credentials."""
import pytest
from homeassistant import setup
from homeassistant.components.google_assistant_sdk.application_credentials import (
async_get_description_placeholders,
)
from homeassistant.core import HomeAssistant
@pytest.mark.parametrize(
("additional_components", "external_url", "expected_redirect_uri"),
[
([], "https://example.com", "https://example.com/auth/external/callback"),
([], None, "https://YOUR_DOMAIN:PORT/auth/external/callback"),
(["my"], "https://example.com", "https://my.home-assistant.io/redirect/oauth"),
],
)
async def test_description_placeholders(
hass: HomeAssistant,
additional_components: list[str],
external_url: str | None,
expected_redirect_uri: str,
) -> None:
"""Test description placeholders."""
for component in additional_components:
assert await setup.async_setup_component(hass, component, {})
hass.config.external_url = external_url
placeholders = await async_get_description_placeholders(hass)
assert placeholders == {
"oauth_consent_url": "https://console.cloud.google.com/apis/credentials/consent",
"more_info_url": "https://www.home-assistant.io/integrations/google_assistant_sdk/",
"oauth_creds_url": "https://console.cloud.google.com/apis/credentials",
"redirect_url": expected_redirect_uri,
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_assistant_sdk/test_application_credentials.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/google_generative_ai_conversation/test_ai_task.py | """Test AI Task platform of Google Generative AI Conversation integration."""
from pathlib import Path
from unittest.mock import AsyncMock, Mock, patch
from google.genai.types import File, FileState, GenerateContentResponse
import pytest
import voluptuous as vol
from homeassistant.components import ai_task, media_source
from homeassistant.components.google_generative_ai_conversation.const import (
RECOMMENDED_IMAGE_MODEL,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er, selector
from tests.common import MockConfigEntry
from tests.components.conversation import (
MockChatLog,
mock_chat_log, # noqa: F401
)
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_chat_log: MockChatLog, # noqa: F811
mock_send_message_stream: AsyncMock,
mock_chat_create: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test generating data."""
entity_id = "ai_task.google_ai_task"
# Ensure it's linked to the subentry
entity_entry = entity_registry.async_get(entity_id)
ai_task_entry = next(
iter(
entry
for entry in mock_config_entry.subentries.values()
if entry.subentry_type == "ai_task_data"
)
)
assert entity_entry.config_entry_id == mock_config_entry.entry_id
assert entity_entry.config_subentry_id == ai_task_entry.subentry_id
mock_send_message_stream.return_value = [
[
GenerateContentResponse(
candidates=[
{
"content": {
"parts": [{"text": "Hi there!"}],
"role": "model",
},
}
],
),
],
]
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Test prompt",
)
assert result.data == "Hi there!"
# Test with attachments
mock_send_message_stream.return_value = [
[
GenerateContentResponse(
candidates=[
{
"content": {
"parts": [{"text": "Hi there!"}],
"role": "model",
},
}
],
),
],
]
file1 = File(name="doorbell_snapshot.jpg", state=FileState.ACTIVE)
file2 = File(name="context.txt", state=FileState.ACTIVE)
with (
patch(
"homeassistant.components.media_source.async_resolve_media",
side_effect=[
media_source.PlayMedia(
url="http://example.com/doorbell_snapshot.jpg",
mime_type="image/jpeg",
path=Path("doorbell_snapshot.jpg"),
),
media_source.PlayMedia(
url="http://example.com/context.txt",
mime_type="text/plain",
path=Path("context.txt"),
),
],
),
patch(
"google.genai.files.Files.upload",
side_effect=[file1, file2],
) as mock_upload,
patch("pathlib.Path.exists", return_value=True),
patch.object(hass.config, "is_allowed_path", return_value=True),
patch("mimetypes.guess_type", return_value=["image/jpeg"]),
):
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Test prompt",
attachments=[
{"media_content_id": "media-source://media/doorbell_snapshot.jpg"},
{"media_content_id": "media-source://media/context.txt"},
],
)
outgoing_message = mock_send_message_stream.mock_calls[1][2]["message"]
assert outgoing_message == ["Test prompt", file1, file2]
assert result.data == "Hi there!"
assert len(mock_upload.mock_calls) == 2
assert mock_upload.mock_calls[0][2]["file"] == Path("doorbell_snapshot.jpg")
assert mock_upload.mock_calls[1][2]["file"] == Path("context.txt")
# Test attachments require play media with a path
with (
patch(
"homeassistant.components.media_source.async_resolve_media",
side_effect=[
media_source.PlayMedia(
url="http://example.com/doorbell_snapshot.jpg",
mime_type="image/jpeg",
path=None,
),
],
),
pytest.raises(
HomeAssistantError, match="Only local attachments are currently supported"
),
):
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Test prompt",
attachments=[
{"media_content_id": "media-source://media/doorbell_snapshot.jpg"},
],
)
# Test with structure
mock_send_message_stream.return_value = [
[
GenerateContentResponse(
candidates=[
{
"content": {
"parts": [{"text": '{"characters": ["Mario", "Luigi"]}'}],
"role": "model",
},
}
],
),
],
]
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Give me 2 mario characters",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
assert result.data == {"characters": ["Mario", "Luigi"]}
assert len(mock_chat_create.mock_calls) == 3
config = mock_chat_create.mock_calls[-1][2]["config"]
assert config.response_mime_type == "application/json"
assert config.response_schema == {
"properties": {"characters": {"items": {"type": "STRING"}, "type": "ARRAY"}},
"required": ["characters"],
"type": "OBJECT",
}
# Raise error on invalid JSON response
mock_send_message_stream.return_value = [
[
GenerateContentResponse(
candidates=[
{
"content": {
"parts": [{"text": "INVALID JSON RESPONSE"}],
"role": "model",
},
}
],
),
],
]
with pytest.raises(HomeAssistantError):
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Test prompt",
structure=vol.Schema({vol.Required("bla"): str}),
)
@pytest.mark.usefixtures("mock_init_component")
@pytest.mark.freeze_time("2025-06-14 22:59:00")
async def test_generate_image(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_generate_content: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task image generation."""
mock_image_data = b"fake_image_data"
mock_generate_content.return_value = Mock(
text="Here is your generated image",
prompt_feedback=None,
candidates=[
Mock(
content=Mock(
parts=[
Mock(
text="Here is your generated image",
inline_data=None,
thought=False,
),
Mock(
inline_data=Mock(
data=mock_image_data, mime_type="image/png"
),
text=None,
thought=False,
),
]
)
)
],
)
with patch.object(
media_source.local_source.LocalSource,
"async_upload_media",
return_value="media-source://ai_task/image/2025-06-14_225900_test_task.png",
) as mock_upload_media:
result = await ai_task.async_generate_image(
hass,
task_name="Test Task",
entity_id="ai_task.google_ai_task",
instructions="Generate a test image",
)
assert result["height"] is None
assert result["width"] is None
assert result["revised_prompt"] == "Generate a test image"
assert result["mime_type"] == "image/png"
assert result["model"] == RECOMMENDED_IMAGE_MODEL.partition("/")[-1]
mock_upload_media.assert_called_once()
image_data = mock_upload_media.call_args[0][1]
assert image_data.file.getvalue() == mock_image_data
assert image_data.content_type == "image/png"
assert image_data.filename == "2025-06-14_225900_test_task.png"
# Verify that generate_content was called with correct parameters
assert mock_generate_content.called
call_args = mock_generate_content.call_args
assert call_args.kwargs["model"] == RECOMMENDED_IMAGE_MODEL
assert call_args.kwargs["contents"] == ["Generate a test image"]
assert call_args.kwargs["config"].response_modalities == ["TEXT", "IMAGE"]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_generative_ai_conversation/test_ai_task.py",
"license": "Apache License 2.0",
"lines": 268,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_generative_ai_conversation/test_stt.py | """Tests for the Google Generative AI Conversation STT entity."""
from __future__ import annotations
from collections.abc import AsyncIterable, Generator
from unittest.mock import AsyncMock, Mock, patch
from google.genai import types
import pytest
from homeassistant.components import stt
from homeassistant.components.google_generative_ai_conversation.const import (
CONF_CHAT_MODEL,
CONF_PROMPT,
DEFAULT_STT_PROMPT,
DOMAIN,
RECOMMENDED_STT_MODEL,
)
from homeassistant.config_entries import ConfigSubentry
from homeassistant.const import CONF_API_KEY
from homeassistant.core import HomeAssistant
from . import API_ERROR_500, CLIENT_ERROR_BAD_REQUEST
from tests.common import MockConfigEntry
TEST_CHAT_MODEL = "models/gemini-2.5-flash"
TEST_PROMPT = "Please transcribe the audio."
async def _async_get_audio_stream(data: bytes) -> AsyncIterable[bytes]:
"""Yield the audio data."""
yield data
@pytest.fixture
def mock_genai_client() -> Generator[AsyncMock]:
"""Mock genai.Client."""
client = Mock()
client.aio.models.get = AsyncMock()
client.aio.models.generate_content = AsyncMock(
return_value=types.GenerateContentResponse(
candidates=[
{
"content": {
"parts": [{"text": "This is a test transcription."}],
"role": "model",
}
}
]
)
)
with patch(
"homeassistant.components.google_generative_ai_conversation.Client",
return_value=client,
) as mock_client:
yield mock_client.return_value
@pytest.fixture
async def setup_integration(
hass: HomeAssistant,
mock_genai_client: AsyncMock,
) -> None:
"""Set up the test environment."""
config_entry = MockConfigEntry(
domain=DOMAIN, data={CONF_API_KEY: "bla"}, version=2, minor_version=1
)
config_entry.add_to_hass(hass)
sub_entry = ConfigSubentry(
data={
CONF_CHAT_MODEL: TEST_CHAT_MODEL,
CONF_PROMPT: TEST_PROMPT,
},
subentry_type="stt",
title="Google AI STT",
unique_id=None,
)
config_entry.runtime_data = mock_genai_client
hass.config_entries.async_add_subentry(config_entry, sub_entry)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
@pytest.mark.usefixtures("setup_integration")
async def test_stt_entity_properties(hass: HomeAssistant) -> None:
"""Test STT entity properties."""
entity: stt.SpeechToTextEntity = hass.data[stt.DOMAIN].get_entity(
"stt.google_ai_stt"
)
assert entity is not None
assert isinstance(entity.supported_languages, list)
assert stt.AudioFormats.WAV in entity.supported_formats
assert stt.AudioFormats.OGG in entity.supported_formats
assert stt.AudioCodecs.PCM in entity.supported_codecs
assert stt.AudioCodecs.OPUS in entity.supported_codecs
assert stt.AudioBitRates.BITRATE_16 in entity.supported_bit_rates
assert stt.AudioSampleRates.SAMPLERATE_16000 in entity.supported_sample_rates
assert stt.AudioChannels.CHANNEL_MONO in entity.supported_channels
@pytest.mark.parametrize(
("audio_format", "call_convert_to_wav"),
[
(stt.AudioFormats.WAV, True),
(stt.AudioFormats.OGG, False),
],
)
@pytest.mark.usefixtures("setup_integration")
async def test_stt_process_audio_stream_success(
hass: HomeAssistant,
mock_genai_client: AsyncMock,
audio_format: stt.AudioFormats,
call_convert_to_wav: bool,
) -> None:
"""Test STT processing audio stream successfully."""
entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt")
metadata = stt.SpeechMetadata(
language="en-US",
format=audio_format,
codec=stt.AudioCodecs.PCM,
bit_rate=stt.AudioBitRates.BITRATE_16,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
)
audio_stream = _async_get_audio_stream(b"test_audio_bytes")
with patch(
"homeassistant.components.google_generative_ai_conversation.stt.convert_to_wav",
return_value=b"converted_wav_bytes",
) as mock_convert_to_wav:
result = await entity.async_process_audio_stream(metadata, audio_stream)
assert result.result == stt.SpeechResultState.SUCCESS
assert result.text == "This is a test transcription."
if call_convert_to_wav:
mock_convert_to_wav.assert_called_once_with(
b"test_audio_bytes", "audio/L16;rate=16000"
)
else:
mock_convert_to_wav.assert_not_called()
mock_genai_client.aio.models.generate_content.assert_called_once()
call_args = mock_genai_client.aio.models.generate_content.call_args
assert call_args.kwargs["model"] == TEST_CHAT_MODEL
contents = call_args.kwargs["contents"]
assert contents[0] == TEST_PROMPT
assert isinstance(contents[1], types.Part)
assert contents[1].inline_data.mime_type == f"audio/{audio_format.value}"
if call_convert_to_wav:
assert contents[1].inline_data.data == b"converted_wav_bytes"
else:
assert contents[1].inline_data.data == b"test_audio_bytes"
@pytest.mark.parametrize(
"side_effect",
[
API_ERROR_500,
CLIENT_ERROR_BAD_REQUEST,
ValueError("Test value error"),
],
)
@pytest.mark.usefixtures("setup_integration")
async def test_stt_process_audio_stream_api_error(
hass: HomeAssistant,
mock_genai_client: AsyncMock,
side_effect: Exception,
) -> None:
"""Test STT processing audio stream with API errors."""
entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt")
mock_genai_client.aio.models.generate_content.side_effect = side_effect
metadata = stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.OGG,
codec=stt.AudioCodecs.OPUS,
bit_rate=stt.AudioBitRates.BITRATE_16,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
)
audio_stream = _async_get_audio_stream(b"test_audio_bytes")
result = await entity.async_process_audio_stream(metadata, audio_stream)
assert result.result == stt.SpeechResultState.ERROR
assert result.text is None
@pytest.mark.usefixtures("setup_integration")
async def test_stt_process_audio_stream_empty_response(
hass: HomeAssistant,
mock_genai_client: AsyncMock,
) -> None:
"""Test STT processing with an empty response from the API."""
entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt")
mock_genai_client.aio.models.generate_content.return_value = (
types.GenerateContentResponse(candidates=[])
)
metadata = stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.OGG,
codec=stt.AudioCodecs.OPUS,
bit_rate=stt.AudioBitRates.BITRATE_16,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
)
audio_stream = _async_get_audio_stream(b"test_audio_bytes")
result = await entity.async_process_audio_stream(metadata, audio_stream)
assert result.result == stt.SpeechResultState.ERROR
assert result.text is None
@pytest.mark.usefixtures("mock_genai_client")
async def test_stt_uses_default_prompt(
hass: HomeAssistant,
mock_genai_client: AsyncMock,
) -> None:
"""Test that the default prompt is used if none is configured."""
config_entry = MockConfigEntry(
domain=DOMAIN, data={CONF_API_KEY: "bla"}, version=2, minor_version=1
)
config_entry.add_to_hass(hass)
config_entry.runtime_data = mock_genai_client
# Subentry with no prompt
sub_entry = ConfigSubentry(
data={CONF_CHAT_MODEL: TEST_CHAT_MODEL},
subentry_type="stt",
title="Google AI STT",
unique_id=None,
)
hass.config_entries.async_add_subentry(config_entry, sub_entry)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt")
metadata = stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.OGG,
codec=stt.AudioCodecs.OPUS,
bit_rate=stt.AudioBitRates.BITRATE_16,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
)
audio_stream = _async_get_audio_stream(b"test_audio_bytes")
await entity.async_process_audio_stream(metadata, audio_stream)
call_args = mock_genai_client.aio.models.generate_content.call_args
contents = call_args.kwargs["contents"]
assert contents[0] == DEFAULT_STT_PROMPT
@pytest.mark.usefixtures("mock_genai_client")
async def test_stt_uses_default_model(
hass: HomeAssistant,
mock_genai_client: AsyncMock,
) -> None:
"""Test that the default model is used if none is configured."""
config_entry = MockConfigEntry(
domain=DOMAIN, data={CONF_API_KEY: "bla"}, version=2, minor_version=1
)
config_entry.add_to_hass(hass)
config_entry.runtime_data = mock_genai_client
# Subentry with no model
sub_entry = ConfigSubentry(
data={CONF_PROMPT: TEST_PROMPT},
subentry_type="stt",
title="Google AI STT",
unique_id=None,
)
hass.config_entries.async_add_subentry(config_entry, sub_entry)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt")
metadata = stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.OGG,
codec=stt.AudioCodecs.OPUS,
bit_rate=stt.AudioBitRates.BITRATE_16,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
)
audio_stream = _async_get_audio_stream(b"test_audio_bytes")
await entity.async_process_audio_stream(metadata, audio_stream)
call_args = mock_genai_client.aio.models.generate_content.call_args
assert call_args.kwargs["model"] == RECOMMENDED_STT_MODEL
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_generative_ai_conversation/test_stt.py",
"license": "Apache License 2.0",
"lines": 253,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homee/test_init.py | """Test Homee initialization."""
from unittest.mock import MagicMock
from pyHomee import HomeeAuthFailedException, HomeeConnectionFailedException
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.homee.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from . import build_mock_node, setup_integration
from .conftest import HOMEE_ID
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
("side_eff", "config_entry_state", "active_flows"),
[
(
HomeeConnectionFailedException("connection timed out"),
ConfigEntryState.SETUP_RETRY,
[],
),
(
HomeeAuthFailedException("wrong username or password"),
ConfigEntryState.SETUP_ERROR,
["reauth"],
),
],
)
async def test_connection_errors(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
side_eff: Exception,
config_entry_state: ConfigEntryState,
active_flows: list[str],
) -> None:
"""Test if connection errors on startup are handled correctly."""
mock_homee.get_access_token.side_effect = side_eff
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is config_entry_state
assert [
flow["context"]["source"] for flow in hass.config_entries.flow.async_progress()
] == active_flows
async def test_connection_listener(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test if loss of connection is sensed correctly."""
mock_homee.nodes = [build_mock_node("homee.json")]
mock_homee.get_node_by_id.return_value = mock_homee.nodes[0]
await setup_integration(hass, mock_config_entry)
await mock_homee.add_connection_listener.call_args_list[0][0][0](False)
await hass.async_block_till_done()
assert "Disconnected from Homee" in caplog.text
await mock_homee.add_connection_listener.call_args_list[0][0][0](True)
await hass.async_block_till_done()
assert "Reconnected to Homee" in caplog.text
async def test_general_data(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test if data is set correctly."""
mock_homee.nodes = [
build_mock_node("cover_with_position_slats.json"),
build_mock_node("homee.json"),
]
mock_homee.get_node_by_id = lambda node_id: (
mock_homee.nodes[0] if node_id == 3 else mock_homee.nodes[1]
)
await setup_integration(hass, mock_config_entry)
# Verify hub and device created correctly using snapshots.
hub = device_registry.async_get_device(identifiers={(DOMAIN, f"{HOMEE_ID}")})
device = device_registry.async_get_device(identifiers={(DOMAIN, f"{HOMEE_ID}-3")})
assert hub == snapshot
assert device == snapshot
async def test_software_version(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test sw_version for device with only AttributeType.SOFTWARE_VERSION."""
mock_homee.nodes = [build_mock_node("cover_without_position.json")]
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, f"{HOMEE_ID}-3")})
assert device.sw_version == "1.45"
async def test_invalid_profile(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test unknown value passed to get_name_for_enum."""
mock_homee.nodes = [build_mock_node("cover_without_position.json")]
# This is a profile, that does not exist in the enum.
mock_homee.nodes[0].profile = 77
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, f"{HOMEE_ID}-3")})
assert device.model is None
async def test_unload_entry(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test unloading of config entry."""
mock_homee.nodes = [build_mock_node("cover_with_position_slats.json")]
mock_homee.get_node_by_id.return_value = mock_homee.nodes[0]
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
async def test_remove_stale_device_on_startup(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test removal of stale device on startup."""
mock_homee.nodes = [
build_mock_node("homee.json"),
build_mock_node("light_single.json"), # id 2
build_mock_node("add_device.json"), # id 3
]
mock_homee.get_node_by_id = lambda node_id: mock_homee.nodes[node_id - 1]
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, f"{HOMEE_ID}-3")})
assert device is not None
mock_homee.nodes.pop() # Remove node with id 3
# Reload integration
await hass.config_entries.async_reload(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Stale device should be removed
device = device_registry.async_get_device(identifiers={(DOMAIN, f"{HOMEE_ID}-3")})
assert device is None
async def test_remove_node_callback(
hass: HomeAssistant,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test removal of device when node is removed in homee."""
mock_homee.nodes = [
build_mock_node("homee.json"),
build_mock_node("light_single.json"), # id 2
build_mock_node("add_device.json"), # id 3
]
mock_homee.get_node_by_id = lambda node_id: mock_homee.nodes[node_id - 1]
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, f"{HOMEE_ID}-3")})
assert device is not None
# Test device not removed when callback called with add=True
await mock_homee.add_nodes_listener.call_args_list[0][0][0](
mock_homee.nodes[2], add=True
)
await hass.async_block_till_done()
device = device_registry.async_get_device(identifiers={(DOMAIN, f"{HOMEE_ID}-3")})
assert device is not None
# Simulate removal of node with id 3 in homee
await mock_homee.add_nodes_listener.call_args_list[0][0][0](
mock_homee.nodes[2], add=False
)
await hass.async_block_till_done()
# Device should be removed
device = device_registry.async_get_device(identifiers={(DOMAIN, f"{HOMEE_ID}-3")})
assert device is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homee/test_init.py",
"license": "Apache License 2.0",
"lines": 171,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homematicip_cloud/test_valve.py | """Test HomematicIP Cloud valve entities."""
from homeassistant.components.valve import (
DOMAIN as VALVE_DOMAIN,
SERVICE_OPEN_VALVE,
ValveState,
)
from homeassistant.core import HomeAssistant
from .helper import HomeFactory, async_manipulate_test_data, get_and_check_entity_basics
async def test_watering_valve(
hass: HomeAssistant, default_mock_hap_factory: HomeFactory
) -> None:
"""Test HomematicIP watering valve."""
entity_id = "valve.bewaesserungsaktor_watering"
entity_name = "Bewaesserungsaktor watering"
device_model = "ELV-SH-WSM"
mock_hap = await default_mock_hap_factory.async_get_mock_hap(
test_devices=["Bewaesserungsaktor"]
)
ha_state, hmip_device = get_and_check_entity_basics(
hass, mock_hap, entity_id, entity_name, device_model
)
assert ha_state.state == ValveState.CLOSED
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_OPEN_VALVE, {"entity_id": entity_id}, blocking=True
)
await async_manipulate_test_data(
hass, hmip_device, "wateringActive", True, channel=1
)
ha_state = hass.states.get(entity_id)
assert ha_state.state == ValveState.OPEN
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homematicip_cloud/test_valve.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/huawei_lte/test_diagnostics.py | """Test huawei_lte diagnostics."""
from unittest.mock import MagicMock, patch
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.components.huawei_lte.const import DOMAIN
from homeassistant.const import CONF_URL
from homeassistant.core import HomeAssistant
from . import magic_client
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry diagnostics."""
huawei_lte = MockConfigEntry(
domain=DOMAIN, data={CONF_URL: "http://huawei-lte.example.com"}
)
huawei_lte.add_to_hass(hass)
with (
patch("homeassistant.components.huawei_lte.Connection", MagicMock()),
patch(
"homeassistant.components.huawei_lte.Client", return_value=magic_client()
),
):
await hass.config_entries.async_setup(huawei_lte.entry_id)
await hass.async_block_till_done()
result = await get_diagnostics_for_config_entry(hass, hass_client, huawei_lte)
assert result == snapshot(exclude=props("entry_id", "created_at", "modified_at"))
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/huawei_lte/test_diagnostics.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/husqvarna_automower_ble/test_sensor.py | """Test the Husqvarna Automower Bluetooth setup."""
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
pytestmark = pytest.mark.usefixtures("mock_automower_client")
async def test_setup(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test setup creates expected entities."""
with patch(
"homeassistant.components.husqvarna_automower_ble.PLATFORMS", [Platform.SENSOR]
):
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/husqvarna_automower_ble/test_sensor.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/huum/test_binary_sensor.py | """Tests for the Huum climate 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
ENTITY_ID = "binary_sensor.huum_sauna_door"
async def test_binary_sensor(
hass: HomeAssistant,
mock_huum: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the initial parameters."""
await setup_with_selected_platforms(
hass, mock_config_entry, [Platform.BINARY_SENSOR]
)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/huum/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/huum/test_climate.py | """Tests for the Huum climate entity."""
from unittest.mock import AsyncMock
from huum.const import SaunaStatus
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.climate import (
ATTR_HVAC_MODE,
DOMAIN as CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_TEMPERATURE,
HVACMode,
)
from homeassistant.components.huum.const import (
CONFIG_DEFAULT_MAX_TEMP,
CONFIG_DEFAULT_MIN_TEMP,
)
from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, 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
ENTITY_ID = "climate.huum_sauna"
async def test_climate_entity(
hass: HomeAssistant,
mock_huum: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the initial parameters."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.CLIMATE])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_set_hvac_mode(
hass: HomeAssistant,
mock_huum: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setting HVAC mode."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.CLIMATE])
mock_huum.status = SaunaStatus.ONLINE_HEATING
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_HVAC_MODE: HVACMode.HEAT},
blocking=True,
)
state = hass.states.get(ENTITY_ID)
assert state.state == HVACMode.HEAT
mock_huum.turn_on.assert_called_once()
async def test_set_temperature(
hass: HomeAssistant,
mock_huum: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setting the temperature."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.CLIMATE])
mock_huum.status = SaunaStatus.ONLINE_HEATING
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: ENTITY_ID,
ATTR_TEMPERATURE: 60,
},
blocking=True,
)
mock_huum.turn_on.assert_called_once_with(60)
async def test_temperature_range(
hass: HomeAssistant,
mock_huum: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the temperature range."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.CLIMATE])
# API response.
state = hass.states.get(ENTITY_ID)
assert state.attributes["min_temp"] == 40
assert state.attributes["max_temp"] == 110
# Empty/unconfigured API response should return default values.
mock_huum.sauna_config.min_temp = 0
mock_huum.sauna_config.max_temp = 0
await mock_config_entry.runtime_data.async_refresh()
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state.attributes["min_temp"] == CONFIG_DEFAULT_MIN_TEMP
assert state.attributes["max_temp"] == CONFIG_DEFAULT_MAX_TEMP
# Custom configured API response.
mock_huum.sauna_config.min_temp = 50
mock_huum.sauna_config.max_temp = 80
await mock_config_entry.runtime_data.async_refresh()
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state.attributes["min_temp"] == 50
assert state.attributes["max_temp"] == 80
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/huum/test_climate.py",
"license": "Apache License 2.0",
"lines": 93,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/huum/test_init.py | """Tests for the Huum __init__."""
from unittest.mock import AsyncMock
from homeassistant.components.huum.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from . import setup_with_selected_platforms
from tests.common import MockConfigEntry
async def test_loading_and_unloading_config_entry(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_huum: AsyncMock
) -> None:
"""Test loading and unloading a config entry."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.CLIMATE])
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert mock_config_entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/huum/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/huum/test_light.py | """Tests for the Huum light entity."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_with_selected_platforms
from tests.common import MockConfigEntry, snapshot_platform
ENTITY_ID = "light.huum_sauna_light"
async def test_light(
hass: HomeAssistant,
mock_huum: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the initial parameters."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.LIGHT])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_light_turn_off(
hass: HomeAssistant,
mock_huum: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test turning off light."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.LIGHT])
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_ON
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
mock_huum.toggle_light.assert_called_once()
async def test_light_turn_on(
hass: HomeAssistant,
mock_huum: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test turning on light."""
mock_huum.light = 0
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.LIGHT])
state = hass.states.get(ENTITY_ID)
assert state.state == STATE_OFF
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
mock_huum.toggle_light.assert_called_once()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/huum/test_light.py",
"license": "Apache License 2.0",
"lines": 60,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/immich/test_services.py | """Test the Immich services."""
from unittest.mock import Mock, patch
from aioimmich.exceptions import ImmichError, ImmichNotFoundError
import pytest
from homeassistant.components.immich.const import DOMAIN
from homeassistant.components.immich.services import SERVICE_UPLOAD_FILE
from homeassistant.components.media_source import PlayMedia
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry
async def test_setup_services(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setup of immich services."""
await setup_integration(hass, mock_config_entry)
services = hass.services.async_services_for_domain(DOMAIN)
assert services
assert SERVICE_UPLOAD_FILE in services
async def test_upload_file(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
mock_media_source: Mock,
) -> None:
"""Test upload_file service."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
DOMAIN,
SERVICE_UPLOAD_FILE,
{
"config_entry_id": mock_config_entry.entry_id,
"file": {
"media_content_id": "media-source://media_source/local/screenshot.jpg",
"media_content_type": "image/jpeg",
},
},
blocking=True,
)
mock_immich.assets.async_upload_asset.assert_called_with("/media/screenshot.jpg")
mock_immich.albums.async_get_album_info.assert_not_called()
mock_immich.albums.async_add_assets_to_album.assert_not_called()
async def test_upload_file_to_album(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
mock_media_source: Mock,
) -> None:
"""Test upload_file service with target album_id."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
DOMAIN,
SERVICE_UPLOAD_FILE,
{
"config_entry_id": mock_config_entry.entry_id,
"file": {
"media_content_id": "media-source://media_source/local/screenshot.jpg",
"media_content_type": "image/jpeg",
},
"album_id": "721e1a4b-aa12-441e-8d3b-5ac7ab283bb6",
},
blocking=True,
)
mock_immich.assets.async_upload_asset.assert_called_with("/media/screenshot.jpg")
mock_immich.albums.async_get_album_info.assert_called_with(
"721e1a4b-aa12-441e-8d3b-5ac7ab283bb6", True
)
mock_immich.albums.async_add_assets_to_album.assert_called_with(
"721e1a4b-aa12-441e-8d3b-5ac7ab283bb6", ["abcdef-0123456789"]
)
async def test_upload_file_config_entry_not_found(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test upload_file service raising config_entry_not_found."""
await setup_integration(hass, mock_config_entry)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_UPLOAD_FILE,
{
"config_entry_id": "unknown_entry",
"file": {
"media_content_id": "media-source://media_source/local/screenshot.jpg",
"media_content_type": "image/jpeg",
},
},
blocking=True,
)
assert err.value.translation_key == "service_config_entry_not_found"
async def test_upload_file_config_entry_not_loaded(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test upload_file service raising config_entry_not_loaded."""
mock_config_entry.disabled_by = er.RegistryEntryDisabler.USER
await setup_integration(hass, mock_config_entry)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_UPLOAD_FILE,
{
"config_entry_id": mock_config_entry.entry_id,
"file": {
"media_content_id": "media-source://media_source/local/screenshot.jpg",
"media_content_type": "image/jpeg",
},
},
blocking=True,
)
assert err.value.translation_key == "service_config_entry_not_loaded"
async def test_upload_file_only_local_media_supported(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
mock_media_source: Mock,
) -> None:
"""Test upload_file service raising only_local_media_supported."""
await setup_integration(hass, mock_config_entry)
with (
patch(
"homeassistant.components.immich.services.async_resolve_media",
return_value=PlayMedia(
url="media-source://media_source/camera/some_entity_id",
mime_type="image/jpeg",
path=None, # Simulate non-local media
),
),
pytest.raises(
ServiceValidationError,
match="Only local media files are currently supported",
),
):
await hass.services.async_call(
DOMAIN,
SERVICE_UPLOAD_FILE,
{
"config_entry_id": mock_config_entry.entry_id,
"file": {
"media_content_id": "media-source://media_source/local/screenshot.jpg",
"media_content_type": "image/jpeg",
},
},
blocking=True,
)
async def test_upload_file_album_not_found(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
mock_media_source: Mock,
) -> None:
"""Test upload_file service raising album_not_found."""
await setup_integration(hass, mock_config_entry)
mock_immich.albums.async_get_album_info.side_effect = ImmichNotFoundError(
{
"message": "Not found or no album.read access",
"error": "Bad Request",
"statusCode": 400,
"correlationId": "nyzxjkno",
}
)
with pytest.raises(
ServiceValidationError,
match="Album with ID `721e1a4b-aa12-441e-8d3b-5ac7ab283bb6` not found",
):
await hass.services.async_call(
DOMAIN,
SERVICE_UPLOAD_FILE,
{
"config_entry_id": mock_config_entry.entry_id,
"file": {
"media_content_id": "media-source://media_source/local/screenshot.jpg",
"media_content_type": "image/jpeg",
},
"album_id": "721e1a4b-aa12-441e-8d3b-5ac7ab283bb6",
},
blocking=True,
)
async def test_upload_file_upload_failed(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
mock_media_source: Mock,
) -> None:
"""Test upload_file service raising upload_failed."""
await setup_integration(hass, mock_config_entry)
mock_immich.assets.async_upload_asset.side_effect = ImmichError(
{
"message": "Boom! Upload failed",
"error": "Bad Request",
"statusCode": 400,
"correlationId": "nyzxjkno",
}
)
with pytest.raises(
ServiceValidationError, match="Upload of file `/media/screenshot.jpg` failed"
):
await hass.services.async_call(
DOMAIN,
SERVICE_UPLOAD_FILE,
{
"config_entry_id": mock_config_entry.entry_id,
"file": {
"media_content_id": "media-source://media_source/local/screenshot.jpg",
"media_content_type": "image/jpeg",
},
},
blocking=True,
)
async def test_upload_file_to_album_upload_failed(
hass: HomeAssistant,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
mock_media_source: Mock,
) -> None:
"""Test upload_file service with target album_id raising upload_failed."""
await setup_integration(hass, mock_config_entry)
mock_immich.albums.async_add_assets_to_album.side_effect = ImmichError(
{
"message": "Boom! Add to album failed.",
"error": "Bad Request",
"statusCode": 400,
"correlationId": "nyzxjkno",
}
)
with pytest.raises(
ServiceValidationError, match="Upload of file `/media/screenshot.jpg` failed"
):
await hass.services.async_call(
DOMAIN,
SERVICE_UPLOAD_FILE,
{
"config_entry_id": mock_config_entry.entry_id,
"file": {
"media_content_id": "media-source://media_source/local/screenshot.jpg",
"media_content_type": "image/jpeg",
},
"album_id": "721e1a4b-aa12-441e-8d3b-5ac7ab283bb6",
},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/immich/test_services.py",
"license": "Apache License 2.0",
"lines": 246,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/ituran/test_binary_sensor.py | """Test the Ituran binary sensor platform."""
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from pyituran.exceptions import IturanApiError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.ituran.const import UPDATE_INTERVAL
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize("mock_ituran", [True], indirect=True)
async def test_ev_binary_sensor(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_ituran: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test state of sensor."""
with patch("homeassistant.components.ituran.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.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize("mock_ituran", [True], indirect=True)
async def test_ev_availability(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_ituran: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test sensor is marked as unavailable when we can't reach the Ituran service."""
entities = [
"binary_sensor.mock_model_charging",
]
await setup_integration(hass, mock_config_entry)
for entity_id in entities:
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
mock_ituran.get_vehicles.side_effect = IturanApiError
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
for entity_id in entities:
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNAVAILABLE
mock_ituran.get_vehicles.side_effect = None
freezer.tick(UPDATE_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
for entity_id in entities:
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ituran/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/kostal_plenticore/test_switch.py | """Test the Kostal Plenticore Solar Inverter switch platform."""
from datetime import timedelta
from unittest.mock import Mock
from pykoplenti import SettingsData
import pytest
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,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry, async_fire_time_changed
pytestmark = [
pytest.mark.usefixtures("mock_plenticore_client"),
]
async def test_installer_setting_not_available(
hass: HomeAssistant,
mock_get_settings: dict[str, list[SettingsData]],
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that the manual charge setting is not available when not using the installer login."""
mock_get_settings.update(
{
"devices:local": [
SettingsData(
min=None,
max=None,
default=None,
access="readwrite",
unit=None,
id="Battery:ManualCharge",
type="bool",
)
]
}
)
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 not entity_registry.async_is_registered("switch.scb_battery_manual_charge")
async def test_installer_setting_available(
hass: HomeAssistant,
mock_get_settings: dict[str, list[SettingsData]],
mock_installer_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that the manual charge setting is available when using the installer login."""
mock_get_settings.update(
{
"devices:local": [
SettingsData(
min=None,
max=None,
default=None,
access="readwrite",
unit=None,
id="Battery:ManualCharge",
type="bool",
)
]
}
)
mock_installer_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_installer_config_entry.entry_id)
await hass.async_block_till_done()
assert entity_registry.async_is_registered("switch.scb_battery_manual_charge")
async def test_invalid_string_count_value(
hass: HomeAssistant,
mock_get_setting_values: dict[str, dict[str, str]],
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that an invalid string count value is handled correctly."""
mock_get_setting_values["devices:local"].update({"Properties:StringCnt": "invalid"})
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# ensure no shadow management switch entities were registered
assert [
name
for name, _ in entity_registry.entities.items()
if name.startswith("switch.scb_shadow_management_dc_string_")
] == []
@pytest.mark.parametrize(
("shadow_mgmt", "string"),
[
("0", (STATE_OFF, STATE_OFF)),
("1", (STATE_ON, STATE_OFF)),
("2", (STATE_OFF, STATE_ON)),
("3", (STATE_ON, STATE_ON)),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_shadow_management_switch_state(
hass: HomeAssistant,
mock_get_setting_values: dict[str, dict[str, str]],
mock_config_entry: MockConfigEntry,
shadow_mgmt: str,
string: tuple[str, str],
) -> None:
"""Test that the state of the shadow management switch is correct."""
mock_get_setting_values["devices:local"].update(
{"Properties:StringCnt": "2", "Generator:ShadowMgmt:Enable": shadow_mgmt}
)
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=300))
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("switch.scb_shadow_management_dc_string_1")
assert state is not None
assert state.state == string[0]
state = hass.states.get("switch.scb_shadow_management_dc_string_2")
assert state is not None
assert state.state == string[1]
@pytest.mark.parametrize(
("initial_shadow_mgmt", "dc_string", "service", "shadow_mgmt"),
[
("0", 1, SERVICE_TURN_ON, "1"),
("0", 2, SERVICE_TURN_ON, "2"),
("2", 1, SERVICE_TURN_ON, "3"),
("1", 2, SERVICE_TURN_ON, "3"),
("1", 1, SERVICE_TURN_OFF, "0"),
("2", 2, SERVICE_TURN_OFF, "0"),
("3", 1, SERVICE_TURN_OFF, "2"),
("3", 2, SERVICE_TURN_OFF, "1"),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_shadow_management_switch_action(
hass: HomeAssistant,
mock_get_setting_values: dict[str, dict[str, str]],
mock_plenticore_client: Mock,
mock_config_entry: MockConfigEntry,
initial_shadow_mgmt: str,
dc_string: int,
service: str,
shadow_mgmt: str,
) -> None:
"""Test that the shadow management can be switch on/off."""
mock_get_setting_values["devices:local"].update(
{
"Properties:StringCnt": "2",
"Generator:ShadowMgmt:Enable": initial_shadow_mgmt,
}
)
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=300))
await hass.async_block_till_done(wait_background_tasks=True)
await hass.services.async_call(
SWITCH_DOMAIN,
service,
target={ATTR_ENTITY_ID: f"switch.scb_shadow_management_dc_string_{dc_string}"},
blocking=True,
)
mock_plenticore_client.set_setting_values.assert_called_with(
"devices:local", {"Generator:ShadowMgmt:Enable": shadow_mgmt}
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/kostal_plenticore/test_switch.py",
"license": "Apache License 2.0",
"lines": 166,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/media_source/test_const.py | """Test constants for the media source component."""
import pytest
from homeassistant.components.media_source.const import URI_SCHEME_REGEX
@pytest.mark.parametrize(
("uri", "expected_domain", "expected_identifier"),
[
("media-source://", None, None),
("media-source://local_media", "local_media", None),
(
"media-source://local_media/some/path/file.mp3",
"local_media",
"some/path/file.mp3",
),
("media-source://a/b", "a", "b"),
(
"media-source://domain/file with spaces.mp4",
"domain",
"file with spaces.mp4",
),
(
"media-source://domain/file-with-dashes.mp3",
"domain",
"file-with-dashes.mp3",
),
("media-source://domain/file.with.dots.mp3", "domain", "file.with.dots.mp3"),
(
"media-source://domain/special!@#$%^&*()chars",
"domain",
"special!@#$%^&*()chars",
),
],
)
def test_valid_uri_patterns(
uri: str, expected_domain: str | None, expected_identifier: str | None
) -> None:
"""Test various valid URI patterns."""
match = URI_SCHEME_REGEX.match(uri)
assert match is not None
assert match.group("domain") == expected_domain
assert match.group("identifier") == expected_identifier
@pytest.mark.parametrize(
"uri",
[
"media-source:", # missing //
"media-source:/", # missing second /
"media-source:///", # extra /
"media-source://domain/", # trailing slash after domain
"invalid-scheme://domain", # wrong scheme
"media-source//domain", # missing :
"MEDIA-SOURCE://domain", # uppercase scheme
"media_source://domain", # underscore in scheme
"", # empty string
"media-source", # scheme only
"media-source://domain extra", # extra content
"prefix media-source://domain", # prefix content
"media-source://domain suffix", # suffix content
# Invalid domain names
"media-source://_test", # starts with underscore
"media-source://test_", # ends with underscore
"media-source://_test_", # starts and ends with underscore
"media-source://_", # single underscore
"media-source://test-123", # contains hyphen
"media-source://test.123", # contains dot
"media-source://test 123", # contains space
"media-source://TEST", # uppercase letters
"media-source://Test", # mixed case
# Identifier cannot start with slash
"media-source://domain//invalid", # identifier starts with slash
],
)
def test_invalid_uris(uri: str) -> None:
"""Test invalid URI formats."""
match = URI_SCHEME_REGEX.match(uri)
assert match is None, f"URI '{uri}' should be invalid"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/media_source/test_const.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/miele/test_services.py | """Tests the services provided by the miele integration."""
from datetime import timedelta
from unittest.mock import MagicMock, Mock
from aiohttp import ClientResponseError
import pytest
from syrupy.assertion import SnapshotAssertion
from voluptuous import MultipleInvalid
from homeassistant.components.miele.const import DOMAIN
from homeassistant.components.miele.services import (
ATTR_DURATION,
ATTR_PROGRAM_ID,
SERVICE_GET_PROGRAMS,
SERVICE_SET_PROGRAM,
SERVICE_SET_PROGRAM_OVEN,
)
from homeassistant.const import ATTR_DEVICE_ID, ATTR_TEMPERATURE
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers.device_registry import DeviceRegistry
from . import setup_integration
from tests.common import MockConfigEntry
TEST_APPLIANCE = "Dummy_Appliance_1"
async def test_services(
hass: HomeAssistant,
device_registry: DeviceRegistry,
mock_miele_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Tests that the custom services are correct."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_APPLIANCE)})
await hass.services.async_call(
DOMAIN,
SERVICE_SET_PROGRAM,
{
ATTR_DEVICE_ID: device.id,
ATTR_PROGRAM_ID: 24,
},
blocking=True,
)
mock_miele_client.set_program.assert_called_once_with(
TEST_APPLIANCE, {"programId": 24}
)
@pytest.mark.parametrize(
("call_arguments", "miele_arguments"),
[
(
{ATTR_PROGRAM_ID: 24},
{"programId": 24},
),
(
{ATTR_PROGRAM_ID: 25, ATTR_DURATION: timedelta(minutes=75)},
{"programId": 25, "duration": [1, 15]},
),
(
{
ATTR_PROGRAM_ID: 26,
ATTR_DURATION: timedelta(minutes=135),
ATTR_TEMPERATURE: 180,
},
{"programId": 26, "duration": [2, 15], "temperature": 180},
),
],
)
async def test_services_oven(
hass: HomeAssistant,
device_registry: DeviceRegistry,
mock_miele_client: MagicMock,
mock_config_entry: MockConfigEntry,
call_arguments: dict,
miele_arguments: dict,
) -> None:
"""Tests that the custom services are correct for ovens."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_APPLIANCE)})
await hass.services.async_call(
DOMAIN,
SERVICE_SET_PROGRAM_OVEN,
{ATTR_DEVICE_ID: device.id, **call_arguments},
blocking=True,
)
mock_miele_client.set_program.assert_called_once_with(
TEST_APPLIANCE, miele_arguments
)
async def test_services_with_response(
hass: HomeAssistant,
device_registry: DeviceRegistry,
mock_miele_client: MagicMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Tests that the custom services that returns a response are correct."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_APPLIANCE)})
assert snapshot == await hass.services.async_call(
DOMAIN,
SERVICE_GET_PROGRAMS,
{
ATTR_DEVICE_ID: device.id,
},
blocking=True,
return_response=True,
)
@pytest.mark.parametrize(
("service", "error"),
[
(SERVICE_SET_PROGRAM, "'Set program' action failed"),
(SERVICE_SET_PROGRAM_OVEN, "'Set program on oven' action failed"),
],
)
async def test_service_api_errors(
hass: HomeAssistant,
device_registry: DeviceRegistry,
mock_miele_client: MagicMock,
mock_config_entry: MockConfigEntry,
service: str,
error: str,
) -> None:
"""Test service api errors."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_APPLIANCE)})
# Test http error
mock_miele_client.set_program.side_effect = ClientResponseError(Mock(), Mock())
with pytest.raises(HomeAssistantError, match=error):
await hass.services.async_call(
DOMAIN,
service,
{ATTR_DEVICE_ID: device.id, ATTR_PROGRAM_ID: 1},
blocking=True,
)
mock_miele_client.set_program.assert_called_once_with(
TEST_APPLIANCE, {"programId": 1}
)
async def test_get_service_api_errors(
hass: HomeAssistant,
device_registry: DeviceRegistry,
mock_miele_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test service api errors."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_APPLIANCE)})
# Test http error
mock_miele_client.get_programs.side_effect = ClientResponseError(Mock(), Mock())
with pytest.raises(HomeAssistantError, match="'Get programs' action failed"):
await hass.services.async_call(
DOMAIN,
SERVICE_GET_PROGRAMS,
{ATTR_DEVICE_ID: device.id},
blocking=True,
return_response=True,
)
mock_miele_client.get_programs.assert_called_once()
async def test_service_validation_errors(
hass: HomeAssistant,
device_registry: DeviceRegistry,
mock_miele_client: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Tests that the custom services handle bad data."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(identifiers={(DOMAIN, TEST_APPLIANCE)})
# Test missing program_id
with pytest.raises(MultipleInvalid, match="required key not provided"):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_PROGRAM,
{"device_id": device.id},
blocking=True,
)
mock_miele_client.set_program.assert_not_called()
# Test invalid program_id
with pytest.raises(MultipleInvalid, match="expected int for dictionary value"):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_PROGRAM,
{"device_id": device.id, ATTR_PROGRAM_ID: "invalid"},
blocking=True,
)
mock_miele_client.set_program.assert_not_called()
# Test invalid device
with pytest.raises(ServiceValidationError, match="Invalid device targeted"):
await hass.services.async_call(
DOMAIN,
SERVICE_SET_PROGRAM,
{"device_id": "invalid_device", ATTR_PROGRAM_ID: 1},
blocking=True,
)
mock_miele_client.set_program.assert_not_called()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/miele/test_services.py",
"license": "Apache License 2.0",
"lines": 189,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/mqtt/test_repairs.py | """Test repairs for MQTT."""
from collections.abc import Coroutine
from copy import deepcopy
from typing import Any
from unittest.mock import patch
import pytest
from homeassistant.components import mqtt
from homeassistant.config_entries import ConfigSubentry, ConfigSubentryData
from homeassistant.const import SERVICE_RELOAD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import device_registry as dr, issue_registry as ir
from homeassistant.util.yaml import parse_yaml
from .common import MOCK_NOTIFY_SUBENTRY_DATA_MULTI, async_fire_mqtt_message
from tests.common import MockConfigEntry, async_capture_events
from tests.components.repairs import (
async_process_repairs_platforms,
process_repair_fix_flow,
start_repair_fix_flow,
)
from tests.conftest import ClientSessionGenerator
from tests.typing import MqttMockHAClientGenerator
async def help_setup_yaml(hass: HomeAssistant, config: dict[str, str]) -> None:
"""Help to set up an exported MQTT device via YAML."""
with patch(
"homeassistant.config.load_yaml_config_file",
return_value=parse_yaml(config["yaml"]),
):
await hass.services.async_call(
mqtt.DOMAIN,
SERVICE_RELOAD,
{},
blocking=True,
)
await hass.async_block_till_done()
async def help_setup_discovery(hass: HomeAssistant, config: dict[str, str]) -> None:
"""Help to set up an exported MQTT device via YAML."""
async_fire_mqtt_message(
hass, config["discovery_topic"], config["discovery_payload"]
)
await hass.async_block_till_done(wait_background_tasks=True)
@pytest.mark.parametrize(
"mqtt_config_subentries_data",
[
(
ConfigSubentryData(
data=MOCK_NOTIFY_SUBENTRY_DATA_MULTI,
subentry_type="device",
title="Mock subentry",
),
)
],
)
@pytest.mark.parametrize(
("flow_step", "setup_helper", "translation_key"),
[
("export_yaml", help_setup_yaml, "subentry_migration_yaml"),
("export_discovery", help_setup_discovery, "subentry_migration_discovery"),
],
)
async def test_subentry_reconfigure_export_settings(
hass: HomeAssistant,
mqtt_mock_entry: MqttMockHAClientGenerator,
device_registry: dr.DeviceRegistry,
hass_client: ClientSessionGenerator,
flow_step: str,
setup_helper: Coroutine[Any, Any, None],
translation_key: str,
) -> None:
"""Test the subentry ConfigFlow YAML export with migration to YAML."""
await mqtt_mock_entry()
config_entry: MockConfigEntry = hass.config_entries.async_entries(mqtt.DOMAIN)[0]
subentry_id: str
subentry: ConfigSubentry
subentry_id, subentry = next(iter(config_entry.subentries.items()))
result = await config_entry.start_subentry_reconfigure_flow(hass, subentry_id)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "summary_menu"
# assert we have a device for the subentry
device = device_registry.async_get_device(identifiers={(mqtt.DOMAIN, subentry_id)})
assert device.config_entries_subentries[config_entry.entry_id] == {subentry_id}
assert device is not None
# assert we entity for all subentry components
components = deepcopy(dict(subentry.data))["components"]
assert len(components) == 2
# assert menu options, we have the option to export
assert result["menu_options"] == [
"entity",
"update_entity",
"delete_entity",
"device",
"availability",
"export",
]
# Open export menu
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{"next_step_id": "export"},
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "export"
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{"next_step_id": flow_step},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == flow_step
assert result["description_placeholders"] == {
"url": "https://www.home-assistant.io/integrations/mqtt/"
}
# Copy the exported config suggested values for an export
suggested_values_from_schema = {
field: field.description["suggested_value"]
for field in result["data_schema"].schema
}
# Try to set up the exported config with a changed device name
events = async_capture_events(hass, ir.EVENT_REPAIRS_ISSUE_REGISTRY_UPDATED)
await setup_helper(hass, suggested_values_from_schema)
# Assert the subentry device was not effected by the exported configs
device = device_registry.async_get_device(identifiers={(mqtt.DOMAIN, subentry_id)})
assert device.config_entries_subentries[config_entry.entry_id] == {subentry_id}
assert device is not None
# Assert a repair flow was created
# This happens when the exported device identifier was detected
# The subentry ID is used as device identifier
assert len(events) == 1
issue_id = events[0].data["issue_id"]
issue_registry = ir.async_get(hass)
repair_issue = issue_registry.async_get_issue(mqtt.DOMAIN, issue_id)
assert repair_issue.translation_key == translation_key
await async_process_repairs_platforms(hass)
client = await hass_client()
data = await start_repair_fix_flow(client, mqtt.DOMAIN, issue_id)
flow_id = data["flow_id"]
assert data["description_placeholders"] == {"name": "Milk notifier"}
assert data["step_id"] == "confirm"
data = await process_repair_fix_flow(client, flow_id)
assert data["type"] == "create_entry"
# Assert the subentry is removed and no other entity has linked the device
device = device_registry.async_get_device(identifiers={(mqtt.DOMAIN, subentry_id)})
assert device is None
await hass.async_block_till_done(wait_background_tasks=True)
assert len(config_entry.subentries) == 0
# Try to set up the exported config again
events = async_capture_events(hass, ir.EVENT_REPAIRS_ISSUE_REGISTRY_UPDATED)
await setup_helper(hass, suggested_values_from_schema)
assert len(events) == 0
# The MQTT device was now set up from the new source
await hass.async_block_till_done(wait_background_tasks=True)
device = device_registry.async_get_device(identifiers={(mqtt.DOMAIN, subentry_id)})
assert device.config_entries_subentries[config_entry.entry_id] == {None}
assert device is not None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/mqtt/test_repairs.py",
"license": "Apache License 2.0",
"lines": 152,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/ollama/test_ai_task.py | """Test AI Task platform of Ollama integration."""
from pathlib import Path
from unittest.mock import patch
import ollama
import pytest
import voluptuous as vol
from homeassistant.components import ai_task, media_source
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er, selector
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation."""
entity_id = "ai_task.ollama_ai_task"
# Ensure entity is linked to the subentry
entity_entry = entity_registry.async_get(entity_id)
ai_task_entry = next(
iter(
entry
for entry in mock_config_entry.subentries.values()
if entry.subentry_type == "ai_task_data"
)
)
assert entity_entry is not None
assert entity_entry.config_entry_id == mock_config_entry.entry_id
assert entity_entry.config_subentry_id == ai_task_entry.subentry_id
# Mock the Ollama chat response as an async iterator
async def mock_chat_response():
"""Mock streaming response."""
yield {
"message": {"role": "assistant", "content": "Generated test data"},
"done": True,
"done_reason": "stop",
}
with patch(
"ollama.AsyncClient.chat",
return_value=mock_chat_response(),
):
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Generate test data",
)
assert result.data == "Generated test data"
@pytest.mark.usefixtures("mock_init_component")
async def test_run_task_with_streaming(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation with streaming response."""
entity_id = "ai_task.ollama_ai_task"
async def mock_stream():
"""Mock streaming response."""
yield {"message": {"role": "assistant", "content": "Stream "}}
yield {
"message": {"role": "assistant", "content": "response"},
"done": True,
"done_reason": "stop",
}
with patch(
"ollama.AsyncClient.chat",
return_value=mock_stream(),
):
result = await ai_task.async_generate_data(
hass,
task_name="Test Streaming Task",
entity_id=entity_id,
instructions="Generate streaming data",
)
assert result.data == "Stream response"
@pytest.mark.usefixtures("mock_init_component")
async def test_run_task_connection_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task with connection error."""
entity_id = "ai_task.ollama_ai_task"
with (
patch(
"ollama.AsyncClient.chat",
side_effect=Exception("Connection failed"),
),
pytest.raises(Exception, match="Connection failed"),
):
await ai_task.async_generate_data(
hass,
task_name="Test Error Task",
entity_id=entity_id,
instructions="Generate data that will fail",
)
@pytest.mark.usefixtures("mock_init_component")
async def test_run_task_empty_response(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task with empty response."""
entity_id = "ai_task.ollama_ai_task"
# Mock response with space (minimally non-empty)
async def mock_minimal_response():
"""Mock minimal streaming response."""
yield {
"message": {"role": "assistant", "content": " "},
"done": True,
"done_reason": "stop",
}
with patch(
"ollama.AsyncClient.chat",
return_value=mock_minimal_response(),
):
result = await ai_task.async_generate_data(
hass,
task_name="Test Minimal Task",
entity_id=entity_id,
instructions="Generate minimal data",
)
assert result.data == " "
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_structured_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation."""
entity_id = "ai_task.ollama_ai_task"
# Mock the Ollama chat response as an async iterator
async def mock_chat_response():
"""Mock streaming response."""
yield {
"message": {
"role": "assistant",
"content": '{"characters": ["Mario", "Luigi"]}',
},
"done": True,
"done_reason": "stop",
}
with patch(
"ollama.AsyncClient.chat",
return_value=mock_chat_response(),
) as mock_chat:
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
assert result.data == {"characters": ["Mario", "Luigi"]}
assert mock_chat.call_count == 1
assert mock_chat.call_args[1]["format"] == {
"type": "object",
"properties": {"characters": {"items": {"type": "string"}, "type": "array"}},
"required": ["characters"],
}
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_invalid_structured_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation."""
entity_id = "ai_task.ollama_ai_task"
# Mock the Ollama chat response as an async iterator
async def mock_chat_response():
"""Mock streaming response."""
yield {
"message": {
"role": "assistant",
"content": "INVALID JSON RESPONSE",
},
"done": True,
"done_reason": "stop",
}
with (
patch(
"ollama.AsyncClient.chat",
return_value=mock_chat_response(),
),
pytest.raises(HomeAssistantError),
):
await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_data_with_attachment(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation with image attachments."""
entity_id = "ai_task.ollama_ai_task"
# Mock the Ollama chat response as an async iterator
async def mock_chat_response():
"""Mock streaming response."""
yield {
"message": {"role": "assistant", "content": "Generated test data"},
"done": True,
"done_reason": "stop",
}
with (
patch(
"homeassistant.components.media_source.async_resolve_media",
side_effect=[
media_source.PlayMedia(
url="http://example.com/doorbell_snapshot.jpg",
mime_type="image/jpeg",
path=Path("doorbell_snapshot.jpg"),
),
],
),
patch(
"ollama.AsyncClient.chat",
return_value=mock_chat_response(),
) as mock_chat,
):
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Generate test data",
attachments=[
{"media_content_id": "media-source://media/doorbell_snapshot.jpg"},
],
)
assert result.data == "Generated test data"
assert mock_chat.call_count == 1
messages = mock_chat.call_args[1]["messages"]
assert len(messages) == 2
chat_message = messages[1]
assert chat_message.role == "user"
assert chat_message.content == "Generate test data"
assert chat_message.images == [
ollama.Image(value=Path("doorbell_snapshot.jpg")),
]
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_data_with_unsupported_file_format(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation with image attachments."""
entity_id = "ai_task.ollama_ai_task"
# Mock the Ollama chat response as an async iterator
async def mock_chat_response():
"""Mock streaming response."""
yield {
"message": {"role": "assistant", "content": "Generated test data"},
"done": True,
"done_reason": "stop",
}
with (
patch(
"homeassistant.components.media_source.async_resolve_media",
side_effect=[
media_source.PlayMedia(
url="http://example.com/doorbell_snapshot.jpg",
mime_type="image/jpeg",
path=Path("doorbell_snapshot.jpg"),
),
media_source.PlayMedia(
url="http://example.com/context.txt",
mime_type="text/plain",
path=Path("context.txt"),
),
],
),
patch(
"ollama.AsyncClient.chat",
return_value=mock_chat_response(),
),
pytest.raises(
HomeAssistantError,
match="Ollama only supports image attachments in user content",
),
):
await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Generate test data",
attachments=[
{"media_content_id": "media-source://media/doorbell_snapshot.jpg"},
{"media_content_id": "media-source://media/context.txt"},
],
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ollama/test_ai_task.py",
"license": "Apache License 2.0",
"lines": 317,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/onkyo/test_media_player.py | """Test Onkyo media player platform."""
import asyncio
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
from aioonkyo import Code, Instruction, Kind, Zone, command, query, status
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.media_player import (
ATTR_INPUT_SOURCE,
ATTR_MEDIA_CONTENT_ID,
ATTR_MEDIA_CONTENT_TYPE,
ATTR_MEDIA_VOLUME_LEVEL,
ATTR_MEDIA_VOLUME_MUTED,
ATTR_SOUND_MODE,
DOMAIN as MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
SERVICE_SELECT_SOUND_MODE,
SERVICE_SELECT_SOURCE,
)
from homeassistant.components.onkyo.services import (
ATTR_HDMI_OUTPUT,
SERVICE_SELECT_HDMI_OUTPUT,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
SERVICE_VOLUME_DOWN,
SERVICE_VOLUME_MUTE,
SERVICE_VOLUME_SET,
SERVICE_VOLUME_UP,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
ENTITY_ID = "media_player.tx_nr7100"
ENTITY_ID_ZONE_2 = "media_player.tx_nr7100_zone_2"
ENTITY_ID_ZONE_3 = "media_player.tx_nr7100_zone_3"
@pytest.fixture(autouse=True)
async def auto_setup_integration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_receiver: AsyncMock,
writes: list[Instruction],
) -> AsyncGenerator[None]:
"""Auto setup integration."""
with (
patch(
"homeassistant.components.onkyo.media_player.QUERY_AV_INFO_DELAY",
0,
),
patch(
"homeassistant.components.onkyo.media_player.QUERY_STATE_DELAY",
0,
),
patch("homeassistant.components.onkyo.PLATFORMS", [Platform.MEDIA_PLAYER]),
):
await setup_integration(hass, mock_config_entry)
writes.clear()
yield
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_availability(hass: HomeAssistant, read_queue: asyncio.Queue) -> None:
"""Test entity availability on disconnect and reconnect."""
assert (state := hass.states.get(ENTITY_ID)) is not None
assert state.state != STATE_UNAVAILABLE
# Simulate a disconnect
read_queue.put_nowait(None)
await asyncio.sleep(0)
assert (state := hass.states.get(ENTITY_ID)) is not None
assert state.state == STATE_UNAVAILABLE
# Simulate first status update after reconnect
read_queue.put_nowait(
status.Power(
Code.from_kind_zone(Kind.POWER, Zone.MAIN), None, status.Power.Param.ON
)
)
await asyncio.sleep(0)
assert (state := hass.states.get(ENTITY_ID)) is not None
assert state.state != STATE_UNAVAILABLE
@pytest.mark.parametrize(
("action", "action_data", "message"),
[
(SERVICE_TURN_ON, {}, command.Power(Zone.MAIN, command.Power.Param.ON)),
(SERVICE_TURN_OFF, {}, command.Power(Zone.MAIN, command.Power.Param.STANDBY)),
(
SERVICE_VOLUME_SET,
{ATTR_MEDIA_VOLUME_LEVEL: 0.5},
command.Volume(Zone.MAIN, 40),
),
(SERVICE_VOLUME_UP, {}, command.Volume(Zone.MAIN, command.Volume.Param.UP)),
(SERVICE_VOLUME_DOWN, {}, command.Volume(Zone.MAIN, command.Volume.Param.DOWN)),
(
SERVICE_VOLUME_MUTE,
{ATTR_MEDIA_VOLUME_MUTED: True},
command.Muting(Zone.MAIN, command.Muting.Param.ON),
),
(
SERVICE_VOLUME_MUTE,
{ATTR_MEDIA_VOLUME_MUTED: False},
command.Muting(Zone.MAIN, command.Muting.Param.OFF),
),
],
)
async def test_actions(
hass: HomeAssistant,
writes: list[Instruction],
action: str,
action_data: dict,
message: Instruction,
) -> None:
"""Test actions."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
action,
{ATTR_ENTITY_ID: ENTITY_ID, **action_data},
blocking=True,
)
assert writes[0] == message
async def test_select_source(hass: HomeAssistant, writes: list[Instruction]) -> None:
"""Test select source."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_SELECT_SOURCE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_INPUT_SOURCE: "TV"},
blocking=True,
)
assert writes[0] == command.InputSource(Zone.MAIN, command.InputSource.Param("12"))
writes.clear()
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_SELECT_SOURCE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_INPUT_SOURCE: "InvalidSource"},
blocking=True,
)
assert not writes
async def test_select_sound_mode(
hass: HomeAssistant, writes: list[Instruction]
) -> None:
"""Test select sound mode."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_SELECT_SOUND_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_SOUND_MODE: "THX"},
blocking=True,
)
assert writes[0] == command.ListeningMode(
Zone.MAIN, command.ListeningMode.Param("04")
)
writes.clear()
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_SELECT_SOUND_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_SOUND_MODE: "InvalidMode"},
blocking=True,
)
assert not writes
async def test_play_media(hass: HomeAssistant, writes: list[Instruction]) -> None:
"""Test play media (radio preset)."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: ENTITY_ID,
ATTR_MEDIA_CONTENT_TYPE: "radio",
ATTR_MEDIA_CONTENT_ID: "5",
},
blocking=True,
)
assert writes[0] == command.TunerPreset(Zone.MAIN, 5)
writes.clear()
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: ENTITY_ID,
ATTR_MEDIA_CONTENT_TYPE: "music",
ATTR_MEDIA_CONTENT_ID: "5",
},
blocking=True,
)
assert not writes
writes.clear()
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: ENTITY_ID_ZONE_2,
ATTR_MEDIA_CONTENT_TYPE: "radio",
ATTR_MEDIA_CONTENT_ID: "5",
},
blocking=True,
)
assert not writes
writes.clear()
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: ENTITY_ID_ZONE_3,
ATTR_MEDIA_CONTENT_TYPE: "radio",
ATTR_MEDIA_CONTENT_ID: "5",
},
blocking=True,
)
assert not writes
async def test_select_hdmi_output(
hass: HomeAssistant, writes: list[Instruction]
) -> None:
"""Test select hdmi output."""
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_SELECT_HDMI_OUTPUT,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_HDMI_OUTPUT: "sub"},
blocking=True,
)
assert writes[0] == command.HDMIOutput(command.HDMIOutput.Param.BOTH)
async def test_query_state_task(
read_queue: asyncio.Queue, writes: list[Instruction]
) -> None:
"""Test query state task."""
read_queue.put_nowait(
status.Power(
Code.from_kind_zone(Kind.POWER, Zone.MAIN), None, status.Power.Param.STANDBY
)
)
read_queue.put_nowait(
status.Power(
Code.from_kind_zone(Kind.POWER, Zone.MAIN), None, status.Power.Param.ON
)
)
read_queue.put_nowait(
status.Power(
Code.from_kind_zone(Kind.POWER, Zone.MAIN), None, status.Power.Param.STANDBY
)
)
read_queue.put_nowait(
status.Power(
Code.from_kind_zone(Kind.POWER, Zone.MAIN), None, status.Power.Param.ON
)
)
await asyncio.sleep(0.1)
queries = [w for w in writes if isinstance(w, query.Volume)]
assert len(queries) == 1
async def test_query_av_info_task(
read_queue: asyncio.Queue, writes: list[Instruction]
) -> None:
"""Test query AV info task."""
read_queue.put_nowait(
status.InputSource(
Code.from_kind_zone(Kind.INPUT_SOURCE, Zone.MAIN),
None,
status.InputSource.Param("24"),
)
)
read_queue.put_nowait(
status.InputSource(
Code.from_kind_zone(Kind.INPUT_SOURCE, Zone.MAIN),
None,
status.InputSource.Param("00"),
)
)
await asyncio.sleep(0.1)
queries = [w for w in writes if isinstance(w, query.AudioInformation)]
assert len(queries) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/onkyo/test_media_player.py",
"license": "Apache License 2.0",
"lines": 277,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/open_router/test_ai_task.py | """Test AI Task structured data generation."""
from pathlib import Path
from unittest.mock import AsyncMock, patch
from openai.types import CompletionUsage
from openai.types.chat import ChatCompletion, ChatCompletionMessage
from openai.types.chat.chat_completion import Choice
import pytest
from syrupy.assertion import SnapshotAssertion
import voluptuous as vol
from homeassistant.components import ai_task, media_source
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er, selector
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.open_router.PLATFORMS",
[Platform.AI_TASK],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_generate_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openai_client: AsyncMock,
) -> None:
"""Test AI Task data generation."""
await setup_integration(hass, mock_config_entry)
entity_id = "ai_task.gemini_1_5_pro"
mock_openai_client.chat.completions.create = AsyncMock(
return_value=ChatCompletion(
id="chatcmpl-1234567890ABCDEFGHIJKLMNOPQRS",
choices=[
Choice(
finish_reason="stop",
index=0,
message=ChatCompletionMessage(
content="The test data",
role="assistant",
function_call=None,
tool_calls=None,
),
)
],
created=1700000000,
model="x-ai/grok-3",
object="chat.completion",
system_fingerprint=None,
usage=CompletionUsage(
completion_tokens=9, prompt_tokens=8, total_tokens=17
),
)
)
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Generate test data",
)
assert result.data == "The test data"
async def test_generate_structured_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openai_client: AsyncMock,
) -> None:
"""Test AI Task structured data generation."""
await setup_integration(hass, mock_config_entry)
mock_openai_client.chat.completions.create = AsyncMock(
return_value=ChatCompletion(
id="chatcmpl-1234567890ABCDEFGHIJKLMNOPQRS",
choices=[
Choice(
finish_reason="stop",
index=0,
message=ChatCompletionMessage(
content='{"characters": ["Mario", "Luigi"]}',
role="assistant",
function_call=None,
tool_calls=None,
),
)
],
created=1700000000,
model="x-ai/grok-3",
object="chat.completion",
system_fingerprint=None,
usage=CompletionUsage(
completion_tokens=9, prompt_tokens=8, total_tokens=17
),
)
)
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.gemini_1_5_pro",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
assert result.data == {"characters": ["Mario", "Luigi"]}
assert mock_openai_client.chat.completions.create.call_args_list[0][1][
"response_format"
] == {
"json_schema": {
"name": "Test Task",
"schema": {
"properties": {
"characters": {
"items": {"type": "string"},
"type": "array",
}
},
"required": ["characters"],
"type": "object",
},
"strict": True,
},
"type": "json_schema",
}
async def test_generate_invalid_structured_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openai_client: AsyncMock,
) -> None:
"""Test AI Task with invalid JSON response."""
await setup_integration(hass, mock_config_entry)
mock_openai_client.chat.completions.create = AsyncMock(
return_value=ChatCompletion(
id="chatcmpl-1234567890ABCDEFGHIJKLMNOPQRS",
choices=[
Choice(
finish_reason="stop",
index=0,
message=ChatCompletionMessage(
content="INVALID JSON RESPONSE",
role="assistant",
function_call=None,
tool_calls=None,
),
)
],
created=1700000000,
model="x-ai/grok-3",
object="chat.completion",
system_fingerprint=None,
usage=CompletionUsage(
completion_tokens=9, prompt_tokens=8, total_tokens=17
),
)
)
with pytest.raises(
HomeAssistantError, match="Error with OpenRouter structured response"
):
await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.gemini_1_5_pro",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
async def test_generate_data_with_attachments(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openai_client: AsyncMock,
) -> None:
"""Test AI Task data generation with attachments."""
await setup_integration(hass, mock_config_entry)
entity_id = "ai_task.gemini_1_5_pro"
mock_openai_client.chat.completions.create = AsyncMock(
return_value=ChatCompletion(
id="chatcmpl-1234567890ABCDEFGHIJKLMNOPQRS",
choices=[
Choice(
finish_reason="stop",
index=0,
message=ChatCompletionMessage(
content="Hi there!",
role="assistant",
function_call=None,
tool_calls=None,
),
)
],
created=1700000000,
model="x-ai/grok-3",
object="chat.completion",
system_fingerprint=None,
usage=CompletionUsage(
completion_tokens=9, prompt_tokens=8, total_tokens=17
),
)
)
# Test with attachments
with (
patch(
"homeassistant.components.media_source.async_resolve_media",
side_effect=[
media_source.PlayMedia(
url="http://example.com/doorbell_snapshot.jpg",
mime_type="image/jpeg",
path=Path("doorbell_snapshot.jpg"),
),
media_source.PlayMedia(
url="http://example.com/context.pdf",
mime_type="application/pdf",
path=Path("context.pdf"),
),
],
),
patch("pathlib.Path.exists", return_value=True),
patch(
"homeassistant.components.open_router.entity.guess_file_type",
return_value=("image/jpeg", None),
),
patch("pathlib.Path.read_bytes", return_value=b"fake_image_data"),
):
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Test prompt",
attachments=[
{"media_content_id": "media-source://media/doorbell_snapshot.jpg"},
{"media_content_id": "media-source://media/context.pdf"},
],
)
assert result.data == "Hi there!"
# Verify that the create was called with the correct parameters
# The last call should have the user message with attachments
call_args = mock_openai_client.chat.completions.create.call_args
assert call_args is not None
# Check that the input includes the attachments
input_messages = call_args[1]["messages"]
assert len(input_messages) > 0
# Find the user message with attachments
user_message_with_attachments = input_messages[-2]
assert user_message_with_attachments is not None
assert len(user_message_with_attachments["content"]) == 3 # Text + attachments
assert user_message_with_attachments["content"] == [
{"type": "text", "text": "Test prompt"},
{
"type": "image_url",
"image_url": {"url": "data:image/jpeg;base64,ZmFrZV9pbWFnZV9kYXRh"},
},
{
"type": "image_url",
"image_url": {"url": "data:application/pdf;base64,ZmFrZV9pbWFnZV9kYXRh"},
},
]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/open_router/test_ai_task.py",
"license": "Apache License 2.0",
"lines": 277,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/open_router/test_config_flow.py | """Test the OpenRouter config flow."""
from unittest.mock import AsyncMock
import pytest
from python_open_router import OpenRouterError
from homeassistant.components.open_router.const import CONF_PROMPT, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_LLM_HASS_API, CONF_MODEL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import get_subentry_id, setup_integration
from tests.common import MockConfigEntry
async def test_full_flow(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test the full config flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert not result["errors"]
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_KEY: "bla"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {CONF_API_KEY: "bla"}
@pytest.mark.parametrize(
("exception", "error"),
[
(OpenRouterError("exception"), "cannot_connect"),
(Exception, "unknown"),
],
)
async def test_form_errors(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_setup_entry: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test we handle errors from the OpenRouter API."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_open_router_client.get_key_data.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "bla"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error}
mock_open_router_client.get_key_data.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "bla"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_duplicate_entry(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test aborting the flow if an 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 not result["errors"]
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "bla"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_create_conversation_agent(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test creating a conversation agent."""
await setup_integration(hass, mock_config_entry)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "conversation"),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert not result["errors"]
assert result["step_id"] == "init"
assert result["data_schema"].schema["model"].config["options"] == [
{"value": "openai/gpt-3.5-turbo", "label": "OpenAI: GPT-3.5 Turbo"},
{"value": "openai/gpt-4", "label": "OpenAI: GPT-4"},
]
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_MODEL: "openai/gpt-3.5-turbo",
CONF_PROMPT: "you are an assistant",
CONF_LLM_HASS_API: ["assist"],
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_MODEL: "openai/gpt-3.5-turbo",
CONF_PROMPT: "you are an assistant",
CONF_LLM_HASS_API: ["assist"],
}
async def test_create_conversation_agent_no_control(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test creating a conversation agent without control over the LLM API."""
await setup_integration(hass, mock_config_entry)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "conversation"),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert not result["errors"]
assert result["step_id"] == "init"
assert result["data_schema"].schema["model"].config["options"] == [
{"value": "openai/gpt-3.5-turbo", "label": "OpenAI: GPT-3.5 Turbo"},
{"value": "openai/gpt-4", "label": "OpenAI: GPT-4"},
]
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_MODEL: "openai/gpt-3.5-turbo",
CONF_PROMPT: "you are an assistant",
CONF_LLM_HASS_API: [],
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_MODEL: "openai/gpt-3.5-turbo",
CONF_PROMPT: "you are an assistant",
}
async def test_create_ai_task(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test creating an AI Task."""
await setup_integration(hass, mock_config_entry)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "ai_task_data"),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert not result["errors"]
assert result["step_id"] == "init"
assert result["data_schema"].schema["model"].config["options"] == [
{"value": "openai/gpt-4", "label": "OpenAI: GPT-4"},
]
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{CONF_MODEL: "openai/gpt-4"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {CONF_MODEL: "openai/gpt-4"}
@pytest.mark.parametrize(
"subentry_type",
["conversation", "ai_task_data"],
)
@pytest.mark.parametrize(
("exception", "reason"),
[(OpenRouterError("exception"), "cannot_connect"), (Exception, "unknown")],
)
async def test_subentry_exceptions(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
subentry_type: str,
exception: Exception,
reason: str,
) -> None:
"""Test subentry flow exceptions."""
await setup_integration(hass, mock_config_entry)
mock_open_router_client.get_models.side_effect = exception
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, subentry_type),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == reason
async def test_reconfigure_conversation_agent(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguring a conversation agent."""
await setup_integration(hass, mock_config_entry)
subentry_id = get_subentry_id(mock_config_entry, "conversation")
# Now reconfigure it
result = await mock_config_entry.start_subentry_reconfigure_flow(hass, subentry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
# Update the configuration
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_MODEL: "openai/gpt-4",
CONF_PROMPT: "updated prompt",
CONF_LLM_HASS_API: ["assist"],
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
async def test_reconfigure_ai_task(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguring an AI task."""
await setup_integration(hass, mock_config_entry)
subentry_id = get_subentry_id(mock_config_entry, "ai_task_data")
result = await mock_config_entry.start_subentry_reconfigure_flow(hass, subentry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
# Update the configuration
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{CONF_MODEL: "openai/gpt-4"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
@pytest.mark.parametrize(
"subentry_type",
["conversation", "ai_task_data"],
)
async def test_reconfigure_entry_not_loaded(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
subentry_type: str,
) -> None:
"""Test reconfiguring an AI task."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, subentry_type),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "entry_not_loaded"
@pytest.mark.parametrize(
("exception", "reason"),
[(OpenRouterError("exception"), "cannot_connect"), (Exception, "unknown")],
)
async def test_reconfigure_conversation_agent_abort(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test reconfiguring a conversation agent with error and recovery."""
await setup_integration(hass, mock_config_entry)
subentry_id = get_subentry_id(mock_config_entry, "conversation")
mock_open_router_client.get_models.side_effect = exception
result = await mock_config_entry.start_subentry_reconfigure_flow(hass, subentry_id)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == reason
@pytest.mark.parametrize(
("exception", "reason"),
[(OpenRouterError("exception"), "cannot_connect"), (Exception, "unknown")],
)
async def test_reconfigure_ai_task_abort(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test reconfiguring an AI task with error and recovery."""
await setup_integration(hass, mock_config_entry)
subentry_id = get_subentry_id(mock_config_entry, "ai_task_data")
# Trigger an error during reconfiguration
mock_open_router_client.get_models.side_effect = exception
result = await mock_config_entry.start_subentry_reconfigure_flow(hass, subentry_id)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == reason
@pytest.mark.parametrize(
("current_llm_apis", "suggested_llm_apis", "expected_options"),
[
(["assist"], ["assist"], ["assist"]),
(["non-existent"], [], ["assist"]),
(["assist", "non-existent"], ["assist"], ["assist"]),
],
)
async def test_reconfigure_conversation_subentry_llm_api_schema(
hass: HomeAssistant,
mock_open_router_client: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
current_llm_apis: list[str],
suggested_llm_apis: list[str],
expected_options: list[str],
) -> None:
"""Test llm_hass_api field values when reconfiguring a conversation subentry."""
await setup_integration(hass, mock_config_entry)
subentry = next(iter(mock_config_entry.subentries.values()))
hass.config_entries.async_update_subentry(
mock_config_entry,
subentry,
data={**subentry.data, CONF_LLM_HASS_API: current_llm_apis},
)
await hass.async_block_till_done()
result = await mock_config_entry.start_subentry_reconfigure_flow(
hass, subentry.subentry_id
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
# Only valid LLM APIs should be suggested and shown as options
schema = result["data_schema"].schema
key = next(k for k in schema if k == CONF_LLM_HASS_API)
assert key.default() == suggested_llm_apis
field_schema = schema[key]
assert field_schema.config
assert [
opt["value"] for opt in field_schema.config.get("options")
] == expected_options
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/open_router/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 335,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/open_router/test_conversation.py | """Tests for the OpenRouter integration."""
import datetime
from unittest.mock import AsyncMock, patch
from freezegun import freeze_time
from openai.types import CompletionUsage
from openai.types.chat import (
ChatCompletion,
ChatCompletionMessage,
ChatCompletionMessageFunctionToolCall,
)
from openai.types.chat.chat_completion import Choice
from openai.types.chat.chat_completion_message_function_tool_call_param import Function
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components import conversation
from homeassistant.const import Platform
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import entity_registry as er, intent
from homeassistant.helpers.llm import ToolInput
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
from tests.components.conversation import MockChatLog, mock_chat_log # noqa: F401
@pytest.fixture(autouse=True)
def freeze_the_time():
"""Freeze the time."""
with freeze_time("2024-05-24 12:00:00", tz_offset=0):
yield
@pytest.mark.parametrize("enable_assist", [True, False], ids=["assist", "no_assist"])
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_openai_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.open_router.PLATFORMS",
[Platform.CONVERSATION],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_default_prompt(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
mock_openai_client: AsyncMock,
mock_chat_log: MockChatLog, # noqa: F811
) -> None:
"""Test that the default prompt works."""
await setup_integration(hass, mock_config_entry)
result = await conversation.async_converse(
hass,
"hello",
mock_chat_log.conversation_id,
Context(),
agent_id="conversation.gpt_3_5_turbo",
)
assert result.response.response_type == intent.IntentResponseType.ACTION_DONE
assert mock_chat_log.content[1:] == snapshot
call = mock_openai_client.chat.completions.create.call_args_list[0][1]
assert call["model"] == "openai/gpt-3.5-turbo"
assert call["extra_headers"] == {
"HTTP-Referer": "https://www.home-assistant.io/integrations/open_router",
"X-Title": "Home Assistant",
}
@pytest.mark.parametrize("enable_assist", [True])
async def test_function_call(
hass: HomeAssistant,
mock_chat_log: MockChatLog, # noqa: F811
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
mock_openai_client: AsyncMock,
) -> None:
"""Test function call from the assistant."""
await setup_integration(hass, mock_config_entry)
# Add some pre-existing content from conversation.default_agent
mock_chat_log.async_add_user_content(
conversation.UserContent(content="What time is it?")
)
mock_chat_log.async_add_assistant_content_without_tools(
conversation.AssistantContent(
agent_id="conversation.gpt_3_5_turbo",
tool_calls=[
ToolInput(
tool_name="HassGetCurrentTime",
tool_args={},
id="mock_tool_call_id",
external=True,
)
],
)
)
mock_chat_log.async_add_assistant_content_without_tools(
conversation.ToolResultContent(
agent_id="conversation.gpt_3_5_turbo",
tool_call_id="mock_tool_call_id",
tool_name="HassGetCurrentTime",
tool_result={
"speech": {"plain": {"speech": "12:00 PM", "extra_data": None}},
"response_type": "action_done",
"speech_slots": {"time": datetime.time(12, 0)},
"data": {"targets": [], "success": [], "failed": []},
},
)
)
mock_chat_log.async_add_assistant_content_without_tools(
conversation.AssistantContent(
agent_id="conversation.gpt_3_5_turbo",
content="12:00 PM",
)
)
mock_chat_log.mock_tool_results(
{
"call_call_1": "value1",
"call_call_2": "value2",
}
)
mock_openai_client.chat.completions.create.side_effect = (
ChatCompletion(
id="chatcmpl-1234567890ABCDEFGHIJKLMNOPQRS",
choices=[
Choice(
finish_reason="tool_calls",
index=0,
message=ChatCompletionMessage(
content=None,
role="assistant",
function_call=None,
tool_calls=[
ChatCompletionMessageFunctionToolCall(
id="call_call_1",
function=Function(
arguments='{"param1":"call1"}',
name="test_tool",
),
type="function",
)
],
),
)
],
created=1700000000,
model="gpt-4-1106-preview",
object="chat.completion",
system_fingerprint=None,
usage=CompletionUsage(
completion_tokens=9, prompt_tokens=8, total_tokens=17
),
),
ChatCompletion(
id="chatcmpl-1234567890ZYXWVUTSRQPONMLKJIH",
choices=[
Choice(
finish_reason="stop",
index=0,
message=ChatCompletionMessage(
content="I have successfully called the function",
role="assistant",
function_call=None,
tool_calls=None,
),
)
],
created=1700000000,
model="gpt-4-1106-preview",
object="chat.completion",
system_fingerprint=None,
usage=CompletionUsage(
completion_tokens=9, prompt_tokens=8, total_tokens=17
),
),
)
result = await conversation.async_converse(
hass,
"Please call the test function",
mock_chat_log.conversation_id,
Context(),
agent_id="conversation.gpt_3_5_turbo",
)
assert result.response.response_type == intent.IntentResponseType.ACTION_DONE
# Don't test the prompt, as it's not deterministic
assert mock_chat_log.content[1:] == snapshot
assert mock_openai_client.chat.completions.create.call_count == 2
assert (
mock_openai_client.chat.completions.create.call_args.kwargs["messages"]
== snapshot
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/open_router/test_conversation.py",
"license": "Apache License 2.0",
"lines": 188,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/openai_conversation/test_ai_task.py | """Test AI Task platform of OpenAI Conversation integration."""
from pathlib import Path
from unittest.mock import AsyncMock, patch
import httpx
from openai import PermissionDeniedError
import pytest
import voluptuous as vol
from homeassistant.components import ai_task, media_source
from homeassistant.components.openai_conversation import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er, issue_registry as ir, selector
from . import create_image_gen_call_item, create_message_item
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_stream: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation."""
entity_id = "ai_task.openai_ai_task"
# Ensure entity is linked to the subentry
entity_entry = entity_registry.async_get(entity_id)
ai_task_entry = next(
iter(
entry
for entry in mock_config_entry.subentries.values()
if entry.subentry_type == "ai_task_data"
)
)
assert entity_entry is not None
assert entity_entry.config_entry_id == mock_config_entry.entry_id
assert entity_entry.config_subentry_id == ai_task_entry.subentry_id
# Mock the OpenAI response stream
mock_create_stream.return_value = [
create_message_item(id="msg_A", text="The test data", output_index=0)
]
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Generate test data",
)
assert result.data == "The test data"
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_structured_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_stream: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task structured data generation."""
# Mock the OpenAI response stream with JSON data
mock_create_stream.return_value = [
create_message_item(
id="msg_A", text='{"characters": ["Mario", "Luigi"]}', output_index=0
)
]
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.openai_ai_task",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
assert result.data == {"characters": ["Mario", "Luigi"]}
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_invalid_structured_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_stream: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task with invalid JSON response."""
# Mock the OpenAI response stream with invalid JSON
mock_create_stream.return_value = [
create_message_item(id="msg_A", text="INVALID JSON RESPONSE", output_index=0)
]
with pytest.raises(
HomeAssistantError, match="Error with OpenAI structured response"
):
await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.openai_ai_task",
instructions="Generate test data",
structure=vol.Schema(
{
vol.Required("characters"): selector.selector(
{
"text": {
"multiple": True,
}
}
)
},
),
)
@pytest.mark.usefixtures("mock_init_component")
async def test_generate_data_with_attachments(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_stream: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test AI Task data generation with attachments."""
entity_id = "ai_task.openai_ai_task"
# Mock the OpenAI response stream
mock_create_stream.return_value = [
create_message_item(id="msg_A", text="Hi there!", output_index=0)
]
# Test with attachments
with (
patch(
"homeassistant.components.media_source.async_resolve_media",
side_effect=[
media_source.PlayMedia(
url="http://example.com/doorbell_snapshot.jpg",
mime_type="image/jpeg",
path=Path("doorbell_snapshot.jpg"),
),
media_source.PlayMedia(
url="http://example.com/context.pdf",
mime_type="application/pdf",
path=Path("context.pdf"),
),
],
),
patch("pathlib.Path.exists", return_value=True),
patch(
"homeassistant.components.openai_conversation.entity.guess_file_type",
return_value=("image/jpeg", None),
),
patch("pathlib.Path.read_bytes", return_value=b"fake_image_data"),
):
result = await ai_task.async_generate_data(
hass,
task_name="Test Task",
entity_id=entity_id,
instructions="Test prompt",
attachments=[
{"media_content_id": "media-source://media/doorbell_snapshot.jpg"},
{"media_content_id": "media-source://media/context.pdf"},
],
)
assert result.data == "Hi there!"
# Verify that the create stream was called with the correct parameters
# The last call should have the user message with attachments
call_args = mock_create_stream.call_args
assert call_args is not None
# Check that the input includes the attachments
input_messages = call_args[1]["input"]
assert len(input_messages) > 0
# Find the user message with attachments
user_message_with_attachments = input_messages[-2]
assert user_message_with_attachments is not None
assert isinstance(user_message_with_attachments["content"], list)
assert len(user_message_with_attachments["content"]) == 3 # Text + attachments
assert user_message_with_attachments["content"] == [
{"type": "input_text", "text": "Test prompt"},
{
"detail": "auto",
"image_url": "data:image/jpeg;base64,ZmFrZV9pbWFnZV9kYXRh",
"type": "input_image",
},
{
"filename": "context.pdf",
"file_data": "data:application/pdf;base64,ZmFrZV9pbWFnZV9kYXRh",
"type": "input_file",
},
]
@pytest.mark.usefixtures("mock_init_component")
@pytest.mark.freeze_time("2025-06-14 22:59:00")
@pytest.mark.parametrize(
"image_model", ["gpt-image-1.5", "gpt-image-1", "gpt-image-1-mini"]
)
async def test_generate_image(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_stream: AsyncMock,
entity_registry: er.EntityRegistry,
issue_registry: ir.IssueRegistry,
image_model: str,
) -> None:
"""Test AI Task image generation."""
entity_id = "ai_task.openai_ai_task"
# Ensure entity is linked to the subentry
entity_entry = entity_registry.async_get(entity_id)
ai_task_entry = next(
iter(
entry
for entry in mock_config_entry.subentries.values()
if entry.subentry_type == "ai_task_data"
)
)
hass.config_entries.async_update_subentry(
mock_config_entry,
ai_task_entry,
data={"image_model": image_model},
)
await hass.async_block_till_done()
assert entity_entry is not None
assert entity_entry.config_entry_id == mock_config_entry.entry_id
assert entity_entry.config_subentry_id == ai_task_entry.subentry_id
# Mock the OpenAI response stream
mock_create_stream.return_value = [
create_image_gen_call_item(id="ig_A", output_index=0),
create_message_item(id="msg_A", text="", output_index=1),
]
with patch.object(
media_source.local_source.LocalSource,
"async_upload_media",
return_value="media-source://ai_task/image/2025-06-14_225900_test_task.png",
) as mock_upload_media:
result = await ai_task.async_generate_image(
hass,
task_name="Test Task",
entity_id="ai_task.openai_ai_task",
instructions="Generate test image",
)
assert result["height"] == 1024
assert result["width"] == 1536
assert result["revised_prompt"] == "Mock revised prompt."
assert result["mime_type"] == "image/png"
assert result["model"] == image_model
mock_upload_media.assert_called_once()
image_data = mock_upload_media.call_args[0][1]
assert image_data.file.getvalue() == b"A"
assert image_data.content_type == "image/png"
assert image_data.filename == "2025-06-14_225900_test_task.png"
assert (
issue_registry.async_get_issue(DOMAIN, "organization_verification_required")
is None
)
@pytest.mark.usefixtures("mock_init_component")
async def test_repair_issue(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test that repair issue is raised when verification is required."""
with (
patch(
"openai.resources.responses.AsyncResponses.create",
side_effect=PermissionDeniedError(
response=httpx.Response(
status_code=403, request=httpx.Request(method="GET", url="")
),
body=None,
message="Please click on Verify Organization.",
),
),
pytest.raises(HomeAssistantError, match="Error talking to OpenAI"),
):
await ai_task.async_generate_image(
hass,
task_name="Test Task",
entity_id="ai_task.openai_ai_task",
instructions="Generate test image",
)
assert issue_registry.async_get_issue(DOMAIN, "organization_verification_required")
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openai_conversation/test_ai_task.py",
"license": "Apache License 2.0",
"lines": 274,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/openai_conversation/test_entity.py | """Tests for the OpenAI Conversation entity."""
import voluptuous as vol
from homeassistant.components.openai_conversation.entity import (
_format_structured_output,
)
from homeassistant.helpers import selector
async def test_format_structured_output() -> None:
"""Test the format_structured_output function."""
schema = vol.Schema(
{
vol.Required("name"): selector.TextSelector(),
vol.Optional("age"): selector.NumberSelector(
config=selector.NumberSelectorConfig(
min=0,
max=120,
),
),
vol.Required("stuff"): selector.ObjectSelector(
{
"multiple": True,
"fields": {
"item_name": {
"selector": {"text": None},
},
"item_value": {
"selector": {"text": None},
},
},
}
),
}
)
assert _format_structured_output(schema, None) == {
"additionalProperties": False,
"properties": {
"age": {
"maximum": 120.0,
"minimum": 0.0,
"type": [
"number",
"null",
],
},
"name": {
"type": "string",
},
"stuff": {
"items": {
"properties": {
"item_name": {
"type": ["string", "null"],
},
"item_value": {
"type": ["string", "null"],
},
},
"required": [
"item_name",
"item_value",
],
"type": "object",
"additionalProperties": False,
"strict": True,
},
"type": "array",
},
},
"required": [
"name",
"stuff",
"age",
],
"strict": True,
"type": "object",
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openai_conversation/test_entity.py",
"license": "Apache License 2.0",
"lines": 75,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/opower/test_coordinator.py | """Tests for the Opower coordinator."""
from datetime import datetime
from unittest.mock import AsyncMock
from opower import CostRead
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.opower.const import DOMAIN
from homeassistant.components.opower.coordinator import OpowerCoordinator
from homeassistant.components.recorder import Recorder
from homeassistant.components.recorder.models import (
StatisticData,
StatisticMeanType,
StatisticMetaData,
)
from homeassistant.components.recorder.statistics import (
async_add_external_statistics,
get_last_statistics,
statistics_during_period,
)
from homeassistant.const import UnitOfEnergy
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir
from homeassistant.util import dt as dt_util
from homeassistant.util.unit_conversion import EnergyConverter
from tests.common import MockConfigEntry
from tests.components.recorder.common import async_wait_recording_done
async def test_coordinator_first_run(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test the coordinator on its first run with no existing statistics."""
mock_opower_api.async_get_cost_reads.return_value = [
CostRead(
start_time=dt_util.as_utc(datetime(2023, 1, 1, 8)),
end_time=dt_util.as_utc(datetime(2023, 1, 1, 9)),
consumption=1.5,
provided_cost=0.5,
),
CostRead(
start_time=dt_util.as_utc(datetime(2023, 1, 1, 9)),
end_time=dt_util.as_utc(datetime(2023, 1, 1, 10)),
consumption=-0.5, # Grid return
provided_cost=-0.1, # Compensation
),
]
coordinator = OpowerCoordinator(hass, mock_config_entry)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# Check stats for electric account '111111'
stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
dt_util.utc_from_timestamp(0),
None,
{
"opower:pge_elec_111111_energy_consumption",
"opower:pge_elec_111111_energy_return",
"opower:pge_elec_111111_energy_cost",
"opower:pge_elec_111111_energy_compensation",
},
"hour",
None,
{"state", "sum"},
)
assert stats == snapshot
async def test_coordinator_subsequent_run(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test the coordinator correctly updates statistics on subsequent runs."""
# First run
mock_opower_api.async_get_cost_reads.return_value = [
CostRead(
start_time=dt_util.as_utc(datetime(2023, 1, 1, 8)),
end_time=dt_util.as_utc(datetime(2023, 1, 1, 9)),
consumption=1.5,
provided_cost=0.5,
),
CostRead(
start_time=dt_util.as_utc(datetime(2023, 1, 1, 9)),
end_time=dt_util.as_utc(datetime(2023, 1, 1, 10)),
consumption=-0.5,
provided_cost=-0.1,
),
]
coordinator = OpowerCoordinator(hass, mock_config_entry)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# Second run with updated data for one hour and new data for the next hour
mock_opower_api.async_get_cost_reads.return_value = [
CostRead(
start_time=dt_util.as_utc(datetime(2023, 1, 1, 9)), # Updated data
end_time=dt_util.as_utc(datetime(2023, 1, 1, 10)),
consumption=-1.0, # Was -0.5
provided_cost=-0.2, # Was -0.1
),
CostRead(
start_time=dt_util.as_utc(datetime(2023, 1, 1, 10)), # New data
end_time=dt_util.as_utc(datetime(2023, 1, 1, 11)),
consumption=2.0,
provided_cost=0.7,
),
]
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# Check all stats
stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
dt_util.utc_from_timestamp(0),
None,
{
"opower:pge_elec_111111_energy_consumption",
"opower:pge_elec_111111_energy_return",
"opower:pge_elec_111111_energy_cost",
"opower:pge_elec_111111_energy_compensation",
},
"hour",
None,
{"state", "sum"},
)
assert stats == snapshot
async def test_coordinator_subsequent_run_no_energy_data(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the coordinator handles no recent usage/cost data."""
# First run
mock_opower_api.async_get_cost_reads.return_value = [
CostRead(
start_time=dt_util.as_utc(datetime(2023, 1, 1, 8)),
end_time=dt_util.as_utc(datetime(2023, 1, 1, 9)),
consumption=1.5,
provided_cost=0.5,
),
]
coordinator = OpowerCoordinator(hass, mock_config_entry)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# Second run with no data
mock_opower_api.async_get_cost_reads.return_value = []
coordinator = OpowerCoordinator(hass, mock_config_entry)
await coordinator._async_update_data()
assert "No recent usage/cost data. Skipping update" in caplog.text
# Verify no new stats were added by checking the sum remains 1.5
statistic_id = "opower:pge_elec_111111_energy_consumption"
stats = await hass.async_add_executor_job(
get_last_statistics, hass, 1, statistic_id, True, {"sum"}
)
assert stats[statistic_id][0]["sum"] == 1.5
async def test_coordinator_migration(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test the one-time migration for return-to-grid statistics."""
# Setup: Create old-style consumption data with negative values
statistic_id = "opower:pge_elec_111111_energy_consumption"
metadata = StatisticMetaData(
has_sum=True,
mean_type=StatisticMeanType.NONE,
name="Opower pge elec 111111 consumption",
source=DOMAIN,
statistic_id=statistic_id,
unit_class=EnergyConverter.UNIT_CLASS,
unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
)
statistics_to_add = [
StatisticData(
start=dt_util.as_utc(datetime(2023, 1, 1, 8)),
state=1.5,
sum=1.5,
),
StatisticData(
start=dt_util.as_utc(datetime(2023, 1, 1, 9)),
state=-0.5, # This should be migrated
sum=1.0,
),
]
async_add_external_statistics(hass, metadata, statistics_to_add)
await async_wait_recording_done(hass)
# When the coordinator runs, it should trigger the migration
# Don't need new cost reads for this test
mock_opower_api.async_get_cost_reads.return_value = []
coordinator = OpowerCoordinator(hass, mock_config_entry)
await coordinator._async_update_data()
await async_wait_recording_done(hass)
# Check that the stats have been migrated
stats = await hass.async_add_executor_job(
statistics_during_period,
hass,
dt_util.utc_from_timestamp(0),
None,
{
"opower:pge_elec_111111_energy_consumption",
"opower:pge_elec_111111_energy_return",
},
"hour",
None,
{"state", "sum"},
)
assert stats == snapshot
# Check that an issue was created
issue_registry = ir.async_get(hass)
issue = issue_registry.async_get_issue(DOMAIN, "return_to_grid_migration_111111")
assert issue is not None
assert issue.severity == ir.IssueSeverity.WARNING
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/opower/test_coordinator.py",
"license": "Apache License 2.0",
"lines": 218,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/opower/test_init.py | """Tests for the Opower integration."""
from unittest.mock import AsyncMock
from opower.exceptions import ApiException, CannotConnect, InvalidAuth
import pytest
from homeassistant.components.opower.const import DOMAIN
from homeassistant.components.recorder import Recorder
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_setup_unload_entry(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
) -> None:
"""Test successful setup and unload of a config entry."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_opower_api.async_login.assert_awaited_once()
mock_opower_api.async_get_forecast.assert_awaited_once()
mock_opower_api.async_get_accounts.assert_awaited_once()
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
assert not hass.data.get(DOMAIN)
@pytest.mark.parametrize(
("login_side_effect", "expected_state"),
[
(
CannotConnect(),
ConfigEntryState.SETUP_RETRY,
),
(
InvalidAuth(),
ConfigEntryState.SETUP_ERROR,
),
],
)
async def test_login_error(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
login_side_effect: Exception,
expected_state: ConfigEntryState,
) -> None:
"""Test for login error."""
mock_opower_api.async_login.side_effect = login_side_effect
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is expected_state
async def test_get_forecast_error(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
) -> None:
"""Test for API error when getting forecast."""
mock_opower_api.async_get_forecast.side_effect = ApiException(
message="forecast error", url=""
)
assert not 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_get_accounts_error(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
) -> None:
"""Test for API error when getting accounts."""
mock_opower_api.async_get_accounts.side_effect = ApiException(
message="accounts error", url=""
)
assert not 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_get_cost_reads_error(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
) -> None:
"""Test for API error when getting cost reads."""
mock_opower_api.async_get_cost_reads.side_effect = ApiException(
message="cost reads error", url=""
)
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/opower/test_init.py",
"license": "Apache License 2.0",
"lines": 91,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/opower/test_sensor.py | """Tests for the Opower sensor platform."""
from datetime import datetime
from unittest.mock import AsyncMock, patch
from opower import CostRead
import pytest
from homeassistant.components.recorder import Recorder
from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, UnitOfEnergy, UnitOfVolume
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry
async def test_sensors(
recorder_mock: Recorder,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_opower_api: AsyncMock,
) -> None:
"""Test the creation and values of Opower sensors."""
mock_opower_api.async_get_cost_reads.return_value = [
CostRead(
start_time=dt_util.as_utc(datetime(2023, 1, 1, 8)),
end_time=dt_util.as_utc(datetime(2023, 1, 1, 9)),
consumption=1.5,
provided_cost=0.5,
),
]
with patch(
"homeassistant.components.opower.coordinator.dt_util.utcnow"
) as mock_utcnow:
mock_utcnow.return_value = datetime(2023, 1, 2, 8, 0, 0, tzinfo=dt_util.UTC)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
entity_registry = er.async_get(hass)
# Check electric sensors
entry = entity_registry.async_get(
"sensor.elec_account_111111_current_bill_electric_usage_to_date"
)
assert entry
assert entry.unique_id == "pge_111111_elec_usage_to_date"
state = hass.states.get(
"sensor.elec_account_111111_current_bill_electric_usage_to_date"
)
assert state
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfEnergy.KILO_WATT_HOUR
assert state.state == "100"
entry = entity_registry.async_get(
"sensor.elec_account_111111_current_bill_electric_cost_to_date"
)
assert entry
assert entry.unique_id == "pge_111111_elec_cost_to_date"
state = hass.states.get(
"sensor.elec_account_111111_current_bill_electric_cost_to_date"
)
assert state
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "USD"
assert state.state == "20.0"
entry = entity_registry.async_get("sensor.elec_account_111111_last_changed")
assert entry
assert entry.unique_id == "pge_111111_last_changed"
state = hass.states.get("sensor.elec_account_111111_last_changed")
assert state
assert state.state == "2023-01-01T16:00:00+00:00"
entry = entity_registry.async_get("sensor.elec_account_111111_last_updated")
assert entry
assert entry.unique_id == "pge_111111_last_updated"
state = hass.states.get("sensor.elec_account_111111_last_updated")
assert state
assert state.state == "2023-01-02T08:00:00+00:00"
# Check gas sensors
entry = entity_registry.async_get(
"sensor.gas_account_222222_current_bill_gas_usage_to_date"
)
assert entry
assert entry.unique_id == "pge_222222_gas_usage_to_date"
state = hass.states.get("sensor.gas_account_222222_current_bill_gas_usage_to_date")
assert state
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == UnitOfVolume.CUBIC_METERS
# Convert 50 CCF to m³
assert float(state.state) == pytest.approx(50 * 2.83168, abs=1e-3)
entry = entity_registry.async_get(
"sensor.gas_account_222222_current_bill_gas_cost_to_date"
)
assert entry
assert entry.unique_id == "pge_222222_gas_cost_to_date"
state = hass.states.get("sensor.gas_account_222222_current_bill_gas_cost_to_date")
assert state
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "USD"
assert state.state == "15.0"
entry = entity_registry.async_get("sensor.gas_account_222222_last_changed")
assert entry
assert entry.unique_id == "pge_222222_last_changed"
state = hass.states.get("sensor.gas_account_222222_last_changed")
assert state
assert state.state == "2023-01-01T16:00:00+00:00"
entry = entity_registry.async_get("sensor.gas_account_222222_last_updated")
assert entry
assert entry.unique_id == "pge_222222_last_updated"
state = hass.states.get("sensor.gas_account_222222_last_updated")
assert state
assert state.state == "2023-01-02T08:00:00+00:00"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/opower/test_sensor.py",
"license": "Apache License 2.0",
"lines": 100,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/pi_hole/test_repairs.py | """Test pi_hole component."""
from datetime import timedelta
from unittest.mock import AsyncMock
from hole.exceptions import HoleConnectionError, HoleError
import pytest
import homeassistant
from homeassistant.components import pi_hole
from homeassistant.components.pi_hole.const import VERSION_6_RESPONSE_TO_5_ERROR
from homeassistant.const import CONF_API_VERSION, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir
from homeassistant.util import dt as dt_util
from . import CONFIG_DATA_DEFAULTS, ZERO_DATA, _create_mocked_hole, _patch_init_hole
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_change_api_5_to_6(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Tests a user with an API version 5 config entry that is updated to API version 6."""
mocked_hole = _create_mocked_hole(api_version=5)
# setu up a valid API version 5 config entry
entry = MockConfigEntry(
domain=pi_hole.DOMAIN,
data={**CONFIG_DATA_DEFAULTS, CONF_API_VERSION: 5},
)
entry.add_to_hass(hass)
with _patch_init_hole(mocked_hole):
assert await hass.config_entries.async_setup(entry.entry_id)
assert mocked_hole.instances[-1].data == ZERO_DATA
# Change the mock's state after setup
mocked_hole.instances[-1].hole_version = 6
mocked_hole.instances[-1].api_token = "wrong_token"
# Patch the method on the coordinator's api reference directly
pihole_data = entry.runtime_data
assert pihole_data.api == mocked_hole.instances[-1]
pihole_data.api.get_data = AsyncMock(
side_effect=lambda: setattr(
pihole_data.api,
"data",
{"error": VERSION_6_RESPONSE_TO_5_ERROR, "took": 0.0001430511474609375},
)
)
# Now trigger the update
with pytest.raises(homeassistant.exceptions.ConfigEntryAuthFailed):
await pihole_data.coordinator.update_method()
assert pihole_data.api.data == {
"error": VERSION_6_RESPONSE_TO_5_ERROR,
"took": 0.0001430511474609375,
}
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10))
await hass.async_block_till_done()
# ensure a re-auth flow is created
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
assert flows[0]["context"]["entry_id"] == entry.entry_id
async def test_app_password_changing(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Tests a user with an API version 5 config entry that is updated to API version 6."""
mocked_hole = _create_mocked_hole(
api_version=6, has_data=True, incorrect_app_password=False
)
entry = MockConfigEntry(domain=pi_hole.DOMAIN, data={**CONFIG_DATA_DEFAULTS})
entry.add_to_hass(hass)
with _patch_init_hole(mocked_hole):
assert await hass.config_entries.async_setup(entry.entry_id)
state = hass.states.get("sensor.pi_hole_ads_blocked")
assert state is not None
assert state.name == "Pi-Hole Ads blocked"
assert state.state == "0"
# Test app password changing
async def fail_auth():
"""Set mocked data to bad_data."""
raise HoleError("Authentication failed: Invalid password")
mocked_hole.instances[-1].get_data = AsyncMock(side_effect=fail_auth)
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10))
await hass.async_block_till_done()
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
assert flows[0]["context"]["entry_id"] == entry.entry_id
# Test app password changing
async def fail_fetch():
"""Set mocked data to bad_data."""
raise HoleConnectionError("Cannot fetch data from Pi-hole: 200")
mocked_hole.instances[-1].get_data = AsyncMock(side_effect=fail_fetch)
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10))
await hass.async_block_till_done()
async def test_app_failed_fetch(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Tests a user with an API version 5 config entry that is updated to API version 6."""
mocked_hole = _create_mocked_hole(
api_version=6, has_data=True, incorrect_app_password=False
)
entry = MockConfigEntry(domain=pi_hole.DOMAIN, data={**CONFIG_DATA_DEFAULTS})
entry.add_to_hass(hass)
with _patch_init_hole(mocked_hole):
assert await hass.config_entries.async_setup(entry.entry_id)
state = hass.states.get("sensor.pi_hole_ads_blocked")
assert state.state == "0"
# Test fetch failing changing
async def fail_fetch():
"""Set mocked data to bad_data."""
raise HoleConnectionError("Cannot fetch data from Pi-hole: 200")
mocked_hole.instances[-1].get_data = AsyncMock(side_effect=fail_fetch)
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10))
await hass.async_block_till_done()
state = hass.states.get("sensor.pi_hole_ads_blocked")
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/pi_hole/test_repairs.py",
"license": "Apache License 2.0",
"lines": 110,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/pi_hole/test_sensor.py | """Test pi_hole component."""
import copy
from datetime import timedelta
from unittest.mock import AsyncMock
import pytest
from homeassistant.components import pi_hole
from homeassistant.components.pi_hole.const import CONF_STATISTICS_ONLY
from homeassistant.core import HomeAssistant
from homeassistant.util import dt as dt_util
from . import CONFIG_DATA_DEFAULTS, ZERO_DATA_V6, _create_mocked_hole, _patch_init_hole
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_bad_data_type(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling of bad data. Mostly for code coverage, rather than simulating known error states."""
mocked_hole = _create_mocked_hole(
api_version=6, has_data=True, incorrect_app_password=False
)
entry = MockConfigEntry(
domain=pi_hole.DOMAIN, data={**CONFIG_DATA_DEFAULTS, CONF_STATISTICS_ONLY: True}
)
entry.add_to_hass(hass)
with _patch_init_hole(mocked_hole):
assert await hass.config_entries.async_setup(entry.entry_id)
bad_data = copy.deepcopy(ZERO_DATA_V6)
bad_data["queries"]["total"] = "error string"
assert bad_data != ZERO_DATA_V6
async def set_bad_data():
"""Set mocked data to bad_data."""
mocked_hole.instances[-1].data = bad_data
mocked_hole.instances[-1].get_data = AsyncMock(side_effect=set_bad_data)
# Wait a minute
future = dt_util.utcnow() + timedelta(minutes=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert "TypeError" in caplog.text
async def test_bad_data_key(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test handling of bad data. Mostly for code coverage, rather than simulating known error states."""
mocked_hole = _create_mocked_hole(
api_version=6, has_data=True, incorrect_app_password=False
)
entry = MockConfigEntry(
domain=pi_hole.DOMAIN, data={**CONFIG_DATA_DEFAULTS, CONF_STATISTICS_ONLY: True}
)
entry.add_to_hass(hass)
with _patch_init_hole(mocked_hole):
assert await hass.config_entries.async_setup(entry.entry_id)
bad_data = copy.deepcopy(ZERO_DATA_V6)
# remove a whole part of the dict tree now
bad_data["queries"] = "error string"
assert bad_data != ZERO_DATA_V6
async def set_bad_data():
"""Set mocked data to bad_data."""
mocked_hole.instances[-1].data = bad_data
mocked_hole.instances[-1].get_data = AsyncMock(side_effect=set_bad_data)
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=1))
await hass.async_block_till_done()
assert mocked_hole.instances[-1].data != ZERO_DATA_V6
assert "KeyError" in caplog.text
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/pi_hole/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/playstation_network/test_binary_sensor.py | """Test the Playstation Network binary sensor platform."""
from collections.abc import Generator
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture(autouse=True)
def binary_sensor_only() -> Generator[None]:
"""Enable only the binary sensor platform."""
with patch(
"homeassistant.components.playstation_network.PLATFORMS",
[Platform.BINARY_SENSOR],
):
yield
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_sensors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test setup of the PlayStation Network binary sensor platform."""
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.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/playstation_network/test_binary_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/playstation_network/test_image.py | """Test the PlayStation Network image platform."""
from collections.abc import Generator
from datetime import timedelta
from http import HTTPStatus
from unittest.mock import MagicMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
import respx
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, async_fire_time_changed
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True)
def image_only() -> Generator[None]:
"""Enable only the image platform."""
with patch(
"homeassistant.components.playstation_network.PLATFORMS",
[Platform.IMAGE],
):
yield
@respx.mock
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_image_platform(
hass: HomeAssistant,
config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
freezer: FrozenDateTimeFactory,
mock_psnawpapi: MagicMock,
) -> None:
"""Test image platform."""
freezer.move_to("2025-06-16T00:00:00-00:00")
respx.get(
"http://static-resource.np.community.playstation.net/avatar_xl/WWS_A/UP90001312L24_DD96EB6A4FF5FE883C09_XL.png"
).respond(status_code=HTTPStatus.OK, content_type="image/png", content=b"Test")
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.LOADED
assert (state := hass.states.get("image.testuser_avatar"))
assert state.state == "2025-06-16T00:00:00+00:00"
access_token = state.attributes["access_token"]
assert (
state.attributes["entity_picture"]
== f"/api/image_proxy/image.testuser_avatar?token={access_token}"
)
client = await hass_client()
resp = await client.get(state.attributes["entity_picture"])
assert resp.status == HTTPStatus.OK
body = await resp.read()
assert body == b"Test"
assert resp.content_type == "image/png"
assert resp.content_length == 4
ava = "https://static-resource.np.community.playstation.net/avatar_m/WWS_E/E0011_m.png"
profile = mock_psnawpapi.user.return_value.profile.return_value
profile["avatars"] = [{"size": "xl", "url": ava}]
mock_psnawpapi.user.return_value.profile.return_value = profile
respx.get(ava).respond(
status_code=HTTPStatus.OK, content_type="image/png", content=b"Test2"
)
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert (state := hass.states.get("image.testuser_avatar"))
assert state.state == "2025-06-16T00:00:30+00:00"
access_token = state.attributes["access_token"]
assert (
state.attributes["entity_picture"]
== f"/api/image_proxy/image.testuser_avatar?token={access_token}"
)
client = await hass_client()
resp = await client.get(state.attributes["entity_picture"])
assert resp.status == HTTPStatus.OK
body = await resp.read()
assert body == b"Test2"
assert resp.content_type == "image/png"
assert resp.content_length == 5
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/playstation_network/test_image.py",
"license": "Apache License 2.0",
"lines": 77,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/playstation_network/test_init.py | """Tests for PlayStation Network."""
from datetime import timedelta
from unittest.mock import MagicMock
from freezegun.api import FrozenDateTimeFactory
from psnawp_api.core import (
PSNAWPAuthenticationError,
PSNAWPClientError,
PSNAWPForbiddenError,
PSNAWPNotFoundError,
PSNAWPServerError,
)
import pytest
from homeassistant.components.playstation_network.const import DOMAIN
from homeassistant.components.playstation_network.coordinator import (
PlaystationNetworkRuntimeData,
)
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry, async_fire_time_changed
@pytest.mark.parametrize(
"exception", [PSNAWPNotFoundError, PSNAWPServerError, PSNAWPClientError]
)
async def test_config_entry_not_ready(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
exception: Exception,
) -> None:
"""Test config entry not ready."""
mock_psnawpapi.user.side_effect = exception
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_RETRY
async def test_config_entry_auth_failed(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
) -> None:
"""Test config entry auth failed setup error."""
mock_psnawpapi.user.side_effect = PSNAWPAuthenticationError("error msg")
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
@pytest.mark.parametrize(
"exception", [PSNAWPNotFoundError, PSNAWPServerError, PSNAWPClientError]
)
async def test_coordinator_update_data_failed(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
exception: Exception,
) -> None:
"""Test coordinator data update failed."""
mock_psnawpapi.user.return_value.get_presence.side_effect = exception
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_RETRY
async def test_coordinator_update_auth_failed(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
) -> None:
"""Test coordinator update auth failed setup error."""
mock_psnawpapi.user.return_value.get_presence.side_effect = (
PSNAWPAuthenticationError("error msg")
)
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
async def test_trophy_title_coordinator(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test trophy title coordinator updates when PS Vita is registered."""
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.LOADED
assert len(mock_psnawpapi.user.return_value.trophy_titles.mock_calls) == 1
freezer.tick(timedelta(days=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert len(mock_psnawpapi.user.return_value.trophy_titles.mock_calls) == 2
async def test_trophy_title_coordinator_auth_failed(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test trophy title coordinator starts reauth on authentication error."""
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.LOADED
mock_psnawpapi.user.return_value.trophy_titles.side_effect = (
PSNAWPAuthenticationError("error msg")
)
freezer.tick(timedelta(days=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
await hass.async_block_till_done(wait_background_tasks=True)
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
@pytest.mark.parametrize(
"exception", [PSNAWPNotFoundError, PSNAWPServerError, PSNAWPClientError]
)
async def test_trophy_title_coordinator_update_data_failed(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
exception: Exception,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test trophy title coordinator update failed."""
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.LOADED
mock_psnawpapi.user.return_value.trophy_titles.side_effect = exception
freezer.tick(timedelta(days=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
await hass.async_block_till_done(wait_background_tasks=True)
runtime_data: PlaystationNetworkRuntimeData = config_entry.runtime_data
assert runtime_data.trophy_titles.last_update_success is False
async def test_trophy_title_coordinator_doesnt_update(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test trophy title coordinator does not update if no PS Vita is registered."""
mock_psnawpapi.me.return_value.get_account_devices.return_value = [
{"deviceType": "PS5"},
{"deviceType": "PS3"},
]
mock_psnawpapi.me.return_value.get_profile_legacy.return_value = {
"profile": {"presences": []}
}
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.LOADED
assert len(mock_psnawpapi.user.return_value.trophy_titles.mock_calls) == 1
freezer.tick(timedelta(days=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert len(mock_psnawpapi.user.return_value.trophy_titles.mock_calls) == 1
async def test_trophy_title_coordinator_play_new_game(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test we play a new game and get a title image on next trophy titles update."""
_tmp = mock_psnawpapi.user.return_value.trophy_titles.return_value
mock_psnawpapi.user.return_value.trophy_titles.return_value = []
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.LOADED
assert len(mock_psnawpapi.user.return_value.trophy_titles.mock_calls) == 1
assert (state := hass.states.get("media_player.playstation_vita"))
assert state.attributes.get("entity_picture") is None
mock_psnawpapi.user.return_value.trophy_titles.return_value = _tmp
# Wait one day to trigger PlaystationNetworkTrophyTitlesCoordinator refresh
freezer.tick(timedelta(days=1))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Wait another 30 seconds in case the PlaystationNetworkUserDataCoordinator,
# which has a 30 second update interval, updated before the
# PlaystationNetworkTrophyTitlesCoordinator.
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert len(mock_psnawpapi.user.return_value.trophy_titles.mock_calls) == 2
assert (state := hass.states.get("media_player.playstation_vita"))
assert (
state.attributes["entity_picture"]
== "https://image.api.playstation.com/trophy/np/NPWR03134_00_0008206095F67FD3BB385E9E00A7C9CFE6F5A4AB96/5F87A6997DD23D1C4D4CC0D1F958ED79CB905331.PNG"
)
@pytest.mark.parametrize(
"exception",
[PSNAWPNotFoundError, PSNAWPServerError, PSNAWPClientError, PSNAWPForbiddenError],
)
async def test_friends_coordinator_update_data_failed(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
exception: Exception,
) -> None:
"""Test friends coordinator setup fails in _update_data."""
mock = mock_psnawpapi.user.return_value.friends_list.return_value[0]
mock.get_presence.side_effect = exception
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_RETRY
@pytest.mark.parametrize(
("exception", "state"),
[
(PSNAWPNotFoundError("error msg"), ConfigEntryState.SETUP_ERROR),
(PSNAWPAuthenticationError("error msg"), ConfigEntryState.SETUP_ERROR),
(PSNAWPServerError("error msg"), ConfigEntryState.SETUP_RETRY),
(PSNAWPClientError("error msg"), ConfigEntryState.SETUP_RETRY),
],
)
async def test_friends_coordinator_setup_failed(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
exception: Exception,
state: ConfigEntryState,
) -> None:
"""Test friends coordinator setup fails in _async_setup."""
mock = mock_psnawpapi.user.return_value.friends_list.return_value[0]
mock.profile.side_effect = exception
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 state
async def test_friends_coordinator_auth_failed(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
) -> None:
"""Test friends coordinator starts reauth on authentication error."""
mock = mock_psnawpapi.user.return_value.friends_list.return_value[0]
mock.profile.side_effect = PSNAWPAuthenticationError("error msg")
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/playstation_network/test_init.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/playstation_network/test_notify.py | """Tests for the PlayStation Network notify platform."""
from collections.abc import AsyncGenerator
from unittest.mock import MagicMock, patch
from psnawp_api.core.psnawp_exceptions import (
PSNAWPClientError,
PSNAWPForbiddenError,
PSNAWPNotFoundError,
PSNAWPServerError,
)
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.notify import (
ATTR_MESSAGE,
DOMAIN as NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
)
from homeassistant.components.playstation_network.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture(autouse=True)
async def notify_only() -> AsyncGenerator[None]:
"""Enable only the notify platform."""
with patch(
"homeassistant.components.playstation_network.PLATFORMS",
[Platform.NOTIFY],
):
yield
@pytest.mark.usefixtures("mock_psnawpapi", "entity_registry_enabled_by_default")
async def test_notify_platform(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test setup of the notify platform."""
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.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize(
"entity_id",
[
"notify.testuser_group_publicuniversalfriend",
"notify.testuser_direct_message_publicuniversalfriend",
],
)
@pytest.mark.freeze_time("2025-07-28T00:00:00+00:00")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_send_message(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
entity_id: str,
) -> None:
"""Test send message."""
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.LOADED
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNKNOWN
await hass.services.async_call(
NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
{
ATTR_ENTITY_ID: entity_id,
ATTR_MESSAGE: "henlo fren",
},
blocking=True,
)
state = hass.states.get(entity_id)
assert state
assert state.state == "2025-07-28T00:00:00+00:00"
mock_psnawpapi.group.return_value.send_message.assert_called_once_with("henlo fren")
@pytest.mark.parametrize(
"exception",
[
PSNAWPClientError("error msg"),
PSNAWPForbiddenError("error msg"),
PSNAWPNotFoundError("error msg"),
PSNAWPServerError("error msg"),
],
)
async def test_send_message_exceptions(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
exception: Exception,
) -> None:
"""Test send message exceptions."""
mock_psnawpapi.group.return_value.send_message.side_effect = exception
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.LOADED
state = hass.states.get("notify.testuser_group_publicuniversalfriend")
assert state
assert state.state == STATE_UNKNOWN
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
{
ATTR_ENTITY_ID: "notify.testuser_group_publicuniversalfriend",
ATTR_MESSAGE: "henlo fren",
},
blocking=True,
)
mock_psnawpapi.group.return_value.send_message.assert_called_once_with("henlo fren")
async def test_notify_skip_forbidden(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test we skip creation of notifiers if forbidden by parental controls."""
mock_psnawpapi.me.return_value.get_groups.side_effect = PSNAWPForbiddenError(
"""{"error": {"message": "Not permitted by parental control"}}"""
)
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.LOADED
state = hass.states.get("notify.testuser_group_publicuniversalfriend")
assert state is None
assert issue_registry.async_get_issue(
domain=DOMAIN, issue_id=f"group_chat_forbidden_{config_entry.entry_id}"
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/playstation_network/test_notify.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/smartthings/test_vacuum.py | """Test for the SmartThings vacuum platform."""
from unittest.mock import AsyncMock
from pysmartthings import Attribute, Capability, Command
from pysmartthings.models import HealthStatus
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.smartthings import MAIN
from homeassistant.components.vacuum import (
ATTR_FAN_SPEED,
DOMAIN as VACUUM_DOMAIN,
SERVICE_PAUSE,
SERVICE_RETURN_TO_BASE,
SERVICE_SET_FAN_SPEED,
SERVICE_START,
VacuumActivity,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import (
setup_integration,
snapshot_smartthings_entities,
trigger_health_update,
trigger_update,
)
from tests.common import MockConfigEntry
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
await setup_integration(hass, mock_config_entry)
snapshot_smartthings_entities(hass, entity_registry, snapshot, Platform.VACUUM)
@pytest.mark.parametrize("device_fixture", ["da_rvc_map_01011"])
@pytest.mark.parametrize(
("action", "command"),
[
(SERVICE_START, Command.START),
(SERVICE_PAUSE, Command.PAUSE),
(SERVICE_RETURN_TO_BASE, Command.RETURN_TO_HOME),
],
)
async def test_vacuum_actions(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
action: str,
command: Command,
) -> None:
"""Test vacuum actions."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
VACUUM_DOMAIN,
action,
{ATTR_ENTITY_ID: "vacuum.robot_vacuum"},
blocking=True,
)
devices.execute_device_command.assert_called_once_with(
"01b28624-5907-c8bc-0325-8ad23f03a637",
Capability.SAMSUNG_CE_ROBOT_CLEANER_OPERATING_STATE,
command,
MAIN,
)
@pytest.mark.parametrize("device_fixture", ["da_rvc_map_01011"])
async def test_state_update(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test state update."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("vacuum.robot_vacuum").state == VacuumActivity.DOCKED
await trigger_update(
hass,
devices,
"01b28624-5907-c8bc-0325-8ad23f03a637",
Capability.SAMSUNG_CE_ROBOT_CLEANER_OPERATING_STATE,
Attribute.OPERATING_STATE,
"error",
)
assert hass.states.get("vacuum.robot_vacuum").state == VacuumActivity.ERROR
@pytest.mark.parametrize("device_fixture", ["da_rvc_map_01011"])
async def test_availability(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test availability."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("vacuum.robot_vacuum").state == VacuumActivity.DOCKED
await trigger_health_update(
hass, devices, "01b28624-5907-c8bc-0325-8ad23f03a637", HealthStatus.OFFLINE
)
assert hass.states.get("vacuum.robot_vacuum").state == STATE_UNAVAILABLE
await trigger_health_update(
hass, devices, "01b28624-5907-c8bc-0325-8ad23f03a637", HealthStatus.ONLINE
)
assert hass.states.get("vacuum.robot_vacuum").state == VacuumActivity.DOCKED
@pytest.mark.parametrize("device_fixture", ["da_rvc_map_01011"])
async def test_availability_at_start(
hass: HomeAssistant,
unavailable_device: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test unavailable at boot."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("vacuum.robot_vacuum").state == STATE_UNAVAILABLE
@pytest.mark.parametrize("device_fixture", ["da_rvc_map_01011"])
async def test_fan_speed_update(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test fan speed state update."""
await setup_integration(hass, mock_config_entry)
assert (
hass.states.get("vacuum.robot_vacuum").attributes[ATTR_FAN_SPEED] == "maximum"
)
await trigger_update(
hass,
devices,
"01b28624-5907-c8bc-0325-8ad23f03a637",
Capability.ROBOT_CLEANER_TURBO_MODE,
Attribute.ROBOT_CLEANER_TURBO_MODE,
"extraSilence",
)
assert hass.states.get("vacuum.robot_vacuum").attributes[ATTR_FAN_SPEED] == "quiet"
@pytest.mark.parametrize("device_fixture", ["da_rvc_map_01011"])
async def test_vacuum_set_fan_speed(
hass: HomeAssistant,
devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setting fan speed."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_SET_FAN_SPEED,
{ATTR_ENTITY_ID: "vacuum.robot_vacuum", ATTR_FAN_SPEED: "normal"},
blocking=True,
)
devices.execute_device_command.assert_called_once_with(
"01b28624-5907-c8bc-0325-8ad23f03a637",
Capability.ROBOT_CLEANER_TURBO_MODE,
Command.SET_ROBOT_CLEANER_TURBO_MODE,
MAIN,
"silence",
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/smartthings/test_vacuum.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/smhi/test_sensor.py | """Test for the smhi weather entity."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import EntityRegistry
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize(
"load_platforms",
[[Platform.SENSOR]],
)
async def test_sensor_setup(
hass: HomeAssistant,
entity_registry: EntityRegistry,
load_int: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test for successfully setting up the smhi sensors."""
await snapshot_platform(hass, entity_registry, snapshot, load_int.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/smhi/test_sensor.py",
"license": "Apache License 2.0",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/snapcast/test_media_player.py | """Test the snapcast media player implementation."""
from unittest.mock import AsyncMock, PropertyMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.media_player import (
ATTR_GROUP_MEMBERS,
DOMAIN as MEDIA_PLAYER_DOMAIN,
SERVICE_JOIN,
SERVICE_UNJOIN,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_state(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_server: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test basic state information."""
# Setup and verify the integration is loaded
with patch("secrets.token_hex", return_value="mock_token"):
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("members"),
[
["media_player.test_client_2_snapcast_client"],
[
"media_player.test_client_1_snapcast_client",
"media_player.test_client_2_snapcast_client",
],
],
)
async def test_join(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_server: AsyncMock,
mock_group_1: AsyncMock,
mock_client_2: AsyncMock,
members: list[str],
) -> None:
"""Test grouping of media players through the join service."""
# Setup and verify the integration is loaded
with patch("secrets.token_hex", return_value="mock_token"):
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_JOIN,
{
ATTR_ENTITY_ID: "media_player.test_client_1_snapcast_client",
ATTR_GROUP_MEMBERS: members,
},
blocking=True,
)
mock_group_1.add_client.assert_awaited_once_with(mock_client_2.identifier)
async def test_unjoin(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_server: AsyncMock,
mock_client_1: AsyncMock,
mock_group_1: AsyncMock,
) -> None:
"""Test the unjoin service removes the client from the group."""
# Setup and verify the integration is loaded
with patch("secrets.token_hex", return_value="mock_token"):
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_UNJOIN,
{
ATTR_ENTITY_ID: "media_player.test_client_1_snapcast_client",
},
blocking=True,
)
mock_group_1.remove_client.assert_awaited_once_with(mock_client_1.identifier)
async def test_join_exception(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_create_server: AsyncMock,
mock_group_1: AsyncMock,
) -> None:
"""Test join service throws an exception when trying to add a non-Snapcast client."""
# Create a dummy media player entity
entity_registry.async_get_or_create(
MEDIA_PLAYER_DOMAIN,
"dummy",
"media_player_1",
)
await hass.async_block_till_done()
# Setup and verify the integration is loaded
with patch("secrets.token_hex", return_value="mock_token"):
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_JOIN,
{
ATTR_ENTITY_ID: "media_player.test_client_1_snapcast_client",
ATTR_GROUP_MEMBERS: ["media_player.dummy_media_player_1"],
},
blocking=True,
)
# Ensure that the group did not attempt to add a non-Snapcast client
mock_group_1.add_client.assert_not_awaited()
async def test_stream_not_found(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_server: AsyncMock,
mock_group_2: AsyncMock,
) -> None:
"""Test server.stream call KeyError."""
mock_create_server.streams = []
with patch("secrets.token_hex", return_value="mock_token"):
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
state = hass.states.get("media_player.test_client_2_snapcast_client")
assert "media_position" not in state.attributes
assert "metadata" not in state.attributes
async def test_state_stream_not_found(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_server: AsyncMock,
mock_group_1: AsyncMock,
) -> None:
"""Test state returns OFF when stream is not found."""
type(mock_group_1).stream_status = PropertyMock(
side_effect=KeyError("Stream not found")
)
with patch("secrets.token_hex", return_value="mock_token"):
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
state = hass.states.get("media_player.test_client_1_snapcast_client")
assert state.state == "off"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/snapcast/test_media_player.py",
"license": "Apache License 2.0",
"lines": 144,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/stookwijzer/test_services.py | """Tests for the Stookwijzer services."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.stookwijzer.const import DOMAIN, SERVICE_GET_FORECAST
from homeassistant.const import ATTR_CONFIG_ENTRY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("init_integration")
async def test_service_get_forecast(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Stookwijzer forecast service."""
assert snapshot == await hass.services.async_call(
DOMAIN,
SERVICE_GET_FORECAST,
{ATTR_CONFIG_ENTRY_ID: mock_config_entry.entry_id},
blocking=True,
return_response=True,
)
@pytest.mark.usefixtures("init_integration")
async def test_service_entry_not_loaded(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test error handling when entry is not loaded."""
mock_config_entry2 = MockConfigEntry(domain=DOMAIN)
mock_config_entry2.add_to_hass(hass)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_GET_FORECAST,
{ATTR_CONFIG_ENTRY_ID: mock_config_entry2.entry_id},
blocking=True,
return_response=True,
)
assert err.value.translation_key == "service_config_entry_not_loaded"
@pytest.mark.usefixtures("init_integration")
async def test_service_integration_not_found(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test error handling when integration not in registry."""
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
SERVICE_GET_FORECAST,
{ATTR_CONFIG_ENTRY_ID: "bad-config_id"},
blocking=True,
return_response=True,
)
assert err.value.translation_key == "service_config_entry_not_found"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/stookwijzer/test_services.py",
"license": "Apache License 2.0",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/switchbot_cloud/test_fan.py | """Test for the Switchbot Battery Circulator Fan."""
from unittest.mock import patch
import pytest
import switchbot_api
from switchbot_api import Device, SwitchBotAPI
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.fan import (
ATTR_PERCENTAGE,
ATTR_PRESET_MODE,
DOMAIN as FAN_DOMAIN,
SERVICE_SET_PERCENTAGE,
SERVICE_SET_PRESET_MODE,
SERVICE_TURN_ON,
)
from homeassistant.components.switchbot_cloud.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
STATE_OFF,
STATE_ON,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import AIR_PURIFIER_INFO, CIRCULATOR_FAN_INFO, configure_integration
from tests.common import async_load_json_object_fixture, snapshot_platform
@pytest.mark.parametrize(
("device_info", "entry_id"),
[
(AIR_PURIFIER_INFO, "fan.air_purifier_1"),
(CIRCULATOR_FAN_INFO, "fan.battery_fan_1"),
],
)
async def test_coordinator_data_is_none(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
device_info: Device,
entry_id: str,
) -> None:
"""Test coordinator data is none."""
mock_list_devices.return_value = [device_info]
mock_get_status.side_effect = [None]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
state = hass.states.get(entry_id)
assert state.state == STATE_UNKNOWN
async def test_turn_on(hass: HomeAssistant, mock_list_devices, mock_get_status) -> None:
"""Test turning on the fan."""
mock_list_devices.return_value = [
CIRCULATOR_FAN_INFO,
]
mock_get_status.side_effect = [
{"power": "off", "mode": "direct", "fanSpeed": "0"},
{"power": "on", "mode": "direct", "fanSpeed": "0"},
{"power": "on", "mode": "direct", "fanSpeed": "0"},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "fan.battery_fan_1"
state = hass.states.get(entity_id)
assert state.state == STATE_OFF
with (
patch.object(SwitchBotAPI, "send_command") as mock_send_command,
):
await hass.services.async_call(
FAN_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity_id}, blocking=True
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state == STATE_ON
async def test_turn_off(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test turning off the fan."""
mock_list_devices.return_value = [
CIRCULATOR_FAN_INFO,
]
mock_get_status.side_effect = [
{"power": "on", "mode": "direct", "fanSpeed": "0"},
{"power": "off", "mode": "direct", "fanSpeed": "0"},
{"power": "off", "mode": "direct", "fanSpeed": "0"},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "fan.battery_fan_1"
state = hass.states.get(entity_id)
assert state.state == STATE_ON
with (
patch.object(SwitchBotAPI, "send_command") as mock_send_command,
):
await hass.services.async_call(
FAN_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id}, blocking=True
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state == STATE_OFF
async def test_set_percentage(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test set percentage."""
mock_list_devices.return_value = [
CIRCULATOR_FAN_INFO,
]
mock_get_status.side_effect = [
{"power": "on", "mode": "direct", "fanSpeed": "0"},
{"power": "on", "mode": "direct", "fanSpeed": "0"},
{"power": "off", "mode": "direct", "fanSpeed": "5"},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "fan.battery_fan_1"
state = hass.states.get(entity_id)
assert state.state == STATE_ON
with (
patch.object(SwitchBotAPI, "send_command") as mock_send_command,
):
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_PERCENTAGE,
{ATTR_ENTITY_ID: entity_id, ATTR_PERCENTAGE: 5},
blocking=True,
)
mock_send_command.assert_called()
async def test_set_preset_mode(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test set preset mode."""
mock_list_devices.return_value = [
CIRCULATOR_FAN_INFO,
]
mock_get_status.side_effect = [
{"power": "on", "mode": "direct", "fanSpeed": "0"},
{"power": "on", "mode": "direct", "fanSpeed": "0"},
{"power": "on", "mode": "baby", "fanSpeed": "0"},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "fan.battery_fan_1"
state = hass.states.get(entity_id)
assert state.state == STATE_ON
with (
patch.object(SwitchBotAPI, "send_command") as mock_send_command,
):
await hass.services.async_call(
FAN_DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: entity_id, ATTR_PRESET_MODE: "baby"},
blocking=True,
)
mock_send_command.assert_called_once()
async def test_air_purifier(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_list_devices,
mock_get_status,
) -> None:
"""Test air purifier."""
mock_list_devices.return_value = [AIR_PURIFIER_INFO]
mock_get_status.return_value = await async_load_json_object_fixture(
hass, "air_purifier_status.json", DOMAIN
)
with patch("homeassistant.components.switchbot_cloud.PLATFORMS", [Platform.FAN]):
entry = await configure_integration(hass)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
@pytest.mark.parametrize(
("service", "service_data", "expected_call_args"),
[
(
"turn_on",
{},
(
"air-purifier-id-1",
switchbot_api.CommonCommands.ON,
"command",
"default",
),
),
(
"turn_off",
{},
(
"air-purifier-id-1",
switchbot_api.CommonCommands.OFF,
"command",
"default",
),
),
(
"set_preset_mode",
{"preset_mode": "sleep"},
(
"air-purifier-id-1",
switchbot_api.AirPurifierCommands.SET_MODE,
"command",
{"mode": 3},
),
),
],
)
async def test_air_purifier_controller(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
service: str,
service_data: dict,
expected_call_args: tuple,
) -> None:
"""Test controlling the air purifier with mocked delay."""
mock_list_devices.return_value = [AIR_PURIFIER_INFO]
mock_get_status.return_value = {"power": "OFF", "mode": 2}
await configure_integration(hass)
fan_id = "fan.air_purifier_1"
with (
patch.object(SwitchBotAPI, "send_command") as mocked_send_command,
):
await hass.services.async_call(
FAN_DOMAIN,
service,
{**service_data, ATTR_ENTITY_ID: fan_id},
blocking=True,
)
mocked_send_command.assert_awaited_once_with(*expected_call_args)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/switchbot_cloud/test_fan.py",
"license": "Apache License 2.0",
"lines": 226,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/switchbot_cloud/test_light.py | """Test for the Switchbot Light Entity."""
from unittest.mock import patch
import pytest
from switchbot_api import CeilingLightCommands, CommonCommands, Device, SwitchBotAPI
from homeassistant.components.light import (
ATTR_COLOR_MODE,
DOMAIN as LIGHT_DOMAIN,
ColorMode,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from . import configure_integration
async def test_coordinator_data_is_none(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test coordinator data is none."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="light-id-1",
deviceName="light-1",
deviceType="Strip Light",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [None]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "light.light_1"
state = hass.states.get(entity_id)
assert state.state is STATE_UNKNOWN
async def test_strip_light_turn_off(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test strip light turn off."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="light-id-1",
deviceName="light-1",
deviceType="Strip Light",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{"power": "off", "brightness": 1, "color": "0:0:0", "colorTemperature": 4567},
{"power": "off", "brightness": 10, "color": "0:0:0", "colorTemperature": 5555},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "light.light_1"
# state = hass.states.get(entity_id)
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id}, blocking=True
)
mock_send_command.assert_called_once()
state = hass.states.get(entity_id)
assert state.state is STATE_OFF
async def test_rgbww_light_turn_off(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test rgbww light turn_off."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="light-id-1",
deviceName="light-1",
deviceType="Strip Light 3",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{"power": "off", "brightness": 1, "color": "0:0:0", "colorTemperature": 4567},
{"power": "off", "brightness": 10, "color": "0:0:0", "colorTemperature": 5555},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "light.light_1"
with (
patch.object(SwitchBotAPI, "send_command") as mock_send_command,
):
await hass.services.async_call(
LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id}, blocking=True
)
mock_send_command.assert_called_once()
state = hass.states.get(entity_id)
assert state.state is STATE_OFF
async def test_strip_light_turn_on(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test strip light turn on."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="light-id-1",
deviceName="light-1",
deviceType="Strip Light",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{"power": "off", "brightness": 1, "color": "0:0:0", "colorTemperature": 4567},
{"power": "on", "brightness": 10, "color": "0:0:0", "colorTemperature": 5555},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "light.light_1"
state = hass.states.get(entity_id)
assert state.state is STATE_OFF
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "brightness": 99},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "rgb_color": (255, 246, 158)},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "color_temp_kelvin": 3333},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
async def test_rgbww_light_turn_on(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test rgbww light turn on."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="light-id-1",
deviceName="light-1",
deviceType="Strip Light 3",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{"power": "off", "brightness": 1, "color": "0:0:0", "colorTemperature": 4567},
{"power": "on", "brightness": 10, "color": "0:0:0", "colorTemperature": 5555},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
"colorTemperature": 5555,
},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "light.light_1"
state = hass.states.get(entity_id)
assert state.state is STATE_OFF
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "color_temp_kelvin": 2800},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "brightness": 99},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "rgb_color": (255, 246, 158)},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
@pytest.mark.parametrize("device_type", ["Ceiling Light", "Ceiling Light Pro"])
async def test_ceiling_light_turn_on(
hass: HomeAssistant, mock_list_devices, mock_get_status, device_type
) -> None:
"""Test ceiling light turn on."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="light-id-1",
deviceName="light-1",
deviceType=device_type,
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{"power": "off", "brightness": 1, "colorTemperature": 4567},
{"power": "on", "brightness": 10, "colorTemperature": 5555},
{"power": "on", "brightness": 10, "colorTemperature": 5555},
{"power": "on", "brightness": 10, "colorTemperature": 5555},
{"power": "on", "brightness": 10, "colorTemperature": 5555},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "light.light_1"
state = hass.states.get(entity_id)
assert state.state is STATE_OFF
# Test turn on with brightness
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "brightness": 99},
blocking=True,
)
mock_send_command.assert_called_with(
"light-id-1",
CeilingLightCommands.SET_BRIGHTNESS,
"command",
"38",
)
state = hass.states.get(entity_id)
assert state.state is STATE_ON
assert state.attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP
# Test turn on with color temp
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "color_temp_kelvin": 3333},
blocking=True,
)
mock_send_command.assert_called_with(
"light-id-1",
CeilingLightCommands.SET_COLOR_TEMPERATURE,
"command",
"3333",
)
state = hass.states.get(entity_id)
assert state.state is STATE_ON
# Test turn on without arguments
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called_with(
"light-id-1",
CommonCommands.ON,
"command",
"default",
)
state = hass.states.get(entity_id)
assert state.state is STATE_ON
assert state.attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP
@pytest.mark.parametrize("device_type", ["Ceiling Light", "Ceiling Light Pro"])
async def test_ceiling_light_turn_off(
hass: HomeAssistant, mock_list_devices, mock_get_status, device_type
) -> None:
"""Test ceiling light turn off."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="light-id-1",
deviceName="light-1",
deviceType=device_type,
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{"power": "on", "brightness": 1, "colorTemperature": 4567},
{"power": "off", "brightness": 1, "colorTemperature": 4567},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "light.light_1"
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity_id}, blocking=True
)
mock_send_command.assert_called_with(
"light-id-1",
CommonCommands.OFF,
"command",
"default",
)
state = hass.states.get(entity_id)
assert state.state is STATE_OFF
@pytest.mark.parametrize(
"device_type", ["RGBIC Neon Rope Light", "RGBIC Neon Wire Rope Light"]
)
async def test_rgbic_neon_rope_light(
hass: HomeAssistant, mock_list_devices, mock_get_status, device_type
) -> None:
"""Test rgbic neon rope light."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="light-id-1",
deviceName="light-1",
deviceType=device_type,
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{"power": "off", "brightness": 1, "color": "0:0:0"},
{"power": "on", "brightness": 10, "color": "0:0:0"},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
},
{
"power": "on",
"brightness": 10,
"color": "255:255:255",
},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "light.light_1"
state = hass.states.get(entity_id)
assert state.state is STATE_OFF
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "brightness": 99},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "rgb_color": (255, 246, 158)},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
async def test_candle_warmer_lamp(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test candle warmer lamp."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="light-id-1",
deviceName="light-1",
deviceType="Candle Warmer Lamp",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{
"power": "off",
"brightness": 1,
},
{
"power": "on",
"brightness": 10,
},
{
"power": "on",
"brightness": 10,
},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "light.light_1"
state = hass.states.get(entity_id)
assert state.state is STATE_OFF
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, "brightness": 99},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called()
state = hass.states.get(entity_id)
assert state.state is STATE_ON
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/switchbot_cloud/test_light.py",
"license": "Apache License 2.0",
"lines": 508,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/switchbot_cloud/test_vacuum.py | """Test for the switchbot_cloud vacuum."""
from unittest.mock import patch
from switchbot_api import (
Device,
VacuumCleanerV2Commands,
VacuumCleanerV3Commands,
VacuumCleanMode,
VacuumCommands,
)
from homeassistant.components.switchbot_cloud import SwitchBotAPI
from homeassistant.components.switchbot_cloud.const import VACUUM_FAN_SPEED_QUIET
from homeassistant.components.vacuum import (
ATTR_FAN_SPEED,
DOMAIN as VACUUM_DOMAIN,
SERVICE_PAUSE,
SERVICE_RETURN_TO_BASE,
SERVICE_SET_FAN_SPEED,
SERVICE_START,
VacuumActivity,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from . import configure_integration
async def test_coordinator_data_is_none(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test coordinator data is none."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="K10+",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
None,
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
state = hass.states.get(entity_id)
assert state.state == STATE_UNKNOWN
async def test_k10_plus_set_fan_speed(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test K10 plus set fan speed."""
mock_list_devices.side_effect = [
[
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="K10+",
hubDeviceId="test-hub-id",
)
]
]
mock_get_status.side_effect = [
{
"deviceType": "K10+",
"workingStatus": "Cleaning",
"battery": 50,
"onlineStatus": "online",
},
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_SET_FAN_SPEED,
{ATTR_ENTITY_ID: entity_id, ATTR_FAN_SPEED: VACUUM_FAN_SPEED_QUIET},
blocking=True,
)
mock_send_command.assert_called_once_with(
"vacuum-id-1", VacuumCommands.POW_LEVEL, "command", "0"
)
async def test_k10_plus_return_to_base(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test k10 plus return to base."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="K10+",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{
"deviceType": "K10+",
"workingStatus": "Charging",
"battery": 50,
"onlineStatus": "online",
}
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
state = hass.states.get(entity_id)
assert state.state == VacuumActivity.DOCKED.value
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_RETURN_TO_BASE,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called_once_with(
"vacuum-id-1", VacuumCommands.DOCK, "command", "default"
)
async def test_k10_plus_pause(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test k10 plus pause."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="K10+",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{
"deviceType": "K10+",
"workingStatus": "Charging",
"battery": 50,
"onlineStatus": "online",
}
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
state = hass.states.get(entity_id)
assert state.state == VacuumActivity.DOCKED.value
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN, SERVICE_PAUSE, {ATTR_ENTITY_ID: entity_id}, blocking=True
)
mock_send_command.assert_called_once_with(
"vacuum-id-1", VacuumCommands.STOP, "command", "default"
)
async def test_k10_plus_set_start(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test K10 plus start."""
mock_list_devices.side_effect = [
[
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="K10+",
hubDeviceId="test-hub-id",
)
]
]
mock_get_status.side_effect = [
{
"deviceType": "K10+",
"workingStatus": "Cleaning",
"battery": 50,
"onlineStatus": "online",
},
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_START,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called_once_with(
"vacuum-id-1", VacuumCommands.START, "command", "default"
)
async def test_k20_plus_pro_set_fan_speed(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test K10 plus set fan speed."""
mock_list_devices.side_effect = [
[
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="K20+ Pro",
hubDeviceId="test-hub-id",
)
]
]
mock_get_status.side_effect = [
{
"deviceType": "K20+ Pro",
"workingStatus": "Cleaning",
"battery": 50,
"onlineStatus": "online",
},
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_SET_FAN_SPEED,
{ATTR_ENTITY_ID: entity_id, ATTR_FAN_SPEED: VACUUM_FAN_SPEED_QUIET},
blocking=True,
)
mock_send_command.assert_called_once_with(
"vacuum-id-1",
VacuumCleanerV2Commands.CHANGE_PARAM,
"command",
{
"fanLevel": 1,
"waterLevel": 1,
"times": 1,
},
)
async def test_k20_plus_pro_return_to_base(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test K20+ Pro return to base."""
mock_list_devices.side_effect = [
[
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="K20+ Pro",
hubDeviceId="test-hub-id",
)
]
]
mock_get_status.side_effect = [
{
"deviceType": "K20+ Pro",
"workingStatus": "Charging",
"battery": 50,
"onlineStatus": "online",
},
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
state = hass.states.get(entity_id)
assert state.state == VacuumActivity.DOCKED.value
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_RETURN_TO_BASE,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called_once_with(
"vacuum-id-1", VacuumCleanerV2Commands.DOCK, "command", "default"
)
async def test_k20_plus_pro_pause(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test K20+ Pro pause."""
mock_list_devices.side_effect = [
[
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="K20+ Pro",
hubDeviceId="test-hub-id",
)
]
]
mock_get_status.side_effect = [
{
"deviceType": "K20+ Pro",
"workingStatus": "Charging",
"battery": 50,
"onlineStatus": "online",
},
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
state = hass.states.get(entity_id)
assert state.state == VacuumActivity.DOCKED.value
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN, SERVICE_PAUSE, {ATTR_ENTITY_ID: entity_id}, blocking=True
)
mock_send_command.assert_called_once_with(
"vacuum-id-1", VacuumCleanerV2Commands.PAUSE, "command", "default"
)
async def test_k20_plus_pro_start(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test K20+ Pro start."""
mock_list_devices.side_effect = [
[
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="K20+ Pro",
hubDeviceId="test-hub-id",
)
]
]
mock_get_status.side_effect = [
{
"deviceType": "K20+ Pro",
"workingStatus": "Cleaning",
"battery": 50,
"onlineStatus": "online",
},
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_START,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called_once_with(
"vacuum-id-1",
VacuumCleanerV2Commands.START_CLEAN,
"command",
{
"action": VacuumCleanMode.SWEEP.value,
"param": {
"fanLevel": 1,
"times": 1,
},
},
)
async def test_k10_plus_pro_combo_set_fan_speed(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test k10+ Pro Combo set fan speed."""
mock_list_devices.side_effect = [
[
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="Robot Vacuum Cleaner K10+ Pro Combo",
hubDeviceId="test-hub-id",
)
]
]
mock_get_status.side_effect = [
{
"deviceType": "Robot Vacuum Cleaner K10+ Pro Combo",
"workingStatus": "Cleaning",
"battery": 50,
"onlineStatus": "online",
},
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_SET_FAN_SPEED,
{ATTR_ENTITY_ID: entity_id, ATTR_FAN_SPEED: VACUUM_FAN_SPEED_QUIET},
blocking=True,
)
mock_send_command.assert_called_once_with(
"vacuum-id-1",
VacuumCleanerV2Commands.CHANGE_PARAM,
"command",
{
"fanLevel": 1,
"times": 1,
},
)
async def test_s20_start(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test s20 start."""
mock_list_devices.side_effect = [
[
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="S20",
hubDeviceId="test-hub-id",
)
]
]
mock_get_status.side_effect = [
{
"deviceType": "s20",
"workingStatus": "Cleaning",
"battery": 50,
"onlineStatus": "online",
},
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_START,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called_once_with(
"vacuum-id-1",
VacuumCleanerV3Commands.START_CLEAN,
"command",
{
"action": VacuumCleanMode.SWEEP.value,
"param": {
"fanLevel": 0,
"waterLevel": 1,
"times": 1,
},
},
)
async def test_s20_set_fan_speed(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test s20 set fan speed."""
mock_list_devices.side_effect = [
[
Device(
version="V1.0",
deviceId="vacuum-id-1",
deviceName="vacuum-1",
deviceType="S20",
hubDeviceId="test-hub-id",
)
]
]
mock_get_status.side_effect = [
{
"deviceType": "S20",
"workingStatus": "Cleaning",
"battery": 50,
"onlineStatus": "online",
},
]
await configure_integration(hass)
entity_id = "vacuum.vacuum_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
VACUUM_DOMAIN,
SERVICE_SET_FAN_SPEED,
{ATTR_ENTITY_ID: entity_id, ATTR_FAN_SPEED: VACUUM_FAN_SPEED_QUIET},
blocking=True,
)
mock_send_command.assert_called_once_with(
"vacuum-id-1",
VacuumCleanerV3Commands.CHANGE_PARAM,
"command",
{
"fanLevel": 1,
"waterLevel": 1,
"times": 1,
},
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/switchbot_cloud/test_vacuum.py",
"license": "Apache License 2.0",
"lines": 465,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/template/test_helpers.py | """The tests for template helpers."""
import pytest
from homeassistant.components.template.alarm_control_panel import (
LEGACY_FIELDS as ALARM_CONTROL_PANEL_LEGACY_FIELDS,
)
from homeassistant.components.template.binary_sensor import (
LEGACY_FIELDS as BINARY_SENSOR_LEGACY_FIELDS,
)
from homeassistant.components.template.button import StateButtonEntity
from homeassistant.components.template.cover import LEGACY_FIELDS as COVER_LEGACY_FIELDS
from homeassistant.components.template.fan import LEGACY_FIELDS as FAN_LEGACY_FIELDS
from homeassistant.components.template.helpers import (
async_setup_template_platform,
create_legacy_template_issue,
format_migration_config,
rewrite_legacy_to_modern_config,
rewrite_legacy_to_modern_configs,
)
from homeassistant.components.template.light import LEGACY_FIELDS as LIGHT_LEGACY_FIELDS
from homeassistant.components.template.lock import LEGACY_FIELDS as LOCK_LEGACY_FIELDS
from homeassistant.components.template.sensor import (
LEGACY_FIELDS as SENSOR_LEGACY_FIELDS,
)
from homeassistant.components.template.switch import (
LEGACY_FIELDS as SWITCH_LEGACY_FIELDS,
)
from homeassistant.components.template.vacuum import (
LEGACY_FIELDS as VACUUM_LEGACY_FIELDS,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.template import Template
from homeassistant.setup import async_setup_component
@pytest.mark.parametrize(
("legacy_fields", "old_attr", "new_attr", "attr_template"),
[
(
LOCK_LEGACY_FIELDS,
"value_template",
"state",
"{{ 1 == 1 }}",
),
(
LOCK_LEGACY_FIELDS,
"code_format_template",
"code_format",
"{{ 'some format' }}",
),
],
)
async def test_legacy_to_modern_config(
hass: HomeAssistant,
legacy_fields,
old_attr: str,
new_attr: str,
attr_template: str,
) -> None:
"""Test the conversion of single legacy template to modern template."""
config = {
"friendly_name": "foo bar",
"unique_id": "foo-bar-entity",
"icon_template": "{{ 'mdi.abc' }}",
"entity_picture_template": "{{ 'mypicture.jpg' }}",
"availability_template": "{{ 1 == 1 }}",
old_attr: attr_template,
}
altered_configs = rewrite_legacy_to_modern_config(hass, config, legacy_fields)
assert {
"availability": Template("{{ 1 == 1 }}", hass),
"icon": Template("{{ 'mdi.abc' }}", hass),
"name": Template("foo bar", hass),
"picture": Template("{{ 'mypicture.jpg' }}", hass),
"unique_id": "foo-bar-entity",
new_attr: Template(attr_template, hass),
} == altered_configs
@pytest.mark.parametrize(
("domain", "legacy_fields", "old_attr", "new_attr", "attr_template"),
[
(
"alarm_control_panel",
ALARM_CONTROL_PANEL_LEGACY_FIELDS,
"value_template",
"state",
"{{ 1 == 1 }}",
),
(
"binary_sensor",
BINARY_SENSOR_LEGACY_FIELDS,
"value_template",
"state",
"{{ 1 == 1 }}",
),
(
"cover",
COVER_LEGACY_FIELDS,
"value_template",
"state",
"{{ 1 == 1 }}",
),
(
"cover",
COVER_LEGACY_FIELDS,
"position_template",
"position",
"{{ 100 }}",
),
(
"cover",
COVER_LEGACY_FIELDS,
"tilt_template",
"tilt",
"{{ 100 }}",
),
(
"fan",
FAN_LEGACY_FIELDS,
"value_template",
"state",
"{{ 1 == 1 }}",
),
(
"fan",
FAN_LEGACY_FIELDS,
"direction_template",
"direction",
"{{ 1 == 1 }}",
),
(
"fan",
FAN_LEGACY_FIELDS,
"oscillating_template",
"oscillating",
"{{ True }}",
),
(
"fan",
FAN_LEGACY_FIELDS,
"percentage_template",
"percentage",
"{{ 100 }}",
),
(
"fan",
FAN_LEGACY_FIELDS,
"preset_mode_template",
"preset_mode",
"{{ 'foo' }}",
),
(
"fan",
LIGHT_LEGACY_FIELDS,
"value_template",
"state",
"{{ 1 == 1 }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"rgb_template",
"rgb",
"{{ (255,255,255) }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"rgbw_template",
"rgbw",
"{{ (255,255,255,255) }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"rgbww_template",
"rgbww",
"{{ (255,255,255,255,255) }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"effect_list_template",
"effect_list",
"{{ ['a', 'b'] }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"effect_template",
"effect",
"{{ 'a' }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"level_template",
"level",
"{{ 255 }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"max_mireds_template",
"max_mireds",
"{{ 255 }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"min_mireds_template",
"min_mireds",
"{{ 255 }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"supports_transition_template",
"supports_transition",
"{{ True }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"temperature_template",
"temperature",
"{{ 255 }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"white_value_template",
"white_value",
"{{ 255 }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"hs_template",
"hs",
"{{ (255, 255) }}",
),
(
"light",
LIGHT_LEGACY_FIELDS,
"color_template",
"hs",
"{{ (255, 255) }}",
),
(
"sensor",
SENSOR_LEGACY_FIELDS,
"value_template",
"state",
"{{ 1 == 1 }}",
),
(
"sensor",
SWITCH_LEGACY_FIELDS,
"value_template",
"state",
"{{ 1 == 1 }}",
),
(
"vacuum",
VACUUM_LEGACY_FIELDS,
"value_template",
"state",
"{{ 1 == 1 }}",
),
(
"vacuum",
VACUUM_LEGACY_FIELDS,
"battery_level_template",
"battery_level",
"{{ 100 }}",
),
(
"vacuum",
VACUUM_LEGACY_FIELDS,
"fan_speed_template",
"fan_speed",
"{{ 7 }}",
),
],
)
async def test_legacy_to_modern_configs(
hass: HomeAssistant,
domain: str,
legacy_fields,
old_attr: str,
new_attr: str,
attr_template: str,
) -> None:
"""Test the conversion of legacy template to modern template."""
config = {
"foo": {
"friendly_name": "foo bar",
"unique_id": "foo-bar-entity",
"icon_template": "{{ 'mdi.abc' }}",
"entity_picture_template": "{{ 'mypicture.jpg' }}",
"availability_template": "{{ 1 == 1 }}",
old_attr: attr_template,
}
}
altered_configs = rewrite_legacy_to_modern_configs(
hass, domain, config, legacy_fields
)
assert len(altered_configs) == 1
assert [
{
"availability": Template("{{ 1 == 1 }}", hass),
"icon": Template("{{ 'mdi.abc' }}", hass),
"name": Template("foo bar", hass),
"default_entity_id": f"{domain}.foo",
"picture": Template("{{ 'mypicture.jpg' }}", hass),
"unique_id": "foo-bar-entity",
new_attr: Template(attr_template, hass),
}
] == altered_configs
@pytest.mark.parametrize(
("domain", "legacy_fields"),
[
("binary_sensor", BINARY_SENSOR_LEGACY_FIELDS),
("sensor", SENSOR_LEGACY_FIELDS),
],
)
async def test_friendly_name_template_legacy_to_modern_configs(
hass: HomeAssistant,
domain: str,
legacy_fields,
) -> None:
"""Test the conversion of friendly_name_tempalte in legacy template to modern template."""
config = {
"foo": {
"unique_id": "foo-bar-entity",
"icon_template": "{{ 'mdi.abc' }}",
"entity_picture_template": "{{ 'mypicture.jpg' }}",
"availability_template": "{{ 1 == 1 }}",
"friendly_name_template": "{{ 'foo bar' }}",
}
}
altered_configs = rewrite_legacy_to_modern_configs(
hass, domain, config, legacy_fields
)
assert len(altered_configs) == 1
assert [
{
"availability": Template("{{ 1 == 1 }}", hass),
"icon": Template("{{ 'mdi.abc' }}", hass),
"default_entity_id": f"{domain}.foo",
"picture": Template("{{ 'mypicture.jpg' }}", hass),
"unique_id": "foo-bar-entity",
"name": Template("{{ 'foo bar' }}", hass),
}
] == altered_configs
async def test_platform_not_ready(
hass: HomeAssistant,
) -> None:
"""Test async_setup_template_platform raises PlatformNotReady when trigger object is None."""
with pytest.raises(PlatformNotReady):
await async_setup_template_platform(
hass,
"button",
{},
StateButtonEntity,
None,
None,
{"coordinator": None, "entities": []},
)
@pytest.mark.parametrize(
("domain", "config", "breadcrumb"),
[
(
"template",
{
"template": [
{
"sensors": {
"undocumented_configuration": {
"value_template": "{{ 'armed_away' }}",
}
}
},
]
},
"undocumented_configuration",
),
(
"template",
{
"template": [
{
"binary_sensors": {
"undocumented_configuration": {
"value_template": "{{ 'armed_away' }}",
}
}
},
]
},
"undocumented_configuration",
),
(
"alarm_control_panel",
{
"alarm_control_panel": {
"platform": "template",
"panels": {
"safe_alarm_panel": {
"value_template": "{{ 'armed_away' }}",
}
},
},
},
"safe_alarm_panel",
),
(
"binary_sensor",
{
"binary_sensor": {
"platform": "template",
"sensors": {
"sun_up": {
"value_template": "{{ state_attr('sun.sun', 'elevation') > 0 }}",
}
},
},
},
"sun_up",
),
(
"cover",
{
"cover": {
"platform": "template",
"covers": {
"garage_door": {
"value_template": "{{ states('sensor.garage_door')|float > 0 }}",
"open_cover": {"action": "script.toggle"},
"close_cover": {"action": "script.toggle"},
}
},
},
},
"garage_door",
),
(
"fan",
{
"fan": {
"platform": "template",
"fans": {
"bedroom_fan": {
"value_template": "{{ states('input_boolean.state') }}",
"turn_on": {"action": "script.toggle"},
"turn_off": {"action": "script.toggle"},
}
},
},
},
"bedroom_fan",
),
(
"light",
{
"light": {
"platform": "template",
"lights": {
"theater_lights": {
"value_template": "{{ states('input_boolean.state') }}",
"turn_on": {"action": "script.toggle"},
"turn_off": {"action": "script.toggle"},
}
},
},
},
"theater_lights",
),
(
"lock",
{
"lock": {
"platform": "template",
"value_template": "{{ states('input_boolean.state') }}",
"lock": {"action": "script.toggle"},
"unlock": {"action": "script.toggle"},
},
},
"Template Entity",
),
(
"sensor",
{
"sensor": {
"platform": "template",
"sensors": {
"test_template_sensor": {
"value_template": "It {{ states.sensor.test_state.state }}.",
"attribute_templates": {"something": "{{ 'bar' }}"},
}
},
},
},
"test_template_sensor",
),
(
"switch",
{
"switch": {
"platform": "template",
"switches": {
"skylight": {
"value_template": "{{ is_state('sensor.skylight', 'on') }}",
"turn_on": {"action": "script.toggle"},
"turn_off": {"action": "script.toggle"},
}
},
},
},
"skylight",
),
(
"vacuum",
{
"vacuum": {
"platform": "template",
"vacuums": {
"living_room_vacuum": {
"start": {"action": "script.start"},
"attribute_templates": {"something": "{{ 'bar' }}"},
}
},
},
},
"living_room_vacuum",
),
(
"weather",
{
"weather": {
"platform": "template",
"name": "My Weather Station",
"unique_id": "Foobar",
"condition_template": "{{ 'rainy' }}",
"temperature_template": "{{ 20 }}",
"humidity_template": "{{ 50 }}",
},
},
"unique_id: Foobar",
),
(
"weather",
{
"weather": {
"platform": "template",
"name": "My Weather Station",
"condition_template": "{{ 'rainy' }}",
"temperature_template": "{{ 20 }}",
"humidity_template": "{{ 50 }}",
},
},
"My Weather Station",
),
],
)
async def test_legacy_deprecation(
hass: HomeAssistant,
domain: str,
config: dict,
breadcrumb: str,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test legacy configuration raises issue."""
await async_setup_component(hass, domain, config)
await hass.async_block_till_done()
assert len(issue_registry.issues) == 1
issue = next(iter(issue_registry.issues.values()))
assert issue.domain == "template"
assert issue.severity == ir.IssueSeverity.WARNING
assert issue.translation_placeholders["breadcrumb"] == breadcrumb
assert "platform: template" not in issue.translation_placeholders["config"]
@pytest.mark.parametrize(
("domain", "config", "strings_to_check"),
[
(
"light",
{
"light": {
"platform": "template",
"lights": {
"garage_light_template": {
"friendly_name": "Garage Light Template",
"min_mireds_template": 153,
"max_mireds_template": 500,
"turn_on": [],
"turn_off": [],
"set_temperature": [],
"set_hs": [],
"set_level": [],
}
},
},
},
[
"turn_on: []",
"turn_off: []",
"set_temperature: []",
"set_hs: []",
"set_level: []",
],
),
(
"switch",
{
"switch": {
"platform": "template",
"switches": {
"my_switch": {
"friendly_name": "Switch Template",
"turn_on": [],
"turn_off": [],
}
},
},
},
[
"turn_on: []",
"turn_off: []",
],
),
(
"light",
{
"light": [
{
"platform": "template",
"lights": {
"atrium_lichterkette": {
"unique_id": "atrium_lichterkette",
"friendly_name": "Atrium Lichterkette",
"value_template": "{{ states('input_boolean.atrium_lichterkette_power') }}",
"level_template": "{% if is_state('input_boolean.atrium_lichterkette_power', 'off') %}\n 0\n{% else %}\n {{ states('input_number.atrium_lichterkette_brightness') | int * (255 / state_attr('input_number.atrium_lichterkette_brightness', 'max') | int) }}\n{% endif %}",
"effect_list_template": "{{ state_attr('input_select.atrium_lichterkette_mode', 'options') }}",
"effect_template": "'{{ states('input_select.atrium_lichterkette_mode')}}'",
"turn_on": [
{
"service": "button.press",
"target": {
"entity_id": "button.esphome_web_28a814_lichterkette_on"
},
},
{
"service": "input_boolean.turn_on",
"target": {
"entity_id": "input_boolean.atrium_lichterkette_power"
},
},
],
"turn_off": [
{
"service": "button.press",
"target": {
"entity_id": "button.esphome_web_28a814_lichterkette_off"
},
},
{
"service": "input_boolean.turn_off",
"target": {
"entity_id": "input_boolean.atrium_lichterkette_power"
},
},
],
"set_level": [
{
"variables": {
"scaled": "{{ (brightness / (255 / state_attr('input_number.atrium_lichterkette_brightness', 'max'))) | round | int }}",
"diff": "{{ scaled | int - states('input_number.atrium_lichterkette_brightness') | int }}",
"direction": "{{ 'dim' if diff | int < 0 else 'bright' }}",
}
},
{
"repeat": {
"count": "{{ diff | int | abs }}",
"sequence": [
{
"service": "button.press",
"target": {
"entity_id": "button.esphome_web_28a814_lichterkette_{{ direction }}"
},
},
{"delay": {"milliseconds": 500}},
],
}
},
{
"service": "input_number.set_value",
"data": {
"value": "{{ scaled }}",
"entity_id": "input_number.atrium_lichterkette_brightness",
},
},
],
"set_effect": [
{
"service": "button.press",
"target": {
"entity_id": "button.esphome_web_28a814_lichterkette_{{ effect }}"
},
}
],
}
},
}
]
},
[
"scaled: ",
"diff: ",
"direction: ",
],
),
(
"cover",
{
"cover": [
{
"platform": "template",
"covers": {
"large_garage_door": {
"device_class": "garage",
"friendly_name": "Large Garage Door",
"value_template": "{% if is_state('binary_sensor.large_garage_door', 'off') %}\n closed\n{% elif is_state('timer.large_garage_opening_timer', 'active') %}\n opening\n{% elif is_state('timer.large_garage_closing_timer', 'active') %} \n closing\n{% elif is_state('binary_sensor.large_garage_door', 'on') %}\n open\n{% endif %}\n",
"open_cover": [
{
"condition": "state",
"entity_id": "binary_sensor.large_garage_door",
"state": "off",
},
{
"action": "switch.turn_on",
"target": {
"entity_id": "switch.garage_door_relay_1"
},
},
{
"action": "timer.start",
"entity_id": "timer.large_garage_opening_timer",
},
],
"close_cover": [
{
"condition": "state",
"entity_id": "binary_sensor.large_garage_door",
"state": "on",
},
{
"action": "switch.turn_on",
"target": {
"entity_id": "switch.garage_door_relay_1"
},
},
{
"action": "timer.start",
"entity_id": "timer.large_garage_closing_timer",
},
],
"stop_cover": [
{
"action": "switch.turn_on",
"target": {
"entity_id": "switch.garage_door_relay_1"
},
},
{
"action": "timer.cancel",
"entity_id": "timer.large_garage_opening_timer",
},
{
"action": "timer.cancel",
"entity_id": "timer.large_garage_closing_timer",
},
],
}
},
}
]
},
["device_class: garage"],
),
(
"binary_sensor",
{
"binary_sensor": {
"platform": "template",
"sensors": {
"motion_sensor": {
"friendly_name": "Motion Sensor",
"device_class": "motion",
"value_template": "{{ is_state('sensor.motion_detector', 'on') }}",
}
},
},
},
["device_class: motion"],
),
(
"sensor",
{
"sensor": {
"platform": "template",
"sensors": {
"some_sensor": {
"friendly_name": "Sensor",
"entity_id": "sensor.some_sensor",
"device_class": "timestamp",
"value_template": "{{ now().isoformat() }}",
}
},
},
},
["device_class: timestamp", "entity_id: sensor.some_sensor"],
),
],
)
async def test_legacy_deprecation_with_unique_objects(
hass: HomeAssistant,
domain: str,
config: dict,
strings_to_check: list[str],
issue_registry: ir.IssueRegistry,
) -> None:
"""Test legacy configuration raises issue and unique objects are properly converted to valid configurations."""
await async_setup_component(hass, domain, config)
await hass.async_block_till_done()
assert len(issue_registry.issues) == 1
issue = next(iter(issue_registry.issues.values()))
assert issue.domain == "template"
assert issue.severity == ir.IssueSeverity.WARNING
assert issue.translation_placeholders is not None
for string in strings_to_check:
assert string in issue.translation_placeholders["config"]
@pytest.mark.parametrize(
("domain", "config"),
[
(
"template",
{"template": [{"sensor": {"name": "test_template_sensor", "state": "OK"}}]},
),
(
"template",
{
"template": [
{
"triggers": {"trigger": "event", "event_type": "test"},
"sensor": {"name": "test_template_sensor", "state": "OK"},
}
]
},
),
],
)
async def test_modern_configuration_does_not_raise_issue(
hass: HomeAssistant,
domain: str,
config: dict,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test modern configuration does not raise issue."""
await async_setup_component(hass, domain, config)
await hass.async_block_till_done()
assert len(issue_registry.issues) == 0
async def test_yaml_config_recursion_depth(hass: HomeAssistant) -> None:
"""Test recursion depth when formatting ConfigType."""
with pytest.raises(RecursionError):
format_migration_config({1: {2: {3: {4: {5: {6: [{7: {8: {9: {10: {}}}}}]}}}}}})
@pytest.mark.parametrize(
("domain", "config"),
[
(
"media_player",
{
"media_player": {
"platform": "template",
"name": "My Media Player",
"unique_id": "Foobar",
},
},
),
(
"climate",
{
"climate": {
"platform": "template",
"name": "My Climate",
"unique_id": "Foobar",
},
},
),
],
)
async def test_custom_integration_deprecation(
hass: HomeAssistant,
domain: str,
config: dict,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test that custom integrations do not create deprecations."""
create_legacy_template_issue(hass, config, domain)
assert len(issue_registry.issues) == 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/template/test_helpers.py",
"license": "Apache License 2.0",
"lines": 908,
"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.