sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
home-assistant/core:homeassistant/components/tilt_pi/entity.py | """Base entity for Tilt Pi integration."""
from tiltpi import TiltHydrometerData
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .coordinator import TiltPiDataUpdateCoordinator
class TiltEntity(CoordinatorEntity[TiltPiDataUpdateCoordinator]):
"""Base class for Tilt entities."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: TiltPiDataUpdateCoordinator,
hydrometer: TiltHydrometerData,
) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
self._mac_id = hydrometer.mac_id
self._attr_device_info = DeviceInfo(
connections={(CONNECTION_NETWORK_MAC, hydrometer.mac_id)},
name=f"Tilt {hydrometer.color}",
manufacturer="Tilt Hydrometer",
model=f"{hydrometer.color} Tilt Hydrometer",
)
@property
def current_hydrometer(self) -> TiltHydrometerData:
"""Return the current hydrometer data for this entity."""
return self.coordinator.data[self._mac_id]
@property
def available(self) -> bool:
"""Return True if the hydrometer is available (present in coordinator data)."""
return super().available and self._mac_id in self.coordinator.data
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/tilt_pi/entity.py",
"license": "Apache License 2.0",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/tilt_pi/sensor.py | """Support for Tilt Hydrometer sensors."""
from collections.abc import Callable
from dataclasses import dataclass
from typing import Final
from tiltpi import TiltHydrometerData
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .coordinator import TiltPiConfigEntry, TiltPiDataUpdateCoordinator
from .entity import TiltEntity
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
ATTR_TEMPERATURE = "temperature"
ATTR_GRAVITY = "gravity"
@dataclass(frozen=True, kw_only=True)
class TiltEntityDescription(SensorEntityDescription):
"""Describes TiltHydrometerData sensor entity."""
value_fn: Callable[[TiltHydrometerData], StateType]
SENSOR_TYPES: Final[list[TiltEntityDescription]] = [
TiltEntityDescription(
key=ATTR_TEMPERATURE,
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.FAHRENHEIT,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.temperature,
),
TiltEntityDescription(
key=ATTR_GRAVITY,
translation_key="gravity",
native_unit_of_measurement="SG",
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.gravity,
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: TiltPiConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Tilt Hydrometer sensors."""
coordinator = config_entry.runtime_data
async_add_entities(
TiltSensor(
coordinator,
description,
hydrometer,
)
for description in SENSOR_TYPES
for hydrometer in coordinator.data.values()
)
class TiltSensor(TiltEntity, SensorEntity):
"""Defines a Tilt sensor."""
entity_description: TiltEntityDescription
def __init__(
self,
coordinator: TiltPiDataUpdateCoordinator,
description: TiltEntityDescription,
hydrometer: TiltHydrometerData,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator, hydrometer)
self.entity_description = description
self._attr_unique_id = f"{hydrometer.mac_id}_{description.key}"
@property
def native_value(self) -> StateType:
"""Return the sensor value."""
return self.entity_description.value_fn(self.current_hydrometer)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/tilt_pi/sensor.py",
"license": "Apache License 2.0",
"lines": 74,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/vegehub/config_flow.py | """Config flow for the VegeHub integration."""
import logging
from typing import Any
from vegehub import VegeHub
import voluptuous as vol
from homeassistant.components.webhook import (
async_generate_id as webhook_generate_id,
async_generate_url as webhook_generate_url,
)
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import (
CONF_DEVICE,
CONF_HOST,
CONF_IP_ADDRESS,
CONF_MAC,
CONF_WEBHOOK_ID,
)
from homeassistant.helpers.service_info import zeroconf
from homeassistant.util.network import is_ip_address
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
class VegeHubConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for VegeHub integration."""
_hub: VegeHub
_hostname: str
webhook_id: str
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a flow initiated by the user."""
errors: dict[str, str] = {}
if user_input is not None:
if not is_ip_address(user_input[CONF_IP_ADDRESS]):
# User-supplied IP address is invalid.
errors["base"] = "invalid_ip"
if not errors:
self._hub = VegeHub(user_input[CONF_IP_ADDRESS])
self._hostname = self._hub.ip_address
errors = await self._setup_device()
if not errors:
# Proceed to create the config entry
return await self._create_entry()
# Show the form to allow the user to manually enter the IP address
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_IP_ADDRESS): str,
}
),
errors=errors,
)
async def async_step_zeroconf(
self, discovery_info: zeroconf.ZeroconfServiceInfo
) -> ConfigFlowResult:
"""Handle zeroconf discovery."""
# Extract the IP address from the zeroconf discovery info
device_ip = discovery_info.host
self._async_abort_entries_match({CONF_IP_ADDRESS: device_ip})
self._hostname = discovery_info.hostname.removesuffix(".local.")
config_url = f"http://{discovery_info.hostname[:-1]}:{discovery_info.port}"
# Create a VegeHub object to interact with the device
self._hub = VegeHub(device_ip)
try:
await self._hub.retrieve_mac_address(retries=2)
except ConnectionError:
return self.async_abort(reason="cannot_connect")
except TimeoutError:
return self.async_abort(reason="timeout_connect")
if not self._hub.mac_address:
return self.async_abort(reason="cannot_connect")
# Check if this device already exists
await self.async_set_unique_id(self._hub.mac_address)
self._abort_if_unique_id_configured(
updates={CONF_IP_ADDRESS: device_ip, CONF_HOST: self._hostname}
)
# Add title and configuration URL to the context so that the device discovery
# tile has the correct title, and a "Visit Device" link available.
self.context.update(
{
"title_placeholders": {"host": self._hostname + " (" + device_ip + ")"},
"configuration_url": (config_url),
}
)
# If the device is new, allow the user to continue setup
return await self.async_step_zeroconf_confirm()
async def async_step_zeroconf_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle user confirmation for a discovered device."""
errors: dict[str, str] = {}
if user_input is not None:
errors = await self._setup_device()
if not errors:
return await self._create_entry()
# Show the confirmation form
self._set_confirm_only()
return self.async_show_form(step_id="zeroconf_confirm", errors=errors)
async def _setup_device(self) -> dict[str, str]:
"""Set up the VegeHub device."""
errors: dict[str, str] = {}
self.webhook_id = webhook_generate_id()
webhook_url = webhook_generate_url(
self.hass,
self.webhook_id,
allow_external=False,
allow_ip=True,
)
# Send the webhook address to the hub as its server target.
# This step can happen in the init, because that gets executed
# every time Home Assistant starts up, and this step should
# only happen in the initial setup of the VegeHub.
try:
await self._hub.setup("", webhook_url, retries=1)
except ConnectionError:
errors["base"] = "cannot_connect"
except TimeoutError:
errors["base"] = "timeout_connect"
if not self._hub.mac_address:
errors["base"] = "cannot_connect"
return errors
async def _create_entry(self) -> ConfigFlowResult:
"""Create a config entry for the device."""
# Check if this device already exists
await self.async_set_unique_id(self._hub.mac_address)
self._abort_if_unique_id_configured()
# Save Hub info to be used later when defining the VegeHub object
info_data = {
CONF_IP_ADDRESS: self._hub.ip_address,
CONF_HOST: self._hostname,
CONF_MAC: self._hub.mac_address,
CONF_DEVICE: self._hub.info,
CONF_WEBHOOK_ID: self.webhook_id,
}
# Create the config entry for the new device
return self.async_create_entry(title=self._hostname, data=info_data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vegehub/config_flow.py",
"license": "Apache License 2.0",
"lines": 136,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/vegehub/const.py | """Constants for the Vegetronix VegeHub integration."""
from homeassistant.const import Platform
DOMAIN = "vegehub"
NAME = "VegeHub"
PLATFORMS = [Platform.SENSOR, Platform.SWITCH]
MANUFACTURER = "vegetronix"
MODEL = "VegeHub"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vegehub/const.py",
"license": "Apache License 2.0",
"lines": 7,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/vegehub/coordinator.py | """Coordinator for the Vegetronix VegeHub."""
from __future__ import annotations
import logging
from typing import Any
from vegehub import VegeHub, update_data_to_ha_dict
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
_LOGGER = logging.getLogger(__name__)
type VegeHubConfigEntry = ConfigEntry[VegeHub]
class VegeHubCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""The DataUpdateCoordinator for VegeHub."""
config_entry: VegeHubConfigEntry
def __init__(
self, hass: HomeAssistant, config_entry: VegeHubConfigEntry, vegehub: VegeHub
) -> None:
"""Initialize VegeHub data coordinator."""
super().__init__(
hass,
_LOGGER,
name=f"{config_entry.unique_id} DataUpdateCoordinator",
config_entry=config_entry,
)
self.vegehub = vegehub
self.device_id = config_entry.unique_id
assert self.device_id is not None, "Config entry is missing unique_id"
async def update_from_webhook(self, data: dict) -> None:
"""Process and update data from webhook."""
sensor_data = update_data_to_ha_dict(
data,
self.vegehub.num_sensors or 0,
self.vegehub.num_actuators or 0,
self.vegehub.is_ac or False,
)
if self.data:
existing_data: dict = self.data
existing_data.update(sensor_data)
if sensor_data:
self.async_set_updated_data(existing_data)
else:
self.async_set_updated_data(sensor_data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vegehub/coordinator.py",
"license": "Apache License 2.0",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/vegehub/entity.py | """Base entity for VegeHub."""
from homeassistant.const import CONF_HOST, CONF_MAC
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import MANUFACTURER, MODEL
from .coordinator import VegeHubCoordinator
class VegeHubEntity(CoordinatorEntity[VegeHubCoordinator]):
"""Defines a base VegeHub entity."""
_attr_has_entity_name = True
def __init__(self, coordinator: VegeHubCoordinator) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
config_entry = coordinator.config_entry
self._mac_address = config_entry.data[CONF_MAC]
self._attr_device_info = DeviceInfo(
connections={(CONNECTION_NETWORK_MAC, self._mac_address)},
name=config_entry.data[CONF_HOST],
manufacturer=MANUFACTURER,
model=MODEL,
sw_version=coordinator.vegehub.sw_version,
configuration_url=coordinator.vegehub.url,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vegehub/entity.py",
"license": "Apache License 2.0",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/vegehub/sensor.py | """Sensor configuration for VegeHub integration."""
from itertools import count
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import UnitOfElectricPotential
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import VegeHubConfigEntry, VegeHubCoordinator
from .entity import VegeHubEntity
SENSOR_TYPES: dict[str, SensorEntityDescription] = {
"analog_sensor": SensorEntityDescription(
key="analog_sensor",
translation_key="analog_sensor",
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
suggested_display_precision=2,
),
"battery_volts": SensorEntityDescription(
key="battery_volts",
translation_key="battery_volts",
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
suggested_display_precision=1,
),
}
async def async_setup_entry(
hass: HomeAssistant,
config_entry: VegeHubConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Vegetronix sensors from a config entry."""
sensors: list[VegeHubSensor] = []
coordinator = config_entry.runtime_data
sensor_index = count(0)
# Add each analog sensor input
for _i in range(coordinator.vegehub.num_sensors):
sensor = VegeHubSensor(
index=next(sensor_index),
coordinator=coordinator,
description=SENSOR_TYPES["analog_sensor"],
)
sensors.append(sensor)
# Add the battery sensor
if not coordinator.vegehub.is_ac:
sensors.append(
VegeHubSensor(
index=next(sensor_index),
coordinator=coordinator,
description=SENSOR_TYPES["battery_volts"],
)
)
async_add_entities(sensors)
class VegeHubSensor(VegeHubEntity, SensorEntity):
"""Class for VegeHub Analog Sensors."""
def __init__(
self,
index: int,
coordinator: VegeHubCoordinator,
description: SensorEntityDescription,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self.entity_description = description
# Set data key for pulling data from the coordinator
if description.key == "battery_volts":
self.data_key = "battery"
else:
self.data_key = f"analog_{index}"
self._attr_translation_placeholders = {"index": str(index + 1)}
self._attr_unique_id = f"{self._mac_address}_{self.data_key}"
self._attr_available = False
@property
def native_value(self) -> float | None:
"""Return the sensor's current value."""
if self.coordinator.data is None:
return None
return self.coordinator.data.get(self.data_key)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vegehub/sensor.py",
"license": "Apache License 2.0",
"lines": 80,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/zoneminder/services.py | """Support for ZoneMinder."""
import logging
import voluptuous as vol
from homeassistant.const import ATTR_ID, ATTR_NAME
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers import config_validation as cv
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
SERVICE_SET_RUN_STATE = "set_run_state"
SET_RUN_STATE_SCHEMA = vol.Schema(
{vol.Required(ATTR_ID): cv.string, vol.Required(ATTR_NAME): cv.string}
)
def _set_active_state(call: ServiceCall) -> None:
"""Set the ZoneMinder run state to the given state name."""
zm_id = call.data[ATTR_ID]
state_name = call.data[ATTR_NAME]
if zm_id not in call.hass.data[DOMAIN]:
_LOGGER.error("Invalid ZoneMinder host provided: %s", zm_id)
if not call.hass.data[DOMAIN][zm_id].set_active_state(state_name):
_LOGGER.error(
"Unable to change ZoneMinder state. Host: %s, state: %s",
zm_id,
state_name,
)
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Register ZoneMinder services."""
hass.services.async_register(
DOMAIN, SERVICE_SET_RUN_STATE, _set_active_state, schema=SET_RUN_STATE_SCHEMA
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zoneminder/services.py",
"license": "Apache License 2.0",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:script/hassfest/triggers.py | """Validate triggers."""
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 config_validation as cv, selector, trigger
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
def validate_field_schema(trigger_schema: dict[str, Any]) -> dict[str, Any]:
"""Validate a field schema including context references."""
for field_name, field_schema in trigger_schema.get("fields", {}).items():
# Validate context if present
if "context" in field_schema:
if CONF_SELECTOR not in field_schema:
raise vol.Invalid(
f"Context defined without a selector in '{field_name}'"
)
context = field_schema["context"]
if not isinstance(context, dict):
raise vol.Invalid(f"Context must be a dictionary in '{field_name}'")
# Determine which selector type is being used
selector_config = field_schema[CONF_SELECTOR]
selector_class = selector.selector(selector_config)
for context_key, field_ref in context.items():
# Check if context key is allowed for this selector type
allowed_keys = selector_class.allowed_context_keys
if context_key not in allowed_keys:
raise vol.Invalid(
f"Invalid context key '{context_key}' for selector type '{selector_class.selector_type}'. "
f"Allowed keys: {', '.join(sorted(allowed_keys)) if allowed_keys else 'none'}"
)
# Check if the referenced field exists in trigger schema or target
if not isinstance(field_ref, str):
raise vol.Invalid(
f"Context value for '{context_key}' must be a string field reference"
)
# Check if field exists in trigger schema fields or target
trigger_fields = trigger_schema["fields"]
field_exists = field_ref in trigger_fields
if field_exists and "selector" in trigger_fields[field_ref]:
# Check if the selector type is allowed for this context key
field_selector_config = trigger_fields[field_ref][CONF_SELECTOR]
field_selector_class = selector.selector(field_selector_config)
if field_selector_class.selector_type not in allowed_keys.get(
context_key, set()
):
raise vol.Invalid(
f"The context '{context_key}' for '{field_name}' references '{field_ref}', but '{context_key}' "
f"does not allow selectors of type '{field_selector_class.selector_type}'. Allowed selector types: {', '.join(allowed_keys.get(context_key, set()))}"
)
if not field_exists and "target" in trigger_schema:
# Target is a special field that always exists when defined
field_exists = field_ref == "target"
if field_exists and "target" not in allowed_keys.get(
context_key, set()
):
raise vol.Invalid(
f"The context '{context_key}' for '{field_name}' references 'target', but '{context_key}' "
f"does not allow 'target'. Allowed selector types: {', '.join(allowed_keys.get(context_key, set()))}"
)
if not field_exists:
raise vol.Invalid(
f"Context reference '{field_ref}' for key '{context_key}' does not exist "
f"in trigger schema fields or target"
)
return trigger_schema
FIELD_SCHEMA = vol.Schema(
{
vol.Optional("example"): exists,
vol.Optional("default"): exists,
vol.Optional("required"): bool,
vol.Optional(CONF_SELECTOR): selector.validate_selector,
vol.Optional("context"): {
str: str # key is context key, value is field name in the schema which value should be used
}, # Will be validated in validate_field_schema
}
)
TRIGGER_SCHEMA = vol.Any(
vol.All(
vol.Schema(
{
vol.Optional("target"): selector.TargetSelector.CONFIG_SCHEMA,
vol.Optional("fields"): vol.Schema({str: FIELD_SCHEMA}),
}
),
validate_field_schema,
),
None,
)
TRIGGERS_SCHEMA = vol.Schema(
{
vol.Remove(vol.All(str, trigger.starts_with_dot)): object,
cv.underscore_slug: TRIGGER_SCHEMA,
}
)
NON_MIGRATED_INTEGRATIONS = {
"calendar",
"conversation",
"device_automation",
"geo_location",
"homeassistant",
"knx",
"lg_netcast",
"litejet",
"persistent_notification",
"samsungtv",
"sun",
"tag",
"template",
"webhook",
"webostv",
"zone",
"zwave_js",
}
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_triggers(config: Config, integration: Integration) -> None: # noqa: C901
"""Validate triggers."""
try:
data = load_yaml_dict(str(integration.path / "triggers.yaml"))
except FileNotFoundError:
# Find if integration uses triggers
has_triggers = grep_dir(
integration.path,
"**/trigger.py",
r"async_attach_trigger|async_get_triggers",
)
if has_triggers and integration.domain not in NON_MIGRATED_INTEGRATIONS:
integration.add_error(
"triggers", "Registers triggers but has no triggers.yaml"
)
return
except HomeAssistantError:
integration.add_error("triggers", "Invalid triggers.yaml")
return
try:
triggers = TRIGGERS_SCHEMA(data)
except vol.Invalid as err:
integration.add_error(
"triggers", f"Invalid triggers.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())
trigger_icons = icons.get("triggers", {})
# 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 trigger in the integration:
# 1. Check if the trigger description is set, if not,
# check if it's in the strings file else add an error.
# 2. Check if the trigger has an icon set in icons.json.
# raise an error if not.,
for trigger_name, trigger_schema in triggers.items():
if integration.core and trigger_name not in trigger_icons:
# This is enforced for Core integrations only
integration.add_error(
"triggers",
f"Trigger {trigger_name} has no icon in icons.json.",
)
if trigger_schema is None:
continue
if "name" not in trigger_schema and integration.core:
try:
strings["triggers"][trigger_name]["name"]
except KeyError:
integration.add_error(
"triggers",
f"Trigger {trigger_name} has no name {error_msg_suffix}",
)
if "description" not in trigger_schema and integration.core:
try:
strings["triggers"][trigger_name]["description"]
except KeyError:
integration.add_error(
"triggers",
f"Trigger {trigger_name} has no description {error_msg_suffix}",
)
# The same check is done for the description in each of the fields of the
# trigger schema.
for field_name, field_schema in trigger_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["triggers"][trigger_name]["fields"][field_name]["name"]
except KeyError:
integration.add_error(
"triggers",
(
f"Trigger {trigger_name} has a field {field_name} with no "
f"name {error_msg_suffix}"
),
)
if "description" not in field_schema and integration.core:
try:
strings["triggers"][trigger_name]["fields"][field_name][
"description"
]
except KeyError:
integration.add_error(
"triggers",
(
f"Trigger {trigger_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(
"triggers",
f"Trigger {trigger_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
# trigger schema.
for section_name, section_schema in trigger_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["triggers"][trigger_name]["sections"][section_name]["name"]
except KeyError:
integration.add_error(
"triggers",
f"Trigger {trigger_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 triggers.yaml is valid
for integration in integrations.values():
validate_triggers(config, integration)
| {
"repo_id": "home-assistant/core",
"file_path": "script/hassfest/triggers.py",
"license": "Apache License 2.0",
"lines": 270,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/adax/test_sensor.py | """Test Adax sensor entity."""
from unittest.mock import AsyncMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_sensor_cloud(
hass: HomeAssistant,
mock_adax_cloud: AsyncMock,
mock_cloud_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test sensor setup for cloud connection."""
with patch("homeassistant.components.adax.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_cloud_config_entry)
# Now we use fetch_rooms_info as primary method
mock_adax_cloud.fetch_rooms_info.assert_called_once()
await snapshot_platform(
hass, entity_registry, snapshot, mock_cloud_config_entry.entry_id
)
async def test_sensor_local_not_created(
hass: HomeAssistant,
mock_adax_local: AsyncMock,
mock_local_config_entry: MockConfigEntry,
) -> None:
"""Test that sensors are not created for local connection."""
with patch("homeassistant.components.adax.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_local_config_entry)
# No sensor entities should be created for local connection
sensor_entities = hass.states.async_entity_ids("sensor")
adax_sensors = [e for e in sensor_entities if "adax" in e or "room" in e]
assert len(adax_sensors) == 0
async def test_multiple_devices_create_individual_sensors(
hass: HomeAssistant,
mock_adax_cloud: AsyncMock,
mock_cloud_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that multiple devices create individual sensors."""
# Mock multiple devices for both fetch_rooms_info and get_rooms (fallback)
multiple_devices_data = [
{
"id": "1",
"homeId": "1",
"name": "Room 1",
"temperature": 15.0,
"targetTemperature": 20,
"heatingEnabled": True,
"energyWh": 1500,
},
{
"id": "2",
"homeId": "1",
"name": "Room 2",
"temperature": 18.0,
"targetTemperature": 22,
"heatingEnabled": True,
"energyWh": 2500,
},
]
mock_adax_cloud.fetch_rooms_info.return_value = multiple_devices_data
mock_adax_cloud.get_rooms.return_value = multiple_devices_data
with patch("homeassistant.components.adax.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_cloud_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_cloud_config_entry.entry_id
)
async def test_fallback_to_get_rooms(
hass: HomeAssistant,
mock_adax_cloud: AsyncMock,
mock_cloud_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test fallback to get_rooms when fetch_rooms_info returns empty list."""
# Mock fetch_rooms_info to return empty list, get_rooms to return data
mock_adax_cloud.fetch_rooms_info.return_value = []
mock_adax_cloud.get_rooms.return_value = [
{
"id": "1",
"homeId": "1",
"name": "Room 1",
"temperature": 15.0,
"targetTemperature": 20,
"heatingEnabled": True,
"energyWh": 0, # No energy data from get_rooms
}
]
with patch("homeassistant.components.adax.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_cloud_config_entry)
# Should call both methods
mock_adax_cloud.fetch_rooms_info.assert_called_once()
mock_adax_cloud.get_rooms.assert_called_once()
await snapshot_platform(
hass, entity_registry, snapshot, mock_cloud_config_entry.entry_id
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/adax/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/ai_task/test_entity.py | """Tests for the AI Task entity model."""
import pytest
import voluptuous as vol
from homeassistant.components.ai_task import async_generate_data
from homeassistant.const import STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import selector
from .conftest import TEST_ENTITY_ID, MockAITaskEntity
from tests.common import MockConfigEntry
@pytest.mark.freeze_time("2025-06-08 16:28:13")
async def test_state_generate_data(
hass: HomeAssistant,
init_components: None,
mock_config_entry: MockConfigEntry,
mock_ai_task_entity: MockAITaskEntity,
) -> None:
"""Test the state of the AI Task entity is updated when generating data."""
entity = hass.states.get(TEST_ENTITY_ID)
assert entity is not None
assert entity.state == STATE_UNKNOWN
result = await async_generate_data(
hass,
task_name="Test task",
entity_id=TEST_ENTITY_ID,
instructions="Test prompt",
)
assert result.data == "Mock result"
entity = hass.states.get(TEST_ENTITY_ID)
assert entity.state == "2025-06-08T16:28:13+00:00"
assert mock_ai_task_entity.mock_generate_data_tasks
task = mock_ai_task_entity.mock_generate_data_tasks[0]
assert task.instructions == "Test prompt"
async def test_generate_structured_data(
hass: HomeAssistant,
init_components: None,
mock_config_entry: MockConfigEntry,
mock_ai_task_entity: MockAITaskEntity,
) -> None:
"""Test the entity can generate structured data."""
result = await async_generate_data(
hass,
task_name="Test task",
entity_id=TEST_ENTITY_ID,
instructions="Please generate a profile for a new user",
structure=vol.Schema(
{
vol.Required("name"): selector.TextSelector(),
vol.Optional("age"): selector.NumberSelector(
config=selector.NumberSelectorConfig(
min=0,
max=120,
)
),
}
),
)
# Arbitrary data returned by the mock entity (not determined by above schema in test)
assert result.data == {
"name": "Tracy Chen",
"age": 30,
}
assert mock_ai_task_entity.mock_generate_data_tasks
task = mock_ai_task_entity.mock_generate_data_tasks[0]
assert task.instructions == "Please generate a profile for a new user"
assert task.structure
assert isinstance(task.structure, vol.Schema)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ai_task/test_entity.py",
"license": "Apache License 2.0",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/ai_task/test_http.py | """Test the HTTP API for AI Task integration."""
from homeassistant.core import HomeAssistant
from tests.typing import WebSocketGenerator
async def test_ws_preferences(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
init_components: None,
) -> None:
"""Test preferences via the WebSocket API."""
client = await hass_ws_client(hass)
# Get initial preferences
await client.send_json_auto_id({"type": "ai_task/preferences/get"})
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": None,
"gen_image_entity_id": None,
}
# Set preferences
await client.send_json_auto_id(
{
"type": "ai_task/preferences/set",
"gen_data_entity_id": "ai_task.summary_1",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": "ai_task.summary_1",
"gen_image_entity_id": None,
}
# Get updated preferences
await client.send_json_auto_id({"type": "ai_task/preferences/get"})
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": "ai_task.summary_1",
"gen_image_entity_id": None,
}
# Update an existing preference
await client.send_json_auto_id(
{
"type": "ai_task/preferences/set",
"gen_data_entity_id": "ai_task.summary_2",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": "ai_task.summary_2",
"gen_image_entity_id": None,
}
# Get updated preferences
await client.send_json_auto_id({"type": "ai_task/preferences/get"})
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": "ai_task.summary_2",
"gen_image_entity_id": None,
}
# No preferences set will preserve existing preferences
await client.send_json_auto_id(
{
"type": "ai_task/preferences/set",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": "ai_task.summary_2",
"gen_image_entity_id": None,
}
# Get updated preferences
await client.send_json_auto_id({"type": "ai_task/preferences/get"})
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": "ai_task.summary_2",
"gen_image_entity_id": None,
}
# Set gen_image_entity_id preference
await client.send_json_auto_id(
{
"type": "ai_task/preferences/set",
"gen_image_entity_id": "ai_task.image_gen_1",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": "ai_task.summary_2",
"gen_image_entity_id": "ai_task.image_gen_1",
}
# Update both preferences
await client.send_json_auto_id(
{
"type": "ai_task/preferences/set",
"gen_data_entity_id": "ai_task.summary_3",
"gen_image_entity_id": "ai_task.image_gen_2",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": "ai_task.summary_3",
"gen_image_entity_id": "ai_task.image_gen_2",
}
# Get final preferences
await client.send_json_auto_id({"type": "ai_task/preferences/get"})
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {
"gen_data_entity_id": "ai_task.summary_3",
"gen_image_entity_id": "ai_task.image_gen_2",
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ai_task/test_http.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/ai_task/test_init.py | """Test initialization of the AI Task component."""
from pathlib import Path
from typing import Any
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
import voluptuous as vol
from homeassistant.components import media_source
from homeassistant.components.ai_task import AITaskPreferences
from homeassistant.components.ai_task.const import DATA_MEDIA_SOURCE, DATA_PREFERENCES
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import selector
from .conftest import TEST_ENTITY_ID, MockAITaskEntity
from tests.common import flush_store
async def test_preferences_storage_load(
hass: HomeAssistant,
) -> None:
"""Test that AITaskPreferences are stored and loaded correctly."""
preferences = AITaskPreferences(hass)
await preferences.async_load()
# Initial state should be None for entity IDs
for key in AITaskPreferences.KEYS:
assert getattr(preferences, key) is None, f"Initial {key} should be None"
new_values = {key: f"ai_task.test_{key}" for key in AITaskPreferences.KEYS}
preferences.async_set_preferences(**new_values)
# Verify that current preferences object is updated
for key, value in new_values.items():
assert getattr(preferences, key) == value, (
f"Current {key} should match set value"
)
await flush_store(preferences._store)
# Create a new preferences instance to test loading from store
new_preferences_instance = AITaskPreferences(hass)
await new_preferences_instance.async_load()
for key in AITaskPreferences.KEYS:
assert getattr(preferences, key) == getattr(new_preferences_instance, key), (
f"Loaded {key} should match saved value"
)
@pytest.mark.parametrize(
("set_preferences", "msg_extra"),
[
(
{"gen_data_entity_id": TEST_ENTITY_ID},
{},
),
(
{},
{
"entity_id": TEST_ENTITY_ID,
"attachments": [
{
"media_content_id": "media-source://mock/blah_blah_blah.mp4",
"media_content_type": "video/mp4",
}
],
},
),
],
)
async def test_generate_data_service(
hass: HomeAssistant,
init_components: None,
freezer: FrozenDateTimeFactory,
set_preferences: dict[str, str | None],
msg_extra: dict[str, str],
mock_ai_task_entity: MockAITaskEntity,
) -> None:
"""Test the generate data service."""
preferences = hass.data[DATA_PREFERENCES]
preferences.async_set_preferences(**set_preferences)
with patch(
"homeassistant.components.media_source.async_resolve_media",
return_value=media_source.PlayMedia(
url="http://example.com/media.mp4",
mime_type="video/mp4",
path=Path("media.mp4"),
),
):
result = await hass.services.async_call(
"ai_task",
"generate_data",
{
"task_name": "Test Name",
"instructions": "Test prompt",
}
| msg_extra,
blocking=True,
return_response=True,
)
assert result["data"] == "Mock result"
assert len(mock_ai_task_entity.mock_generate_data_tasks) == 1
task = mock_ai_task_entity.mock_generate_data_tasks[0]
assert len(task.attachments or []) == len(
msg_attachments := msg_extra.get("attachments", [])
)
for msg_attachment, attachment in zip(
msg_attachments, task.attachments or [], strict=False
):
assert attachment.mime_type == "video/mp4"
assert attachment.media_content_id == msg_attachment["media_content_id"]
assert attachment.path == Path("media.mp4")
async def test_generate_data_service_structure_fields(
hass: HomeAssistant,
init_components: None,
mock_ai_task_entity: MockAITaskEntity,
) -> None:
"""Test the entity can generate structured data with a top level object schema."""
result = await hass.services.async_call(
"ai_task",
"generate_data",
{
"task_name": "Profile Generation",
"instructions": "Please generate a profile for a new user",
"entity_id": TEST_ENTITY_ID,
"structure": {
"name": {
"description": "First and last name of the user such as Alice Smith",
"required": True,
"selector": {"text": {}},
},
"age": {
"description": "Age of the user",
"selector": {
"number": {
"min": 0,
"max": 120,
}
},
},
},
},
blocking=True,
return_response=True,
)
# Arbitrary data returned by the mock entity (not determined by above schema in test)
assert result["data"] == {
"name": "Tracy Chen",
"age": 30,
}
assert mock_ai_task_entity.mock_generate_data_tasks
task = mock_ai_task_entity.mock_generate_data_tasks[0]
assert task.instructions == "Please generate a profile for a new user"
assert task.structure
assert isinstance(task.structure, vol.Schema)
schema = list(task.structure.schema.items())
assert len(schema) == 2
name_key, name_value = schema[0]
assert name_key == "name"
assert isinstance(name_key, vol.Required)
assert name_key.description == "First and last name of the user such as Alice Smith"
assert isinstance(name_value, selector.TextSelector)
age_key, age_value = schema[1]
assert age_key == "age"
assert isinstance(age_key, vol.Optional)
assert age_key.description == "Age of the user"
assert isinstance(age_value, selector.NumberSelector)
assert age_value.config["min"] == 0
assert age_value.config["max"] == 120
@pytest.mark.parametrize(
("structure", "expected_exception", "expected_error"),
[
(
{
"name": {
"description": "First and last name of the user such as Alice Smith",
"selector": {"invalid-selector": {}},
},
},
vol.Invalid,
r"Unknown selector type invalid-selector.*",
),
(
{
"name": {
"description": "First and last name of the user such as Alice Smith",
"selector": {
"text": {
"extra-config": False,
}
},
},
},
vol.Invalid,
r"extra keys not allowed.*",
),
(
{
"name": {
"description": "First and last name of the user such as Alice Smith",
},
},
vol.Invalid,
r"required key not provided.*selector.*",
),
(12345, vol.Invalid, r"xpected a dictionary.*"),
("name", vol.Invalid, r"xpected a dictionary.*"),
(["name"], vol.Invalid, r"xpected a dictionary.*"),
(
{
"name": {
"description": "First and last name of the user such as Alice Smith",
"selector": {"text": {}},
"extra-fields": "Some extra fields",
},
},
vol.Invalid,
r"extra keys not allowed .*",
),
(
{
"name": {
"description": "First and last name of the user such as Alice Smith",
"selector": "invalid-schema",
},
},
vol.Invalid,
r"xpected a dictionary for dictionary.",
),
],
ids=(
"invalid-selector",
"invalid-selector-config",
"missing-selector",
"structure-is-int-not-object",
"structure-is-str-not-object",
"structure-is-list-not-object",
"extra-fields",
"invalid-selector-schema",
),
)
async def test_generate_data_service_invalid_structure(
hass: HomeAssistant,
init_components: None,
structure: Any,
expected_exception: Exception,
expected_error: str,
) -> None:
"""Test the entity can generate structured data."""
with pytest.raises(expected_exception, match=expected_error):
await hass.services.async_call(
"ai_task",
"generate_data",
{
"task_name": "Profile Generation",
"instructions": "Please generate a profile for a new user",
"entity_id": TEST_ENTITY_ID,
"structure": structure,
},
blocking=True,
return_response=True,
)
@pytest.mark.parametrize(
("set_preferences", "msg_extra"),
[
({}, {"entity_id": TEST_ENTITY_ID}),
({"gen_image_entity_id": TEST_ENTITY_ID}, {}),
(
{"gen_image_entity_id": "ai_task.other_entity"},
{"entity_id": TEST_ENTITY_ID},
),
],
)
@pytest.mark.freeze_time("2025-06-14 22:59:00")
async def test_generate_image_service(
hass: HomeAssistant,
init_components: None,
set_preferences: dict[str, str | None],
msg_extra: dict[str, str],
mock_ai_task_entity: MockAITaskEntity,
) -> None:
"""Test the generate image service."""
preferences = hass.data[DATA_PREFERENCES]
preferences.async_set_preferences(**set_preferences)
with patch.object(
hass.data[DATA_MEDIA_SOURCE],
"async_upload_media",
return_value="media-source://ai_task/image/2025-06-14_225900_test_task.png",
) as mock_upload_media:
result = await hass.services.async_call(
"ai_task",
"generate_image",
{
"task_name": "Test Image",
"instructions": "Generate a test image",
}
| msg_extra,
blocking=True,
return_response=True,
)
mock_upload_media.assert_called_once()
assert "image_data" not in result
assert (
result["media_source_id"]
== "media-source://ai_task/image/2025-06-14_225900_test_task.png"
)
assert result["url"].startswith(
"/ai_task/image/2025-06-14_225900_test_task.png?authSig="
)
assert result["mime_type"] == "image/png"
assert result["model"] == "mock_model"
assert result["revised_prompt"] == "mock_revised_prompt"
assert len(mock_ai_task_entity.mock_generate_image_tasks) == 1
task = mock_ai_task_entity.mock_generate_image_tasks[0]
assert task.instructions == "Generate a test image"
async def test_generate_image_service_no_entity(
hass: HomeAssistant,
init_components: None,
) -> None:
"""Test the generate image service with no entity specified."""
with pytest.raises(
HomeAssistantError,
match="No entity_id provided and no preferred entity set",
):
await hass.services.async_call(
"ai_task",
"generate_image",
{
"task_name": "Test Image",
"instructions": "Generate a test image",
},
blocking=True,
return_response=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ai_task/test_init.py",
"license": "Apache License 2.0",
"lines": 324,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/ai_task/test_task.py | """Test tasks for the AI Task integration."""
from datetime import timedelta
from pathlib import Path
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components import media_source
from homeassistant.components.ai_task import (
AITaskEntityFeature,
async_generate_data,
async_generate_image,
)
from homeassistant.components.ai_task.const import DATA_MEDIA_SOURCE
from homeassistant.components.camera import Image
from homeassistant.components.conversation import async_get_chat_log
from homeassistant.const import STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import chat_session, llm
from homeassistant.util import dt as dt_util
from .conftest import TEST_ENTITY_ID, MockAITaskEntity
from tests.common import async_fire_time_changed
from tests.typing import WebSocketGenerator
async def test_generate_data_preferred_entity(
hass: HomeAssistant,
init_components: None,
mock_ai_task_entity: MockAITaskEntity,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test generating data with entity via preferences."""
client = await hass_ws_client(hass)
with pytest.raises(
HomeAssistantError, match="No entity_id provided and no preferred entity set"
):
await async_generate_data(
hass,
task_name="Test Task",
instructions="Test prompt",
)
await client.send_json_auto_id(
{
"type": "ai_task/preferences/set",
"gen_data_entity_id": "ai_task.unknown",
}
)
msg = await client.receive_json()
assert msg["success"]
with pytest.raises(
HomeAssistantError, match="AI Task entity ai_task.unknown not found"
):
await async_generate_data(
hass,
task_name="Test Task",
instructions="Test prompt",
)
await client.send_json_auto_id(
{
"type": "ai_task/preferences/set",
"gen_data_entity_id": TEST_ENTITY_ID,
}
)
msg = await client.receive_json()
assert msg["success"]
state = hass.states.get(TEST_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNKNOWN
llm_api = llm.AssistAPI(hass)
result = await async_generate_data(
hass,
task_name="Test Task",
instructions="Test prompt",
llm_api=llm_api,
)
assert result.data == "Mock result"
as_dict = result.as_dict()
assert as_dict["conversation_id"] == result.conversation_id
assert as_dict["data"] == "Mock result"
state = hass.states.get(TEST_ENTITY_ID)
assert state is not None
assert state.state != STATE_UNKNOWN
with (
chat_session.async_get_chat_session(hass, result.conversation_id) as session,
async_get_chat_log(hass, session) as chat_log,
):
assert chat_log.llm_api.api is llm_api
mock_ai_task_entity.supported_features = AITaskEntityFeature(0)
with pytest.raises(
HomeAssistantError,
match="AI Task entity ai_task.test_task_entity does not support generating data",
):
await async_generate_data(
hass,
task_name="Test Task",
instructions="Test prompt",
)
async def test_generate_data_unknown_entity(
hass: HomeAssistant,
init_components: None,
) -> None:
"""Test generating data with an unknown entity."""
with pytest.raises(
HomeAssistantError, match="AI Task entity ai_task.unknown_entity not found"
):
await async_generate_data(
hass,
task_name="Test Task",
entity_id="ai_task.unknown_entity",
instructions="Test prompt",
)
@pytest.mark.freeze_time("2025-06-14 22:59:00")
async def test_run_data_task_updates_chat_log(
hass: HomeAssistant,
init_components: None,
snapshot: SnapshotAssertion,
) -> None:
"""Test that generating data updates the chat log."""
result = await async_generate_data(
hass,
task_name="Test Task",
entity_id=TEST_ENTITY_ID,
instructions="Test prompt",
)
assert result.data == "Mock result"
with (
chat_session.async_get_chat_session(hass, result.conversation_id) as session,
async_get_chat_log(hass, session) as chat_log,
):
assert chat_log.content == snapshot
async def test_generate_data_attachments_not_supported(
hass: HomeAssistant,
init_components: None,
mock_ai_task_entity: MockAITaskEntity,
) -> None:
"""Test generating data with attachments when entity doesn't support them."""
# Remove attachment support from the entity
mock_ai_task_entity._attr_supported_features = AITaskEntityFeature.GENERATE_DATA
with pytest.raises(
HomeAssistantError,
match="AI Task entity ai_task.test_task_entity does not support attachments",
):
await async_generate_data(
hass,
task_name="Test Task",
entity_id=TEST_ENTITY_ID,
instructions="Test prompt",
attachments=[
{
"media_content_id": "media-source://mock/test.mp4",
"media_content_type": "video/mp4",
}
],
)
async def test_generate_data_mixed_attachments(
hass: HomeAssistant,
init_components: None,
mock_ai_task_entity: MockAITaskEntity,
) -> None:
"""Test generating data with both camera and regular media source attachments."""
with (
patch(
"homeassistant.components.camera.async_get_image",
return_value=Image(content_type="image/jpeg", content=b"fake_camera_jpeg"),
) as mock_get_camera_image,
patch(
"homeassistant.components.image.async_get_image",
return_value=Image(content_type="image/jpeg", content=b"fake_image_jpeg"),
) as mock_get_image_image,
patch(
"homeassistant.components.media_source.async_resolve_media",
return_value=media_source.PlayMedia(
url="http://example.com/test.mp4",
mime_type="video/mp4",
path=Path("/media/test.mp4"),
),
) as mock_resolve_media,
):
await async_generate_data(
hass,
task_name="Test Task",
entity_id=TEST_ENTITY_ID,
instructions="Analyze these files",
attachments=[
{
"media_content_id": "media-source://camera/camera.front_door",
"media_content_type": "image/jpeg",
},
{
"media_content_id": "media-source://image/image.floorplan",
"media_content_type": "image/jpeg",
},
{
"media_content_id": "media-source://media_player/video.mp4",
"media_content_type": "video/mp4",
},
],
)
# Verify both methods were called
mock_get_camera_image.assert_called_once_with(hass, "camera.front_door")
mock_get_image_image.assert_called_once_with(hass, "image.floorplan")
mock_resolve_media.assert_called_once_with(
hass, "media-source://media_player/video.mp4", None
)
# Check attachments
assert len(mock_ai_task_entity.mock_generate_data_tasks) == 1
task = mock_ai_task_entity.mock_generate_data_tasks[0]
assert task.attachments is not None
assert len(task.attachments) == 3
# Check camera attachment
camera_attachment = task.attachments[0]
assert (
camera_attachment.media_content_id == "media-source://camera/camera.front_door"
)
assert camera_attachment.mime_type == "image/jpeg"
assert isinstance(camera_attachment.path, Path)
assert camera_attachment.path.suffix == ".jpg"
# Verify camera snapshot content
assert camera_attachment.path.exists()
content = await hass.async_add_executor_job(camera_attachment.path.read_bytes)
assert content == b"fake_camera_jpeg"
# Check image attachment
image_attachment = task.attachments[1]
assert image_attachment.media_content_id == "media-source://image/image.floorplan"
assert image_attachment.mime_type == "image/jpeg"
assert isinstance(image_attachment.path, Path)
assert image_attachment.path.suffix == ".jpg"
# Verify image snapshot content
assert image_attachment.path.exists()
content = await hass.async_add_executor_job(image_attachment.path.read_bytes)
assert content == b"fake_image_jpeg"
# Trigger clean up
async_fire_time_changed(
hass,
dt_util.utcnow() + chat_session.CONVERSATION_TIMEOUT + timedelta(seconds=1),
)
await hass.async_block_till_done(wait_background_tasks=True)
# Verify the temporary file cleaned up
assert not camera_attachment.path.exists()
assert not image_attachment.path.exists()
# Check regular media attachment
media_attachment = task.attachments[2]
assert media_attachment.media_content_id == "media-source://media_player/video.mp4"
assert media_attachment.mime_type == "video/mp4"
assert media_attachment.path == Path("/media/test.mp4")
@pytest.mark.freeze_time("2025-06-14 22:59:00")
async def test_generate_image(
hass: HomeAssistant,
init_components: None,
mock_ai_task_entity: MockAITaskEntity,
) -> None:
"""Test generating image service."""
with pytest.raises(
HomeAssistantError, match="AI Task entity ai_task.unknown not found"
):
await async_generate_image(
hass,
task_name="Test Task",
entity_id="ai_task.unknown",
instructions="Test prompt",
)
state = hass.states.get(TEST_ENTITY_ID)
assert state is not None
assert state.state == STATE_UNKNOWN
with patch.object(
hass.data[DATA_MEDIA_SOURCE],
"async_upload_media",
return_value="media-source://ai_task/image/2025-06-14_225900_test_task.png",
) as mock_upload_media:
result = await async_generate_image(
hass,
task_name="Test Task",
entity_id=TEST_ENTITY_ID,
instructions="Test prompt",
)
mock_upload_media.assert_called_once()
assert "image_data" not in result
assert (
result["media_source_id"]
== "media-source://ai_task/image/2025-06-14_225900_test_task.png"
)
assert result["url"].startswith(
"/ai_task/image/2025-06-14_225900_test_task.png?authSig="
)
assert result["mime_type"] == "image/png"
assert result["model"] == "mock_model"
assert result["revised_prompt"] == "mock_revised_prompt"
assert result["height"] == 1024
assert result["width"] == 1536
state = hass.states.get(TEST_ENTITY_ID)
assert state is not None
assert state.state != STATE_UNKNOWN
mock_ai_task_entity.supported_features = AITaskEntityFeature(0)
with pytest.raises(
HomeAssistantError,
match="AI Task entity ai_task.test_task_entity does not support generating images",
):
await async_generate_image(
hass,
task_name="Test Task",
entity_id=TEST_ENTITY_ID,
instructions="Test prompt",
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ai_task/test_task.py",
"license": "Apache License 2.0",
"lines": 301,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/alexa_devices/test_sensor.py | """Tests for the Alexa Devices sensor platform."""
from typing import Any
from unittest.mock import AsyncMock, patch
from aioamazondevices.api import AmazonDeviceSensor
from aioamazondevices.exceptions import (
CannotAuthenticate,
CannotConnect,
CannotRetrieveData,
)
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.alexa_devices.coordinator 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 .const import TEST_DEVICE_1_SN
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.alexa_devices.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"side_effect",
[
CannotConnect,
CannotRetrieveData,
CannotAuthenticate,
],
)
async def test_coordinator_data_update_fails(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
side_effect: Exception,
) -> None:
"""Test coordinator data update exceptions."""
entity_id = "sensor.echo_test_temperature"
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(entity_id))
assert state.state == "22.5"
mock_amazon_devices_client.get_devices_data.side_effect = side_effect
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
async def test_offline_device(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test offline device handling."""
entity_id = "sensor.echo_test_temperature"
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].online = False
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].online = True
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state != STATE_UNAVAILABLE
@pytest.mark.parametrize(
("sensor", "api_value", "scale", "state_value", "unit"),
[
(
"temperature",
"86",
"FAHRENHEIT",
"30.0", # State machine converts to °C
"°C", # State machine converts to °C
),
("temperature", "22.5", "CELSIUS", "22.5", "°C"),
("illuminance", "800", None, "800", "lx"),
],
)
async def test_unit_of_measurement(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
sensor: str,
api_value: Any,
scale: str | None,
state_value: Any,
unit: str | None,
) -> None:
"""Test sensor unit of measurement handling."""
entity_id = f"sensor.echo_test_{sensor}"
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].sensors = {
sensor: AmazonDeviceSensor(
name=sensor,
value=api_value,
error=False,
error_msg=None,
error_type=None,
scale=scale,
)
}
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(entity_id))
assert state.state == state_value
assert state.attributes["unit_of_measurement"] == unit
async def test_sensor_unavailable(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test sensor is unavailable."""
entity_id = "sensor.echo_test_illuminance"
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].sensors = {
"illuminance": AmazonDeviceSensor(
name="illuminance",
value="800",
error=True,
error_msg=None,
error_type=None,
scale=None,
)
}
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/test_sensor.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/alexa_devices/test_utils.py | """Tests for Alexa Devices utils."""
from unittest.mock import AsyncMock
from aioamazondevices.const.devices import SPEAKER_GROUP_FAMILY, SPEAKER_GROUP_MODEL
from aioamazondevices.exceptions import CannotConnect, CannotRetrieveData
import pytest
from homeassistant.components.alexa_devices.const import DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SERVICE_TURN_ON
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import setup_integration
from .const import TEST_DEVICE_1_SN
from tests.common import MockConfigEntry
ENTITY_ID = "switch.echo_test_do_not_disturb"
@pytest.mark.parametrize(
("side_effect", "key", "error"),
[
(CannotConnect, "cannot_connect_with_error", "CannotConnect()"),
(CannotRetrieveData, "cannot_retrieve_data_with_error", "CannotRetrieveData()"),
],
)
async def test_alexa_api_call_exceptions(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
side_effect: Exception,
key: str,
error: str,
) -> None:
"""Test alexa_api_call decorator for exceptions."""
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get(ENTITY_ID))
assert state.state == STATE_OFF
mock_amazon_devices_client.set_do_not_disturb.side_effect = side_effect
# Call API
with pytest.raises(HomeAssistantError) as exc_info:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
assert exc_info.value.translation_domain == DOMAIN
assert exc_info.value.translation_key == key
assert exc_info.value.translation_placeholders == {"error": error}
async def test_alexa_unique_id_migration(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test unique_id migration."""
mock_config_entry.add_to_hass(hass)
device = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, mock_config_entry.entry_id)},
name=mock_config_entry.title,
manufacturer="Amazon",
model="Echo Dot",
entry_type=dr.DeviceEntryType.SERVICE,
)
entity = entity_registry.async_get_or_create(
DOMAIN,
SWITCH_DOMAIN,
unique_id=f"{TEST_DEVICE_1_SN}-do_not_disturb",
device_id=device.id,
config_entry=mock_config_entry,
has_entity_name=True,
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
migrated_entity = entity_registry.async_get(entity.entity_id)
assert migrated_entity is not None
assert migrated_entity.config_entry_id == mock_config_entry.entry_id
assert migrated_entity.unique_id == f"{TEST_DEVICE_1_SN}-dnd"
async def test_alexa_dnd_group_removal(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test dnd switch is removed for Speaker Groups."""
mock_config_entry.add_to_hass(hass)
device = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, mock_config_entry.entry_id)},
name=mock_config_entry.title,
manufacturer="Amazon",
model=SPEAKER_GROUP_MODEL,
entry_type=dr.DeviceEntryType.SERVICE,
)
entity = entity_registry.async_get_or_create(
DOMAIN,
SWITCH_DOMAIN,
unique_id=f"{TEST_DEVICE_1_SN}-do_not_disturb",
device_id=device.id,
config_entry=mock_config_entry,
has_entity_name=True,
)
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].device_family = SPEAKER_GROUP_FAMILY
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert not hass.states.get(entity.entity_id)
async def test_alexa_unsupported_notification_sensor_removal(
hass: HomeAssistant,
mock_amazon_devices_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test notification sensors are removed from devices that do not support them."""
mock_config_entry.add_to_hass(hass)
device = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, mock_config_entry.entry_id)},
name=mock_config_entry.title,
manufacturer="Amazon",
model=SPEAKER_GROUP_MODEL,
entry_type=dr.DeviceEntryType.SERVICE,
)
entity = entity_registry.async_get_or_create(
DOMAIN,
SENSOR_DOMAIN,
unique_id=f"{TEST_DEVICE_1_SN}-Timer",
device_id=device.id,
config_entry=mock_config_entry,
has_entity_name=True,
)
mock_amazon_devices_client.get_devices_data.return_value[
TEST_DEVICE_1_SN
].notifications_supported = False
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert not hass.states.get(entity.entity_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/alexa_devices/test_utils.py",
"license": "Apache License 2.0",
"lines": 140,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/altruist/test_config_flow.py | """Test the Altruist config flow."""
from ipaddress import ip_address
from unittest.mock import AsyncMock
from homeassistant.components.altruist.const import CONF_HOST, DOMAIN
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from tests.common import MockConfigEntry
ZEROCONF_DISCOVERY = ZeroconfServiceInfo(
ip_address=ip_address("192.168.1.100"),
ip_addresses=[ip_address("192.168.1.100")],
hostname="altruist-purple.local.",
name="altruist-purple._altruist._tcp.local.",
port=80,
type="_altruist._tcp.local.",
properties={
"PATH": "/config",
},
)
async def test_form_user_step_success(
hass: HomeAssistant,
mock_altruist_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test user step shows form and succeeds with valid input."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.100"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "5366960e8b18"
assert result["data"] == {
CONF_HOST: "192.168.1.100",
}
assert result["result"].unique_id == "5366960e8b18"
async def test_form_user_step_cannot_connect_then_recovers(
hass: HomeAssistant,
mock_altruist_client: AsyncMock,
mock_altruist_client_fails_once: None,
mock_setup_entry: AsyncMock,
) -> None:
"""Test we handle connection error and allow recovery."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
# First attempt triggers an error
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.100"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "no_device_found"}
# Second attempt recovers with a valid client
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.100"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "5366960e8b18"
assert result["result"].unique_id == "5366960e8b18"
assert result["data"] == {
CONF_HOST: "192.168.1.100",
}
async def test_form_user_step_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_altruist_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test we abort if already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_HOST: "192.168.1.100"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_zeroconf_discovery(
hass: HomeAssistant,
mock_altruist_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test zeroconf discovery."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY,
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "5366960e8b18"
assert result["data"] == {
CONF_HOST: "192.168.1.100",
}
assert result["result"].unique_id == "5366960e8b18"
async def test_zeroconf_discovery_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_altruist_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test zeroconf discovery when already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_zeroconf_discovery_cant_create_client(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_altruist_client_fails_once: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test zeroconf discovery when already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=ZEROCONF_DISCOVERY,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_device_found"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/altruist/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 138,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/altruist/test_init.py | """Test the Altruist integration."""
from unittest.mock import AsyncMock
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_setup_entry_client_creation_failure(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_altruist_client_fails_once: None,
) -> None:
"""Test setup failure when client creation fails."""
mock_config_entry.add_to_hass(hass)
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_setup_entry_fetch_data_failure(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_altruist_client: AsyncMock,
) -> None:
"""Test setup failure when initial data fetch fails."""
mock_config_entry.add_to_hass(hass)
mock_altruist_client.fetch_data.side_effect = Exception("Fetch failed")
assert not await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_unload_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_altruist_client: AsyncMock,
) -> None:
"""Test unloading of config entry."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
# Now test unloading
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/altruist/test_init.py",
"license": "Apache License 2.0",
"lines": 38,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/altruist/test_sensor.py | """Tests for the Altruist integration sensor platform."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from altruistclient import AltruistError
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_altruist_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.altruist.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)
async def test_connection_error(
hass: HomeAssistant,
mock_altruist_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test coordinator error handling during update."""
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
mock_altruist_client.fetch_data.side_effect = AltruistError()
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (
hass.states.get("sensor.5366960e8b18_bme280_temperature").state
== STATE_UNAVAILABLE
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/altruist/test_sensor.py",
"license": "Apache License 2.0",
"lines": 43,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/android_ip_webcam/test_camera.py | """Test the Android IP Webcam camera."""
from typing import Any
import pytest
from homeassistant.components.android_ip_webcam.const import DOMAIN
from homeassistant.components.camera import async_get_stream_source
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("aioclient_mock_fixture")
@pytest.mark.parametrize(
("config", "expected_stream_source"),
[
(
{
"host": "1.1.1.1",
"port": 8080,
"username": "user",
"password": "pass",
},
"rtsp://user:pass@1.1.1.1:8080/h264_aac.sdp",
),
(
{
"host": "1.1.1.1",
"port": 8080,
},
"rtsp://1.1.1.1:8080/h264_aac.sdp",
),
],
)
async def test_camera_stream_source(
hass: HomeAssistant,
config: dict[str, Any],
expected_stream_source: str,
) -> None:
"""Test camera stream source."""
entity_id = "camera.1_1_1_1"
entry = MockConfigEntry(domain=DOMAIN, data=config)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state is not None
stream_source = await async_get_stream_source(hass, entity_id)
assert stream_source == expected_stream_source
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/android_ip_webcam/test_camera.py",
"license": "Apache License 2.0",
"lines": 44,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/google_generative_ai_conversation/test_tts.py | """Tests for the Google Generative AI Conversation TTS entity."""
from __future__ import annotations
from collections.abc import Generator
from http import HTTPStatus
from pathlib import Path
from typing import Any
from unittest.mock import AsyncMock, MagicMock, Mock, patch
from google.genai import types
from google.genai.errors import APIError
import pytest
from homeassistant.components import tts
from homeassistant.components.google_generative_ai_conversation.const import (
CONF_CHAT_MODEL,
DOMAIN,
RECOMMENDED_HARM_BLOCK_THRESHOLD,
RECOMMENDED_MAX_TOKENS,
RECOMMENDED_TEMPERATURE,
RECOMMENDED_TOP_K,
RECOMMENDED_TOP_P,
)
from homeassistant.components.media_player import (
ATTR_MEDIA_CONTENT_ID,
DOMAIN as MP_DOMAIN,
SERVICE_PLAY_MEDIA,
)
from homeassistant.config_entries import ConfigSubentry
from homeassistant.const import ATTR_ENTITY_ID, CONF_API_KEY
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.core_config import async_process_ha_core_config
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_mock_service
from tests.components.tts.common import retrieve_media
from tests.typing import ClientSessionGenerator
API_ERROR_500 = APIError("test", response_json={})
TEST_CHAT_MODEL = "models/some-tts-model"
@pytest.fixture(autouse=True)
def tts_mutagen_mock_fixture_autouse(tts_mutagen_mock: MagicMock) -> None:
"""Mock writing tags."""
@pytest.fixture(autouse=True)
def mock_tts_cache_dir_autouse(mock_tts_cache_dir: Path) -> None:
"""Mock the TTS cache dir with empty dir."""
@pytest.fixture
async def calls(hass: HomeAssistant) -> list[ServiceCall]:
"""Mock media player calls."""
return async_mock_service(hass, MP_DOMAIN, SERVICE_PLAY_MEDIA)
@pytest.fixture(autouse=True)
async def setup_internal_url(hass: HomeAssistant) -> None:
"""Set up internal url."""
await async_process_ha_core_config(
hass, {"internal_url": "http://example.local:8123"}
)
@pytest.fixture
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=(
types.Candidate(
content=types.Content(
parts=(
types.Part(
inline_data=types.Blob(
data=b"raw-audio-bytes",
mime_type="audio/L16;rate=24000",
)
),
)
)
),
)
)
)
with patch(
"homeassistant.components.google_generative_ai_conversation.Client",
return_value=client,
) as mock_client:
yield mock_client
@pytest.fixture(name="setup")
async def setup_fixture(
hass: HomeAssistant,
config: dict[str, Any],
mock_genai_client: AsyncMock,
) -> None:
"""Set up the test environment."""
config_entry = MockConfigEntry(domain=DOMAIN, data=config, version=2)
config_entry.add_to_hass(hass)
sub_entry = ConfigSubentry(
data={
tts.CONF_LANG: "en-US",
CONF_CHAT_MODEL: TEST_CHAT_MODEL,
},
subentry_type="tts",
title="Google AI TTS",
subentry_id="test_subentry_tts_id",
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)
assert await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
@pytest.fixture(name="config")
def config_fixture() -> dict[str, Any]:
"""Return config."""
return {
CONF_API_KEY: "bla",
}
@pytest.mark.parametrize(
"service_data",
[
{
ATTR_ENTITY_ID: "tts.google_ai_tts",
tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something",
tts.ATTR_MESSAGE: "There is a person at the front door.",
tts.ATTR_OPTIONS: {},
},
{
ATTR_ENTITY_ID: "tts.google_ai_tts",
tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something",
tts.ATTR_MESSAGE: "There is a person at the front door.",
tts.ATTR_OPTIONS: {tts.ATTR_VOICE: "voice2"},
},
],
)
@pytest.mark.usefixtures("setup")
async def test_tts_service_speak(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
calls: list[ServiceCall],
service_data: dict[str, Any],
) -> None:
"""Test tts service."""
tts_entity = hass.data[tts.DOMAIN].get_entity(service_data[ATTR_ENTITY_ID])
tts_entity._genai_client.aio.models.generate_content.reset_mock()
await hass.services.async_call(
tts.DOMAIN,
"speak",
service_data,
blocking=True,
)
assert len(calls) == 1
assert (
await retrieve_media(hass, hass_client, calls[0].data[ATTR_MEDIA_CONTENT_ID])
== HTTPStatus.OK
)
voice_id = service_data[tts.ATTR_OPTIONS].get(tts.ATTR_VOICE, "zephyr")
tts_entity._genai_client.aio.models.generate_content.assert_called_once_with(
model=TEST_CHAT_MODEL,
contents="There is a person at the front door.",
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice_id)
)
),
temperature=RECOMMENDED_TEMPERATURE,
top_k=RECOMMENDED_TOP_K,
top_p=RECOMMENDED_TOP_P,
max_output_tokens=RECOMMENDED_MAX_TOKENS,
safety_settings=[
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=RECOMMENDED_HARM_BLOCK_THRESHOLD,
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold=RECOMMENDED_HARM_BLOCK_THRESHOLD,
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=RECOMMENDED_HARM_BLOCK_THRESHOLD,
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold=RECOMMENDED_HARM_BLOCK_THRESHOLD,
),
],
thinking_config=None,
),
)
@pytest.mark.usefixtures("setup")
async def test_tts_service_speak_error(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
calls: list[ServiceCall],
) -> None:
"""Test service call with HTTP response 500."""
service_data = {
ATTR_ENTITY_ID: "tts.google_ai_tts",
tts.ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something",
tts.ATTR_MESSAGE: "There is a person at the front door.",
tts.ATTR_OPTIONS: {tts.ATTR_VOICE: "voice1"},
}
tts_entity = hass.data[tts.DOMAIN].get_entity(service_data[ATTR_ENTITY_ID])
tts_entity._genai_client.aio.models.generate_content.reset_mock()
tts_entity._genai_client.aio.models.generate_content.side_effect = API_ERROR_500
await hass.services.async_call(
tts.DOMAIN,
"speak",
service_data,
blocking=True,
)
assert len(calls) == 1
assert (
await retrieve_media(hass, hass_client, calls[0].data[ATTR_MEDIA_CONTENT_ID])
== HTTPStatus.INTERNAL_SERVER_ERROR
)
voice_id = service_data[tts.ATTR_OPTIONS].get(tts.ATTR_VOICE)
tts_entity._genai_client.aio.models.generate_content.assert_called_once_with(
model=TEST_CHAT_MODEL,
contents="There is a person at the front door.",
config=types.GenerateContentConfig(
response_modalities=["AUDIO"],
speech_config=types.SpeechConfig(
voice_config=types.VoiceConfig(
prebuilt_voice_config=types.PrebuiltVoiceConfig(voice_name=voice_id)
)
),
temperature=RECOMMENDED_TEMPERATURE,
top_k=RECOMMENDED_TOP_K,
top_p=RECOMMENDED_TOP_P,
max_output_tokens=RECOMMENDED_MAX_TOKENS,
safety_settings=[
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
threshold=RECOMMENDED_HARM_BLOCK_THRESHOLD,
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold=RECOMMENDED_HARM_BLOCK_THRESHOLD,
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=RECOMMENDED_HARM_BLOCK_THRESHOLD,
),
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
threshold=RECOMMENDED_HARM_BLOCK_THRESHOLD,
),
],
thinking_config=None,
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/google_generative_ai_conversation/test_tts.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/homee/test_diagnostics.py | """Test homee diagnostics."""
from unittest.mock import MagicMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.homee.const import DOMAIN
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
from tests.components.diagnostics import (
get_diagnostics_for_config_entry,
get_diagnostics_for_device,
)
from tests.typing import ClientSessionGenerator
async def setup_mock_homee(
hass: HomeAssistant, mock_homee: MagicMock, mock_config_entry: MockConfigEntry
) -> None:
"""Set up the number platform."""
mock_homee.nodes = [
build_mock_node("numbers.json"),
build_mock_node("thermostat_with_currenttemp.json"),
build_mock_node("cover_with_position_slats.json"),
]
mock_homee.get_node_by_id = lambda node_id: mock_homee.nodes[node_id - 1]
await setup_integration(hass, mock_config_entry)
async def test_diagnostics_config_entry(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics for config entry."""
await setup_mock_homee(hass, mock_homee, mock_config_entry)
result = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
assert result == snapshot
async def test_diagnostics_device(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics for a device."""
await setup_mock_homee(hass, mock_homee, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, f"{HOMEE_ID}-1")}
)
assert device_entry is not None
result = await get_diagnostics_for_device(
hass, hass_client, mock_config_entry, device_entry
)
assert result == snapshot
async def test_diagnostics_homee_device(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_homee: MagicMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics for the homee hub device."""
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)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, f"{HOMEE_ID}")}
)
assert device_entry is not None
result = await get_diagnostics_for_device(
hass, hass_client, mock_config_entry, device_entry
)
assert result == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homee/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 78,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homee/test_siren.py | """Test homee sirens."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.siren import (
DOMAIN as SIREN_DOMAIN,
SERVICE_TOGGLE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import async_update_attribute_value, build_mock_node, setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def setup_siren(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_homee: MagicMock
) -> None:
"""Setups the integration siren tests."""
mock_homee.nodes = [build_mock_node("siren.json")]
mock_homee.get_node_by_id.return_value = mock_homee.nodes[0]
await setup_integration(hass, mock_config_entry)
@pytest.mark.parametrize(
("service", "target_value"),
[
(SERVICE_TURN_ON, 1),
(SERVICE_TURN_OFF, 0),
(SERVICE_TOGGLE, 1),
],
)
async def test_siren_services(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_homee: MagicMock,
service: str,
target_value: int,
) -> None:
"""Test siren services."""
await setup_siren(hass, mock_config_entry, mock_homee)
await hass.services.async_call(
SIREN_DOMAIN,
service,
{ATTR_ENTITY_ID: "siren.test_siren"},
)
mock_homee.set_value.assert_called_once_with(1, 1, target_value)
async def test_siren_state(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_homee: MagicMock,
) -> None:
"""Test siren state."""
await setup_siren(hass, mock_config_entry, mock_homee)
state = hass.states.get("siren.test_siren")
assert state.state == "off"
attribute = mock_homee.nodes[0].attributes[0]
await async_update_attribute_value(hass, attribute, 1.0)
state = hass.states.get("siren.test_siren")
assert state.state == "on"
async def test_siren_snapshot(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_homee: MagicMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test siren snapshot."""
with patch("homeassistant.components.homee.PLATFORMS", [Platform.SIREN]):
await setup_siren(hass, mock_config_entry, mock_homee)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homee/test_siren.py",
"license": "Apache License 2.0",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homewizard/test_select.py | """Test the Select entity for HomeWizard."""
from unittest.mock import MagicMock
from homewizard_energy import UnsupportedError
from homewizard_energy.errors import RequestError, UnauthorizedError
from homewizard_energy.models import Batteries
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.homewizard.const import UPDATE_INTERVAL
from homeassistant.components.select import (
ATTR_OPTION,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.util import dt as dt_util
from tests.common import async_fire_time_changed
pytestmark = [
pytest.mark.usefixtures("init_integration"),
]
@pytest.mark.parametrize(
("device_fixture", "entity_ids"),
[
(
"HWE-WTR",
[
"select.device_battery_group_mode",
],
),
(
"SDM230",
[
"select.device_battery_group_mode",
],
),
(
"SDM630",
[
"select.device_battery_group_mode",
],
),
(
"HWE-KWH1",
[
"select.device_battery_group_mode",
],
),
(
"HWE-KWH3",
[
"select.device_battery_group_mode",
],
),
],
)
async def test_entities_not_created_for_device(
hass: HomeAssistant,
entity_ids: list[str],
) -> None:
"""Ensures entities for a specific device are not created."""
for entity_id in entity_ids:
assert not hass.states.get(entity_id)
@pytest.mark.parametrize(
("device_fixture", "entity_id"),
[
("HWE-P1", "select.device_battery_group_mode"),
],
)
async def test_select_entity_snapshots(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
entity_id: str,
) -> None:
"""Test that select entity state and registry entries match snapshots."""
assert (state := hass.states.get(entity_id))
assert snapshot == state
assert (entity_entry := entity_registry.async_get(entity_id))
assert snapshot == entity_entry
assert entity_entry.device_id
assert (device_entry := device_registry.async_get(entity_entry.device_id))
assert snapshot == device_entry
@pytest.mark.parametrize(
("device_fixture", "entity_id", "option", "expected_mode"),
[
(
"HWE-P1",
"select.device_battery_group_mode",
"standby",
Batteries.Mode.STANDBY,
),
(
"HWE-P1",
"select.device_battery_group_mode",
"to_full",
Batteries.Mode.TO_FULL,
),
("HWE-P1", "select.device_battery_group_mode", "zero", Batteries.Mode.ZERO),
],
)
async def test_select_set_option(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
entity_id: str,
option: str,
expected_mode: Batteries.Mode,
) -> None:
"""Test that selecting an option calls the correct API method."""
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: option,
},
blocking=True,
)
mock_homewizardenergy.batteries.assert_called_with(mode=expected_mode)
@pytest.mark.parametrize(
("device_fixture", "entity_id", "option"),
[
("HWE-P1", "select.device_battery_group_mode", "zero"),
("HWE-P1", "select.device_battery_group_mode", "standby"),
("HWE-P1", "select.device_battery_group_mode", "to_full"),
],
)
async def test_select_request_error(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
entity_id: str,
option: str,
) -> None:
"""Test that RequestError is handled and raises HomeAssistantError."""
mock_homewizardenergy.batteries.side_effect = RequestError
with pytest.raises(
HomeAssistantError,
match=r"^An error occurred while communicating with your HomeWizard device$",
):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: option,
},
blocking=True,
)
@pytest.mark.parametrize(
("device_fixture", "entity_id", "option"),
[
("HWE-P1", "select.device_battery_group_mode", "to_full"),
],
)
async def test_select_unauthorized_error(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
entity_id: str,
option: str,
) -> None:
"""Test that UnauthorizedError is handled and raises HomeAssistantError."""
mock_homewizardenergy.batteries.side_effect = UnauthorizedError
with pytest.raises(
HomeAssistantError,
match=r"^The local API is unauthorized\. Restore API access by following the instructions in the repair issue$",
):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: option,
},
blocking=True,
)
@pytest.mark.parametrize("device_fixture", ["HWE-P1"])
@pytest.mark.parametrize("exception", [RequestError, UnsupportedError])
@pytest.mark.parametrize(
("entity_id", "method"),
[
("select.device_battery_group_mode", "combined"),
],
)
async def test_select_unreachable(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
exception: Exception,
entity_id: str,
method: str,
) -> None:
"""Test that unreachable devices are marked as unavailable."""
mocked_method = getattr(mock_homewizardenergy, method)
mocked_method.side_effect = exception
async_fire_time_changed(hass, dt_util.utcnow() + UPDATE_INTERVAL)
await hass.async_block_till_done()
assert (state := hass.states.get(entity_id))
assert state.state == STATE_UNAVAILABLE
@pytest.mark.parametrize(
("device_fixture", "entity_id"),
[
("HWE-P1", "select.device_battery_group_mode"),
],
)
async def test_select_multiple_state_changes(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
entity_id: str,
) -> None:
"""Test changing select state multiple times in sequence."""
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: "zero",
},
blocking=True,
)
mock_homewizardenergy.batteries.assert_called_with(mode=Batteries.Mode.ZERO)
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: "to_full",
},
blocking=True,
)
mock_homewizardenergy.batteries.assert_called_with(mode=Batteries.Mode.TO_FULL)
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: entity_id,
ATTR_OPTION: "standby",
},
blocking=True,
)
mock_homewizardenergy.batteries.assert_called_with(mode=Batteries.Mode.STANDBY)
@pytest.mark.parametrize(
("device_fixture", "entity_ids"),
[
(
"HWE-P1-no-batteries",
[
"select.device_battery_group_mode",
],
),
],
)
async def test_disabled_by_default_selects(
hass: HomeAssistant, entity_registry: er.EntityRegistry, entity_ids: list[str]
) -> None:
"""Test the disabled by default selects."""
for entity_id in entity_ids:
assert not hass.states.get(entity_id)
assert (entry := entity_registry.async_get(entity_id))
assert entry.disabled
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homewizard/test_select.py",
"license": "Apache License 2.0",
"lines": 261,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/immich/test_update.py | """Test the Immich update platform."""
from unittest.mock import Mock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_update(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Immich update platform."""
with patch("homeassistant.components.immich.PLATFORMS", [Platform.UPDATE]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_update_min_version(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_immich: Mock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Immich update platform with min version not installed."""
mock_immich.server.async_get_about_info.return_value.version = "v1.132.3"
with patch("homeassistant.components.immich.PLATFORMS", [Platform.UPDATE]):
await setup_integration(hass, mock_config_entry)
assert not hass.states.async_all()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/immich/test_update.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/lametric/test_update.py | """Tests for the LaMetric update platform."""
from unittest.mock import MagicMock
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.parametrize("init_integration", [Platform.UPDATE], indirect=True),
pytest.mark.usefixtures("init_integration"),
]
@pytest.mark.parametrize("device_fixture", ["device_sa5"])
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_lametric: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/lametric/test_update.py",
"license": "Apache License 2.0",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/meater/test_diagnostics.py | """Test Meater diagnostics."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_entry_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_meater_client: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test config entry 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/meater/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/meater/test_init.py | """Tests for the Meater integration."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.meater.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import setup_integration
from .const import PROBE_ID
from tests.common import MockConfigEntry
async def test_device_info(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_meater_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test device registry integration."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(identifiers={(DOMAIN, PROBE_ID)})
assert device_entry is not None
assert device_entry == snapshot
async def test_load_unload(
hass: HomeAssistant,
mock_meater_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test unload of Meater integration."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
assert (
len(
er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
)
== 8
)
assert (
hass.states.get("sensor.meater_probe_40a72384_ambient_temperature").state
!= STATE_UNAVAILABLE
)
assert await hass.config_entries.async_reload(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.LOADED
assert (
len(
er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
)
== 8
)
assert (
hass.states.get("sensor.meater_probe_40a72384_ambient_temperature").state
!= STATE_UNAVAILABLE
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/meater/test_init.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/meater/test_sensor.py | """Tests for the Meater sensors."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.freeze_time("2023-10-21")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_meater_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the sensor entities."""
with patch("homeassistant.components.meater.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/meater/test_sensor.py",
"license": "Apache License 2.0",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/music_assistant/test_button.py | """Test Music Assistant button entities."""
from unittest.mock import MagicMock, call
from music_assistant_models.enums import EventType
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant, HomeAssistantError
from homeassistant.helpers import entity_registry as er
from .common import (
setup_integration_from_fixtures,
snapshot_music_assistant_entities,
trigger_subscription_callback,
)
async def test_button_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
music_assistant_client: MagicMock,
) -> None:
"""Test media player."""
await setup_integration_from_fixtures(hass, music_assistant_client)
snapshot_music_assistant_entities(hass, entity_registry, snapshot, Platform.BUTTON)
async def test_button_press_action(
hass: HomeAssistant,
music_assistant_client: MagicMock,
) -> None:
"""Test button press action."""
await setup_integration_from_fixtures(hass, music_assistant_client)
entity_id = "button.my_super_test_player_2_favorite_current_song"
state = hass.states.get(entity_id)
assert state
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
assert music_assistant_client.send_command.call_count == 1
assert music_assistant_client.send_command.call_args == call(
"music/favorites/add_item",
item="spotify://track/5d95dc5be77e4f7eb4939f62cfef527b",
)
# test again without current_media
mass_player_id = "00:00:00:00:00:02"
music_assistant_client.players._players[mass_player_id].current_media = None
await trigger_subscription_callback(
hass, music_assistant_client, EventType.PLAYER_CONFIG_UPDATED, mass_player_id
)
with pytest.raises(HomeAssistantError, match="No current item to add to favorites"):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
# test again without active source
mass_player_id = "00:00:00:00:00:02"
music_assistant_client.players._players[mass_player_id].active_source = None
await trigger_subscription_callback(
hass, music_assistant_client, EventType.PLAYER_CONFIG_UPDATED, mass_player_id
)
with pytest.raises(HomeAssistantError, match="No current item to add to favorites"):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/music_assistant/test_button.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/ntfy/test_sensor.py | """Tests for the ntfy 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 sensor_only() -> Generator[None]:
"""Enable only the sensor platform."""
with patch(
"homeassistant.components.ntfy.PLATFORMS",
[Platform.SENSOR],
):
yield
@pytest.mark.usefixtures("mock_aiontfy", "entity_registry_enabled_by_default")
async def test_setup(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Snapshot test states of 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/ntfy/test_sensor.py",
"license": "Apache License 2.0",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/openuv/test_binary_sensor.py | """Test OpenUV binary sensors."""
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.homeassistant import (
DOMAIN as HOMEASSISTANT_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_binary_sensors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_pyopenuv: None,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all binary sensors created by the integration."""
with patch("homeassistant.components.openuv.PLATFORMS", [Platform.BINARY_SENSOR]):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
async def test_protection_window_update(
hass: HomeAssistant,
set_time_zone,
config,
client,
config_entry,
setup_config_entry,
snapshot: SnapshotAssertion,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that updating the protection window makes an extra API call."""
assert await async_setup_component(hass, HOMEASSISTANT_DOMAIN, {})
assert client.uv_protection_window.call_count == 1
await hass.services.async_call(
HOMEASSISTANT_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: "binary_sensor.openuv_protection_window"},
blocking=True,
)
assert client.uv_protection_window.call_count == 2
@pytest.mark.parametrize(
"data_protection_window",
[{"result": {"from_time": None, "from_uv": 0, "to_time": None, "to_uv": 0}}],
)
async def test_protection_window_null_value_response(
hass: HomeAssistant,
set_time_zone,
config,
client,
config_entry,
setup_config_entry,
) -> None:
"""Test that null values in the protection window clears the state."""
entity_id = "binary_sensor.openuv_protection_window"
hass.states.async_set(entity_id, "on", {})
assert await async_setup_component(hass, HOMEASSISTANT_DOMAIN, {})
await hass.services.async_call(
HOMEASSISTANT_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
state = hass.states.get(entity_id)
assert state.state == "unknown"
@pytest.mark.parametrize(
"data_protection_window",
[{"result": {"error": "missing expected keys"}}],
)
async def test_protection_window_invalid_response(
hass: HomeAssistant,
set_time_zone,
config,
client,
config_entry,
mock_pyopenuv,
) -> None:
"""Test that missing values in the protection window generate an error."""
assert await hass.config_entries.async_setup(config_entry.entry_id) is False
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_protection_window_recalculation(
hass: HomeAssistant,
config,
config_entry,
snapshot: SnapshotAssertion,
set_time_zone,
mock_pyopenuv,
client,
freezer: FrozenDateTimeFactory,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that protection window updates automatically without extra API calls."""
freezer.move_to("2018-07-30T06:17:59-06:00")
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
entity_id = "binary_sensor.openuv_protection_window"
state = hass.states.get(entity_id)
assert state.state == "off"
assert state == snapshot(name="before-protection-state")
# move to when the protection window starts
freezer.move_to("2018-07-30T09:17:59-06:00")
async_fire_time_changed(hass)
await hass.async_block_till_done()
entity_id = "binary_sensor.openuv_protection_window"
state = hass.states.get(entity_id)
assert state.state == "on"
assert state == snapshot(name="during-protection-state")
# move to when the protection window ends
freezer.move_to("2018-07-30T16:47:59-06:00")
async_fire_time_changed(hass)
await hass.async_block_till_done()
entity_id = "binary_sensor.openuv_protection_window"
state = hass.states.get(entity_id)
assert state.state == "off"
assert state == snapshot(name="after-protection-state")
assert client.uv_protection_window.call_count == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openuv/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 125,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/openuv/test_sensor.py | """Test OpenUV sensors."""
from unittest.mock import patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
async def test_sensors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_pyopenuv: None,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all sensors created by the integration."""
with patch("homeassistant.components.openuv.PLATFORMS", [Platform.SENSOR]):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openuv/test_sensor.py",
"license": "Apache License 2.0",
"lines": 19,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/paperless_ngx/test_update.py | """Tests for Paperless-ngx update platform."""
from unittest.mock import AsyncMock, MagicMock
from freezegun.api import FrozenDateTimeFactory
from pypaperless.exceptions import PaperlessConnectionError
from pypaperless.models import RemoteVersion
import pytest
from homeassistant.components.paperless_ngx.update import SCAN_INTERVAL
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 . import setup_integration
from tests.common import (
MockConfigEntry,
SnapshotAssertion,
async_fire_time_changed,
patch,
snapshot_platform,
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_update_platfom(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test paperless_ngx update sensors."""
with patch("homeassistant.components.paperless_ngx.PLATFORMS", [Platform.UPDATE]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("init_integration")
async def test_update_sensor_downgrade_upgrade(
hass: HomeAssistant,
mock_paperless: AsyncMock,
freezer: FrozenDateTimeFactory,
init_integration: MockConfigEntry,
) -> None:
"""Ensure update entities are updating properly on downgrade and upgrade."""
state = hass.states.get("update.paperless_ngx_software")
assert state.state == STATE_OFF
# downgrade host version
mock_paperless.host_version = "2.2.0"
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("update.paperless_ngx_software")
assert state.state == STATE_ON
# upgrade host version
mock_paperless.host_version = "2.3.0"
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("update.paperless_ngx_software")
assert state.state == STATE_OFF
@pytest.mark.usefixtures("init_integration")
async def test_update_sensor_state_on_error(
hass: HomeAssistant,
mock_paperless: AsyncMock,
freezer: FrozenDateTimeFactory,
mock_remote_version_data: MagicMock,
) -> None:
"""Ensure update entities handle errors properly."""
# simulate error
mock_paperless.remote_version.side_effect = PaperlessConnectionError
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("update.paperless_ngx_software")
assert state.state == STATE_UNAVAILABLE
# recover from not auth errors
mock_paperless.remote_version = AsyncMock(
return_value=RemoteVersion.create_with_data(
mock_paperless, data=mock_remote_version_data, fetched=True
)
)
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("update.paperless_ngx_software")
assert state.state == STATE_OFF
@pytest.mark.usefixtures("init_integration")
async def test_update_sensor_version_unavailable(
hass: HomeAssistant,
mock_paperless: AsyncMock,
freezer: FrozenDateTimeFactory,
mock_remote_version_data_unavailable: MagicMock,
) -> None:
"""Ensure update entities handle version unavailable properly."""
state = hass.states.get("update.paperless_ngx_software")
assert state.state == STATE_OFF
# set version unavailable
mock_paperless.remote_version = AsyncMock(
return_value=RemoteVersion.create_with_data(
mock_paperless, data=mock_remote_version_data_unavailable, fetched=True
)
)
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("update.paperless_ngx_software")
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/paperless_ngx/test_update.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/playstation_network/test_config_flow.py | """Test the Playstation Network config flow."""
from unittest.mock import MagicMock
import pytest
from homeassistant.components.playstation_network.config_flow import (
PSNAWPAuthenticationError,
PSNAWPError,
PSNAWPInvalidTokenError,
PSNAWPNotFoundError,
)
from homeassistant.components.playstation_network.const import (
CONF_ACCOUNT_ID,
CONF_NPSSO,
DOMAIN,
)
from homeassistant.config_entries import (
SOURCE_USER,
ConfigEntryDisabler,
ConfigEntryState,
ConfigSubentry,
ConfigSubentryData,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import NPSSO_TOKEN, NPSSO_TOKEN_INVALID_JSON, PSN_ID
from tests.common import MockConfigEntry
MOCK_DATA_ADVANCED_STEP = {CONF_NPSSO: NPSSO_TOKEN}
async def test_manual_config(hass: HomeAssistant, mock_psnawpapi: MagicMock) -> None:
"""Test creating via manual configuration."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: "TEST_NPSSO_TOKEN"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["result"].unique_id == PSN_ID
assert result["data"] == {
CONF_NPSSO: "TEST_NPSSO_TOKEN",
}
async def test_form_already_configured(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
) -> None:
"""Test we abort form login when entry is already configured."""
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: NPSSO_TOKEN},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_form_already_configured_as_subentry(hass: HomeAssistant) -> None:
"""Test we abort form login when entry is already configured as subentry of another entry."""
config_entry = MockConfigEntry(
domain=DOMAIN,
title="PublicUniversalFriend",
data={
CONF_NPSSO: NPSSO_TOKEN,
},
unique_id="fren-psn-id",
subentries_data=[
ConfigSubentryData(
data={CONF_ACCOUNT_ID: PSN_ID},
subentry_id="ABCDEF",
subentry_type="friend",
title="test-user",
unique_id=PSN_ID,
)
],
)
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: NPSSO_TOKEN},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured_as_subentry"
@pytest.mark.parametrize(
("raise_error", "text_error"),
[
(PSNAWPNotFoundError("error msg"), "invalid_account"),
(PSNAWPAuthenticationError("error msg"), "invalid_auth"),
(PSNAWPError("error msg"), "cannot_connect"),
(Exception(), "unknown"),
],
)
async def test_form_failures(
hass: HomeAssistant,
mock_psnawpapi: MagicMock,
raise_error: Exception,
text_error: str,
) -> None:
"""Test we handle a connection error.
First we generate an error and after fixing it, we are still able to submit.
"""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
mock_psnawpapi.user.side_effect = raise_error
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: NPSSO_TOKEN},
)
assert result["step_id"] == "user"
assert result["errors"] == {"base": text_error}
mock_psnawpapi.user.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: NPSSO_TOKEN},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_NPSSO: NPSSO_TOKEN,
}
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_parse_npsso_token_failures(
hass: HomeAssistant,
mock_psnawp_npsso: MagicMock,
) -> None:
"""Test parse_npsso_token raises the correct exceptions during config flow."""
mock_psnawp_npsso.side_effect = PSNAWPInvalidTokenError("error msg")
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data={CONF_NPSSO: NPSSO_TOKEN_INVALID_JSON},
)
assert result["errors"] == {"base": "invalid_account"}
mock_psnawp_npsso.side_effect = lambda token: token
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: NPSSO_TOKEN},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_NPSSO: NPSSO_TOKEN,
}
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_flow_reauth(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test reauth flow."""
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: "NEW_NPSSO_TOKEN"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert config_entry.data[CONF_NPSSO] == "NEW_NPSSO_TOKEN"
assert len(hass.config_entries.async_entries()) == 1
@pytest.mark.parametrize(
("raise_error", "text_error"),
[
(PSNAWPNotFoundError("error msg"), "invalid_account"),
(PSNAWPAuthenticationError("error msg"), "invalid_auth"),
(PSNAWPError("error msg"), "cannot_connect"),
(Exception(), "unknown"),
],
)
async def test_flow_reauth_errors(
hass: HomeAssistant,
mock_psnawpapi: MagicMock,
config_entry: MockConfigEntry,
raise_error: Exception,
text_error: str,
) -> None:
"""Test reauth flow errors."""
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
mock_psnawpapi.user.side_effect = raise_error
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: "NEW_NPSSO_TOKEN"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": text_error}
mock_psnawpapi.user.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: "NEW_NPSSO_TOKEN"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert config_entry.data[CONF_NPSSO] == "NEW_NPSSO_TOKEN"
assert len(hass.config_entries.async_entries()) == 1
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_flow_reauth_token_error(
hass: HomeAssistant,
mock_psnawp_npsso: MagicMock,
config_entry: MockConfigEntry,
) -> None:
"""Test reauth flow token error."""
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
mock_psnawp_npsso.side_effect = PSNAWPInvalidTokenError("error msg")
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: "NEW_NPSSO_TOKEN"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "invalid_account"}
mock_psnawp_npsso.side_effect = lambda token: token
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: "NEW_NPSSO_TOKEN"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert config_entry.data[CONF_NPSSO] == "NEW_NPSSO_TOKEN"
assert len(hass.config_entries.async_entries()) == 1
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_flow_reauth_account_mismatch(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_user: MagicMock,
) -> None:
"""Test reauth flow unique_id mismatch."""
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
mock_user.account_id = "other_account"
result = await config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: "NEW_NPSSO_TOKEN"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_flow_reconfigure(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test reconfigure flow."""
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
result = await config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_NPSSO: "NEW_NPSSO_TOKEN"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert config_entry.data[CONF_NPSSO] == "NEW_NPSSO_TOKEN"
assert len(hass.config_entries.async_entries()) == 1
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_add_friend_flow(hass: HomeAssistant) -> None:
"""Test add friend subentry flow."""
config_entry = MockConfigEntry(
domain=DOMAIN,
title="test-user",
data={
CONF_NPSSO: NPSSO_TOKEN,
},
unique_id=PSN_ID,
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
result = await hass.config_entries.subentries.async_init(
(config_entry.entry_id, "friend"),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
user_input={CONF_ACCOUNT_ID: "fren-psn-id"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
subentry_id = list(config_entry.subentries)[0]
assert config_entry.subentries == {
subentry_id: ConfigSubentry(
data={},
subentry_id=subentry_id,
subentry_type="friend",
title="PublicUniversalFriend",
unique_id="fren-psn-id",
)
}
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_add_friend_flow_already_configured(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test we abort add friend subentry flow when already configured."""
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
result = await hass.config_entries.subentries.async_init(
(config_entry.entry_id, "friend"),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
user_input={CONF_ACCOUNT_ID: "fren-psn-id"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_add_friend_flow_already_configured_as_entry(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test we abort add friend subentry flow when already configured as config entry."""
config_entry = MockConfigEntry(
domain=DOMAIN,
title="test-user",
data={
CONF_NPSSO: NPSSO_TOKEN,
},
unique_id=PSN_ID,
)
fren_config_entry = MockConfigEntry(
domain=DOMAIN,
title="PublicUniversalFriend",
data={
CONF_NPSSO: NPSSO_TOKEN,
},
unique_id="fren-psn-id",
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
fren_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(fren_config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
result = await hass.config_entries.subentries.async_init(
(config_entry.entry_id, "friend"),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
user_input={CONF_ACCOUNT_ID: "fren-psn-id"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured_as_entry"
async def test_add_friend_flow_no_friends(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_psnawpapi: MagicMock,
) -> None:
"""Test we abort add friend subentry flow when the user has no friends."""
mock_psnawpapi.user.return_value.friends_list.return_value = []
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
result = await hass.config_entries.subentries.async_init(
(config_entry.entry_id, "friend"),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_friends"
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_add_friend_disabled_config_entry(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test we abort add friend subentry flow when the parent config entry is disabled."""
config_entry = MockConfigEntry(
domain=DOMAIN,
title="test-user",
data={
CONF_NPSSO: NPSSO_TOKEN,
},
disabled_by=ConfigEntryDisabler.USER,
unique_id=PSN_ID,
)
config_entry.add_to_hass(hass)
result = await hass.config_entries.subentries.async_init(
(config_entry.entry_id, "friend"),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "config_entry_disabled"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/playstation_network/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 426,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/playstation_network/test_diagnostics.py | """Tests for PlayStation Network diagnostics."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
@pytest.mark.usefixtures("mock_psnawpapi")
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert (
await get_diagnostics_for_config_entry(hass, hass_client, config_entry)
== snapshot
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/playstation_network/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/playstation_network/test_media_player.py | """Test the Playstation Network media player platform."""
from collections.abc import AsyncGenerator
from typing import Any
from unittest.mock import MagicMock, 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)
async def media_player_only() -> AsyncGenerator[None]:
"""Enable only the media_player platform."""
with patch(
"homeassistant.components.playstation_network.PLATFORMS",
[Platform.MEDIA_PLAYER],
):
yield
@pytest.mark.parametrize(
"presence_payload",
[
{
"basicPresence": {
"availability": "availableToPlay",
"primaryPlatformInfo": {"onlineStatus": "online", "platform": "PS5"},
"gameTitleInfoList": [
{
"npTitleId": "PPSA07784_00",
"titleName": "STAR WARS Jedi: Survivor™",
"format": "PS5",
"launchPlatform": "PS5",
"conceptIconUrl": "https://image.api.playstation.com/vulcan/ap/rnd/202211/2222/l8QTN7ThQK3lRBHhB3nX1s7h.png",
}
],
}
},
{
"basicPresence": {
"availability": "availableToPlay",
"primaryPlatformInfo": {"onlineStatus": "online", "platform": "PS4"},
"gameTitleInfoList": [
{
"npTitleId": "CUSA23081_00",
"titleName": "Untitled Goose Game",
"format": "PS4",
"launchPlatform": "PS4",
"npTitleIconUrl": "http://gs2-sec.ww.prod.dl.playstation.net/gs2-sec/appkgo/prod/CUSA23081_00/5/i_f5d2adec7665af80b8550fb33fe808df10d292cdd47629a991debfdf72bdee34/i/icon0.png",
}
],
}
},
{
"basicPresence": {
"availability": "unavailable",
"lastAvailableDate": "2025-05-02T17:47:59.392Z",
"primaryPlatformInfo": {
"onlineStatus": "offline",
"platform": "PS5",
"lastOnlineDate": "2025-05-02T17:47:59.392Z",
},
}
},
{
"basicPresence": {
"availability": "unavailable",
"lastAvailableDate": "2025-05-02T17:47:59.392Z",
"primaryPlatformInfo": {
"onlineStatus": "offline",
"platform": "PS4",
"lastOnlineDate": "2025-05-02T17:47:59.392Z",
},
}
},
{
"basicPresence": {
"availability": "availableToPlay",
"primaryPlatformInfo": {"onlineStatus": "online", "platform": "PS5"},
}
},
{
"basicPresence": {
"availability": "availableToPlay",
"primaryPlatformInfo": {"onlineStatus": "online", "platform": "PS4"},
}
},
],
ids=[
"PS5_playing",
"PS4_playing",
"PS5_offline",
"PS4_offline",
"PS5_idle",
"PS4_idle",
],
)
@pytest.mark.usefixtures("mock_psnawpapi", "mock_token")
async def test_platform(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_psnawpapi: MagicMock,
presence_payload: dict[str, Any],
) -> None:
"""Test setup of the PlayStation Network media_player platform."""
mock_psnawpapi.user().get_presence.return_value = presence_payload
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
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize(
"presence_payload",
[
{
"profile": {
"presences": [
{
"onlineStatus": "standby",
"platform": "PSVITA",
"hasBroadcastData": False,
}
]
}
},
{
"profile": {
"presences": [
{
"onlineStatus": "online",
"platform": "PSVITA",
"npTitleId": "PCSB00074_00",
"titleName": "Assassin's Creed® III Liberation",
"hasBroadcastData": False,
}
]
}
},
{
"profile": {
"presences": [
{
"onlineStatus": "online",
"platform": "PSVITA",
"hasBroadcastData": False,
}
]
}
},
],
)
@pytest.mark.usefixtures("mock_psnawpapi", "mock_token")
async def test_media_player_psvita(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_psnawpapi: MagicMock,
presence_payload: dict[str, Any],
) -> None:
"""Test setup of the PlayStation Network media_player for PlayStation Vita."""
mock_psnawpapi.user().get_presence.return_value = {
"basicPresence": {
"availability": "unavailable",
"primaryPlatformInfo": {"onlineStatus": "offline", "platform": ""},
}
}
mock_psnawpapi.me.return_value.get_profile_legacy.return_value = presence_payload
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_media_player.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/playstation_network/test_sensor.py | """Test the Playstation Network 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 sensor_only() -> Generator[None]:
"""Enable only the sensor platform."""
with patch(
"homeassistant.components.playstation_network.PLATFORMS",
[Platform.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 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_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/pushbullet/test_sensor.py | """Test pushbullet sensor platform."""
from unittest.mock import Mock
import pytest
from homeassistant.components.pushbullet.const import DOMAIN
from homeassistant.components.pushbullet.sensor import (
SENSOR_TYPES,
PushBulletNotificationSensor,
)
from homeassistant.const import MAX_LENGTH_STATE_STATE
from homeassistant.core import HomeAssistant
from . import MOCK_CONFIG
from tests.common import MockConfigEntry
def _create_mock_provider() -> Mock:
"""Create a mock pushbullet provider for testing."""
mock_provider = Mock()
mock_provider.pushbullet.user_info = {"iden": "test_user_123"}
return mock_provider
def _get_sensor_description(key: str):
"""Get sensor description by key."""
for desc in SENSOR_TYPES:
if desc.key == key:
return desc
raise ValueError(f"Sensor description not found for key: {key}")
def _create_test_sensor(
provider: Mock, sensor_key: str
) -> PushBulletNotificationSensor:
"""Create a test sensor instance with mocked dependencies."""
description = _get_sensor_description(sensor_key)
sensor = PushBulletNotificationSensor(
name="Test Pushbullet", pb_provider=provider, description=description
)
# Mock async_write_ha_state to avoid requiring full HA setup
sensor.async_write_ha_state = Mock()
return sensor
@pytest.fixture
async def mock_pushbullet_entry(hass: HomeAssistant, requests_mock_fixture):
"""Set up pushbullet integration."""
entry = MockConfigEntry(
domain=DOMAIN,
data=MOCK_CONFIG,
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry
def test_sensor_truncation_logic() -> None:
"""Test sensor truncation logic for body sensor."""
provider = _create_mock_provider()
sensor = _create_test_sensor(provider, "body")
# Test long body truncation
long_body = "a" * (MAX_LENGTH_STATE_STATE + 50)
provider.data = {
"body": long_body,
"title": "Test Title",
"type": "note",
}
sensor.async_update_callback()
# Verify truncation
assert len(sensor._attr_native_value) == MAX_LENGTH_STATE_STATE
assert sensor._attr_native_value.endswith("...")
assert sensor._attr_native_value.startswith("a")
assert sensor._attr_extra_state_attributes["body"] == long_body
# Test normal length body
normal_body = "This is a normal body"
provider.data = {
"body": normal_body,
"title": "Test Title",
"type": "note",
}
sensor.async_update_callback()
# Verify no truncation
assert sensor._attr_native_value == normal_body
assert len(sensor._attr_native_value) < MAX_LENGTH_STATE_STATE
assert sensor._attr_extra_state_attributes["body"] == normal_body
# Test exactly max length
exact_body = "a" * MAX_LENGTH_STATE_STATE
provider.data = {
"body": exact_body,
"title": "Test Title",
"type": "note",
}
sensor.async_update_callback()
# Verify no truncation at the limit
assert sensor._attr_native_value == exact_body
assert len(sensor._attr_native_value) == MAX_LENGTH_STATE_STATE
assert sensor._attr_extra_state_attributes["body"] == exact_body
def test_sensor_truncation_title_sensor() -> None:
"""Test sensor truncation logic on title sensor."""
provider = _create_mock_provider()
sensor = _create_test_sensor(provider, "title")
# Test long title truncation
long_title = "Title " + "x" * (MAX_LENGTH_STATE_STATE)
provider.data = {
"body": "Test body",
"title": long_title,
"type": "note",
}
sensor.async_update_callback()
# Verify truncation
assert len(sensor._attr_native_value) == MAX_LENGTH_STATE_STATE
assert sensor._attr_native_value.endswith("...")
assert sensor._attr_native_value.startswith("Title")
assert sensor._attr_extra_state_attributes["title"] == long_title
def test_sensor_truncation_non_string_handling() -> None:
"""Test that non-string values are handled correctly."""
provider = _create_mock_provider()
sensor = _create_test_sensor(provider, "body")
# Test with None value
provider.data = {
"body": None,
"title": "Test Title",
"type": "note",
}
sensor.async_update_callback()
assert sensor._attr_native_value is None
# Test with integer value (would be converted to string by Home Assistant)
provider.data = {
"body": 12345,
"title": "Test Title",
"type": "note",
}
sensor.async_update_callback()
assert sensor._attr_native_value == 12345 # Not truncated since it's not a string
# Test with missing key
provider.data = {
"title": "Test Title",
"type": "note",
}
# This should not raise an exception
sensor.async_update_callback()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/pushbullet/test_sensor.py",
"license": "Apache License 2.0",
"lines": 130,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/qbus/test_cover.py | """Test Qbus cover entities."""
from unittest.mock import AsyncMock
from qbusmqttapi.state import QbusMqttShutterState
from homeassistant.components.cover import (
ATTR_CURRENT_POSITION,
ATTR_CURRENT_TILT_POSITION,
ATTR_POSITION,
ATTR_TILT_POSITION,
DOMAIN as COVER_DOMAIN,
CoverEntityFeature,
CoverState,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_CLOSE_COVER,
SERVICE_CLOSE_COVER_TILT,
SERVICE_OPEN_COVER,
SERVICE_OPEN_COVER_TILT,
SERVICE_SET_COVER_POSITION,
SERVICE_SET_COVER_TILT_POSITION,
SERVICE_STOP_COVER,
)
from homeassistant.core import HomeAssistant
from tests.common import async_fire_mqtt_message
_PAYLOAD_UDS_STATE_CLOSED = '{"id":"UL30","properties":{"state":"down"},"type":"state"}'
_PAYLOAD_UDS_STATE_OPENED = '{"id":"UL30","properties":{"state":"up"},"type":"state"}'
_PAYLOAD_UDS_STATE_STOPPED = (
'{"id":"UL30","properties":{"state":"stop"},"type":"state"}'
)
_PAYLOAD_POS_STATE_CLOSED = (
'{"id":"UL32","properties":{"shutterPosition":0},"type":"event"}'
)
_PAYLOAD_POS_STATE_OPENED = (
'{"id":"UL32","properties":{"shutterPosition":100},"type":"event"}'
)
_PAYLOAD_POS_STATE_POSITION = (
'{"id":"UL32","properties":{"shutterPosition":50},"type":"event"}'
)
_PAYLOAD_SLAT_STATE_CLOSED = (
'{"id":"UL31","properties":{"slatPosition":0},"type":"event"}'
)
_PAYLOAD_SLAT_STATE_FULLY_CLOSED = (
'{"id":"UL31","properties":{"slatPosition":0,"shutterPosition":0},"type":"event"}'
)
_PAYLOAD_SLAT_STATE_OPENED = (
'{"id":"UL31","properties":{"slatPosition":50},"type":"event"}'
)
_PAYLOAD_SLAT_STATE_POSITION = (
'{"id":"UL31","properties":{"slatPosition":75},"type":"event"}'
)
_TOPIC_UDS_STATE = "cloudapp/QBUSMQTTGW/UL1/UL30/state"
_TOPIC_POS_STATE = "cloudapp/QBUSMQTTGW/UL1/UL32/state"
_TOPIC_SLAT_STATE = "cloudapp/QBUSMQTTGW/UL1/UL31/state"
_ENTITY_ID_UDS = "cover.curtains"
_ENTITY_ID_POS = "cover.blinds"
_ENTITY_ID_SLAT = "cover.slats"
async def test_cover_up_down_stop(
hass: HomeAssistant, setup_integration: None, mock_publish_state: AsyncMock
) -> None:
"""Test cover up, down and stop."""
attributes = hass.states.get(_ENTITY_ID_UDS).attributes
assert attributes.get("supported_features") == (
CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | CoverEntityFeature.STOP
)
# Cover open
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{ATTR_ENTITY_ID: _ENTITY_ID_UDS},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_state() == "up"
# Simulate response
async_fire_mqtt_message(hass, _TOPIC_UDS_STATE, _PAYLOAD_UDS_STATE_OPENED)
await hass.async_block_till_done()
assert hass.states.get(_ENTITY_ID_UDS).state == CoverState.OPEN
# Cover close
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: _ENTITY_ID_UDS},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_state() == "down"
# Simulate response
async_fire_mqtt_message(hass, _TOPIC_UDS_STATE, _PAYLOAD_UDS_STATE_CLOSED)
await hass.async_block_till_done()
assert hass.states.get(_ENTITY_ID_UDS).state == CoverState.OPEN
# Cover stop
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_STOP_COVER,
{ATTR_ENTITY_ID: _ENTITY_ID_UDS},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_state() == "stop"
# Simulate response
async_fire_mqtt_message(hass, _TOPIC_UDS_STATE, _PAYLOAD_UDS_STATE_STOPPED)
await hass.async_block_till_done()
assert hass.states.get(_ENTITY_ID_UDS).state == CoverState.CLOSED
async def test_cover_position(
hass: HomeAssistant, setup_integration: None, mock_publish_state: AsyncMock
) -> None:
"""Test cover positions."""
attributes = hass.states.get(_ENTITY_ID_POS).attributes
assert attributes.get("supported_features") == (
CoverEntityFeature.OPEN
| CoverEntityFeature.CLOSE
| CoverEntityFeature.SET_POSITION
)
# Cover open
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER,
{ATTR_ENTITY_ID: _ENTITY_ID_POS},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_position() == 100
async_fire_mqtt_message(hass, _TOPIC_POS_STATE, _PAYLOAD_POS_STATE_OPENED)
await hass.async_block_till_done()
entity_state = hass.states.get(_ENTITY_ID_POS)
assert entity_state.state == CoverState.OPEN
assert entity_state.attributes[ATTR_CURRENT_POSITION] == 100
# Cover position
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_POSITION,
{ATTR_ENTITY_ID: _ENTITY_ID_POS, ATTR_POSITION: 50},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_position() == 50
async_fire_mqtt_message(hass, _TOPIC_POS_STATE, _PAYLOAD_POS_STATE_POSITION)
await hass.async_block_till_done()
entity_state = hass.states.get(_ENTITY_ID_POS)
assert entity_state.state == CoverState.OPEN
assert entity_state.attributes[ATTR_CURRENT_POSITION] == 50
# Cover close
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: _ENTITY_ID_POS},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_position() == 0
async_fire_mqtt_message(hass, _TOPIC_POS_STATE, _PAYLOAD_POS_STATE_CLOSED)
await hass.async_block_till_done()
entity_state = hass.states.get(_ENTITY_ID_POS)
assert entity_state.state == CoverState.CLOSED
assert entity_state.attributes[ATTR_CURRENT_POSITION] == 0
async def test_cover_slats(
hass: HomeAssistant, setup_integration: None, mock_publish_state: AsyncMock
) -> None:
"""Test cover slats."""
attributes = hass.states.get(_ENTITY_ID_SLAT).attributes
assert attributes.get("supported_features") == (
CoverEntityFeature.OPEN
| CoverEntityFeature.CLOSE
| CoverEntityFeature.SET_POSITION
| CoverEntityFeature.OPEN_TILT
| CoverEntityFeature.CLOSE_TILT
| CoverEntityFeature.SET_TILT_POSITION
)
# Start with a fully closed cover
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: _ENTITY_ID_SLAT},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_position() == 0
assert publish_state.read_slat_position() == 0
async_fire_mqtt_message(hass, _TOPIC_SLAT_STATE, _PAYLOAD_SLAT_STATE_FULLY_CLOSED)
await hass.async_block_till_done()
entity_state = hass.states.get(_ENTITY_ID_SLAT)
assert entity_state.state == CoverState.CLOSED
assert entity_state.attributes[ATTR_CURRENT_POSITION] == 0
assert entity_state.attributes[ATTR_CURRENT_TILT_POSITION] == 0
# Slat open
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER_TILT,
{ATTR_ENTITY_ID: _ENTITY_ID_SLAT},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_slat_position() == 50
async_fire_mqtt_message(hass, _TOPIC_SLAT_STATE, _PAYLOAD_SLAT_STATE_OPENED)
await hass.async_block_till_done()
entity_state = hass.states.get(_ENTITY_ID_SLAT)
assert entity_state.state == CoverState.OPEN
assert entity_state.attributes[ATTR_CURRENT_TILT_POSITION] == 50
# SLat position
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{ATTR_ENTITY_ID: _ENTITY_ID_SLAT, ATTR_TILT_POSITION: 75},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_slat_position() == 75
async_fire_mqtt_message(hass, _TOPIC_SLAT_STATE, _PAYLOAD_SLAT_STATE_POSITION)
await hass.async_block_till_done()
entity_state = hass.states.get(_ENTITY_ID_SLAT)
assert entity_state.state == CoverState.OPEN
assert entity_state.attributes[ATTR_CURRENT_TILT_POSITION] == 75
# Slat close
mock_publish_state.reset_mock()
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER_TILT,
{ATTR_ENTITY_ID: _ENTITY_ID_SLAT},
blocking=True,
)
publish_state = _get_publish_state(mock_publish_state)
assert publish_state.read_slat_position() == 0
async_fire_mqtt_message(hass, _TOPIC_SLAT_STATE, _PAYLOAD_SLAT_STATE_CLOSED)
await hass.async_block_till_done()
entity_state = hass.states.get(_ENTITY_ID_SLAT)
assert entity_state.state == CoverState.CLOSED
assert entity_state.attributes[ATTR_CURRENT_TILT_POSITION] == 0
def _get_publish_state(mock_publish_state: AsyncMock) -> QbusMqttShutterState:
assert mock_publish_state.call_count == 1
state = mock_publish_state.call_args.args[0]
assert isinstance(state, QbusMqttShutterState)
return state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/qbus/test_cover.py",
"license": "Apache License 2.0",
"lines": 241,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/rest/test_data.py | """Test REST data module logging improvements."""
from datetime import timedelta
import logging
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components.rest import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import async_fire_time_changed
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_rest_data_log_warning_on_error_status(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that warning is logged for error status codes."""
# Mock a 403 response with HTML content
aioclient_mock.get(
"http://example.com/api",
status=403,
text="<html><body>Access Denied</body></html>",
headers={"Content-Type": "text/html"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value_json.test }}",
}
],
}
},
)
await hass.async_block_till_done()
# Check that warning was logged
assert (
"REST request to http://example.com/api returned status 403 "
"with text/html response" in caplog.text
)
assert "<html><body>Access Denied</body></html>" in caplog.text
async def test_rest_data_no_warning_on_200_with_wrong_content_type(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that no warning is logged for 200 status with wrong content."""
# Mock a 200 response with HTML - users might still want to parse this
aioclient_mock.get(
"http://example.com/api",
status=200,
text="<p>This is HTML, not JSON!</p>",
headers={"Content-Type": "text/html; charset=utf-8"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value }}",
}
],
}
},
)
await hass.async_block_till_done()
# Should NOT warn for 200 status, even with HTML content type
assert (
"REST request to http://example.com/api returned status 200" not in caplog.text
)
async def test_rest_data_with_incorrect_charset_in_header(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that we can handle sites which provides an incorrect charset."""
aioclient_mock.get(
"http://example.com/api",
status=200,
text="<p>Some html</p>",
headers={"Content-Type": "text/html; charset=utf-8"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"encoding": "windows-1250",
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value }}",
}
],
}
},
)
await hass.async_block_till_done()
with patch(
"tests.test_util.aiohttp.AiohttpClientMockResponse.text",
side_effect=UnicodeDecodeError("utf-8", b"", 1, 0, ""),
):
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
log_text = "Response charset came back as utf-8 but could not be decoded, continue with configured encoding windows-1250."
assert log_text in caplog.text
caplog.clear()
freezer.tick(timedelta(minutes=1))
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Only log once as we only try once with automatic decoding
assert log_text not in caplog.text
async def test_rest_data_no_warning_on_success_json(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that no warning is logged for successful JSON responses."""
# Mock a successful JSON response
aioclient_mock.get(
"http://example.com/api",
status=200,
json={"status": "ok", "value": 42},
headers={"Content-Type": "application/json"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value_json.value }}",
}
],
}
},
)
await hass.async_block_till_done()
# Check that no warning was logged
assert "REST request to http://example.com/api returned status" not in caplog.text
async def test_rest_data_no_warning_on_success_xml(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that no warning is logged for successful XML responses."""
# Mock a successful XML response
aioclient_mock.get(
"http://example.com/api",
status=200,
text='<?xml version="1.0"?><root><value>42</value></root>',
headers={"Content-Type": "application/xml"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value_json.root.value }}",
}
],
}
},
)
await hass.async_block_till_done()
# Check that no warning was logged
assert "REST request to http://example.com/api returned status" not in caplog.text
async def test_rest_data_warning_truncates_long_responses(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that warning truncates very long response bodies."""
# Create a very long error message
long_message = "Error: " + "x" * 1000
aioclient_mock.get(
"http://example.com/api",
status=500,
text=long_message,
headers={"Content-Type": "text/plain"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value_json.test }}",
}
],
}
},
)
await hass.async_block_till_done()
# Check that warning was logged with truncation
# Set the logger filter to only check our specific logger
caplog.set_level(logging.WARNING, logger="homeassistant.components.rest.data")
# Verify the truncated warning appears
assert (
"REST request to http://example.com/api returned status 500 "
"with text/plain response: Error: " + "x" * 493 + "..." in caplog.text
)
async def test_rest_data_debug_logging_shows_response_details(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that debug logging shows response details."""
caplog.set_level(logging.DEBUG)
aioclient_mock.get(
"http://example.com/api",
status=200,
json={"test": "data"},
headers={"Content-Type": "application/json"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value_json.test }}",
}
],
}
},
)
await hass.async_block_till_done()
# Check debug log
assert (
"REST response from http://example.com/api: status=200, "
"content-type=application/json, length=" in caplog.text
)
async def test_rest_data_no_content_type_header(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test handling of responses without Content-Type header."""
caplog.set_level(logging.DEBUG)
# Mock response without Content-Type header
aioclient_mock.get(
"http://example.com/api",
status=200,
text="plain text response",
headers={}, # No Content-Type
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"sensor": [
{
"name": "test_sensor",
}
],
}
},
)
await hass.async_block_till_done()
# Check debug log shows "not set"
assert "content-type=not set" in caplog.text
# No warning for 200 with missing content-type
assert "REST request to http://example.com/api returned status" not in caplog.text
async def test_rest_data_real_world_bom_blocking_scenario(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test real-world scenario where BOM blocks with HTML response."""
# Mock BOM blocking response
bom_block_html = "<p>Your access is blocked due to automated access</p>"
aioclient_mock.get(
"http://www.bom.gov.au/fwo/IDN60901/IDN60901.94767.json",
status=403,
text=bom_block_html,
headers={"Content-Type": "text/html"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": ("http://www.bom.gov.au/fwo/IDN60901/IDN60901.94767.json"),
"method": "GET",
"sensor": [
{
"name": "bom_temperature",
"value_template": (
"{{ value_json.observations.data[0].air_temp }}"
),
}
],
}
},
)
await hass.async_block_till_done()
# Check that warning was logged with clear indication of the issue
assert (
"REST request to http://www.bom.gov.au/fwo/IDN60901/"
"IDN60901.94767.json returned status 403 with text/html response"
) in caplog.text
assert "Your access is blocked" in caplog.text
async def test_rest_data_warning_on_html_error(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that warning is logged for error status with HTML content."""
# Mock a 404 response with HTML error page
aioclient_mock.get(
"http://example.com/api",
status=404,
text="<html><body><h1>404 Not Found</h1></body></html>",
headers={"Content-Type": "text/html"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value_json.test }}",
}
],
}
},
)
await hass.async_block_till_done()
# Should warn for error status with HTML
assert (
"REST request to http://example.com/api returned status 404 "
"with text/html response" in caplog.text
)
assert "<html><body><h1>404 Not Found</h1></body></html>" in caplog.text
async def test_rest_data_no_warning_on_json_error(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test POST request that returns JSON error - no warning expected."""
aioclient_mock.post(
"http://example.com/api",
status=400,
text='{"error": "Invalid request payload"}',
headers={"Content-Type": "application/json"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "POST",
"payload": '{"data": "test"}',
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value_json.error }}",
}
],
}
},
)
await hass.async_block_till_done()
# Should NOT warn for JSON error responses - users can parse these
assert (
"REST request to http://example.com/api returned status 400" not in caplog.text
)
async def test_rest_data_timeout_error(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test timeout error logging."""
aioclient_mock.get(
"http://example.com/api",
exc=TimeoutError(),
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"timeout": 10,
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value_json.test }}",
}
],
}
},
)
await hass.async_block_till_done()
# Check timeout error is logged or platform reports not ready
assert (
"Timeout while fetching data: http://example.com/api" in caplog.text
or "Platform rest not ready yet" in caplog.text
)
async def test_rest_data_boolean_params_converted_to_strings(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that boolean parameters are converted to lowercase strings."""
# Mock the request and capture the actual URL
aioclient_mock.get(
"http://example.com/api",
status=200,
json={"status": "ok"},
headers={"Content-Type": "application/json"},
)
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"resource": "http://example.com/api",
"method": "GET",
"params": {
"boolTrue": True,
"boolFalse": False,
"stringParam": "test",
"intParam": 123,
},
"sensor": [
{
"name": "test_sensor",
"value_template": "{{ value_json.status }}",
}
],
}
},
)
await hass.async_block_till_done()
# Check that the request was made with boolean values converted to strings
assert len(aioclient_mock.mock_calls) == 1
_method, url, _data, _headers = aioclient_mock.mock_calls[0]
# Check that the URL query parameters have boolean values converted to strings
assert url.query["boolTrue"] == "true"
assert url.query["boolFalse"] == "false"
assert url.query["stringParam"] == "test"
assert url.query["intParam"] == "123"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/rest/test_data.py",
"license": "Apache License 2.0",
"lines": 485,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/russound_rio/test_number.py | """Tests for the Russound RIO number platform."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from .const import NAME_ZONE_1
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_russound_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.russound_rio.PLATFORMS", [Platform.NUMBER]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("entity_suffix", "value", "expected_method", "expected_arg"),
[
("bass", -5, "set_bass", -5),
("balance", 3, "set_balance", 3),
("treble", 7, "set_treble", 7),
("turn_on_volume", 60, "set_turn_on_volume", 30),
],
)
async def test_setting_number_value(
hass: HomeAssistant,
mock_russound_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_suffix: str,
value: int,
expected_method: str,
expected_arg: int,
) -> None:
"""Test setting value on Russound number entity."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{
ATTR_ENTITY_ID: f"{NUMBER_DOMAIN}.{NAME_ZONE_1}_{entity_suffix}",
ATTR_VALUE: value,
},
blocking=True,
)
zone = mock_russound_client.controllers[1].zones[1]
getattr(zone, expected_method).assert_called_once_with(expected_arg)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/russound_rio/test_number.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/russound_rio/test_switch.py | """Tests for the Russound RIO switch platform."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN, SERVICE_TURN_ON
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_OFF, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_russound_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.russound_rio.PLATFORMS", [Platform.SWITCH]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_setting_value(
hass: HomeAssistant,
mock_russound_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setting value."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "switch.backyard_loudness",
},
blocking=True,
)
mock_russound_client.controllers[1].zones[1].set_loudness.assert_called_once_with(
True
)
mock_russound_client.controllers[1].zones[1].set_loudness.reset_mock()
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{
ATTR_ENTITY_ID: "switch.backyard_loudness",
},
blocking=True,
)
mock_russound_client.controllers[1].zones[1].set_loudness.assert_called_once_with(
False
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/russound_rio/test_switch.py",
"license": "Apache License 2.0",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/smarla/test_number.py | """Test number platform for Swing2Sleep Smarla integration."""
from unittest.mock import MagicMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration, update_property_listeners
from tests.common import MockConfigEntry, snapshot_platform
NUMBER_ENTITIES = [
{
"entity_id": "number.smarla_intensity",
"service": "babywiege",
"property": "intensity",
},
]
@pytest.mark.usefixtures("mock_federwiege")
async def test_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the Smarla entities."""
with (
patch("homeassistant.components.smarla.PLATFORMS", [Platform.NUMBER]),
):
assert await setup_integration(hass, mock_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
@pytest.mark.parametrize(
("service", "parameter"),
[(SERVICE_SET_VALUE, 100)],
)
@pytest.mark.parametrize("entity_info", NUMBER_ENTITIES)
async def test_number_action(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_federwiege: MagicMock,
entity_info: dict[str, str],
service: str,
parameter: int,
) -> None:
"""Test Smarla Number set behavior."""
assert await setup_integration(hass, mock_config_entry)
mock_number_property = mock_federwiege.get_property(
entity_info["service"], entity_info["property"]
)
entity_id = entity_info["entity_id"]
# Turn on
await hass.services.async_call(
NUMBER_DOMAIN,
service,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: parameter},
blocking=True,
)
mock_number_property.set.assert_called_once_with(parameter)
@pytest.mark.parametrize("entity_info", NUMBER_ENTITIES)
async def test_number_state_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_federwiege: MagicMock,
entity_info: dict[str, str],
) -> None:
"""Test Smarla Number callback."""
assert await setup_integration(hass, mock_config_entry)
mock_number_property = mock_federwiege.get_property(
entity_info["service"], entity_info["property"]
)
entity_id = entity_info["entity_id"]
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "1.0"
mock_number_property.get.return_value = 100
await update_property_listeners(mock_number_property)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "100.0"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/smarla/test_number.py",
"license": "Apache License 2.0",
"lines": 85,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/sonos/test_diagnostics.py | """Tests for the diagnostics data provided by the Sonos integration."""
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import paths
from homeassistant.components.sonos.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceRegistry
from tests.common import MockConfigEntry
from tests.components.diagnostics import (
get_diagnostics_for_config_entry,
get_diagnostics_for_device,
)
from tests.typing import ClientSessionGenerator
async def test_diagnostics_config_entry(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
async_autosetup_sonos,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics for config entry."""
result = await get_diagnostics_for_config_entry(hass, hass_client, config_entry)
# Exclude items that are timing dependent.
assert result == snapshot(
exclude=paths(
"current_timestamp",
"discovered.RINCON_test.event_stats.soco:from_didl_string",
"discovered.RINCON_test.sonos_group_entities",
)
)
async def test_diagnostics_device(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
device_registry: DeviceRegistry,
async_autosetup_sonos,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics for device."""
TEST_DEVICE = "RINCON_test"
device_entry = device_registry.async_get_device(identifiers={(DOMAIN, TEST_DEVICE)})
assert device_entry is not None
result = await get_diagnostics_for_device(
hass, hass_client, config_entry, device_entry
)
assert result == snapshot(
exclude=paths(
"event_stats.soco:from_didl_string",
"sonos_group_entities",
)
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sonos/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/sun/test_binary_sensor.py | """The tests for the Sun binary_sensor platform."""
from datetime import datetime, timedelta
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components import sun
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_setting_rising(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test retrieving sun setting and rising."""
utc_now = datetime(2016, 11, 1, 8, 0, 0, tzinfo=dt_util.UTC)
freezer.move_to(utc_now)
await async_setup_component(hass, sun.DOMAIN, {sun.DOMAIN: {}})
await hass.async_block_till_done()
assert hass.states.get("binary_sensor.sun_solar_rising").state == "on"
entry_ids = hass.config_entries.async_entries("sun")
freezer.tick(timedelta(hours=12))
# Block once for Sun to update
await hass.async_block_till_done()
# Block another time for the sensors to update
await hass.async_block_till_done()
# Make sure all the signals work
assert hass.states.get("binary_sensor.sun_solar_rising").state == "off"
entity = entity_registry.async_get("binary_sensor.sun_solar_rising")
assert entity
assert entity.entity_category is EntityCategory.DIAGNOSTIC
assert entity.unique_id == f"{entry_ids[0].entry_id}-solar_rising"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sun/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 34,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/telegram_bot/test_config_flow.py | """Config flow tests for the Telegram Bot integration."""
from unittest.mock import AsyncMock, patch
from telegram import AcceptedGiftTypes, ChatFullInfo, User
from telegram.constants import AccentColor
from telegram.error import BadRequest, InvalidToken, NetworkError
from homeassistant.components.telegram_bot.config_flow import DESCRIPTION_PLACEHOLDERS
from homeassistant.components.telegram_bot.const import (
ATTR_PARSER,
CONF_API_ENDPOINT,
CONF_CHAT_ID,
CONF_PROXY_URL,
CONF_TRUSTED_NETWORKS,
DOMAIN,
PARSER_MD,
PARSER_PLAIN_TEXT,
PLATFORM_BROADCAST,
PLATFORM_WEBHOOKS,
SECTION_ADVANCED_SETTINGS,
SUBENTRY_TYPE_ALLOWED_CHAT_IDS,
)
from homeassistant.config_entries import SOURCE_USER, ConfigSubentry
from homeassistant.const import CONF_API_KEY, CONF_PLATFORM, CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry, pytest
async def test_options_flow(
hass: HomeAssistant, mock_webhooks_config_entry: MockConfigEntry
) -> None:
"""Test options flow."""
mock_webhooks_config_entry.add_to_hass(hass)
# test: no input
result = await hass.config_entries.options.async_init(
mock_webhooks_config_entry.entry_id
)
await hass.async_block_till_done()
assert result["step_id"] == "init"
assert result["type"] is FlowResultType.FORM
# test: valid input
result = await hass.config_entries.options.async_configure(
result["flow_id"],
{
ATTR_PARSER: PARSER_PLAIN_TEXT,
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"][ATTR_PARSER] == PARSER_PLAIN_TEXT
async def test_reconfigure_flow_broadcast(
hass: HomeAssistant,
mock_webhooks_config_entry: MockConfigEntry,
mock_external_calls: None,
) -> None:
"""Test reconfigure flow for broadcast bot."""
mock_webhooks_config_entry.add_to_hass(hass)
result = await mock_webhooks_config_entry.start_reconfigure_flow(hass)
assert result["step_id"] == "reconfigure"
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
# test: invalid proxy url
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_me",
) as mock_bot:
mock_bot.side_effect = NetworkError("mock invalid proxy")
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PLATFORM: PLATFORM_BROADCAST,
SECTION_ADVANCED_SETTINGS: {
CONF_PROXY_URL: "invalid",
},
},
)
await hass.async_block_till_done()
assert result["step_id"] == "reconfigure"
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "invalid_proxy_url"
# test: valid
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PLATFORM: PLATFORM_BROADCAST,
SECTION_ADVANCED_SETTINGS: {
CONF_PROXY_URL: "https://test",
},
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_webhooks_config_entry.data[CONF_PLATFORM] == PLATFORM_BROADCAST
assert mock_webhooks_config_entry.data[CONF_PROXY_URL] == "https://test"
async def test_reconfigure_flow_webhooks(
hass: HomeAssistant,
mock_broadcast_config_entry: MockConfigEntry,
mock_external_calls: None,
) -> None:
"""Test reconfigure flow for webhook."""
mock_broadcast_config_entry.add_to_hass(hass)
result = await mock_broadcast_config_entry.start_reconfigure_flow(hass)
assert result["step_id"] == "reconfigure"
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PLATFORM: PLATFORM_WEBHOOKS,
SECTION_ADVANCED_SETTINGS: {
CONF_API_ENDPOINT: "http://mock_api_endpoint",
CONF_PROXY_URL: "https://test",
},
},
)
await hass.async_block_till_done()
assert result["step_id"] == "webhooks"
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
# test: invalid url
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "http://test",
CONF_TRUSTED_NETWORKS: "149.154.160.0/20,91.108.4.0/22",
},
)
assert result["step_id"] == "webhooks"
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "invalid_url"
# test: HA external url not configured
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_TRUSTED_NETWORKS: "149.154.160.0/20,91.108.4.0/22"},
)
assert result["step_id"] == "webhooks"
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "no_url_available"
# test: invalid trusted networks
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://reconfigure",
CONF_TRUSTED_NETWORKS: "invalid trusted networks",
},
)
assert result["step_id"] == "webhooks"
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "invalid_trusted_networks"
# test: valid input
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://reconfigure",
CONF_TRUSTED_NETWORKS: "149.154.160.0/20",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_broadcast_config_entry.data[CONF_URL] == "https://reconfigure"
assert (
mock_broadcast_config_entry.data[CONF_API_ENDPOINT]
== "http://mock_api_endpoint"
)
assert mock_broadcast_config_entry.data[CONF_TRUSTED_NETWORKS] == [
"149.154.160.0/20"
]
@pytest.mark.parametrize(
("side_effect", "expected_error", "expected_description_placeholders"),
[
# test case 1: logout fails with network error, then succeeds
pytest.param(
[NetworkError("mock network error"), True],
"telegram_error",
{**DESCRIPTION_PLACEHOLDERS, "error_message": "mock network error"},
),
# test case 2: logout fails with unsuccessful response, then succeeds
pytest.param(
[False, True],
"bot_logout_failed",
DESCRIPTION_PLACEHOLDERS,
),
],
)
async def test_reconfigure_flow_logout_failed(
hass: HomeAssistant,
mock_broadcast_config_entry: MockConfigEntry,
mock_external_calls: None,
side_effect: list,
expected_error: str,
expected_description_placeholders: dict[str, str],
) -> None:
"""Test reconfigure flow for with change in API endpoint and logout failed."""
mock_broadcast_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id)
await hass.async_block_till_done()
result = await mock_broadcast_config_entry.start_reconfigure_flow(hass)
assert result["step_id"] == "reconfigure"
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
with patch(
"homeassistant.components.telegram_bot.bot.Bot.log_out",
AsyncMock(side_effect=side_effect),
):
# first logout attempt fails
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PLATFORM: PLATFORM_BROADCAST,
SECTION_ADVANCED_SETTINGS: {
CONF_API_ENDPOINT: "http://mock1",
},
},
)
await hass.async_block_till_done()
assert result["step_id"] == "reconfigure"
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": expected_error}
assert result["description_placeholders"] == expected_description_placeholders
# second logout attempt success
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PLATFORM: PLATFORM_BROADCAST,
SECTION_ADVANCED_SETTINGS: {
CONF_API_ENDPOINT: "http://mock2",
},
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_broadcast_config_entry.data[CONF_API_ENDPOINT] == "http://mock2"
async def test_create_entry(hass: HomeAssistant) -> None:
"""Test user flow."""
# test: no input
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["step_id"] == "user"
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
# test: invalid proxy url
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PLATFORM: PLATFORM_WEBHOOKS,
CONF_API_KEY: "mock api key",
SECTION_ADVANCED_SETTINGS: {
CONF_PROXY_URL: "invalid",
},
},
)
await hass.async_block_till_done()
assert result["step_id"] == "user"
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "invalid_proxy_url"
assert result["description_placeholders"]["error_field"] == "proxy url"
# test: telegram error
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_me",
) as mock_bot:
mock_bot.side_effect = NetworkError("mock network error")
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PLATFORM: PLATFORM_WEBHOOKS,
CONF_API_KEY: "mock api key",
SECTION_ADVANCED_SETTINGS: {
CONF_PROXY_URL: "https://proxy",
},
},
)
await hass.async_block_till_done()
assert result["step_id"] == "user"
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "telegram_error"
assert result["description_placeholders"]["error_message"] == "mock network error"
# test: valid input, to continue with webhooks step
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_me",
return_value=User(123456, "Testbot", True),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_PLATFORM: PLATFORM_WEBHOOKS,
CONF_API_KEY: "mock api key",
SECTION_ADVANCED_SETTINGS: {
CONF_PROXY_URL: "https://proxy",
},
},
)
await hass.async_block_till_done()
assert result["step_id"] == "webhooks"
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
# test: valid input for webhooks
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_URL: "https://test",
CONF_TRUSTED_NETWORKS: "149.154.160.0/20",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Testbot"
assert result["data"][CONF_PLATFORM] == PLATFORM_WEBHOOKS
assert result["data"][CONF_API_KEY] == "mock api key"
assert result["data"][CONF_PROXY_URL] == "https://proxy"
assert result["data"][CONF_URL] == "https://test"
assert result["data"][CONF_TRUSTED_NETWORKS] == ["149.154.160.0/20"]
async def test_reauth_flow(
hass: HomeAssistant, mock_webhooks_config_entry: MockConfigEntry
) -> None:
"""Test a reauthentication flow."""
mock_webhooks_config_entry.add_to_hass(hass)
result = await mock_webhooks_config_entry.start_reauth_flow(
hass, data={CONF_API_KEY: "dummy"}
)
assert result["step_id"] == "reauth_confirm"
assert result["type"] is FlowResultType.FORM
assert result["errors"] is None
# test: reauth invalid api key
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_me"
) as mock_bot:
mock_bot.side_effect = InvalidToken("mock invalid token error")
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "new mock api key"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "invalid_api_key"
# test: valid
with (
patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_me",
return_value=User(123456, "Testbot", True),
),
patch(
"homeassistant.components.telegram_bot.webhooks.PushBot",
) as mock_pushbot,
):
mock_pushbot.return_value.start_application = AsyncMock()
mock_pushbot.return_value.register_webhook = AsyncMock()
mock_pushbot.return_value.shutdown = AsyncMock()
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_API_KEY: "new mock api key"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_webhooks_config_entry.data[CONF_API_KEY] == "new mock api key"
async def test_subentry_flow(
hass: HomeAssistant, mock_broadcast_config_entry: MockConfigEntry
) -> None:
"""Test subentry flow."""
mock_broadcast_config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_me",
return_value=User(123456, "Testbot", True),
):
assert await hass.config_entries.async_setup(
mock_broadcast_config_entry.entry_id
)
await hass.async_block_till_done()
result = await hass.config_entries.subentries.async_init(
(mock_broadcast_config_entry.entry_id, SUBENTRY_TYPE_ALLOWED_CHAT_IDS),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_chat",
return_value=ChatFullInfo(
id=987654321,
title="mock title",
first_name="mock first_name",
type="PRIVATE",
max_reaction_count=100,
accent_color_id=AccentColor.COLOR_000,
accepted_gift_types=AcceptedGiftTypes(True, True, True, True),
),
):
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
user_input={CONF_CHAT_ID: 987654321},
)
await hass.async_block_till_done()
subentry_id = list(mock_broadcast_config_entry.subentries)[-1]
subentry: ConfigSubentry = mock_broadcast_config_entry.subentries[subentry_id]
assert result["type"] is FlowResultType.CREATE_ENTRY
assert subentry.subentry_type == SUBENTRY_TYPE_ALLOWED_CHAT_IDS
assert subentry.title == "mock title (987654321)"
assert subentry.unique_id == "987654321"
assert subentry.data == {CONF_CHAT_ID: 987654321}
async def test_subentry_flow_config_not_ready(
hass: HomeAssistant, mock_broadcast_config_entry: MockConfigEntry
) -> None:
"""Test subentry flow where config entry is not loaded."""
mock_broadcast_config_entry.add_to_hass(hass)
result = await hass.config_entries.subentries.async_init(
(mock_broadcast_config_entry.entry_id, SUBENTRY_TYPE_ALLOWED_CHAT_IDS),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "entry_not_loaded"
assert result["description_placeholders"] == {"telegram_bot": "Mock Title"}
async def test_subentry_flow_chat_error(
hass: HomeAssistant, mock_broadcast_config_entry: MockConfigEntry
) -> None:
"""Test subentry flow."""
mock_broadcast_config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_me",
return_value=User(123456, "Testbot", True),
):
assert await hass.config_entries.async_setup(
mock_broadcast_config_entry.entry_id
)
await hass.async_block_till_done()
result = await hass.config_entries.subentries.async_init(
(mock_broadcast_config_entry.entry_id, SUBENTRY_TYPE_ALLOWED_CHAT_IDS),
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
# test: chat not found
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_chat"
) as mock_bot:
mock_bot.side_effect = BadRequest("mock chat not found")
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
user_input={CONF_CHAT_ID: 1234567890},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"]["base"] == "chat_not_found"
# test: chat id already configured
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_chat",
return_value=ChatFullInfo(
id=123456,
title="mock title",
first_name="mock first_name",
type="PRIVATE",
max_reaction_count=100,
accent_color_id=AccentColor.COLOR_000,
accepted_gift_types=AcceptedGiftTypes(True, True, True, True),
),
):
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
user_input={CONF_CHAT_ID: 123456},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_duplicate_entry(hass: HomeAssistant) -> None:
"""Test user flow with duplicated entries."""
data = {
CONF_PLATFORM: PLATFORM_BROADCAST,
CONF_API_KEY: "mock api key",
SECTION_ADVANCED_SETTINGS: {
CONF_API_ENDPOINT: "http://mock_api_endpoint",
},
}
with patch(
"homeassistant.components.telegram_bot.config_flow.Bot.get_me",
return_value=User(123456, "Testbot", True),
):
# test: import first entry success
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=data,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"][CONF_PLATFORM] == PLATFORM_BROADCAST
assert result["data"][CONF_API_KEY] == "mock api key"
assert result["data"][CONF_API_ENDPOINT] == "http://mock_api_endpoint"
assert result["options"][ATTR_PARSER] == PARSER_MD
# test: import 2nd entry failed due to duplicate
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data=data,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/telegram_bot/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 496,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/telegram_bot/test_webhooks.py | """Tests for webhooks."""
from ipaddress import IPv4Network
from unittest.mock import patch
from telegram.error import TimedOut
from homeassistant.components.telegram_bot.const import DOMAIN
from homeassistant.components.telegram_bot.webhooks import TELEGRAM_WEBHOOK_URL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.typing import ClientSessionGenerator
async def test_set_webhooks_failed(
hass: HomeAssistant,
mock_webhooks_config_entry: MockConfigEntry,
mock_external_calls: None,
mock_register_webhook: None,
) -> None:
"""Test set webhooks failed."""
mock_webhooks_config_entry.add_to_hass(hass)
with (
patch(
"homeassistant.components.telegram_bot.webhooks.secrets.choice",
return_value="DEADBEEF12345678DEADBEEF87654321",
),
patch(
"homeassistant.components.telegram_bot.webhooks.Bot.set_webhook",
) as mock_set_webhook,
):
mock_set_webhook.side_effect = [TimedOut("mock timeout"), False]
await hass.config_entries.async_setup(mock_webhooks_config_entry.entry_id)
await hass.async_block_till_done()
await hass.async_stop()
# first fail with exception, second fail with False
assert mock_set_webhook.call_count == 2
# SETUP_ERROR is result of RuntimeError("Failed to register webhook with Telegram") in webhooks.py
assert mock_webhooks_config_entry.state is ConfigEntryState.SETUP_ERROR
# test fail after retries
mock_set_webhook.reset_mock()
mock_set_webhook.side_effect = TimedOut("mock timeout")
await hass.config_entries.async_reload(mock_webhooks_config_entry.entry_id)
await hass.async_block_till_done()
# 3 retries
assert mock_set_webhook.call_count == 3
assert mock_webhooks_config_entry.state is ConfigEntryState.SETUP_ERROR
await hass.async_block_till_done()
async def test_set_webhooks(
hass: HomeAssistant,
mock_webhooks_config_entry: MockConfigEntry,
mock_external_calls: None,
mock_register_webhook: None,
mock_generate_secret_token,
) -> None:
"""Test set webhooks success."""
mock_webhooks_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_webhooks_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_webhooks_config_entry.state is ConfigEntryState.LOADED
async def test_webhooks_update_invalid_json(
hass: HomeAssistant,
webhook_bot,
hass_client: ClientSessionGenerator,
mock_generate_secret_token,
) -> None:
"""Test update with invalid json."""
client = await hass_client()
response = await client.post(
f"{TELEGRAM_WEBHOOK_URL}_123456",
headers={"X-Telegram-Bot-Api-Secret-Token": mock_generate_secret_token},
)
assert response.status == 400
await hass.async_block_till_done()
async def test_webhooks_unauthorized_network(
hass: HomeAssistant,
webhook_bot,
mock_generate_secret_token,
hass_client: ClientSessionGenerator,
) -> None:
"""Test update with request outside of trusted networks."""
client = await hass_client()
with patch(
"homeassistant.components.telegram_bot.webhooks.ip_address",
return_value=IPv4Network("1.2.3.4"),
) as mock_remote:
response = await client.post(
f"{TELEGRAM_WEBHOOK_URL}_123456",
json="mock json",
headers={"X-Telegram-Bot-Api-Secret-Token": mock_generate_secret_token},
)
assert response.status == 401
await hass.async_block_till_done()
mock_remote.assert_called_once()
async def test_webhooks_deregister_failed(
hass: HomeAssistant,
webhook_bot,
) -> None:
"""Test deregister webhooks."""
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
assert config_entry.state is ConfigEntryState.LOADED
with patch(
"homeassistant.components.telegram_bot.webhooks.Bot.delete_webhook",
) as mock_delete_webhook:
mock_delete_webhook.side_effect = TimedOut("mock timeout")
await hass.config_entries.async_unload(config_entry.entry_id)
mock_delete_webhook.assert_called_once()
assert config_entry.state is ConfigEntryState.NOT_LOADED
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/telegram_bot/test_webhooks.py",
"license": "Apache License 2.0",
"lines": 104,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tilt_pi/test_config_flow.py | """Test the Tilt config flow."""
from unittest.mock import AsyncMock
from homeassistant.components.tilt_pi.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_async_step_user_gets_form_and_creates_entry(
hass: HomeAssistant,
mock_tiltpi_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test that the we can view the form and that the config flow creates an entry."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "http://192.168.1.123:1880"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_HOST: "192.168.1.123",
CONF_PORT: 1880,
}
async def test_abort_if_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test that we abort if we attempt to submit the same entry twice."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "http://192.168.1.123:1880"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_successful_recovery_after_invalid_host(
hass: HomeAssistant,
mock_tiltpi_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test error shown when user submits invalid host."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
# Simulate a invalid host error by providing an invalid URL
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "not-a-valid-url"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"url": "invalid_host"}
# Demonstrate successful connection on retry
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "http://192.168.1.123:1880"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_HOST: "192.168.1.123",
CONF_PORT: 1880,
}
async def test_successful_recovery_after_connection_error(
hass: HomeAssistant,
mock_tiltpi_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test error shown when connection fails."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
# Simulate a connection error by raising a TimeoutError
mock_tiltpi_client.get_hydrometers.side_effect = TimeoutError()
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "http://192.168.1.123:1880"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
# Simulate successful connection on retry
mock_tiltpi_client.get_hydrometers.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: "http://192.168.1.123:1880"},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_HOST: "192.168.1.123",
CONF_PORT: 1880,
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tilt_pi/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 105,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tilt_pi/test_sensor.py | """Test the Tilt Hydrometer sensors."""
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from syrupy.assertion import SnapshotAssertion
from tiltpi import TiltColor, TiltPiConnectionError
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
async def test_all_sensors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_tiltpi_client: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the Tilt Pi sensors.
When making changes to this test, ensure that the snapshot reflects the
new data by generating it via:
$ pytest tests/components/tilt_pi/test_sensor.py -v --snapshot-update
"""
with patch("homeassistant.components.tilt_pi.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_availability(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_tiltpi_client: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that entities become unavailable when the coordinator fails."""
with patch("homeassistant.components.tilt_pi.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
# Simulate a coordinator update failure
mock_tiltpi_client.get_hydrometers.side_effect = TiltPiConnectionError()
freezer.tick(60)
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Check that entities are unavailable
for color in (TiltColor.BLACK, TiltColor.YELLOW):
temperature_entity_id = f"sensor.tilt_{color}_temperature"
gravity_entity_id = f"sensor.tilt_{color}_gravity"
temperature_state = hass.states.get(temperature_entity_id)
assert temperature_state is not None
assert temperature_state.state == STATE_UNAVAILABLE
gravity_state = hass.states.get(gravity_entity_id)
assert gravity_state is not None
assert gravity_state.state == STATE_UNAVAILABLE
# Simulate a coordinator update success
mock_tiltpi_client.get_hydrometers.side_effect = None
freezer.tick(60)
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Check that entities are now available
for color in (TiltColor.BLACK, TiltColor.YELLOW):
temperature_entity_id = f"sensor.tilt_{color}_temperature"
gravity_entity_id = f"sensor.tilt_{color}_gravity"
temperature_state = hass.states.get(temperature_entity_id)
assert temperature_state is not None
assert temperature_state.state != STATE_UNAVAILABLE
gravity_state = hass.states.get(gravity_entity_id)
assert gravity_state is not None
assert gravity_state.state != STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tilt_pi/test_sensor.py",
"license": "Apache License 2.0",
"lines": 64,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/vegehub/test_config_flow.py | """Tests for VegeHub config flow."""
from collections.abc import Generator
from ipaddress import ip_address
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from homeassistant import config_entries
from homeassistant.components.vegehub.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.const import (
CONF_DEVICE,
CONF_HOST,
CONF_IP_ADDRESS,
CONF_MAC,
CONF_WEBHOOK_ID,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import (
ATTR_PROPERTIES_ID,
ZeroconfServiceInfo,
)
from .conftest import TEST_HOSTNAME, TEST_IP, TEST_SIMPLE_MAC
from tests.common import MockConfigEntry
DISCOVERY_INFO = ZeroconfServiceInfo(
ip_address=ip_address(TEST_IP),
ip_addresses=[ip_address(TEST_IP)],
port=80,
hostname=f"{TEST_HOSTNAME}.local.",
type="mock_type",
name="myVege",
properties={
ATTR_PROPERTIES_ID: TEST_HOSTNAME,
"version": "5.1.1",
},
)
@pytest.fixture(autouse=True)
def mock_setup_entry() -> Generator[Any]:
"""Prevent the actual integration from being set up."""
with (
patch("homeassistant.components.vegehub.async_setup_entry", return_value=True),
):
yield
# Tests for flows where the user manually inputs an IP address
async def test_user_flow_success(hass: HomeAssistant) -> None:
"""Test the user flow with successful configuration."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: TEST_IP}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == TEST_IP
assert result["data"][CONF_MAC] == TEST_SIMPLE_MAC
assert result["data"][CONF_IP_ADDRESS] == TEST_IP
assert result["data"][CONF_DEVICE] is not None
assert result["data"][CONF_WEBHOOK_ID] is not None
# Since this is user flow, there is no hostname, so hostname should be the IP address
assert result["data"][CONF_HOST] == TEST_IP
assert result["result"].unique_id == TEST_SIMPLE_MAC
# Confirm that the entry was created
entries = hass.config_entries.async_entries(domain=DOMAIN)
assert len(entries) == 1
async def test_user_flow_cannot_connect(
hass: HomeAssistant,
mock_vegehub: MagicMock,
) -> None:
"""Test the user flow with bad data."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
mock_vegehub.mac_address = ""
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: TEST_IP}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "cannot_connect"
mock_vegehub.mac_address = TEST_SIMPLE_MAC
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: TEST_IP}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(TimeoutError, "timeout_connect"),
(ConnectionError, "cannot_connect"),
],
)
async def test_user_flow_device_bad_connection_then_success(
hass: HomeAssistant,
mock_vegehub: MagicMock,
side_effect: Exception,
expected_error: str,
) -> None:
"""Test the user flow with a timeout."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
mock_vegehub.setup.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: TEST_IP}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert "errors" in result
assert result["errors"] == {"base": expected_error}
mock_vegehub.setup.side_effect = None # Clear the error
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: TEST_IP}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == TEST_IP
assert result["data"][CONF_IP_ADDRESS] == TEST_IP
assert result["data"][CONF_MAC] == TEST_SIMPLE_MAC
async def test_user_flow_no_ip_entered(hass: HomeAssistant) -> None:
"""Test the user flow with blank IP."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: ""}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "invalid_ip"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: TEST_IP}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_user_flow_bad_ip_entered(hass: HomeAssistant) -> None:
"""Test the user flow with badly formed IP."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: "192.168.0"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == "invalid_ip"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: TEST_IP}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_user_flow_duplicate_device(
hass: HomeAssistant, mocked_config_entry: MockConfigEntry
) -> None:
"""Test when user flow gets the same device twice."""
mocked_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_IP_ADDRESS: TEST_IP}
)
assert result["type"] is FlowResultType.ABORT
# Tests for flows that start in zeroconf
async def test_zeroconf_flow_success(hass: HomeAssistant) -> None:
"""Test the zeroconf discovery flow with successful configuration."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_confirm"
# Display the confirmation form
result = await hass.config_entries.flow.async_configure(result["flow_id"], None)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_confirm"
# Proceed to creating the entry
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == TEST_HOSTNAME
assert result["data"][CONF_HOST] == TEST_HOSTNAME
assert result["data"][CONF_MAC] == TEST_SIMPLE_MAC
assert result["result"].unique_id == TEST_SIMPLE_MAC
async def test_zeroconf_flow_abort_device_asleep(
hass: HomeAssistant,
mock_vegehub: MagicMock,
) -> None:
"""Test when zeroconf tries to contact a device that is asleep."""
mock_vegehub.retrieve_mac_address.side_effect = TimeoutError
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "timeout_connect"
async def test_zeroconf_flow_abort_same_id(
hass: HomeAssistant,
mocked_config_entry: MockConfigEntry,
) -> None:
"""Test when zeroconf gets the same device twice."""
mocked_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO
)
assert result["type"] is FlowResultType.ABORT
async def test_zeroconf_flow_abort_cannot_connect(
hass: HomeAssistant,
mock_vegehub: MagicMock,
) -> None:
"""Test when zeroconf gets bad data."""
mock_vegehub.mac_address = ""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_zeroconf_flow_abort_cannot_connect_404(
hass: HomeAssistant,
mock_vegehub: MagicMock,
) -> None:
"""Test when zeroconf gets bad responses."""
mock_vegehub.retrieve_mac_address.side_effect = ConnectionError
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(TimeoutError, "timeout_connect"),
(ConnectionError, "cannot_connect"),
],
)
async def test_zeroconf_flow_device_error_response(
hass: HomeAssistant,
mock_vegehub: MagicMock,
side_effect: Exception,
expected_error: str,
) -> None:
"""Test when zeroconf detects the device, but the communication fails at setup."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=DISCOVERY_INFO
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "zeroconf_confirm"
# Part way through the process, we simulate getting bad responses
mock_vegehub.setup.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == expected_error
mock_vegehub.setup.side_effect = None
# Proceed to creating the entry
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_zeroconf_flow_update_ip_hostname(
hass: HomeAssistant,
mocked_config_entry: MockConfigEntry,
) -> None:
"""Test when zeroconf gets the same device with a new IP and hostname."""
mocked_config_entry.add_to_hass(hass)
# Use the same discovery info, but change the IP and hostname
new_ip = "192.168.0.99"
new_hostname = "new_hostname"
new_discovery_info = ZeroconfServiceInfo(
ip_address=ip_address(new_ip),
ip_addresses=[ip_address(new_ip)],
port=DISCOVERY_INFO.port,
hostname=f"{new_hostname}.local.",
type=DISCOVERY_INFO.type,
name=DISCOVERY_INFO.name,
properties=DISCOVERY_INFO.properties,
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=new_discovery_info,
)
assert result["type"] is FlowResultType.ABORT
# Check if the original config entry has been updated
entries = hass.config_entries.async_entries(domain=DOMAIN)
assert len(entries) == 1
assert mocked_config_entry.data[CONF_IP_ADDRESS] == new_ip
assert mocked_config_entry.data[CONF_HOST] == new_hostname
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/vegehub/test_config_flow.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/vegehub/test_sensor.py | """Unit tests for the VegeHub integration's sensor.py."""
from unittest.mock import patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import init_integration
from .conftest import TEST_SIMPLE_MAC, TEST_WEBHOOK_ID
from tests.common import MockConfigEntry, snapshot_platform
from tests.typing import ClientSessionGenerator
UPDATE_DATA = {
"api_key": "",
"mac": TEST_SIMPLE_MAC,
"error_code": 0,
"sensors": [
{"slot": 1, "samples": [{"v": 1.5, "t": "2025-01-15T16:51:23Z"}]},
{"slot": 2, "samples": [{"v": 1.45599997, "t": "2025-01-15T16:51:23Z"}]},
{"slot": 3, "samples": [{"v": 1.330000043, "t": "2025-01-15T16:51:23Z"}]},
{"slot": 4, "samples": [{"v": 0.075999998, "t": "2025-01-15T16:51:23Z"}]},
{"slot": 5, "samples": [{"v": 9.314800262, "t": "2025-01-15T16:51:23Z"}]},
],
"send_time": 1736959883,
"wifi_str": -27,
}
async def test_sensor_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
hass_client_no_auth: ClientSessionGenerator,
entity_registry: er.EntityRegistry,
mocked_config_entry: MockConfigEntry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.vegehub.PLATFORMS", [Platform.SENSOR]):
await init_integration(hass, mocked_config_entry)
assert TEST_WEBHOOK_ID in hass.data["webhook"], "Webhook was not registered"
# Verify the webhook handler
webhook_info = hass.data["webhook"][TEST_WEBHOOK_ID]
assert webhook_info["handler"], "Webhook handler is not set"
client = await hass_client_no_auth()
resp = await client.post(f"/api/webhook/{TEST_WEBHOOK_ID}", json=UPDATE_DATA)
# Send the same update again so that the coordinator modifies existing data
# instead of creating new data.
resp = await client.post(f"/api/webhook/{TEST_WEBHOOK_ID}", json=UPDATE_DATA)
# Wait for remaining tasks to complete.
await hass.async_block_till_done()
assert resp.status == 200, f"Unexpected status code: {resp.status}"
await snapshot_platform(
hass, entity_registry, snapshot, mocked_config_entry.entry_id
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/vegehub/test_sensor.py",
"license": "Apache License 2.0",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/xiaomi_miio/test_fan.py | """The tests for the xiaomi_miio fan component."""
from collections.abc import Generator
from unittest.mock import MagicMock, Mock, patch
from miio.integrations.fan.dmaker.fan import FanStatusP5
from miio.integrations.fan.dmaker.fan_miot import FanStatusMiot
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.xiaomi_miio import MODEL_TO_CLASS_MAP
from homeassistant.components.xiaomi_miio.const import CONF_FLOW_TYPE, DOMAIN
from homeassistant.const import (
CONF_DEVICE,
CONF_HOST,
CONF_MAC,
CONF_MODEL,
CONF_TOKEN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import TEST_MAC
from tests.common import MockConfigEntry, snapshot_platform
_MODEL_INFORMATION = {
"dmaker.fan.p5": {
"patch_class": "homeassistant.components.xiaomi_miio.FanP5",
"mock_status": FanStatusP5(
{
"roll_angle": 60,
"beep_sound": False,
"child_lock": False,
"time_off": 0,
"power": False,
"light": True,
"mode": "nature",
"roll_enable": False,
"speed": 64,
}
),
},
"dmaker.fan.p18": {
"patch_class": "homeassistant.components.xiaomi_miio.FanMiot",
"mock_status": FanStatusMiot(
{
"swing_mode_angle": 90,
"buzzer": False,
"child_lock": False,
"power_off_time": 0,
"power": False,
"light": True,
"mode": 0,
"swing_mode": False,
"fan_speed": 100,
}
),
},
}
@pytest.fixture(
name="model_code",
params=_MODEL_INFORMATION.keys(),
)
def get_model_code(request: pytest.FixtureRequest) -> str:
"""Parametrize model code."""
return request.param
@pytest.fixture(autouse=True)
def setup_device(model_code: str) -> Generator[MagicMock]:
"""Initialize test xiaomi_miio for fan entity."""
model_information = _MODEL_INFORMATION[model_code]
mock_fan = MagicMock()
mock_fan.status = Mock(return_value=model_information["mock_status"])
with (
patch(
"homeassistant.components.xiaomi_miio.get_platforms",
return_value=[Platform.FAN],
),
patch(model_information["patch_class"]) as mock_fan_cls,
patch.dict(
MODEL_TO_CLASS_MAP,
{model_code: mock_fan_cls} if model_code in MODEL_TO_CLASS_MAP else {},
),
):
mock_fan_cls.return_value = mock_fan
yield mock_fan
async def setup_component(
hass: HomeAssistant, model_code: str, entry_title: str
) -> MockConfigEntry:
"""Set up fan component."""
config_entry = MockConfigEntry(
domain=DOMAIN,
unique_id="123456",
title=entry_title,
data={
CONF_FLOW_TYPE: CONF_DEVICE,
CONF_HOST: "192.168.1.100",
CONF_TOKEN: "12345678901234567890123456789012",
CONF_MODEL: model_code,
CONF_MAC: TEST_MAC,
},
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
return config_entry
async def test_fan_status(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
model_code: str,
snapshot: SnapshotAssertion,
) -> None:
"""Test fan status."""
config_entry = await setup_component(hass, model_code, "test_fan")
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/xiaomi_miio/test_fan.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/switchbot_cloud/test_binary_sensor.py | """Test for the switchbot_cloud binary sensors."""
from unittest.mock import patch
import pytest
from switchbot_api import Device
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switchbot_cloud.const import DOMAIN
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import (
CONTACT_SENSOR_INFO,
HUB3_INFO,
MOTION_SENSOR_INFO,
WATER_DETECTOR_INFO,
configure_integration,
)
from tests.common import async_load_json_array_fixture, snapshot_platform
async def test_unsupported_device_type(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_list_devices,
mock_get_status,
) -> None:
"""Test that unsupported device types do not create sensors."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="unsupported-id-1",
deviceName="unsupported-device",
deviceType="UnsupportedDevice",
hubDeviceId="test-hub-id",
),
]
mock_get_status.return_value = {}
with patch(
"homeassistant.components.switchbot_cloud.PLATFORMS", [Platform.BINARY_SENSOR]
):
entry = await configure_integration(hass)
# Assert no binary sensor entities were created for unsupported device type
entities = er.async_entries_for_config_entry(entity_registry, entry.entry_id)
assert len([e for e in entities if e.domain == "binary_sensor"]) == 0
@pytest.mark.parametrize(
("device_info", "index"),
[
(CONTACT_SENSOR_INFO, 0),
(CONTACT_SENSOR_INFO, 2),
(HUB3_INFO, 3),
(MOTION_SENSOR_INFO, 4),
(WATER_DETECTOR_INFO, 5),
],
)
async def test_binary_sensors(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_list_devices,
mock_get_status,
device_info: Device,
index: int,
) -> None:
"""Test binary sensors."""
mock_list_devices.return_value = [device_info]
json_data = await async_load_json_array_fixture(hass, "status.json", DOMAIN)
mock_get_status.return_value = json_data[index]
with patch(
"homeassistant.components.switchbot_cloud.PLATFORMS", [Platform.BINARY_SENSOR]
):
entry = await configure_integration(hass)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/switchbot_cloud/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/alexa_devices/binary_sensor.py | """Support for binary sensors."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from typing import Final
from aioamazondevices.const.metadata import SENSOR_STATE_OFF
from aioamazondevices.structures import AmazonDevice
from homeassistant.components.binary_sensor import (
DOMAIN as BINARY_SENSOR_DOMAIN,
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
import homeassistant.helpers.entity_registry as er
from .const import _LOGGER, DOMAIN
from .coordinator import AmazonConfigEntry
from .entity import AmazonEntity
from .utils import async_update_unique_id
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class AmazonBinarySensorEntityDescription(BinarySensorEntityDescription):
"""Alexa Devices binary sensor entity description."""
is_on_fn: Callable[[AmazonDevice, str], bool]
is_supported: Callable[[AmazonDevice, str], bool] = lambda device, key: True
is_available_fn: Callable[[AmazonDevice, str], bool] = lambda device, key: True
BINARY_SENSORS: Final = (
AmazonBinarySensorEntityDescription(
key="online",
device_class=BinarySensorDeviceClass.CONNECTIVITY,
entity_category=EntityCategory.DIAGNOSTIC,
is_on_fn=lambda device, _: device.online,
),
AmazonBinarySensorEntityDescription(
key="detectionState",
device_class=BinarySensorDeviceClass.MOTION,
is_on_fn=lambda device, key: bool(
device.sensors[key].value != SENSOR_STATE_OFF
),
is_supported=lambda device, key: device.sensors.get(key) is not None,
is_available_fn=lambda device, key: (
device.online
and (sensor := device.sensors.get(key)) is not None
and sensor.error is False
),
),
)
DEPRECATED_BINARY_SENSORS: Final = (
AmazonBinarySensorEntityDescription(
key="bluetooth",
entity_category=EntityCategory.DIAGNOSTIC,
translation_key="bluetooth",
is_on_fn=lambda device, key: False,
),
AmazonBinarySensorEntityDescription(
key="babyCryDetectionState",
translation_key="baby_cry_detection",
is_on_fn=lambda device, key: False,
),
AmazonBinarySensorEntityDescription(
key="beepingApplianceDetectionState",
translation_key="beeping_appliance_detection",
is_on_fn=lambda device, key: False,
),
AmazonBinarySensorEntityDescription(
key="coughDetectionState",
translation_key="cough_detection",
is_on_fn=lambda device, key: False,
),
AmazonBinarySensorEntityDescription(
key="dogBarkDetectionState",
translation_key="dog_bark_detection",
is_on_fn=lambda device, key: False,
),
AmazonBinarySensorEntityDescription(
key="waterSoundsDetectionState",
translation_key="water_sounds_detection",
is_on_fn=lambda device, key: False,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: AmazonConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Alexa Devices binary sensors based on a config entry."""
coordinator = entry.runtime_data
entity_registry = er.async_get(hass)
# Replace unique id for "detectionState" binary sensor
await async_update_unique_id(
hass,
coordinator,
BINARY_SENSOR_DOMAIN,
"humanPresenceDetectionState",
"detectionState",
)
# Clean up deprecated sensors
for sensor_desc in DEPRECATED_BINARY_SENSORS:
for serial_num in coordinator.data:
unique_id = f"{serial_num}-{sensor_desc.key}"
if entity_id := entity_registry.async_get_entity_id(
BINARY_SENSOR_DOMAIN, DOMAIN, unique_id
):
_LOGGER.debug("Removing deprecated entity %s", entity_id)
entity_registry.async_remove(entity_id)
known_devices: set[str] = set()
def _check_device() -> None:
current_devices = set(coordinator.data)
new_devices = current_devices - known_devices
if new_devices:
known_devices.update(new_devices)
async_add_entities(
AmazonBinarySensorEntity(coordinator, serial_num, sensor_desc)
for sensor_desc in BINARY_SENSORS
for serial_num in new_devices
if sensor_desc.is_supported(
coordinator.data[serial_num], sensor_desc.key
)
)
_check_device()
entry.async_on_unload(coordinator.async_add_listener(_check_device))
class AmazonBinarySensorEntity(AmazonEntity, BinarySensorEntity):
"""Binary sensor device."""
entity_description: AmazonBinarySensorEntityDescription
@property
def is_on(self) -> bool:
"""Return True if the binary sensor is on."""
return self.entity_description.is_on_fn(
self.device, self.entity_description.key
)
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
self.entity_description.is_available_fn(
self.device, self.entity_description.key
)
and super().available
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 142,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/alexa_devices/config_flow.py | """Config flow for Alexa Devices integration."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from aioamazondevices.api import AmazonEchoApi
from aioamazondevices.exceptions import (
CannotAuthenticate,
CannotConnect,
CannotRetrieveData,
)
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_CODE, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers import aiohttp_client
import homeassistant.helpers.config_validation as cv
from .const import CONF_LOGIN_DATA, DOMAIN
STEP_REAUTH_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_CODE): cv.string,
}
)
STEP_RECONFIGURE = vol.Schema(
{
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_CODE): cv.string,
}
)
async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, Any]:
"""Validate the user input allows us to connect."""
session = aiohttp_client.async_create_clientsession(hass)
api = AmazonEchoApi(
session,
data[CONF_USERNAME],
data[CONF_PASSWORD],
)
return await api.login.login_mode_interactive(data[CONF_CODE])
class AmazonDevicesConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Alexa Devices."""
VERSION = 1
MINOR_VERSION = 3
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors = {}
if user_input:
try:
data = await validate_input(self.hass, user_input)
except CannotConnect:
errors["base"] = "cannot_connect"
except CannotAuthenticate:
errors["base"] = "invalid_auth"
except CannotRetrieveData:
errors["base"] = "cannot_retrieve_data"
else:
await self.async_set_unique_id(data["customer_info"]["user_id"])
self._abort_if_unique_id_configured()
user_input.pop(CONF_CODE)
return self.async_create_entry(
title=user_input[CONF_USERNAME],
data=user_input | {CONF_LOGIN_DATA: data},
)
return self.async_show_form(
step_id="user",
errors=errors,
data_schema=vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_CODE): cv.string,
}
),
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Handle reauth flow."""
self.context["title_placeholders"] = {CONF_USERNAME: entry_data[CONF_USERNAME]}
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reauth confirm."""
errors: dict[str, str] = {}
reauth_entry = self._get_reauth_entry()
entry_data = reauth_entry.data
if user_input is not None:
try:
data = await validate_input(
self.hass, {**reauth_entry.data, **user_input}
)
except CannotConnect:
errors["base"] = "cannot_connect"
except CannotAuthenticate:
errors["base"] = "invalid_auth"
except CannotRetrieveData:
errors["base"] = "cannot_retrieve_data"
else:
return self.async_update_reload_and_abort(
reauth_entry,
data={
CONF_USERNAME: entry_data[CONF_USERNAME],
CONF_PASSWORD: user_input[CONF_PASSWORD],
CONF_CODE: user_input[CONF_CODE],
CONF_LOGIN_DATA: data,
},
)
return self.async_show_form(
step_id="reauth_confirm",
description_placeholders={CONF_USERNAME: entry_data[CONF_USERNAME]},
data_schema=STEP_REAUTH_DATA_SCHEMA,
errors=errors,
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reconfiguration of the device."""
reconfigure_entry = self._get_reconfigure_entry()
if not user_input:
return self.async_show_form(
step_id="reconfigure",
data_schema=STEP_RECONFIGURE,
)
updated_password = user_input[CONF_PASSWORD]
self._async_abort_entries_match(
{CONF_USERNAME: reconfigure_entry.data[CONF_USERNAME]}
)
errors: dict[str, str] = {}
try:
data = await validate_input(
self.hass, {**reconfigure_entry.data, **user_input}
)
except CannotConnect:
errors["base"] = "cannot_connect"
except CannotAuthenticate:
errors["base"] = "invalid_auth"
except CannotRetrieveData:
errors["base"] = "cannot_retrieve_data"
else:
return self.async_update_reload_and_abort(
reconfigure_entry,
data_updates={
CONF_PASSWORD: updated_password,
CONF_LOGIN_DATA: data,
},
)
return self.async_show_form(
step_id="reconfigure",
data_schema=STEP_RECONFIGURE,
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/config_flow.py",
"license": "Apache License 2.0",
"lines": 153,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/alexa_devices/const.py | """Alexa Devices constants."""
import logging
_LOGGER = logging.getLogger(__package__)
DOMAIN = "alexa_devices"
CONF_LOGIN_DATA = "login_data"
CONF_SITE = "site"
DEFAULT_DOMAIN = "com"
COUNTRY_DOMAINS = {
"ar": DEFAULT_DOMAIN,
"at": DEFAULT_DOMAIN,
"au": "com.au",
"be": "com.be",
"br": DEFAULT_DOMAIN,
"gb": "co.uk",
"il": DEFAULT_DOMAIN,
"jp": "co.jp",
"mx": "com.mx",
"no": DEFAULT_DOMAIN,
"nz": "com.au",
"pl": DEFAULT_DOMAIN,
"tr": "com.tr",
"us": DEFAULT_DOMAIN,
"za": "co.za",
}
CATEGORY_SENSORS = "sensors"
CATEGORY_NOTIFICATIONS = "notifications"
# Map service translation keys to Alexa API
INFO_SKILLS_MAPPING = {
"calendar_today": "Alexa.Calendar.PlayToday",
"calendar_tomorrow": "Alexa.Calendar.PlayTomorrow",
"calendar_next": "Alexa.Calendar.PlayNext",
"date": "Alexa.Date.Play",
"time": "Alexa.Time.Play",
"national_news": "Alexa.News.NationalNews",
"flash_briefing": "Alexa.FlashBriefing.Play",
"traffic": "Alexa.Traffic.Play",
"weather": "Alexa.Weather.Play",
"cleanup": "Alexa.CleanUp.Play",
"good_morning": "Alexa.GoodMorning.Play",
"sing_song": "Alexa.SingASong.Play",
"fun_fact": "Alexa.FunFact.Play",
"tell_joke": "Alexa.Joke.Play",
"tell_story": "Alexa.TellStory.Play",
"im_home": "Alexa.ImHome.Play",
"goodnight": "Alexa.GoodNight.Play",
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/const.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/alexa_devices/coordinator.py | """Support for Alexa Devices."""
from datetime import timedelta
from aioamazondevices.api import AmazonEchoApi
from aioamazondevices.exceptions import (
CannotAuthenticate,
CannotConnect,
CannotRetrieveData,
)
from aioamazondevices.structures import AmazonDevice
from aiohttp import ClientSession
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.debounce import Debouncer
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import _LOGGER, CONF_LOGIN_DATA, DOMAIN
SCAN_INTERVAL = 300
type AmazonConfigEntry = ConfigEntry[AmazonDevicesCoordinator]
class AmazonDevicesCoordinator(DataUpdateCoordinator[dict[str, AmazonDevice]]):
"""Base coordinator for Alexa Devices."""
config_entry: AmazonConfigEntry
def __init__(
self,
hass: HomeAssistant,
entry: AmazonConfigEntry,
session: ClientSession,
) -> None:
"""Initialize the scanner."""
super().__init__(
hass,
_LOGGER,
name=entry.title,
config_entry=entry,
update_interval=timedelta(seconds=SCAN_INTERVAL),
request_refresh_debouncer=Debouncer(
hass, _LOGGER, cooldown=SCAN_INTERVAL, immediate=False
),
)
self.api = AmazonEchoApi(
session,
entry.data[CONF_USERNAME],
entry.data[CONF_PASSWORD],
entry.data[CONF_LOGIN_DATA],
)
self.previous_devices: set[str] = set()
async def _async_update_data(self) -> dict[str, AmazonDevice]:
"""Update device data."""
try:
await self.api.login.login_mode_stored_data()
data = await self.api.get_devices_data()
except CannotConnect as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="cannot_connect_with_error",
translation_placeholders={"error": repr(err)},
) from err
except CannotRetrieveData as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="cannot_retrieve_data_with_error",
translation_placeholders={"error": repr(err)},
) from err
except CannotAuthenticate as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="invalid_auth",
translation_placeholders={"error": repr(err)},
) from err
else:
current_devices = set(data.keys())
if stale_devices := self.previous_devices - current_devices:
await self._async_remove_device_stale(stale_devices)
self.previous_devices = current_devices
return data
async def _async_remove_device_stale(
self,
stale_devices: set[str],
) -> None:
"""Remove stale device."""
device_registry = dr.async_get(self.hass)
for serial_num in stale_devices:
_LOGGER.debug(
"Detected change in devices: serial %s removed",
serial_num,
)
device = device_registry.async_get_device(
identifiers={(DOMAIN, serial_num)}
)
if device:
device_registry.async_update_device(
device_id=device.id,
remove_config_entry_id=self.config_entry.entry_id,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/coordinator.py",
"license": "Apache License 2.0",
"lines": 95,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/alexa_devices/diagnostics.py | """Diagnostics support for Alexa Devices integration."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from aioamazondevices.structures import AmazonDevice
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceEntry
from .coordinator import AmazonConfigEntry
TO_REDACT = {CONF_PASSWORD, CONF_USERNAME, CONF_NAME, "title"}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: AmazonConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator = entry.runtime_data
devices: list[dict[str, dict[str, Any]]] = [
build_device_data(device) for device in coordinator.data.values()
]
return {
"entry": async_redact_data(entry.as_dict(), TO_REDACT),
"device_info": {
"last_update success": coordinator.last_update_success,
"last_exception": repr(coordinator.last_exception),
"devices": devices,
},
}
async def async_get_device_diagnostics(
hass: HomeAssistant, entry: AmazonConfigEntry, device_entry: DeviceEntry
) -> dict[str, Any]:
"""Return diagnostics for a device."""
coordinator = entry.runtime_data
assert device_entry.serial_number
return build_device_data(coordinator.data[device_entry.serial_number])
def build_device_data(device: AmazonDevice) -> dict[str, Any]:
"""Build device data for diagnostics."""
return {
"account name": device.account_name,
"capabilities": device.capabilities,
"device family": device.device_family,
"device type": device.device_type,
"device cluster members": device.device_cluster_members,
"online": device.online,
"serial number": device.serial_number,
"software version": device.software_version,
"sensors": {key: asdict(sensor) for key, sensor in device.sensors.items()},
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/diagnostics.py",
"license": "Apache License 2.0",
"lines": 47,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/alexa_devices/entity.py | """Defines a base Alexa Devices entity."""
from aioamazondevices.const.devices import SPEAKER_GROUP_MODEL
from aioamazondevices.structures import AmazonDevice
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import AmazonDevicesCoordinator
class AmazonEntity(CoordinatorEntity[AmazonDevicesCoordinator]):
"""Defines a base Alexa Devices entity."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: AmazonDevicesCoordinator,
serial_num: str,
description: EntityDescription,
) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
self._serial_num = serial_num
model_details = coordinator.api.get_model_details(self.device) or {}
model = model_details.get("model")
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, serial_num)},
name=self.device.account_name,
model=model,
model_id=self.device.device_type,
manufacturer=model_details.get("manufacturer", "Amazon"),
hw_version=model_details.get("hw_version"),
sw_version=(
self.device.software_version if model != SPEAKER_GROUP_MODEL else None
),
serial_number=serial_num if model != SPEAKER_GROUP_MODEL else None,
)
self.entity_description = description
self._attr_unique_id = f"{serial_num}-{description.key}"
@property
def device(self) -> AmazonDevice:
"""Return the device."""
return self.coordinator.data[self._serial_num]
@property
def available(self) -> bool:
"""Return True if entity is available."""
return (
super().available
and self._serial_num in self.coordinator.data
and self.device.online
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/entity.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/alexa_devices/notify.py | """Support for notification entity."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any, Final
from aioamazondevices.api import AmazonEchoApi
from aioamazondevices.const.devices import SPEAKER_GROUP_FAMILY
from aioamazondevices.structures import AmazonDevice
from homeassistant.components.notify import NotifyEntity, NotifyEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import AmazonConfigEntry
from .entity import AmazonEntity
from .utils import alexa_api_call
PARALLEL_UPDATES = 1
@dataclass(frozen=True, kw_only=True)
class AmazonNotifyEntityDescription(NotifyEntityDescription):
"""Alexa Devices notify entity description."""
is_supported: Callable[[AmazonDevice], bool] = lambda _device: True
method: Callable[[AmazonEchoApi, AmazonDevice, str], Awaitable[None]]
subkey: str
NOTIFY: Final = (
AmazonNotifyEntityDescription(
key="speak",
translation_key="speak",
subkey="AUDIO_PLAYER",
is_supported=lambda _device: _device.device_family != SPEAKER_GROUP_FAMILY,
method=lambda api, device, message: api.call_alexa_speak(device, message),
),
AmazonNotifyEntityDescription(
key="announce",
translation_key="announce",
subkey="AUDIO_PLAYER",
method=lambda api, device, message: api.call_alexa_announcement(
device, message
),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: AmazonConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Alexa Devices notification entity based on a config entry."""
coordinator = entry.runtime_data
known_devices: set[str] = set()
def _check_device() -> None:
current_devices = set(coordinator.data)
new_devices = current_devices - known_devices
if new_devices:
known_devices.update(new_devices)
async_add_entities(
AmazonNotifyEntity(coordinator, serial_num, sensor_desc)
for sensor_desc in NOTIFY
for serial_num in new_devices
if sensor_desc.subkey in coordinator.data[serial_num].capabilities
and sensor_desc.is_supported(coordinator.data[serial_num])
)
_check_device()
entry.async_on_unload(coordinator.async_add_listener(_check_device))
class AmazonNotifyEntity(AmazonEntity, NotifyEntity):
"""Binary sensor notify platform."""
entity_description: AmazonNotifyEntityDescription
@alexa_api_call
async def async_send_message(
self, message: str, title: str | None = None, **kwargs: Any
) -> None:
"""Send a message."""
await self.entity_description.method(self.coordinator.api, self.device, message)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/notify.py",
"license": "Apache License 2.0",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/alexa_devices/switch.py | """Support for switches."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Final
from aioamazondevices.structures import AmazonDevice
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SwitchEntity,
SwitchEntityDescription,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import AmazonConfigEntry
from .entity import AmazonEntity
from .utils import (
alexa_api_call,
async_remove_dnd_from_virtual_group,
async_update_unique_id,
)
PARALLEL_UPDATES = 1
@dataclass(frozen=True, kw_only=True)
class AmazonSwitchEntityDescription(SwitchEntityDescription):
"""Alexa Devices switch entity description."""
is_on_fn: Callable[[AmazonDevice], bool]
is_available_fn: Callable[[AmazonDevice, str], bool] = lambda device, key: (
device.online
and (sensor := device.sensors.get(key)) is not None
and sensor.error is False
)
method: str
SWITCHES: Final = (
AmazonSwitchEntityDescription(
key="dnd",
translation_key="do_not_disturb",
is_on_fn=lambda device: bool(device.sensors["dnd"].value),
method="set_do_not_disturb",
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: AmazonConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Alexa Devices switches based on a config entry."""
coordinator = entry.runtime_data
# DND keys
old_key = "do_not_disturb"
new_key = "dnd"
# Remove old DND switch from virtual groups
await async_remove_dnd_from_virtual_group(hass, coordinator, old_key)
# Replace unique id for DND switch
await async_update_unique_id(hass, coordinator, SWITCH_DOMAIN, old_key, new_key)
known_devices: set[str] = set()
def _check_device() -> None:
current_devices = set(coordinator.data)
new_devices = current_devices - known_devices
if new_devices:
known_devices.update(new_devices)
async_add_entities(
AmazonSwitchEntity(coordinator, serial_num, switch_desc)
for switch_desc in SWITCHES
for serial_num in new_devices
if switch_desc.key in coordinator.data[serial_num].sensors
)
_check_device()
entry.async_on_unload(coordinator.async_add_listener(_check_device))
class AmazonSwitchEntity(AmazonEntity, SwitchEntity):
"""Switch device."""
entity_description: AmazonSwitchEntityDescription
@alexa_api_call
async def _switch_set_state(self, state: bool) -> None:
"""Set desired switch state."""
method = getattr(self.coordinator.api, self.entity_description.method)
if TYPE_CHECKING:
assert method is not None
await method(self.device, state)
await self.coordinator.async_request_refresh()
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
await self._switch_set_state(True)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
await self._switch_set_state(False)
@property
def is_on(self) -> bool:
"""Return True if switch is on."""
return self.entity_description.is_on_fn(self.device)
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
self.entity_description.is_available_fn(
self.device, self.entity_description.key
)
and super().available
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/alexa_devices/switch.py",
"license": "Apache License 2.0",
"lines": 97,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/backup/event.py | """Event platform for Home Assistant Backup integration."""
from __future__ import annotations
from typing import Final
from homeassistant.components.event import EventEntity
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import BackupConfigEntry, BackupDataUpdateCoordinator
from .entity import BackupManagerBaseEntity
from .manager import CreateBackupEvent, CreateBackupState
ATTR_BACKUP_STAGE: Final[str] = "backup_stage"
ATTR_FAILED_REASON: Final[str] = "failed_reason"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: BackupConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Event set up for backup config entry."""
coordinator = config_entry.runtime_data
async_add_entities([AutomaticBackupEvent(coordinator)])
class AutomaticBackupEvent(BackupManagerBaseEntity, EventEntity):
"""Representation of an automatic backup event."""
_attr_event_types = [s.value for s in CreateBackupState]
_unrecorded_attributes = frozenset({ATTR_FAILED_REASON, ATTR_BACKUP_STAGE})
coordinator: BackupDataUpdateCoordinator
def __init__(self, coordinator: BackupDataUpdateCoordinator) -> None:
"""Initialize the automatic backup event."""
super().__init__(coordinator)
self._attr_unique_id = "automatic_backup_event"
self._attr_translation_key = "automatic_backup_event"
@callback
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
if (
not (data := self.coordinator.data)
or (event := data.last_event) is None
or not isinstance(event, CreateBackupEvent)
):
return
self._trigger_event(
event.state,
{
ATTR_BACKUP_STAGE: event.stage,
ATTR_FAILED_REASON: event.reason,
},
)
self.async_write_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/backup/event.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/blue_current/button.py | """Support for Blue Current buttons."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from typing import Any
from bluecurrent_api.client import Client
from homeassistant.components.button import (
ButtonDeviceClass,
ButtonEntity,
ButtonEntityDescription,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import BlueCurrentConfigEntry, Connector
from .entity import ChargepointEntity
@dataclass(kw_only=True, frozen=True)
class ChargePointButtonEntityDescription(ButtonEntityDescription):
"""Describes a Blue Current button entity."""
function: Callable[[Client, str], Coroutine[Any, Any, None]]
CHARGE_POINT_BUTTONS = (
ChargePointButtonEntityDescription(
key="reset",
translation_key="reset",
function=lambda client, evse_id: client.reset(evse_id),
device_class=ButtonDeviceClass.RESTART,
),
ChargePointButtonEntityDescription(
key="reboot",
translation_key="reboot",
function=lambda client, evse_id: client.reboot(evse_id),
device_class=ButtonDeviceClass.RESTART,
),
ChargePointButtonEntityDescription(
key="stop_charge_session",
translation_key="stop_charge_session",
function=lambda client, evse_id: client.stop_session(evse_id),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: BlueCurrentConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Blue Current buttons."""
connector: Connector = entry.runtime_data
async_add_entities(
ChargePointButton(
connector,
button,
evse_id,
)
for evse_id in connector.charge_points
for button in CHARGE_POINT_BUTTONS
)
class ChargePointButton(ChargepointEntity, ButtonEntity):
"""Define a charge point button."""
has_value = True
entity_description: ChargePointButtonEntityDescription
def __init__(
self,
connector: Connector,
description: ChargePointButtonEntityDescription,
evse_id: str,
) -> None:
"""Initialize the button."""
super().__init__(connector, evse_id)
self.entity_description = description
self._attr_unique_id = f"{description.key}_{evse_id}"
async def async_press(self) -> None:
"""Handle the button press."""
await self.entity_description.function(self.connector.client, self.evse_id)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/blue_current/button.py",
"license": "Apache License 2.0",
"lines": 71,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/bluesound/button.py | """Button entities for Bluesound."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING
from pyblu import Player
from homeassistant.components.button import ButtonEntity, ButtonEntityDescription
from homeassistant.const import CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import (
CONNECTION_NETWORK_MAC,
DeviceInfo,
format_mac,
)
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import BluesoundCoordinator
from .media_player import DEFAULT_PORT
from .utils import format_unique_id
if TYPE_CHECKING:
from . import BluesoundConfigEntry
async def async_setup_entry(
hass: HomeAssistant,
config_entry: BluesoundConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Bluesound entry."""
async_add_entities(
BluesoundButton(
config_entry.runtime_data.coordinator,
config_entry.runtime_data.player,
config_entry.data[CONF_PORT],
description,
)
for description in BUTTON_DESCRIPTIONS
)
@dataclass(kw_only=True, frozen=True)
class BluesoundButtonEntityDescription(ButtonEntityDescription):
"""Description for Bluesound button entities."""
press_fn: Callable[[Player], Awaitable[None]]
async def clear_sleep_timer(player: Player) -> None:
"""Clear the sleep timer."""
sleep = -1
while sleep != 0:
sleep = await player.sleep_timer()
async def set_sleep_timer(player: Player) -> None:
"""Set the sleep timer."""
await player.sleep_timer()
BUTTON_DESCRIPTIONS = [
BluesoundButtonEntityDescription(
key="set_sleep_timer",
translation_key="set_sleep_timer",
entity_registry_enabled_default=False,
press_fn=set_sleep_timer,
),
BluesoundButtonEntityDescription(
key="clear_sleep_timer",
translation_key="clear_sleep_timer",
entity_registry_enabled_default=False,
press_fn=clear_sleep_timer,
),
]
class BluesoundButton(CoordinatorEntity[BluesoundCoordinator], ButtonEntity):
"""Base class for Bluesound buttons."""
_attr_has_entity_name = True
entity_description: BluesoundButtonEntityDescription
def __init__(
self,
coordinator: BluesoundCoordinator,
player: Player,
port: int,
description: BluesoundButtonEntityDescription,
) -> None:
"""Initialize the Bluesound button."""
super().__init__(coordinator)
sync_status = coordinator.data.sync_status
self.entity_description = description
self._player = player
self._attr_unique_id = (
f"{description.key}-{format_unique_id(sync_status.mac, port)}"
)
if port == DEFAULT_PORT:
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, format_mac(sync_status.mac))},
connections={(CONNECTION_NETWORK_MAC, format_mac(sync_status.mac))},
name=sync_status.name,
manufacturer=sync_status.brand,
model=sync_status.model_name,
model_id=sync_status.model,
)
else:
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, format_unique_id(sync_status.mac, port))},
name=sync_status.name,
manufacturer=sync_status.brand,
model=sync_status.model_name,
model_id=sync_status.model,
via_device=(DOMAIN, format_mac(sync_status.mac)),
)
async def async_press(self) -> None:
"""Handle the button press."""
await self.entity_description.press_fn(self._player)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/bluesound/button.py",
"license": "Apache License 2.0",
"lines": 103,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/bosch_alarm/binary_sensor.py | """Support for Bosch Alarm Panel binary sensors."""
from __future__ import annotations
from dataclasses import dataclass
from bosch_alarm_mode2 import Panel
from bosch_alarm_mode2.const import ALARM_PANEL_FAULTS
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import BoschAlarmConfigEntry
from .entity import BoschAlarmAreaEntity, BoschAlarmEntity, BoschAlarmPointEntity
@dataclass(kw_only=True, frozen=True)
class BoschAlarmFaultEntityDescription(BinarySensorEntityDescription):
"""Describes Bosch Alarm sensor entity."""
fault: int
FAULT_TYPES = [
BoschAlarmFaultEntityDescription(
key="panel_fault_battery_low",
entity_registry_enabled_default=True,
device_class=BinarySensorDeviceClass.BATTERY,
fault=ALARM_PANEL_FAULTS.BATTERY_LOW,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_battery_mising",
translation_key="panel_fault_battery_mising",
entity_registry_enabled_default=True,
device_class=BinarySensorDeviceClass.PROBLEM,
fault=ALARM_PANEL_FAULTS.BATTERY_MISING,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_ac_fail",
translation_key="panel_fault_ac_fail",
entity_registry_enabled_default=True,
device_class=BinarySensorDeviceClass.PROBLEM,
fault=ALARM_PANEL_FAULTS.AC_FAIL,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_phone_line_failure",
translation_key="panel_fault_phone_line_failure",
entity_registry_enabled_default=False,
device_class=BinarySensorDeviceClass.CONNECTIVITY,
fault=ALARM_PANEL_FAULTS.PHONE_LINE_FAILURE,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_parameter_crc_fail_in_pif",
translation_key="panel_fault_parameter_crc_fail_in_pif",
entity_registry_enabled_default=False,
device_class=BinarySensorDeviceClass.PROBLEM,
fault=ALARM_PANEL_FAULTS.PARAMETER_CRC_FAIL_IN_PIF,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_communication_fail_since_rps_hang_up",
translation_key="panel_fault_communication_fail_since_rps_hang_up",
entity_registry_enabled_default=False,
device_class=BinarySensorDeviceClass.PROBLEM,
fault=ALARM_PANEL_FAULTS.COMMUNICATION_FAIL_SINCE_RPS_HANG_UP,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_sdi_fail_since_rps_hang_up",
translation_key="panel_fault_sdi_fail_since_rps_hang_up",
entity_registry_enabled_default=False,
device_class=BinarySensorDeviceClass.PROBLEM,
fault=ALARM_PANEL_FAULTS.SDI_FAIL_SINCE_RPS_HANG_UP,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_user_code_tamper_since_rps_hang_up",
translation_key="panel_fault_user_code_tamper_since_rps_hang_up",
entity_registry_enabled_default=False,
device_class=BinarySensorDeviceClass.PROBLEM,
fault=ALARM_PANEL_FAULTS.USER_CODE_TAMPER_SINCE_RPS_HANG_UP,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_fail_to_call_rps_since_rps_hang_up",
translation_key="panel_fault_fail_to_call_rps_since_rps_hang_up",
entity_registry_enabled_default=False,
fault=ALARM_PANEL_FAULTS.FAIL_TO_CALL_RPS_SINCE_RPS_HANG_UP,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_point_bus_fail_since_rps_hang_up",
translation_key="panel_fault_point_bus_fail_since_rps_hang_up",
entity_registry_enabled_default=False,
device_class=BinarySensorDeviceClass.PROBLEM,
fault=ALARM_PANEL_FAULTS.POINT_BUS_FAIL_SINCE_RPS_HANG_UP,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_log_overflow",
translation_key="panel_fault_log_overflow",
entity_registry_enabled_default=False,
device_class=BinarySensorDeviceClass.PROBLEM,
fault=ALARM_PANEL_FAULTS.LOG_OVERFLOW,
),
BoschAlarmFaultEntityDescription(
key="panel_fault_log_threshold",
translation_key="panel_fault_log_threshold",
entity_registry_enabled_default=False,
device_class=BinarySensorDeviceClass.PROBLEM,
fault=ALARM_PANEL_FAULTS.LOG_THRESHOLD,
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: BoschAlarmConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up binary sensors for alarm points and the connection status."""
panel = config_entry.runtime_data
entities: list[BinarySensorEntity] = [
PointSensor(panel, point_id, config_entry.unique_id or config_entry.entry_id)
for point_id in panel.points
]
entities.extend(
PanelFaultsSensor(
panel,
config_entry.unique_id or config_entry.entry_id,
fault_type,
)
for fault_type in FAULT_TYPES
)
entities.extend(
AreaReadyToArmSensor(
panel, area_id, config_entry.unique_id or config_entry.entry_id, "away"
)
for area_id in panel.areas
)
entities.extend(
AreaReadyToArmSensor(
panel, area_id, config_entry.unique_id or config_entry.entry_id, "home"
)
for area_id in panel.areas
)
async_add_entities(entities)
PARALLEL_UPDATES = 0
class PanelFaultsSensor(BoschAlarmEntity, BinarySensorEntity):
"""A binary sensor entity for each fault type in a bosch alarm panel."""
_attr_entity_category = EntityCategory.DIAGNOSTIC
entity_description: BoschAlarmFaultEntityDescription
def __init__(
self,
panel: Panel,
unique_id: str,
entity_description: BoschAlarmFaultEntityDescription,
) -> None:
"""Set up a binary sensor entity for each fault type in a bosch alarm panel."""
super().__init__(panel, unique_id, True)
self.entity_description = entity_description
self._fault_type = entity_description.fault
self._attr_unique_id = f"{unique_id}_fault_{entity_description.key}"
@property
def is_on(self) -> bool:
"""Return if this fault has occurred."""
return self._fault_type in self.panel.panel_faults_ids
class AreaReadyToArmSensor(BoschAlarmAreaEntity, BinarySensorEntity):
"""A binary sensor entity showing if a panel is ready to arm."""
_attr_entity_category = EntityCategory.DIAGNOSTIC
def __init__(
self, panel: Panel, area_id: int, unique_id: str, arm_type: str
) -> None:
"""Set up a binary sensor entity for the arming status in a bosch alarm panel."""
super().__init__(panel, area_id, unique_id, False, False, True)
self.panel = panel
self._arm_type = arm_type
self._attr_translation_key = f"area_ready_to_arm_{arm_type}"
self._attr_unique_id = f"{self._area_unique_id}_ready_to_arm_{arm_type}"
@property
def is_on(self) -> bool:
"""Return if this panel is ready to arm."""
if self._arm_type == "away":
return self._area.all_ready
if self._arm_type == "home":
return self._area.all_ready or self._area.part_ready
return False
class PointSensor(BoschAlarmPointEntity, BinarySensorEntity):
"""A binary sensor entity for a point in a bosch alarm panel."""
_attr_name = None
def __init__(self, panel: Panel, point_id: int, unique_id: str) -> None:
"""Set up a binary sensor entity for a point in a bosch alarm panel."""
super().__init__(panel, point_id, unique_id)
self._attr_unique_id = self._point_unique_id
@property
def is_on(self) -> bool:
"""Return if this point sensor is on."""
return self._point.is_open()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/bosch_alarm/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 186,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/bosch_alarm/services.py | """Services for the bosch_alarm integration."""
from __future__ import annotations
import asyncio
import datetime as dt
from typing import Any
import voluptuous as vol
from homeassistant.const import ATTR_CONFIG_ENTRY_ID
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv, service
from homeassistant.util import dt as dt_util
from .const import ATTR_DATETIME, DOMAIN, SERVICE_SET_DATE_TIME
from .types import BoschAlarmConfigEntry
def validate_datetime(value: Any) -> dt.datetime:
"""Validate that a provided datetime is supported on a bosch alarm panel."""
date_val = cv.datetime(value)
if date_val.year < 2010:
raise vol.RangeInvalid("datetime must be after 2009")
if date_val.year > 2037:
raise vol.RangeInvalid("datetime must be before 2038")
return date_val
SET_DATE_TIME_SCHEMA = vol.Schema(
{
vol.Required(ATTR_CONFIG_ENTRY_ID): cv.string,
vol.Optional(ATTR_DATETIME): validate_datetime,
}
)
async def async_set_panel_date(call: ServiceCall) -> None:
"""Set the date and time on a bosch alarm panel."""
value: dt.datetime = call.data.get(ATTR_DATETIME, dt_util.now())
config_entry: BoschAlarmConfigEntry = service.async_get_config_entry(
call.hass, DOMAIN, call.data[ATTR_CONFIG_ENTRY_ID]
)
panel = config_entry.runtime_data
try:
await panel.set_panel_date(value)
except asyncio.InvalidStateError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="connection_error",
translation_placeholders={"target": config_entry.title},
) from err
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Set up the services for the bosch alarm integration."""
hass.services.async_register(
DOMAIN,
SERVICE_SET_DATE_TIME,
async_set_panel_date,
schema=SET_DATE_TIME_SCHEMA,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/bosch_alarm/services.py",
"license": "Apache License 2.0",
"lines": 51,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/bosch_alarm/switch.py | """Support for Bosch Alarm Panel outputs and doors as switches."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from typing import Any
from bosch_alarm_mode2 import Panel
from bosch_alarm_mode2.panel import Door
from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import BoschAlarmConfigEntry
from .const import DOMAIN
from .entity import BoschAlarmDoorEntity, BoschAlarmOutputEntity
@dataclass(kw_only=True, frozen=True)
class BoschAlarmSwitchEntityDescription(SwitchEntityDescription):
"""Describes Bosch Alarm door entity."""
value_fn: Callable[[Door], bool]
on_fn: Callable[[Panel, int], Coroutine[Any, Any, None]]
off_fn: Callable[[Panel, int], Coroutine[Any, Any, None]]
DOOR_SWITCH_TYPES: list[BoschAlarmSwitchEntityDescription] = [
BoschAlarmSwitchEntityDescription(
key="locked",
translation_key="locked",
value_fn=lambda door: door.is_locked(),
on_fn=lambda panel, door_id: panel.door_relock(door_id),
off_fn=lambda panel, door_id: panel.door_unlock(door_id),
),
BoschAlarmSwitchEntityDescription(
key="secured",
translation_key="secured",
value_fn=lambda door: door.is_secured(),
on_fn=lambda panel, door_id: panel.door_secure(door_id),
off_fn=lambda panel, door_id: panel.door_unsecure(door_id),
),
BoschAlarmSwitchEntityDescription(
key="cycling",
translation_key="cycling",
value_fn=lambda door: door.is_cycling(),
on_fn=lambda panel, door_id: panel.door_cycle(door_id),
off_fn=lambda panel, door_id: panel.door_relock(door_id),
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: BoschAlarmConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up switch entities for outputs."""
panel = config_entry.runtime_data
entities: list[SwitchEntity] = [
PanelOutputEntity(
panel, output_id, config_entry.unique_id or config_entry.entry_id
)
for output_id in panel.outputs
]
entities.extend(
PanelDoorEntity(
panel,
door_id,
config_entry.unique_id or config_entry.entry_id,
entity_description,
)
for door_id in panel.doors
for entity_description in DOOR_SWITCH_TYPES
)
async_add_entities(entities)
PARALLEL_UPDATES = 0
class PanelDoorEntity(BoschAlarmDoorEntity, SwitchEntity):
"""A switch entity for a door on a bosch alarm panel."""
entity_description: BoschAlarmSwitchEntityDescription
def __init__(
self,
panel: Panel,
door_id: int,
unique_id: str,
entity_description: BoschAlarmSwitchEntityDescription,
) -> None:
"""Set up a switch entity for a door on a bosch alarm panel."""
super().__init__(panel, door_id, unique_id)
self.entity_description = entity_description
self._attr_unique_id = f"{self._door_unique_id}_{entity_description.key}"
@property
def is_on(self) -> bool:
"""Return the value function."""
return self.entity_description.value_fn(self._door)
async def async_turn_on(self, **kwargs: Any) -> None:
"""Run the on function."""
# If the door is currently cycling, we can't send it any other commands until it is done
if self._door.is_cycling():
raise HomeAssistantError(
translation_domain=DOMAIN, translation_key="incorrect_door_state"
)
await self.entity_description.on_fn(self.panel, self._door_id)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Run the off function."""
# If the door is currently cycling, we can't send it any other commands until it is done
if self._door.is_cycling():
raise HomeAssistantError(
translation_domain=DOMAIN, translation_key="incorrect_door_state"
)
await self.entity_description.off_fn(self.panel, self._door_id)
class PanelOutputEntity(BoschAlarmOutputEntity, SwitchEntity):
"""An output entity for a bosch alarm panel."""
_attr_name = None
def __init__(self, panel: Panel, output_id: int, unique_id: str) -> None:
"""Set up an output entity for a bosch alarm panel."""
super().__init__(panel, output_id, unique_id)
self._attr_unique_id = self._output_unique_id
@property
def is_on(self) -> bool:
"""Check if this entity is on."""
return self._output.is_active()
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on this output."""
await self.panel.set_output_active(self._output_id)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off this output."""
await self.panel.set_output_inactive(self._output_id)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/bosch_alarm/switch.py",
"license": "Apache License 2.0",
"lines": 119,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/downloader/services.py | """Support for functionality to download files."""
from __future__ import annotations
from http import HTTPStatus
import os
import re
import threading
import requests
import voluptuous as vol
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.service import async_register_admin_service
from homeassistant.util import raise_if_invalid_filename, raise_if_invalid_path
from .const import (
_LOGGER,
ATTR_FILENAME,
ATTR_HEADERS,
ATTR_OVERWRITE,
ATTR_SUBDIR,
ATTR_URL,
CONF_DOWNLOAD_DIR,
DOMAIN,
DOWNLOAD_COMPLETED_EVENT,
DOWNLOAD_FAILED_EVENT,
SERVICE_DOWNLOAD_FILE,
)
def download_file(service: ServiceCall) -> None:
"""Start thread to download file specified in the URL."""
entry = service.hass.config_entries.async_loaded_entries(DOMAIN)[0]
download_path = entry.data[CONF_DOWNLOAD_DIR]
url: str = service.data[ATTR_URL]
subdir: str | None = service.data.get(ATTR_SUBDIR)
target_filename: str | None = service.data.get(ATTR_FILENAME)
overwrite: bool = service.data[ATTR_OVERWRITE]
headers: dict[str, str] = service.data[ATTR_HEADERS]
if subdir:
# Check the path
try:
raise_if_invalid_path(subdir)
except ValueError as err:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="subdir_invalid",
translation_placeholders={"subdir": subdir},
) from err
if os.path.isabs(subdir):
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="subdir_not_relative",
translation_placeholders={"subdir": subdir},
)
def do_download() -> None:
"""Download the file."""
final_path = None
filename = target_filename
try:
req = requests.get(url, stream=True, headers=headers, timeout=10)
if req.status_code != HTTPStatus.OK:
_LOGGER.warning(
"Downloading '%s' failed, status_code=%d", url, req.status_code
)
service.hass.bus.fire(
f"{DOMAIN}_{DOWNLOAD_FAILED_EVENT}",
{"url": url, "filename": filename},
)
else:
if filename is None and "content-disposition" in req.headers:
if match := re.search(
r"filename=(\S+)", req.headers["content-disposition"]
):
filename = match.group(1).strip("'\" ")
if not filename:
filename = os.path.basename(url).strip()
if not filename:
filename = "ha_download"
# Check the filename
raise_if_invalid_filename(filename)
# Do we want to download to subdir, create if needed
if subdir:
subdir_path = os.path.join(download_path, subdir)
# Ensure subdir exist
os.makedirs(subdir_path, exist_ok=True)
final_path = os.path.join(subdir_path, filename)
else:
final_path = os.path.join(download_path, filename)
path, ext = os.path.splitext(final_path)
# If file exist append a number.
# We test filename, filename_2..
if not overwrite:
tries = 1
final_path = path + ext
while os.path.isfile(final_path):
tries += 1
final_path = f"{path}_{tries}.{ext}"
_LOGGER.debug("%s -> %s", url, final_path)
with open(final_path, "wb") as fil:
fil.writelines(req.iter_content(1024))
_LOGGER.debug("Downloading of %s done", url)
service.hass.bus.fire(
f"{DOMAIN}_{DOWNLOAD_COMPLETED_EVENT}",
{"url": url, "filename": filename},
)
except requests.exceptions.ConnectionError:
_LOGGER.exception("ConnectionError occurred for %s", url)
service.hass.bus.fire(
f"{DOMAIN}_{DOWNLOAD_FAILED_EVENT}",
{"url": url, "filename": filename},
)
# Remove file if we started downloading but failed
if final_path and os.path.isfile(final_path):
os.remove(final_path)
except ValueError:
_LOGGER.exception("Invalid value")
service.hass.bus.fire(
f"{DOMAIN}_{DOWNLOAD_FAILED_EVENT}",
{"url": url, "filename": filename},
)
# Remove file if we started downloading but failed
if final_path and os.path.isfile(final_path):
os.remove(final_path)
threading.Thread(target=do_download).start()
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Register the services for the downloader component."""
async_register_admin_service(
hass,
DOMAIN,
SERVICE_DOWNLOAD_FILE,
download_file,
schema=vol.Schema(
{
vol.Optional(ATTR_FILENAME): cv.string,
vol.Optional(ATTR_SUBDIR): cv.string,
vol.Required(ATTR_URL): cv.url,
vol.Optional(ATTR_OVERWRITE, default=False): cv.boolean,
vol.Optional(ATTR_HEADERS, default=dict): vol.Schema(
{cv.string: cv.string}
),
}
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/downloader/services.py",
"license": "Apache License 2.0",
"lines": 141,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/eheimdigital/diagnostics.py | """Diagnostics for the EHEIM Digital integration."""
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.core import HomeAssistant
from .coordinator import EheimDigitalConfigEntry
TO_REDACT = {"emailAddr", "usrName"}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: EheimDigitalConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return async_redact_data(
{"entry": entry.as_dict(), "data": entry.runtime_data.data}, TO_REDACT
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/eheimdigital/diagnostics.py",
"license": "Apache License 2.0",
"lines": 13,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/eheimdigital/select.py | """EHEIM Digital select entities."""
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Any, Literal, override
from eheimdigital.classic_vario import EheimDigitalClassicVario
from eheimdigital.device import EheimDigitalDevice
from eheimdigital.filter import EheimDigitalFilter
from eheimdigital.types import (
FilterMode,
FilterModeProf,
UnitOfMeasurement as EheimDigitalUnitOfMeasurement,
)
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.const import EntityCategory, UnitOfFrequency, UnitOfVolumeFlowRate
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import EheimDigitalConfigEntry, EheimDigitalUpdateCoordinator
from .entity import EheimDigitalEntity, exception_handler
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class EheimDigitalSelectDescription[_DeviceT: EheimDigitalDevice](
SelectEntityDescription
):
"""Class describing EHEIM Digital select entities."""
options_fn: Callable[[_DeviceT], list[str]] | None = None
use_api_unit: Literal[True] | None = None
value_fn: Callable[[_DeviceT], str | None]
set_value_fn: Callable[[_DeviceT, str], Awaitable[None] | None]
FILTER_DESCRIPTIONS: tuple[EheimDigitalSelectDescription[EheimDigitalFilter], ...] = (
EheimDigitalSelectDescription[EheimDigitalFilter](
key="filter_mode",
translation_key="filter_mode",
entity_category=EntityCategory.CONFIG,
options=[item.lower() for item in FilterModeProf._member_names_],
value_fn=lambda device: device.filter_mode.name.lower(),
set_value_fn=lambda device, value: device.set_filter_mode(
FilterModeProf[value.upper()]
),
),
EheimDigitalSelectDescription[EheimDigitalFilter](
key="manual_speed",
translation_key="manual_speed",
entity_category=EntityCategory.CONFIG,
unit_of_measurement=UnitOfFrequency.HERTZ,
options_fn=lambda device: [str(i) for i in device.filter_manual_values],
value_fn=lambda device: str(device.manual_speed),
set_value_fn=lambda device, value: device.set_manual_speed(float(value)),
),
EheimDigitalSelectDescription[EheimDigitalFilter](
key="const_flow_speed",
translation_key="const_flow_speed",
entity_category=EntityCategory.CONFIG,
use_api_unit=True,
unit_of_measurement=UnitOfVolumeFlowRate.LITERS_PER_HOUR,
options_fn=lambda device: [str(i) for i in device.filter_const_flow_values],
value_fn=lambda device: str(device.filter_const_flow_values[device.const_flow]),
set_value_fn=(
lambda device, value: device.set_const_flow(
device.filter_const_flow_values.index(int(value))
)
),
),
EheimDigitalSelectDescription[EheimDigitalFilter](
key="day_speed",
translation_key="day_speed",
entity_category=EntityCategory.CONFIG,
use_api_unit=True,
unit_of_measurement=UnitOfVolumeFlowRate.LITERS_PER_HOUR,
options_fn=lambda device: [str(i) for i in device.filter_const_flow_values],
value_fn=lambda device: str(device.filter_const_flow_values[device.day_speed]),
set_value_fn=(
lambda device, value: device.set_day_speed(
device.filter_const_flow_values.index(int(value))
)
),
),
EheimDigitalSelectDescription[EheimDigitalFilter](
key="night_speed",
translation_key="night_speed",
entity_category=EntityCategory.CONFIG,
use_api_unit=True,
unit_of_measurement=UnitOfVolumeFlowRate.LITERS_PER_HOUR,
options_fn=lambda device: [str(i) for i in device.filter_const_flow_values],
value_fn=lambda device: str(
device.filter_const_flow_values[device.night_speed]
),
set_value_fn=(
lambda device, value: device.set_night_speed(
device.filter_const_flow_values.index(int(value))
)
),
),
EheimDigitalSelectDescription[EheimDigitalFilter](
key="high_pulse_speed",
translation_key="high_pulse_speed",
entity_category=EntityCategory.CONFIG,
use_api_unit=True,
unit_of_measurement=UnitOfVolumeFlowRate.LITERS_PER_HOUR,
options_fn=lambda device: [str(i) for i in device.filter_const_flow_values],
value_fn=lambda device: str(
device.filter_const_flow_values[device.high_pulse_speed]
),
set_value_fn=(
lambda device, value: device.set_high_pulse_speed(
device.filter_const_flow_values.index(int(value))
)
),
),
EheimDigitalSelectDescription[EheimDigitalFilter](
key="low_pulse_speed",
translation_key="low_pulse_speed",
entity_category=EntityCategory.CONFIG,
use_api_unit=True,
unit_of_measurement=UnitOfVolumeFlowRate.LITERS_PER_HOUR,
options_fn=lambda device: [str(i) for i in device.filter_const_flow_values],
value_fn=lambda device: str(
device.filter_const_flow_values[device.low_pulse_speed]
),
set_value_fn=(
lambda device, value: device.set_low_pulse_speed(
device.filter_const_flow_values.index(int(value))
)
),
),
)
CLASSICVARIO_DESCRIPTIONS: tuple[
EheimDigitalSelectDescription[EheimDigitalClassicVario], ...
] = (
EheimDigitalSelectDescription[EheimDigitalClassicVario](
key="filter_mode",
translation_key="filter_mode",
value_fn=lambda device: device.filter_mode.name.lower(),
set_value_fn=(
lambda device, value: device.set_filter_mode(FilterMode[value.upper()])
),
options=[name.lower() for name in FilterMode.__members__],
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: EheimDigitalConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the callbacks for the coordinator so select entities can be added as devices are found."""
coordinator = entry.runtime_data
def async_setup_device_entities(
device_address: dict[str, EheimDigitalDevice],
) -> None:
"""Set up the number entities for one or multiple devices."""
entities: list[EheimDigitalSelect[Any]] = []
for device in device_address.values():
if isinstance(device, EheimDigitalClassicVario):
entities.extend(
EheimDigitalSelect[EheimDigitalClassicVario](
coordinator, device, description
)
for description in CLASSICVARIO_DESCRIPTIONS
)
if isinstance(device, EheimDigitalFilter):
entities.extend(
EheimDigitalFilterSelect(coordinator, device, description)
for description in FILTER_DESCRIPTIONS
)
async_add_entities(entities)
coordinator.add_platform_callback(async_setup_device_entities)
async_setup_device_entities(coordinator.hub.devices)
class EheimDigitalSelect[_DeviceT: EheimDigitalDevice](
EheimDigitalEntity[_DeviceT], SelectEntity
):
"""Represent an EHEIM Digital select entity."""
entity_description: EheimDigitalSelectDescription[_DeviceT]
_attr_options: list[str]
def __init__(
self,
coordinator: EheimDigitalUpdateCoordinator,
device: _DeviceT,
description: EheimDigitalSelectDescription[_DeviceT],
) -> None:
"""Initialize an EHEIM Digital select entity."""
super().__init__(coordinator, device)
self.entity_description = description
if description.options_fn is not None:
self._attr_options = description.options_fn(device)
elif description.options is not None:
self._attr_options = description.options
self._attr_unique_id = f"{self._device_address}_{description.key}"
@override
@exception_handler
async def async_select_option(self, option: str) -> None:
if await_return := self.entity_description.set_value_fn(self._device, option):
return await await_return
return None
@override
def _async_update_attrs(self) -> None:
self._attr_current_option = self.entity_description.value_fn(self._device)
class EheimDigitalFilterSelect(EheimDigitalSelect[EheimDigitalFilter]):
"""Represent an EHEIM Digital Filter select entity."""
entity_description: EheimDigitalSelectDescription[EheimDigitalFilter]
_attr_native_unit_of_measurement: str | None
@override
def _async_update_attrs(self) -> None:
if (
self.entity_description.options is None
and self.entity_description.options_fn is not None
):
self._attr_options = self.entity_description.options_fn(self._device)
if self.entity_description.use_api_unit:
if (
self.entity_description.unit_of_measurement
== UnitOfVolumeFlowRate.LITERS_PER_HOUR
and self._device.usrdta["unit"]
== int(EheimDigitalUnitOfMeasurement.US_CUSTOMARY)
):
self._attr_native_unit_of_measurement = (
UnitOfVolumeFlowRate.GALLONS_PER_HOUR
)
else:
self._attr_native_unit_of_measurement = (
self.entity_description.unit_of_measurement
)
super()._async_update_attrs()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/eheimdigital/select.py",
"license": "Apache License 2.0",
"lines": 221,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/guardian/services.py | """Support for Guardian services."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from typing import TYPE_CHECKING, Any
from aioguardian.errors import GuardianError
import voluptuous as vol
from homeassistant.const import (
ATTR_DEVICE_ID,
CONF_DEVICE_ID,
CONF_FILENAME,
CONF_PORT,
CONF_URL,
)
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv, device_registry as dr
from .const import CONF_UID, DOMAIN
if TYPE_CHECKING:
from . import GuardianConfigEntry, GuardianData
SERVICE_NAME_PAIR_SENSOR = "pair_sensor"
SERVICE_NAME_UNPAIR_SENSOR = "unpair_sensor"
SERVICE_NAME_UPGRADE_FIRMWARE = "upgrade_firmware"
SERVICES = (
SERVICE_NAME_PAIR_SENSOR,
SERVICE_NAME_UNPAIR_SENSOR,
SERVICE_NAME_UPGRADE_FIRMWARE,
)
SERVICE_BASE_SCHEMA = vol.Schema(
{
vol.Required(ATTR_DEVICE_ID): cv.string,
}
)
SERVICE_PAIR_UNPAIR_SENSOR_SCHEMA = vol.Schema(
{
vol.Required(ATTR_DEVICE_ID): cv.string,
vol.Required(CONF_UID): cv.string,
}
)
SERVICE_UPGRADE_FIRMWARE_SCHEMA = vol.Schema(
{
vol.Required(ATTR_DEVICE_ID): cv.string,
vol.Optional(CONF_URL): cv.url,
vol.Optional(CONF_PORT): cv.port,
vol.Optional(CONF_FILENAME): cv.string,
},
)
@callback
def async_get_entry_id_for_service_call(call: ServiceCall) -> GuardianConfigEntry:
"""Get the entry ID related to a service call (by device ID)."""
device_id = call.data[CONF_DEVICE_ID]
device_registry = dr.async_get(call.hass)
if (device_entry := device_registry.async_get(device_id)) is None:
raise ValueError(f"Invalid Guardian device ID: {device_id}")
for entry_id in device_entry.config_entries:
if (entry := call.hass.config_entries.async_get_entry(entry_id)) is None:
continue
if entry.domain == DOMAIN:
return entry
raise ValueError(f"No config entry for device ID: {device_id}")
@callback
def call_with_data(
func: Callable[[ServiceCall, GuardianData], Coroutine[Any, Any, None]],
) -> Callable[[ServiceCall], Coroutine[Any, Any, None]]:
"""Hydrate a service call with the appropriate GuardianData object."""
async def wrapper(call: ServiceCall) -> None:
"""Wrap the service function."""
data = async_get_entry_id_for_service_call(call).runtime_data
try:
async with data.client:
await func(call, data)
except GuardianError as err:
raise HomeAssistantError(
f"Error while executing {func.__name__}: {err}"
) from err
return wrapper
@call_with_data
async def async_pair_sensor(call: ServiceCall, data: GuardianData) -> None:
"""Add a new paired sensor."""
uid = call.data[CONF_UID]
await data.client.sensor.pair_sensor(uid)
await data.paired_sensor_manager.async_pair_sensor(uid)
@call_with_data
async def async_unpair_sensor(call: ServiceCall, data: GuardianData) -> None:
"""Remove a paired sensor."""
uid = call.data[CONF_UID]
await data.client.sensor.unpair_sensor(uid)
await data.paired_sensor_manager.async_unpair_sensor(uid)
@call_with_data
async def async_upgrade_firmware(call: ServiceCall, data: GuardianData) -> None:
"""Upgrade the device firmware."""
await data.client.system.upgrade_firmware(
url=call.data[CONF_URL],
port=call.data[CONF_PORT],
filename=call.data[CONF_FILENAME],
)
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Register the guardian services."""
for service_name, schema, method in (
(
SERVICE_NAME_PAIR_SENSOR,
SERVICE_PAIR_UNPAIR_SENSOR_SCHEMA,
async_pair_sensor,
),
(
SERVICE_NAME_UNPAIR_SENSOR,
SERVICE_PAIR_UNPAIR_SENSOR_SCHEMA,
async_unpair_sensor,
),
(
SERVICE_NAME_UPGRADE_FIRMWARE,
SERVICE_UPGRADE_FIRMWARE_SCHEMA,
async_upgrade_firmware,
),
):
hass.services.async_register(DOMAIN, service_name, method, schema=schema)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/guardian/services.py",
"license": "Apache License 2.0",
"lines": 116,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/homee/alarm_control_panel.py | """The Homee alarm control panel platform."""
from dataclasses import dataclass
from pyHomee.const import AttributeChangedBy, AttributeType
from pyHomee.model import HomeeAttribute, HomeeNode
from homeassistant.components.alarm_control_panel import (
AlarmControlPanelEntity,
AlarmControlPanelEntityDescription,
AlarmControlPanelEntityFeature,
AlarmControlPanelState,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import DOMAIN, HomeeConfigEntry
from .entity import HomeeEntity
from .helpers import get_name_for_enum, setup_homee_platform
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class HomeeAlarmControlPanelEntityDescription(AlarmControlPanelEntityDescription):
"""A class that describes Homee alarm control panel entities."""
code_arm_required: bool = False
state_list: list[AlarmControlPanelState]
ALARM_DESCRIPTIONS = {
AttributeType.HOMEE_MODE: HomeeAlarmControlPanelEntityDescription(
key="homee_mode",
code_arm_required=False,
state_list=[
AlarmControlPanelState.ARMED_HOME,
AlarmControlPanelState.ARMED_NIGHT,
AlarmControlPanelState.ARMED_AWAY,
AlarmControlPanelState.ARMED_VACATION,
],
)
}
def get_supported_features(
state_list: list[AlarmControlPanelState],
) -> AlarmControlPanelEntityFeature:
"""Return supported features based on the state list."""
supported_features = AlarmControlPanelEntityFeature(0)
if AlarmControlPanelState.ARMED_HOME in state_list:
supported_features |= AlarmControlPanelEntityFeature.ARM_HOME
if AlarmControlPanelState.ARMED_AWAY in state_list:
supported_features |= AlarmControlPanelEntityFeature.ARM_AWAY
if AlarmControlPanelState.ARMED_NIGHT in state_list:
supported_features |= AlarmControlPanelEntityFeature.ARM_NIGHT
if AlarmControlPanelState.ARMED_VACATION in state_list:
supported_features |= AlarmControlPanelEntityFeature.ARM_VACATION
return supported_features
async def add_alarm_control_panel_entities(
config_entry: HomeeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
nodes: list[HomeeNode],
) -> None:
"""Add homee alarm control panel entities."""
async_add_entities(
HomeeAlarmPanel(attribute, config_entry, ALARM_DESCRIPTIONS[attribute.type])
for node in nodes
for attribute in node.attributes
if attribute.type in ALARM_DESCRIPTIONS and attribute.editable
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: HomeeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add the homee platform for the alarm control panel component."""
await setup_homee_platform(
add_alarm_control_panel_entities, async_add_entities, config_entry
)
class HomeeAlarmPanel(HomeeEntity, AlarmControlPanelEntity):
"""Representation of a Homee alarm control panel."""
entity_description: HomeeAlarmControlPanelEntityDescription
def __init__(
self,
attribute: HomeeAttribute,
entry: HomeeConfigEntry,
description: HomeeAlarmControlPanelEntityDescription,
) -> None:
"""Initialize a Homee alarm control panel entity."""
super().__init__(attribute, entry)
self.entity_description = description
self._attr_code_arm_required = description.code_arm_required
self._attr_supported_features = get_supported_features(description.state_list)
self._attr_translation_key = description.key
@property
def alarm_state(self) -> AlarmControlPanelState:
"""Return current state."""
return self.entity_description.state_list[int(self._attribute.current_value)]
@property
def changed_by(self) -> str:
"""Return by whom or what the entity was last changed."""
changed_by_name = get_name_for_enum(
AttributeChangedBy, self._attribute.changed_by
)
return f"{changed_by_name} - {self._attribute.changed_by_id}"
async def _async_set_alarm_state(self, state: AlarmControlPanelState) -> None:
"""Set the alarm state."""
if state in self.entity_description.state_list:
await self.async_set_homee_value(
self.entity_description.state_list.index(state)
)
async def async_alarm_disarm(self, code: str | None = None) -> None:
"""Send disarm command."""
# Since disarm is always present in the UI, we raise an error.
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="disarm_not_supported",
)
async def async_alarm_arm_home(self, code: str | None = None) -> None:
"""Send arm home command."""
await self._async_set_alarm_state(AlarmControlPanelState.ARMED_HOME)
async def async_alarm_arm_night(self, code: str | None = None) -> None:
"""Send arm night command."""
await self._async_set_alarm_state(AlarmControlPanelState.ARMED_NIGHT)
async def async_alarm_arm_away(self, code: str | None = None) -> None:
"""Send arm away command."""
await self._async_set_alarm_state(AlarmControlPanelState.ARMED_AWAY)
async def async_alarm_arm_vacation(self, code: str | None = None) -> None:
"""Send arm vacation command."""
await self._async_set_alarm_state(AlarmControlPanelState.ARMED_VACATION)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/homee/alarm_control_panel.py",
"license": "Apache License 2.0",
"lines": 120,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/homee/event.py | """The homee event platform."""
from pyHomee.const import AttributeType, NodeProfile
from pyHomee.model import HomeeAttribute, HomeeNode
from homeassistant.components.event import (
EventDeviceClass,
EventEntity,
EventEntityDescription,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import HomeeConfigEntry
from .entity import HomeeEntity
from .helpers import setup_homee_platform
PARALLEL_UPDATES = 0
REMOTE_PROFILES = [
NodeProfile.REMOTE,
NodeProfile.ONE_BUTTON_REMOTE,
NodeProfile.TWO_BUTTON_REMOTE,
NodeProfile.THREE_BUTTON_REMOTE,
NodeProfile.FOUR_BUTTON_REMOTE,
]
EVENT_DESCRIPTIONS: dict[AttributeType, EventEntityDescription] = {
AttributeType.BUTTON_STATE: EventEntityDescription(
key="button_state",
device_class=EventDeviceClass.BUTTON,
event_types=["upper", "lower", "released"],
),
AttributeType.UP_DOWN_REMOTE: EventEntityDescription(
key="up_down_remote",
device_class=EventDeviceClass.BUTTON,
event_types=[
"released",
"up",
"down",
"stop",
"up_long",
"down_long",
"stop_long",
"c_button",
"b_button",
"a_button",
],
),
}
async def add_event_entities(
config_entry: HomeeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
nodes: list[HomeeNode],
) -> None:
"""Add homee event entities."""
async_add_entities(
HomeeEvent(attribute, config_entry, EVENT_DESCRIPTIONS[attribute.type])
for node in nodes
for attribute in node.attributes
if attribute.type in EVENT_DESCRIPTIONS
and node.profile in REMOTE_PROFILES
and not attribute.editable
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: HomeeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add event entities for homee."""
await setup_homee_platform(add_event_entities, async_add_entities, config_entry)
class HomeeEvent(HomeeEntity, EventEntity):
"""Representation of a homee event."""
def __init__(
self,
attribute: HomeeAttribute,
entry: HomeeConfigEntry,
description: EventEntityDescription,
) -> None:
"""Initialize the homee event entity."""
super().__init__(attribute, entry)
self.entity_description = description
self._attr_translation_key = description.key
if attribute.instance > 0:
self._attr_translation_key = f"{self._attr_translation_key}_instance"
self._attr_translation_placeholders = {"instance": str(attribute.instance)}
async def async_added_to_hass(self) -> None:
"""Add the homee event entity to home assistant."""
await super().async_added_to_hass()
self.async_on_remove(
self._attribute.add_on_changed_listener(self._event_triggered)
)
@callback
def _event_triggered(self, event: HomeeAttribute) -> None:
"""Handle a homee event."""
self._trigger_event(self.event_types[int(event.current_value)])
self.schedule_update_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/homee/event.py",
"license": "Apache License 2.0",
"lines": 91,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/homee/fan.py | """The Homee fan platform."""
import math
from typing import Any, cast
from pyHomee.const import AttributeType, NodeProfile
from pyHomee.model import HomeeAttribute, HomeeNode
from homeassistant.components.fan import FanEntity, FanEntityFeature
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.percentage import (
percentage_to_ranged_value,
ranged_value_to_percentage,
)
from homeassistant.util.scaling import int_states_in_range
from . import HomeeConfigEntry
from .const import DOMAIN, PRESET_AUTO, PRESET_MANUAL, PRESET_SUMMER
from .entity import HomeeNodeEntity
from .helpers import setup_homee_platform
PARALLEL_UPDATES = 0
async def add_fan_entities(
config_entry: HomeeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
nodes: list[HomeeNode],
) -> None:
"""Add homee fan entities."""
async_add_entities(
HomeeFan(node, config_entry)
for node in nodes
if node.profile == NodeProfile.VENTILATION_CONTROL
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: HomeeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Homee fan platform."""
await setup_homee_platform(add_fan_entities, async_add_entities, config_entry)
class HomeeFan(HomeeNodeEntity, FanEntity):
"""Representation of a Homee fan entity."""
_attr_translation_key = DOMAIN
_attr_name = None
_attr_preset_modes = [PRESET_MANUAL, PRESET_AUTO, PRESET_SUMMER]
speed_range = (1, 8)
_attr_speed_count = int_states_in_range(speed_range)
def __init__(self, node: HomeeNode, entry: HomeeConfigEntry) -> None:
"""Initialize a Homee fan entity."""
super().__init__(node, entry)
self._speed_attribute: HomeeAttribute = cast(
HomeeAttribute, node.get_attribute_by_type(AttributeType.VENTILATION_LEVEL)
)
self._mode_attribute: HomeeAttribute = cast(
HomeeAttribute, node.get_attribute_by_type(AttributeType.VENTILATION_MODE)
)
@property
def supported_features(self) -> FanEntityFeature:
"""Return the supported features based on preset_mode."""
features = FanEntityFeature.PRESET_MODE
if self.preset_mode == PRESET_MANUAL:
features |= (
FanEntityFeature.SET_SPEED
| FanEntityFeature.TURN_ON
| FanEntityFeature.TURN_OFF
)
return features
@property
def is_on(self) -> bool:
"""Return true if the entity is on."""
return self.percentage > 0
@property
def percentage(self) -> int:
"""Return the current speed percentage."""
return ranged_value_to_percentage(
self.speed_range, self._speed_attribute.current_value
)
@property
def preset_mode(self) -> str:
"""Return the mode from the float state."""
return self._attr_preset_modes[int(self._mode_attribute.current_value)]
async def async_set_percentage(self, percentage: int) -> None:
"""Set the speed percentage of the fan."""
await self.async_set_homee_value(
self._speed_attribute,
math.ceil(percentage_to_ranged_value(self.speed_range, percentage)),
)
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set the preset mode of the fan."""
await self.async_set_homee_value(
self._mode_attribute, self._attr_preset_modes.index(preset_mode)
)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the fan off."""
await self.async_set_homee_value(self._speed_attribute, 0)
async def async_turn_on(
self,
percentage: int | None = None,
preset_mode: str | None = None,
**kwargs: Any,
) -> None:
"""Turn the fan on."""
if preset_mode is not None:
if preset_mode != "manual":
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_preset_mode",
translation_placeholders={"preset_mode": preset_mode},
)
await self.async_set_preset_mode(preset_mode)
# If no percentage is given, use the last known value.
if percentage is None:
percentage = ranged_value_to_percentage(
self.speed_range,
self._speed_attribute.last_value,
)
# If the last known value is 0, set 100%.
if percentage == 0:
percentage = 100
await self.async_set_percentage(percentage)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/homee/fan.py",
"license": "Apache License 2.0",
"lines": 117,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/huisbaasje/coordinator.py | """The EnergyFlip integration."""
import asyncio
from datetime import timedelta
import logging
from typing import Any
from energyflip import EnergyFlip, EnergyFlipException
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import (
FETCH_TIMEOUT,
POLLING_INTERVAL,
SENSOR_TYPE_RATE,
SENSOR_TYPE_THIS_DAY,
SENSOR_TYPE_THIS_MONTH,
SENSOR_TYPE_THIS_WEEK,
SENSOR_TYPE_THIS_YEAR,
SOURCE_TYPES,
)
PLATFORMS = [Platform.SENSOR]
_LOGGER = logging.getLogger(__name__)
type EnergyFlipConfigEntry = ConfigEntry[EnergyFlipUpdateCoordinator]
class EnergyFlipUpdateCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]]):
"""EnergyFlip data update coordinator."""
config_entry: EnergyFlipConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: EnergyFlipConfigEntry,
energyflip: EnergyFlip,
) -> None:
"""Initialize the Huisbaasje data coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name="sensor",
update_interval=timedelta(seconds=POLLING_INTERVAL),
)
self._energyflip = energyflip
async def _async_update_data(self) -> dict[str, dict[str, Any]]:
"""Update the data by performing a request to EnergyFlip."""
try:
# Note: TimeoutError and aiohttp.ClientError are already
# handled by the data update coordinator.
async with asyncio.timeout(FETCH_TIMEOUT):
if not self._energyflip.is_authenticated():
_LOGGER.warning("EnergyFlip is unauthenticated. Reauthenticating")
await self._energyflip.authenticate()
current_measurements = await self._energyflip.current_measurements()
return {
source_type: {
SENSOR_TYPE_RATE: _get_measurement_rate(
current_measurements, source_type
),
SENSOR_TYPE_THIS_DAY: _get_cumulative_value(
current_measurements, source_type, SENSOR_TYPE_THIS_DAY
),
SENSOR_TYPE_THIS_WEEK: _get_cumulative_value(
current_measurements, source_type, SENSOR_TYPE_THIS_WEEK
),
SENSOR_TYPE_THIS_MONTH: _get_cumulative_value(
current_measurements, source_type, SENSOR_TYPE_THIS_MONTH
),
SENSOR_TYPE_THIS_YEAR: _get_cumulative_value(
current_measurements, source_type, SENSOR_TYPE_THIS_YEAR
),
}
for source_type in SOURCE_TYPES
}
except EnergyFlipException as exception:
raise UpdateFailed(
f"Error communicating with API: {exception}"
) from exception
def _get_cumulative_value(
current_measurements: dict,
source_type: str,
period_type: str,
):
"""Get the cumulative energy consumption for a certain period.
:param current_measurements: The result from the EnergyFlip client
:param source_type: The source of energy (electricity or gas)
:param period_type: The period for which cumulative value should be given.
"""
if source_type in current_measurements:
if (
period_type in current_measurements[source_type]
and current_measurements[source_type][period_type] is not None
):
return current_measurements[source_type][period_type]["value"]
else:
_LOGGER.error(
"Source type %s not present in %s", source_type, current_measurements
)
return None
def _get_measurement_rate(current_measurements: dict, source_type: str):
if source_type in current_measurements:
if (
"measurement" in current_measurements[source_type]
and current_measurements[source_type]["measurement"] is not None
):
return current_measurements[source_type]["measurement"]["rate"]
else:
_LOGGER.error(
"Source type %s not present in %s", source_type, current_measurements
)
return None
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/huisbaasje/coordinator.py",
"license": "Apache License 2.0",
"lines": 108,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/icloud/services.py | """The iCloud component."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.util import slugify
from .account import IcloudAccount, IcloudConfigEntry
from .const import (
ATTR_ACCOUNT,
ATTR_DEVICE_NAME,
ATTR_LOST_DEVICE_MESSAGE,
ATTR_LOST_DEVICE_NUMBER,
ATTR_LOST_DEVICE_SOUND,
DOMAIN,
)
# services
SERVICE_ICLOUD_PLAY_SOUND = "play_sound"
SERVICE_ICLOUD_DISPLAY_MESSAGE = "display_message"
SERVICE_ICLOUD_LOST_DEVICE = "lost_device"
SERVICE_ICLOUD_UPDATE = "update"
SERVICE_SCHEMA = vol.Schema({vol.Optional(ATTR_ACCOUNT): cv.string})
SERVICE_SCHEMA_PLAY_SOUND = vol.Schema(
{vol.Required(ATTR_ACCOUNT): cv.string, vol.Required(ATTR_DEVICE_NAME): cv.string}
)
SERVICE_SCHEMA_DISPLAY_MESSAGE = vol.Schema(
{
vol.Required(ATTR_ACCOUNT): cv.string,
vol.Required(ATTR_DEVICE_NAME): cv.string,
vol.Required(ATTR_LOST_DEVICE_MESSAGE): cv.string,
vol.Optional(ATTR_LOST_DEVICE_SOUND): cv.boolean,
}
)
SERVICE_SCHEMA_LOST_DEVICE = vol.Schema(
{
vol.Required(ATTR_ACCOUNT): cv.string,
vol.Required(ATTR_DEVICE_NAME): cv.string,
vol.Required(ATTR_LOST_DEVICE_NUMBER): cv.string,
vol.Required(ATTR_LOST_DEVICE_MESSAGE): cv.string,
}
)
def play_sound(service: ServiceCall) -> None:
"""Play sound on the device."""
account = service.data[ATTR_ACCOUNT]
device_name: str = service.data[ATTR_DEVICE_NAME]
device_name = slugify(device_name.replace(" ", "", 99))
for device in _get_account(service.hass, account).get_devices_with_name(
device_name
):
device.play_sound()
def display_message(service: ServiceCall) -> None:
"""Display a message on the device."""
account = service.data[ATTR_ACCOUNT]
device_name: str = service.data[ATTR_DEVICE_NAME]
device_name = slugify(device_name.replace(" ", "", 99))
message = service.data.get(ATTR_LOST_DEVICE_MESSAGE)
sound = service.data.get(ATTR_LOST_DEVICE_SOUND, False)
for device in _get_account(service.hass, account).get_devices_with_name(
device_name
):
device.display_message(message, sound)
def lost_device(service: ServiceCall) -> None:
"""Make the device in lost state."""
account = service.data[ATTR_ACCOUNT]
device_name: str = service.data[ATTR_DEVICE_NAME]
device_name = slugify(device_name.replace(" ", "", 99))
number = service.data.get(ATTR_LOST_DEVICE_NUMBER)
message = service.data.get(ATTR_LOST_DEVICE_MESSAGE)
for device in _get_account(service.hass, account).get_devices_with_name(
device_name
):
device.lost_device(number, message)
def update_account(service: ServiceCall) -> None:
"""Call the update function of an iCloud account."""
if (account := service.data.get(ATTR_ACCOUNT)) is None:
# Update all accounts when no specific account is provided
entry: IcloudConfigEntry
for entry in service.hass.config_entries.async_loaded_entries(DOMAIN):
entry.runtime_data.keep_alive()
else:
_get_account(service.hass, account).keep_alive()
def _get_account(hass: HomeAssistant, account_identifier: str) -> IcloudAccount:
if account_identifier is None:
return None
entry: IcloudConfigEntry
for entry in hass.config_entries.async_loaded_entries(DOMAIN):
if entry.runtime_data.username == account_identifier:
return entry.runtime_data
raise ValueError(f"No iCloud account with username or name {account_identifier}")
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Register iCloud services."""
hass.services.async_register(
DOMAIN, SERVICE_ICLOUD_PLAY_SOUND, play_sound, schema=SERVICE_SCHEMA_PLAY_SOUND
)
hass.services.async_register(
DOMAIN,
SERVICE_ICLOUD_DISPLAY_MESSAGE,
display_message,
schema=SERVICE_SCHEMA_DISPLAY_MESSAGE,
)
hass.services.async_register(
DOMAIN,
SERVICE_ICLOUD_LOST_DEVICE,
lost_device,
schema=SERVICE_SCHEMA_LOST_DEVICE,
)
hass.services.async_register(
DOMAIN, SERVICE_ICLOUD_UPDATE, update_account, schema=SERVICE_SCHEMA
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/icloud/services.py",
"license": "Apache License 2.0",
"lines": 109,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/immich/config_flow.py | """Config flow for the Immich integration."""
from __future__ import annotations
from collections.abc import Mapping
import logging
from typing import Any
from aioimmich import Immich
from aioimmich.const import CONNECT_ERRORS
from aioimmich.exceptions import ImmichUnauthorizedError
from aioimmich.users.models import ImmichUser
import voluptuous as vol
from yarl import URL
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import (
CONF_API_KEY,
CONF_HOST,
CONF_PORT,
CONF_SSL,
CONF_URL,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.selector import (
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from .const import DEFAULT_VERIFY_SSL, DOMAIN
class InvalidUrl(HomeAssistantError):
"""Error to indicate invalid URL."""
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_URL): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.URL)
),
vol.Required(CONF_API_KEY): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.PASSWORD)
),
vol.Required(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): bool,
}
)
def _parse_url(url: str) -> tuple[str, int, bool]:
"""Parse the URL and return host, port, and ssl."""
parsed_url = URL(url)
if (
(host := parsed_url.host) is None
or (port := parsed_url.port) is None
or (scheme := parsed_url.scheme) is None
):
raise InvalidUrl
return host, port, scheme == "https"
async def check_user_info(
hass: HomeAssistant, host: str, port: int, ssl: bool, verify_ssl: bool, api_key: str
) -> ImmichUser:
"""Test connection and fetch own user info."""
session = async_get_clientsession(hass, verify_ssl)
immich = Immich(session, api_key, host, port, ssl)
return await immich.users.async_get_my_user()
class ImmichConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Immich."""
VERSION = 1
_name: str
_current_data: Mapping[str, Any]
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:
try:
(host, port, ssl) = _parse_url(user_input[CONF_URL])
except InvalidUrl:
errors[CONF_URL] = "invalid_url"
else:
try:
my_user_info = await check_user_info(
self.hass,
host,
port,
ssl,
user_input[CONF_VERIFY_SSL],
user_input[CONF_API_KEY],
)
except ImmichUnauthorizedError:
errors["base"] = "invalid_auth"
except CONNECT_ERRORS:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(my_user_info.user_id)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=my_user_info.name,
data={
CONF_HOST: host,
CONF_PORT: port,
CONF_SSL: ssl,
CONF_VERIFY_SSL: user_input[CONF_VERIFY_SSL],
CONF_API_KEY: user_input[CONF_API_KEY],
},
)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Trigger a reauthentication flow."""
self._current_data = entry_data
self._name = entry_data[CONF_HOST]
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reauthorization flow."""
errors = {}
if user_input is not None:
try:
my_user_info = await check_user_info(
self.hass,
self._current_data[CONF_HOST],
self._current_data[CONF_PORT],
self._current_data[CONF_SSL],
self._current_data[CONF_VERIFY_SSL],
user_input[CONF_API_KEY],
)
except ImmichUnauthorizedError:
errors["base"] = "invalid_auth"
except CONNECT_ERRORS:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(my_user_info.user_id)
self._abort_if_unique_id_mismatch()
return self.async_update_reload_and_abort(
self._get_reauth_entry(), data_updates=user_input
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema({vol.Required(CONF_API_KEY): str}),
description_placeholders={"name": self._name},
errors=errors,
)
async def async_step_reconfigure(
self,
user_input: Mapping[str, Any] | None = None,
) -> ConfigFlowResult:
"""Handle reconfiguration of immich."""
entry = self._get_reconfigure_entry()
current_data = entry.data
url = f"{'https' if current_data[CONF_SSL] else 'http'}://{current_data[CONF_HOST]}:{current_data[CONF_PORT]}"
verify_ssl = current_data[CONF_VERIFY_SSL]
errors: dict[str, str] = {}
if user_input is not None:
url = user_input[CONF_URL]
verify_ssl = user_input[CONF_VERIFY_SSL]
try:
(host, port, ssl) = _parse_url(user_input[CONF_URL])
except InvalidUrl:
errors[CONF_URL] = "invalid_url"
else:
try:
await check_user_info(
self.hass,
host,
port,
ssl,
user_input[CONF_VERIFY_SSL],
current_data[CONF_API_KEY],
)
except ImmichUnauthorizedError:
errors["base"] = "invalid_auth"
except CONNECT_ERRORS:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_update_reload_and_abort(
entry,
data_updates={
**current_data,
CONF_HOST: host,
CONF_PORT: port,
CONF_SSL: ssl,
CONF_VERIFY_SSL: user_input[CONF_VERIFY_SSL],
},
)
return self.async_show_form(
step_id="reconfigure",
data_schema=vol.Schema(
{
vol.Required(CONF_URL, default=url): TextSelector(
config=TextSelectorConfig(type=TextSelectorType.URL)
),
vol.Required(CONF_VERIFY_SSL, default=verify_ssl): bool,
}
),
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/immich/config_flow.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/immich/const.py | """Constants for the Immich integration."""
DOMAIN = "immich"
DEFAULT_PORT = 2283
DEFAULT_USE_SSL = False
DEFAULT_VERIFY_SSL = False
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/immich/const.py",
"license": "Apache License 2.0",
"lines": 5,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/immich/coordinator.py | """Coordinator for the Immich integration."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import timedelta
import logging
from aioimmich import Immich
from aioimmich.const import CONNECT_ERRORS
from aioimmich.exceptions import ImmichUnauthorizedError
from aioimmich.server.models import (
ImmichServerAbout,
ImmichServerStatistics,
ImmichServerStorage,
ImmichServerVersionCheck,
)
from awesomeversion import AwesomeVersion
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_SSL
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
@dataclass
class ImmichData:
"""Data class for storing data from the API."""
server_about: ImmichServerAbout
server_storage: ImmichServerStorage
server_usage: ImmichServerStatistics | None
server_version_check: ImmichServerVersionCheck | None
type ImmichConfigEntry = ConfigEntry[ImmichDataUpdateCoordinator]
class ImmichDataUpdateCoordinator(DataUpdateCoordinator[ImmichData]):
"""Class to manage fetching IMGW-PIB data API."""
config_entry: ImmichConfigEntry
def __init__(
self, hass: HomeAssistant, entry: ConfigEntry, api: Immich, is_admin: bool
) -> None:
"""Initialize the data update coordinator."""
self.api = api
self.is_admin = is_admin
self.configuration_url = (
f"{'https' if entry.data[CONF_SSL] else 'http'}://"
f"{entry.data[CONF_HOST]}:{entry.data[CONF_PORT]}"
)
super().__init__(
hass,
_LOGGER,
config_entry=entry,
name=DOMAIN,
update_interval=timedelta(seconds=60),
)
async def _async_update_data(self) -> ImmichData:
"""Update data via internal method."""
try:
server_about = await self.api.server.async_get_about_info()
server_storage = await self.api.server.async_get_storage_info()
server_usage = (
await self.api.server.async_get_server_statistics()
if self.is_admin
else None
)
server_version_check = (
await self.api.server.async_get_version_check()
if AwesomeVersion(server_about.version) >= AwesomeVersion("v1.134.0")
else None
)
except ImmichUnauthorizedError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="auth_error",
) from err
except CONNECT_ERRORS as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_error",
translation_placeholders={"error": repr(err)},
) from err
return ImmichData(
server_about, server_storage, server_usage, server_version_check
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/immich/coordinator.py",
"license": "Apache License 2.0",
"lines": 79,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/immich/diagnostics.py | """Diagnostics support for immich."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.const import CONF_API_KEY, CONF_HOST
from homeassistant.core import HomeAssistant
from .coordinator import ImmichConfigEntry
TO_REDACT = {CONF_API_KEY, CONF_HOST}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: ImmichConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator = entry.runtime_data
return {
"entry": async_redact_data(entry.as_dict(), TO_REDACT),
"data": asdict(coordinator.data),
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/immich/diagnostics.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/immich/entity.py | """Base entity for the Immich integration."""
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import ImmichDataUpdateCoordinator
class ImmichEntity(CoordinatorEntity[ImmichDataUpdateCoordinator]):
"""Define immich base entity."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: ImmichDataUpdateCoordinator,
) -> None:
"""Initialize."""
super().__init__(coordinator)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, coordinator.config_entry.entry_id)},
manufacturer="Immich",
sw_version=coordinator.data.server_about.version,
entry_type=DeviceEntryType.SERVICE,
configuration_url=coordinator.configuration_url,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/immich/entity.py",
"license": "Apache License 2.0",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/immich/media_source.py | """Immich as a media source."""
from __future__ import annotations
from logging import getLogger
from aiohttp.web import HTTPNotFound, Request, Response, StreamResponse
from aioimmich.assets.models import ImmichAsset
from aioimmich.exceptions import ImmichError
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.media_player import BrowseError, MediaClass
from homeassistant.components.media_source import (
BrowseMediaSource,
MediaSource,
MediaSourceItem,
PlayMedia,
Unresolvable,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import ChunkAsyncStreamIterator
from .const import DOMAIN
from .coordinator import ImmichConfigEntry
LOGGER = getLogger(__name__)
async def async_get_media_source(hass: HomeAssistant) -> MediaSource:
"""Set up Immich media source."""
hass.http.register_view(ImmichMediaView(hass))
return ImmichMediaSource(hass)
class ImmichMediaSourceIdentifier:
"""Immich media item identifier."""
def __init__(self, identifier: str) -> None:
"""Split identifier into parts."""
parts = identifier.split("|")
# config_entry.unique_id|collection|collection_id|asset_id|file_name|mime_type
self.unique_id = parts[0]
self.collection = parts[1] if len(parts) > 1 else None
self.collection_id = parts[2] if len(parts) > 2 else None
self.asset_id = parts[3] if len(parts) > 3 else None
self.file_name = parts[4] if len(parts) > 3 else None
self.mime_type = parts[5] if len(parts) > 3 else None
class ImmichMediaSource(MediaSource):
"""Provide Immich as media sources."""
name = "Immich"
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize Immich media source."""
super().__init__(DOMAIN)
self.hass = hass
async def async_browse_media(
self,
item: MediaSourceItem,
) -> BrowseMediaSource:
"""Return media."""
if not (entries := self.hass.config_entries.async_loaded_entries(DOMAIN)):
raise BrowseError(
translation_domain=DOMAIN, translation_key="not_configured"
)
return BrowseMediaSource(
domain=DOMAIN,
identifier=None,
media_class=MediaClass.DIRECTORY,
media_content_type=MediaClass.IMAGE,
title="Immich",
can_play=False,
can_expand=True,
children_media_class=MediaClass.DIRECTORY,
children=[
*await self._async_build_immich(item, entries),
],
)
async def _async_build_immich(
self, item: MediaSourceItem, entries: list[ConfigEntry]
) -> list[BrowseMediaSource]:
"""Handle browsing different immich instances."""
# --------------------------------------------------------
# root level, render immich instances
# --------------------------------------------------------
if not item.identifier:
LOGGER.debug("Render all Immich instances")
return [
BrowseMediaSource(
domain=DOMAIN,
identifier=entry.unique_id,
media_class=MediaClass.DIRECTORY,
media_content_type=MediaClass.IMAGE,
title=entry.title,
can_play=False,
can_expand=True,
)
for entry in entries
]
# --------------------------------------------------------
# 1st level, render collections overview
# --------------------------------------------------------
identifier = ImmichMediaSourceIdentifier(item.identifier)
entry: ImmichConfigEntry | None = (
self.hass.config_entries.async_entry_for_domain_unique_id(
DOMAIN, identifier.unique_id
)
)
assert entry
immich_api = entry.runtime_data.api
if identifier.collection is None:
LOGGER.debug("Render all collections for %s", entry.title)
return [
BrowseMediaSource(
domain=DOMAIN,
identifier=f"{identifier.unique_id}|{collection}",
media_class=MediaClass.DIRECTORY,
media_content_type=MediaClass.IMAGE,
title=collection,
can_play=False,
can_expand=True,
)
for collection in ("albums", "people", "tags")
]
# --------------------------------------------------------
# 2nd level, render collection
# --------------------------------------------------------
if identifier.collection_id is None:
if identifier.collection == "albums":
LOGGER.debug("Render all albums for %s", entry.title)
try:
albums = await immich_api.albums.async_get_all_albums()
except ImmichError:
return []
return [
BrowseMediaSource(
domain=DOMAIN,
identifier=f"{identifier.unique_id}|albums|{album.album_id}",
media_class=MediaClass.DIRECTORY,
media_content_type=MediaClass.IMAGE,
title=album.album_name,
can_play=False,
can_expand=True,
thumbnail=f"/immich/{identifier.unique_id}/{album.album_thumbnail_asset_id}/thumbnail/image/jpg",
)
for album in albums
]
if identifier.collection == "tags":
LOGGER.debug("Render all tags for %s", entry.title)
try:
tags = await immich_api.tags.async_get_all_tags()
except ImmichError:
return []
return [
BrowseMediaSource(
domain=DOMAIN,
identifier=f"{identifier.unique_id}|tags|{tag.tag_id}",
media_class=MediaClass.DIRECTORY,
media_content_type=MediaClass.IMAGE,
title=tag.name,
can_play=False,
can_expand=True,
)
for tag in tags
]
if identifier.collection == "people":
LOGGER.debug("Render all people for %s", entry.title)
try:
people = await immich_api.people.async_get_all_people()
except ImmichError:
return []
return [
BrowseMediaSource(
domain=DOMAIN,
identifier=f"{identifier.unique_id}|people|{person.person_id}",
media_class=MediaClass.DIRECTORY,
media_content_type=MediaClass.IMAGE,
title=person.name,
can_play=False,
can_expand=True,
thumbnail=f"/immich/{identifier.unique_id}/{person.person_id}/person/image/jpg",
)
for person in people
]
# --------------------------------------------------------
# final level, render assets
# --------------------------------------------------------
assert identifier.collection_id is not None
assets: list[ImmichAsset] = []
if identifier.collection == "albums":
LOGGER.debug(
"Render all assets of album %s for %s",
identifier.collection_id,
entry.title,
)
try:
album_info = await immich_api.albums.async_get_album_info(
identifier.collection_id
)
assets = album_info.assets
except ImmichError:
return []
elif identifier.collection == "tags":
LOGGER.debug(
"Render all assets with tag %s",
identifier.collection_id,
)
try:
assets = await immich_api.search.async_get_all_by_tag_ids(
[identifier.collection_id]
)
except ImmichError:
return []
elif identifier.collection == "people":
LOGGER.debug(
"Render all assets for person %s",
identifier.collection_id,
)
try:
assets = await immich_api.search.async_get_all_by_person_ids(
[identifier.collection_id]
)
except ImmichError:
return []
ret: list[BrowseMediaSource] = []
for asset in assets:
if not (mime_type := asset.original_mime_type) or not mime_type.startswith(
("image/", "video/")
):
continue
if mime_type.startswith("image/"):
media_class = MediaClass.IMAGE
can_play = False
thumb_mime_type = mime_type
else:
media_class = MediaClass.VIDEO
can_play = True
thumb_mime_type = "image/jpeg"
ret.append(
BrowseMediaSource(
domain=DOMAIN,
identifier=(
f"{identifier.unique_id}|"
f"{identifier.collection}|"
f"{identifier.collection_id}|"
f"{asset.asset_id}|"
f"{asset.original_file_name}|"
f"{mime_type}"
),
media_class=media_class,
media_content_type=mime_type,
title=asset.original_file_name,
can_play=can_play,
can_expand=False,
thumbnail=f"/immich/{identifier.unique_id}/{asset.asset_id}/thumbnail/{thumb_mime_type}",
)
)
return ret
async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia:
"""Resolve media to a url."""
try:
identifier = ImmichMediaSourceIdentifier(item.identifier)
except IndexError as err:
raise Unresolvable(
translation_domain=DOMAIN,
translation_key="identifier_unresolvable",
translation_placeholders={"identifier": item.identifier},
) from err
if identifier.mime_type is None:
raise Unresolvable(
translation_domain=DOMAIN,
translation_key="identifier_no_mime_type_unresolvable",
translation_placeholders={"identifier": item.identifier},
)
return PlayMedia(
(
f"/immich/{identifier.unique_id}/{identifier.asset_id}/fullsize/{identifier.mime_type}"
),
identifier.mime_type,
)
class ImmichMediaView(HomeAssistantView):
"""Immich Media Finder View."""
url = "/immich/{source_dir_id}/{location:.*}"
name = "immich"
def __init__(self, hass: HomeAssistant) -> None:
"""Initialize the media view."""
self.hass = hass
async def get(
self, request: Request, source_dir_id: str, location: str
) -> Response | StreamResponse:
"""Start a GET request."""
if not self.hass.config_entries.async_loaded_entries(DOMAIN):
raise HTTPNotFound
try:
asset_id, size, mime_type_base, mime_type_format = location.split("/")
except ValueError as err:
raise HTTPNotFound from err
entry: ImmichConfigEntry | None = (
self.hass.config_entries.async_entry_for_domain_unique_id(
DOMAIN, source_dir_id
)
)
assert entry
immich_api = entry.runtime_data.api
# stream response for videos
if mime_type_base == "video":
try:
resp = await immich_api.assets.async_play_video_stream(asset_id)
except ImmichError as exc:
raise HTTPNotFound from exc
stream = ChunkAsyncStreamIterator(resp)
response = StreamResponse()
await response.prepare(request)
async for chunk in stream:
await response.write(chunk)
return response
# web response for images
try:
if size == "person":
image = await immich_api.people.async_get_person_thumbnail(asset_id)
else:
image = await immich_api.assets.async_view_asset(asset_id, size)
except ImmichError as exc:
raise HTTPNotFound from exc
return Response(body=image, content_type=f"{mime_type_base}/{mime_type_format}")
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/immich/media_source.py",
"license": "Apache License 2.0",
"lines": 313,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/immich/sensor.py | """Sensor platform for the Immich integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfInformation
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .coordinator import ImmichConfigEntry, ImmichData, ImmichDataUpdateCoordinator
from .entity import ImmichEntity
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class ImmichSensorEntityDescription(SensorEntityDescription):
"""Immich sensor entity description."""
value: Callable[[ImmichData], StateType]
is_suitable: Callable[[ImmichData], bool] = lambda _: True
SENSOR_TYPES: tuple[ImmichSensorEntityDescription, ...] = (
ImmichSensorEntityDescription(
key="disk_size",
translation_key="disk_size",
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES,
suggested_display_precision=1,
device_class=SensorDeviceClass.DATA_SIZE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
value=lambda data: data.server_storage.disk_size_raw,
),
ImmichSensorEntityDescription(
key="disk_available",
translation_key="disk_available",
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES,
suggested_display_precision=1,
device_class=SensorDeviceClass.DATA_SIZE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
value=lambda data: data.server_storage.disk_available_raw,
),
ImmichSensorEntityDescription(
key="disk_use",
translation_key="disk_use",
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES,
suggested_display_precision=1,
device_class=SensorDeviceClass.DATA_SIZE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
value=lambda data: data.server_storage.disk_use_raw,
entity_registry_enabled_default=False,
),
ImmichSensorEntityDescription(
key="disk_usage",
translation_key="disk_usage",
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
value=lambda data: data.server_storage.disk_usage_percentage,
entity_registry_enabled_default=False,
),
ImmichSensorEntityDescription(
key="photos_count",
translation_key="photos_count",
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
value=lambda data: data.server_usage.photos if data.server_usage else None,
is_suitable=lambda data: data.server_usage is not None,
),
ImmichSensorEntityDescription(
key="videos_count",
translation_key="videos_count",
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
value=lambda data: data.server_usage.videos if data.server_usage else None,
is_suitable=lambda data: data.server_usage is not None,
),
ImmichSensorEntityDescription(
key="usage_by_photos",
translation_key="usage_by_photos",
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES,
suggested_display_precision=1,
device_class=SensorDeviceClass.DATA_SIZE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
value=lambda d: d.server_usage.usage_photos if d.server_usage else None,
is_suitable=lambda data: data.server_usage is not None,
entity_registry_enabled_default=False,
),
ImmichSensorEntityDescription(
key="usage_by_videos",
translation_key="usage_by_videos",
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES,
suggested_display_precision=1,
device_class=SensorDeviceClass.DATA_SIZE,
state_class=SensorStateClass.MEASUREMENT,
entity_category=EntityCategory.DIAGNOSTIC,
value=lambda d: d.server_usage.usage_videos if d.server_usage else None,
is_suitable=lambda data: data.server_usage is not None,
entity_registry_enabled_default=False,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: ImmichConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add immich server state sensors."""
coordinator = entry.runtime_data
async_add_entities(
ImmichSensorEntity(coordinator, description)
for description in SENSOR_TYPES
if description.is_suitable(coordinator.data)
)
class ImmichSensorEntity(ImmichEntity, SensorEntity):
"""Define Immich sensor entity."""
entity_description: ImmichSensorEntityDescription
def __init__(
self,
coordinator: ImmichDataUpdateCoordinator,
description: ImmichSensorEntityDescription,
) -> None:
"""Initialize."""
super().__init__(coordinator)
self._attr_unique_id = f"{coordinator.config_entry.unique_id}_{description.key}"
self.entity_description = description
@property
def native_value(self) -> StateType:
"""Return the value reported by the sensor."""
return self.entity_description.value(self.coordinator.data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/immich/sensor.py",
"license": "Apache License 2.0",
"lines": 138,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/iqvia/coordinator.py | """Support for IQVIA."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from datetime import timedelta
from typing import Any
from pyiqvia.errors import IQVIAError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import LOGGER
DEFAULT_SCAN_INTERVAL = timedelta(minutes=30)
type IqviaConfigEntry = ConfigEntry[dict[str, IqviaUpdateCoordinator]]
class IqviaUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]):
"""Custom DataUpdateCoordinator for IQVIA."""
config_entry: IqviaConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: IqviaConfigEntry,
name: str,
update_method: Callable[[], Coroutine[Any, Any, dict[str, Any]]],
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
LOGGER,
name=name,
config_entry=config_entry,
update_interval=DEFAULT_SCAN_INTERVAL,
)
self._update_method = update_method
async def _async_update_data(self) -> dict[str, Any]:
"""Fetch data from the API."""
try:
return await self._update_method()
except IQVIAError as err:
raise UpdateFailed from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/iqvia/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/jewish_calendar/diagnostics.py | """Diagnostics support for Jewish Calendar integration."""
from dataclasses import asdict
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.core import HomeAssistant
from .const import CONF_ALTITUDE
from .entity import JewishCalendarConfigEntry
TO_REDACT = [
CONF_ALTITUDE,
CONF_LATITUDE,
CONF_LONGITUDE,
]
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: JewishCalendarConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return {
"entry_data": async_redact_data(entry.data, TO_REDACT),
"data": async_redact_data(asdict(entry.runtime_data.data), TO_REDACT),
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/jewish_calendar/diagnostics.py",
"license": "Apache License 2.0",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/miele/vacuum.py | """Platform for Miele vacuum integration."""
from __future__ import annotations
from dataclasses import dataclass
from enum import IntEnum
import logging
from typing import Any, Final
from aiohttp import ClientResponseError
from pymiele import MieleEnum
from homeassistant.components.vacuum import (
StateVacuumEntity,
StateVacuumEntityDescription,
VacuumActivity,
VacuumEntityFeature,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN, PROCESS_ACTION, PROGRAM_ID, MieleActions, MieleAppliance
from .coordinator import MieleConfigEntry
from .entity import MieleEntity
PARALLEL_UPDATES = 1
_LOGGER = logging.getLogger(__name__)
# The following const classes define program speeds and programs for the vacuum cleaner.
# Miele have used the same and overlapping names for fan_speeds and programs even
# if the contexts are different. This is an attempt to make it clearer in the integration.
class FanSpeed(IntEnum):
"""Define fan speeds."""
normal = 0
turbo = 1
silent = 2
class FanProgram(IntEnum):
"""Define fan programs."""
auto = 1
spot = 2
turbo = 3
silent = 4
PROGRAM_MAP = {
"normal": FanProgram.auto,
"turbo": FanProgram.turbo,
"silent": FanProgram.silent,
}
PROGRAM_TO_SPEED: dict[int, str] = {
FanProgram.auto: "normal",
FanProgram.turbo: "turbo",
FanProgram.silent: "silent",
FanProgram.spot: "normal",
}
class MieleVacuumStateCode(MieleEnum, missing_to_none=True):
"""Define vacuum state codes."""
idle = 0
cleaning = 5889
returning = 5890
paused = 5891
going_to_target_area = 5892
wheel_lifted = 5893
dirty_sensors = 5894
dust_box_missing = 5895
blocked_drive_wheels = 5896
blocked_brushes = 5897
check_dust_box_and_filter = 5898
internal_fault_reboot = 5899
blocked_front_wheel = 5900
docked = 5903, 5904
remote_controlled = 5910
SUPPORTED_FEATURES = (
VacuumEntityFeature.STATE
| VacuumEntityFeature.FAN_SPEED
| VacuumEntityFeature.START
| VacuumEntityFeature.STOP
| VacuumEntityFeature.PAUSE
| VacuumEntityFeature.CLEAN_SPOT
)
@dataclass(frozen=True, kw_only=True)
class MieleVacuumDescription(StateVacuumEntityDescription):
"""Class describing Miele vacuum entities."""
on_value: int
@dataclass
class MieleVacuumDefinition:
"""Class for defining vacuum entities."""
types: tuple[MieleAppliance, ...]
description: MieleVacuumDescription
VACUUM_TYPES: Final[tuple[MieleVacuumDefinition, ...]] = (
MieleVacuumDefinition(
types=(MieleAppliance.ROBOT_VACUUM_CLEANER,),
description=MieleVacuumDescription(
key="vacuum",
on_value=14,
name=None,
translation_key="vacuum",
),
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: MieleConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the vacuum platform."""
coordinator = config_entry.runtime_data.coordinator
async_add_entities(
MieleVacuum(coordinator, device_id, definition.description)
for device_id, device in coordinator.data.devices.items()
for definition in VACUUM_TYPES
if device.device_type in definition.types
)
VACUUM_PHASE_TO_ACTIVITY = {
MieleVacuumStateCode.idle.value: VacuumActivity.IDLE,
MieleVacuumStateCode.docked.value: VacuumActivity.DOCKED,
MieleVacuumStateCode.cleaning.value: VacuumActivity.CLEANING,
MieleVacuumStateCode.going_to_target_area.value: VacuumActivity.CLEANING,
MieleVacuumStateCode.returning.value: VacuumActivity.RETURNING,
MieleVacuumStateCode.wheel_lifted.value: VacuumActivity.ERROR,
MieleVacuumStateCode.dirty_sensors.value: VacuumActivity.ERROR,
MieleVacuumStateCode.dust_box_missing.value: VacuumActivity.ERROR,
MieleVacuumStateCode.blocked_drive_wheels.value: VacuumActivity.ERROR,
MieleVacuumStateCode.blocked_brushes.value: VacuumActivity.ERROR,
MieleVacuumStateCode.check_dust_box_and_filter.value: VacuumActivity.ERROR,
MieleVacuumStateCode.internal_fault_reboot.value: VacuumActivity.ERROR,
MieleVacuumStateCode.blocked_front_wheel.value: VacuumActivity.ERROR,
MieleVacuumStateCode.paused.value: VacuumActivity.PAUSED,
MieleVacuumStateCode.remote_controlled.value: VacuumActivity.PAUSED,
}
class MieleVacuum(MieleEntity, StateVacuumEntity):
"""Representation of a Vacuum entity."""
entity_description: MieleVacuumDescription
_attr_supported_features = SUPPORTED_FEATURES
_attr_fan_speed_list = [fan_speed.name for fan_speed in FanSpeed]
_attr_name = None
@property
def activity(self) -> VacuumActivity | None:
"""Return activity."""
return VACUUM_PHASE_TO_ACTIVITY.get(
MieleVacuumStateCode(self.device.state_program_phase).value
)
@property
def fan_speed(self) -> str | None:
"""Return the fan speed."""
return PROGRAM_TO_SPEED.get(self.device.state_program_id)
@property
def available(self) -> bool:
"""Return the availability of the entity."""
return (
self.action.power_off_enabled or self.action.power_on_enabled
) and super().available
async def send(self, device_id: str, action: dict[str, Any]) -> None:
"""Send action to the device."""
try:
await self.api.send_action(device_id, action)
except ClientResponseError as err:
_LOGGER.debug("Error setting vacuum state for %s: %s", self.entity_id, err)
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="set_state_error",
translation_placeholders={
"entity": self.entity_id,
},
) from err
async def async_clean_spot(self, **kwargs: Any) -> None:
"""Clean spot."""
await self.send(self._device_id, {PROGRAM_ID: FanProgram.spot})
async def async_start(self, **kwargs: Any) -> None:
"""Start cleaning."""
await self.send(self._device_id, {PROCESS_ACTION: MieleActions.START})
async def async_stop(self, **kwargs: Any) -> None:
"""Stop cleaning."""
await self.send(self._device_id, {PROCESS_ACTION: MieleActions.STOP})
async def async_pause(self, **kwargs: Any) -> None:
"""Pause cleaning."""
await self.send(self._device_id, {PROCESS_ACTION: MieleActions.PAUSE})
async def async_set_fan_speed(self, fan_speed: str, **kwargs: Any) -> None:
"""Set fan speed."""
await self.send(self._device_id, {PROGRAM_ID: PROGRAM_MAP[fan_speed]})
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/miele/vacuum.py",
"license": "Apache License 2.0",
"lines": 172,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/paperless_ngx/config_flow.py | """Config flow for the Paperless-ngx integration."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from pypaperless import Paperless
from pypaperless.exceptions import (
InitializationError,
PaperlessConnectionError,
PaperlessForbiddenError,
PaperlessInactiveOrDeletedError,
PaperlessInvalidTokenError,
)
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DOMAIN, LOGGER
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_URL): str,
vol.Required(CONF_API_KEY): str,
vol.Required(CONF_VERIFY_SSL, default=True): bool,
}
)
class PaperlessConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Paperless-ngx."""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
self._async_abort_entries_match(
{
CONF_URL: user_input[CONF_URL],
CONF_API_KEY: user_input[CONF_API_KEY],
}
)
errors = await self._validate_input(user_input)
if not errors:
return self.async_create_entry(
title=user_input[CONF_URL], data=user_input
)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Reconfigure flow for Paperless-ngx integration."""
entry = self._get_reconfigure_entry()
errors: dict[str, str] = {}
if user_input is not None:
self._async_abort_entries_match(
{
CONF_URL: user_input[CONF_URL],
CONF_API_KEY: user_input[CONF_API_KEY],
}
)
errors = await self._validate_input(user_input)
if not errors:
return self.async_update_reload_and_abort(entry, data=user_input)
if user_input is not None:
suggested_values = user_input
else:
suggested_values = {
CONF_URL: entry.data[CONF_URL],
CONF_VERIFY_SSL: entry.data.get(CONF_VERIFY_SSL, True),
}
return self.async_show_form(
step_id="reconfigure",
data_schema=self.add_suggested_values_to_schema(
data_schema=STEP_USER_DATA_SCHEMA,
suggested_values=suggested_values,
),
errors=errors,
)
async def async_step_reauth(
self, user_input: Mapping[str, Any]
) -> ConfigFlowResult:
"""Handle re-auth."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Reauth flow for Paperless-ngx integration."""
entry = self._get_reauth_entry()
errors: dict[str, str] = {}
if user_input is not None:
updated_data = {**entry.data, CONF_API_KEY: user_input[CONF_API_KEY]}
errors = await self._validate_input(updated_data)
if not errors:
return self.async_update_reload_and_abort(
entry,
data=updated_data,
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=vol.Schema({vol.Required(CONF_API_KEY): str}),
errors=errors,
)
async def _validate_input(self, user_input: dict[str, Any]) -> dict[str, str]:
errors: dict[str, str] = {}
client = Paperless(
user_input[CONF_URL],
user_input[CONF_API_KEY],
session=async_get_clientsession(
self.hass, user_input.get(CONF_VERIFY_SSL, True)
),
)
try:
await client.initialize()
await client.statistics() # test permissions on api
except PaperlessConnectionError:
errors[CONF_URL] = "cannot_connect"
except PaperlessInvalidTokenError:
errors[CONF_API_KEY] = "invalid_api_key"
except PaperlessInactiveOrDeletedError:
errors[CONF_API_KEY] = "user_inactive_or_deleted"
except PaperlessForbiddenError:
errors[CONF_API_KEY] = "forbidden"
except InitializationError:
errors[CONF_URL] = "cannot_connect"
except Exception as err: # noqa: BLE001
LOGGER.exception("Unexpected exception: %s", err)
errors["base"] = "unknown"
return errors
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/paperless_ngx/config_flow.py",
"license": "Apache License 2.0",
"lines": 127,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/paperless_ngx/coordinator.py | """Paperless-ngx Status coordinator."""
from __future__ import annotations
from abc import abstractmethod
from dataclasses import dataclass
from datetime import timedelta
from pypaperless import Paperless
from pypaperless.exceptions import (
PaperlessConnectionError,
PaperlessForbiddenError,
PaperlessInactiveOrDeletedError,
PaperlessInvalidTokenError,
)
from pypaperless.models import Statistic, Status
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN, LOGGER
type PaperlessConfigEntry = ConfigEntry[PaperlessData]
UPDATE_INTERVAL_STATISTICS = timedelta(seconds=120)
UPDATE_INTERVAL_STATUS = timedelta(seconds=300)
@dataclass
class PaperlessData:
"""Data for the Paperless-ngx integration."""
statistics: PaperlessStatisticCoordinator
status: PaperlessStatusCoordinator
class PaperlessCoordinator[DataT](DataUpdateCoordinator[DataT]):
"""Coordinator to manage fetching Paperless-ngx API."""
config_entry: PaperlessConfigEntry
def __init__(
self,
hass: HomeAssistant,
entry: PaperlessConfigEntry,
api: Paperless,
name: str,
update_interval: timedelta,
) -> None:
"""Initialize Paperless-ngx statistics coordinator."""
self.api = api
super().__init__(
hass,
LOGGER,
config_entry=entry,
name=name,
update_interval=update_interval,
)
async def _async_update_data(self) -> DataT:
"""Update data via internal method."""
try:
return await self._async_update_data_internal()
except PaperlessConnectionError as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="cannot_connect",
) from err
except PaperlessInvalidTokenError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="invalid_api_key",
) from err
except PaperlessInactiveOrDeletedError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="user_inactive_or_deleted",
) from err
except PaperlessForbiddenError as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="forbidden",
) from err
@abstractmethod
async def _async_update_data_internal(self) -> DataT:
"""Update data via paperless-ngx API."""
class PaperlessStatisticCoordinator(PaperlessCoordinator[Statistic]):
"""Coordinator to manage Paperless-ngx statistic updates."""
def __init__(
self,
hass: HomeAssistant,
entry: PaperlessConfigEntry,
api: Paperless,
) -> None:
"""Initialize Paperless-ngx status coordinator."""
super().__init__(
hass,
entry,
api,
name="Statistics Coordinator",
update_interval=UPDATE_INTERVAL_STATISTICS,
)
async def _async_update_data_internal(self) -> Statistic:
"""Fetch statistics data from API endpoint."""
return await self.api.statistics()
class PaperlessStatusCoordinator(PaperlessCoordinator[Status]):
"""Coordinator to manage Paperless-ngx status updates."""
def __init__(
self,
hass: HomeAssistant,
entry: PaperlessConfigEntry,
api: Paperless,
) -> None:
"""Initialize Paperless-ngx status coordinator."""
super().__init__(
hass,
entry,
api,
name="Status Coordinator",
update_interval=UPDATE_INTERVAL_STATUS,
)
async def _async_update_data_internal(self) -> Status:
"""Fetch status data from API endpoint."""
return await self.api.status()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/paperless_ngx/coordinator.py",
"license": "Apache License 2.0",
"lines": 111,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/paperless_ngx/diagnostics.py | """Diagnostics support for Paperless-ngx."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from homeassistant.core import HomeAssistant
from . import PaperlessConfigEntry
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: PaperlessConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return {
"pngx_version": entry.runtime_data.status.api.host_version,
"data": {
"statistics": asdict(entry.runtime_data.statistics.data),
"status": asdict(entry.runtime_data.status.data),
},
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/paperless_ngx/diagnostics.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/paperless_ngx/entity.py | """Paperless-ngx base entity."""
from __future__ import annotations
from homeassistant.components.sensor import EntityDescription
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import PaperlessCoordinator
class PaperlessEntity[CoordinatorT: PaperlessCoordinator](
CoordinatorEntity[CoordinatorT]
):
"""Defines a base Paperless-ngx entity."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: CoordinatorT,
description: EntityDescription,
) -> None:
"""Initialize the Paperless-ngx entity."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.config_entry.entry_id}_{description.key}"
self._attr_device_info = DeviceInfo(
entry_type=DeviceEntryType.SERVICE,
identifiers={(DOMAIN, coordinator.config_entry.entry_id)},
manufacturer="Paperless-ngx",
sw_version=coordinator.api.host_version,
configuration_url=coordinator.api.base_url,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/paperless_ngx/entity.py",
"license": "Apache License 2.0",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/paperless_ngx/sensor.py | """Sensor platform for Paperless-ngx."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from pypaperless.models import Statistic, Status
from pypaperless.models.common import StatusType
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import EntityCategory, UnitOfInformation
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.util.unit_conversion import InformationConverter
from .coordinator import (
PaperlessConfigEntry,
PaperlessCoordinator,
PaperlessStatisticCoordinator,
PaperlessStatusCoordinator,
)
from .entity import PaperlessEntity
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class PaperlessEntityDescription[DataT](SensorEntityDescription):
"""Describes Paperless-ngx sensor entity."""
value_fn: Callable[[DataT], StateType]
SENSOR_STATISTICS: tuple[PaperlessEntityDescription[Statistic], ...] = (
PaperlessEntityDescription[Statistic](
key="documents_total",
translation_key="documents_total",
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.documents_total,
),
PaperlessEntityDescription[Statistic](
key="documents_inbox",
translation_key="documents_inbox",
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.documents_inbox,
),
PaperlessEntityDescription[Statistic](
key="characters_count",
translation_key="characters_count",
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.character_count,
entity_registry_enabled_default=False,
),
PaperlessEntityDescription[Statistic](
key="tag_count",
translation_key="tag_count",
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.tag_count,
entity_registry_enabled_default=False,
),
PaperlessEntityDescription[Statistic](
key="correspondent_count",
translation_key="correspondent_count",
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.correspondent_count,
entity_registry_enabled_default=False,
),
PaperlessEntityDescription[Statistic](
key="document_type_count",
translation_key="document_type_count",
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.document_type_count,
entity_registry_enabled_default=False,
),
)
SENSOR_STATUS: tuple[PaperlessEntityDescription[Status], ...] = (
PaperlessEntityDescription[Status](
key="storage_total",
translation_key="storage_total",
state_class=SensorStateClass.MEASUREMENT,
device_class=SensorDeviceClass.DATA_SIZE,
native_unit_of_measurement=UnitOfInformation.GIGABYTES,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=(
lambda data: (
round(
InformationConverter().convert(
data.storage.total,
UnitOfInformation.BYTES,
UnitOfInformation.GIGABYTES,
),
2,
)
if data.storage is not None and data.storage.total is not None
else None
)
),
),
PaperlessEntityDescription[Status](
key="storage_available",
translation_key="storage_available",
state_class=SensorStateClass.MEASUREMENT,
device_class=SensorDeviceClass.DATA_SIZE,
native_unit_of_measurement=UnitOfInformation.GIGABYTES,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=(
lambda data: (
round(
InformationConverter().convert(
data.storage.available,
UnitOfInformation.BYTES,
UnitOfInformation.GIGABYTES,
),
2,
)
if data.storage is not None and data.storage.available is not None
else None
)
),
),
PaperlessEntityDescription[Status](
key="database_status",
translation_key="database_status",
device_class=SensorDeviceClass.ENUM,
entity_category=EntityCategory.DIAGNOSTIC,
options=[
item.value.lower() for item in StatusType if item != StatusType.UNKNOWN
],
value_fn=(
lambda data: (
data.database.status.value.lower()
if (
data.database is not None
and data.database.status is not None
and data.database.status != StatusType.UNKNOWN
)
else None
)
),
),
PaperlessEntityDescription[Status](
key="index_status",
translation_key="index_status",
device_class=SensorDeviceClass.ENUM,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
options=[
item.value.lower() for item in StatusType if item != StatusType.UNKNOWN
],
value_fn=(
lambda data: (
data.tasks.index_status.value.lower()
if (
data.tasks is not None
and data.tasks.index_status is not None
and data.tasks.index_status != StatusType.UNKNOWN
)
else None
)
),
),
PaperlessEntityDescription[Status](
key="classifier_status",
translation_key="classifier_status",
device_class=SensorDeviceClass.ENUM,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
options=[
item.value.lower() for item in StatusType if item != StatusType.UNKNOWN
],
value_fn=(
lambda data: (
data.tasks.classifier_status.value.lower()
if (
data.tasks is not None
and data.tasks.classifier_status is not None
and data.tasks.classifier_status != StatusType.UNKNOWN
)
else None
)
),
),
PaperlessEntityDescription[Status](
key="celery_status",
translation_key="celery_status",
device_class=SensorDeviceClass.ENUM,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
options=[
item.value.lower() for item in StatusType if item != StatusType.UNKNOWN
],
value_fn=(
lambda data: (
data.tasks.celery_status.value.lower()
if (
data.tasks is not None
and data.tasks.celery_status is not None
and data.tasks.celery_status != StatusType.UNKNOWN
)
else None
)
),
),
PaperlessEntityDescription[Status](
key="redis_status",
translation_key="redis_status",
device_class=SensorDeviceClass.ENUM,
entity_category=EntityCategory.DIAGNOSTIC,
options=[
item.value.lower() for item in StatusType if item != StatusType.UNKNOWN
],
value_fn=(
lambda data: (
data.tasks.redis_status.value.lower()
if (
data.tasks is not None
and data.tasks.redis_status is not None
and data.tasks.redis_status != StatusType.UNKNOWN
)
else None
)
),
),
PaperlessEntityDescription[Status](
key="sanity_check_status",
translation_key="sanity_check_status",
device_class=SensorDeviceClass.ENUM,
entity_category=EntityCategory.DIAGNOSTIC,
options=[
item.value.lower() for item in StatusType if item != StatusType.UNKNOWN
],
value_fn=(
lambda data: (
data.tasks.sanity_check_status.value.lower()
if (
data.tasks is not None
and data.tasks.sanity_check_status is not None
and data.tasks.sanity_check_status != StatusType.UNKNOWN
)
else None
)
),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: PaperlessConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Paperless-ngx sensors."""
entities: list[PaperlessSensor] = []
entities += [
PaperlessSensor[PaperlessStatisticCoordinator](
coordinator=entry.runtime_data.statistics,
description=description,
)
for description in SENSOR_STATISTICS
]
entities += [
PaperlessSensor[PaperlessStatusCoordinator](
coordinator=entry.runtime_data.status,
description=description,
)
for description in SENSOR_STATUS
]
async_add_entities(entities)
class PaperlessSensor[CoordinatorT: PaperlessCoordinator](
PaperlessEntity[CoordinatorT], SensorEntity
):
"""Defines a Paperless-ngx sensor entity."""
entity_description: PaperlessEntityDescription
@property
def native_value(self) -> StateType:
"""Return the current value of the sensor."""
return self.entity_description.value_fn(self.coordinator.data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/paperless_ngx/sensor.py",
"license": "Apache License 2.0",
"lines": 271,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/probe_plus/config_flow.py | """Config flow for probe_plus integration."""
from __future__ import annotations
import dataclasses
import logging
from typing import Any
import voluptuous as vol
from homeassistant.components.bluetooth import (
BluetoothServiceInfo,
async_discovered_service_info,
)
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_ADDRESS, CONF_MODEL
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
@dataclasses.dataclass(frozen=True)
class Discovery:
"""Represents a discovered Bluetooth device.
Attributes:
title: The name or title of the discovered device.
discovery_info: Information about the discovered device.
"""
title: str
discovery_info: BluetoothServiceInfo
def title(discovery_info: BluetoothServiceInfo) -> str:
"""Return a title for the discovered device."""
return f"{discovery_info.name} {discovery_info.address}"
class ProbeConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for BT Probe."""
def __init__(self) -> None:
"""Initialize the config flow."""
self._discovered_devices: dict[str, Discovery] = {}
async def async_step_bluetooth(
self, discovery_info: BluetoothServiceInfo
) -> ConfigFlowResult:
"""Handle the bluetooth discovery step."""
_LOGGER.debug("Discovered BT device: %s", discovery_info)
await self.async_set_unique_id(discovery_info.address)
self._abort_if_unique_id_configured()
self.context["title_placeholders"] = {"name": title(discovery_info)}
self._discovered_devices[discovery_info.address] = Discovery(
title(discovery_info), discovery_info
)
return await self.async_step_bluetooth_confirm()
async def async_step_bluetooth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the bluetooth confirmation step."""
if user_input is not None:
assert self.unique_id
self._abort_if_unique_id_configured()
discovery = self._discovered_devices[self.unique_id]
return self.async_create_entry(
title=discovery.title,
data={
CONF_ADDRESS: discovery.discovery_info.address,
CONF_MODEL: discovery.discovery_info.name,
},
)
self._set_confirm_only()
assert self.unique_id
return self.async_show_form(
step_id="bluetooth_confirm",
description_placeholders={
"name": title(self._discovered_devices[self.unique_id].discovery_info)
},
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the user step to pick discovered device."""
if user_input is not None:
address = user_input[CONF_ADDRESS]
await self.async_set_unique_id(address, raise_on_progress=False)
self._abort_if_unique_id_configured()
discovery = self._discovered_devices[address]
return self.async_create_entry(
title=discovery.title,
data={**user_input, CONF_MODEL: discovery.discovery_info.name},
)
current_addresses = self._async_current_ids(include_ignore=False)
for discovery_info in async_discovered_service_info(self.hass):
address = discovery_info.address
if address in current_addresses or address in self._discovered_devices:
continue
self._discovered_devices[address] = Discovery(
title(discovery_info), discovery_info
)
if not self._discovered_devices:
return self.async_abort(reason="no_devices_found")
titles = {
address: discovery.title
for (address, discovery) in self._discovered_devices.items()
}
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_ADDRESS): vol.In(titles),
}
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/probe_plus/config_flow.py",
"license": "Apache License 2.0",
"lines": 101,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/probe_plus/coordinator.py | """Coordinator for the probe_plus integration."""
from __future__ import annotations
from datetime import timedelta
import logging
from pyprobeplus import ProbePlusDevice
from pyprobeplus.exceptions import ProbePlusDeviceNotFound, ProbePlusError
from homeassistant.components import bluetooth
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ADDRESS
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import DOMAIN
type ProbePlusConfigEntry = ConfigEntry[ProbePlusDataUpdateCoordinator]
_LOGGER = logging.getLogger(__name__)
SCAN_INTERVAL = timedelta(seconds=15)
class ProbePlusDataUpdateCoordinator(DataUpdateCoordinator[None]):
"""Coordinator to manage data updates for a probe device.
This class handles the communication with Probe Plus devices.
Data is updated by the device itself.
"""
config_entry: ProbePlusConfigEntry
def __init__(self, hass: HomeAssistant, entry: ProbePlusConfigEntry) -> None:
"""Initialize coordinator."""
super().__init__(
hass,
_LOGGER,
name="ProbePlusDataUpdateCoordinator",
update_interval=SCAN_INTERVAL,
config_entry=entry,
)
available_scanners = bluetooth.async_scanner_count(hass, connectable=True)
if available_scanners == 0:
raise ConfigEntryNotReady(
translation_domain=DOMAIN,
translation_key="no_bleak_scanner",
)
self.device: ProbePlusDevice = ProbePlusDevice(
address_or_ble_device=entry.data[CONF_ADDRESS],
scanner=bluetooth.async_get_scanner(hass),
name=entry.title,
notify_callback=self.async_update_listeners,
)
async def _async_update_data(self) -> None:
"""Connect to the Probe Plus device on a set interval.
This method is called periodically to reconnect to the device
Data updates are handled by the device itself.
"""
# Already connected, no need to update any data as the device streams this.
if self.device.connected:
return
# Probe is not connected, try to connect
try:
await self.device.connect()
except (ProbePlusError, ProbePlusDeviceNotFound, TimeoutError) as e:
_LOGGER.debug(
"Could not connect to scale: %s, Error: %s",
self.config_entry.data[CONF_ADDRESS],
e,
)
self.device.device_disconnected_handler(notify=False)
return
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/probe_plus/coordinator.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/probe_plus/entity.py | """Probe Plus base entity type."""
from dataclasses import dataclass
from pyprobeplus import ProbePlusDevice
from homeassistant.const import CONF_MODEL
from homeassistant.helpers.device_registry import (
CONNECTION_BLUETOOTH,
DeviceInfo,
format_mac,
)
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import ProbePlusDataUpdateCoordinator
@dataclass
class ProbePlusEntity(CoordinatorEntity[ProbePlusDataUpdateCoordinator]):
"""Base class for Probe Plus entities."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: ProbePlusDataUpdateCoordinator,
entity_description: EntityDescription,
) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
self.entity_description = entity_description
# Set the unique ID for the entity
self._attr_unique_id = (
f"{format_mac(coordinator.device.mac)}_{entity_description.key}"
)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, format_mac(coordinator.device.mac))},
name=coordinator.device.name,
manufacturer="Probe Plus",
suggested_area="Kitchen",
model=coordinator.config_entry.data.get(CONF_MODEL),
connections={(CONNECTION_BLUETOOTH, coordinator.device.mac)},
)
@property
def available(self) -> bool:
"""Return True if the entity is available."""
return super().available and self.coordinator.device.connected
@property
def device(self) -> ProbePlusDevice:
"""Return the device associated with this entity."""
return self.coordinator.device
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/probe_plus/entity.py",
"license": "Apache License 2.0",
"lines": 45,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/probe_plus/sensor.py | """Support for Probe Plus BLE sensors."""
from collections.abc import Callable
from dataclasses import dataclass
from homeassistant.components.sensor import (
RestoreSensor,
SensorDeviceClass,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import (
PERCENTAGE,
SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
EntityCategory,
UnitOfElectricPotential,
UnitOfTemperature,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import ProbePlusConfigEntry, ProbePlusDevice
from .entity import ProbePlusEntity
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
@dataclass(kw_only=True, frozen=True)
class ProbePlusSensorEntityDescription(SensorEntityDescription):
"""Description for Probe Plus sensor entities."""
value_fn: Callable[[ProbePlusDevice], int | float | None]
SENSOR_DESCRIPTIONS: tuple[ProbePlusSensorEntityDescription, ...] = (
ProbePlusSensorEntityDescription(
key="probe_temperature",
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
value_fn=lambda device: device.device_state.probe_temperature,
device_class=SensorDeviceClass.TEMPERATURE,
),
ProbePlusSensorEntityDescription(
key="probe_battery",
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=PERCENTAGE,
value_fn=lambda device: device.device_state.probe_battery,
device_class=SensorDeviceClass.BATTERY,
),
ProbePlusSensorEntityDescription(
key="relay_battery",
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=PERCENTAGE,
value_fn=lambda device: device.device_state.relay_battery,
device_class=SensorDeviceClass.BATTERY,
),
ProbePlusSensorEntityDescription(
key="probe_rssi",
device_class=SensorDeviceClass.SIGNAL_STRENGTH,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda device: device.device_state.probe_rssi,
entity_registry_enabled_default=False,
),
ProbePlusSensorEntityDescription(
key="relay_voltage",
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.VOLTAGE,
value_fn=lambda device: device.device_state.relay_voltage,
entity_registry_enabled_default=False,
),
ProbePlusSensorEntityDescription(
key="probe_voltage",
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.VOLTAGE,
value_fn=lambda device: device.device_state.probe_voltage,
entity_registry_enabled_default=False,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: ProbePlusConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Probe Plus sensors."""
coordinator = entry.runtime_data
async_add_entities(ProbeSensor(coordinator, desc) for desc in SENSOR_DESCRIPTIONS)
class ProbeSensor(ProbePlusEntity, RestoreSensor):
"""Representation of a Probe Plus sensor."""
entity_description: ProbePlusSensorEntityDescription
@property
def native_value(self) -> int | float | None:
"""Return the state of the sensor."""
return self.entity_description.value_fn(self.device)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/probe_plus/sensor.py",
"license": "Apache License 2.0",
"lines": 91,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ps4/services.py | """Support for PlayStation 4 consoles."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import ATTR_COMMAND, ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant, ServiceCall, callback
from homeassistant.helpers import config_validation as cv
from .const import COMMANDS, DOMAIN, PS4_DATA
SERVICE_COMMAND = "send_command"
PS4_COMMAND_SCHEMA = vol.Schema(
{
vol.Required(ATTR_ENTITY_ID): cv.entity_ids,
vol.Required(ATTR_COMMAND): vol.In(list(COMMANDS)),
}
)
async def async_service_command(call: ServiceCall) -> None:
"""Service for sending commands."""
entity_ids = call.data[ATTR_ENTITY_ID]
command = call.data[ATTR_COMMAND]
for device in call.hass.data[PS4_DATA].devices:
if device.entity_id in entity_ids:
await device.async_send_command(command)
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Handle for services."""
hass.services.async_register(
DOMAIN, SERVICE_COMMAND, async_service_command, schema=PS4_COMMAND_SCHEMA
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ps4/services.py",
"license": "Apache License 2.0",
"lines": 27,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/qbus/scene.py | """Support for Qbus scene."""
from typing import Any
from qbusmqttapi.discovery import QbusMqttOutput
from qbusmqttapi.state import QbusMqttState, StateAction, StateType
from homeassistant.components.scene import BaseScene
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import QbusConfigEntry
from .entity import QbusEntity, create_new_entities
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
entry: QbusConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up scene entities."""
coordinator = entry.runtime_data
added_outputs: list[QbusMqttOutput] = []
def _check_outputs() -> None:
entities = create_new_entities(
coordinator,
added_outputs,
lambda output: output.type == "scene",
QbusScene,
)
async_add_entities(entities)
_check_outputs()
entry.async_on_unload(coordinator.async_add_listener(_check_outputs))
class QbusScene(QbusEntity, BaseScene):
"""Representation of a Qbus scene entity."""
def __init__(self, mqtt_output: QbusMqttOutput) -> None:
"""Initialize scene entity."""
super().__init__(mqtt_output, link_to_main_device=True)
self._attr_name = mqtt_output.name.title()
async def _async_activate(self, **kwargs: Any) -> None:
"""Activate scene."""
state = QbusMqttState(
id=self._mqtt_output.id, type=StateType.ACTION, action=StateAction.ACTIVE
)
await self._async_publish_output_state(state)
async def _handle_state_received(self, state: QbusMqttState) -> None:
self._async_record_activation()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/qbus/scene.py",
"license": "Apache License 2.0",
"lines": 42,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/rehlko/binary_sensor.py | """Binary sensor platform for Rehlko integration."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import (
DEVICE_DATA_DEVICES,
DEVICE_DATA_ID,
DEVICE_DATA_IS_CONNECTED,
GENERATOR_DATA_DEVICE,
)
from .coordinator import RehlkoConfigEntry
from .entity import RehlkoEntity
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
_LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True, kw_only=True)
class RehlkoBinarySensorEntityDescription(BinarySensorEntityDescription):
"""Class describing Rehlko binary sensor entities."""
on_value: str | bool = True
off_value: str | bool = False
document_key: str | None = None
connectivity_key: str | None = DEVICE_DATA_IS_CONNECTED
BINARY_SENSORS: tuple[RehlkoBinarySensorEntityDescription, ...] = (
RehlkoBinarySensorEntityDescription(
key=DEVICE_DATA_IS_CONNECTED,
device_class=BinarySensorDeviceClass.CONNECTIVITY,
entity_category=EntityCategory.DIAGNOSTIC,
document_key=GENERATOR_DATA_DEVICE,
# Entity is available when the device is disconnected
connectivity_key=None,
),
RehlkoBinarySensorEntityDescription(
key="switchState",
translation_key="auto_run",
on_value="Auto",
off_value="Off",
),
RehlkoBinarySensorEntityDescription(
key="engineOilPressureOk",
translation_key="oil_pressure",
device_class=BinarySensorDeviceClass.PROBLEM,
entity_category=EntityCategory.DIAGNOSTIC,
on_value=False,
off_value=True,
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: RehlkoConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the binary sensor platform."""
homes = config_entry.runtime_data.homes
coordinators = config_entry.runtime_data.coordinators
async_add_entities(
RehlkoBinarySensorEntity(
coordinators[device_data[DEVICE_DATA_ID]],
device_data[DEVICE_DATA_ID],
device_data,
sensor_description,
document_key=sensor_description.document_key,
connectivity_key=sensor_description.connectivity_key,
)
for home_data in homes
for device_data in home_data[DEVICE_DATA_DEVICES]
for sensor_description in BINARY_SENSORS
)
class RehlkoBinarySensorEntity(RehlkoEntity, BinarySensorEntity):
"""Representation of a Binary Sensor."""
entity_description: RehlkoBinarySensorEntityDescription
@property
def is_on(self) -> bool | None:
"""Return the state of the binary sensor."""
if self._rehlko_value == self.entity_description.on_value:
return True
if self._rehlko_value == self.entity_description.off_value:
return False
_LOGGER.warning(
"Unexpected value for %s: %s",
self.entity_description.key,
self._rehlko_value,
)
return None
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/rehlko/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 91,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/smarla/config_flow.py | """Config flow for Swing2Sleep Smarla integration."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from pysmarlaapi import Connection
from pysmarlaapi.connection.exceptions import (
AuthenticationException,
ConnectionException,
)
import voluptuous as vol
from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_ACCESS_TOKEN
from .const import DOMAIN, HOST
STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_ACCESS_TOKEN): str})
class SmarlaConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Swing2Sleep Smarla."""
VERSION = 1
def __init__(self) -> None:
"""Initialize the config flow."""
super().__init__()
self.errors: dict[str, str] = {}
async def _handle_token(self, token: str) -> str | None:
"""Handle the token input."""
try:
conn = Connection(url=HOST, token_b64=token)
except ValueError:
self.errors["base"] = "malformed_token"
return None
try:
await conn.refresh_token()
except ConnectionException:
self.errors["base"] = "cannot_connect"
return None
except AuthenticationException:
self.errors["base"] = "invalid_auth"
return None
return conn.token.serialNumber
async def _validate_input(
self, user_input: dict[str, Any]
) -> dict[str, Any] | None:
"""Validate the user input."""
token = user_input[CONF_ACCESS_TOKEN]
serial_number = await self._handle_token(token=token)
if serial_number is not None:
await self.async_set_unique_id(serial_number)
if self.source == SOURCE_REAUTH:
self._abort_if_unique_id_mismatch()
else:
self._abort_if_unique_id_configured()
return {"token": token, "serial_number": serial_number}
return None
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
self.errors = {}
if user_input is not None:
validated_info = await self._validate_input(user_input)
if validated_info is not None:
return self.async_create_entry(
title=validated_info["serial_number"],
data={CONF_ACCESS_TOKEN: validated_info["token"]},
)
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
errors=self.errors,
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauthentication upon an API authentication error."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauthentication dialog."""
self.errors = {}
if user_input is not None:
validated_info = await self._validate_input(user_input)
if validated_info is not None:
return self.async_update_reload_and_abort(
self._get_reauth_entry(),
data_updates={CONF_ACCESS_TOKEN: validated_info["token"]},
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=STEP_USER_DATA_SCHEMA,
errors=self.errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/smarla/config_flow.py",
"license": "Apache License 2.0",
"lines": 90,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.