sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
home-assistant/core:tests/components/homeassistant_connect_zbt2/test_config_flow.py | """Test the Home Assistant Connect ZBT-2 config flow."""
from collections.abc import Generator
from unittest.mock import AsyncMock, Mock, call, patch
import pytest
from homeassistant.components.homeassistant_connect_zbt2.const import DOMAIN
from homeassistant.components.homeassistant_hardware import (
DOMAIN as HOMEASSISTANT_HARDWARE_DOMAIN,
)
from homeassistant.components.homeassistant_hardware.firmware_config_flow import (
STEP_PICK_FIRMWARE_THREAD,
STEP_PICK_FIRMWARE_ZIGBEE,
)
from homeassistant.components.homeassistant_hardware.helpers import (
async_notify_firmware_info,
)
from homeassistant.components.homeassistant_hardware.util import (
ApplicationType,
FirmwareInfo,
ResetTarget,
)
from homeassistant.components.usb import DOMAIN as USB_DOMAIN, USBDevice
from homeassistant.config_entries import ConfigFlowResult
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.usb import UsbServiceInfo
from homeassistant.setup import async_setup_component
from .common import USB_DATA_ZBT2
from tests.common import MockConfigEntry
@pytest.fixture(name="supervisor")
def mock_supervisor_fixture() -> Generator[None]:
"""Mock Supervisor."""
with patch(
"homeassistant.components.homeassistant_hardware.firmware_config_flow.is_hassio",
return_value=True,
):
yield
@pytest.fixture(name="setup_entry", autouse=True)
def setup_entry_fixture() -> Generator[AsyncMock]:
"""Mock entry setup."""
with patch(
"homeassistant.components.homeassistant_connect_zbt2.async_setup_entry",
return_value=True,
) as mock_setup_entry:
yield mock_setup_entry
async def test_config_flow_zigbee(hass: HomeAssistant) -> None:
"""Test Zigbee config flow for Connect ZBT-2."""
fw_type = ApplicationType.EZSP
fw_version = "7.4.4.0 build 0"
model = "Home Assistant Connect ZBT-2"
usb_data = USB_DATA_ZBT2
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "usb"}, data=usb_data
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "pick_firmware"
description_placeholders = result["description_placeholders"]
assert description_placeholders is not None
assert description_placeholders["model"] == model
async def mock_install_firmware_step(
self,
fw_update_url: str,
fw_type: str,
firmware_name: str,
expected_installed_firmware_type: ApplicationType,
step_id: str,
next_step_id: str,
) -> ConfigFlowResult:
self._probed_firmware_info = FirmwareInfo(
device=usb_data.device,
firmware_type=expected_installed_firmware_type,
firmware_version=fw_version,
owners=[],
source="probe",
)
return await getattr(self, f"async_step_{next_step_id}")()
with (
patch(
"homeassistant.components.homeassistant_hardware.firmware_config_flow.BaseFirmwareConfigFlow._install_firmware_step",
autospec=True,
side_effect=mock_install_firmware_step,
),
):
pick_result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={"next_step_id": STEP_PICK_FIRMWARE_ZIGBEE},
)
assert pick_result["type"] is FlowResultType.MENU
assert pick_result["step_id"] == "zigbee_installation_type"
create_result = await hass.config_entries.flow.async_configure(
pick_result["flow_id"],
user_input={"next_step_id": "zigbee_intent_recommended"},
)
assert create_result["type"] is FlowResultType.CREATE_ENTRY
config_entry = create_result["result"]
assert config_entry.data == {
"firmware": fw_type.value,
"firmware_version": fw_version,
"device": usb_data.device,
"manufacturer": usb_data.manufacturer,
"pid": usb_data.pid,
"product": usb_data.description,
"serial_number": usb_data.serial_number,
"vid": usb_data.vid,
}
flows = hass.config_entries.flow.async_progress()
# Ensure a ZHA discovery flow has been created
assert len(flows) == 1
zha_flow = flows[0]
assert zha_flow["handler"] == "zha"
assert zha_flow["context"]["source"] == "hardware"
assert zha_flow["step_id"] == "confirm"
progress_zha_flows = hass.config_entries.flow._async_progress_by_handler(
handler="zha",
match_context=None,
)
assert len(progress_zha_flows) == 1
# Ensure correct baudrate
progress_zha_flow = progress_zha_flows[0]
assert progress_zha_flow.init_data == {
"flow_strategy": "recommended",
"name": model,
"port": {
"path": usb_data.device,
"baudrate": 460800,
"flow_control": "hardware",
},
"radio_type": fw_type.value,
}
@pytest.mark.usefixtures("addon_installed", "supervisor")
async def test_config_flow_thread(
hass: HomeAssistant,
start_addon: AsyncMock,
) -> None:
"""Test Thread config flow for Connect ZBT-2."""
fw_type = ApplicationType.SPINEL
fw_version = "2.4.4.0"
model = "Home Assistant Connect ZBT-2"
usb_data = USB_DATA_ZBT2
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "usb"}, data=usb_data
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "pick_firmware"
description_placeholders = result["description_placeholders"]
assert description_placeholders is not None
assert description_placeholders["model"] == model
async def mock_install_firmware_step(
self,
fw_update_url: str,
fw_type: str,
firmware_name: str,
expected_installed_firmware_type: ApplicationType,
step_id: str,
next_step_id: str,
) -> ConfigFlowResult:
self._probed_firmware_info = FirmwareInfo(
device=usb_data.device,
firmware_type=expected_installed_firmware_type,
firmware_version=fw_version,
owners=[],
source="probe",
)
return await getattr(self, f"async_step_{next_step_id}")()
with (
patch(
"homeassistant.components.homeassistant_hardware.firmware_config_flow.BaseFirmwareConfigFlow._install_firmware_step",
autospec=True,
side_effect=mock_install_firmware_step,
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={"next_step_id": STEP_PICK_FIRMWARE_THREAD},
)
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "start_otbr_addon"
# Make sure the flow continues when the progress task is done.
await hass.async_block_till_done()
create_result = await hass.config_entries.flow.async_configure(
result["flow_id"]
)
assert start_addon.call_count == 1
assert start_addon.call_args == call("core_openthread_border_router")
assert create_result["type"] is FlowResultType.CREATE_ENTRY
config_entry = create_result["result"]
assert config_entry.data == {
"firmware": fw_type.value,
"firmware_version": fw_version,
"device": usb_data.device,
"manufacturer": usb_data.manufacturer,
"pid": usb_data.pid,
"product": usb_data.description,
"serial_number": usb_data.serial_number,
"vid": usb_data.vid,
}
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 0
@pytest.mark.parametrize(
("usb_data", "model"),
[
(USB_DATA_ZBT2, "Home Assistant Connect ZBT-2"),
],
)
async def test_options_flow(
usb_data: UsbServiceInfo, model: str, hass: HomeAssistant
) -> None:
"""Test the options flow for Connect ZBT-2."""
config_entry = MockConfigEntry(
domain="homeassistant_connect_zbt2",
data={
"firmware": "spinel",
"firmware_version": "SL-OPENTHREAD/2.4.4.0_GitHub-7074a43e4",
"device": usb_data.device,
"manufacturer": usb_data.manufacturer,
"pid": usb_data.pid,
"product": usb_data.description,
"serial_number": usb_data.serial_number,
"vid": usb_data.vid,
},
version=1,
minor_version=1,
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
# First step is confirmation
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "pick_firmware"
description_placeholders = result["description_placeholders"]
assert description_placeholders is not None
assert description_placeholders["firmware_type"] == "spinel"
assert description_placeholders["model"] == model
mock_update_client = AsyncMock()
mock_manifest = Mock()
mock_firmware = Mock()
mock_firmware.filename = "zbt2_zigbee_ncp_7.4.4.0.gbl"
mock_firmware.metadata = {
"ezsp_version": "7.4.4.0",
"fw_type": "zbt2_zigbee_ncp",
"metadata_version": 2,
}
mock_manifest.firmwares = [mock_firmware]
mock_update_client.async_update_data.return_value = mock_manifest
mock_update_client.async_fetch_firmware.return_value = b"firmware_data"
with (
patch(
"homeassistant.components.homeassistant_hardware.firmware_config_flow.guess_hardware_owners",
return_value=[],
),
patch(
"homeassistant.components.homeassistant_hardware.firmware_config_flow.FirmwareUpdateClient",
return_value=mock_update_client,
),
patch(
"homeassistant.components.homeassistant_hardware.firmware_config_flow.async_flash_silabs_firmware",
return_value=FirmwareInfo(
device=usb_data.device,
firmware_type=ApplicationType.EZSP,
firmware_version="7.4.4.0 build 0",
owners=[],
source="probe",
),
) as flash_mock,
patch(
"homeassistant.components.homeassistant_hardware.firmware_config_flow.probe_silabs_firmware_info",
side_effect=[
# First call: probe before installation (returns current SPINEL firmware)
FirmwareInfo(
device=usb_data.device,
firmware_type=ApplicationType.SPINEL,
firmware_version="2.4.4.0",
owners=[],
source="probe",
),
# Second call: probe after installation (returns new EZSP firmware)
FirmwareInfo(
device=usb_data.device,
firmware_type=ApplicationType.EZSP,
firmware_version="7.4.4.0 build 0",
owners=[],
source="probe",
),
],
),
patch(
"homeassistant.components.homeassistant_hardware.util.parse_firmware_image"
),
):
pick_result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={"next_step_id": STEP_PICK_FIRMWARE_ZIGBEE},
)
assert pick_result["type"] is FlowResultType.MENU
assert pick_result["step_id"] == "zigbee_installation_type"
create_result = await hass.config_entries.options.async_configure(
pick_result["flow_id"],
user_input={"next_step_id": "zigbee_intent_recommended"},
)
assert create_result["type"] is FlowResultType.CREATE_ENTRY
assert config_entry.data == {
"firmware": "ezsp",
"firmware_version": "7.4.4.0 build 0",
"device": usb_data.device,
"manufacturer": usb_data.manufacturer,
"pid": usb_data.pid,
"product": usb_data.description,
"serial_number": usb_data.serial_number,
"vid": usb_data.vid,
}
# Verify async_flash_silabs_firmware was called with ZBT-2's reset methods
assert flash_mock.call_count == 1
assert flash_mock.mock_calls[0].kwargs["bootloader_reset_methods"] == [
ResetTarget.RTS_DTR,
ResetTarget.BAUDRATE,
]
flows = hass.config_entries.flow.async_progress()
# Ensure a ZHA discovery flow has been created
assert len(flows) == 1
zha_flow = flows[0]
assert zha_flow["handler"] == "zha"
assert zha_flow["context"]["source"] == "hardware"
assert zha_flow["step_id"] == "confirm"
progress_zha_flows = hass.config_entries.flow._async_progress_by_handler(
handler="zha",
match_context=None,
)
assert len(progress_zha_flows) == 1
# Ensure correct baudrate
progress_zha_flow = progress_zha_flows[0]
assert progress_zha_flow.init_data == {
"flow_strategy": "recommended",
"name": model,
"port": {
"path": usb_data.device,
"baudrate": 460800,
"flow_control": "hardware",
},
"radio_type": "ezsp",
}
async def test_duplicate_discovery(hass: HomeAssistant) -> None:
"""Test config flow unique_id deduplication."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "usb"}, data=USB_DATA_ZBT2
)
assert result["type"] is FlowResultType.MENU
result_duplicate = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "usb"}, data=USB_DATA_ZBT2
)
assert result_duplicate["type"] is FlowResultType.ABORT
assert result_duplicate["reason"] == "already_in_progress"
async def test_duplicate_discovery_updates_usb_path(hass: HomeAssistant) -> None:
"""Test config flow unique_id deduplication updates USB path."""
config_entry = MockConfigEntry(
domain="homeassistant_connect_zbt2",
data={
"firmware": "spinel",
"firmware_version": "SL-OPENTHREAD/2.4.4.0_GitHub-7074a43e4",
"device": "/dev/oldpath",
"manufacturer": USB_DATA_ZBT2.manufacturer,
"pid": USB_DATA_ZBT2.pid,
"product": USB_DATA_ZBT2.description,
"serial_number": USB_DATA_ZBT2.serial_number,
"vid": USB_DATA_ZBT2.vid,
},
version=1,
minor_version=1,
unique_id=(
f"{USB_DATA_ZBT2.vid}:{USB_DATA_ZBT2.pid}_"
f"{USB_DATA_ZBT2.serial_number}_"
f"{USB_DATA_ZBT2.manufacturer}_"
f"{USB_DATA_ZBT2.description}"
),
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "usb"}, data=USB_DATA_ZBT2
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert config_entry.data["device"] == USB_DATA_ZBT2.device
async def test_firmware_callback_auto_creates_entry(hass: HomeAssistant) -> None:
"""Test that firmware notification triggers import flow that auto-creates config entry."""
await async_setup_component(hass, HOMEASSISTANT_HARDWARE_DOMAIN, {})
await async_setup_component(hass, USB_DOMAIN, {})
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "usb"}, data=USB_DATA_ZBT2
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "pick_firmware"
usb_device = USBDevice(
device=USB_DATA_ZBT2.device,
vid=USB_DATA_ZBT2.vid,
pid=USB_DATA_ZBT2.pid,
serial_number=USB_DATA_ZBT2.serial_number,
manufacturer=USB_DATA_ZBT2.manufacturer,
description=USB_DATA_ZBT2.description,
)
with patch(
"homeassistant.components.homeassistant_hardware.helpers.usb_device_from_path",
return_value=usb_device,
):
await async_notify_firmware_info(
hass,
"zha",
FirmwareInfo(
device=USB_DATA_ZBT2.device,
firmware_type=ApplicationType.EZSP,
firmware_version="7.4.4.0",
owners=[],
source="zha",
),
)
await hass.async_block_till_done()
# The config entry was auto-created
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].data == {
"device": USB_DATA_ZBT2.device,
"firmware": ApplicationType.EZSP.value,
"firmware_version": "7.4.4.0",
"vid": USB_DATA_ZBT2.vid,
"pid": USB_DATA_ZBT2.pid,
"serial_number": USB_DATA_ZBT2.serial_number,
"manufacturer": USB_DATA_ZBT2.manufacturer,
"product": USB_DATA_ZBT2.description,
}
# The discovery flow is gone
assert not hass.config_entries.flow.async_progress_by_handler(DOMAIN)
async def test_firmware_callback_updates_existing_entry(hass: HomeAssistant) -> None:
"""Test that firmware notification updates existing config entry device path."""
await async_setup_component(hass, HOMEASSISTANT_HARDWARE_DOMAIN, {})
await async_setup_component(hass, USB_DOMAIN, {})
# Create existing config entry with old device path
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
"firmware": ApplicationType.EZSP.value,
"firmware_version": "7.4.4.0",
"device": "/dev/oldpath",
"vid": USB_DATA_ZBT2.vid,
"pid": USB_DATA_ZBT2.pid,
"serial_number": USB_DATA_ZBT2.serial_number,
"manufacturer": USB_DATA_ZBT2.manufacturer,
"product": USB_DATA_ZBT2.description,
},
unique_id=(
f"{USB_DATA_ZBT2.vid}:{USB_DATA_ZBT2.pid}_"
f"{USB_DATA_ZBT2.serial_number}_"
f"{USB_DATA_ZBT2.manufacturer}_"
f"{USB_DATA_ZBT2.description}"
),
)
config_entry.add_to_hass(hass)
usb_device = USBDevice(
device=USB_DATA_ZBT2.device,
vid=USB_DATA_ZBT2.vid,
pid=USB_DATA_ZBT2.pid,
serial_number=USB_DATA_ZBT2.serial_number,
manufacturer=USB_DATA_ZBT2.manufacturer,
description=USB_DATA_ZBT2.description,
)
with patch(
"homeassistant.components.homeassistant_hardware.helpers.usb_device_from_path",
return_value=usb_device,
):
await async_notify_firmware_info(
hass,
"zha",
FirmwareInfo(
device=USB_DATA_ZBT2.device,
firmware_type=ApplicationType.EZSP,
firmware_version="7.4.4.0",
owners=[],
source="zha",
),
)
await hass.async_block_till_done()
# The config entry device path should be updated
assert config_entry.data["device"] == USB_DATA_ZBT2.device
# No new config entry was created
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_connect_zbt2/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 483,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homeassistant_connect_zbt2/test_hardware.py | """Test the Home Assistant Connect ZBT-2 hardware platform."""
from homeassistant.components.homeassistant_connect_zbt2.const import DOMAIN
from homeassistant.components.usb import DOMAIN as USB_DOMAIN
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
from tests.typing import WebSocketGenerator
CONFIG_ENTRY_DATA = {
"device": "/dev/serial/by-id/usb-Nabu_Casa_ZBT-2_80B54EEFAE18-if01-port0",
"vid": "303A",
"pid": "4001",
"serial_number": "80B54EEFAE18",
"manufacturer": "Nabu Casa",
"product": "ZBT-2",
"firmware": "ezsp",
"firmware_version": "7.4.4.0 build 0",
}
async def test_hardware_info(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, addon_store_info
) -> None:
"""Test we can get the board info."""
assert await async_setup_component(hass, USB_DOMAIN, {})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
# Setup the config entry
config_entry = MockConfigEntry(
data=CONFIG_ENTRY_DATA,
domain=DOMAIN,
options={},
title="Home Assistant Connect ZBT-2",
unique_id="unique_1",
version=1,
minor_version=1,
)
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
client = await hass_ws_client(hass)
await client.send_json({"id": 1, "type": "hardware/info"})
msg = await client.receive_json()
assert msg["id"] == 1
assert msg["success"]
assert msg["result"] == {
"hardware": [
{
"board": None,
"config_entries": [config_entry.entry_id],
"dongle": {
"vid": "303A",
"pid": "4001",
"serial_number": "80B54EEFAE18",
"manufacturer": "Nabu Casa",
"description": "ZBT-2",
},
"name": "Home Assistant Connect ZBT-2",
"url": "https://support.nabucasa.com/hc/en-us/categories/24734620813469-Home-Assistant-Connect-ZBT-1",
}
]
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_connect_zbt2/test_hardware.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/homeassistant_connect_zbt2/test_init.py | """Test the Home Assistant Connect ZBT-2 integration."""
from datetime import timedelta
from unittest.mock import patch
import pytest
from homeassistant.components.homeassistant_connect_zbt2.const import DOMAIN
from homeassistant.components.usb import DOMAIN as USB_DOMAIN, USBDevice
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry, async_fire_time_changed
from tests.components.usb import (
async_request_scan,
force_usb_polling_watcher, # noqa: F401
patch_scanned_serial_ports,
)
async def test_setup_fails_on_missing_usb_port(hass: HomeAssistant) -> None:
"""Test setup failing when the USB port is missing."""
config_entry = MockConfigEntry(
domain=DOMAIN,
unique_id="some_unique_id",
data={
"device": "/dev/serial/by-id/usb-Nabu_Casa_ZBT-2_80B54EEFAE18-if01-port0",
"vid": "303A",
"pid": "4001",
"serial_number": "80B54EEFAE18",
"manufacturer": "Nabu Casa",
"product": "ZBT-2",
"firmware": "ezsp",
"firmware_version": "7.4.4.0",
},
version=1,
minor_version=1,
)
config_entry.add_to_hass(hass)
# Set up the config entry
with patch(
"homeassistant.components.homeassistant_connect_zbt2.os.path.exists"
) as mock_exists:
mock_exists.return_value = False
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
# Failed to set up, the device is missing
assert config_entry.state is ConfigEntryState.SETUP_RETRY
mock_exists.return_value = True
async_fire_time_changed(hass, dt_util.now() + timedelta(seconds=30))
await hass.async_block_till_done(wait_background_tasks=True)
# Now it's ready
assert config_entry.state is ConfigEntryState.LOADED
@pytest.mark.usefixtures("force_usb_polling_watcher")
async def test_usb_device_reactivity(hass: HomeAssistant) -> None:
"""Test setting up USB monitoring."""
assert await async_setup_component(hass, USB_DOMAIN, {"usb": {}})
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
config_entry = MockConfigEntry(
domain=DOMAIN,
unique_id="some_unique_id",
data={
"device": "/dev/serial/by-id/usb-Nabu_Casa_ZBT-2_80B54EEFAE18-if01-port0",
"vid": "303A",
"pid": "4001",
"serial_number": "80B54EEFAE18",
"manufacturer": "Nabu Casa",
"product": "ZBT-2",
"firmware": "ezsp",
"firmware_version": "7.4.4.0",
},
version=1,
minor_version=1,
)
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.homeassistant_connect_zbt2.os.path.exists"
) as mock_exists:
mock_exists.return_value = False
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
# Failed to set up, the device is missing
assert config_entry.state is ConfigEntryState.SETUP_RETRY
# Now we make it available but do not wait
mock_exists.return_value = True
with patch_scanned_serial_ports(
return_value=[
USBDevice(
device="/dev/serial/by-id/usb-Nabu_Casa_ZBT-2_80B54EEFAE18-if01-port0",
vid="303A",
pid="4001",
serial_number="80B54EEFAE18",
manufacturer="Nabu Casa",
description="ZBT-2",
)
],
):
await async_request_scan(hass)
# It loads immediately
await hass.async_block_till_done(wait_background_tasks=True)
assert config_entry.state is ConfigEntryState.LOADED
# Wait for a bit for the USB scan debouncer to cool off
async_fire_time_changed(hass, dt_util.now() + timedelta(minutes=5))
# Unplug the stick
mock_exists.return_value = False
with patch_scanned_serial_ports(return_value=[]):
await async_request_scan(hass)
# The integration has reloaded and is now in a failed state
await hass.async_block_till_done(wait_background_tasks=True)
assert config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_connect_zbt2/test_init.py",
"license": "Apache License 2.0",
"lines": 109,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homeassistant_connect_zbt2/test_update.py | """Test Connect ZBT-2 firmware update entity."""
import pytest
from homeassistant.components.homeassistant_hardware.helpers import (
async_notify_firmware_info,
)
from homeassistant.components.homeassistant_hardware.util import (
ApplicationType,
FirmwareInfo,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from .common import USB_DATA_ZBT2
from tests.common import MockConfigEntry
UPDATE_ENTITY_ID = "update.home_assistant_connect_zbt_2_80b54eefae18_firmware"
async def test_zbt2_update_entity(hass: HomeAssistant) -> None:
"""Test the ZBT-2 firmware update entity."""
await async_setup_component(hass, "homeassistant", {})
# Set up the ZBT-2 integration
zbt2_config_entry = MockConfigEntry(
domain="homeassistant_connect_zbt2",
data={
"firmware": "ezsp",
"firmware_version": "7.3.1.0 build 0",
"device": USB_DATA_ZBT2.device,
"manufacturer": USB_DATA_ZBT2.manufacturer,
"pid": USB_DATA_ZBT2.pid,
"product": USB_DATA_ZBT2.description,
"serial_number": USB_DATA_ZBT2.serial_number,
"vid": USB_DATA_ZBT2.vid,
},
version=1,
minor_version=1,
)
zbt2_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(zbt2_config_entry.entry_id)
await hass.async_block_till_done()
# Pretend ZHA loaded and notified hardware of the running firmware
await async_notify_firmware_info(
hass,
"zha",
FirmwareInfo(
device=USB_DATA_ZBT2.device,
firmware_type=ApplicationType.EZSP,
firmware_version="7.3.1.0 build 0",
owners=[],
source="zha",
),
)
await hass.async_block_till_done()
state_ezsp = hass.states.get(UPDATE_ENTITY_ID)
assert state_ezsp is not None
assert state_ezsp.state == "unknown"
assert state_ezsp.attributes["title"] == "EmberZNet Zigbee"
assert state_ezsp.attributes["installed_version"] == "7.3.1.0"
assert state_ezsp.attributes["latest_version"] is None
# Now, have OTBR push some info
await async_notify_firmware_info(
hass,
"otbr",
FirmwareInfo(
device=USB_DATA_ZBT2.device,
firmware_type=ApplicationType.SPINEL,
firmware_version="SL-OPENTHREAD/2.4.4.0_GitHub-7074a43e4; EFR32; Oct 21 2024 14:40:57",
owners=[],
source="otbr",
),
)
await hass.async_block_till_done()
# After the firmware update, the entity has the new version and the correct state
state_spinel = hass.states.get(UPDATE_ENTITY_ID)
assert state_spinel is not None
assert state_spinel.state == "unknown"
assert state_spinel.attributes["title"] == "OpenThread RCP"
assert state_spinel.attributes["installed_version"] == "2.4.4.0"
assert state_spinel.attributes["latest_version"] is None
@pytest.mark.parametrize(
("firmware", "version", "expected"),
[
("ezsp", "7.3.1.0 build 0", "EmberZNet Zigbee 7.3.1.0"),
("spinel", "SL-OPENTHREAD/2.4.4.0_GitHub-7074a43e4", "OpenThread RCP 2.4.4.0"),
("bootloader", "2.4.2", "Gecko Bootloader 2.4.2"),
("router", "1.2.3.4", "Unknown 1.2.3.4"), # Not supported but still shown
],
)
async def test_zbt2_update_entity_state(
hass: HomeAssistant, firmware: str, version: str, expected: str
) -> None:
"""Test the ZBT-2 firmware update entity with different firmware types."""
await async_setup_component(hass, "homeassistant", {})
zbt2_config_entry = MockConfigEntry(
domain="homeassistant_connect_zbt2",
data={
"firmware": firmware,
"firmware_version": version,
"device": USB_DATA_ZBT2.device,
"manufacturer": USB_DATA_ZBT2.manufacturer,
"pid": USB_DATA_ZBT2.pid,
"product": USB_DATA_ZBT2.description,
"serial_number": USB_DATA_ZBT2.serial_number,
"vid": USB_DATA_ZBT2.vid,
},
version=1,
minor_version=1,
)
zbt2_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(zbt2_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(UPDATE_ENTITY_ID)
assert state is not None
assert (
f"{state.attributes['title']} {state.attributes['installed_version']}"
== expected
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_connect_zbt2/test_update.py",
"license": "Apache License 2.0",
"lines": 113,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homeassistant_connect_zbt2/test_util.py | """Test Connect ZBT-2 utilities."""
from homeassistant.components.homeassistant_connect_zbt2.const import DOMAIN
from homeassistant.components.homeassistant_connect_zbt2.util import (
get_usb_service_info,
)
from homeassistant.helpers.service_info.usb import UsbServiceInfo
from tests.common import MockConfigEntry
CONNECT_ZBT2_CONFIG_ENTRY = MockConfigEntry(
domain=DOMAIN,
unique_id="some_unique_id",
data={
"device": "/dev/serial/by-id/usb-Nabu_Casa_ZBT-2_80B54EEFAE18-if01-port0",
"vid": "303A",
"pid": "4001",
"serial_number": "80B54EEFAE18",
"manufacturer": "Nabu Casa",
"product": "ZBT-2",
"firmware": "ezsp",
},
version=2,
)
def test_get_usb_service_info() -> None:
"""Test `get_usb_service_info` conversion."""
assert get_usb_service_info(CONNECT_ZBT2_CONFIG_ENTRY) == UsbServiceInfo(
device=CONNECT_ZBT2_CONFIG_ENTRY.data["device"],
vid=CONNECT_ZBT2_CONFIG_ENTRY.data["vid"],
pid=CONNECT_ZBT2_CONFIG_ENTRY.data["pid"],
serial_number=CONNECT_ZBT2_CONFIG_ENTRY.data["serial_number"],
manufacturer=CONNECT_ZBT2_CONFIG_ENTRY.data["manufacturer"],
description=CONNECT_ZBT2_CONFIG_ENTRY.data["product"],
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_connect_zbt2/test_util.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/imeon_inverter/test_select.py | """Test the Imeon Inverter selects."""
from unittest.mock import MagicMock, patch
from freezegun.api import FrozenDateTimeFactory
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.select import DOMAIN as SELECT_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_OPTION,
SERVICE_SELECT_OPTION,
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_selects(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Imeon Inverter selects."""
with patch("homeassistant.components.imeon_inverter.PLATFORMS", [Platform.SELECT]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_select_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_imeon_inverter: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test select mode updates entity state."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
entity_id = "sensor.imeon_inverter_inverter_mode"
assert entity_id
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: "smart_grid"},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/imeon_inverter/test_select.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/irm_kmi/test_config_flow.py | """Tests for the IRM KMI config flow."""
from unittest.mock import MagicMock
from homeassistant.components.irm_kmi.const import CONF_LANGUAGE_OVERRIDE, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import (
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_LOCATION,
CONF_UNIQUE_ID,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_full_user_flow(
hass: HomeAssistant,
mock_setup_entry: MagicMock,
mock_get_forecast_in_benelux: MagicMock,
) -> None:
"""Test the full user configuration flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_LOCATION: {ATTR_LATITUDE: 50.123, ATTR_LONGITUDE: 4.456}},
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result.get("title") == "Brussels"
assert result.get("data") == {
CONF_LOCATION: {ATTR_LATITUDE: 50.123, ATTR_LONGITUDE: 4.456},
CONF_UNIQUE_ID: "brussels be",
}
async def test_user_flow_home(
hass: HomeAssistant,
mock_setup_entry: MagicMock,
mock_get_forecast_in_benelux: MagicMock,
) -> None:
"""Test the full user configuration flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_LOCATION: {ATTR_LATITUDE: 50.123, ATTR_LONGITUDE: 4.456}},
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result.get("title") == "Brussels"
async def test_config_flow_location_out_benelux(
hass: HomeAssistant,
mock_setup_entry: MagicMock,
mock_get_forecast_out_benelux_then_in_belgium: MagicMock,
) -> None:
"""Test configuration flow with a zone outside of Benelux."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_LOCATION: {ATTR_LATITUDE: 0.123, ATTR_LONGITUDE: 0.456}},
)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "user"
assert CONF_LOCATION in result.get("errors")
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_LOCATION: {ATTR_LATITUDE: 50.123, ATTR_LONGITUDE: 4.456}},
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
async def test_config_flow_with_api_error(
hass: HomeAssistant,
mock_setup_entry: MagicMock,
mock_get_forecast_api_error: MagicMock,
) -> None:
"""Test when API returns an error during the configuration flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_LOCATION: {ATTR_LATITUDE: 50.123, ATTR_LONGITUDE: 4.456}},
)
assert result.get("type") is FlowResultType.ABORT
async def test_setup_twice_same_location(
hass: HomeAssistant,
mock_setup_entry: MagicMock,
mock_get_forecast_in_benelux: MagicMock,
) -> None:
"""Test when the user tries to set up the weather twice for the same location."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_LOCATION: {ATTR_LATITUDE: 50.5, ATTR_LONGITUDE: 4.6}},
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
# Set up a second time
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_LOCATION: {ATTR_LATITUDE: 50.5, ATTR_LONGITUDE: 4.6}},
)
assert result.get("type") is FlowResultType.ABORT
async def test_option_flow(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test when the user changes options with the option flow."""
mock_config_entry.add_to_hass(hass)
assert not mock_config_entry.options
result = await hass.config_entries.options.async_init(
mock_config_entry.entry_id, data=None
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {CONF_LANGUAGE_OVERRIDE: "none"}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/irm_kmi/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 123,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/irm_kmi/test_init.py | """Tests for the IRM KMI integration."""
from unittest.mock import AsyncMock
from homeassistant.components.irm_kmi.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_load_unload_config_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_irm_kmi_api: AsyncMock,
) -> None:
"""Test the IRM KMI configuration entry loading/unloading."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert not hass.data.get(DOMAIN)
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
async def test_config_entry_not_ready(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_exception_irm_kmi_api: AsyncMock,
) -> None:
"""Test the IRM KMI configuration entry not ready."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_exception_irm_kmi_api.refresh_forecasts_coord.call_count == 1
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/irm_kmi/test_init.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/irm_kmi/test_weather.py | """Test for the weather entity of the IRM KMI integration."""
from unittest.mock import AsyncMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.weather import (
DOMAIN as WEATHER_DOMAIN,
SERVICE_GET_FORECASTS,
)
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
import homeassistant.helpers.entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.freeze_time("2023-12-28T15:30:00+01:00")
async def test_weather_nl(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_irm_kmi_api_nl: AsyncMock,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test weather with forecast from the Netherland."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"forecast_type",
["daily", "hourly"],
)
@pytest.mark.freeze_time("2025-09-22T15:30:00+01:00")
async def test_forecast_service(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_irm_kmi_api_nl: AsyncMock,
mock_config_entry: MockConfigEntry,
forecast_type: str,
) -> None:
"""Test multiple forecast."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
response = await hass.services.async_call(
WEATHER_DOMAIN,
SERVICE_GET_FORECASTS,
{
ATTR_ENTITY_ID: "weather.home",
"type": forecast_type,
},
blocking=True,
return_response=True,
)
assert response == snapshot
@pytest.mark.freeze_time("2024-01-21T14:15:00+01:00")
@pytest.mark.parametrize(
"forecast_type",
["daily", "hourly"],
)
async def test_weather_higher_temp_at_night(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_irm_kmi_api_high_low_temp: AsyncMock,
forecast_type: str,
) -> None:
"""Test that the templow is always lower than temperature, even when API returns the opposite."""
# Test case for https://github.com/jdejaegh/irm-kmi-ha/issues/8
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
response = await hass.services.async_call(
WEATHER_DOMAIN,
SERVICE_GET_FORECASTS,
{
ATTR_ENTITY_ID: "weather.home",
"type": forecast_type,
},
blocking=True,
return_response=True,
)
for forecast in response["weather.home"]["forecast"]:
assert (
forecast.get("native_temperature") is None
or forecast.get("native_templow") is None
or forecast["native_temperature"] >= forecast["native_templow"]
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/irm_kmi/test_weather.py",
"license": "Apache License 2.0",
"lines": 84,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/lawn_mower/test_intent.py | """The tests for the lawn mower platform."""
from homeassistant.components.lawn_mower import (
DOMAIN,
SERVICE_DOCK,
SERVICE_START_MOWING,
LawnMowerActivity,
LawnMowerEntityFeature,
intent as lawn_mower_intent,
)
from homeassistant.const import ATTR_SUPPORTED_FEATURES
from homeassistant.core import HomeAssistant
from homeassistant.helpers import intent
from tests.common import async_mock_service
async def test_start_lawn_mower_intent(hass: HomeAssistant) -> None:
"""Test HassLawnMowerStartMowing intent for lawn mowers."""
await lawn_mower_intent.async_setup_intents(hass)
entity_id = f"{DOMAIN}.test_lawn_mower"
hass.states.async_set(
entity_id,
LawnMowerActivity.DOCKED,
{ATTR_SUPPORTED_FEATURES: LawnMowerEntityFeature.START_MOWING},
)
calls = async_mock_service(hass, DOMAIN, SERVICE_START_MOWING)
response = await intent.async_handle(
hass,
"test",
lawn_mower_intent.INTENT_LANW_MOWER_START_MOWING,
{"name": {"value": "test lawn mower"}},
)
await hass.async_block_till_done()
assert response.response_type == intent.IntentResponseType.ACTION_DONE
assert len(calls) == 1
call = calls[0]
assert call.domain == DOMAIN
assert call.service == SERVICE_START_MOWING
assert call.data == {"entity_id": entity_id}
async def test_start_lawn_mower_without_name(hass: HomeAssistant) -> None:
"""Test starting a lawn mower without specifying the name."""
await lawn_mower_intent.async_setup_intents(hass)
entity_id = f"{DOMAIN}.test_lawn_mower"
hass.states.async_set(
entity_id,
LawnMowerActivity.DOCKED,
{ATTR_SUPPORTED_FEATURES: LawnMowerEntityFeature.START_MOWING},
)
calls = async_mock_service(hass, DOMAIN, SERVICE_START_MOWING)
response = await intent.async_handle(
hass, "test", lawn_mower_intent.INTENT_LANW_MOWER_START_MOWING, {}
)
await hass.async_block_till_done()
assert response.response_type == intent.IntentResponseType.ACTION_DONE
assert len(calls) == 1
call = calls[0]
assert call.domain == DOMAIN
assert call.service == SERVICE_START_MOWING
assert call.data == {"entity_id": entity_id}
async def test_stop_lawn_mower_intent(hass: HomeAssistant) -> None:
"""Test HassLawnMowerDock intent for lawn mowers."""
await lawn_mower_intent.async_setup_intents(hass)
entity_id = f"{DOMAIN}.test_lawn_mower"
hass.states.async_set(
entity_id,
LawnMowerActivity.MOWING,
{ATTR_SUPPORTED_FEATURES: LawnMowerEntityFeature.DOCK},
)
calls = async_mock_service(hass, DOMAIN, SERVICE_DOCK)
response = await intent.async_handle(
hass,
"test",
lawn_mower_intent.INTENT_LANW_MOWER_DOCK,
{"name": {"value": "test lawn mower"}},
)
await hass.async_block_till_done()
assert response.response_type == intent.IntentResponseType.ACTION_DONE
assert len(calls) == 1
call = calls[0]
assert call.domain == DOMAIN
assert call.service == SERVICE_DOCK
assert call.data == {"entity_id": entity_id}
async def test_stop_lawn_mower_without_name(hass: HomeAssistant) -> None:
"""Test stopping a lawn mower without specifying the name."""
await lawn_mower_intent.async_setup_intents(hass)
entity_id = f"{DOMAIN}.test_lawn_mower"
hass.states.async_set(
entity_id,
LawnMowerActivity.MOWING,
{ATTR_SUPPORTED_FEATURES: LawnMowerEntityFeature.DOCK},
)
calls = async_mock_service(hass, DOMAIN, SERVICE_DOCK)
response = await intent.async_handle(
hass, "test", lawn_mower_intent.INTENT_LANW_MOWER_DOCK, {}
)
await hass.async_block_till_done()
assert response.response_type == intent.IntentResponseType.ACTION_DONE
assert len(calls) == 1
call = calls[0]
assert call.domain == DOMAIN
assert call.service == SERVICE_DOCK
assert call.data == {"entity_id": entity_id}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/lawn_mower/test_intent.py",
"license": "Apache License 2.0",
"lines": 99,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/letpot/test_number.py | """Test number entities for the LetPot integration."""
from unittest.mock import MagicMock, patch
from letpot.exceptions import LetPotConnectionException, LetPotException
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_client: MagicMock,
mock_device_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test number entities."""
with patch("homeassistant.components.letpot.PLATFORMS", [Platform.NUMBER]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_set_number(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_client: MagicMock,
mock_device_client: MagicMock,
device_type: str,
) -> None:
"""Test number entity set to value."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{
ATTR_ENTITY_ID: "number.garden_light_brightness",
ATTR_VALUE: 6,
},
blocking=True,
)
mock_device_client.set_light_brightness.assert_awaited_once_with(
f"{device_type}ABCD", 750
)
@pytest.mark.parametrize(
("exception", "user_error"),
[
(
LetPotConnectionException("Connection failed"),
"An error occurred while communicating with the LetPot device: Connection failed",
),
(
LetPotException("Random thing failed"),
"An unknown error occurred while communicating with the LetPot device: Random thing failed",
),
],
)
async def test_number_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_client: MagicMock,
mock_device_client: MagicMock,
exception: Exception,
user_error: str,
) -> None:
"""Test number entity exception handling."""
await setup_integration(hass, mock_config_entry)
mock_device_client.set_plant_days.side_effect = exception
with pytest.raises(HomeAssistantError, match=user_error):
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{
ATTR_ENTITY_ID: "number.garden_plants_age",
ATTR_VALUE: 7,
},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/letpot/test_number.py",
"license": "Apache License 2.0",
"lines": 83,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/libre_hardware_monitor/test_config_flow.py | """Test the LibreHardwareMonitor config flow."""
from unittest.mock import AsyncMock
from librehardwaremonitor_api import (
LibreHardwareMonitorConnectionError,
LibreHardwareMonitorNoDevicesError,
LibreHardwareMonitorUnauthorizedError,
)
import pytest
from homeassistant.components.libre_hardware_monitor.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import AUTH_INPUT, REAUTH_INPUT, VALID_CONFIG, VALID_CONFIG_WITH_AUTH
from tests.common import MockConfigEntry
async def test_create_entry_without_auth(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_lhm_client: AsyncMock,
) -> None:
"""Test that a complete config entry is created."""
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=VALID_CONFIG
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["result"].unique_id is None
created_config_entry = result["result"]
assert (
created_config_entry.title
== f"GAMING-PC ({VALID_CONFIG[CONF_HOST]}:{VALID_CONFIG[CONF_PORT]})"
)
assert created_config_entry.data == VALID_CONFIG
assert mock_setup_entry.call_count == 1
async def test_create_entry_with_auth(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_lhm_client: AsyncMock,
) -> None:
"""Test that a complete config entry is created with authentication credentials."""
mock_lhm_client.get_data.side_effect = LibreHardwareMonitorUnauthorizedError()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=VALID_CONFIG
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
mock_lhm_client.get_data.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=AUTH_INPUT
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["result"].unique_id is None
created_config_entry = result["result"]
assert created_config_entry.data == VALID_CONFIG_WITH_AUTH
assert mock_setup_entry.call_count == 1
@pytest.mark.parametrize(
("side_effect", "error_text"),
[
(LibreHardwareMonitorConnectionError, "cannot_connect"),
(LibreHardwareMonitorNoDevicesError, "no_devices"),
],
)
async def test_errors_and_flow_recovery(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_lhm_client: AsyncMock,
side_effect: Exception,
error_text: str,
) -> None:
"""Test that errors are shown as expected."""
mock_lhm_client.get_data.side_effect = side_effect
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=VALID_CONFIG
)
assert result["errors"] == {"base": error_text}
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
mock_lhm_client.get_data.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=VALID_CONFIG
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert mock_setup_entry.call_count == 1
async def test_lhm_server_already_exists_without_auth(
hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test we only allow a single entry per server."""
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=VALID_CONFIG
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_setup_entry.call_count == 0
async def test_lhm_server_already_exists_with_auth(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_auth_config_entry: MockConfigEntry,
) -> None:
"""Test auth has no influence on single entry per server."""
mock_auth_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=VALID_CONFIG
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_setup_entry.call_count == 0
async def test_reauth_no_previous_credentials(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_lhm_client: AsyncMock,
) -> None:
"""Test reauth flow when web server did not require auth before."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
REAUTH_INPUT,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == {**VALID_CONFIG, **REAUTH_INPUT}
assert len(hass.config_entries.async_entries()) == 1
async def test_reauth_with_previous_credentials(
hass: HomeAssistant,
mock_auth_config_entry: MockConfigEntry,
mock_lhm_client: AsyncMock,
) -> None:
"""Test reauth flow when web server credentials changed."""
mock_auth_config_entry.add_to_hass(hass)
result = await mock_auth_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"],
REAUTH_INPUT,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_auth_config_entry.data == {**VALID_CONFIG, **REAUTH_INPUT}
assert len(hass.config_entries.async_entries()) == 1
@pytest.mark.parametrize(
("side_effect", "error_text"),
[
(LibreHardwareMonitorConnectionError, "cannot_connect"),
(LibreHardwareMonitorUnauthorizedError, "invalid_auth"),
(LibreHardwareMonitorNoDevicesError, "no_devices"),
],
)
async def test_reauth_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_lhm_client: AsyncMock,
side_effect: Exception,
error_text: str,
) -> None:
"""Test reauth flow errors."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
mock_lhm_client.get_data.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
REAUTH_INPUT,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_text}
mock_lhm_client.get_data.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
REAUTH_INPUT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == {**VALID_CONFIG, **REAUTH_INPUT}
assert len(hass.config_entries.async_entries()) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/libre_hardware_monitor/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 202,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/libre_hardware_monitor/test_sensor.py | """Test the LibreHardwareMonitor sensor."""
from dataclasses import replace
from datetime import timedelta
import logging
from types import MappingProxyType
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
from librehardwaremonitor_api import (
LibreHardwareMonitorConnectionError,
LibreHardwareMonitorNoDevicesError,
LibreHardwareMonitorUnauthorizedError,
)
from librehardwaremonitor_api.model import (
DeviceId,
DeviceName,
LibreHardwareMonitorData,
)
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.libre_hardware_monitor.const import (
DEFAULT_SCAN_INTERVAL,
DOMAIN,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import (
device_registry as dr,
entity_registry as er,
issue_registry as ir,
)
from homeassistant.helpers.device_registry import DeviceEntry
from . import init_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_sensors_are_created(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test sensors are created."""
await init_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
"error", [LibreHardwareMonitorConnectionError, LibreHardwareMonitorNoDevicesError]
)
async def test_sensors_go_unavailable_in_case_of_error_and_recover_after_successful_retry(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
error: type[Exception],
) -> None:
"""Test sensors go unavailable."""
await init_integration(hass, mock_config_entry)
initial_states = hass.states.async_all()
assert initial_states == snapshot(name="valid_sensor_data")
mock_lhm_client.get_data.side_effect = error
freezer.tick(timedelta(DEFAULT_SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
unavailable_states = hass.states.async_all()
assert all(state.state == STATE_UNAVAILABLE for state in unavailable_states)
mock_lhm_client.get_data.side_effect = None
freezer.tick(timedelta(DEFAULT_SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
recovered_states = hass.states.async_all()
assert all(state.state != STATE_UNAVAILABLE for state in recovered_states)
async def test_sensor_invalid_auth_after_update(
hass: HomeAssistant,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test invalid auth after sensor update."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
mock_lhm_client.get_data.side_effect = LibreHardwareMonitorUnauthorizedError
freezer.tick(timedelta(DEFAULT_SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert "Authentication against LibreHardwareMonitor instance failed" in caplog.text
unavailable_states = hass.states.async_all()
assert all(state.state == STATE_UNAVAILABLE for state in unavailable_states)
async def test_sensor_invalid_auth_during_startup(
hass: HomeAssistant,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test invalid auth in initial sensor update during integration startup."""
mock_lhm_client.get_data.side_effect = LibreHardwareMonitorUnauthorizedError
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert "Authentication against LibreHardwareMonitor instance failed" in caplog.text
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
assert mock_config_entry.reason == "Authentication failed"
unavailable_states = hass.states.async_all()
assert all(state.state == STATE_UNAVAILABLE for state in unavailable_states)
@pytest.mark.parametrize(
("object_id", "sensor_id", "new_value", "state_value"),
[
(
"gaming_pc_amd_ryzen_7_7800x3d_package_temperature",
"amdcpu-0-temperature-3",
"42.1",
"42.1",
),
(
"gaming_pc_nvidia_geforce_rtx_4080_super_gpu_pcie_tx_throughput",
"gpu-nvidia-0-throughput-1",
"792150000.0",
"773584.0",
),
],
)
async def test_sensors_are_updated(
hass: HomeAssistant,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
object_id: str,
sensor_id: str,
new_value: str,
state_value: str,
) -> None:
"""Test sensors are updated with properly formatted values."""
await init_integration(hass, mock_config_entry)
updated_data = dict(mock_lhm_client.get_data.return_value.sensor_data)
updated_data[sensor_id] = replace(updated_data[sensor_id], value=new_value)
mock_lhm_client.get_data.return_value = replace(
mock_lhm_client.get_data.return_value,
sensor_data=MappingProxyType(updated_data),
)
freezer.tick(timedelta(DEFAULT_SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(f"sensor.{object_id}")
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == state_value
async def test_sensor_state_is_unknown_when_no_sensor_data_is_provided(
hass: HomeAssistant,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test sensor state is unknown when sensor data is missing."""
await init_integration(hass, mock_config_entry)
entity_id = "sensor.gaming_pc_amd_ryzen_7_7800x3d_package_temperature"
state = hass.states.get(entity_id)
assert state
assert state.state != STATE_UNAVAILABLE
assert state.state == "52.8"
updated_data = dict(mock_lhm_client.get_data.return_value.sensor_data)
del updated_data["amdcpu-0-temperature-3"]
mock_lhm_client.get_data.return_value = replace(
mock_lhm_client.get_data.return_value,
sensor_data=MappingProxyType(updated_data),
)
freezer.tick(timedelta(DEFAULT_SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNKNOWN
async def test_orphaned_devices_are_removed_if_not_present_after_update(
hass: HomeAssistant,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test that devices in HA that are not found in LHM's data after sensor update are removed."""
orphaned_device = await _mock_orphaned_device(
device_registry, hass, mock_config_entry, mock_lhm_client
)
freezer.tick(timedelta(DEFAULT_SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert device_registry.async_get(orphaned_device.id) is None
async def test_orphaned_devices_are_removed_if_not_present_during_startup(
hass: HomeAssistant,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test that devices in HA that are not found in LHM's data during integration startup are removed."""
orphaned_device = await _mock_orphaned_device(
device_registry, hass, mock_config_entry, mock_lhm_client
)
hass.config_entries.async_schedule_reload(mock_config_entry.entry_id)
assert device_registry.async_get(orphaned_device.id) is None
async def _mock_orphaned_device(
device_registry: dr.DeviceRegistry,
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_lhm_client: AsyncMock,
) -> DeviceEntry:
await init_integration(hass, mock_config_entry)
removed_device = "gpu-nvidia-0"
previous_data = mock_lhm_client.get_data.return_value
assert removed_device in previous_data.main_device_ids_and_names
mock_lhm_client.get_data.return_value = LibreHardwareMonitorData(
computer_name=mock_lhm_client.get_data.return_value.computer_name,
main_device_ids_and_names=MappingProxyType(
{
device_id: name
for (device_id, name) in previous_data.main_device_ids_and_names.items()
if device_id != removed_device
}
),
sensor_data=MappingProxyType(
{
sensor_id: data
for (sensor_id, data) in previous_data.sensor_data.items()
if not sensor_id.startswith(removed_device)
}
),
is_deprecated_version=False,
)
return device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, f"{mock_config_entry.entry_id}_{removed_device}")},
)
async def test_integration_does_not_log_new_devices_on_first_refresh(
hass: HomeAssistant,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that initial data update does not cause warning about new devices."""
mock_lhm_client.get_data.return_value = LibreHardwareMonitorData(
computer_name=mock_lhm_client.get_data.return_value.computer_name,
main_device_ids_and_names=MappingProxyType(
{
**mock_lhm_client.get_data.return_value.main_device_ids_and_names,
DeviceId("generic-memory"): DeviceName("Generic Memory"),
}
),
sensor_data=mock_lhm_client.get_data.return_value.sensor_data,
is_deprecated_version=False,
)
with caplog.at_level(logging.WARNING):
await init_integration(hass, mock_config_entry)
libre_hardware_monitor_logs = [
record
for record in caplog.records
if record.name.startswith("homeassistant.components.libre_hardware_monitor")
]
assert len(libre_hardware_monitor_logs) == 0
async def test_non_deprecated_version_does_not_raise_issue(
hass: HomeAssistant,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test that a non-deprecated Libre Hardware Monitor version does not raise an issue."""
await init_integration(hass, mock_config_entry)
assert (
DOMAIN,
f"deprecated_api_{mock_config_entry.entry_id}",
) not in issue_registry.issues
async def test_deprecated_version_raises_issue_and_is_removed_after_update(
hass: HomeAssistant,
mock_lhm_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test that a deprecated Libre Hardware Monitor version raises an issue that is removed after updating."""
mock_lhm_client.get_data.return_value = replace(
mock_lhm_client.get_data.return_value,
is_deprecated_version=True,
)
await init_integration(hass, mock_config_entry)
assert (
DOMAIN,
f"deprecated_api_{mock_config_entry.entry_id}",
) in issue_registry.issues
mock_lhm_client.get_data.return_value = replace(
mock_lhm_client.get_data.return_value,
is_deprecated_version=False,
)
freezer.tick(timedelta(DEFAULT_SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (
DOMAIN,
f"deprecated_api_{mock_config_entry.entry_id}",
) not in issue_registry.issues
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/libre_hardware_monitor/test_sensor.py",
"license": "Apache License 2.0",
"lines": 298,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/media_source/test_helper.py | """Test media source helpers."""
from unittest.mock import Mock, patch
import pytest
from homeassistant.components import media_source
from homeassistant.components.media_player import BrowseError
from homeassistant.components.media_source import const, models
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
async def test_async_browse_media(hass: HomeAssistant) -> None:
"""Test browse media."""
assert await async_setup_component(hass, media_source.DOMAIN, {})
await hass.async_block_till_done()
# Test non-media ignored (/media has test.mp3 and not_media.txt)
media = await media_source.async_browse_media(hass, "")
assert isinstance(media, media_source.models.BrowseMediaSource)
assert media.title == "media"
assert len(media.children) == 2
# Test content filter
media = await media_source.async_browse_media(
hass,
"",
content_filter=lambda item: item.media_content_type.startswith("video/"),
)
assert isinstance(media, media_source.models.BrowseMediaSource)
assert media.title == "media"
assert len(media.children) == 1, media.children
media.children[0].title = "Epic Sax Guy 10 Hours"
assert media.not_shown == 1
# Test content filter adds to original not_shown
orig_browse = models.MediaSourceItem.async_browse
async def not_shown_browse(self):
"""Patch browsed item to set not_shown base value."""
item = await orig_browse(self)
item.not_shown = 10
return item
with patch(
"homeassistant.components.media_source.models.MediaSourceItem.async_browse",
not_shown_browse,
):
media = await media_source.async_browse_media(
hass,
"",
content_filter=lambda item: item.media_content_type.startswith("video/"),
)
assert isinstance(media, media_source.models.BrowseMediaSource)
assert media.title == "media"
assert len(media.children) == 1, media.children
media.children[0].title = "Epic Sax Guy 10 Hours"
assert media.not_shown == 11
# Test invalid media content
with pytest.raises(BrowseError):
await media_source.async_browse_media(hass, "invalid")
# Test base URI returns all domains
media = await media_source.async_browse_media(hass, const.URI_SCHEME)
assert isinstance(media, media_source.models.BrowseMediaSource)
assert len(media.children) == 1
assert media.children[0].title == "My media"
async def test_async_resolve_media(hass: HomeAssistant) -> None:
"""Test browse media."""
assert await async_setup_component(hass, media_source.DOMAIN, {})
await hass.async_block_till_done()
media = await media_source.async_resolve_media(
hass,
media_source.generate_media_source_id(media_source.DOMAIN, "local/test.mp3"),
None,
)
assert isinstance(media, media_source.models.PlayMedia)
assert media.url == "/media/local/test.mp3"
assert media.mime_type == "audio/mpeg"
async def test_async_resolve_media_no_entity(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test browse media."""
assert await async_setup_component(hass, media_source.DOMAIN, {})
await hass.async_block_till_done()
with pytest.raises(RuntimeError):
await media_source.async_resolve_media(
hass,
media_source.generate_media_source_id(
media_source.DOMAIN, "local/test.mp3"
),
)
async def test_async_unresolve_media(hass: HomeAssistant) -> None:
"""Test browse media."""
assert await async_setup_component(hass, media_source.DOMAIN, {})
await hass.async_block_till_done()
# Test no media content
with pytest.raises(media_source.Unresolvable):
await media_source.async_resolve_media(hass, "", None)
# Test invalid media content
with pytest.raises(media_source.Unresolvable):
await media_source.async_resolve_media(hass, "invalid", None)
# Test invalid media source
with pytest.raises(media_source.Unresolvable):
await media_source.async_resolve_media(
hass, "media-source://media_source2", None
)
async def test_browse_resolve_without_setup() -> None:
"""Test browse and resolve work without being setup."""
with pytest.raises(BrowseError):
await media_source.async_browse_media(Mock(data={}), None)
with pytest.raises(media_source.Unresolvable):
await media_source.async_resolve_media(Mock(data={}), None, None)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/media_source/test_helper.py",
"license": "Apache License 2.0",
"lines": 103,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/media_source/test_http.py | """Test media source HTTP."""
from unittest.mock import patch
import pytest
import yarl
from homeassistant.components import media_source
from homeassistant.components.media_player import BrowseError, MediaClass
from homeassistant.components.media_source import const
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.typing import WebSocketGenerator
async def test_websocket_browse_media(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator
) -> None:
"""Test browse media websocket."""
assert await async_setup_component(hass, media_source.DOMAIN, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
media = media_source.models.BrowseMediaSource(
domain=media_source.DOMAIN,
identifier="/media",
title="Local Media",
media_class=MediaClass.DIRECTORY,
media_content_type="listing",
can_play=False,
can_expand=True,
)
with patch(
"homeassistant.components.media_source.http.async_browse_media",
return_value=media,
):
await client.send_json(
{
"id": 1,
"type": "media_source/browse_media",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["id"] == 1
assert media.as_dict() == msg["result"]
with patch(
"homeassistant.components.media_source.http.async_browse_media",
side_effect=BrowseError("test"),
):
await client.send_json(
{
"id": 2,
"type": "media_source/browse_media",
"media_content_id": "invalid",
}
)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "browse_media_failed"
assert msg["error"]["message"] == "test"
@pytest.mark.parametrize("filename", ["test.mp3", "Epic Sax Guy 10 Hours.mp4"])
async def test_websocket_resolve_media(
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, filename
) -> None:
"""Test browse media websocket."""
assert await async_setup_component(hass, media_source.DOMAIN, {})
await hass.async_block_till_done()
client = await hass_ws_client(hass)
media = media_source.models.PlayMedia(
f"/media/local/{filename}",
"audio/mpeg",
)
with patch(
"homeassistant.components.media_source.http.async_resolve_media",
return_value=media,
):
await client.send_json(
{
"id": 1,
"type": "media_source/resolve_media",
"media_content_id": f"{const.URI_SCHEME}{media_source.DOMAIN}/local/{filename}",
}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["id"] == 1
assert msg["result"]["mime_type"] == media.mime_type
# Validate url is relative and signed.
assert msg["result"]["url"][0] == "/"
parsed = yarl.URL(msg["result"]["url"])
assert parsed.path == media.url
assert "authSig" in parsed.query
with patch(
"homeassistant.components.media_source.http.async_resolve_media",
side_effect=media_source.Unresolvable("test"),
):
await client.send_json(
{
"id": 2,
"type": "media_source/resolve_media",
"media_content_id": "invalid",
}
)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == "resolve_media_failed"
assert msg["error"]["message"] == "test"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/media_source/test_http.py",
"license": "Apache License 2.0",
"lines": 102,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nederlandse_spoorwegen/const.py | """Constants for the Nederlandse Spoorwegen integration tests."""
API_KEY = "abc1234567"
# Date/time format strings
DATETIME_FORMAT_LENGTH = 16 # "DD-MM-YYYY HH:MM" format
DATE_SEPARATOR = "-"
DATETIME_SPACE = " "
TIME_SEPARATOR = ":"
# Test route names
TEST_ROUTE_TITLE_1 = "Route 1"
TEST_ROUTE_TITLE_2 = "Route 2"
SUBENTRY_ID_1 = "01K721DZPMEN39R5DK0ATBMSY8"
SUBENTRY_ID_2 = "01K721DZPMEN39R5DK0ATBMSY9"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nederlandse_spoorwegen/const.py",
"license": "Apache License 2.0",
"lines": 12,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nederlandse_spoorwegen/test_config_flow.py | """Test config flow for Nederlandse Spoorwegen integration."""
from datetime import time
from typing import Any
from unittest.mock import AsyncMock
import pytest
from requests import ConnectionError as RequestsConnectionError, HTTPError, Timeout
from homeassistant.components.nederlandse_spoorwegen.const import (
CONF_FROM,
CONF_ROUTES,
CONF_TIME,
CONF_TO,
CONF_VIA,
DOMAIN,
)
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_RECONFIGURE, SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import API_KEY
from tests.common import MockConfigEntry
async def test_full_flow(
hass: HomeAssistant, mock_nsapi: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test successful user config flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: API_KEY}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Nederlandse Spoorwegen"
assert result["data"] == {CONF_API_KEY: API_KEY}
assert len(mock_setup_entry.mock_calls) == 1
async def test_creating_route(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test creating a route after setting up the main config entry."""
mock_config_entry.add_to_hass(hass)
assert len(mock_config_entry.subentries) == 2
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "route"), context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
user_input={
CONF_FROM: "ASD",
CONF_TO: "RTD",
CONF_VIA: "HT",
CONF_NAME: "Home to Work",
CONF_TIME: "08:30",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Home to Work"
assert result["data"] == {
CONF_FROM: "ASD",
CONF_TO: "RTD",
CONF_VIA: "HT",
CONF_NAME: "Home to Work",
CONF_TIME: "08:30",
}
assert len(mock_config_entry.subentries) == 3
@pytest.mark.parametrize(
("exception", "expected_error"),
[
(HTTPError("Invalid API key"), "invalid_auth"),
(Timeout("Cannot connect"), "cannot_connect"),
(RequestsConnectionError("Cannot connect"), "cannot_connect"),
(Exception("Unexpected error"), "unknown"),
],
)
async def test_flow_exceptions(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_setup_entry: AsyncMock,
exception: Exception,
expected_error: str,
) -> None:
"""Test config flow handling different exceptions."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
mock_nsapi.get_stations.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: API_KEY}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": expected_error}
mock_nsapi.get_stations.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: API_KEY}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Nederlandse Spoorwegen"
assert result["data"] == {CONF_API_KEY: API_KEY}
assert len(mock_setup_entry.mock_calls) == 1
async def test_fetching_stations_failed(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test creating a route after setting up the main config entry."""
mock_config_entry.add_to_hass(hass)
assert len(mock_config_entry.subentries) == 2
mock_nsapi.get_stations.side_effect = RequestsConnectionError("Unexpected error")
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, "route"), context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test config flow aborts if already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: API_KEY}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_config_flow_import_success(
hass: HomeAssistant, mock_nsapi: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test successful import flow from YAML configuration."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_API_KEY: API_KEY},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Nederlandse Spoorwegen"
assert result["data"] == {CONF_API_KEY: API_KEY}
assert not result["result"].subentries
@pytest.mark.parametrize(
("routes_data", "expected_routes_data"),
[
(
# Test with uppercase station codes (UI behavior)
[
{
CONF_NAME: "Home to Work",
CONF_FROM: "ASD",
CONF_TO: "RTD",
CONF_VIA: "HT",
CONF_TIME: time(hour=8, minute=30),
}
],
[
{
CONF_NAME: "Home to Work",
CONF_FROM: "ASD",
CONF_TO: "RTD",
CONF_VIA: "HT",
CONF_TIME: time(hour=8, minute=30),
}
],
),
(
# Test with lowercase station codes (converted to uppercase)
[
{
CONF_NAME: "Rotterdam-Amsterdam",
CONF_FROM: "rtd", # lowercase input
CONF_TO: "asd", # lowercase input
},
{
CONF_NAME: "Amsterdam-Haarlem",
CONF_FROM: "asd", # lowercase input
CONF_TO: "ht", # lowercase input
CONF_VIA: "rtd", # lowercase input
},
],
[
{
CONF_NAME: "Rotterdam-Amsterdam",
CONF_FROM: "RTD", # converted to uppercase
CONF_TO: "ASD", # converted to uppercase
},
{
CONF_NAME: "Amsterdam-Haarlem",
CONF_FROM: "ASD", # converted to uppercase
CONF_TO: "HT", # converted to uppercase
CONF_VIA: "RTD", # converted to uppercase
},
],
),
],
)
async def test_config_flow_import_with_routes(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_setup_entry: AsyncMock,
routes_data: list[dict[str, Any]],
expected_routes_data: list[dict[str, Any]],
) -> None:
"""Test import flow with routes from YAML configuration."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_API_KEY: API_KEY,
CONF_ROUTES: routes_data,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Nederlandse Spoorwegen"
assert result["data"] == {CONF_API_KEY: API_KEY}
assert len(result["result"].subentries) == len(expected_routes_data)
subentries = list(result["result"].subentries.values())
for expected_route in expected_routes_data:
route_entry = next(
entry for entry in subentries if entry.title == expected_route[CONF_NAME]
)
assert route_entry.data == expected_route
assert route_entry.subentry_type == "route"
async def test_config_flow_import_with_unknown_station(
hass: HomeAssistant, mock_nsapi: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test import flow aborts with unknown station in routes."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_API_KEY: API_KEY,
CONF_ROUTES: [
{
CONF_NAME: "Home to Work",
CONF_FROM: "HRM",
CONF_TO: "RTD",
CONF_VIA: "HT",
CONF_TIME: time(hour=8, minute=30),
}
],
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "invalid_station"
async def test_config_flow_import_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test import flow when integration is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={CONF_API_KEY: API_KEY},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("exception", "expected_error"),
[
(HTTPError("Invalid API key"), "invalid_auth"),
(Timeout("Cannot connect"), "cannot_connect"),
(RequestsConnectionError("Cannot connect"), "cannot_connect"),
(Exception("Unexpected error"), "unknown"),
],
)
async def test_import_flow_exceptions(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
exception: Exception,
expected_error: str,
) -> None:
"""Test config flow handling different exceptions."""
mock_nsapi.get_stations.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data={CONF_API_KEY: API_KEY}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == expected_error
async def test_reconfigure_success(
hass: HomeAssistant, mock_nsapi: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test successfully reconfiguring (updating) the API key."""
new_key = "new_api_key_123456"
mock_config_entry.add_to_hass(hass)
# Start reconfigure flow
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_RECONFIGURE, "entry_id": mock_config_entry.entry_id},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
# Submit new API key, mock_nsapi.get_stations returns OK by default
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: new_key}
)
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "reconfigure_successful"
# Entry should be updated with the new API key
assert mock_config_entry.data[CONF_API_KEY] == new_key
@pytest.mark.parametrize(
("exception", "expected_error"),
[
(HTTPError("Invalid API key"), "invalid_auth"),
(Timeout("Cannot connect"), "cannot_connect"),
(RequestsConnectionError("Cannot connect"), "cannot_connect"),
(Exception("Unexpected error"), "unknown"),
],
)
async def test_reconfigure_errors(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
expected_error: str,
) -> None:
"""Test reconfigure flow error handling (invalid auth and cannot connect)."""
mock_config_entry.add_to_hass(hass)
# First present the form
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_RECONFIGURE, "entry_id": mock_config_entry.entry_id},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
# Make get_stations raise the requested exception
mock_nsapi.get_stations.side_effect = exception
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: "bad_key"}
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": expected_error}
# Clear side effect and submit valid API key to complete the flow
mock_nsapi.get_stations.side_effect = None
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: "new_valid_key"}
)
assert result3["type"] is FlowResultType.ABORT
assert result3["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_API_KEY] == "new_valid_key"
async def test_reconfigure_already_configured(
hass: HomeAssistant, mock_nsapi: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test reconfiguring with an API key that's already used by another entry."""
# Add first entry
mock_config_entry.add_to_hass(hass)
# Create and add second entry with different API key
second_entry = MockConfigEntry(
domain=DOMAIN,
title="NS Integration 2",
data={CONF_API_KEY: "another_api_key_456"},
unique_id="second_entry",
)
second_entry.add_to_hass(hass)
# Start reconfigure flow for the first entry
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_RECONFIGURE, "entry_id": mock_config_entry.entry_id},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
# Try to reconfigure to use the API key from the second entry
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: "another_api_key_456"}
)
# Should show error that it's already configured
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": "already_configured"}
# Verify the original entry was not changed
assert mock_config_entry.data[CONF_API_KEY] == API_KEY
# Now submit a valid unique API key to complete the flow
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_KEY: "new_unique_key_789"}
)
assert result3["type"] is FlowResultType.ABORT
assert result3["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_API_KEY] == "new_unique_key_789"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nederlandse_spoorwegen/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 390,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nederlandse_spoorwegen/test_sensor.py | """Test the Nederlandse Spoorwegen sensor."""
from collections.abc import Generator
from datetime import date, datetime
from unittest.mock import AsyncMock, patch
import zoneinfo
import pytest
from requests.exceptions import ConnectionError as RequestsConnectionError
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.nederlandse_spoorwegen.const import (
CONF_FROM,
CONF_ROUTES,
CONF_TIME,
CONF_TO,
CONF_VIA,
DOMAIN,
INTEGRATION_TITLE,
SUBENTRY_TYPE_ROUTE,
)
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.config_entries import ConfigSubentryDataWithId
from homeassistant.const import (
CONF_API_KEY,
CONF_NAME,
CONF_PLATFORM,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant
import homeassistant.helpers.entity_registry as er
import homeassistant.helpers.issue_registry as ir
from homeassistant.setup import async_setup_component
from . import setup_integration
from .const import API_KEY
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture(autouse=True)
def mock_sensor_platform() -> Generator:
"""Override PLATFORMS for NS integration."""
with patch(
"homeassistant.components.nederlandse_spoorwegen.PLATFORMS",
[Platform.SENSOR],
) as mock_platform:
yield mock_platform
async def test_config_import(
hass: HomeAssistant,
mock_nsapi,
mock_setup_entry: AsyncMock,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test sensor initialization."""
await async_setup_component(
hass,
SENSOR_DOMAIN,
{
SENSOR_DOMAIN: [
{
CONF_PLATFORM: DOMAIN,
CONF_API_KEY: API_KEY,
CONF_ROUTES: [
{
CONF_NAME: "Spoorwegen Nederlande Station",
CONF_FROM: "ASD",
CONF_TO: "RTD",
CONF_VIA: "HT",
}
],
}
]
},
)
await hass.async_block_till_done()
assert len(issue_registry.issues) == 1
assert (HOMEASSISTANT_DOMAIN, "deprecated_yaml") in issue_registry.issues
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
@pytest.mark.freeze_time("2025-09-15 14:30:00+00:00")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test sensor initialization."""
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.freeze_time("2025-09-15 14:30:00+00:00")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_single_trip_sensor(
hass: HomeAssistant,
mock_single_trip_nsapi: AsyncMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test sensor initialization."""
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.freeze_time("2025-09-15 14:30:00+00:00")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_no_trips_sensor(
hass: HomeAssistant,
mock_no_trips_nsapi: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test sensor initialization."""
await setup_integration(hass, mock_config_entry)
for entity_entry in er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
):
state = hass.states.get(entity_entry.entity_id)
assert state is not None
assert state.state == STATE_UNKNOWN
async def test_sensor_with_api_connection_error(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test sensor behavior when API connection fails."""
# Make API calls fail from the start
mock_nsapi.get_trips.side_effect = RequestsConnectionError("Connection failed")
await setup_integration(hass, mock_config_entry)
await hass.async_block_till_done()
# Sensors should not be created at all if initial API call fails
sensor_states = hass.states.async_all("sensor")
assert len(sensor_states) == 0
@pytest.mark.parametrize(
("time_input", "route_name", "description"),
[
(None, "Current time route", "No specific time - should use current time"),
("08:30", "Morning commute", "Time only - should use today's date with time"),
("08:30:45", "Early commute", "Time with seconds - should truncate seconds"),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_with_custom_time_parsing(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
time_input,
route_name,
description,
) -> None:
"""Test sensor with different time parsing scenarios."""
# Create a config entry with a route that has the specified time
config_entry = MockConfigEntry(
title=INTEGRATION_TITLE,
data={CONF_API_KEY: API_KEY},
domain=DOMAIN,
subentries_data=[
ConfigSubentryDataWithId(
data={
CONF_NAME: route_name,
CONF_FROM: "Ams",
CONF_TO: "Rot",
CONF_VIA: "Ht",
CONF_TIME: time_input,
},
subentry_type=SUBENTRY_TYPE_ROUTE,
title=f"{route_name} Route",
unique_id=None,
subentry_id=f"test_route_{time_input or 'none'}".replace(":", "_")
.replace("-", "_")
.replace(" ", "_"),
),
],
)
await setup_integration(hass, config_entry)
await hass.async_block_till_done()
# Should create 13 sensors for the route with time parsing
sensor_states = hass.states.async_all("sensor")
assert len(sensor_states) == 13
# Verify sensor was created successfully with time parsing
state = sensor_states[0]
assert state is not None
assert state.state != "unavailable"
assert state.attributes.get("attribution") == "Data provided by NS"
# The sensor should have a friendly name based on the route name
friendly_name = state.attributes.get("friendly_name", "").lower()
assert (
route_name.lower() in friendly_name
or route_name.replace(" ", "_").lower() in state.entity_id
)
@pytest.mark.freeze_time("2025-09-15 14:30:00+00:00")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_with_time_filtering(
hass: HomeAssistant,
mock_nsapi: AsyncMock,
) -> None:
"""Test that the time-based window filter correctly filters trips.
This test verifies that:
1. Trips BEFORE the configured time are filtered out
2. Trips AT or AFTER the configured time are included
3. The filtering is based on time-only (ignoring date)
"""
# Create a config entry with a route that has time set to 16:00
# Test frozen at: 2025-09-15 14:30 UTC = 16:30 Amsterdam time
# The fixture includes trips at the following times:
# 16:24/16:25 (trip 0) - FILTERED OUT (departed before 16:30 now)
# 16:34/16:35 (trip 1) - INCLUDED (>= 16:00 configured time AND > 16:30 now)
# With time=16:00, only future trips at or after 16:00 are included
config_entry = MockConfigEntry(
title=INTEGRATION_TITLE,
data={CONF_API_KEY: API_KEY},
domain=DOMAIN,
subentries_data=[
ConfigSubentryDataWithId(
data={
CONF_NAME: "Afternoon commute",
CONF_FROM: "Ams",
CONF_TO: "Rot",
CONF_VIA: "Ht",
CONF_TIME: "16:00",
},
subentry_type=SUBENTRY_TYPE_ROUTE,
title="Afternoon Route",
unique_id=None,
subentry_id="test_route_time_filter",
),
],
)
await setup_integration(hass, config_entry)
await hass.async_block_till_done()
# Should create sensors for the route
sensor_states = hass.states.async_all("sensor")
assert len(sensor_states) == 13
# Find the actual departure time sensor and next departure sensor
actual_departure_sensor = hass.states.get("sensor.afternoon_commute_departure")
next_departure_sensor = hass.states.get("sensor.afternoon_commute_next_departure")
assert actual_departure_sensor is not None, "Actual departure sensor not found"
assert actual_departure_sensor.state != STATE_UNKNOWN
# The sensor state is a UTC timestamp, convert it to Amsterdam time
ams_tz = zoneinfo.ZoneInfo("Europe/Amsterdam")
departure_dt = datetime.fromisoformat(actual_departure_sensor.state)
departure_local = departure_dt.astimezone(ams_tz)
hour = departure_local.hour
minute = departure_local.minute
# Verify first trip: is NOT before 16:00 (i.e., filtered trips are excluded)
assert hour >= 16, (
f"Expected first trip at or after 16:00 Amsterdam time, but got {hour}:{minute:02d}. "
"This means trips before the configured time were NOT filtered out by the time window filter."
)
# Verify next trip also passes the filter
assert next_departure_sensor is not None, "Next departure sensor not found"
next_departure_dt = datetime.fromisoformat(next_departure_sensor.state)
next_departure_local = next_departure_dt.astimezone(ams_tz)
next_hour = next_departure_local.hour
next_minute = next_departure_local.minute
# Verify next trip is also at or after 16:00
assert next_hour >= 16, (
f"Expected next trip at or after 16:00 Amsterdam time, but got {next_hour}:{next_minute:02d}. "
"This means the window filter is not applied consistently to all trips."
)
# Verify next trip is after the first trip
assert (next_hour, next_minute) > (hour, minute), (
f"Expected next trip ({next_hour}:{next_minute:02d}) to be after first trip ({hour}:{minute:02d})"
)
@pytest.mark.freeze_time("2025-09-15 14:30:00+00:00")
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensor_with_time_filtering_next_day(
hass: HomeAssistant,
mock_tomorrow_trips_nsapi: AsyncMock,
) -> None:
"""Test that time filtering automatically rolls over to next day when time is in past.
This test verifies the day boundary logic:
1. When configured time is >1 hour in the past, coordinator queries tomorrow's trips
2. The API is called with tomorrow's date + configured time
3. This ensures users get their morning commute trips even when configured in evening
Example: It's 16:30 (4:30 PM), user configured 08:00 (8:00 AM) for morning commute.
Instead of showing no trips (since 08:00 already passed today), we show tomorrow's 08:00 trips.
"""
# Current time: 16:30 Amsterdam (14:30 UTC frozen)
# Configured time: 08:00 (8.5 hours in the past, >1 hour threshold)
# Expected behavior: Query tomorrow (2025-09-16) at 08:00
config_entry = MockConfigEntry(
title=INTEGRATION_TITLE,
data={CONF_API_KEY: API_KEY},
domain=DOMAIN,
subentries_data=[
ConfigSubentryDataWithId(
data={
CONF_NAME: "Morning commute",
CONF_FROM: "Ams",
CONF_TO: "Rot",
CONF_VIA: "Ht",
CONF_TIME: "08:00",
},
subentry_type=SUBENTRY_TYPE_ROUTE,
title="Morning Route",
unique_id=None,
subentry_id="test_route_morning",
),
],
)
await setup_integration(hass, config_entry)
await hass.async_block_till_done()
# Should create sensors for the route
sensor_states = hass.states.async_all("sensor")
assert len(sensor_states) == 13
# Find the actual departure sensor
actual_departure_sensor = hass.states.get("sensor.morning_commute_departure")
assert actual_departure_sensor is not None, "Actual departure sensor not found"
# The sensor should have a valid trip
assert actual_departure_sensor.state != STATE_UNKNOWN, (
"Expected to have trips from tomorrow when configured time is in the past"
)
# Verify the first trip is tomorrow morning at or after 08:00
# The fixture has trips at 08:24, 08:34 on 2025-09-16 (tomorrow)
departure_dt = datetime.fromisoformat(actual_departure_sensor.state)
ams_tz = zoneinfo.ZoneInfo("Europe/Amsterdam")
departure_local = departure_dt.astimezone(ams_tz)
departure_hour = departure_local.hour
departure_minute = departure_local.minute
departure_date = departure_local.date()
# Verify trip is at or after 08:00 morning time
assert 8 <= departure_hour < 12, (
f"Expected morning trip (08:00-11:59) but got {departure_hour}:{departure_minute:02d}. "
"This means the rollover to tomorrow logic is not working correctly."
)
# Verify trip is from tomorrow (2025-09-16)
expected_date = date(2025, 9, 16)
assert departure_date == expected_date, (
f"Expected trip from tomorrow (2025-09-16) but got {departure_date}. "
"The coordinator should query tomorrow's trips when configured time is >1 hour in the past."
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nederlandse_spoorwegen/test_sensor.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/ntfy/test_event.py | """Tests for the ntfy event platform."""
import asyncio
from collections.abc import AsyncGenerator
from datetime import UTC, datetime, timedelta
from unittest.mock import AsyncMock, patch
from aiontfy import Event
from aiontfy.exceptions import (
NtfyConnectionError,
NtfyForbiddenError,
NtfyHTTPError,
NtfyTimeoutError,
NtfyUnauthorizedAuthenticationError,
)
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.ntfy.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
from tests.components.repairs import (
async_process_repairs_platforms,
process_repair_fix_flow,
start_repair_fix_flow,
)
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True)
async def event_only() -> AsyncGenerator[None]:
"""Enable only the event platform."""
with patch(
"homeassistant.components.ntfy.PLATFORMS",
[Platform.EVENT],
):
yield
@pytest.mark.usefixtures("mock_aiontfy")
@pytest.mark.freeze_time("2025-09-03T22:00:00.000Z")
async def test_event_platform(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test setup of the ntfy event platform."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.usefixtures("mock_aiontfy")
async def test_event(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test ntfy events."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
assert (state := hass.states.get("event.mytopic"))
assert state.state != STATE_UNKNOWN
assert state.attributes == {
"actions": [],
"attachment": None,
"click": "https://example.com/",
"content_type": None,
"entity_picture": "https://example.com/icon.png",
"event": Event.MESSAGE,
"event_type": "Title: Hello",
"event_types": [
"Title: Hello",
],
"expires": datetime(2025, 3, 29, 5, 58, 46, tzinfo=UTC),
"friendly_name": "mytopic",
"icon": "https://example.com/icon.png",
"id": "h6Y2hKA5sy0U",
"message": "Hello",
"priority": 3,
"tags": [
"octopus",
],
"time": datetime(2025, 3, 28, 17, 58, 46, tzinfo=UTC),
"title": "Title",
"topic": "mytopic",
"sequence_id": "Mc3otamDNcpJ",
}
@pytest.mark.parametrize(
("exception", "expected_state"),
[
(
NtfyHTTPError(41801, 418, "I'm a teapot", ""),
STATE_UNAVAILABLE,
),
(
NtfyConnectionError,
STATE_UNAVAILABLE,
),
(
NtfyTimeoutError,
STATE_UNAVAILABLE,
),
(
NtfyUnauthorizedAuthenticationError(40101, 401, "unauthorized"),
STATE_UNAVAILABLE,
),
(
NtfyForbiddenError(403, 403, "forbidden"),
STATE_UNAVAILABLE,
),
(
asyncio.CancelledError,
STATE_UNAVAILABLE,
),
(
asyncio.InvalidStateError,
STATE_UNKNOWN,
),
(
ValueError,
STATE_UNAVAILABLE,
),
],
)
async def test_event_exceptions(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
freezer: FrozenDateTimeFactory,
exception: Exception,
expected_state: str,
) -> None:
"""Test ntfy events exceptions."""
mock_aiontfy.subscribe.side_effect = exception
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
freezer.tick(timedelta(seconds=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get("event.mytopic"))
assert state.state == expected_state
async def test_event_topic_protected(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
freezer: FrozenDateTimeFactory,
issue_registry: ir.IssueRegistry,
entity_registry: er.EntityRegistry,
hass_client: ClientSessionGenerator,
) -> None:
"""Test ntfy events cannot subscribe to protected topic."""
mock_aiontfy.subscribe.side_effect = NtfyForbiddenError(403, 403, "forbidden")
config_entry.add_to_hass(hass)
assert await async_setup_component(hass, "repairs", {})
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
freezer.tick(timedelta(seconds=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get("event.mytopic"))
assert state.state == STATE_UNAVAILABLE
assert issue_registry.async_get_issue(
domain=DOMAIN, issue_id="topic_protected_mytopic"
)
await async_process_repairs_platforms(hass)
client = await hass_client()
result = await start_repair_fix_flow(client, DOMAIN, "topic_protected_mytopic")
flow_id = result["flow_id"]
assert result["step_id"] == "confirm"
result = await process_repair_fix_flow(client, flow_id)
assert result["type"] == "create_entry"
assert (entity := entity_registry.async_get("event.mytopic"))
assert entity.disabled
assert entity.disabled_by is er.RegistryEntryDisabler.USER
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ntfy/test_event.py",
"license": "Apache License 2.0",
"lines": 178,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/ntfy/test_services.py | """Tests for the ntfy notify platform."""
from typing import Any
from aiontfy import BroadcastAction, HttpAction, Message, ViewAction
from aiontfy.exceptions import (
NtfyException,
NtfyHTTPError,
NtfyUnauthorizedAuthenticationError,
)
import pytest
import voluptuous as vol
from yarl import URL
from homeassistant.components import camera, image, media_source
from homeassistant.components.notify import ATTR_MESSAGE, ATTR_TITLE
from homeassistant.components.ntfy.const import DOMAIN
from homeassistant.components.ntfy.services import (
ATTR_ACTIONS,
ATTR_ATTACH,
ATTR_ATTACH_FILE,
ATTR_CALL,
ATTR_CLICK,
ATTR_DELAY,
ATTR_EMAIL,
ATTR_FILENAME,
ATTR_ICON,
ATTR_MARKDOWN,
ATTR_PRIORITY,
ATTR_SEQUENCE_ID,
ATTR_TAGS,
SERVICE_CLEAR,
SERVICE_DELETE,
SERVICE_PUBLISH,
)
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.setup import async_setup_component
from tests.common import AsyncMock, MockConfigEntry, patch
async def test_ntfy_publish(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
) -> None:
"""Test publishing ntfy message via ntfy.publish action."""
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 hass.services.async_call(
DOMAIN,
SERVICE_PUBLISH,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_MESSAGE: "Hello",
ATTR_TITLE: "World",
ATTR_ATTACH: "https://example.org/download.zip",
ATTR_CLICK: "https://example.org",
ATTR_DELAY: {"days": 1, "seconds": 30},
ATTR_ICON: "https://example.org/logo.png",
ATTR_MARKDOWN: True,
ATTR_PRIORITY: "5",
ATTR_TAGS: ["partying_face", "grin"],
ATTR_SEQUENCE_ID: "Mc3otamDNcpJ",
ATTR_ACTIONS: [
{
"action": "broadcast",
"label": "Take picture",
"intent": "com.example.AN_INTENT",
"extras": {"cmd": "pic"},
"clear": True,
},
{
"action": "view",
"label": "Open website",
"url": "https://example.com",
"clear": False,
},
{
"action": "http",
"label": "Close door",
"url": "https://api.example.local/",
"method": "PUT",
"headers": {"Authorization": "Bearer ..."},
"clear": False,
},
],
},
blocking=True,
)
mock_aiontfy.publish.assert_called_once_with(
Message(
topic="mytopic",
message="Hello",
title="World",
tags=["partying_face", "grin"],
priority=5,
click=URL("https://example.org"),
attach=URL("https://example.org/download.zip"),
markdown=True,
icon=URL("https://example.org/logo.png"),
delay="86430.0s",
sequence_id="Mc3otamDNcpJ",
actions=[
BroadcastAction(
label="Take picture",
intent="com.example.AN_INTENT",
extras={"cmd": "pic"},
clear=True,
),
ViewAction(
label="Open website",
url=URL("https://example.com"),
clear=False,
),
HttpAction(
label="Close door",
url=URL("https://api.example.local/"),
method="PUT",
headers={"Authorization": "Bearer ..."},
body=None,
clear=False,
),
],
),
None,
)
@pytest.mark.parametrize(
("exception", "error_msg"),
[
(
NtfyHTTPError(41801, 418, "I'm a teapot", ""),
"Failed to publish notification: I'm a teapot",
),
(
NtfyException,
"Failed to publish notification due to a connection error",
),
(
NtfyUnauthorizedAuthenticationError(40101, 401, "unauthorized"),
"Failed to authenticate with ntfy service. Please verify your credentials",
),
],
)
async def test_send_message_exception(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
exception: Exception,
error_msg: str,
) -> None:
"""Test publish message exceptions."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
mock_aiontfy.publish.side_effect = exception
with pytest.raises(HomeAssistantError, match=error_msg):
await hass.services.async_call(
DOMAIN,
SERVICE_PUBLISH,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_MESSAGE: "triggered",
ATTR_TITLE: "test",
},
blocking=True,
)
mock_aiontfy.publish.assert_called_once_with(
Message(topic="mytopic", message="triggered", title="test"), None
)
@pytest.mark.parametrize(
("exception", "payload", "error_msg"),
[
(
ServiceValidationError,
{ATTR_DELAY: {"days": 1, "seconds": 30}, ATTR_CALL: "1234567890"},
"Delayed call notifications are not supported",
),
(
ServiceValidationError,
{ATTR_DELAY: {"days": 1, "seconds": 30}, ATTR_EMAIL: "mail@example.org"},
"Delayed email notifications are not supported",
),
(
vol.MultipleInvalid,
{
ATTR_ATTACH: "https://example.com/Epic Sax Guy 10 Hours.mp4",
ATTR_ATTACH_FILE: {
"media_content_id": "media-source://media_source/local/Epic Sax Guy 10 Hours.mp4",
"media_content_type": "video/mp4",
},
},
"Only one attachment source is allowed: URL or local file",
),
(
vol.MultipleInvalid,
{
ATTR_FILENAME: "Epic Sax Guy 10 Hours.mp4",
},
"Filename only allowed when attachment is provided",
),
(
vol.MultipleInvalid,
{
ATTR_ACTIONS: [
{"action": "broadcast", "label": "1"},
{"action": "broadcast", "label": "2"},
{"action": "broadcast", "label": "3"},
{"action": "broadcast", "label": "4"},
],
},
"Too many actions defined. A maximum of 3 is supported",
),
],
)
@pytest.mark.usefixtures("mock_aiontfy")
async def test_send_message_validation_errors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
payload: dict[str, Any],
error_msg: str,
exception: type[Exception],
) -> None:
"""Test publish message service validation errors."""
assert await async_setup_component(hass, "media_source", {})
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
with pytest.raises(exception, match=error_msg):
await hass.services.async_call(
DOMAIN,
SERVICE_PUBLISH,
{ATTR_ENTITY_ID: "notify.mytopic", **payload},
blocking=True,
)
@pytest.mark.parametrize(
("service", "call_method"),
[
(SERVICE_PUBLISH, "publish"),
(SERVICE_CLEAR, "clear"),
(SERVICE_DELETE, "delete"),
],
)
async def test_send_message_reauth_flow(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
service: str,
call_method,
) -> None:
"""Test unauthorized exception initiates reauth flow."""
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
getattr(mock_aiontfy, call_method).side_effect = (
NtfyUnauthorizedAuthenticationError(40101, 401, "unauthorized"),
)
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
service,
{ATTR_ENTITY_ID: "notify.mytopic", ATTR_SEQUENCE_ID: "Mc3otamDNcpJ"},
blocking=True,
)
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
flow = flows[0]
assert flow.get("step_id") == "reauth_confirm"
assert flow.get("handler") == DOMAIN
assert "context" in flow
assert flow["context"].get("source") == SOURCE_REAUTH
assert flow["context"].get("entry_id") == config_entry.entry_id
async def test_ntfy_publish_attachment_upload(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
) -> None:
"""Test publishing ntfy message via ntfy.publish action with attachment upload."""
assert await async_setup_component(hass, "media_source", {})
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 hass.services.async_call(
DOMAIN,
SERVICE_PUBLISH,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_ATTACH_FILE: {
"media_content_id": "media-source://media_source/local/Epic Sax Guy 10 Hours.mp4",
"media_content_type": "video/mp4",
},
},
blocking=True,
)
mock_aiontfy.publish.assert_called_once_with(
Message(topic="mytopic", filename="Epic Sax Guy 10 Hours.mp4"),
b"I play the sax\n",
)
async def test_ntfy_publish_upload_camera_snapshot(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
) -> None:
"""Test publishing ntfy message via ntfy.publish action with camera snapshot upload."""
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
with (
patch(
"homeassistant.components.camera.async_get_image",
return_value=camera.Image("image/jpeg", b"I play the sax\n"),
) as mock_get_image,
):
await hass.services.async_call(
DOMAIN,
SERVICE_PUBLISH,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_ATTACH_FILE: {
"media_content_id": "media-source://camera/camera.demo_camera",
"media_content_type": "image/jpeg",
},
ATTR_FILENAME: "Epic Sax Guy 10 Hours.jpg",
},
blocking=True,
)
mock_get_image.assert_called_once_with(hass, "camera.demo_camera")
mock_aiontfy.publish.assert_called_once_with(
Message(topic="mytopic", filename="Epic Sax Guy 10 Hours.jpg"),
b"I play the sax\n",
)
@pytest.mark.usefixtures("mock_aiontfy")
async def test_ntfy_publish_upload_media_source_not_supported(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test publishing ntfy message via ntfy.publish action with unsupported media source."""
assert await async_setup_component(hass, "tts", {})
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
with (
patch(
"homeassistant.components.ntfy.notify.async_resolve_media",
return_value=media_source.PlayMedia(
url="/api/tts_proxy/WDyphPCh3sAoO3koDY87ew.mp3",
mime_type="audio/mpeg",
path=None,
),
),
pytest.raises(
ServiceValidationError,
match="Media source currently not supported",
),
):
await hass.services.async_call(
DOMAIN,
SERVICE_PUBLISH,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_ATTACH_FILE: {
"media_content_id": "media-source://tts/demo?message=Hello+world%21&language=en",
"media_content_type": "audio/mp3",
},
},
blocking=True,
)
@pytest.mark.usefixtures("mock_aiontfy")
async def test_ntfy_publish_upload_media_image_source(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
) -> None:
"""Test publishing ntfy message with image source."""
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
with patch(
"homeassistant.components.image.async_get_image",
return_value=image.Image(content_type="image/jpeg", content=b"\x89PNG"),
) as mock_get_image:
await hass.services.async_call(
DOMAIN,
SERVICE_PUBLISH,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_ATTACH_FILE: {
"media_content_id": "media-source://image/image.test",
"media_content_type": "image/png",
},
},
blocking=True,
)
mock_get_image.assert_called_once_with(hass, "image.test")
mock_aiontfy.publish.assert_called_once_with(Message(topic="mytopic"), b"\x89PNG")
async def test_ntfy_clear(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
) -> None:
"""Test dismiss a ntfy message via ntfy.clear action."""
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 hass.services.async_call(
DOMAIN,
SERVICE_CLEAR,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_SEQUENCE_ID: "Mc3otamDNcpJ",
},
blocking=True,
)
mock_aiontfy.clear.assert_called_once_with("mytopic", "Mc3otamDNcpJ")
@pytest.mark.parametrize(
"exception",
[
NtfyException,
NtfyUnauthorizedAuthenticationError(40101, 401, "unauthorized"),
],
)
async def test_clear_exception(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
exception: Exception,
) -> None:
"""Test clear message exceptions."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
mock_aiontfy.clear.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
SERVICE_CLEAR,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_SEQUENCE_ID: "Mc3otamDNcpJ",
},
blocking=True,
)
mock_aiontfy.clear.assert_called_once_with("mytopic", "Mc3otamDNcpJ")
async def test_ntfy_delete(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
) -> None:
"""Test delete a ntfy message via ntfy.delete action."""
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 hass.services.async_call(
DOMAIN,
SERVICE_DELETE,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_SEQUENCE_ID: "Mc3otamDNcpJ",
},
blocking=True,
)
mock_aiontfy.delete.assert_called_once_with("mytopic", "Mc3otamDNcpJ")
@pytest.mark.parametrize(
"exception",
[
NtfyException,
NtfyUnauthorizedAuthenticationError(40101, 401, "unauthorized"),
],
)
async def test_delete_exception(
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_aiontfy: AsyncMock,
exception: Exception,
) -> None:
"""Test delete message exceptions."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
mock_aiontfy.delete.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
DOMAIN,
SERVICE_DELETE,
{
ATTR_ENTITY_ID: "notify.mytopic",
ATTR_SEQUENCE_ID: "Mc3otamDNcpJ",
},
blocking=True,
)
mock_aiontfy.delete.assert_called_once_with("mytopic", "Mc3otamDNcpJ")
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ntfy/test_services.py",
"license": "Apache License 2.0",
"lines": 501,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/portainer/test_binary_sensor.py | """Tests for the Portainer binary sensor platform."""
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from pyportainer.exceptions import (
PortainerAuthenticationError,
PortainerConnectionError,
PortainerTimeoutError,
)
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.portainer.coordinator import DEFAULT_SCAN_INTERVAL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.fixture(autouse=True)
def enable_all_entities(entity_registry_enabled_by_default: None) -> None:
"""Make sure all entities are enabled."""
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.portainer._PLATFORMS",
[Platform.BINARY_SENSOR],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
@pytest.mark.parametrize(
("exception"),
[
PortainerAuthenticationError("bad creds"),
PortainerConnectionError("cannot connect"),
PortainerTimeoutError("timeout"),
],
)
async def test_refresh_endpoints_exceptions(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test entities go unavailable after coordinator refresh failures, for the endpoint fetch."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_portainer_client.get_endpoints.side_effect = exception
freezer.tick(DEFAULT_SCAN_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow())
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("binary_sensor.practical_morse_status")
assert state.state == STATE_UNAVAILABLE
@pytest.mark.parametrize(
("exception"),
[
PortainerAuthenticationError("bad creds"),
PortainerConnectionError("cannot connect"),
PortainerTimeoutError("timeout"),
],
)
async def test_refresh_containers_exceptions(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test entities go unavailable after coordinator refresh failures, for the container fetch."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_portainer_client.get_containers.side_effect = exception
freezer.tick(DEFAULT_SCAN_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow())
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("binary_sensor.practical_morse_status")
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/portainer/test_binary_sensor.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/portainer/test_config_flow.py | """Test the Portainer config flow."""
from unittest.mock import AsyncMock, MagicMock
from pyportainer.exceptions import (
PortainerAuthenticationError,
PortainerConnectionError,
PortainerTimeoutError,
)
import pytest
from homeassistant.components.portainer.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_API_TOKEN, CONF_URL, CONF_VERIFY_SSL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import MOCK_TEST_CONFIG
from tests.common import MockConfigEntry
MOCK_USER_SETUP = {
CONF_URL: "https://127.0.0.1:9000/",
CONF_API_TOKEN: "test_api_token",
CONF_VERIFY_SSL: True,
}
USER_INPUT_RECONFIGURE = {
CONF_URL: "https://new_domain:9000/",
CONF_API_TOKEN: "new_api_key",
CONF_VERIFY_SSL: True,
}
async def test_form(
hass: HomeAssistant,
mock_portainer_client: MagicMock,
) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_SETUP,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "https://127.0.0.1:9000/"
assert result["data"] == MOCK_TEST_CONFIG
@pytest.mark.parametrize(
("exception", "reason"),
[
(
PortainerAuthenticationError,
"invalid_auth",
),
(
PortainerConnectionError,
"cannot_connect",
),
(
PortainerTimeoutError,
"timeout_connect",
),
(
Exception("Some other error"),
"unknown",
),
],
)
async def test_form_exceptions(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
exception: Exception,
reason: str,
) -> None:
"""Test we handle all exceptions."""
mock_portainer_client.get_endpoints.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_SETUP,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
mock_portainer_client.get_endpoints.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_SETUP,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "https://127.0.0.1:9000/"
assert result["data"] == MOCK_TEST_CONFIG
async def test_duplicate_entry(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test we handle duplicate entries."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_SETUP,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_full_flow_reauth(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full flow of the config flow."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
# There is no user input
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_API_TOKEN: "new_api_key"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_API_TOKEN] == "new_api_key"
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("exception", "reason"),
[
(
PortainerAuthenticationError,
"invalid_auth",
),
(
PortainerConnectionError,
"cannot_connect",
),
(
PortainerTimeoutError,
"timeout_connect",
),
(
Exception("Some other error"),
"unknown",
),
],
)
async def test_reauth_flow_exceptions(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test we handle all exceptions in the reauth flow."""
mock_config_entry.add_to_hass(hass)
mock_portainer_client.get_endpoints.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_API_TOKEN: "new_api_key"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
# Now test that we can recover from the error
mock_portainer_client.get_endpoints.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_API_TOKEN: "new_api_key"},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_API_TOKEN] == "new_api_key"
assert len(mock_setup_entry.mock_calls) == 1
async def test_full_flow_reconfigure(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full flow of the config flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=USER_INPUT_RECONFIGURE,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_API_TOKEN] == "new_api_key"
assert mock_config_entry.data[CONF_URL] == "https://new_domain:9000/"
assert mock_config_entry.data[CONF_VERIFY_SSL] is True
assert len(mock_setup_entry.mock_calls) == 1
async def test_full_flow_reconfigure_unique_id(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full flow of the config flow, this time with a known unique ID."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_SETUP,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert mock_config_entry.data[CONF_API_TOKEN] == "test_api_token"
assert mock_config_entry.data[CONF_URL] == "https://127.0.0.1:9000/"
assert mock_config_entry.data[CONF_VERIFY_SSL] is True
assert len(mock_setup_entry.mock_calls) == 0
@pytest.mark.parametrize(
("exception", "reason"),
[
(
PortainerAuthenticationError,
"invalid_auth",
),
(
PortainerConnectionError,
"cannot_connect",
),
(
PortainerTimeoutError,
"timeout_connect",
),
(
Exception("Some other error"),
"unknown",
),
],
)
async def test_full_flow_reconfigure_exceptions(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test the full flow of the config flow, this time with exceptions."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_portainer_client.get_endpoints.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=USER_INPUT_RECONFIGURE,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
mock_portainer_client.get_endpoints.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=USER_INPUT_RECONFIGURE,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_API_TOKEN] == "new_api_key"
assert mock_config_entry.data[CONF_URL] == "https://new_domain:9000/"
assert mock_config_entry.data[CONF_VERIFY_SSL] is True
assert len(mock_setup_entry.mock_calls) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/portainer/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 284,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/portainer/test_init.py | """Test the Portainer initial specific behavior."""
from unittest.mock import AsyncMock
from pyportainer.exceptions import (
PortainerAuthenticationError,
PortainerConnectionError,
PortainerTimeoutError,
)
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.portainer.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
CONF_API_KEY,
CONF_API_TOKEN,
CONF_HOST,
CONF_URL,
CONF_VERIFY_SSL,
)
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 . import setup_integration
from tests.common import MockConfigEntry
from tests.typing import WebSocketGenerator
@pytest.mark.parametrize(
("exception", "expected_state"),
[
(PortainerAuthenticationError("bad creds"), ConfigEntryState.SETUP_ERROR),
(PortainerConnectionError("cannot connect"), ConfigEntryState.SETUP_RETRY),
(PortainerTimeoutError("timeout"), ConfigEntryState.SETUP_RETRY),
],
)
async def test_setup_exceptions(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
expected_state: ConfigEntryState,
) -> None:
"""Test the _async_setup."""
mock_portainer_client.get_endpoints.side_effect = exception
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state == expected_state
async def test_migrations(hass: HomeAssistant) -> None:
"""Test migration from v1 config entry."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HOST: "http://test_host",
CONF_API_KEY: "test_key",
},
unique_id="1",
version=1,
)
entry.add_to_hass(hass)
assert entry.version == 1
assert CONF_VERIFY_SSL not in entry.data
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert CONF_HOST not in entry.data
assert CONF_API_KEY not in entry.data
assert entry.data[CONF_URL] == "http://test_host"
assert entry.data[CONF_API_TOKEN] == "test_key"
assert entry.data[CONF_VERIFY_SSL] is True
# Confirm we went through all current migrations
assert entry.version == 4
@pytest.mark.parametrize(
("container_id", "expected_result"),
[("1", False), ("5", True)],
ids=("Present container", "Stale container"),
)
async def test_remove_config_entry_device(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
hass_ws_client: WebSocketGenerator,
container_id: str,
expected_result: bool,
) -> None:
"""Test manually removing a stale device."""
assert await async_setup_component(hass, "config", {})
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
device_entry = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={(DOMAIN, f"{mock_config_entry.entry_id}_{container_id}")},
)
ws_client = await hass_ws_client(hass)
response = await ws_client.remove_device(
device_entry.id, mock_config_entry.entry_id
)
assert response["success"] == expected_result
async def test_migration_v3_to_v4(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migration from v3 config entry."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HOST: "http://test_host",
CONF_API_KEY: "test_key",
},
unique_id="1",
version=3,
)
entry.add_to_hass(hass)
assert entry.version == 3
endpoint_device = device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, f"{entry.entry_id}_endpoint_1")},
name="Test Endpoint",
)
original_container_identifier = f"{entry.entry_id}_adguard"
container_device = device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, original_container_identifier)},
via_device=(DOMAIN, f"{entry.entry_id}_endpoint_1"),
name="Test Container",
)
container_entity = entity_registry.async_get_or_create(
domain="switch",
platform=DOMAIN,
unique_id=f"{entry.entry_id}_adguard_container",
config_entry=entry,
device_id=container_device.id,
original_name="Test Container Switch",
)
assert container_device.via_device_id == endpoint_device.id
assert container_device.identifiers == {(DOMAIN, original_container_identifier)}
assert container_entity.unique_id == f"{entry.entry_id}_adguard_container"
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.version == 4
# Fetch again, to assert the new identifiers
container_after = device_registry.async_get(container_device.id)
entity_after = entity_registry.async_get(container_entity.entity_id)
assert container_after.identifiers == {
(DOMAIN, original_container_identifier),
(DOMAIN, f"{entry.entry_id}_1_adguard"),
}
assert entity_after.unique_id == f"{entry.entry_id}_1_adguard_container"
async def test_device_registry(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test devices are correctly registered."""
await setup_integration(hass, mock_config_entry)
device_entries = dr.async_entries_for_config_entry(
device_registry, mock_config_entry.entry_id
)
assert device_entries == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/portainer/test_init.py",
"license": "Apache License 2.0",
"lines": 157,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/prowl/test_notify.py | """Test the Prowl notifications."""
from typing import Any
from unittest.mock import AsyncMock
import prowlpy
import pytest
from homeassistant.components import notify
from homeassistant.components.prowl.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from .conftest import ENTITY_ID, TEST_API_KEY
from tests.common import MockConfigEntry
SERVICE_DATA = {"message": "Test Notification", "title": "Test Title"}
EXPECTED_SEND_PARAMETERS = {
"application": "Home-Assistant",
"event": "Test Title",
"description": "Test Notification",
"priority": 0,
"url": None,
}
@pytest.mark.usefixtures("configure_prowl_through_yaml")
async def test_send_notification_service(
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
) -> None:
"""Set up Prowl, call notify service, and check API call."""
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
await hass.services.async_call(
notify.DOMAIN,
DOMAIN,
SERVICE_DATA,
blocking=True,
)
mock_prowlpy.post.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
async def test_send_notification_entity_service(
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
mock_prowlpy_config_entry: MockConfigEntry,
) -> None:
"""Set up Prowl via config entry, call notify service, and check API call."""
mock_prowlpy_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service(notify.DOMAIN, notify.SERVICE_SEND_MESSAGE)
await hass.services.async_call(
notify.DOMAIN,
notify.SERVICE_SEND_MESSAGE,
{
"entity_id": ENTITY_ID,
notify.ATTR_MESSAGE: SERVICE_DATA["message"],
notify.ATTR_TITLE: SERVICE_DATA["title"],
},
blocking=True,
)
mock_prowlpy.post.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
@pytest.mark.parametrize(
("prowlpy_side_effect", "raised_exception", "exception_message"),
[
(
prowlpy.APIError("Internal server error"),
HomeAssistantError,
"Unexpected error when calling Prowl API",
),
(
TimeoutError,
HomeAssistantError,
"Timeout accessing Prowl API",
),
(
prowlpy.APIError(f"Invalid API key: {TEST_API_KEY}"),
HomeAssistantError,
"Invalid API key for Prowl service",
),
(
prowlpy.APIError(
"Not accepted: Your IP address has exceeded the API limit"
),
HomeAssistantError,
"Prowl service reported: exceeded rate limit",
),
(
SyntaxError(),
SyntaxError,
None,
),
],
)
async def test_fail_send_notification_entity_service(
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
mock_prowlpy_config_entry: MockConfigEntry,
prowlpy_side_effect: Exception,
raised_exception: type[Exception],
exception_message: str | None,
) -> None:
"""Set up Prowl via config entry, call notify service, and check API call."""
mock_prowlpy_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
mock_prowlpy.post.side_effect = prowlpy_side_effect
assert hass.services.has_service(notify.DOMAIN, notify.SERVICE_SEND_MESSAGE)
with pytest.raises(raised_exception, match=exception_message):
await hass.services.async_call(
notify.DOMAIN,
notify.SERVICE_SEND_MESSAGE,
{
"entity_id": ENTITY_ID,
notify.ATTR_MESSAGE: SERVICE_DATA["message"],
notify.ATTR_TITLE: SERVICE_DATA["title"],
},
blocking=True,
)
mock_prowlpy.post.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
@pytest.mark.parametrize(
("prowlpy_side_effect", "raised_exception", "exception_message"),
[
(
prowlpy.APIError("Internal server error"),
HomeAssistantError,
"Unexpected error when calling Prowl API",
),
(
TimeoutError,
HomeAssistantError,
"Timeout accessing Prowl API",
),
(
prowlpy.APIError(f"Invalid API key: {TEST_API_KEY}"),
HomeAssistantError,
"Invalid API key for Prowl service",
),
(
prowlpy.APIError(
"Not accepted: Your IP address has exceeded the API limit"
),
HomeAssistantError,
"Prowl service reported: exceeded rate limit",
),
(
SyntaxError(),
SyntaxError,
None,
),
],
)
@pytest.mark.usefixtures("configure_prowl_through_yaml")
async def test_fail_send_notification(
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
prowlpy_side_effect: Exception,
raised_exception: type[Exception],
exception_message: str | None,
) -> None:
"""Sending a message via Prowl with a failure."""
mock_prowlpy.post.side_effect = prowlpy_side_effect
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
with pytest.raises(raised_exception, match=exception_message):
await hass.services.async_call(
notify.DOMAIN,
DOMAIN,
SERVICE_DATA,
blocking=True,
)
mock_prowlpy.post.assert_called_once_with(**EXPECTED_SEND_PARAMETERS)
@pytest.mark.parametrize(
("service_data", "expected_send_parameters"),
[
(
{"message": "Test Notification", "title": "Test Title"},
{
"application": "Home-Assistant",
"event": "Test Title",
"description": "Test Notification",
"priority": 0,
"url": None,
},
)
],
)
@pytest.mark.usefixtures("configure_prowl_through_yaml")
async def test_other_exception_send_notification(
hass: HomeAssistant,
mock_prowlpy: AsyncMock,
service_data: dict[str, Any],
expected_send_parameters: dict[str, Any],
) -> None:
"""Sending a message via Prowl with a general unhandled exception."""
mock_prowlpy.post.side_effect = SyntaxError
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
with pytest.raises(SyntaxError):
await hass.services.async_call(
notify.DOMAIN,
DOMAIN,
SERVICE_DATA,
blocking=True,
)
mock_prowlpy.post.assert_called_once_with(**expected_send_parameters)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/prowl/test_notify.py",
"license": "Apache License 2.0",
"lines": 196,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/pushover/test_notify.py | """Test the pushover notify platform."""
from unittest.mock import MagicMock, patch
import pytest
from homeassistant.components.pushover import DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
@pytest.fixture(autouse=False)
def mock_pushover():
"""Mock pushover."""
with patch(
"pushover_complete.PushoverAPI._generic_post", return_value={}
) as mock_generic_post:
yield mock_generic_post
@pytest.fixture
def mock_send_message():
"""Patch PushoverAPI.send_message for TTL test."""
with patch(
"homeassistant.components.pushover.notify.PushoverAPI.send_message"
) as mock:
yield mock
async def test_send_message(
hass: HomeAssistant, mock_pushover: MagicMock, mock_send_message: MagicMock
) -> None:
"""Test sending a message."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
"name": "pushover",
"api_key": "API_KEY",
"user_key": "USER_KEY",
},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
"notify",
"pushover",
{"message": "Hello TTL", "data": {"ttl": 900}},
blocking=True,
)
mock_send_message.assert_called_once_with(
user="USER_KEY",
message="Hello TTL",
device="",
title="Home Assistant",
url=None,
url_title=None,
image=None,
priority=None,
retry=None,
expire=None,
callback_url=None,
timestamp=None,
sound=None,
html=0,
ttl=900,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/pushover/test_notify.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/radio_browser/test_media_source.py | """Tests for radio_browser media_source."""
from unittest.mock import AsyncMock
import pytest
from radios import FilterBy, Order
from homeassistant.components import media_source
from homeassistant.components.radio_browser.media_source import async_get_media_source
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
DOMAIN = "radio_browser"
@pytest.fixture(autouse=True)
async def setup_media_source(hass: HomeAssistant) -> None:
"""Set up media source."""
assert await async_setup_component(hass, "media_source", {})
async def test_browsing_local(
hass: HomeAssistant, init_integration: AsyncMock, patch_radios
) -> None:
"""Test browsing local stations."""
hass.config.latitude = 45.58539
hass.config.longitude = -122.40320
hass.config.country = "US"
source = await async_get_media_source(hass)
patch_radios(source)
item = await media_source.async_browse_media(
hass, f"{media_source.URI_SCHEME}{DOMAIN}"
)
assert item is not None
assert item.title == "My Radios"
assert item.children is not None
assert len(item.children) == 5
assert item.can_play is False
assert item.can_expand is True
assert item.children[3].title == "Local stations"
item_child = await media_source.async_browse_media(
hass, item.children[3].media_content_id
)
source.radios.stations.assert_awaited_with(
filter_by=FilterBy.COUNTRY_CODE_EXACT,
filter_term=hass.config.country,
hide_broken=True,
order=Order.NAME,
reverse=False,
)
assert item_child is not None
assert item_child.title == "My Radios"
assert len(item_child.children) == 2
assert item_child.children[0].title == "Near Station 1"
assert item_child.children[1].title == "Near Station 2"
# Test browsing a different category to hit the path where async_build_local
# returns []
other_browse = await media_source.async_browse_media(
hass, f"{media_source.URI_SCHEME}{DOMAIN}/nonexistent"
)
assert other_browse is not None
assert other_browse.title == "My Radios"
assert len(other_browse.children) == 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/radio_browser/test_media_source.py",
"license": "Apache License 2.0",
"lines": 55,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/route_b_smart_meter/test_config_flow.py | """Test the Smart Meter B-route config flow."""
from collections.abc import Generator
from unittest.mock import AsyncMock, Mock, patch
from momonga import MomongaSkJoinFailure, MomongaSkScanFailure
import pytest
from serial.tools.list_ports_linux import SysFS
from homeassistant.components.route_b_smart_meter.const import DOMAIN, ENTRY_TITLE
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_DEVICE, CONF_ID, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
@pytest.fixture
def mock_comports() -> Generator[AsyncMock]:
"""Override comports."""
device = SysFS("/dev/ttyUSB42")
device.vid = 0x1234
device.pid = 0x5678
device.serial_number = "123456"
device.manufacturer = "Test"
device.description = "Test Device"
with patch(
"homeassistant.components.route_b_smart_meter.config_flow.comports",
return_value=[SysFS("/dev/ttyUSB41"), device],
) as mock:
yield mock
async def test_step_user_form(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_comports: AsyncMock,
mock_momonga: Mock,
user_input: dict[str, str],
) -> None:
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert not result["errors"]
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == ENTRY_TITLE
assert result["data"] == user_input
assert result["result"].unique_id == user_input[CONF_ID]
mock_setup_entry.assert_called_once()
mock_comports.assert_called()
mock_momonga.assert_called_once_with(
dev=user_input[CONF_DEVICE],
rbid=user_input[CONF_ID],
pwd=user_input[CONF_PASSWORD],
)
@pytest.mark.parametrize(
("error", "message"),
[
(MomongaSkJoinFailure, "invalid_auth"),
(MomongaSkScanFailure, "cannot_connect"),
(Exception, "unknown"),
],
)
async def test_step_user_form_errors(
hass: HomeAssistant,
error: Exception,
message: str,
mock_setup_entry: AsyncMock,
mock_comports: AsyncMock,
mock_momonga: AsyncMock,
user_input: dict[str, str],
) -> None:
"""Test we handle error."""
result_init = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_momonga.side_effect = error
result_configure = await hass.config_entries.flow.async_configure(
result_init["flow_id"],
user_input,
)
assert result_configure["type"] is FlowResultType.FORM
assert result_configure["errors"] == {"base": message}
await hass.async_block_till_done()
mock_comports.assert_called()
mock_momonga.assert_called_once_with(
dev=user_input[CONF_DEVICE],
rbid=user_input[CONF_ID],
pwd=user_input[CONF_PASSWORD],
)
mock_momonga.side_effect = None
result = await hass.config_entries.flow.async_configure(
result_configure["flow_id"],
user_input,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == ENTRY_TITLE
assert result["data"] == user_input
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/route_b_smart_meter/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 97,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/route_b_smart_meter/test_init.py | """Tests for the Smart Meter B Route integration init."""
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_async_setup_entry_success(
hass: HomeAssistant, mock_momonga, mock_config_entry: MockConfigEntry
) -> None:
"""Test successful setup of entry."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
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/route_b_smart_meter/test_init.py",
"license": "Apache License 2.0",
"lines": 14,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/route_b_smart_meter/test_sensor.py | """Tests for the Smart Meter B-Route sensor."""
from unittest.mock import Mock
from freezegun.api import FrozenDateTimeFactory
from momonga import MomongaError
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.route_b_smart_meter.const import DEFAULT_SCAN_INTERVAL
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import EntityRegistry
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_route_b_smart_meter_sensor_update(
hass: HomeAssistant,
mock_momonga: Mock,
freezer: FrozenDateTimeFactory,
entity_registry: EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the BRouteUpdateCoordinator successful behavior."""
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
freezer.tick(DEFAULT_SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_route_b_smart_meter_sensor_no_update(
hass: HomeAssistant,
mock_momonga: Mock,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the BRouteUpdateCoordinator when failing."""
entity_id = "sensor.route_b_smart_meter_01234567890123456789012345f789_instantaneous_current_r_phase"
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
entity = hass.states.get(entity_id)
assert entity.state == "1"
mock_momonga.return_value.get_instantaneous_current.side_effect = MomongaError
freezer.tick(DEFAULT_SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
entity = hass.states.get(entity_id)
assert entity.state is STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/route_b_smart_meter/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/satel_integra/test_config_flow.py | """Test the satel integra config flow."""
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
from homeassistant.components.satel_integra.const import (
CONF_ARM_HOME_MODE,
CONF_DEVICE_PARTITIONS,
CONF_OUTPUT_NUMBER,
CONF_OUTPUTS,
CONF_PARTITION_NUMBER,
CONF_SWITCHABLE_OUTPUT_NUMBER,
CONF_SWITCHABLE_OUTPUTS,
CONF_ZONE_NUMBER,
CONF_ZONE_TYPE,
CONF_ZONES,
DEFAULT_PORT,
DOMAIN,
)
from homeassistant.config_entries import (
SOURCE_IMPORT,
SOURCE_RECONFIGURE,
SOURCE_USER,
ConfigSubentry,
)
from homeassistant.const import CONF_CODE, CONF_HOST, CONF_NAME, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import (
MOCK_CONFIG_DATA,
MOCK_CONFIG_OPTIONS,
MOCK_OUTPUT_SUBENTRY,
MOCK_PARTITION_SUBENTRY,
MOCK_SWITCHABLE_OUTPUT_SUBENTRY,
MOCK_ZONE_SUBENTRY,
setup_integration,
)
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
("user_input", "entry_data", "entry_options"),
[
(
{**MOCK_CONFIG_DATA, **MOCK_CONFIG_OPTIONS},
MOCK_CONFIG_DATA,
MOCK_CONFIG_OPTIONS,
),
(
{CONF_HOST: MOCK_CONFIG_DATA[CONF_HOST]},
{CONF_HOST: MOCK_CONFIG_DATA[CONF_HOST], CONF_PORT: DEFAULT_PORT},
{CONF_CODE: None},
),
],
)
async def test_setup_flow(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_setup_entry: AsyncMock,
user_input: dict[str, Any],
entry_data: dict[str, Any],
entry_options: dict[str, Any],
) -> None:
"""Test the setup flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == MOCK_CONFIG_DATA[CONF_HOST]
assert result["data"] == entry_data
assert result["options"] == entry_options
assert len(mock_setup_entry.mock_calls) == 1
async def test_setup_connection_failed(
hass: HomeAssistant, mock_satel: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test the setup flow when connection fails."""
user_input = MOCK_CONFIG_DATA
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_satel.connect.return_value = False
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "cannot_connect"}
mock_satel.connect.return_value = True
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("import_input", "entry_data", "entry_options"),
[
(
{
CONF_HOST: MOCK_CONFIG_DATA[CONF_HOST],
CONF_PORT: MOCK_CONFIG_DATA[CONF_PORT],
CONF_CODE: MOCK_CONFIG_OPTIONS[CONF_CODE],
CONF_DEVICE_PARTITIONS: {
"1": {CONF_NAME: "Partition Import 1", CONF_ARM_HOME_MODE: 1}
},
CONF_ZONES: {
"1": {CONF_NAME: "Zone Import 1", CONF_ZONE_TYPE: "motion"},
"2": {CONF_NAME: "Zone Import 2", CONF_ZONE_TYPE: "door"},
},
CONF_OUTPUTS: {
"1": {CONF_NAME: "Output Import 1", CONF_ZONE_TYPE: "light"},
"2": {CONF_NAME: "Output Import 2", CONF_ZONE_TYPE: "safety"},
},
CONF_SWITCHABLE_OUTPUTS: {
"1": {CONF_NAME: "Switchable output Import 1"},
"2": {CONF_NAME: "Switchable output Import 2"},
},
},
MOCK_CONFIG_DATA,
MOCK_CONFIG_OPTIONS,
)
],
)
async def test_import_flow(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_setup_entry: AsyncMock,
import_input: dict[str, Any],
entry_data: dict[str, Any],
entry_options: dict[str, Any],
) -> None:
"""Test the import flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=import_input
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == MOCK_CONFIG_DATA[CONF_HOST]
assert result["data"] == entry_data
assert result["options"] == entry_options
assert len(result["subentries"]) == 7
assert len(mock_setup_entry.mock_calls) == 1
async def test_import_flow_connection_failure(
hass: HomeAssistant, mock_satel: AsyncMock
) -> None:
"""Test the import flow."""
mock_satel.connect.return_value = False
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=MOCK_CONFIG_DATA,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
@pytest.mark.parametrize(
("user_input", "entry_options"),
[
({CONF_CODE: "1111"}, {CONF_CODE: "1111"}),
({}, {CONF_CODE: None}),
],
)
async def test_options_flow(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_reload_after_entry_update: MagicMock,
mock_config_entry: MockConfigEntry,
user_input: dict[str, Any],
entry_options: dict[str, Any],
) -> None:
"""Test general options flow."""
await setup_integration(hass, mock_config_entry)
result = await hass.config_entries.options.async_init(mock_config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"], user_input
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert mock_config_entry.options == entry_options
# Assert the entry is reloaded to use the updated code
assert mock_reload_after_entry_update.call_count == 1
@pytest.mark.parametrize(
("user_input", "subentry"),
[
(MOCK_PARTITION_SUBENTRY.data, MOCK_PARTITION_SUBENTRY),
(MOCK_ZONE_SUBENTRY.data, MOCK_ZONE_SUBENTRY),
(MOCK_OUTPUT_SUBENTRY.data, MOCK_OUTPUT_SUBENTRY),
(MOCK_SWITCHABLE_OUTPUT_SUBENTRY.data, MOCK_SWITCHABLE_OUTPUT_SUBENTRY),
],
)
async def test_subentry_creation(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_reload_after_entry_update: MagicMock,
mock_config_entry: MockConfigEntry,
user_input: dict[str, Any],
subentry: ConfigSubentry,
) -> None:
"""Test partitions options flow."""
await setup_integration(hass, mock_config_entry)
result = await hass.config_entries.subentries.async_init(
(mock_config_entry.entry_id, subentry.subentry_type),
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,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert len(mock_config_entry.subentries) == 1
subentry_id = list(mock_config_entry.subentries)[0]
subentry_result = {
**subentry.as_dict(),
"subentry_id": subentry_id,
}
assert mock_config_entry.subentries.get(subentry_id) == ConfigSubentry(
**subentry_result
)
# Assert the entry is reloaded to set up the entity
assert mock_reload_after_entry_update.call_count == 1
@pytest.mark.parametrize(
(
"user_input",
"subentry",
"number_property",
),
[
(
{CONF_NAME: "New Home", CONF_ARM_HOME_MODE: 3},
MOCK_PARTITION_SUBENTRY,
CONF_PARTITION_NUMBER,
),
(
{CONF_NAME: "Backdoor", CONF_ZONE_TYPE: BinarySensorDeviceClass.DOOR},
MOCK_ZONE_SUBENTRY,
CONF_ZONE_NUMBER,
),
(
{
CONF_NAME: "Alarm Triggered",
CONF_ZONE_TYPE: BinarySensorDeviceClass.PROBLEM,
},
MOCK_OUTPUT_SUBENTRY,
CONF_OUTPUT_NUMBER,
),
(
{CONF_NAME: "Gate Lock"},
MOCK_SWITCHABLE_OUTPUT_SUBENTRY,
CONF_SWITCHABLE_OUTPUT_NUMBER,
),
],
)
async def test_subentry_reconfigure(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
user_input: dict[str, Any],
subentry: ConfigSubentry,
number_property: str,
) -> None:
"""Test subentry reconfiguration."""
await setup_integration(hass, mock_config_entry_with_subentries)
result = await hass.config_entries.subentries.async_init(
(
mock_config_entry_with_subentries.entry_id,
subentry.subentry_type,
),
context={
"source": SOURCE_RECONFIGURE,
"subentry_id": subentry.subentry_id,
},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
user_input,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert len(mock_config_entry_with_subentries.subentries) == 4
subentry_result = {
**subentry.as_dict(),
"data": {**subentry.data, **user_input},
"title": f"{user_input.get(CONF_NAME)} ({subentry.data[number_property]})",
}
assert mock_config_entry_with_subentries.subentries.get(
subentry.subentry_id
) == ConfigSubentry(**subentry_result)
@pytest.mark.parametrize(
("subentry", "error_field"),
[
(MOCK_PARTITION_SUBENTRY, CONF_PARTITION_NUMBER),
(MOCK_ZONE_SUBENTRY, CONF_ZONE_NUMBER),
(MOCK_OUTPUT_SUBENTRY, CONF_OUTPUT_NUMBER),
(MOCK_SWITCHABLE_OUTPUT_SUBENTRY, CONF_SWITCHABLE_OUTPUT_NUMBER),
],
)
async def test_cannot_create_same_subentry(
hass: HomeAssistant,
mock_satel: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry_with_subentries: MockConfigEntry,
subentry: ConfigSubentry,
error_field: str,
) -> None:
"""Test subentry reconfiguration."""
await setup_integration(hass, mock_config_entry_with_subentries)
mock_setup_entry.reset_mock()
result = await hass.config_entries.subentries.async_init(
(mock_config_entry_with_subentries.entry_id, subentry.subentry_type),
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"], {**subentry.data}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {error_field: "already_configured"}
assert len(mock_config_entry_with_subentries.subentries) == 4
assert len(mock_setup_entry.mock_calls) == 0
async def test_same_host_config_disallowed(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test that only one Satel Integra configuration is allowed."""
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"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
MOCK_CONFIG_DATA,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/satel_integra/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 346,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/satel_integra/test_diagnostics.py | """Tests for satel integra diagnostics."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_diagnostics(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
hass_client: ClientSessionGenerator,
mock_config_entry_with_subentries: MockConfigEntry,
mock_satel: AsyncMock,
) -> None:
"""Test diagnostics for config entry."""
await setup_integration(hass, mock_config_entry_with_subentries)
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry_with_subentries
)
assert diagnostics == snapshot(exclude=props("created_at", "modified_at", "id"))
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/satel_integra/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/sftp_storage/asyncssh_mock.py | """Mock classes for asyncssh module."""
from __future__ import annotations
import json
from typing import Self
from unittest.mock import AsyncMock
from asyncssh.misc import async_context_manager
class SSHClientConnectionMock:
"""Class that mocks SSH Client connection."""
def __init__(self, *args, **kwargs) -> None:
"""Initialize SSHClientConnectionMock."""
self._sftp: SFTPClientMock = SFTPClientMock()
async def __aenter__(self) -> Self:
"""Allow SSHClientConnectionMock to be used as an async context manager."""
return self
async def __aexit__(self, *args) -> None:
"""Allow SSHClientConnectionMock to be used as an async context manager."""
self.close()
def close(self):
"""Mock `close` from `SSHClientConnection`."""
return
def mock_setup_backup(self, metadata: dict, with_bad: bool = False) -> str:
"""Setup mocks to properly return a backup.
Return: Backup ID (slug)
"""
slug = metadata["metadata"]["backup_id"]
side_effect = [
json.dumps(metadata), # from async_list_backups
json.dumps(metadata), # from iter_file -> _load_metadata
b"backup data", # from AsyncFileIterator
b"",
]
self._sftp._mock_listdir.return_value = [f"{slug}.metadata.json"]
if with_bad:
side_effect.insert(0, "invalid")
self._sftp._mock_listdir.return_value = [
"invalid.metadata.json",
f"{slug}.metadata.json",
]
self._sftp._mock_open._mock_read.side_effect = side_effect
return slug
@async_context_manager
async def start_sftp_client(self, *args, **kwargs) -> SFTPClientMock:
"""Return mocked SFTP Client."""
return self._sftp
async def wait_closed(self):
"""Mock `wait_closed` from `SFTPClient`."""
return
class SFTPClientMock:
"""Class that mocks SFTP Client connection."""
def __init__(self, *args, **kwargs) -> None:
"""Initialize `SFTPClientMock`."""
self._mock_chdir = AsyncMock()
self._mock_listdir = AsyncMock()
self._mock_exists = AsyncMock(return_value=True)
self._mock_unlink = AsyncMock()
self._mock_open = SFTPOpenMock()
async def __aenter__(self) -> Self:
"""Allow SFTPClientMock to be used as an async context manager."""
return self
async def __aexit__(self, *args) -> None:
"""Allow SFTPClientMock to be used as an async context manager."""
self.exit()
async def chdir(self, *args) -> None:
"""Mock `chdir` method from SFTPClient."""
await self._mock_chdir(*args)
async def listdir(self, *args) -> list[str]:
"""Mock `listdir` method from SFTPClient."""
result = await self._mock_listdir(*args)
return result if result is not None else []
@async_context_manager
async def open(self, *args, **kwargs) -> SFTPOpenMock:
"""Mock open a remote file."""
return self._mock_open
async def exists(self, *args) -> bool:
"""Mock `exists` method from SFTPClient."""
return await self._mock_exists(*args)
async def unlink(self, *args) -> None:
"""Mock `unlink` method from SFTPClient."""
await self._mock_unlink(*args)
def exit(self):
"""Mandatory method for quitting SFTP Client."""
return
async def wait_closed(self):
"""Mock `wait_closed` from `SFTPClient`."""
return
class SFTPOpenMock:
"""Mocked remote file."""
def __init__(self) -> None:
"""Initialize arguments for mocked responses."""
self._mock_read = AsyncMock(return_value=b"")
self._mock_write = AsyncMock()
self.close = AsyncMock(return_value=None)
async def __aenter__(self):
"""Allow SFTPOpenMock to be used as an async context manager."""
return self
async def __aexit__(self, *args) -> None:
"""Allow SFTPOpenMock to be used as an async context manager."""
async def read(self, *args, **kwargs) -> bytes:
"""Read remote file - mocked response from `self._mock_read`."""
return await self._mock_read(*args, **kwargs)
async def write(self, content, *args, **kwargs) -> int:
"""Mock write to remote file."""
await self._mock_write(content, *args, **kwargs)
return len(content)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sftp_storage/asyncssh_mock.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/sftp_storage/test_backup.py | """Test the Backup SFTP Location platform."""
from io import StringIO
import json
from typing import Any
from unittest.mock import MagicMock, patch
from asyncssh.sftp import SFTPError
import pytest
from homeassistant.components.sftp_storage.backup import (
async_register_backup_agents_listener,
)
from homeassistant.components.sftp_storage.const import (
DATA_BACKUP_AGENT_LISTENERS,
DOMAIN,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from .asyncssh_mock import SSHClientConnectionMock
from .conftest import (
BACKUP_METADATA,
CONFIG_ENTRY_TITLE,
TEST_AGENT_BACKUP,
TEST_AGENT_ID,
ComponentSetup,
)
from tests.typing import ClientSessionGenerator, WebSocketGenerator
@pytest.fixture(autouse=True)
async def mock_setup_integration(
setup_integration: ComponentSetup,
) -> None:
"""Set up the integration automatically for backup tests."""
await setup_integration()
def generate_result(metadata: dict) -> dict:
"""Generates an expected result from metadata."""
expected_result: dict = metadata["metadata"].copy()
expected_result["agents"] = {
f"{DOMAIN}.{TEST_AGENT_ID}": {
"protected": expected_result.pop("protected"),
"size": expected_result.pop("size"),
}
}
expected_result.update(
{
"failed_addons": [],
"failed_agent_ids": [],
"failed_folders": [],
"with_automatic_settings": None,
}
)
return expected_result
async def test_agents_info(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test backup agent info."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/agents/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
"agents": [
{"agent_id": "backup.local", "name": "local"},
{"agent_id": f"{DOMAIN}.{TEST_AGENT_ID}", "name": CONFIG_ENTRY_TITLE},
],
}
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
await hass.config_entries.async_unload(config_entry.entry_id)
await client.send_json_auto_id({"type": "backup/agents/info"})
response = await client.receive_json()
assert response["success"]
assert (
response["result"]
== {"agents": [{"agent_id": "backup.local", "name": "local"}]}
or config_entry.state == ConfigEntryState.NOT_LOADED
)
async def test_agents_list_backups(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent list backups."""
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA)
expected_result = generate_result(BACKUP_METADATA)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backups"] == [expected_result]
async def test_agents_list_backups_fail(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent list backups fails."""
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA)
mock_ssh_connection._sftp._mock_open._mock_read.side_effect = SFTPError(
2, "Error message"
)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"]["backups"] == []
assert response["result"]["agent_errors"] == {
f"{DOMAIN}.{TEST_AGENT_ID}": "Remote server error while attempting to list backups: Error message"
}
async def test_agents_list_backups_include_bad_metadata(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_ssh_connection: SSHClientConnectionMock,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test agent list backups."""
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA, with_bad=True)
expected_result = generate_result(BACKUP_METADATA)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backups"] == [expected_result]
# Called two times, one for bad backup metadata and once for good
assert mock_ssh_connection._sftp._mock_open._mock_read.call_count == 2
assert (
"Failed to load backup metadata from file: /backup_location/invalid.metadata.json. Expecting value: line 1 column 1 (char 0)"
in caplog.messages
)
@pytest.mark.parametrize(
("backup_id", "expected_result"),
[
(TEST_AGENT_BACKUP.backup_id, generate_result(BACKUP_METADATA)),
("12345", None),
],
ids=["found", "not_found"],
)
async def test_agents_get_backup(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
backup_id: str,
expected_result: dict[str, Any] | None,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent get backup."""
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA)
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/details", "backup_id": backup_id})
response = await client.receive_json()
assert response["success"]
assert response["result"]["backup"] == expected_result
async def test_agents_download(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent download backup."""
client = await hass_client()
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA)
resp = await client.get(
f"/api/backup/download/{TEST_AGENT_BACKUP.backup_id}?agent_id={DOMAIN}.{TEST_AGENT_ID}"
)
assert resp.status == 200
assert await resp.content.read() == b"backup data"
mock_ssh_connection._sftp._mock_open.close.assert_awaited()
async def test_agents_download_fail(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent download backup fails."""
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA)
# This will cause `FileNotFoundError` exception in `BackupAgentClient.iter_file() method.`
mock_ssh_connection._sftp._mock_exists.side_effect = [True, False]
client = await hass_client()
resp = await client.get(
f"/api/backup/download/{TEST_AGENT_BACKUP.backup_id}?agent_id={DOMAIN}.{TEST_AGENT_ID}"
)
assert resp.status == 404
# This will raise `RuntimeError` causing Internal Server Error, mimicking that the SFTP setup failed.
mock_ssh_connection._sftp = None
resp = await client.get(
f"/api/backup/download/{TEST_AGENT_BACKUP.backup_id}?agent_id={DOMAIN}.{TEST_AGENT_ID}"
)
assert resp.status == 500
content = await resp.content.read()
assert b"Internal Server Error" in content
async def test_agents_download_metadata_not_found(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent download backup raises error if not found."""
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA)
mock_ssh_connection._sftp._mock_exists.return_value = False
client = await hass_client()
resp = await client.get(
f"/api/backup/download/{TEST_AGENT_BACKUP.backup_id}?agent_id={DOMAIN}.{TEST_AGENT_ID}"
)
assert resp.status == 404
content = await resp.content.read()
assert content.decode() == ""
async def test_agents_upload(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent upload backup."""
client = await hass_client()
with (
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=TEST_AGENT_BACKUP,
),
):
resp = await client.post(
f"/api/backup/upload?agent_id={DOMAIN}.{TEST_AGENT_ID}",
data={"file": StringIO("test")},
)
assert resp.status == 201
assert f"Uploading backup: {TEST_AGENT_BACKUP.backup_id}" in caplog.text
assert (
f"Successfully uploaded backup id: {TEST_AGENT_BACKUP.backup_id}" in caplog.text
)
# Called write 2 times
# 1. When writing backup file
# 2. When writing metadata file
assert mock_ssh_connection._sftp._mock_open._mock_write.call_count == 2
# This is 'backup file'
assert (
b"test"
in mock_ssh_connection._sftp._mock_open._mock_write.call_args_list[0].args
)
# This is backup metadata
uploaded_metadata = json.loads(
mock_ssh_connection._sftp._mock_open._mock_write.call_args_list[1].args[0]
)["metadata"]
assert uploaded_metadata == BACKUP_METADATA["metadata"]
async def test_agents_upload_fail(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent upload backup fails."""
client = await hass_client()
mock_ssh_connection._sftp._mock_open._mock_write.side_effect = SFTPError(
2, "Error message"
)
with (
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=TEST_AGENT_BACKUP,
),
):
resp = await client.post(
f"/api/backup/upload?agent_id={DOMAIN}.{TEST_AGENT_ID}",
data={"file": StringIO("test")},
)
assert resp.status == 201
assert (
f"Unexpected error for {DOMAIN}.{TEST_AGENT_ID}: Error message"
in caplog.messages
)
async def test_agents_delete(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent delete backup."""
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA)
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": TEST_AGENT_BACKUP.backup_id,
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {"agent_errors": {}}
# Called 2 times, to remove metadata and backup file.
assert mock_ssh_connection._sftp._mock_unlink.call_count == 2
@pytest.mark.parametrize(
("exists_side_effect", "expected_result"),
[
(
[True, False],
{"agent_errors": {}},
), # First `True` is to confirm the metadata file exists
(
SFTPError(0, "manual"),
{
"agent_errors": {
f"{DOMAIN}.{TEST_AGENT_ID}": f"Failed to delete backup id: {TEST_AGENT_BACKUP.backup_id}: manual"
}
},
),
],
ids=["file_not_found_exc", "sftp_error_exc"],
)
async def test_agents_delete_fail(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_ssh_connection: SSHClientConnectionMock,
exists_side_effect: bool | Exception,
expected_result: dict[str, dict[str, str]],
) -> None:
"""Test agent delete backup fails."""
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA)
mock_ssh_connection._sftp._mock_exists.side_effect = exists_side_effect
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": TEST_AGENT_BACKUP.backup_id,
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == expected_result
async def test_agents_delete_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test agent delete backup not found."""
mock_ssh_connection.mock_setup_backup(BACKUP_METADATA)
client = await hass_ws_client(hass)
backup_id = "1234"
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": backup_id,
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {"agent_errors": {}}
async def test_listeners_get_cleaned_up(hass: HomeAssistant) -> None:
"""Test listener gets cleaned up."""
listener = MagicMock()
remove_listener = async_register_backup_agents_listener(hass, listener=listener)
hass.data[DATA_BACKUP_AGENT_LISTENERS] = [
listener
] # make sure it's the last listener
remove_listener()
assert DATA_BACKUP_AGENT_LISTENERS not in hass.data
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sftp_storage/test_backup.py",
"license": "Apache License 2.0",
"lines": 347,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/sftp_storage/test_config_flow.py | """Tests config_flow."""
from collections.abc import Awaitable, Callable
from pathlib import Path
from tempfile import NamedTemporaryFile
from unittest.mock import patch
from asyncssh import KeyImportError, generate_private_key
from asyncssh.misc import PermissionDenied
from asyncssh.sftp import SFTPNoSuchFile, SFTPPermissionDenied
import pytest
from homeassistant.components.sftp_storage.config_flow import (
SFTPStorageInvalidPrivateKey,
SFTPStorageMissingPasswordOrPkey,
)
from homeassistant.components.sftp_storage.const import (
CONF_BACKUP_LOCATION,
CONF_HOST,
CONF_PASSWORD,
CONF_PRIVATE_KEY_FILE,
CONF_USERNAME,
DOMAIN,
)
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.storage import STORAGE_DIR
from .conftest import USER_INPUT, SSHClientConnectionMock
from tests.common import MockConfigEntry
type ComponentSetup = Callable[[], Awaitable[None]]
@pytest.fixture
def mock_process_uploaded_file(hass: HomeAssistant):
"""Mocks ability to process uploaded private key."""
# Ensure .storage directory exists, as it would in a real HA instance
Path(hass.config.path(STORAGE_DIR)).mkdir(parents=True, exist_ok=True)
with (
patch(
"homeassistant.components.sftp_storage.config_flow.process_uploaded_file"
) as mock_process_uploaded_file,
patch("shutil.move") as mock_shutil_move,
NamedTemporaryFile() as f,
):
pkey = generate_private_key("ssh-rsa")
f.write(pkey.export_private_key("pkcs8-pem"))
f.flush()
mock_process_uploaded_file.return_value.__enter__.return_value = f.name
mock_shutil_move.return_value = f.name
yield
@pytest.mark.usefixtures("current_request_with_host")
@pytest.mark.usefixtures("mock_process_uploaded_file")
@pytest.mark.usefixtures("mock_ssh_connection")
async def test_backup_sftp_full_flow(
hass: HomeAssistant,
) -> None:
"""Test the full backup_sftp config flow with valid user input."""
user_input = USER_INPUT.copy()
# Start the configuration flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
# The first step should be the "user" form.
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
# Verify that a new config entry is created.
assert result["type"] is FlowResultType.CREATE_ENTRY
expected_title = f"{user_input[CONF_USERNAME]}@{user_input[CONF_HOST]}"
assert result["title"] == expected_title
# Make sure to match the `private_key_file` from entry
user_input[CONF_PRIVATE_KEY_FILE] = result["data"][CONF_PRIVATE_KEY_FILE]
assert result["data"] == user_input
@pytest.mark.usefixtures("current_request_with_host")
@pytest.mark.usefixtures("mock_process_uploaded_file")
@pytest.mark.usefixtures("mock_ssh_connection")
async def test_already_configured(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test successful failure of already added config entry."""
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], USER_INPUT
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("exception_type", "error_base"),
[
(OSError, "os_error"),
(SFTPStorageInvalidPrivateKey, "invalid_key"),
(PermissionDenied, "permission_denied"),
(SFTPStorageMissingPasswordOrPkey, "key_or_password_needed"),
(SFTPNoSuchFile, "sftp_no_such_file"),
(SFTPPermissionDenied, "sftp_permission_denied"),
(Exception, "unknown"),
],
)
@pytest.mark.usefixtures("current_request_with_host")
@pytest.mark.usefixtures("mock_process_uploaded_file")
async def test_config_flow_exceptions(
exception_type: Exception,
error_base: str,
hass: HomeAssistant,
config_entry: MockConfigEntry,
mock_ssh_connection: SSHClientConnectionMock,
) -> None:
"""Test successful failure of already added config entry."""
mock_ssh_connection._sftp._mock_chdir.side_effect = exception_type("Error message.")
# config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], USER_INPUT
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] and result["errors"]["base"] == error_base
# Recover from the error
mock_ssh_connection._sftp._mock_chdir.side_effect = None
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], USER_INPUT
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("current_request_with_host")
@pytest.mark.usefixtures("mock_process_uploaded_file")
async def test_config_entry_error(hass: HomeAssistant) -> None:
"""Test config flow with raised `KeyImportError`."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["step_id"] == "user"
with (
patch(
"homeassistant.components.sftp_storage.config_flow.SSHClientConnectionOptions",
side_effect=KeyImportError("Invalid key"),
),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], USER_INPUT
)
assert "errors" in result and result["errors"]["base"] == "invalid_key"
user_input = USER_INPUT.copy()
user_input[CONF_PASSWORD] = ""
del user_input[CONF_PRIVATE_KEY_FILE]
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
assert "errors" in result and result["errors"]["base"] == "key_or_password_needed"
@pytest.mark.usefixtures("current_request_with_host")
@pytest.mark.usefixtures("mock_process_uploaded_file")
@pytest.mark.usefixtures("mock_ssh_connection")
async def test_relative_backup_location_rejected(
hass: HomeAssistant,
) -> None:
"""Test that a relative backup location path is rejected."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["step_id"] == "user"
user_input = USER_INPUT.copy()
user_input[CONF_BACKUP_LOCATION] = "backups"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {CONF_BACKUP_LOCATION: "backup_location_relative"}
# Fix the path and verify the flow succeeds
user_input[CONF_BACKUP_LOCATION] = "/backups"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
assert result["type"] is FlowResultType.CREATE_ENTRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sftp_storage/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 183,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/sftp_storage/test_init.py | """Tests for SFTP Storage."""
from pathlib import Path
from unittest.mock import patch
from asyncssh.sftp import SFTPPermissionDenied
import pytest
from homeassistant.components.sftp_storage import SFTPConfigEntryData
from homeassistant.components.sftp_storage.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.util.ulid import ulid
from .asyncssh_mock import SSHClientConnectionMock
from .conftest import (
CONF_BACKUP_LOCATION,
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_PRIVATE_KEY_FILE,
CONF_USERNAME,
USER_INPUT,
ComponentSetup,
create_private_key_file,
)
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_ssh_connection")
async def test_setup_and_unload(
hass: HomeAssistant,
setup_integration: ComponentSetup,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test successful setup and unload."""
# Patch the `exists` function of Path so that we can also
# test the `homeassistant.components.sftp_storage.client.get_client_keys()` function
with (
patch(
"homeassistant.components.sftp_storage.client.SSHClientConnectionOptions"
),
patch("pathlib.Path.exists", return_value=True),
):
await setup_integration()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(entries[0].entry_id)
assert entries[0].state is ConfigEntryState.NOT_LOADED
assert (
f"Unloading {DOMAIN} integration for host {entries[0].data[CONF_USERNAME]}@{entries[0].data[CONF_HOST]}"
in caplog.messages
)
async def test_setup_error(
mock_ssh_connection: SSHClientConnectionMock,
hass: HomeAssistant,
setup_integration: ComponentSetup,
) -> None:
"""Test setup error."""
mock_ssh_connection._sftp._mock_chdir.side_effect = SFTPPermissionDenied(
"Error message"
)
await setup_integration()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is ConfigEntryState.SETUP_ERROR
async def test_setup_unexpected_error(
hass: HomeAssistant,
setup_integration: ComponentSetup,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test setup error."""
with patch(
"homeassistant.components.sftp_storage.client.connect",
side_effect=OSError("Error message"),
):
await setup_integration()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].state is ConfigEntryState.SETUP_ERROR
assert (
"Failure while attempting to establish SSH connection. Please check SSH credentials and if changed, re-install the integration"
in caplog.text
)
async def test_async_remove_entry(
hass: HomeAssistant,
setup_integration: ComponentSetup,
) -> None:
"""Test async_remove_entry."""
# Setup default config entry
await setup_integration()
# Setup additional config entry
agent_id = ulid()
private_key = create_private_key_file(hass)
new_config_entry = MockConfigEntry(
domain=DOMAIN,
entry_id=agent_id,
unique_id=agent_id,
title="another@192.168.0.100",
data={
CONF_HOST: "127.0.0.1",
CONF_PORT: 22,
CONF_USERNAME: "another",
CONF_PASSWORD: "password",
CONF_PRIVATE_KEY_FILE: str(private_key),
CONF_BACKUP_LOCATION: "backup_location",
},
)
new_config_entry.add_to_hass(hass)
await setup_integration(new_config_entry)
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 2
config_entry = entries[0]
private_key = Path(config_entry.data[CONF_PRIVATE_KEY_FILE])
new_private_key = Path(new_config_entry.data[CONF_PRIVATE_KEY_FILE])
# Make sure private keys from both configs exists
assert private_key.parent == new_private_key.parent
assert private_key.exists()
assert new_private_key.exists()
# Remove first config entry - the private key from second will still be in filesystem
# as well as integration storage directory
assert await hass.config_entries.async_remove(config_entry.entry_id)
assert not private_key.exists()
assert new_private_key.exists()
assert new_private_key.parent.exists()
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
# Remove the second config entry, ensuring all files and integration storage directory removed.
assert await hass.config_entries.async_remove(new_config_entry.entry_id)
assert not new_private_key.exists()
assert not new_private_key.parent.exists()
assert hass.config_entries.async_entries(DOMAIN) == []
assert config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
("patch_target", "expected_logs"),
[
(
"os.unlink",
[
"Failed to remove private key",
f"Storage directory for {DOMAIN} integration is not empty",
],
),
("os.rmdir", ["Error occurred while removing directory"]),
],
)
async def test_async_remove_entry_errors(
patch_target: str,
expected_logs: list[str],
hass: HomeAssistant,
setup_integration: ComponentSetup,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test async_remove_entry."""
# Setup default config entry
await setup_integration()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
config_entry = entries[0]
with patch(patch_target, side_effect=OSError(13, "Permission denied")):
await hass.config_entries.async_remove(config_entry.entry_id)
for logline in expected_logs:
assert logline in caplog.text
async def test_config_entry_data_password_hidden() -> None:
"""Test hiding password in `SFTPConfigEntryData` string representation."""
user_input = USER_INPUT.copy()
entry_data = SFTPConfigEntryData(**user_input)
assert "password=" not in str(entry_data)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sftp_storage/test_init.py",
"license": "Apache License 2.0",
"lines": 162,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/switchbot_cloud/test_climate.py | """Test for the switchbot_cloud climate."""
from unittest.mock import patch
from switchbot_api import Device, Remote, SmartRadiatorThermostatCommands, SwitchBotAPI
from homeassistant.components.climate import (
ATTR_FAN_MODE,
ATTR_HVAC_MODE,
ATTR_TEMPERATURE,
DOMAIN as CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_PRESET_MODE,
SERVICE_SET_TEMPERATURE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
HVACMode,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant, State
from . import configure_integration
from tests.common import mock_restore_cache
async def test_air_conditioner_set_hvac_mode(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test setting HVAC mode for air conditioner."""
mock_list_devices.return_value = [
Remote(
deviceId="ac-device-id-1",
deviceName="climate-1",
remoteType="DIY Air Conditioner",
hubDeviceId="test-hub-id",
),
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: entity_id, ATTR_HVAC_MODE: "cool"},
blocking=True,
)
mock_send_command.assert_called_once()
assert "21,2,1,on" in str(mock_send_command.call_args)
assert hass.states.get(entity_id).state == "cool"
# Test turning off
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: entity_id, ATTR_HVAC_MODE: "off"},
blocking=True,
)
mock_send_command.assert_called_once()
assert "21,2,1,off" in str(mock_send_command.call_args)
assert hass.states.get(entity_id).state == "off"
async def test_air_conditioner_set_fan_mode(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test setting fan mode for air conditioner."""
mock_list_devices.return_value = [
Remote(
deviceId="ac-device-id-1",
deviceName="climate-1",
remoteType="Air Conditioner",
hubDeviceId="test-hub-id",
),
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: entity_id, ATTR_FAN_MODE: "high"},
blocking=True,
)
mock_send_command.assert_called_once()
assert "21,4,4,on" in str(mock_send_command.call_args)
assert hass.states.get(entity_id).attributes[ATTR_FAN_MODE] == "high"
async def test_air_conditioner_set_temperature(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test setting temperature for air conditioner."""
mock_list_devices.return_value = [
Remote(
deviceId="ac-device-id-1",
deviceName="climate-1",
remoteType="Air Conditioner",
hubDeviceId="test-hub-id",
),
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: entity_id, ATTR_TEMPERATURE: 25},
blocking=True,
)
mock_send_command.assert_called_once()
assert "25,4,1,on" in str(mock_send_command.call_args)
assert hass.states.get(entity_id).attributes[ATTR_TEMPERATURE] == 25
async def test_air_conditioner_restore_state(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test restoring state for air conditioner."""
mock_list_devices.return_value = [
Remote(
deviceId="ac-device-id-1",
deviceName="climate-1",
remoteType="Air Conditioner",
hubDeviceId="test-hub-id",
),
]
mock_state = State(
"climate.climate_1",
"cool",
{
ATTR_FAN_MODE: "high",
ATTR_TEMPERATURE: 25,
},
)
mock_restore_cache(hass, (mock_state,))
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
state = hass.states.get(entity_id)
assert state.state == "cool"
assert state.attributes[ATTR_FAN_MODE] == "high"
assert state.attributes[ATTR_TEMPERATURE] == 25
async def test_air_conditioner_no_last_state(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test behavior when no previous state exists."""
mock_list_devices.return_value = [
Remote(
deviceId="ac-device-id-1",
deviceName="climate-1",
remoteType="Air Conditioner",
hubDeviceId="test-hub-id",
),
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
state = hass.states.get(entity_id)
assert state.state == "fan_only"
assert state.attributes[ATTR_FAN_MODE] == "auto"
assert state.attributes[ATTR_TEMPERATURE] == 21
async def test_air_conditioner_turn_off(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test the climate.turn_off service."""
mock_list_devices.return_value = [
Remote(
deviceId="ac-device-id-1",
deviceName="climate-1",
remoteType="DIY Air Conditioner",
hubDeviceId="test-hub-id",
),
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
assert hass.states.get(entity_id).state == "fan_only"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_send_command.assert_called_once()
assert "21,4,1,off" in str(mock_send_command.call_args)
assert hass.states.get(entity_id).state == "off"
async def test_air_conditioner_turn_on(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test turning on a climate entity that has a non-off HVAC_STATE."""
mock_list_devices.return_value = [
Remote(
deviceId="ac-device-id-1",
deviceName="climate-1",
remoteType="DIY Air Conditioner",
hubDeviceId="test-hub-id",
),
]
mock_state = State(
"climate.climate_1",
"cool",
{
ATTR_FAN_MODE: "high",
ATTR_TEMPERATURE: 25,
},
)
mock_restore_cache(hass, (mock_state,))
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
assert hass.states.get(entity_id).state == "cool"
with patch.object(SwitchBotAPI, "send_command") as mock_turn_on_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_turn_on_command.assert_called_once()
assert "25,2,4,on" in str(mock_turn_on_command.call_args)
assert hass.states.get(entity_id).state == "cool"
async def test_air_conditioner_turn_on_from_hvac_mode_off(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test turning on a climate entity that has an off HVAC_STATE."""
mock_list_devices.return_value = [
Remote(
deviceId="ac-device-id-1",
deviceName="climate-1",
remoteType="DIY Air Conditioner",
hubDeviceId="test-hub-id",
),
]
mock_state = State(
"climate.climate_1",
"off",
{
ATTR_FAN_MODE: "high",
ATTR_TEMPERATURE: 25,
},
)
mock_restore_cache(hass, (mock_state,))
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
assert hass.states.get(entity_id).state == "off"
with patch.object(SwitchBotAPI, "send_command") as mock_turn_on_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_turn_on_command.assert_called_once()
assert "25,4,4,on" in str(mock_turn_on_command.call_args)
assert hass.states.get(entity_id).state == "fan_only"
async def test_smart_radiator_thermostat_set_temperature(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test smart radiator thermostat set temperature."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="ac-device-id-1",
deviceName="climate-1",
deviceType="Smart Radiator Thermostat",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{
"mode": 1,
"temperature": 27.5,
},
{
"mode": 1,
"temperature": 27.5,
},
{
"mode": 2,
"temperature": 27.5,
},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: entity_id, "temperature": 27},
)
mock_send_command.assert_called_once_with(
"ac-device-id-1",
SmartRadiatorThermostatCommands.SET_MANUAL_MODE_TEMPERATURE,
"command",
"27.0",
)
async def test_smart_radiator_thermostat_set_preset_mode(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test smart radiator thermostat set preset mode."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="ac-device-id-1",
deviceName="climate-1",
deviceType="Smart Radiator Thermostat",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{
"mode": 1,
"temperature": 27.5,
},
{
"mode": 1,
"temperature": 27.5,
},
{
"mode": 2,
"temperature": 27.5,
},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: entity_id, "preset_mode": "none"},
)
mock_send_command.assert_called_once_with(
"ac-device-id-1",
SmartRadiatorThermostatCommands.SET_MODE,
"command",
2,
)
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_PRESET_MODE,
{ATTR_ENTITY_ID: entity_id, "preset_mode": "home"},
)
mock_send_command.assert_called_once_with(
"ac-device-id-1",
SmartRadiatorThermostatCommands.SET_MODE,
"command",
1,
)
async def test_smart_radiator_thermostat_set_hvac_mode(
hass: HomeAssistant, mock_list_devices, mock_get_status
) -> None:
"""Test smart radiator thermostat set hvac mode."""
mock_list_devices.return_value = [
Device(
version="V1.0",
deviceId="ac-device-id-1",
deviceName="climate-1",
deviceType="Smart Radiator Thermostat",
hubDeviceId="test-hub-id",
),
]
mock_get_status.side_effect = [
{
"mode": 2,
"temperature": 27.5,
},
{
"mode": 2,
"temperature": 27.5,
},
{
"mode": 2,
"temperature": 27.5,
},
]
entry = await configure_integration(hass)
assert entry.state is ConfigEntryState.LOADED
entity_id = "climate.climate_1"
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: entity_id, "hvac_mode": HVACMode.OFF},
)
mock_send_command.assert_called_once_with(
"ac-device-id-1",
SmartRadiatorThermostatCommands.SET_MODE,
"command",
2,
)
with patch.object(SwitchBotAPI, "send_command") as mock_send_command:
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: entity_id, "hvac_mode": HVACMode.HEAT},
)
mock_send_command.assert_called_once_with(
"ac-device-id-1",
SmartRadiatorThermostatCommands.SET_MODE,
"command",
5,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/switchbot_cloud/test_climate.py",
"license": "Apache License 2.0",
"lines": 400,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/switchbot_cloud/test_humidifier.py | """Test for the switchbot_cloud humidifiers."""
from unittest.mock import patch
import pytest
import switchbot_api
from switchbot_api import Device
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.humidifier import DOMAIN as HUMIDIFIER_DOMAIN
from homeassistant.components.switchbot_cloud import SwitchBotAPI
from homeassistant.components.switchbot_cloud.const import DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import HUMIDIFIER2_INFO, HUMIDIFIER_INFO, configure_integration
from tests.common import async_load_json_array_fixture, snapshot_platform
@pytest.mark.parametrize(
("device_info", "index"),
[
(HUMIDIFIER_INFO, 6),
(HUMIDIFIER2_INFO, 7),
],
)
async def test_humidifier(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_list_devices,
mock_get_status,
device_info: Device,
index: int,
) -> None:
"""Test humidifier 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.HUMIDIFIER]
):
entry = await configure_integration(hass)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
@pytest.mark.parametrize(
("service", "service_data", "expected_call_args"),
[
(
"turn_on",
{},
(
"humidifier-id-1",
switchbot_api.CommonCommands.ON,
"command",
"default",
),
),
(
"turn_off",
{},
(
"humidifier-id-1",
switchbot_api.CommonCommands.OFF,
"command",
"default",
),
),
(
"set_humidity",
{"humidity": 15},
(
"humidifier-id-1",
switchbot_api.HumidifierCommands.SET_MODE,
"command",
"101",
),
),
(
"set_humidity",
{"humidity": 60},
(
"humidifier-id-1",
switchbot_api.HumidifierCommands.SET_MODE,
"command",
"102",
),
),
(
"set_humidity",
{"humidity": 80},
(
"humidifier-id-1",
switchbot_api.HumidifierCommands.SET_MODE,
"command",
"103",
),
),
(
"set_mode",
{"mode": "auto"},
(
"humidifier-id-1",
switchbot_api.HumidifierCommands.SET_MODE,
"command",
"auto",
),
),
(
"set_mode",
{"mode": "normal"},
(
"humidifier-id-1",
switchbot_api.HumidifierCommands.SET_MODE,
"command",
"102",
),
),
],
)
async def test_humidifier_controller(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
service: str,
service_data: dict,
expected_call_args: tuple,
) -> None:
"""Test controlling the humidifier with mocked delay."""
mock_list_devices.return_value = [HUMIDIFIER_INFO]
mock_get_status.return_value = {"power": "OFF", "mode": 2}
await configure_integration(hass)
humidifier_id = "humidifier.humidifier_1"
with patch.object(SwitchBotAPI, "send_command") as mocked_send_command:
await hass.services.async_call(
HUMIDIFIER_DOMAIN,
service,
{**service_data, ATTR_ENTITY_ID: humidifier_id},
blocking=True,
)
mocked_send_command.assert_awaited_once_with(*expected_call_args)
@pytest.mark.parametrize(
("service", "service_data", "expected_call_args"),
[
(
"turn_on",
{},
(
"humidifier2-id-1",
switchbot_api.CommonCommands.ON,
"command",
"default",
),
),
(
"turn_off",
{},
(
"humidifier2-id-1",
switchbot_api.CommonCommands.OFF,
"command",
"default",
),
),
(
"set_humidity",
{"humidity": 50},
(
"humidifier2-id-1",
switchbot_api.HumidifierV2Commands.SET_MODE,
"command",
{"mode": 2, "humidity": 50},
),
),
(
"set_mode",
{"mode": "auto"},
(
"humidifier2-id-1",
switchbot_api.HumidifierV2Commands.SET_MODE,
"command",
{"mode": 7},
),
),
],
)
async def test_humidifier2_controller(
hass: HomeAssistant,
mock_list_devices,
mock_get_status,
service: str,
service_data: dict,
expected_call_args: tuple,
) -> None:
"""Test controlling the humidifier2 with mocked delay."""
mock_list_devices.return_value = [HUMIDIFIER2_INFO]
mock_get_status.return_value = {"power": "off", "mode": 2}
await configure_integration(hass)
humidifier_id = "humidifier.humidifier2_1"
with patch.object(SwitchBotAPI, "send_command") as mocked_send_command:
await hass.services.async_call(
HUMIDIFIER_DOMAIN,
service,
{**service_data, ATTR_ENTITY_ID: humidifier_id},
blocking=True,
)
mocked_send_command.assert_awaited_once_with(*expected_call_args)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/switchbot_cloud/test_humidifier.py",
"license": "Apache License 2.0",
"lines": 201,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/tasmota/test_camera.py | """The tests for the Tasmota camera platform."""
from asyncio import Future
import copy
import json
from unittest.mock import patch
import pytest
from homeassistant.components.camera import CameraState
from homeassistant.components.tasmota.const import DEFAULT_PREFIX
from homeassistant.const import ATTR_ASSUMED_STATE, Platform
from homeassistant.core import HomeAssistant
from .test_common import (
DEFAULT_CONFIG,
help_test_availability,
help_test_availability_discovery_update,
help_test_availability_poll_state,
help_test_availability_when_connection_lost,
help_test_deep_sleep_availability,
help_test_deep_sleep_availability_when_connection_lost,
help_test_discovery_device_remove,
help_test_discovery_removal,
help_test_discovery_update_unchanged,
help_test_entity_id_update_discovery_update,
)
from tests.common import async_fire_mqtt_message
from tests.typing import ClientSessionGenerator, MqttMockHAClient, MqttMockPahoClient
SMALLEST_VALID_JPEG = (
"ffd8ffe000104a46494600010101004800480000ffdb00430003020202020203020202030303030406040404040408060"
"6050609080a0a090809090a0c0f0c0a0b0e0b09090d110d0e0f101011100a0c12131210130f101010ffc9000b08000100"
"0101011100ffcc000600101005ffda0008010100003f00d2cf20ffd9"
)
SMALLEST_VALID_JPEG_BYTES = bytes.fromhex(SMALLEST_VALID_JPEG)
async def test_controlling_state_via_mqtt(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient, setup_tasmota
) -> None:
"""Test state update via MQTT."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
await hass.async_block_till_done()
state = hass.states.get("camera.tasmota")
assert state.state == "unavailable"
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async_fire_mqtt_message(hass, "tasmota_49A3BC/tele/LWT", "Online")
await hass.async_block_till_done()
state = hass.states.get("camera.tasmota")
assert state.state == CameraState.IDLE
assert not state.attributes.get(ATTR_ASSUMED_STATE)
async def test_availability_when_connection_lost(
hass: HomeAssistant,
mqtt_client_mock: MqttMockPahoClient,
mqtt_mock: MqttMockHAClient,
setup_tasmota,
) -> None:
"""Test availability after MQTT disconnection."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
await help_test_availability_when_connection_lost(
hass, mqtt_client_mock, mqtt_mock, Platform.CAMERA, config, object_id="tasmota"
)
async def test_deep_sleep_availability_when_connection_lost(
hass: HomeAssistant,
mqtt_client_mock: MqttMockPahoClient,
mqtt_mock: MqttMockHAClient,
setup_tasmota,
) -> None:
"""Test availability after MQTT disconnection."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
await help_test_deep_sleep_availability_when_connection_lost(
hass, mqtt_client_mock, mqtt_mock, Platform.CAMERA, config, object_id="tasmota"
)
async def test_availability(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient, setup_tasmota
) -> None:
"""Test availability."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
await help_test_availability(
hass, mqtt_mock, Platform.CAMERA, config, object_id="tasmota"
)
async def test_deep_sleep_availability(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient, setup_tasmota
) -> None:
"""Test availability."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
await help_test_deep_sleep_availability(
hass, mqtt_mock, Platform.CAMERA, config, object_id="tasmota"
)
async def test_availability_discovery_update(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient, setup_tasmota
) -> None:
"""Test availability discovery update."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
await help_test_availability_discovery_update(
hass, mqtt_mock, Platform.CAMERA, config, object_id="tasmota"
)
async def test_availability_poll_state(
hass: HomeAssistant,
mqtt_client_mock: MqttMockPahoClient,
mqtt_mock: MqttMockHAClient,
setup_tasmota,
) -> None:
"""Test polling after MQTT connection (re)established."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
poll_topic = "tasmota_49A3BC/cmnd/STATE"
await help_test_availability_poll_state(
hass, mqtt_client_mock, mqtt_mock, Platform.CAMERA, config, poll_topic, ""
)
async def test_discovery_removal_camera(
hass: HomeAssistant,
mqtt_mock: MqttMockHAClient,
caplog: pytest.LogCaptureFixture,
setup_tasmota,
) -> None:
"""Test removal of discovered camera."""
config1 = copy.deepcopy(DEFAULT_CONFIG)
config1["cam"] = 1
config2 = copy.deepcopy(DEFAULT_CONFIG)
config2["cam"] = 0
await help_test_discovery_removal(
hass,
mqtt_mock,
caplog,
Platform.CAMERA,
config1,
config2,
object_id="tasmota",
name="Tasmota",
)
async def test_discovery_update_unchanged_camera(
hass: HomeAssistant,
mqtt_mock: MqttMockHAClient,
caplog: pytest.LogCaptureFixture,
setup_tasmota,
) -> None:
"""Test update of discovered camera."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
with patch(
"homeassistant.components.tasmota.camera.TasmotaCamera.discovery_update"
) as discovery_update:
await help_test_discovery_update_unchanged(
hass,
mqtt_mock,
caplog,
Platform.CAMERA,
config,
discovery_update,
object_id="tasmota",
name="Tasmota",
)
async def test_discovery_device_remove(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient, setup_tasmota
) -> None:
"""Test device registry remove."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
unique_id = f"{DEFAULT_CONFIG['mac']}_camera_camera_0"
await help_test_discovery_device_remove(
hass, mqtt_mock, Platform.CAMERA, unique_id, config
)
async def test_entity_id_update_discovery_update(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient, setup_tasmota
) -> None:
"""Test MQTT discovery update when entity_id is updated."""
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
await help_test_entity_id_update_discovery_update(
hass, mqtt_mock, Platform.CAMERA, config, object_id="tasmota"
)
async def test_camera_single_frame(
hass: HomeAssistant,
mqtt_mock: MqttMockHAClient,
setup_tasmota,
hass_client: ClientSessionGenerator,
) -> None:
"""Test single frame capture."""
class MockClientResponse:
def __init__(self, text) -> None:
self._text = text
async def read(self):
return self._text
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
mock_single_image_stream = Future()
mock_single_image_stream.set_result(MockClientResponse(SMALLEST_VALID_JPEG_BYTES))
with patch(
"hatasmota.camera.TasmotaCamera.get_still_image_stream",
return_value=mock_single_image_stream,
):
client = await hass_client()
resp = await client.get("/api/camera_proxy/camera.tasmota")
await hass.async_block_till_done()
assert resp.status == 200
assert resp.content_type == "image/jpeg"
assert resp.content_length == len(SMALLEST_VALID_JPEG_BYTES)
assert await resp.read() == SMALLEST_VALID_JPEG_BYTES
async def test_camera_stream(
hass: HomeAssistant,
mqtt_mock: MqttMockHAClient,
setup_tasmota,
hass_client: ClientSessionGenerator,
) -> None:
"""Test mjpeg stream capture."""
class MockClientResponse:
def __init__(self, text) -> None:
self._text = text
self._frame_available = True
async def read(self, buffer_size):
if self._frame_available:
self._frame_available = False
return self._text
return None
def close(self):
pass
@property
def headers(self):
return {"Content-Type": "multipart/x-mixed-replace"}
@property
def content(self):
return self
config = copy.deepcopy(DEFAULT_CONFIG)
config["cam"] = 1
mac = config["mac"]
async_fire_mqtt_message(
hass,
f"{DEFAULT_PREFIX}/{mac}/config",
json.dumps(config),
)
mock_mjpeg_stream = Future()
mock_mjpeg_stream.set_result(MockClientResponse(SMALLEST_VALID_JPEG_BYTES))
with patch(
"hatasmota.camera.TasmotaCamera.get_mjpeg_stream",
return_value=mock_mjpeg_stream,
):
client = await hass_client()
resp = await client.get("/api/camera_proxy_stream/camera.tasmota")
await hass.async_block_till_done()
assert resp.status == 200
assert resp.content_type == "multipart/x-mixed-replace"
assert await resp.read() == SMALLEST_VALID_JPEG_BYTES
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/tasmota/test_camera.py",
"license": "Apache License 2.0",
"lines": 255,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/togrill/test_select.py | """Test select for ToGrill integration."""
from unittest.mock import Mock
import pytest
from syrupy.assertion import SnapshotAssertion
from togrill_bluetooth.packets import (
GrillType,
PacketA0Notify,
PacketA8Notify,
PacketA303Write,
Taste,
)
from homeassistant.components.select import (
ATTR_OPTION,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import TOGRILL_SERVICE_INFO, setup_entry
from tests.common import MockConfigEntry, snapshot_platform
from tests.components.bluetooth import inject_bluetooth_service_info
@pytest.mark.parametrize(
"packets",
[
pytest.param([], id="no_data"),
pytest.param(
[
PacketA0Notify(
battery=45,
version_major=1,
version_minor=5,
function_type=1,
probe_count=2,
ambient=False,
alarm_interval=5,
alarm_sound=True,
),
PacketA8Notify(
probe=1,
alarm_type=0,
grill_type=1,
),
PacketA8Notify(
probe=2,
alarm_type=0,
taste=1,
),
PacketA8Notify(probe=2, alarm_type=None),
],
id="probes_with_different_data",
),
pytest.param(
[
PacketA8Notify(
probe=1,
alarm_type=0,
grill_type=99,
),
PacketA8Notify(
probe=2,
alarm_type=0,
taste=99,
),
],
id="probes_with_unknown_data",
),
],
)
async def test_setup(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_entry: MockConfigEntry,
mock_client: Mock,
packets,
) -> None:
"""Test the setup."""
inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO)
await setup_entry(hass, mock_entry, [Platform.SELECT])
for packet in packets:
mock_client.mocked_notify(packet)
await snapshot_platform(hass, entity_registry, snapshot, mock_entry.entry_id)
@pytest.mark.parametrize(
("packets", "entity_id", "value", "write_packet"),
[
pytest.param(
[
PacketA8Notify(
probe=1,
alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_TARGET,
temperature_1=50.0,
),
],
"select.probe_1_grill_type",
"veal",
PacketA303Write(probe=1, grill_type=GrillType.VEAL, taste=None),
id="grill_type",
),
pytest.param(
[
PacketA8Notify(
probe=1,
alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_TARGET,
grill_type=GrillType.BEEF,
),
],
"select.probe_1_taste",
"medium",
PacketA303Write(probe=1, grill_type=GrillType.BEEF, taste=Taste.MEDIUM),
id="taste",
),
pytest.param(
[
PacketA8Notify(
probe=1,
alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_TARGET,
grill_type=GrillType.BEEF,
taste=Taste.MEDIUM,
),
],
"select.probe_1_taste",
"none",
PacketA303Write(probe=1, grill_type=GrillType.BEEF, taste=None),
id="taste_none",
),
],
)
async def test_set_option(
hass: HomeAssistant,
mock_entry: MockConfigEntry,
mock_client: Mock,
packets,
entity_id,
value,
write_packet,
) -> None:
"""Test the selection of option."""
inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO)
await setup_entry(hass, mock_entry, [Platform.SELECT])
for packet in packets:
mock_client.mocked_notify(packet)
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
service_data={
ATTR_OPTION: value,
},
target={
ATTR_ENTITY_ID: entity_id,
},
blocking=True,
)
mock_client.write.assert_any_call(write_packet)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/togrill/test_select.py",
"license": "Apache License 2.0",
"lines": 154,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/usage_prediction/test_common_control.py | """Test the common control usage prediction."""
from __future__ import annotations
from unittest.mock import patch
import uuid
from freezegun import freeze_time
import pytest
from homeassistant.components.usage_prediction.common_control import (
async_predict_common_control,
time_category,
)
from homeassistant.components.usage_prediction.models import EntityUsagePredictions
from homeassistant.const import EVENT_CALL_SERVICE
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.components.recorder.common import async_wait_recording_done
def test_time_category() -> None:
"""Test the time category calculation logic."""
for hour in range(6):
assert time_category(hour) == "night", hour
for hour in range(7, 12):
assert time_category(hour) == "morning", hour
for hour in range(13, 18):
assert time_category(hour) == "afternoon", hour
for hour in range(19, 22):
assert time_category(hour) == "evening", hour
@pytest.mark.usefixtures("recorder_mock")
async def test_empty_database(hass: HomeAssistant) -> None:
"""Test function with empty database returns empty results."""
user_id = str(uuid.uuid4())
# Call the function with empty database
results = await async_predict_common_control(hass, user_id)
# Should return empty lists for all time categories
assert results == EntityUsagePredictions(
morning=[],
afternoon=[],
evening=[],
night=[],
)
@pytest.mark.usefixtures("recorder_mock")
async def test_invalid_user_id(hass: HomeAssistant) -> None:
"""Test function with invalid user ID returns empty results."""
# Invalid user ID format (not a valid UUID)
with pytest.raises(ValueError, match=r"Invalid user_id format"):
await async_predict_common_control(hass, "invalid-user-id")
@pytest.mark.usefixtures("recorder_mock")
async def test_with_service_calls(hass: HomeAssistant) -> None:
"""Test function with actual service call events in database."""
user_id = str(uuid.uuid4())
hass.states.async_set("light.living_room", "off")
hass.states.async_set("light.kitchen", "off")
hass.states.async_set("climate.thermostat", "off")
hass.states.async_set("light.bedroom", "off")
hass.states.async_set("lock.front_door", "locked")
# Create service call events at different times of day
# Morning events - use separate service calls to get around context deduplication
with freeze_time("2023-07-01 07:00:00"): # Morning
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "light",
"service": "turn_on",
"service_data": {"entity_id": ["light.living_room", "light.kitchen"]},
},
context=Context(user_id=user_id),
)
await hass.async_block_till_done()
# Afternoon events
with freeze_time("2023-07-01 14:00:00"): # Afternoon
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "climate",
"service": "set_temperature",
"service_data": {"entity_id": "climate.thermostat"},
},
context=Context(user_id=user_id),
)
await hass.async_block_till_done()
# Evening events
with freeze_time("2023-07-01 19:00:00"): # Evening
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "light",
"service": "turn_off",
"service_data": {"entity_id": "light.bedroom"},
},
context=Context(user_id=user_id),
)
await hass.async_block_till_done()
# Night events
with freeze_time("2023-07-01 23:00:00"): # Night
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "lock",
"service": "lock",
"service_data": {"entity_id": "lock.front_door"},
},
context=Context(user_id=user_id),
)
await hass.async_block_till_done()
# Wait for events to be recorded
await async_wait_recording_done(hass)
# Get predictions - make sure we're still in a reasonable timeframe
with freeze_time("2023-07-02 10:00:00"): # Next day, so events are recent
results = await async_predict_common_control(hass, user_id)
# Verify results contain the expected entities in the correct time periods
assert results == EntityUsagePredictions(
morning=["climate.thermostat"],
afternoon=["light.bedroom", "lock.front_door"],
evening=[],
night=["light.living_room", "light.kitchen"],
)
@pytest.mark.usefixtures("recorder_mock")
async def test_multiple_entities_in_one_call(hass: HomeAssistant) -> None:
"""Test handling of service calls with multiple entity IDs."""
user_id = str(uuid.uuid4())
ent_reg = er.async_get(hass)
ent_reg.async_get_or_create(
"light",
"test",
"living_room",
suggested_object_id="living_room",
hidden_by=er.RegistryEntryHider.USER,
)
ent_reg.async_get_or_create(
"light",
"test",
"kitchen",
suggested_object_id="kitchen",
)
hass.states.async_set("light.living_room", "off")
hass.states.async_set("light.kitchen", "off")
hass.states.async_set("light.hallway", "off")
hass.states.async_set("not_allowed.domain", "off")
with freeze_time("2023-07-01 10:00:00"): # Morning
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "light",
"service": "turn_on",
"service_data": {
"entity_id": [
"light.living_room",
"light.kitchen",
"light.hallway",
"not_allowed.domain",
"light.not_in_state_machine",
]
},
},
context=Context(user_id=user_id),
)
await hass.async_block_till_done()
await async_wait_recording_done(hass)
with freeze_time("2023-07-02 10:00:00"): # Next day, so events are recent
results = await async_predict_common_control(hass, user_id)
# Two lights should be counted (10:00 UTC = 02:00 local = night)
# Living room is hidden via entity registry
assert results.night == ["light.kitchen", "light.hallway"]
assert results.morning == []
assert results.afternoon == []
assert results.evening == []
@pytest.mark.usefixtures("recorder_mock")
async def test_context_deduplication(hass: HomeAssistant) -> None:
"""Test that multiple events with the same context are deduplicated."""
user_id = str(uuid.uuid4())
context = Context(user_id=user_id)
hass.states.async_set("light.living_room", "off")
hass.states.async_set("switch.coffee_maker", "off")
with freeze_time("2023-07-01 10:00:00"): # Morning
# Fire multiple events with the same context
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "light",
"service": "turn_on",
"service_data": {"entity_id": "light.living_room"},
},
context=context,
)
await hass.async_block_till_done()
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "switch",
"service": "turn_on",
"service_data": {"entity_id": "switch.coffee_maker"},
},
context=context, # Same context
)
await hass.async_block_till_done()
await async_wait_recording_done(hass)
with freeze_time("2023-07-02 10:00:00"): # Next day, so events are recent
results = await async_predict_common_control(hass, user_id)
# Only the first event should be processed (10:00 UTC = 02:00 local = night)
assert results == EntityUsagePredictions(
morning=[],
afternoon=[],
evening=[],
night=["light.living_room"],
)
@pytest.mark.usefixtures("recorder_mock")
async def test_old_events_excluded(hass: HomeAssistant) -> None:
"""Test that events older than 30 days are excluded."""
user_id = str(uuid.uuid4())
hass.states.async_set("light.old_event", "off")
hass.states.async_set("light.recent_event", "off")
# Create an old event (35 days ago)
with freeze_time("2023-05-27 10:00:00"): # 35 days before July 1st
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "light",
"service": "turn_on",
"service_data": {"entity_id": "light.old_event"},
},
context=Context(user_id=user_id),
)
await hass.async_block_till_done()
# Create a recent event (5 days ago)
with freeze_time("2023-06-26 10:00:00"): # 5 days before July 1st
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "light",
"service": "turn_on",
"service_data": {"entity_id": "light.recent_event"},
},
context=Context(user_id=user_id),
)
await hass.async_block_till_done()
await async_wait_recording_done(hass)
# Query with current time
with freeze_time("2023-07-01 10:00:00"):
results = await async_predict_common_control(hass, user_id)
# Only recent event should be included (10:00 UTC = 02:00 local = night)
assert results == EntityUsagePredictions(
morning=[],
afternoon=[],
evening=[],
night=["light.recent_event"],
)
@pytest.mark.usefixtures("recorder_mock")
async def test_entities_limit(hass: HomeAssistant) -> None:
"""Test that only top entities are returned per time category."""
user_id = str(uuid.uuid4())
hass.states.async_set("light.most_used", "off")
hass.states.async_set("light.second", "off")
hass.states.async_set("light.third", "off")
hass.states.async_set("light.fourth", "off")
hass.states.async_set("light.fifth", "off")
hass.states.async_set("light.sixth", "off")
hass.states.async_set("light.seventh", "off")
# Create more than 5 different entities in morning
with freeze_time("2023-07-01 08:00:00"):
# Create entities with different frequencies
entities_with_counts = [
("light.most_used", 10),
("light.second", 8),
("light.third", 6),
("light.fourth", 4),
("light.fifth", 2),
("light.sixth", 1),
("light.seventh", 1),
]
for entity_id, count in entities_with_counts:
for _ in range(count):
# Use different context for each call
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "light",
"service": "toggle",
"service_data": {"entity_id": entity_id},
},
context=Context(user_id=user_id),
)
await hass.async_block_till_done()
await async_wait_recording_done(hass)
with (
freeze_time("2023-07-02 10:00:00"),
patch(
"homeassistant.components.usage_prediction.common_control.RESULTS_TO_INCLUDE",
5,
),
): # Next day, so events are recent
results = await async_predict_common_control(hass, user_id)
# Should be the top 5 most used (08:00 UTC = 00:00 local = night)
assert results.night == [
"light.most_used",
"light.second",
"light.third",
"light.fourth",
"light.fifth",
]
assert results.morning == []
assert results.afternoon == []
assert results.evening == []
@pytest.mark.usefixtures("recorder_mock")
async def test_different_users_separated(hass: HomeAssistant) -> None:
"""Test that events from different users are properly separated."""
user_id_1 = str(uuid.uuid4())
user_id_2 = str(uuid.uuid4())
hass.states.async_set("light.user1_light", "off")
hass.states.async_set("light.user2_light", "off")
with freeze_time("2023-07-01 10:00:00"):
# User 1 events
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "light",
"service": "turn_on",
"service_data": {"entity_id": "light.user1_light"},
},
context=Context(user_id=user_id_1),
)
await hass.async_block_till_done()
# User 2 events
hass.bus.async_fire(
EVENT_CALL_SERVICE,
{
"domain": "light",
"service": "turn_on",
"service_data": {"entity_id": "light.user2_light"},
},
context=Context(user_id=user_id_2),
)
await hass.async_block_till_done()
await async_wait_recording_done(hass)
# Get results for each user
with freeze_time("2023-07-02 10:00:00"): # Next day, so events are recent
results_user1 = await async_predict_common_control(hass, user_id_1)
results_user2 = await async_predict_common_control(hass, user_id_2)
# Each user should only see their own entities (10:00 UTC = 02:00 local = night)
assert results_user1 == EntityUsagePredictions(
morning=[],
afternoon=[],
evening=[],
night=["light.user1_light"],
)
assert results_user2 == EntityUsagePredictions(
morning=[],
afternoon=[],
evening=[],
night=["light.user2_light"],
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/usage_prediction/test_common_control.py",
"license": "Apache License 2.0",
"lines": 348,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/usage_prediction/test_init.py | """Test usage_prediction integration."""
import asyncio
from unittest.mock import patch
import pytest
from homeassistant.components.usage_prediction import get_cached_common_control
from homeassistant.components.usage_prediction.models import EntityUsagePredictions
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
@pytest.mark.usefixtures("recorder_mock")
async def test_usage_prediction_caching(hass: HomeAssistant) -> None:
"""Test that usage prediction results are cached for 24 hours."""
assert await async_setup_component(hass, "usage_prediction", {})
finish_event = asyncio.Event()
async def mock_common_control_error(*args) -> EntityUsagePredictions:
await finish_event.wait()
raise Exception("Boom") # noqa: TRY002
with patch(
"homeassistant.components.usage_prediction.common_control.async_predict_common_control",
mock_common_control_error,
):
# First call, should trigger prediction
task1 = asyncio.create_task(get_cached_common_control(hass, "user_1"))
task2 = asyncio.create_task(get_cached_common_control(hass, "user_1"))
await asyncio.sleep(0)
finish_event.set()
with pytest.raises(Exception, match="Boom"):
await task2
with pytest.raises(Exception, match="Boom"):
await task1
finish_event.clear()
results = EntityUsagePredictions(
morning=["light.kitchen"],
afternoon=["climate.thermostat"],
evening=["light.bedroom"],
night=["lock.front_door"],
)
# The exception is not cached, we hit the method again.
async def mock_common_control(*args) -> EntityUsagePredictions:
await finish_event.wait()
return results
with patch(
"homeassistant.components.usage_prediction.common_control.async_predict_common_control",
mock_common_control,
):
# First call, should trigger prediction
task1 = asyncio.create_task(get_cached_common_control(hass, "user_1"))
task2 = asyncio.create_task(get_cached_common_control(hass, "user_1"))
await asyncio.sleep(0)
finish_event.set()
assert await task2 is results
assert await task1 is results
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/usage_prediction/test_init.py",
"license": "Apache License 2.0",
"lines": 51,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/usage_prediction/test_websocket.py | """Test usage_prediction WebSocket API."""
from collections.abc import Generator
from copy import deepcopy
from datetime import datetime, timedelta
from unittest.mock import Mock, patch
from freezegun import freeze_time
import pytest
from homeassistant.components.usage_prediction.models import EntityUsagePredictions
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.common import MockUser
from tests.typing import WebSocketGenerator
NOW = datetime(2026, 8, 26, 15, 0, 0, tzinfo=dt_util.UTC)
@pytest.fixture
def mock_predict_common_control() -> Generator[Mock]:
"""Return a mock result for common control."""
with patch(
"homeassistant.components.usage_prediction.common_control.async_predict_common_control",
return_value=EntityUsagePredictions(
morning=["light.kitchen"],
afternoon=["climate.thermostat"],
evening=["light.bedroom"],
night=["lock.front_door"],
),
) as mock_predict:
yield mock_predict
@pytest.mark.usefixtures("recorder_mock")
async def test_common_control(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_admin_user: MockUser,
mock_predict_common_control: Mock,
) -> None:
"""Test usage_prediction common control WebSocket command."""
assert await async_setup_component(hass, "usage_prediction", {})
client = await hass_ws_client(hass)
with freeze_time(NOW):
await client.send_json({"id": 1, "type": "usage_prediction/common_control"})
msg = await client.receive_json()
assert msg["id"] == 1
assert msg["type"] == "result"
assert msg["success"] is True
assert msg["result"] == {
"entities": [
"light.kitchen",
]
}
assert mock_predict_common_control.call_count == 1
assert mock_predict_common_control.mock_calls[0][1][1] == hass_admin_user.id
@pytest.mark.usefixtures("recorder_mock")
async def test_caching_behavior(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_predict_common_control: Mock,
) -> None:
"""Test that results are cached for 24 hours."""
assert await async_setup_component(hass, "usage_prediction", {})
client = await hass_ws_client(hass)
# First call should fetch from database
with freeze_time(NOW):
await client.send_json({"id": 1, "type": "usage_prediction/common_control"})
msg = await client.receive_json()
assert msg["success"] is True
assert msg["result"] == {
"entities": [
"light.kitchen",
]
}
assert mock_predict_common_control.call_count == 1
new_result = deepcopy(mock_predict_common_control.return_value)
new_result.morning.append("light.bla")
mock_predict_common_control.return_value = new_result
# Second call within 24 hours should use cache
with freeze_time(NOW + timedelta(hours=23)):
await client.send_json({"id": 2, "type": "usage_prediction/common_control"})
msg = await client.receive_json()
assert msg["success"] is True
assert msg["result"] == {
"entities": [
"light.kitchen",
]
}
# Should still be 1 (no new database call)
assert mock_predict_common_control.call_count == 1
# Third call after 24 hours should fetch from database again
with freeze_time(NOW + timedelta(hours=25)):
await client.send_json({"id": 3, "type": "usage_prediction/common_control"})
msg = await client.receive_json()
assert msg["success"] is True
assert msg["result"] == {"entities": ["light.kitchen", "light.bla"]}
# Should now be 2 (new database call)
assert mock_predict_common_control.call_count == 2
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/usage_prediction/test_websocket.py",
"license": "Apache License 2.0",
"lines": 93,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/vesync/test_binary_sensor.py | """Tests for the binary sensor module."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from .common import ALL_DEVICE_NAMES, mock_devices_response
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.mark.parametrize("device_name", ALL_DEVICE_NAMES)
async def test_sensor_state(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
aioclient_mock: AiohttpClientMocker,
device_name: str,
) -> None:
"""Test the resulting setup state is as expected for the platform."""
# Configure the API devices call for device_name
mock_devices_response(aioclient_mock, device_name)
# setup platform - only including the named device
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
# Check device registry
devices = dr.async_entries_for_config_entry(device_registry, config_entry.entry_id)
assert devices == snapshot(name="devices")
# Check entity registry
entities = [
entity
for entity in er.async_entries_for_config_entry(
entity_registry, config_entry.entry_id
)
if entity.domain == BINARY_SENSOR_DOMAIN
]
assert entities == snapshot(name="entities")
# Check states
for entity in entities:
assert hass.states.get(entity.entity_id) == snapshot(name=entity.entity_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/vesync/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 40,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/victron_remote_monitoring/test_config_flow.py | """Test the Victron VRM Solar Forecast config flow."""
from unittest.mock import AsyncMock, Mock
import pytest
from victron_vrm.exceptions import AuthenticationError, VictronVRMError
from homeassistant.components.victron_remote_monitoring.config_flow import SiteNotFound
from homeassistant.components.victron_remote_monitoring.const import (
CONF_API_TOKEN,
CONF_SITE_ID,
DOMAIN,
)
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
def _make_site(site_id: int, name: str = "ESS System") -> Mock:
"""Return a mock site object exposing id and name attributes.
Using a mock (instead of SimpleNamespace) helps ensure tests rely only on
the attributes we explicitly define and will surface unexpected attribute
access via mock assertions if the implementation changes.
"""
site = Mock()
site.id = site_id
site.name = name
return site
async def test_full_flow_success(
hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_vrm_client: AsyncMock
) -> None:
"""Test the 2-step flow: token -> select site -> create entry."""
site1 = _make_site(123456, "ESS")
site2 = _make_site(987654, "Cabin")
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"] == {}
mock_vrm_client.users.list_sites = AsyncMock(return_value=[site2, site1])
mock_vrm_client.users.get_site = AsyncMock(return_value=site1)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_TOKEN: "test_token"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "select_site"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_SITE_ID: str(site1.id)}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"VRM for {site1.name}"
assert result["data"] == {
CONF_API_TOKEN: "test_token",
CONF_SITE_ID: site1.id,
}
assert mock_setup_entry.call_count == 1
async def test_user_step_no_sites(
hass: HomeAssistant, mock_vrm_client: AsyncMock
) -> None:
"""No sites available keeps user step with no_sites error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
# Reuse existing async mock instead of replacing it
mock_vrm_client.users.list_sites.return_value = []
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_TOKEN: "token"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "no_sites"}
# Provide a site afterwards and resubmit to complete the flow
site = _make_site(999999, "Only Site")
mock_vrm_client.users.list_sites.return_value = [site]
mock_vrm_client.users.list_sites.side_effect = (
None # ensure no leftover side effect
)
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_TOKEN: "token"}
)
assert result2["type"] is FlowResultType.CREATE_ENTRY
assert result2["data"] == {CONF_API_TOKEN: "token", CONF_SITE_ID: site.id}
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(AuthenticationError("bad", status_code=401), "invalid_auth"),
(VictronVRMError("auth", status_code=401, response_data={}), "invalid_auth"),
(
VictronVRMError("server", status_code=500, response_data={}),
"cannot_connect",
),
(ValueError("boom"), "unknown"),
],
)
async def test_user_step_errors_then_success(
hass: HomeAssistant,
mock_vrm_client: AsyncMock,
side_effect: Exception,
expected_error: str,
) -> None:
"""Test token validation errors (user step) and eventual success."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
flow_id = result["flow_id"]
# First call raises/returns error via side_effect, we then clear and set return value
mock_vrm_client.users.list_sites.side_effect = side_effect
result_err = await hass.config_entries.flow.async_configure(
flow_id, {CONF_API_TOKEN: "token"}
)
assert result_err["type"] is FlowResultType.FORM
assert result_err["step_id"] == "user"
assert result_err["errors"] == {"base": expected_error}
# Now make it succeed with a single site, which should auto-complete
site = _make_site(24680, "AutoSite")
mock_vrm_client.users.list_sites.side_effect = None
mock_vrm_client.users.list_sites.return_value = [site]
result_ok = await hass.config_entries.flow.async_configure(
flow_id, {CONF_API_TOKEN: "token"}
)
assert result_ok["type"] is FlowResultType.CREATE_ENTRY
assert result_ok["data"] == {
CONF_API_TOKEN: "token",
CONF_SITE_ID: site.id,
}
@pytest.mark.parametrize(
("side_effect", "return_value", "expected_error"),
[
(AuthenticationError("ExpiredToken", status_code=403), None, "invalid_auth"),
(
VictronVRMError("forbidden", status_code=403, response_data={}),
None,
"invalid_auth",
),
(
VictronVRMError("Internal server error", status_code=500, response_data={}),
None,
"cannot_connect",
),
(None, None, "site_not_found"), # get_site returns None
(ValueError("missing"), None, "unknown"),
],
)
async def test_select_site_errors(
hass: HomeAssistant,
mock_vrm_client: AsyncMock,
side_effect: Exception | None,
return_value: Mock | None,
expected_error: str,
) -> None:
"""Parametrized select_site error scenarios."""
sites = [_make_site(1, "A"), _make_site(2, "B")]
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
flow_id = result["flow_id"]
mock_vrm_client.users.list_sites = AsyncMock(return_value=sites)
if side_effect is not None:
mock_vrm_client.users.get_site = AsyncMock(side_effect=side_effect)
else:
mock_vrm_client.users.get_site = AsyncMock(return_value=return_value)
res_intermediate = await hass.config_entries.flow.async_configure(
flow_id, {CONF_API_TOKEN: "token"}
)
assert res_intermediate["step_id"] == "select_site"
result = await hass.config_entries.flow.async_configure(
flow_id, {CONF_SITE_ID: str(sites[0].id)}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "select_site"
assert result["errors"] == {"base": expected_error}
# Fix the error path by making get_site succeed and submit again
good_site = _make_site(sites[0].id, sites[0].name)
mock_vrm_client.users.get_site = AsyncMock(return_value=good_site)
result_success = await hass.config_entries.flow.async_configure(
flow_id, {CONF_SITE_ID: str(sites[0].id)}
)
assert result_success["type"] is FlowResultType.CREATE_ENTRY
assert result_success["data"] == {
CONF_API_TOKEN: "token",
CONF_SITE_ID: good_site.id,
}
async def test_select_site_duplicate_aborts(
hass: HomeAssistant, mock_vrm_client: AsyncMock
) -> None:
"""Selecting an already configured site aborts during the select step (multi-site)."""
site_id = 555
# Existing entry with same site id
existing = MockConfigEntry(
domain=DOMAIN,
data={CONF_API_TOKEN: "token", CONF_SITE_ID: site_id},
unique_id=str(site_id),
title="Existing",
)
existing.add_to_hass(hass)
# Start flow and reach select_site
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_vrm_client.users.list_sites = AsyncMock(
return_value=[_make_site(site_id, "Dup"), _make_site(777, "Other")]
)
mock_vrm_client.users.get_site = AsyncMock()
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_TOKEN: "token2"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "select_site"
# Selecting the same site should abort before validation (get_site not called)
res_abort = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_SITE_ID: str(site_id)}
)
assert res_abort["type"] is FlowResultType.ABORT
assert res_abort["reason"] == "already_configured"
assert mock_vrm_client.users.get_site.call_count == 0
# Start a new flow selecting the other site to finish with a create entry
result_new = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
other_site = _make_site(777, "Other")
mock_vrm_client.users.list_sites = AsyncMock(return_value=[other_site])
result_new2 = await hass.config_entries.flow.async_configure(
result_new["flow_id"], {CONF_API_TOKEN: "token3"}
)
assert result_new2["type"] is FlowResultType.CREATE_ENTRY
assert result_new2["data"] == {
CONF_API_TOKEN: "token3",
CONF_SITE_ID: other_site.id,
}
async def test_reauth_flow_success(
hass: HomeAssistant, mock_vrm_client: AsyncMock
) -> None:
"""Test successful reauthentication with new token."""
# Existing configured entry
site_id = 123456
existing = MockConfigEntry(
domain=DOMAIN,
data={CONF_API_TOKEN: "old_token", CONF_SITE_ID: site_id},
unique_id=str(site_id),
title="Existing",
)
existing.add_to_hass(hass)
# Start reauth
result = await existing.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
# Provide new token; validate by returning the site
site = _make_site(site_id, "ESS")
mock_vrm_client.users.get_site = AsyncMock(return_value=site)
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_TOKEN: "new_token"}
)
assert result2["type"] is FlowResultType.ABORT
assert result2["reason"] == "reauth_successful"
# Data updated
assert existing.data[CONF_API_TOKEN] == "new_token"
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(AuthenticationError("bad", status_code=401), "invalid_auth"),
(VictronVRMError("down", status_code=500, response_data={}), "cannot_connect"),
(SiteNotFound(), "site_not_found"),
],
)
async def test_reauth_flow_errors(
hass: HomeAssistant,
mock_vrm_client: AsyncMock,
side_effect: Exception,
expected_error: str,
) -> None:
"""Reauth shows errors when validation fails."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_API_TOKEN: "old", CONF_SITE_ID: 555},
unique_id="555",
title="Existing",
)
entry.add_to_hass(hass)
result = await entry.start_reauth_flow(hass)
assert result["step_id"] == "reauth_confirm"
mock_vrm_client.users.get_site = AsyncMock(side_effect=side_effect)
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_TOKEN: "bad"}
)
assert result2["type"] is FlowResultType.FORM
assert result2["errors"] == {"base": expected_error}
# Provide a valid token afterwards to finish the reauth flow successfully
good_site = _make_site(555, "Existing")
mock_vrm_client.users.get_site = AsyncMock(return_value=good_site)
result3 = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_API_TOKEN: "new_valid"}
)
assert result3["type"] is FlowResultType.ABORT
assert result3["reason"] == "reauth_successful"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/victron_remote_monitoring/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 291,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/victron_remote_monitoring/test_init.py | """Tests for Victron Remote Monitoring integration setup and auth handling."""
from __future__ import annotations
import pytest
from victron_vrm.exceptions import AuthenticationError, VictronVRMError
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
("side_effect", "expected_state", "expects_reauth"),
[
(
AuthenticationError("bad", status_code=401),
ConfigEntryState.SETUP_ERROR,
True,
),
(
VictronVRMError("boom", status_code=500, response_data={}),
ConfigEntryState.SETUP_RETRY,
False,
),
],
)
async def test_setup_auth_or_connection_error_starts_retry_or_reauth(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_vrm_client,
side_effect: Exception | None,
expected_state: ConfigEntryState,
expects_reauth: bool,
) -> None:
"""Auth errors initiate reauth flow; other errors set entry to retry.
AuthenticationError should surface as ConfigEntryAuthFailed which marks the entry in SETUP_ERROR and starts a reauth flow.
Generic VictronVRMError should set the entry to SETUP_RETRY without a reauth flow.
"""
mock_config_entry.add_to_hass(hass)
# Override default success behaviour of fixture to raise side effect
mock_vrm_client.installations.stats.side_effect = side_effect
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is expected_state
flows_list = list(mock_config_entry.async_get_active_flows(hass, {SOURCE_REAUTH}))
assert bool(flows_list) is expects_reauth
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/victron_remote_monitoring/test_init.py",
"license": "Apache License 2.0",
"lines": 42,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/victron_remote_monitoring/test_sensor.py | """Tests for the VRM Forecasts sensors.
Consolidates most per-sensor assertions into snapshot-based regression tests.
"""
from __future__ import annotations
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_sensors_snapshot(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
init_integration,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot all VRM sensor states & key attributes."""
await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/victron_remote_monitoring/test_sensor.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/volvooncall/test_init.py | """Test the Volvo On Call integration setup."""
from homeassistant.components.volvooncall.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import issue_registry as ir
from tests.common import MockConfigEntry
async def test_setup_entry_creates_repair_issue(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test that setup creates a repair issue."""
entry = MockConfigEntry(
domain=DOMAIN,
title="Volvo On Call",
data={},
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.LOADED
issue = issue_registry.async_get_issue(DOMAIN, "volvooncall_deprecated")
assert issue is not None
assert issue.severity is ir.IssueSeverity.WARNING
assert issue.translation_key == "volvooncall_deprecated"
async def test_unload_entry_removes_repair_issue(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test that unloading the last config entry removes the repair issue."""
first_config_entry = MockConfigEntry(
domain=DOMAIN,
title="Volvo On Call",
data={},
)
first_config_entry.add_to_hass(hass)
second_config_entry = MockConfigEntry(
domain=DOMAIN,
title="Volvo On Call second",
data={},
)
second_config_entry.add_to_hass(hass)
# Setup entry
assert await hass.config_entries.async_setup(first_config_entry.entry_id)
await hass.async_block_till_done()
assert len(hass.config_entries.async_entries(DOMAIN)) == 2
# Check that the repair issue was created
issue = issue_registry.async_get_issue(DOMAIN, "volvooncall_deprecated")
assert issue is not None
# Unload entry (this is the only entry, so issue should be removed)
assert await hass.config_entries.async_remove(first_config_entry.entry_id)
await hass.async_block_till_done(wait_background_tasks=True)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
# Check that the repair issue still exists because there's another entry
issue = issue_registry.async_get_issue(DOMAIN, "volvooncall_deprecated")
assert issue is not None
# Unload entry (this is the only entry, so issue should be removed)
assert await hass.config_entries.async_remove(second_config_entry.entry_id)
await hass.async_block_till_done(wait_background_tasks=True)
# Check that the repair issue was removed
issue = issue_registry.async_get_issue(DOMAIN, "volvooncall_deprecated")
assert issue is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/volvooncall/test_init.py",
"license": "Apache License 2.0",
"lines": 59,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/wled/test_analytics.py | """Tests for analytics platform."""
from homeassistant.components.analytics import async_devices_payload
from homeassistant.components.wled import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
async def test_analytics(
hass: HomeAssistant, device_registry: dr.DeviceRegistry
) -> None:
"""Test the analytics platform."""
await async_setup_component(hass, "analytics", {})
config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass)
device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
identifiers={(DOMAIN, "test")},
manufacturer="Test Manufacturer",
)
result = await async_devices_payload(hass)
assert DOMAIN not in result["integrations"]
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/wled/test_analytics.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/workday/test_calendar.py | """Tests for calendar platform of Workday integration."""
from datetime import datetime, timedelta
from freezegun.api import FrozenDateTimeFactory
import pytest
from homeassistant.components.calendar import (
DOMAIN as CALENDAR_DOMAIN,
EVENT_END_DATETIME,
EVENT_START_DATETIME,
EVENT_SUMMARY,
SERVICE_GET_EVENTS,
)
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.util import dt as dt_util
from . import TEST_CONFIG_WITH_PROVINCE, init_integration
from tests.common import async_fire_time_changed
ATTR_END = "end"
ATTR_START = "start"
@pytest.mark.parametrize(
"time_zone", ["Asia/Tokyo", "Europe/Berlin", "America/Chicago", "US/Hawaii"]
)
async def test_holiday_calendar_entity(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
time_zone: str,
) -> None:
"""Test HolidayCalendarEntity functionality."""
await hass.config.async_set_time_zone(time_zone)
zone = await dt_util.async_get_time_zone(time_zone)
freezer.move_to(datetime(2023, 1, 1, 0, 1, 1, tzinfo=zone)) # New Years Day
await init_integration(hass, TEST_CONFIG_WITH_PROVINCE)
response = await hass.services.async_call(
CALENDAR_DOMAIN,
SERVICE_GET_EVENTS,
{
ATTR_ENTITY_ID: "calendar.workday_sensor_calendar",
EVENT_START_DATETIME: dt_util.now(),
EVENT_END_DATETIME: dt_util.now() + timedelta(days=10, hours=1),
},
blocking=True,
return_response=True,
)
assert {
ATTR_END: "2023-01-02",
ATTR_START: "2023-01-01",
EVENT_SUMMARY: "Workday Sensor",
} not in response["calendar.workday_sensor_calendar"]["events"]
assert {
ATTR_END: "2023-01-04",
ATTR_START: "2023-01-03",
EVENT_SUMMARY: "Workday Sensor",
} in response["calendar.workday_sensor_calendar"]["events"]
state = hass.states.get("calendar.workday_sensor_calendar")
assert state is not None
assert state.state == "off"
freezer.move_to(
datetime(2023, 1, 2, 0, 1, 1, tzinfo=zone)
) # Day after New Years Day
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Binary sensor added to ensure same state for both entities
state = hass.states.get("binary_sensor.workday_sensor")
assert state is not None
assert state.state == "on"
state = hass.states.get("calendar.workday_sensor_calendar")
assert state is not None
assert state.state == "on"
freezer.move_to(datetime(2023, 1, 7, 0, 1, 1, tzinfo=zone)) # Workday
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get("binary_sensor.workday_sensor")
assert state is not None
assert state.state == "off"
state = hass.states.get("calendar.workday_sensor_calendar")
assert state is not None
assert state.state == "off"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/workday/test_calendar.py",
"license": "Apache License 2.0",
"lines": 76,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/hassfest/test_conditions.py | """Tests for hassfest conditions."""
import io
import json
from pathlib import Path
from unittest.mock import patch
import pytest
from homeassistant.util.yaml.loader import parse_yaml
from script.hassfest import conditions
from script.hassfest.model import Config
from . import get_integration
CONDITION_DESCRIPTION_FILENAME = "conditions.yaml"
CONDITION_ICONS_FILENAME = "icons.json"
CONDITION_STRINGS_FILENAME = "strings.json"
CONDITION_DESCRIPTIONS = {
"valid": {
CONDITION_DESCRIPTION_FILENAME: """
_:
target:
entity:
domain: light
fields:
after:
example: sunrise
selector:
select:
options:
- sunrise
- sunset
after_offset:
selector:
time: null
""",
CONDITION_ICONS_FILENAME: {"conditions": {"_": {"condition": "mdi:flash"}}},
CONDITION_STRINGS_FILENAME: {
"conditions": {
"_": {
"name": "Sun",
"description": "When the sun is above/below the horizon",
"fields": {
"after": {"name": "After event", "description": "The event."},
"after_offset": {
"name": "Offset",
"description": "The offset.",
},
},
}
}
},
"errors": [],
},
"yaml_missing_colon": {
CONDITION_DESCRIPTION_FILENAME: """
test:
fields
entity:
selector:
entity:
""",
"errors": ["Invalid conditions.yaml"],
},
"invalid_conditions_schema": {
CONDITION_DESCRIPTION_FILENAME: """
invalid_condition:
fields:
entity:
selector:
invalid_selector: null
""",
"errors": ["Unknown selector type invalid_selector"],
},
"missing_strings_and_icons": {
CONDITION_DESCRIPTION_FILENAME: """
sun:
fields:
after:
example: sunrise
selector:
select:
options:
- sunrise
- sunset
translation_key: after
after_offset:
selector:
time: null
""",
CONDITION_ICONS_FILENAME: {"conditions": {}},
CONDITION_STRINGS_FILENAME: {
"conditions": {
"sun": {
"fields": {
"after_offset": {},
},
}
}
},
"errors": [
"has no icon",
"has no name",
"has no description",
"field after with no name",
"field after with no description",
"field after with a selector with a translation key",
"field after_offset with no name",
"field after_offset with no description",
],
},
}
@pytest.mark.usefixtures("mock_core_integration")
def test_validate(config: Config) -> None:
"""Test validate version with no key."""
def _load_yaml(fname, secrets=None):
domain, yaml_file = fname.split("/")
assert yaml_file == CONDITION_DESCRIPTION_FILENAME
condition_descriptions = CONDITION_DESCRIPTIONS[domain][yaml_file]
with io.StringIO(condition_descriptions) as file:
return parse_yaml(file)
def _patched_path_read_text(path: Path):
domain = path.parent.name
filename = path.name
return json.dumps(CONDITION_DESCRIPTIONS[domain][filename])
integrations = {
domain: get_integration(domain, config) for domain in CONDITION_DESCRIPTIONS
}
with (
patch("script.hassfest.conditions.grep_dir", return_value=True),
patch("pathlib.Path.is_file", return_value=True),
patch("pathlib.Path.read_text", _patched_path_read_text),
patch("annotatedyaml.loader.load_yaml", side_effect=_load_yaml),
):
conditions.validate(integrations, config)
assert not config.errors
for domain, description in CONDITION_DESCRIPTIONS.items():
assert len(integrations[domain].errors) == len(description["errors"]), (
f"Domain '{domain}' has unexpected errors: {integrations[domain].errors}"
)
for error, expected_error in zip(
integrations[domain].errors, description["errors"], strict=True
):
assert expected_error in error.error
| {
"repo_id": "home-assistant/core",
"file_path": "tests/hassfest/test_conditions.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/hassfest/test_triggers.py | """Tests for hassfest triggers."""
import io
import json
from pathlib import Path
from unittest.mock import patch
import pytest
from homeassistant.util.yaml.loader import parse_yaml
from script.hassfest import triggers
from script.hassfest.model import Config
from . import get_integration
TRIGGER_DESCRIPTION_FILENAME = "triggers.yaml"
TRIGGER_ICONS_FILENAME = "icons.json"
TRIGGER_STRINGS_FILENAME = "strings.json"
TRIGGER_DESCRIPTIONS = {
"valid": {
TRIGGER_DESCRIPTION_FILENAME: """
_:
fields:
event:
example: sunrise
selector:
select:
options:
- sunrise
- sunset
offset:
selector:
time: null
""",
TRIGGER_ICONS_FILENAME: {"triggers": {"_": {"trigger": "mdi:flash"}}},
TRIGGER_STRINGS_FILENAME: {
"triggers": {
"_": {
"name": "MQTT",
"description": "When a specific message is received on a given MQTT topic.",
"fields": {
"event": {"name": "Event", "description": "The event."},
"offset": {"name": "Offset", "description": "The offset."},
},
}
}
},
"errors": [],
},
"yaml_missing_colon": {
TRIGGER_DESCRIPTION_FILENAME: """
test:
fields
entity:
selector:
entity:
""",
"errors": ["Invalid triggers.yaml"],
},
"invalid_triggers_schema": {
TRIGGER_DESCRIPTION_FILENAME: """
invalid_trigger:
fields:
entity:
selector:
invalid_selector: null
""",
"errors": ["Unknown selector type invalid_selector"],
},
"missing_strings_and_icons": {
TRIGGER_DESCRIPTION_FILENAME: """
sun:
fields:
event:
example: sunrise
selector:
select:
options:
- sunrise
- sunset
translation_key: event
offset:
selector:
time: null
""",
TRIGGER_ICONS_FILENAME: {"triggers": {}},
TRIGGER_STRINGS_FILENAME: {
"triggers": {
"sun": {
"fields": {
"offset": {},
},
}
}
},
"errors": [
"has no icon",
"has no name",
"has no description",
"field event with no name",
"field event with no description",
"field event with a selector with a translation key",
"field offset with no name",
"field offset with no description",
],
},
}
@pytest.mark.usefixtures("mock_core_integration")
def test_validate(config: Config) -> None:
"""Test validate version with no key."""
def _load_yaml(fname, secrets=None):
domain, yaml_file = fname.split("/")
assert yaml_file == TRIGGER_DESCRIPTION_FILENAME
trigger_descriptions = TRIGGER_DESCRIPTIONS[domain][yaml_file]
with io.StringIO(trigger_descriptions) as file:
return parse_yaml(file)
def _patched_path_read_text(path: Path):
domain = path.parent.name
filename = path.name
return json.dumps(TRIGGER_DESCRIPTIONS[domain][filename])
integrations = {
domain: get_integration(domain, config) for domain in TRIGGER_DESCRIPTIONS
}
with (
patch("script.hassfest.triggers.grep_dir", return_value=True),
patch("pathlib.Path.is_file", return_value=True),
patch("pathlib.Path.read_text", _patched_path_read_text),
patch("annotatedyaml.loader.load_yaml", side_effect=_load_yaml),
):
triggers.validate(integrations, config)
assert not config.errors
for domain, description in TRIGGER_DESCRIPTIONS.items():
assert len(integrations[domain].errors) == len(description["errors"]), (
f"Domain '{domain}' has unexpected errors: {integrations[domain].errors}"
)
for error, expected_error in zip(
integrations[domain].errors, description["errors"], strict=True
):
assert expected_error in error.error
| {
"repo_id": "home-assistant/core",
"file_path": "tests/hassfest/test_triggers.py",
"license": "Apache License 2.0",
"lines": 134,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/template/extensions/test_base64.py | """Test base64 encoding and decoding functions for Home Assistant templates."""
from __future__ import annotations
import pytest
from homeassistant.core import HomeAssistant
from tests.helpers.template.helpers import render
@pytest.mark.parametrize(
("value_template", "expected"),
[
('{{ "homeassistant" | base64_encode }}', "aG9tZWFzc2lzdGFudA=="),
("{{ int('0F010003', base=16) | pack('>I') | base64_encode }}", "DwEAAw=="),
("{{ 'AA01000200150020' | from_hex | base64_encode }}", "qgEAAgAVACA="),
],
)
def test_base64_encode(hass: HomeAssistant, value_template: str, expected: str) -> None:
"""Test the base64_encode filter."""
assert render(hass, value_template) == expected
def test_base64_decode(hass: HomeAssistant) -> None:
"""Test the base64_decode filter."""
assert (
render(hass, '{{ "aG9tZWFzc2lzdGFudA==" | base64_decode }}') == "homeassistant"
)
assert (
render(hass, '{{ "aG9tZWFzc2lzdGFudA==" | base64_decode(None) }}')
== b"homeassistant"
)
assert (
render(hass, '{{ "aG9tZWFzc2lzdGFudA==" | base64_decode("ascii") }}')
== "homeassistant"
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/extensions/test_base64.py",
"license": "Apache License 2.0",
"lines": 29,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/template/extensions/test_collection.py | """Test collection extension."""
from __future__ import annotations
from typing import Any
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import TemplateError
from tests.helpers.template.helpers import render
@pytest.mark.parametrize(
("value", "expected"),
[
([1, 2, 3], True),
({"a": 1}, False),
({1, 2, 3}, False),
((1, 2, 3), False),
("abc", False),
("", False),
(5, False),
(None, False),
({"foo": "bar", "baz": "qux"}, False),
],
)
def test_is_list(hass: HomeAssistant, value: Any, expected: bool) -> None:
"""Test list test."""
assert render(hass, "{{ value is list }}", {"value": value}) == expected
@pytest.mark.parametrize(
("value", "expected"),
[
([1, 2, 3], False),
({"a": 1}, False),
({1, 2, 3}, True),
((1, 2, 3), False),
("abc", False),
("", False),
(5, False),
(None, False),
({"foo": "bar", "baz": "qux"}, False),
],
)
def test_is_set(hass: HomeAssistant, value: Any, expected: bool) -> None:
"""Test set test."""
assert render(hass, "{{ value is set }}", {"value": value}) == expected
@pytest.mark.parametrize(
("value", "expected"),
[
([1, 2, 3], False),
({"a": 1}, False),
({1, 2, 3}, False),
((1, 2, 3), True),
("abc", False),
("", False),
(5, False),
(None, False),
({"foo": "bar", "baz": "qux"}, False),
],
)
def test_is_tuple(hass: HomeAssistant, value: Any, expected: bool) -> None:
"""Test tuple test."""
assert render(hass, "{{ value is tuple }}", {"value": value}) == expected
@pytest.mark.parametrize(
("value", "expected"),
[
([1, 2, 3], {"expected0": {1, 2, 3}}),
({"a": 1}, {"expected1": {"a"}}),
({1, 2, 3}, {"expected2": {1, 2, 3}}),
((1, 2, 3), {"expected3": {1, 2, 3}}),
("abc", {"expected4": {"a", "b", "c"}}),
("", {"expected5": set()}),
(range(3), {"expected6": {0, 1, 2}}),
({"foo": "bar", "baz": "qux"}, {"expected7": {"foo", "baz"}}),
],
)
def test_set(hass: HomeAssistant, value: Any, expected: bool) -> None:
"""Test set conversion."""
assert (
render(hass, "{{ set(value) }}", {"value": value}) == list(expected.values())[0]
)
@pytest.mark.parametrize(
("value", "expected"),
[
([1, 2, 3], {"expected0": (1, 2, 3)}),
({"a": 1}, {"expected1": ("a",)}),
({1, 2, 3}, {"expected2": (1, 2, 3)}), # Note: set order is not guaranteed
((1, 2, 3), {"expected3": (1, 2, 3)}),
("abc", {"expected4": ("a", "b", "c")}),
("", {"expected5": ()}),
(range(3), {"expected6": (0, 1, 2)}),
({"foo": "bar", "baz": "qux"}, {"expected7": ("foo", "baz")}),
],
)
def test_tuple(hass: HomeAssistant, value: Any, expected: bool) -> None:
"""Test tuple conversion."""
result = render(hass, "{{ tuple(value) }}", {"value": value})
expected_value = list(expected.values())[0]
if isinstance(value, set): # Sets don't have predictable order
assert set(result) == set(expected_value)
else:
assert result == expected_value
@pytest.mark.parametrize(
("cola", "colb", "expected"),
[
([1, 2], [3, 4], [(1, 3), (2, 4)]),
([1, 2], [3, 4, 5], [(1, 3), (2, 4)]),
([1, 2, 3, 4], [3, 4], [(1, 3), (2, 4)]),
],
)
def test_zip(hass: HomeAssistant, cola, colb, expected) -> None:
"""Test zip."""
for tpl in (
"{{ zip(cola, colb) | list }}",
"[{% for a, b in zip(cola, colb) %}({{a}}, {{b}}), {% endfor %}]",
):
assert render(hass, tpl, {"cola": cola, "colb": colb}) == expected
@pytest.mark.parametrize(
("col", "expected"),
[
([(1, 3), (2, 4)], [(1, 2), (3, 4)]),
(["ax", "by", "cz"], [("a", "b", "c"), ("x", "y", "z")]),
],
)
def test_unzip(hass: HomeAssistant, col, expected) -> None:
"""Test unzipping using zip."""
for tpl in (
"{{ zip(*col) | list }}",
"{% set a, b = zip(*col) %}[{{a}}, {{b}}]",
):
assert render(hass, tpl, {"col": col}) == expected
def test_shuffle(hass: HomeAssistant) -> None:
"""Test shuffle."""
# Test basic shuffle
result = render(hass, "{{ shuffle([1, 2, 3, 4, 5]) }}")
assert len(result) == 5
assert set(result) == {1, 2, 3, 4, 5}
# Test shuffle with seed
result1 = render(hass, "{{ shuffle([1, 2, 3, 4, 5], seed=42) }}")
result2 = render(hass, "{{ shuffle([1, 2, 3, 4, 5], seed=42) }}")
assert result1 == result2 # Same seed should give same result
# Test shuffle with different seed
result3 = render(hass, "{{ shuffle([1, 2, 3, 4, 5], seed=123) }}")
# Different seeds should usually give different results
# (but we can't guarantee it for small lists)
assert len(result3) == 5
assert set(result3) == {1, 2, 3, 4, 5}
def test_flatten(hass: HomeAssistant) -> None:
"""Test flatten."""
# Test basic flattening
assert render(hass, "{{ flatten([[1, 2], [3, 4]]) }}") == [1, 2, 3, 4]
# Test nested flattening
expected = [1, 2, 3, 4, 5, 6, 7, 8]
assert (
render(hass, "{{ flatten([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) }}") == expected
)
# Test flattening with levels
assert render(
hass, "{{ flatten([[[1, 2], [3, 4]], [[5, 6], [7, 8]]], levels=1) }}"
) == [[1, 2], [3, 4], [5, 6], [7, 8]]
# Test mixed types
assert render(hass, "{{ flatten([[1, 'a'], [2, 'b']]) }}") == [1, "a", 2, "b"]
# Test empty list
assert render(hass, "{{ flatten([]) }}") == []
# Test single level
assert render(hass, "{{ flatten([1, 2, 3]) }}") == [1, 2, 3]
def test_intersect(hass: HomeAssistant) -> None:
"""Test intersect."""
# Test basic intersection
result = render(hass, "{{ [1, 2, 3, 4] | intersect([3, 4, 5, 6]) | sort }}")
assert result == [3, 4]
# Test no intersection
result = render(hass, "{{ [1, 2] | intersect([3, 4]) }}")
assert result == []
# Test string intersection
result = render(hass, "{{ ['a', 'b', 'c'] | intersect(['b', 'c', 'd']) | sort }}")
assert result == ["b", "c"]
# Test empty list intersection
result = render(hass, "{{ [] | intersect([1, 2, 3]) }}")
assert result == []
def test_difference(hass: HomeAssistant) -> None:
"""Test difference."""
# Test basic difference
result = render(hass, "{{ [1, 2, 3, 4] | difference([3, 4, 5, 6]) | sort }}")
assert result == [1, 2]
# Test no difference
result = render(hass, "{{ [1, 2] | difference([1, 2, 3, 4]) }}")
assert result == []
# Test string difference
result = render(hass, "{{ ['a', 'b', 'c'] | difference(['b', 'c', 'd']) | sort }}")
assert result == ["a"]
# Test empty list difference
result = render(hass, "{{ [] | difference([1, 2, 3]) }}")
assert result == []
def test_union(hass: HomeAssistant) -> None:
"""Test union."""
# Test basic union
result = render(hass, "{{ [1, 2, 3] | union([3, 4, 5]) | sort }}")
assert result == [1, 2, 3, 4, 5]
# Test string union
result = render(hass, "{{ ['a', 'b'] | union(['b', 'c']) | sort }}")
assert result == ["a", "b", "c"]
# Test empty list union
result = render(hass, "{{ [] | union([1, 2, 3]) | sort }}")
assert result == [1, 2, 3]
# Test duplicate elements
result = render(hass, "{{ [1, 1, 2, 2] | union([2, 2, 3, 3]) | sort }}")
assert result == [1, 2, 3]
def test_symmetric_difference(hass: HomeAssistant) -> None:
"""Test symmetric_difference."""
# Test basic symmetric difference
result = render(
hass, "{{ [1, 2, 3, 4] | symmetric_difference([3, 4, 5, 6]) | sort }}"
)
assert result == [1, 2, 5, 6]
# Test no symmetric difference (identical sets)
result = render(hass, "{{ [1, 2, 3] | symmetric_difference([1, 2, 3]) }}")
assert result == []
# Test string symmetric difference
result = render(
hass, "{{ ['a', 'b', 'c'] | symmetric_difference(['b', 'c', 'd']) | sort }}"
)
assert result == ["a", "d"]
# Test empty list symmetric difference
result = render(hass, "{{ [] | symmetric_difference([1, 2, 3]) | sort }}")
assert result == [1, 2, 3]
def test_collection_functions_as_tests(hass: HomeAssistant) -> None:
"""Test that type checking functions work as tests."""
# Test various type checking functions
assert render(hass, "{{ [1,2,3] is list }}")
assert render(hass, "{{ set([1,2,3]) is set }}")
assert render(hass, "{{ (1,2,3) is tuple }}")
def test_collection_error_handling(hass: HomeAssistant) -> None:
"""Test error handling in collection functions."""
# Test flatten with non-iterable
with pytest.raises(TemplateError, match="flatten expected a list"):
render(hass, "{{ flatten(123) }}")
# Test intersect with non-iterable
with pytest.raises(TemplateError, match="intersect expected a list"):
render(hass, "{{ [1, 2] | intersect(123) }}")
# Test difference with non-iterable
with pytest.raises(TemplateError, match="difference expected a list"):
render(hass, "{{ [1, 2] | difference(123) }}")
# Test shuffle with no arguments
with pytest.raises(TemplateError, match="shuffle expected at least 1 argument"):
render(hass, "{{ shuffle() }}")
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/extensions/test_collection.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/helpers/template/extensions/test_crypto.py | """Test cryptographic hash functions for Home Assistant templates."""
from __future__ import annotations
from homeassistant.core import HomeAssistant
from tests.helpers.template.helpers import render
def test_md5(hass: HomeAssistant) -> None:
"""Test the md5 function and filter."""
ha_md5 = "3d15e5c102c3413d0337393c3287e006"
assert render(hass, "{{ md5('Home Assistant') }}") == ha_md5
assert render(hass, "{{ 'Home Assistant' | md5 }}") == ha_md5
def test_sha1(hass: HomeAssistant) -> None:
"""Test the sha1 function and filter."""
ha_sha1 = "c8fd3bb19b94312664faa619af7729bdbf6e9f8a"
assert render(hass, "{{ sha1('Home Assistant') }}") == ha_sha1
assert render(hass, "{{ 'Home Assistant' | sha1 }}") == ha_sha1
def test_sha256(hass: HomeAssistant) -> None:
"""Test the sha256 function and filter."""
ha_sha256 = "2a366abb0cd47f51f3725bf0fb7ebcb4fefa6e20f4971e25fe2bb8da8145ce2b"
assert render(hass, "{{ sha256('Home Assistant') }}") == ha_sha256
assert render(hass, "{{ 'Home Assistant' | sha256 }}") == ha_sha256
def test_sha512(hass: HomeAssistant) -> None:
"""Test the sha512 function and filter."""
ha_sha512 = "9e3c2cdd1fbab0037378d37e1baf8a3a4bf92c54b56ad1d459deee30ccbb2acbebd7a3614552ea08992ad27dedeb7b4c5473525ba90cb73dbe8b9ec5f69295bb"
assert render(hass, "{{ sha512('Home Assistant') }}") == ha_sha512
assert render(hass, "{{ 'Home Assistant' | sha512 }}") == ha_sha512
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/extensions/test_crypto.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/template/extensions/test_math.py | """Test mathematical and statistical functions for Home Assistant templates."""
from __future__ import annotations
import math
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import TemplateError
from homeassistant.helpers.template.extensions import MathExtension
from tests.helpers.template.helpers import render
def test_math_constants(hass: HomeAssistant) -> None:
"""Test math constants."""
assert render(hass, "{{ e }}") == math.e
assert render(hass, "{{ pi }}") == math.pi
assert render(hass, "{{ tau }}") == math.pi * 2
def test_logarithm(hass: HomeAssistant) -> None:
"""Test logarithm."""
tests = [
(4, 2, 2.0),
(1000, 10, 3.0),
(math.e, "", 1.0), # The "" means the default base (e) will be used
]
for value, base, expected in tests:
assert render(hass, f"{{{{ {value} | log({base}) | round(1) }}}}") == expected
assert render(hass, f"{{{{ log({value}, {base}) | round(1) }}}}") == expected
# Test handling of invalid input
with pytest.raises(TemplateError):
render(hass, "{{ invalid | log(_) }}")
with pytest.raises(TemplateError):
render(hass, "{{ log(invalid, _) }}")
with pytest.raises(TemplateError):
render(hass, "{{ 10 | log(invalid) }}")
with pytest.raises(TemplateError):
render(hass, "{{ log(10, invalid) }}")
# Test handling of default return value
assert render(hass, "{{ 'no_number' | log(10, 1) }}") == 1
assert render(hass, "{{ 'no_number' | log(10, default=1) }}") == 1
assert render(hass, "{{ log('no_number', 10, 1) }}") == 1
assert render(hass, "{{ log('no_number', 10, default=1) }}") == 1
assert render(hass, "{{ log(0, 10, 1) }}") == 1
assert render(hass, "{{ log(0, 10, default=1) }}") == 1
def test_sine(hass: HomeAssistant) -> None:
"""Test sine."""
tests = [
(0, 0.0),
(math.pi / 2, 1.0),
(math.pi, 0.0),
(math.pi * 1.5, -1.0),
(math.pi / 10, 0.309),
]
for value, expected in tests:
assert render(hass, f"{{{{ {value} | sin | round(3) }}}}") == expected
assert render(hass, f"{{{{ sin({value}) | round(3) }}}}") == expected
# Test handling of invalid input
with pytest.raises(TemplateError):
render(hass, "{{ 'duck' | sin }}")
with pytest.raises(TemplateError):
render(hass, "{{ invalid | sin('duck') }}")
# Test handling of default return value
assert render(hass, "{{ 'no_number' | sin(1) }}") == 1
assert render(hass, "{{ 'no_number' | sin(default=1) }}") == 1
assert render(hass, "{{ sin('no_number', 1) }}") == 1
assert render(hass, "{{ sin('no_number', default=1) }}") == 1
def test_cosine(hass: HomeAssistant) -> None:
"""Test cosine."""
tests = [
(0, 1.0),
(math.pi / 2, 0.0),
(math.pi, -1.0),
(math.pi * 1.5, 0.0),
(math.pi / 3, 0.5),
]
for value, expected in tests:
assert render(hass, f"{{{{ {value} | cos | round(3) }}}}") == expected
assert render(hass, f"{{{{ cos({value}) | round(3) }}}}") == expected
# Test handling of invalid input
with pytest.raises(TemplateError):
render(hass, "{{ 'duck' | cos }}")
# Test handling of default return value
assert render(hass, "{{ 'no_number' | cos(1) }}") == 1
assert render(hass, "{{ 'no_number' | cos(default=1) }}") == 1
assert render(hass, "{{ cos('no_number', 1) }}") == 1
assert render(hass, "{{ cos('no_number', default=1) }}") == 1
def test_tangent(hass: HomeAssistant) -> None:
"""Test tangent."""
tests = [
(0, 0.0),
(math.pi / 4, 1.0),
(math.pi, 0.0),
(math.pi / 6, 0.577),
]
for value, expected in tests:
assert render(hass, f"{{{{ {value} | tan | round(3) }}}}") == expected
assert render(hass, f"{{{{ tan({value}) | round(3) }}}}") == expected
# Test handling of invalid input
with pytest.raises(TemplateError):
render(hass, "{{ 'duck' | tan }}")
# Test handling of default return value
assert render(hass, "{{ 'no_number' | tan(1) }}") == 1
assert render(hass, "{{ 'no_number' | tan(default=1) }}") == 1
assert render(hass, "{{ tan('no_number', 1) }}") == 1
assert render(hass, "{{ tan('no_number', default=1) }}") == 1
def test_square_root(hass: HomeAssistant) -> None:
"""Test square root."""
tests = [
(0, 0.0),
(1, 1.0),
(4, 2.0),
(9, 3.0),
(16, 4.0),
(0.25, 0.5),
]
for value, expected in tests:
assert render(hass, f"{{{{ {value} | sqrt }}}}") == expected
assert render(hass, f"{{{{ sqrt({value}) }}}}") == expected
# Test handling of invalid input
with pytest.raises(TemplateError):
render(hass, "{{ 'duck' | sqrt }}")
with pytest.raises(TemplateError):
render(hass, "{{ -1 | sqrt }}")
# Test handling of default return value
assert render(hass, "{{ 'no_number' | sqrt(1) }}") == 1
assert render(hass, "{{ 'no_number' | sqrt(default=1) }}") == 1
assert render(hass, "{{ sqrt('no_number', 1) }}") == 1
assert render(hass, "{{ sqrt('no_number', default=1) }}") == 1
assert render(hass, "{{ sqrt(-1, 1) }}") == 1
assert render(hass, "{{ sqrt(-1, default=1) }}") == 1
def test_arc_functions(hass: HomeAssistant) -> None:
"""Test arc trigonometric functions."""
# Test arc sine
assert render(hass, "{{ asin(0.5) | round(3) }}") == round(math.asin(0.5), 3)
assert render(hass, "{{ 0.5 | asin | round(3) }}") == round(math.asin(0.5), 3)
# Test arc cosine
assert render(hass, "{{ acos(0.5) | round(3) }}") == round(math.acos(0.5), 3)
assert render(hass, "{{ 0.5 | acos | round(3) }}") == round(math.acos(0.5), 3)
# Test arc tangent
assert render(hass, "{{ atan(1) | round(3) }}") == round(math.atan(1), 3)
assert render(hass, "{{ 1 | atan | round(3) }}") == round(math.atan(1), 3)
# Test atan2
assert render(hass, "{{ atan2(1, 1) | round(3) }}") == round(math.atan2(1, 1), 3)
assert render(hass, "{{ atan2([1, 1]) | round(3) }}") == round(math.atan2(1, 1), 3)
# Test invalid input handling
with pytest.raises(TemplateError):
render(hass, "{{ asin(2) }}") # Outside domain [-1, 1]
# Test default values
assert render(hass, "{{ asin(2, 1) }}") == 1
assert render(hass, "{{ acos(2, 1) }}") == 1
assert render(hass, "{{ atan('invalid', 1) }}") == 1
assert render(hass, "{{ atan2('invalid', 1, 1) }}") == 1
def test_average(hass: HomeAssistant) -> None:
"""Test the average function."""
assert render(hass, "{{ average([1, 2, 3]) }}") == 2
assert render(hass, "{{ average(1, 2, 3) }}") == 2
# Testing of default values
assert render(hass, "{{ average([1, 2, 3], -1) }}") == 2
assert render(hass, "{{ average([], -1) }}") == -1
assert render(hass, "{{ average([], default=-1) }}") == -1
assert render(hass, "{{ average([], 5, default=-1) }}") == -1
assert render(hass, "{{ average(1, 'a', 3, default=-1) }}") == -1
with pytest.raises(TemplateError):
render(hass, "{{ average() }}")
with pytest.raises(TemplateError):
render(hass, "{{ average([]) }}")
def test_median(hass: HomeAssistant) -> None:
"""Test the median function."""
assert render(hass, "{{ median([1, 2, 3]) }}") == 2
assert render(hass, "{{ median([1, 2, 3, 4]) }}") == 2.5
assert render(hass, "{{ median(1, 2, 3) }}") == 2
# Testing of default values
assert render(hass, "{{ median([1, 2, 3], -1) }}") == 2
assert render(hass, "{{ median([], -1) }}") == -1
assert render(hass, "{{ median([], default=-1) }}") == -1
with pytest.raises(TemplateError):
render(hass, "{{ median() }}")
with pytest.raises(TemplateError):
render(hass, "{{ median([]) }}")
def test_statistical_mode(hass: HomeAssistant) -> None:
"""Test the statistical mode function."""
assert render(hass, "{{ statistical_mode([1, 1, 2, 3]) }}") == 1
assert render(hass, "{{ statistical_mode(1, 1, 2, 3) }}") == 1
# Testing of default values
assert render(hass, "{{ statistical_mode([1, 1, 2], -1) }}") == 1
assert render(hass, "{{ statistical_mode([], -1) }}") == -1
assert render(hass, "{{ statistical_mode([], default=-1) }}") == -1
with pytest.raises(TemplateError):
render(hass, "{{ statistical_mode() }}")
with pytest.raises(TemplateError):
render(hass, "{{ statistical_mode([]) }}")
def test_min_max_functions(hass: HomeAssistant) -> None:
"""Test min and max functions."""
# Test min function
assert render(hass, "{{ min([1, 2, 3]) }}") == 1
assert render(hass, "{{ min(1, 2, 3) }}") == 1
# Test max function
assert render(hass, "{{ max([1, 2, 3]) }}") == 3
assert render(hass, "{{ max(1, 2, 3) }}") == 3
# Test error handling
with pytest.raises(TemplateError):
render(hass, "{{ min() }}")
with pytest.raises(TemplateError):
render(hass, "{{ max() }}")
def test_bitwise_and(hass: HomeAssistant) -> None:
"""Test bitwise and."""
assert render(hass, "{{ bitwise_and(8, 2) }}") == 0
assert render(hass, "{{ bitwise_and(10, 2) }}") == 2
assert render(hass, "{{ bitwise_and(8, 8) }}") == 8
def test_bitwise_or(hass: HomeAssistant) -> None:
"""Test bitwise or."""
assert render(hass, "{{ bitwise_or(8, 2) }}") == 10
assert render(hass, "{{ bitwise_or(8, 8) }}") == 8
assert render(hass, "{{ bitwise_or(10, 2) }}") == 10
def test_bitwise_xor(hass: HomeAssistant) -> None:
"""Test bitwise xor."""
assert render(hass, "{{ bitwise_xor(8, 2) }}") == 10
assert render(hass, "{{ bitwise_xor(8, 8) }}") == 0
assert render(hass, "{{ bitwise_xor(10, 2) }}") == 8
@pytest.mark.parametrize(
"attribute",
[
"a",
"b",
"c",
],
)
def test_min_max_attribute(hass: HomeAssistant, attribute) -> None:
"""Test the min and max filters with attribute."""
hass.states.async_set(
"test.object",
"test",
{
"objects": [
{
"a": 1,
"b": 2,
"c": 3,
},
{
"a": 2,
"b": 1,
"c": 2,
},
{
"a": 3,
"b": 3,
"c": 1,
},
],
},
)
assert (
render(
hass,
f"{{{{ (state_attr('test.object', 'objects') | min(attribute='{attribute}'))['{attribute}']}}}}",
)
== 1
)
assert (
render(
hass,
f"{{{{ (min(state_attr('test.object', 'objects'), attribute='{attribute}'))['{attribute}']}}}}",
)
== 1
)
assert (
render(
hass,
f"{{{{ (state_attr('test.object', 'objects') | max(attribute='{attribute}'))['{attribute}']}}}}",
)
== 3
)
assert (
render(
hass,
f"{{{{ (max(state_attr('test.object', 'objects'), attribute='{attribute}'))['{attribute}']}}}}",
)
== 3
)
def test_clamp(hass: HomeAssistant) -> None:
"""Test clamp function."""
# Test function and filter usage in templates.
assert render(hass, "{{ clamp(15, 0, 10) }}") == 10.0
assert render(hass, "{{ -5 | clamp(0, 10) }}") == 0.0
# Test basic clamping behavior
assert MathExtension.clamp(5, 0, 10) == 5.0
assert MathExtension.clamp(-5, 0, 10) == 0.0
assert MathExtension.clamp(15, 0, 10) == 10.0
assert MathExtension.clamp(0, 0, 10) == 0.0
assert MathExtension.clamp(10, 0, 10) == 10.0
# Test with float values
assert MathExtension.clamp(5.5, 0, 10) == 5.5
assert MathExtension.clamp(5.5, 0.5, 10.5) == 5.5
assert MathExtension.clamp(0.25, 0.5, 10.5) == 0.5
assert MathExtension.clamp(11.0, 0.5, 10.5) == 10.5
# Test with negative ranges
assert MathExtension.clamp(-5, -10, -1) == -5.0
assert MathExtension.clamp(-15, -10, -1) == -10.0
assert MathExtension.clamp(0, -10, -1) == -1.0
# Test with non-range
assert MathExtension.clamp(5, 10, 10) == 10.0
# Test error handling - invalid input types
for case in (
"{{ clamp('invalid', 0, 10) }}",
"{{ clamp(5, 'invalid', 10) }}",
"{{ clamp(5, 0, 'invalid') }}",
):
with pytest.raises(TemplateError):
render(hass, case)
def test_wrap(hass: HomeAssistant) -> None:
"""Test wrap function."""
# Test function and filter usage in templates.
assert render(hass, "{{ wrap(15, 0, 10) }}") == 5.0
assert render(hass, "{{ -5 | wrap(0, 10) }}") == 5.0
# Test basic wrapping behavior
assert MathExtension.wrap(5, 0, 10) == 5.0
assert MathExtension.wrap(10, 0, 10) == 0.0 # max wraps to min
assert MathExtension.wrap(15, 0, 10) == 5.0
assert MathExtension.wrap(25, 0, 10) == 5.0
assert MathExtension.wrap(-5, 0, 10) == 5.0
assert MathExtension.wrap(-10, 0, 10) == 0.0
# Test angle wrapping (common use case)
assert MathExtension.wrap(370, 0, 360) == 10.0
assert MathExtension.wrap(-10, 0, 360) == 350.0
assert MathExtension.wrap(720, 0, 360) == 0.0
assert MathExtension.wrap(361, 0, 360) == 1.0
# Test with float values
assert MathExtension.wrap(10.5, 0, 10) == 0.5
assert MathExtension.wrap(370.5, 0, 360) == 10.5
# Test with negative ranges
assert MathExtension.wrap(-15, -10, 0) == -5.0
assert MathExtension.wrap(5, -10, 0) == -5.0
# Test with arbitrary ranges
assert MathExtension.wrap(25, 10, 20) == 15.0
assert MathExtension.wrap(5, 10, 20) == 15.0
# Test with non-range
assert MathExtension.wrap(5, 10, 10) == 10.0
# Test error handling - invalid input types
for case in (
"{{ wrap('invalid', 0, 10) }}",
"{{ wrap(5, 'invalid', 10) }}",
"{{ wrap(5, 0, 'invalid') }}",
):
with pytest.raises(TemplateError):
render(hass, case)
def test_remap(hass: HomeAssistant) -> None:
"""Test remap function."""
# Test function and filter usage in templates, with kitchen sink parameters.
# We don't check the return value; that's covered by the unit tests below.
assert render(hass, "{{ remap(5, 0, 6, 0, 740, steps=10) }}")
assert render(hass, "{{ 50 | remap(0, 100, 0, 10, steps=8) }}")
# Test basic remapping - scale from 0-10 to 0-100
assert MathExtension.remap(0, 0, 10, 0, 100) == 0.0
assert MathExtension.remap(5, 0, 10, 0, 100) == 50.0
assert MathExtension.remap(10, 0, 10, 0, 100) == 100.0
# Test with different input and output ranges
assert MathExtension.remap(50, 0, 100, 0, 10) == 5.0
assert MathExtension.remap(25, 0, 100, 0, 10) == 2.5
# Test with negative ranges
assert MathExtension.remap(0, -10, 10, 0, 100) == 50.0
assert MathExtension.remap(-10, -10, 10, 0, 100) == 0.0
assert MathExtension.remap(10, -10, 10, 0, 100) == 100.0
# Test inverted output range
assert MathExtension.remap(0, 0, 10, 100, 0) == 100.0
assert MathExtension.remap(5, 0, 10, 100, 0) == 50.0
assert MathExtension.remap(10, 0, 10, 100, 0) == 0.0
# Test values outside input range, and edge modes
assert MathExtension.remap(15, 0, 10, 0, 100, edges="none") == 150.0
assert MathExtension.remap(-4, 0, 10, 0, 100, edges="none") == -40.0
assert MathExtension.remap(15, 0, 10, 0, 80, edges="clamp") == 80.0
assert MathExtension.remap(-5, 0, 10, -1, 1, edges="clamp") == -1
assert MathExtension.remap(15, 0, 10, 0, 100, edges="wrap") == 50.0
assert MathExtension.remap(-5, 0, 10, 0, 100, edges="wrap") == 50.0
# Test sensor conversion use case: Celsius to Fahrenheit: 0-100°C to 32-212°F
assert MathExtension.remap(0, 0, 100, 32, 212) == 32.0
assert MathExtension.remap(100, 0, 100, 32, 212) == 212.0
assert MathExtension.remap(50, 0, 100, 32, 212) == 122.0
# Test time conversion use case: 0-60 minutes to 0-360 degrees, with wrap
assert MathExtension.remap(80, 0, 60, 0, 360, edges="wrap") == 120.0
# Test percentage to byte conversion (0-100% to 0-255)
assert MathExtension.remap(0, 0, 100, 0, 255) == 0.0
assert MathExtension.remap(50, 0, 100, 0, 255) == 127.5
assert MathExtension.remap(100, 0, 100, 0, 255) == 255.0
# Test with float precision
assert MathExtension.remap(2.5, 0, 10, 0, 100) == 25.0
assert MathExtension.remap(7.5, 0, 10, 0, 100) == 75.0
# Test error handling
for case in (
"{{ remap(5, 10, 10, 0, 100) }}",
"{{ remap('invalid', 0, 10, 0, 100) }}",
"{{ remap(5, 'invalid', 10, 0, 100) }}",
"{{ remap(5, 0, 'invalid', 0, 100) }}",
"{{ remap(5, 0, 10, 'invalid', 100) }}",
"{{ remap(5, 0, 10, 0, 'invalid') }}",
):
with pytest.raises(TemplateError):
render(hass, case)
def test_remap_with_steps(hass: HomeAssistant) -> None:
"""Test remap function with steps parameter."""
# Test basic stepping - quantize to 10 steps
assert MathExtension.remap(0.2, 0, 10, 0, 100, steps=10) == 0.0
assert MathExtension.remap(5.3, 0, 10, 0, 100, steps=10) == 50.0
assert MathExtension.remap(10, 0, 10, 0, 100, steps=10) == 100.0
# Test stepping with intermediate values - should snap to nearest step
# With 10 steps, normalized values are rounded: 0.0, 0.1, 0.2, ..., 1.0
assert MathExtension.remap(2.4, 0, 10, 0, 100, steps=10) == 20.0
assert MathExtension.remap(2.5, 0, 10, 0, 100, steps=10) == 20.0
assert MathExtension.remap(2.6, 0, 10, 0, 100, steps=10) == 30.0
# Test with 4 steps (0%, 25%, 50%, 75%, 100%)
assert MathExtension.remap(0, 0, 10, 0, 100, steps=4) == 0.0
assert MathExtension.remap(2.5, 0, 10, 0, 100, steps=4) == 25.0
assert MathExtension.remap(5, 0, 10, 0, 100, steps=4) == 50.0
assert MathExtension.remap(7.5, 0, 10, 0, 100, steps=4) == 75.0
assert MathExtension.remap(10, 0, 10, 0, 100, steps=4) == 100.0
# Test with 2 steps (0%, 50%, 100%)
assert MathExtension.remap(2, 0, 10, 0, 100, steps=2) == 0.0
assert MathExtension.remap(6, 0, 10, 0, 100, steps=2) == 50.0
assert MathExtension.remap(8, 0, 10, 0, 100, steps=2) == 100.0
# Test with 1 step (0%, 100%)
assert MathExtension.remap(0, 0, 10, 0, 100, steps=1) == 0.0
assert MathExtension.remap(5, 0, 10, 0, 100, steps=1) == 0.0
assert MathExtension.remap(6, 0, 10, 0, 100, steps=1) == 100.0
assert MathExtension.remap(10, 0, 10, 0, 100, steps=1) == 100.0
# Test with inverted output range and steps
assert MathExtension.remap(4.8, 0, 10, 100, 0, steps=4) == 50.0
# Test with 0 or negative steps (should be ignored/no quantization)
assert MathExtension.remap(5, 0, 10, 0, 100, steps=0) == 50.0
assert MathExtension.remap(2.7, 0, 10, 0, 100, steps=0) == 27.0
assert MathExtension.remap(5, 0, 10, 0, 100, steps=-1) == 50.0
def test_remap_with_mirror(hass: HomeAssistant) -> None:
"""Test the mirror edge mode of the remap function."""
assert [
MathExtension.remap(i, 0, 4, 0, 1, edges="mirror") for i in range(-4, 9)
] == [1.0, 0.75, 0.5, 0.25, 0.0, 0.25, 0.5, 0.75, 1.0, 0.75, 0.5, 0.25, 0.0]
# Test with different output range
assert MathExtension.remap(15, 0, 10, 50, 150, edges="mirror") == 100.0
assert MathExtension.remap(25, 0, 10, 50, 150, edges="mirror") == 100.0
# Test with inverted output range
assert MathExtension.remap(15, 0, 10, 100, 0, edges="mirror") == 50.0
assert MathExtension.remap(12, 0, 10, 100, 0, edges="mirror") == 20.0
# Test without remapping
assert MathExtension.remap(-0.1, 0, 1, 0, 1, edges="mirror") == pytest.approx(0.1)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/extensions/test_math.py",
"license": "Apache License 2.0",
"lines": 438,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/template/extensions/test_regex.py | """Test regex template extension."""
from __future__ import annotations
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import TemplateError
from tests.helpers.template.helpers import render
def test_regex_match(hass: HomeAssistant) -> None:
"""Test regex_match method."""
result = render(
hass, r"""{{ '123-456-7890' | regex_match('(\\d{3})-(\\d{3})-(\\d{4})') }}"""
)
assert result is True
result = render(hass, """{{ 'Home Assistant test' | regex_match('home', True) }}""")
assert result is True
result = render(hass, """{{ 'Another Home Assistant test'|regex_match('Home') }}""")
assert result is False
result = render(hass, """{{ ['Home Assistant test'] | regex_match('.*Assist') }}""")
assert result is True
def test_match_test(hass: HomeAssistant) -> None:
"""Test match test."""
result = render(
hass, r"""{{ '123-456-7890' is match('(\\d{3})-(\\d{3})-(\\d{4})') }}"""
)
assert result is True
def test_regex_search(hass: HomeAssistant) -> None:
"""Test regex_search method."""
result = render(
hass, r"""{{ '123-456-7890' | regex_search('(\\d{3})-(\\d{3})-(\\d{4})') }}"""
)
assert result is True
result = render(
hass, """{{ 'Home Assistant test' | regex_search('home', True) }}"""
)
assert result is True
result = render(
hass, """ {{ 'Another Home Assistant test' | regex_search('Home') }}"""
)
assert result is True
result = render(hass, """{{ ['Home Assistant test'] | regex_search('Assist') }}""")
assert result is True
def test_search_test(hass: HomeAssistant) -> None:
"""Test search test."""
result = render(
hass, r"""{{ '123-456-7890' is search('(\\d{3})-(\\d{3})-(\\d{4})') }}"""
)
assert result is True
def test_regex_replace(hass: HomeAssistant) -> None:
"""Test regex_replace method."""
result = render(hass, r"""{{ 'Hello World' | regex_replace('(Hello\\s)',) }}""")
assert result == "World"
result = render(
hass, """{{ ['Home hinderant test'] | regex_replace('hinder', 'Assist') }}"""
)
assert result == ["Home Assistant test"]
def test_regex_findall(hass: HomeAssistant) -> None:
"""Test regex_findall method."""
result = render(
hass, """{{ 'Flight from JFK to LHR' | regex_findall('([A-Z]{3})') }}"""
)
assert result == ["JFK", "LHR"]
def test_regex_findall_index(hass: HomeAssistant) -> None:
"""Test regex_findall_index method."""
result = render(
hass,
"""{{ 'Flight from JFK to LHR' | regex_findall_index('([A-Z]{3})', 0) }}""",
)
assert result == "JFK"
result = render(
hass,
"""{{ 'Flight from JFK to LHR' | regex_findall_index('([A-Z]{3})', 1) }}""",
)
assert result == "LHR"
def test_regex_ignorecase_parameter(hass: HomeAssistant) -> None:
"""Test ignorecase parameter across all regex functions."""
# Test regex_match with ignorecase
result = render(hass, """{{ 'TEST' | regex_match('test', True) }}""")
assert result is True
# Test regex_search with ignorecase
result = render(hass, """{{ 'TEST STRING' | regex_search('test', True) }}""")
assert result is True
# Test regex_replace with ignorecase
result = render(hass, """{{ 'TEST' | regex_replace('test', 'replaced', True) }}""")
assert result == "replaced"
# Test regex_findall with ignorecase
result = render(hass, """{{ 'TEST test Test' | regex_findall('test', True) }}""")
assert result == ["TEST", "test", "Test"]
def test_regex_with_non_string_input(hass: HomeAssistant) -> None:
"""Test regex functions with non-string input (automatic conversion)."""
# Test with integer
result = render(hass, r"""{{ 12345 | regex_match('\\d+') }}""")
assert result is True
# Test with list (string conversion)
result = render(hass, r"""{{ [1, 2, 3] | regex_search('\\d') }}""")
assert result is True
def test_regex_edge_cases(hass: HomeAssistant) -> None:
"""Test regex functions with edge cases."""
# Test with empty string
assert render(hass, """{{ '' | regex_match('.*') }}""") is True
# Test regex_findall_index with out of bounds index
with pytest.raises(TemplateError):
render(hass, """{{ 'test' | regex_findall_index('t', 5) }}""")
# Test with invalid regex pattern
with pytest.raises(TemplateError): # re.error wrapped in TemplateError
render(hass, """{{ 'test' | regex_match('[') }}""")
def test_regex_groups_and_replacement_patterns(hass: HomeAssistant) -> None:
"""Test regex with groups and replacement patterns."""
# Test replacement with groups
result = render(
hass, r"""{{ 'John Doe' | regex_replace('(\\w+) (\\w+)', '\\2, \\1') }}"""
)
assert result == "Doe, John"
# Test findall with groups
result = render(
hass,
r"""{{ 'Email: test@example.com, Phone: 123-456-7890' | regex_findall('(\\w+@\\w+\\.\\w+)|(\\d{3}-\\d{3}-\\d{4})') }}""",
)
# The result will contain tuples with empty strings for non-matching groups
assert len(result) == 2
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/extensions/test_regex.py",
"license": "Apache License 2.0",
"lines": 118,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/template/extensions/test_string.py | """Test string template extension."""
from __future__ import annotations
from homeassistant.core import HomeAssistant
from tests.helpers.template.helpers import render
def test_ordinal(hass: HomeAssistant) -> None:
"""Test the ordinal filter."""
tests = [
(1, "1st"),
(2, "2nd"),
(3, "3rd"),
(4, "4th"),
(5, "5th"),
(12, "12th"),
(100, "100th"),
(101, "101st"),
]
for value, expected in tests:
assert render(hass, f"{{{{ {value} | ordinal }}}}") == expected
def test_slugify(hass: HomeAssistant) -> None:
"""Test the slugify filter."""
# Test as global function
assert render(hass, '{{ slugify("Home Assistant") }}') == "home_assistant"
# Test as filter
assert render(hass, '{{ "Home Assistant" | slugify }}') == "home_assistant"
# Test with custom separator as global
assert render(hass, '{{ slugify("Home Assistant", "-") }}') == "home-assistant"
# Test with custom separator as filter
assert render(hass, '{{ "Home Assistant" | slugify("-") }}') == "home-assistant"
def test_urlencode(hass: HomeAssistant) -> None:
"""Test the urlencode method."""
# Test with dictionary
result = render(
hass, "{% set dict = {'foo': 'x&y', 'bar': 42} %}{{ dict | urlencode }}"
)
assert result == "foo=x%26y&bar=42"
# Test with string
result = render(
hass, "{% set string = 'the quick brown fox = true' %}{{ string | urlencode }}"
)
assert result == "the%20quick%20brown%20fox%20%3D%20true"
def test_string_functions_with_non_string_input(hass: HomeAssistant) -> None:
"""Test string functions with non-string input (automatic conversion)."""
# Test ordinal with integer
assert render(hass, "{{ 42 | ordinal }}") == "42nd"
# Test slugify with integer - Note: Jinja2 may return integer for simple cases
result = render(hass, "{{ 123 | slugify }}")
# Accept either string or integer result for simple numeric cases
assert result in ["123", 123]
def test_ordinal_edge_cases(hass: HomeAssistant) -> None:
"""Test ordinal function with edge cases."""
# Test teens (11th, 12th, 13th should all be 'th')
teens_tests = [
(11, "11th"),
(12, "12th"),
(13, "13th"),
(111, "111th"),
(112, "112th"),
(113, "113th"),
]
for value, expected in teens_tests:
assert render(hass, f"{{{{ {value} | ordinal }}}}") == expected
# Test other numbers ending in 1, 2, 3
other_tests = [
(21, "21st"),
(22, "22nd"),
(23, "23rd"),
(121, "121st"),
(122, "122nd"),
(123, "123rd"),
]
for value, expected in other_tests:
assert render(hass, f"{{{{ {value} | ordinal }}}}") == expected
def test_slugify_various_separators(hass: HomeAssistant) -> None:
"""Test slugify with various separators."""
test_cases = [
("Hello World", "_", "hello_world"),
("Hello World", "-", "hello-world"),
("Hello World", ".", "hello.world"),
("Hello-World_Test", "~", "hello~world~test"),
]
for text, separator, expected in test_cases:
# Test as global function
assert render(hass, f'{{{{ slugify("{text}", "{separator}") }}}}') == expected
# Test as filter
assert render(hass, f'{{{{ "{text}" | slugify("{separator}") }}}}') == expected
def test_urlencode_various_types(hass: HomeAssistant) -> None:
"""Test urlencode with various data types."""
# Test with nested dictionary values
result = render(
hass,
"{% set data = {'key': 'value with spaces', 'num': 123} %}{{ data | urlencode }}",
)
# URL encoding can have different order, so check both parts are present
# Note: urllib.parse.urlencode uses + for spaces in form data
assert "key=value+with+spaces" in result
assert "num=123" in result
# Test with special characters
result = render(
hass, "{% set data = {'special': 'a+b=c&d'} %}{{ data | urlencode }}"
)
assert result == "special=a%2Bb%3Dc%26d"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/extensions/test_string.py",
"license": "Apache License 2.0",
"lines": 101,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/template/test_context.py | """Test template context management for Home Assistant."""
from __future__ import annotations
import jinja2
from homeassistant.helpers.template.context import (
TemplateContextManager,
render_with_context,
template_context_manager,
template_cv,
)
def test_template_context_manager() -> None:
"""Test TemplateContextManager functionality."""
cm = TemplateContextManager()
# Test setting template
cm.set_template("{{ test }}", "rendering")
assert template_cv.get() == ("{{ test }}", "rendering")
# Test context manager exit
cm.__exit__(None, None, None)
assert template_cv.get() is None
def test_template_context_manager_context() -> None:
"""Test TemplateContextManager as context manager."""
cm = TemplateContextManager()
with cm:
cm.set_template("{{ test }}", "parsing")
assert template_cv.get() == ("{{ test }}", "parsing")
# Should be cleared after exit
assert template_cv.get() is None
def test_global_template_context_manager() -> None:
"""Test global template context manager instance."""
# Should be an instance of TemplateContextManager
assert isinstance(template_context_manager, TemplateContextManager)
# Test it works like any other context manager
template_context_manager.set_template("{{ global_test }}", "testing")
assert template_cv.get() == ("{{ global_test }}", "testing")
template_context_manager.__exit__(None, None, None)
assert template_cv.get() is None
def test_render_with_context() -> None:
"""Test render_with_context function."""
# Create a simple template
env = jinja2.Environment()
template_obj = env.from_string("Hello {{ name }}!")
# Test rendering with context tracking
result = render_with_context("Hello {{ name }}!", template_obj, name="World")
assert result == "Hello World!"
# Context should be cleared after rendering
assert template_cv.get() is None
def test_render_with_context_sets_context() -> None:
"""Test that render_with_context properly sets template context."""
# Create a template that we can use to check context
jinja2.Environment()
# We'll use a custom template class to capture context during rendering
context_during_render = []
class MockTemplate:
def render(self, **kwargs):
# Capture the context during rendering
context_during_render.append(template_cv.get())
return "rendered"
mock_template = MockTemplate()
# Render with context
result = render_with_context("{{ test_template }}", mock_template, test=True)
assert result == "rendered"
# Should have captured the context during rendering
assert len(context_during_render) == 1
assert context_during_render[0] == ("{{ test_template }}", "rendering")
# Context should be cleared after rendering
assert template_cv.get() is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/test_context.py",
"license": "Apache License 2.0",
"lines": 65,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/template/test_helpers.py | """Test template helper functions."""
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.helpers import (
area_registry as ar,
device_registry as dr,
entity_registry as er,
)
from homeassistant.helpers.template.helpers import raise_no_default, resolve_area_id
from tests.common import MockConfigEntry
def test_raise_no_default() -> None:
"""Test raise_no_default raises ValueError with correct message."""
with pytest.raises(
ValueError,
match="Template error: test got invalid input 'invalid' when rendering or compiling template '' but no default was specified",
):
raise_no_default("test", "invalid")
async def test_resolve_area_id(
hass: HomeAssistant,
area_registry: ar.AreaRegistry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test resolve_area_id function."""
config_entry = MockConfigEntry(domain="light")
config_entry.add_to_hass(hass)
# Test non existing entity id
assert resolve_area_id(hass, "sensor.fake") is None
# Test non existing device id (hex value)
assert resolve_area_id(hass, "123abc") is None
# Test non existing area name
assert resolve_area_id(hass, "fake area name") is None
# Test wrong value type
assert resolve_area_id(hass, 56) is None
area_entry_entity_id = area_registry.async_get_or_create("sensor.fake")
# Test device with single entity, which has no area
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
"light",
"hue",
"5678",
config_entry=config_entry,
device_id=device_entry.id,
)
assert resolve_area_id(hass, device_entry.id) is None
assert resolve_area_id(hass, entity_entry.entity_id) is None
# Test device ID, entity ID and area name as input with area name that looks like
# a device ID
area_entry_hex = area_registry.async_get_or_create("123abc")
device_entry = device_registry.async_update_device(
device_entry.id, area_id=area_entry_hex.id
)
entity_entry = entity_registry.async_update_entity(
entity_entry.entity_id, area_id=area_entry_hex.id
)
assert resolve_area_id(hass, device_entry.id) == area_entry_hex.id
assert resolve_area_id(hass, entity_entry.entity_id) == area_entry_hex.id
assert resolve_area_id(hass, area_entry_hex.name) == area_entry_hex.id
# Test device ID, entity ID and area name as input with area name that looks like an
# entity ID
area_entry_entity_id = area_registry.async_get_or_create("sensor.fake")
device_entry = device_registry.async_update_device(
device_entry.id, area_id=area_entry_entity_id.id
)
entity_entry = entity_registry.async_update_entity(
entity_entry.entity_id, area_id=area_entry_entity_id.id
)
assert resolve_area_id(hass, device_entry.id) == area_entry_entity_id.id
assert resolve_area_id(hass, entity_entry.entity_id) == area_entry_entity_id.id
assert resolve_area_id(hass, area_entry_entity_id.name) == area_entry_entity_id.id
# Make sure that when entity doesn't have an area but its device does, that's what
# gets returned
entity_entry = entity_registry.async_update_entity(
entity_entry.entity_id, area_id=None
)
assert resolve_area_id(hass, entity_entry.entity_id) == area_entry_entity_id.id
# Test area alias
area_with_alias = area_registry.async_get_or_create("Living Room")
area_registry.async_update(area_with_alias.id, aliases={"lounge", "family room"})
assert resolve_area_id(hass, "Living Room") == area_with_alias.id
assert resolve_area_id(hass, "lounge") == area_with_alias.id
assert resolve_area_id(hass, "family room") == area_with_alias.id
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/test_helpers.py",
"license": "Apache License 2.0",
"lines": 85,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/template/test_render_info.py | """Test template render information tracking for Home Assistant."""
from __future__ import annotations
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import TemplateError
from homeassistant.helpers import template
from homeassistant.helpers.template.render_info import (
ALL_STATES_RATE_LIMIT,
DOMAIN_STATES_RATE_LIMIT,
RenderInfo,
_false,
_true,
render_info_cv,
)
@pytest.fixture
def template_obj(hass: HomeAssistant) -> template.Template:
"""Template object for test_render_info."""
return template.Template("{{ 1 + 1 }}", hass)
def test_render_info_initialization(template_obj: template.Template) -> None:
"""Test RenderInfo initialization."""
info = RenderInfo(template_obj)
assert info.template is template_obj
assert info._result is None
assert info.is_static is False
assert info.exception is None
assert info.all_states is False
assert info.all_states_lifecycle is False
assert info.domains == set()
assert info.domains_lifecycle == set()
assert info.entities == set()
assert info.rate_limit is None
assert info.has_time is False
assert info.filter_lifecycle is _true
assert info.filter is _true
def test_render_info_repr(template_obj: template.Template) -> None:
"""Test RenderInfo representation."""
info = RenderInfo(template_obj)
info.domains.add("sensor")
info.entities.add("sensor.test")
repr_str = repr(info)
assert "RenderInfo" in repr_str
assert "domains={'sensor'}" in repr_str
assert "entities={'sensor.test'}" in repr_str
def test_render_info_result(template_obj: template.Template) -> None:
"""Test RenderInfo result property."""
info = RenderInfo(template_obj)
# Test with no result set - should return None cast as str
assert info.result() is None
# Test with result set
info._result = "test_result"
assert info.result() == "test_result"
# Test with exception
info.exception = TemplateError("Test error")
with pytest.raises(TemplateError, match="Test error"):
info.result()
def test_render_info_filter_domains_and_entities(
template_obj: template.Template,
) -> None:
"""Test RenderInfo entity and domain filtering."""
info = RenderInfo(template_obj)
# Add domain and entity
info.domains.add("sensor")
info.entities.add("light.test")
# Should match domain
assert info._filter_domains_and_entities("sensor.temperature") is True
# Should match entity
assert info._filter_domains_and_entities("light.test") is True
# Should not match
assert info._filter_domains_and_entities("switch.kitchen") is False
def test_render_info_filter_entities(template_obj: template.Template) -> None:
"""Test RenderInfo entity-only filtering."""
info = RenderInfo(template_obj)
info.entities.add("sensor.test")
assert info._filter_entities("sensor.test") is True
assert info._filter_entities("sensor.other") is False
def test_render_info_filter_lifecycle_domains(template_obj: template.Template) -> None:
"""Test RenderInfo domain lifecycle filtering."""
info = RenderInfo(template_obj)
info.domains_lifecycle.add("sensor")
assert info._filter_lifecycle_domains("sensor.test") is True
assert info._filter_lifecycle_domains("light.test") is False
def test_render_info_freeze_static(template_obj: template.Template) -> None:
"""Test RenderInfo static freezing."""
info = RenderInfo(template_obj)
info.domains.add("sensor")
info.entities.add("sensor.test")
info.all_states = True
info._freeze_static()
assert info.is_static is True
assert info.all_states is False
assert isinstance(info.domains, frozenset)
assert isinstance(info.entities, frozenset)
def test_render_info_freeze(template_obj: template.Template) -> None:
"""Test RenderInfo freezing with rate limits."""
info = RenderInfo(template_obj)
# Test all_states rate limit
info.all_states = True
info._freeze()
assert info.rate_limit == ALL_STATES_RATE_LIMIT
# Test domain rate limit
info = RenderInfo(template_obj)
info.domains.add("sensor")
info._freeze()
assert info.rate_limit == DOMAIN_STATES_RATE_LIMIT
# Test exception rate limit
info = RenderInfo(template_obj)
info.exception = TemplateError("Test")
info._freeze()
assert info.rate_limit == ALL_STATES_RATE_LIMIT
def test_render_info_freeze_filters(template_obj: template.Template) -> None:
"""Test RenderInfo filter assignment during freeze."""
# Test lifecycle filter assignment
info = RenderInfo(template_obj)
info.domains_lifecycle.add("sensor")
info._freeze()
assert info.filter_lifecycle == info._filter_lifecycle_domains
# Test no lifecycle domains
info = RenderInfo(template_obj)
info._freeze()
assert info.filter_lifecycle is _false
# Test domain and entity filter
info = RenderInfo(template_obj)
info.domains.add("sensor")
info._freeze()
assert info.filter == info._filter_domains_and_entities
# Test entity-only filter
info = RenderInfo(template_obj)
info.entities.add("sensor.test")
info._freeze()
assert info.filter == info._filter_entities
# Test no domains or entities
info = RenderInfo(template_obj)
info._freeze()
assert info.filter is _false
def test_render_info_context_var(template_obj: template.Template) -> None:
"""Test render_info_cv context variable."""
# Should start as None
assert render_info_cv.get() is None
# Test setting and getting
info = RenderInfo(template_obj)
render_info_cv.set(info)
assert render_info_cv.get() is info
# Reset for other tests
render_info_cv.set(None)
assert render_info_cv.get() is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/test_render_info.py",
"license": "Apache License 2.0",
"lines": 145,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/helpers/test_service_info.py | """Test service_info helpers."""
import pytest
from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo
from homeassistant.helpers.service_info.esphome import ESPHomeServiceInfo
# Ensure that incorrectly formatted mac addresses are rejected, even
# on a constant outside of a test
try:
_ = DhcpServiceInfo(ip="", hostname="", macaddress="AA:BB:CC:DD:EE:FF")
except ValueError:
pass
else:
raise RuntimeError(
"DhcpServiceInfo incorrectly formatted mac address was not rejected. "
"Please ensure that the DhcpServiceInfo is correctly patched."
)
def test_invalid_macaddress() -> None:
"""Test that DhcpServiceInfo raises ValueError for unformatted macaddress."""
with pytest.raises(ValueError):
DhcpServiceInfo(ip="", hostname="", macaddress="AA:BB:CC:DD:EE:FF")
def test_esphome_socket_path() -> None:
"""Test ESPHomeServiceInfo socket_path property."""
info = ESPHomeServiceInfo(
name="Hello World",
zwave_home_id=123456789,
ip_address="192.168.1.100",
port=6053,
)
assert info.socket_path == "esphome://192.168.1.100:6053"
info.noise_psk = "my-noise-psk"
assert info.socket_path == "esphome://my-noise-psk@192.168.1.100:6053"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/test_service_info.py",
"license": "Apache License 2.0",
"lines": 30,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/vegehub/test_switch.py | """Unit tests for the VegeHub integration's switch.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"}]},
{"slot": 6, "samples": [{"v": 1, "t": "2025-01-15T16:51:23Z"}]},
{"slot": 7, "samples": [{"v": 0, "t": "2025-01-15T16:51:23Z"}]},
],
"send_time": 1736959883,
"wifi_str": -27,
}
async def test_switch_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.SWITCH]):
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
)
async def test_switch_turn_on_off(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
mocked_config_entry: MockConfigEntry,
) -> None:
"""Test switch turn_on and turn_off methods."""
with patch("homeassistant.components.vegehub.PLATFORMS", [Platform.SWITCH]):
await init_integration(hass, mocked_config_entry)
# Send webhook data to initialize switches
client = await hass_client_no_auth()
resp = await client.post(f"/api/webhook/{TEST_WEBHOOK_ID}", json=UPDATE_DATA)
await hass.async_block_till_done()
assert resp.status == 200
# Get switch entity IDs
switch_entity_ids = hass.states.async_entity_ids("switch")
assert len(switch_entity_ids) > 0, "No switch entities found"
# Test turn_on method
with patch(
"homeassistant.components.vegehub.VegeHub.set_actuator"
) as mock_set_actuator:
await hass.services.async_call(
"switch", "turn_on", {"entity_id": switch_entity_ids[0]}, blocking=True
)
mock_set_actuator.assert_called_once_with(
1, 0, 600
) # on, index 0, duration 600
# Test turn_off method
with patch(
"homeassistant.components.vegehub.VegeHub.set_actuator"
) as mock_set_actuator:
await hass.services.async_call(
"switch", "turn_off", {"entity_id": switch_entity_ids[0]}, blocking=True
)
mock_set_actuator.assert_called_once_with(
0, 0, 600
) # off, index 0, duration 600
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/vegehub/test_switch.py",
"license": "Apache License 2.0",
"lines": 87,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/roomba/test_sensor.py | """Tests for IRobotEntity usage in Roomba sensor platform."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_roomba: AsyncMock,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test roomba entities."""
with patch("homeassistant.components.roomba.PLATFORMS", [Platform.SENSOR]):
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/roomba/test_sensor.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/snoo/test_button.py | """Test Snoo Buttons."""
from unittest.mock import AsyncMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import async_init_integration
from tests.common import snapshot_platform
async def test_entities(
hass: HomeAssistant,
bypass_api: AsyncMock,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test buttons."""
with patch("homeassistant.components.snoo.PLATFORMS", [Platform.BUTTON]):
entry = await async_init_integration(hass)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
async def test_button_starts_snoo(hass: HomeAssistant, bypass_api: AsyncMock) -> None:
"""Test start_snoo button works correctly."""
await async_init_integration(hass)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.test_snoo_start"},
blocking=True,
)
assert bypass_api.start_snoo.assert_called_once
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/snoo/test_button.py",
"license": "Apache License 2.0",
"lines": 29,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/util/test_async_iterator.py | """Tests for async iterator utility functions."""
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.util.async_iterator import (
Abort,
AsyncIteratorReader,
AsyncIteratorWriter,
)
def _read_all(reader: AsyncIteratorReader) -> bytes:
output = b""
while chunk := reader.read(500):
output += chunk
return output
async def test_async_iterator_reader(hass: HomeAssistant) -> None:
"""Test the async iterator reader."""
data = b"hello world" * 1000
async def async_gen() -> AsyncIterator[bytes]:
for _ in range(10):
yield data
reader = AsyncIteratorReader(hass.loop, async_gen())
assert await hass.async_add_executor_job(_read_all, reader) == data * 10
async def test_async_iterator_reader_abort_early(hass: HomeAssistant) -> None:
"""Test abort the async iterator reader."""
evt = asyncio.Event()
async def async_gen() -> AsyncIterator[bytes]:
await evt.wait()
yield b""
reader = AsyncIteratorReader(hass.loop, async_gen())
reader.abort()
fut = hass.async_add_executor_job(_read_all, reader)
with pytest.raises(Abort):
await fut
async def test_async_iterator_reader_abort_late(hass: HomeAssistant) -> None:
"""Test abort the async iterator reader."""
evt = asyncio.Event()
async def async_gen() -> AsyncIterator[bytes]:
await evt.wait()
yield b""
reader = AsyncIteratorReader(hass.loop, async_gen())
fut = hass.async_add_executor_job(_read_all, reader)
await asyncio.sleep(0.1)
reader.abort()
with pytest.raises(Abort):
await fut
def _write_all(writer: AsyncIteratorWriter, data: list[bytes]) -> bytes:
for chunk in data:
assert writer.write(chunk) == len(chunk)
assert writer.write(b"") == 0
async def test_async_iterator_writer(hass: HomeAssistant) -> None:
"""Test the async iterator writer."""
chunk = b"hello world" * 1000
chunks = [chunk] * 10
writer = AsyncIteratorWriter(hass.loop)
fut = hass.async_add_executor_job(_write_all, writer, chunks)
read = b""
async for data in writer:
read += data
await fut
assert read == chunk * 10
assert writer.tell() == len(read)
async def test_async_iterator_writer_abort_early(hass: HomeAssistant) -> None:
"""Test the async iterator writer."""
chunk = b"hello world" * 1000
chunks = [chunk] * 10
writer = AsyncIteratorWriter(hass.loop)
writer.abort()
fut = hass.async_add_executor_job(_write_all, writer, chunks)
with pytest.raises(Abort):
await fut
async def test_async_iterator_writer_abort_late(hass: HomeAssistant) -> None:
"""Test the async iterator writer."""
chunk = b"hello world" * 1000
chunks = [chunk] * 10
writer = AsyncIteratorWriter(hass.loop)
fut = hass.async_add_executor_job(_write_all, writer, chunks)
await asyncio.sleep(0.1)
writer.abort()
with pytest.raises(Abort):
await fut
async def test_async_iterator_reader_exhausted(hass: HomeAssistant) -> None:
"""Test that read() returns empty bytes after stream exhaustion."""
async def async_gen() -> AsyncIterator[bytes]:
yield b"hello"
reader = AsyncIteratorReader(hass.loop, async_gen())
def _read_then_read_again() -> bytes:
data = _read_all(reader)
# Second read after exhaustion should return b"" immediately
assert reader.read(500) == b""
return data
assert await hass.async_add_executor_job(_read_then_read_again) == b"hello"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/util/test_async_iterator.py",
"license": "Apache License 2.0",
"lines": 93,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/velux/test_cover.py | """Tests for the Velux cover platform."""
from unittest.mock import AsyncMock
import pytest
from pyvlx.exception import PyVLXException
from pyvlx.opening_device import (
Awning,
DualRollerShutter,
GarageDoor,
Gate,
RollerShutter,
Window,
)
from homeassistant.components.cover import (
ATTR_POSITION,
ATTR_TILT_POSITION,
DOMAIN as COVER_DOMAIN,
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,
SERVICE_STOP_COVER_TILT,
)
from homeassistant.components.velux import DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_CLOSED,
STATE_CLOSING,
STATE_OPEN,
STATE_OPENING,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import update_callback_entity
from tests.common import MockConfigEntry, SnapshotAssertion, snapshot_platform
# Apply setup_integration fixture to all tests in this module
pytestmark = pytest.mark.usefixtures("setup_integration")
@pytest.fixture
def platform() -> Platform:
"""Fixture to specify platform to test."""
return Platform.COVER
@pytest.mark.parametrize("mock_pyvlx", ["mock_blind"], indirect=True)
async def test_blind_entity_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot the entity and validate registry metadata."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
@pytest.mark.usefixtures("mock_cover_type")
@pytest.mark.parametrize(
"mock_cover_type",
[Awning, DualRollerShutter, GarageDoor, Gate, RollerShutter, Window],
indirect=True,
)
@pytest.mark.parametrize(
"mock_pyvlx",
["mock_cover_type"],
indirect=True,
)
async def test_cover_entity_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot the entity and validate entity metadata."""
await snapshot_platform(
hass,
entity_registry,
snapshot,
mock_config_entry.entry_id,
)
async def test_cover_device_association(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test the cover entity device association."""
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert len(entity_entries) >= 1
for entry in entity_entries:
assert entry.device_id is not None
device_entry = device_registry.async_get(entry.device_id)
assert device_entry is not None
# For dual roller shutters, the unique_id is suffixed with "_upper" or "_lower",
# so remove that suffix to get the domain_id for device registry lookup
domain_id = entry.unique_id
if entry.unique_id.endswith("_upper") or entry.unique_id.endswith("_lower"):
domain_id = entry.unique_id.rsplit("_", 1)[0]
assert (DOMAIN, domain_id) in device_entry.identifiers
assert device_entry.via_device_id is not None
via_device_entry = device_registry.async_get(device_entry.via_device_id)
assert via_device_entry is not None
assert (
DOMAIN,
f"gateway_{mock_config_entry.entry_id}",
) in via_device_entry.identifiers
async def test_cover_closed(
hass: HomeAssistant,
mock_window: AsyncMock,
) -> None:
"""Test the cover closed state."""
test_entity_id = "cover.test_window"
# Initial state should be open
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_OPEN
# Update mock window position to closed percentage
mock_window.position.position_percent = 100
# Also directly set position to closed, so this test should
# continue to be green after the lib is fixed
mock_window.position.closed = True
# Trigger entity state update via registered callback
await update_callback_entity(hass, mock_window)
state = hass.states.get(test_entity_id)
assert state is not None
assert state.state == STATE_CLOSED
# Window command tests
async def test_window_open_close_stop_services(
hass: HomeAssistant, mock_window: AsyncMock
) -> None:
"""Verify open/close/stop services map to device calls with no wait."""
entity_id = "cover.test_window"
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {"entity_id": entity_id}, blocking=True
)
mock_window.open.assert_awaited_once_with(wait_for_completion=False)
await hass.services.async_call(
COVER_DOMAIN, SERVICE_CLOSE_COVER, {"entity_id": entity_id}, blocking=True
)
mock_window.close.assert_awaited_once_with(wait_for_completion=False)
await hass.services.async_call(
COVER_DOMAIN, SERVICE_STOP_COVER, {"entity_id": entity_id}, blocking=True
)
mock_window.stop.assert_awaited_once_with(wait_for_completion=False)
async def test_window_set_cover_position_inversion(
hass: HomeAssistant, mock_window: AsyncMock
) -> None:
"""HA position is inverted for device's Position."""
entity_id = "cover.test_window"
# Call with position 30 (=70% for device)
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_POSITION,
{"entity_id": entity_id, ATTR_POSITION: 30},
blocking=True,
)
# Expect device Position 70%
args, kwargs = mock_window.set_position.await_args
position_obj = args[0]
assert position_obj.position_percent == 70
assert kwargs.get("wait_for_completion") is False
async def test_window_current_position_and_opening_closing_states(
hass: HomeAssistant, mock_window: AsyncMock
) -> None:
"""Validate current_position and opening/closing state transitions."""
entity_id = "cover.test_window"
# device position 30 -> current_position 70
mock_window.position.position_percent = 30
await update_callback_entity(hass, mock_window)
state = hass.states.get(entity_id)
assert state is not None
assert state.attributes.get("current_position") == 70
assert state.state == STATE_OPEN
# Opening
mock_window.is_opening = True
mock_window.is_closing = False
await update_callback_entity(hass, mock_window)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_OPENING
# Closing
mock_window.is_opening = False
mock_window.is_closing = True
await update_callback_entity(hass, mock_window)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_CLOSING
# Dual roller shutter command tests
async def test_dual_roller_shutter_open_close_services(
hass: HomeAssistant, mock_dual_roller_shutter: AsyncMock
) -> None:
"""Verify open/close services map to device calls with correct part."""
dual_entity_id = "cover.test_dual_roller_shutter"
upper_entity_id = "cover.test_dual_roller_shutter_upper_shutter"
lower_entity_id = "cover.test_dual_roller_shutter_lower_shutter"
# Open upper part
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {"entity_id": upper_entity_id}, blocking=True
)
mock_dual_roller_shutter.open.assert_awaited_with(
curtain="upper", wait_for_completion=False
)
# Open lower part
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {"entity_id": lower_entity_id}, blocking=True
)
mock_dual_roller_shutter.open.assert_awaited_with(
curtain="lower", wait_for_completion=False
)
# Open dual
await hass.services.async_call(
COVER_DOMAIN, SERVICE_OPEN_COVER, {"entity_id": dual_entity_id}, blocking=True
)
mock_dual_roller_shutter.open.assert_awaited_with(
curtain="dual", wait_for_completion=False
)
# Close upper part
await hass.services.async_call(
COVER_DOMAIN, SERVICE_CLOSE_COVER, {"entity_id": upper_entity_id}, blocking=True
)
mock_dual_roller_shutter.close.assert_awaited_with(
curtain="upper", wait_for_completion=False
)
# Close lower part
await hass.services.async_call(
COVER_DOMAIN, SERVICE_CLOSE_COVER, {"entity_id": lower_entity_id}, blocking=True
)
mock_dual_roller_shutter.close.assert_awaited_with(
curtain="lower", wait_for_completion=False
)
# Close dual
await hass.services.async_call(
COVER_DOMAIN, SERVICE_CLOSE_COVER, {"entity_id": dual_entity_id}, blocking=True
)
mock_dual_roller_shutter.close.assert_awaited_with(
curtain="dual", wait_for_completion=False
)
async def test_dual_shutter_set_cover_position_inversion(
hass: HomeAssistant, mock_dual_roller_shutter: AsyncMock
) -> None:
"""HA position is inverted for device's Position."""
entity_id = "cover.test_dual_roller_shutter"
# Call with position 30 (=70% for device)
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_POSITION,
{"entity_id": entity_id, ATTR_POSITION: 30},
blocking=True,
)
# Expect device Position 70%
args, kwargs = mock_dual_roller_shutter.set_position.await_args
position_obj = args[0]
assert position_obj.position_percent == 70
assert kwargs.get("wait_for_completion") is False
assert kwargs.get("curtain") == "dual"
entity_id = "cover.test_dual_roller_shutter_upper_shutter"
# Call with position 30 (=70% for device)
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_POSITION,
{"entity_id": entity_id, ATTR_POSITION: 30},
blocking=True,
)
# Expect device Position 70%
args, kwargs = mock_dual_roller_shutter.set_position.await_args
position_obj = args[0]
assert position_obj.position_percent == 70
assert kwargs.get("wait_for_completion") is False
assert kwargs.get("curtain") == "upper"
entity_id = "cover.test_dual_roller_shutter_lower_shutter"
# Call with position 30 (=70% for device)
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_POSITION,
{"entity_id": entity_id, ATTR_POSITION: 30},
blocking=True,
)
# Expect device Position 70%
args, kwargs = mock_dual_roller_shutter.set_position.await_args
position_obj = args[0]
assert position_obj.position_percent == 70
assert kwargs.get("wait_for_completion") is False
assert kwargs.get("curtain") == "lower"
async def test_dual_roller_shutter_position_tests(
hass: HomeAssistant, mock_dual_roller_shutter: AsyncMock
) -> None:
"""Validate current_position and open/closed state."""
entity_id_dual = "cover.test_dual_roller_shutter"
entity_id_lower = "cover.test_dual_roller_shutter_lower_shutter"
entity_id_upper = "cover.test_dual_roller_shutter_upper_shutter"
# device position is inverted (100 - x)
mock_dual_roller_shutter.position.position_percent = 29
mock_dual_roller_shutter.position_upper_curtain.position_percent = 28
mock_dual_roller_shutter.position_lower_curtain.position_percent = 27
await update_callback_entity(hass, mock_dual_roller_shutter)
state = hass.states.get(entity_id_dual)
assert state is not None
assert state.attributes.get("current_position") == 71
assert state.state == STATE_OPEN
state = hass.states.get(entity_id_upper)
assert state is not None
assert state.attributes.get("current_position") == 72
assert state.state == STATE_OPEN
state = hass.states.get(entity_id_lower)
assert state is not None
assert state.attributes.get("current_position") == 73
assert state.state == STATE_OPEN
mock_dual_roller_shutter.position.closed = True
mock_dual_roller_shutter.position_upper_curtain.closed = True
mock_dual_roller_shutter.position_lower_curtain.closed = True
await update_callback_entity(hass, mock_dual_roller_shutter)
state = hass.states.get(entity_id_dual)
assert state is not None
assert state.state == STATE_CLOSED
state = hass.states.get(entity_id_upper)
assert state is not None
assert state.state == STATE_CLOSED
state = hass.states.get(entity_id_lower)
assert state is not None
assert state.state == STATE_CLOSED
# Blind command tests
async def test_blind_open_close_stop_tilt_services(
hass: HomeAssistant, mock_blind: AsyncMock
) -> None:
"""Verify tilt services map to orientation calls."""
entity_id = "cover.test_blind"
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_OPEN_COVER_TILT,
{"entity_id": entity_id},
blocking=True,
)
mock_blind.open_orientation.assert_awaited_once_with(wait_for_completion=False)
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER_TILT,
{"entity_id": entity_id},
blocking=True,
)
mock_blind.close_orientation.assert_awaited_once_with(wait_for_completion=False)
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_STOP_COVER_TILT,
{"entity_id": entity_id},
blocking=True,
)
mock_blind.stop_orientation.assert_awaited_once_with(wait_for_completion=False)
async def test_blind_set_cover_tilt_position_inversion(
hass: HomeAssistant, mock_blind: AsyncMock
) -> None:
"""HA tilt position is inverted for device orientation."""
entity_id = "cover.test_blind"
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_SET_COVER_TILT_POSITION,
{"entity_id": entity_id, ATTR_TILT_POSITION: 25},
blocking=True,
)
call = mock_blind.set_orientation.await_args
orientation_obj = call.kwargs.get("orientation")
assert orientation_obj is not None
assert orientation_obj.position_percent == 75
assert call.kwargs.get("wait_for_completion") is False
async def test_blind_current_tilt_position(
hass: HomeAssistant, mock_blind: AsyncMock
) -> None:
"""Validate current_tilt_position attribute reflects inverted orientation."""
entity_id = "cover.test_blind"
mock_blind.orientation.position_percent = 10
await update_callback_entity(hass, mock_blind)
state = hass.states.get(entity_id)
assert state is not None
assert state.attributes.get("current_tilt_position") == 90
async def test_non_blind_has_no_tilt_position(
hass: HomeAssistant, mock_window: AsyncMock
) -> None:
"""Non-blind covers should not expose current_tilt_position attribute."""
entity_id = "cover.test_window"
await update_callback_entity(hass, mock_window)
state = hass.states.get(entity_id)
assert state is not None
assert "current_tilt_position" not in state.attributes
# Exception handling tests
@pytest.mark.parametrize(
"exception",
[PyVLXException("PyVLX error"), OSError("OS error")],
)
async def test_cover_command_exception_handling(
hass: HomeAssistant,
mock_window: AsyncMock,
exception: Exception,
) -> None:
"""Test that exceptions from node commands are wrapped in HomeAssistantError."""
entity_id = "cover.test_window"
# Make the close method raise an exception
mock_window.close.side_effect = exception
with pytest.raises(
HomeAssistantError,
match="Failed to communicate with Velux device",
):
await hass.services.async_call(
COVER_DOMAIN,
SERVICE_CLOSE_COVER,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/velux/test_cover.py",
"license": "Apache License 2.0",
"lines": 411,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/ai_task/media_source.py | """Expose images as media sources."""
from __future__ import annotations
from pathlib import Path
from homeassistant.components.media_source import MediaSource, local_source
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from .const import DATA_MEDIA_SOURCE, DOMAIN, IMAGE_DIR
async def async_get_media_source(hass: HomeAssistant) -> MediaSource:
"""Set up local media source."""
media_dirs = list(hass.config.media_dirs.values())
if not media_dirs:
raise HomeAssistantError(
"AI Task media source requires at least one media directory configured"
)
media_dir = Path(media_dirs[0]) / DOMAIN / IMAGE_DIR
hass.data[DATA_MEDIA_SOURCE] = source = local_source.LocalSource(
hass,
DOMAIN,
"AI Generated Images",
{IMAGE_DIR: str(media_dir)},
f"/{DOMAIN}",
)
return source
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ai_task/media_source.py",
"license": "Apache License 2.0",
"lines": 23,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/airos/binary_sensor.py | """AirOS Binary Sensor component for Home Assistant."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from typing import Generic, TypeVar
from airos.data import AirOSDataBaseClass
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 .coordinator import AirOS8Data, AirOSConfigEntry, AirOSDataUpdateCoordinator
from .entity import AirOSEntity
PARALLEL_UPDATES = 0
AirOSDataModel = TypeVar("AirOSDataModel", bound=AirOSDataBaseClass)
@dataclass(frozen=True, kw_only=True)
class AirOSBinarySensorEntityDescription(
BinarySensorEntityDescription,
Generic[AirOSDataModel],
):
"""Describe an AirOS binary sensor."""
value_fn: Callable[[AirOSDataModel], bool]
AirOS8BinarySensorEntityDescription = AirOSBinarySensorEntityDescription[AirOS8Data]
COMMON_BINARY_SENSORS: tuple[AirOSBinarySensorEntityDescription, ...] = (
AirOSBinarySensorEntityDescription(
key="dhcp_client",
translation_key="dhcp_client",
device_class=BinarySensorDeviceClass.RUNNING,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda data: data.services.dhcpc,
),
AirOSBinarySensorEntityDescription(
key="dhcp_server",
translation_key="dhcp_server",
device_class=BinarySensorDeviceClass.RUNNING,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda data: data.services.dhcpd,
entity_registry_enabled_default=False,
),
AirOSBinarySensorEntityDescription(
key="pppoe",
translation_key="pppoe",
device_class=BinarySensorDeviceClass.CONNECTIVITY,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda data: data.services.pppoe,
entity_registry_enabled_default=False,
),
)
AIROS8_BINARY_SENSORS: tuple[AirOS8BinarySensorEntityDescription, ...] = (
AirOS8BinarySensorEntityDescription(
key="portfw",
translation_key="port_forwarding",
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda data: data.portfw,
),
AirOS8BinarySensorEntityDescription(
key="dhcp6_server",
translation_key="dhcp6_server",
device_class=BinarySensorDeviceClass.RUNNING,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda data: data.services.dhcp6d_stateful,
entity_registry_enabled_default=False,
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: AirOSConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the AirOS binary sensors from a config entry."""
coordinator = config_entry.runtime_data
entities = [
AirOSBinarySensor(coordinator, description)
for description in COMMON_BINARY_SENSORS
]
if coordinator.device_data["fw_major"] == 8:
entities.extend(
AirOSBinarySensor(coordinator, description)
for description in AIROS8_BINARY_SENSORS
)
async_add_entities(entities)
class AirOSBinarySensor(AirOSEntity, BinarySensorEntity):
"""Representation of a binary sensor."""
entity_description: AirOSBinarySensorEntityDescription
def __init__(
self,
coordinator: AirOSDataUpdateCoordinator,
description: AirOSBinarySensorEntityDescription,
) -> None:
"""Initialize the binary sensor."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.data.derived.mac}_{description.key}"
@property
def is_on(self) -> bool:
"""Return the state of the binary sensor."""
return self.entity_description.value_fn(self.coordinator.data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/airos/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 100,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/airq/number.py | """Definition of air-Q number platform used to control the LED strips."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
import logging
from aioairq.core import AirQ
from homeassistant.components.number import NumberEntity, NumberEntityDescription
from homeassistant.const import PERCENTAGE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import AirQConfigEntry, AirQCoordinator
_LOGGER = logging.getLogger(__name__)
@dataclass(frozen=True, kw_only=True)
class AirQBrightnessDescription(NumberEntityDescription):
"""Describes AirQ number entity responsible for brightness control."""
value: Callable[[dict], float]
set_value: Callable[[AirQ, float], Awaitable[None]]
AIRQ_LED_BRIGHTNESS = AirQBrightnessDescription(
key="airq_led_brightness",
translation_key="airq_led_brightness",
native_min_value=0.0,
native_max_value=100.0,
native_step=1.0,
native_unit_of_measurement=PERCENTAGE,
value=lambda data: data["brightness"],
set_value=lambda device, value: device.set_current_brightness(value),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: AirQConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up number entities: a single entity for the LEDs."""
coordinator = entry.runtime_data
entities = [AirQLEDBrightness(coordinator, AIRQ_LED_BRIGHTNESS)]
async_add_entities(entities)
class AirQLEDBrightness(CoordinatorEntity[AirQCoordinator], NumberEntity):
"""Representation of the LEDs from a single AirQ."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: AirQCoordinator,
description: AirQBrightnessDescription,
) -> None:
"""Initialize a single sensor."""
super().__init__(coordinator)
self.entity_description: AirQBrightnessDescription = description
self._attr_device_info = coordinator.device_info
self._attr_unique_id = f"{coordinator.device_id}_{description.key}"
@property
def native_value(self) -> float:
"""Return the brightness of the LEDs in %."""
return self.entity_description.value(self.coordinator.data)
async def async_set_native_value(self, value: float) -> None:
"""Set the brightness of the LEDs to the value in %."""
_LOGGER.debug(
"Changing LED brighntess from %.0f%% to %.0f%%",
self.coordinator.data["brightness"],
value,
)
await self.entity_description.set_value(self.coordinator.airq, value)
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/airq/number.py",
"license": "Apache License 2.0",
"lines": 63,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/apcupsd/entity.py | """Base entity for APCUPSd integration."""
from __future__ import annotations
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .coordinator import APCUPSdCoordinator
class APCUPSdEntity(CoordinatorEntity[APCUPSdCoordinator]):
"""Base entity for APCUPSd integration."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: APCUPSdCoordinator,
description: EntityDescription,
) -> None:
"""Initialize the APCUPSd entity."""
super().__init__(coordinator, context=description.key.upper())
self.entity_description = description
self._attr_unique_id = f"{coordinator.unique_device_id}_{description.key}"
self._attr_device_info = coordinator.device_info
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/apcupsd/entity.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/asuswrt/helpers.py | """Helpers for AsusWRT integration."""
from __future__ import annotations
from typing import Any
TRANSLATION_MAP = {
"wan_rx": "sensor_rx_bytes",
"wan_tx": "sensor_tx_bytes",
"total_usage": "cpu_total_usage",
"usage": "mem_usage_perc",
"free": "mem_free",
"used": "mem_used",
"wan_rx_speed": "sensor_rx_rates",
"wan_tx_speed": "sensor_tx_rates",
"2ghz": "2.4GHz",
"5ghz": "5.0GHz",
"5ghz2": "5.0GHz_2",
"6ghz": "6.0GHz",
"cpu": "CPU",
"datetime": "sensor_last_boot",
"uptime": "sensor_uptime",
**{f"{num}_usage": f"cpu{num}_usage" for num in range(1, 9)},
**{f"load_avg_{load}": f"sensor_load_avg{load}" for load in ("1", "5", "15")},
}
def clean_dict(raw: dict[str, Any]) -> dict[str, Any]:
"""Cleans dictionary from None values.
The `state` key is always preserved regardless of its value.
"""
return {k: v for k, v in raw.items() if v is not None or k.endswith("state")}
def translate_to_legacy[T: (dict[str, Any], list[Any], None)](raw: T) -> T:
"""Translate raw data to legacy format for dicts and lists."""
if raw is None:
return None
if isinstance(raw, dict):
return {TRANSLATION_MAP.get(k, k): v for k, v in raw.items()}
if isinstance(raw, list):
return [
TRANSLATION_MAP[item]
if isinstance(item, str) and item in TRANSLATION_MAP
else item
for item in raw
]
return raw
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/asuswrt/helpers.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/august/application_credentials.py | """application_credentials platform for the august integration."""
from homeassistant.components.application_credentials import AuthorizationServer
from homeassistant.core import HomeAssistant
OAUTH2_AUTHORIZE = "https://auth.august.com/authorization"
OAUTH2_TOKEN = "https://auth.august.com/access_token"
async def async_get_authorization_server(hass: HomeAssistant) -> AuthorizationServer:
"""Return authorization server."""
return AuthorizationServer(
authorize_url=OAUTH2_AUTHORIZE,
token_url=OAUTH2_TOKEN,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/august/application_credentials.py",
"license": "Apache License 2.0",
"lines": 11,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/bayesian/config_flow.py | """Config flow for the Bayesian integration."""
from collections.abc import Mapping
from enum import StrEnum
import logging
from typing import Any
import voluptuous as vol
from homeassistant.components.alarm_control_panel import DOMAIN as ALARM_DOMAIN
from homeassistant.components.binary_sensor import (
DOMAIN as BINARY_SENSOR_DOMAIN,
BinarySensorDeviceClass,
)
from homeassistant.components.calendar import DOMAIN as CALENDAR_DOMAIN
from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN
from homeassistant.components.cover import DOMAIN as COVER_DOMAIN
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN
from homeassistant.components.input_boolean import DOMAIN as INPUT_BOOLEAN_DOMAIN
from homeassistant.components.input_number import DOMAIN as INPUT_NUMBER_DOMAIN
from homeassistant.components.input_text import DOMAIN as INPUT_TEXT_DOMAIN
from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN
from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN
from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN
from homeassistant.components.number import DOMAIN as NUMBER_DOMAIN
from homeassistant.components.person import DOMAIN as PERSON_DOMAIN
from homeassistant.components.select import DOMAIN as SELECT_DOMAIN
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.sun import DOMAIN as SUN_DOMAIN
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.components.todo import DOMAIN as TODO_DOMAIN
from homeassistant.components.update import DOMAIN as UPDATE_DOMAIN
from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN
from homeassistant.components.zone import DOMAIN as ZONE_DOMAIN
from homeassistant.config_entries import (
ConfigEntry,
ConfigFlowResult,
ConfigSubentry,
ConfigSubentryData,
ConfigSubentryFlow,
SubentryFlowResult,
)
from homeassistant.const import (
CONF_ABOVE,
CONF_BELOW,
CONF_DEVICE_CLASS,
CONF_ENTITY_ID,
CONF_NAME,
CONF_PLATFORM,
CONF_STATE,
CONF_VALUE_TEMPLATE,
)
from homeassistant.core import callback
from homeassistant.helpers import selector, translation
from homeassistant.helpers.schema_config_entry_flow import (
SchemaCommonFlowHandler,
SchemaConfigFlowHandler,
SchemaFlowError,
SchemaFlowFormStep,
SchemaFlowMenuStep,
)
from .binary_sensor import above_greater_than_below, no_overlapping
from .const import (
CONF_OBSERVATIONS,
CONF_P_GIVEN_F,
CONF_P_GIVEN_T,
CONF_PRIOR,
CONF_PROBABILITY_THRESHOLD,
CONF_TEMPLATE,
CONF_TO_STATE,
DEFAULT_NAME,
DEFAULT_PROBABILITY_THRESHOLD,
DOMAIN,
)
_LOGGER = logging.getLogger(__name__)
USER = "user"
OBSERVATION_SELECTOR = "observation_selector"
ALLOWED_STATE_DOMAINS = [
ALARM_DOMAIN,
BINARY_SENSOR_DOMAIN,
CALENDAR_DOMAIN,
CLIMATE_DOMAIN,
COVER_DOMAIN,
DEVICE_TRACKER_DOMAIN,
INPUT_BOOLEAN_DOMAIN,
INPUT_NUMBER_DOMAIN,
INPUT_TEXT_DOMAIN,
LIGHT_DOMAIN,
MEDIA_PLAYER_DOMAIN,
NOTIFY_DOMAIN,
NUMBER_DOMAIN,
PERSON_DOMAIN,
"schedule", # Avoids an import that would introduce a dependency.
SELECT_DOMAIN,
SENSOR_DOMAIN,
SUN_DOMAIN,
SWITCH_DOMAIN,
TODO_DOMAIN,
UPDATE_DOMAIN,
WEATHER_DOMAIN,
]
ALLOWED_NUMERIC_DOMAINS = [
SENSOR_DOMAIN,
INPUT_NUMBER_DOMAIN,
NUMBER_DOMAIN,
TODO_DOMAIN,
ZONE_DOMAIN,
]
class ObservationTypes(StrEnum):
"""StrEnum for all the different observation types."""
STATE = CONF_STATE
NUMERIC_STATE = "numeric_state"
TEMPLATE = CONF_TEMPLATE
class OptionsFlowSteps(StrEnum):
"""StrEnum for all the different options flow steps."""
INIT = "init"
ADD_OBSERVATION = OBSERVATION_SELECTOR
OPTIONS_SCHEMA = vol.Schema(
{
vol.Required(
CONF_PROBABILITY_THRESHOLD, default=DEFAULT_PROBABILITY_THRESHOLD * 100
): vol.All(
selector.NumberSelector(
selector.NumberSelectorConfig(
mode=selector.NumberSelectorMode.SLIDER,
step=1.0,
min=0,
max=100,
unit_of_measurement="%",
),
),
vol.Range(
min=0,
max=100,
min_included=False,
max_included=False,
msg="extreme_threshold_error",
),
),
vol.Required(CONF_PRIOR, default=DEFAULT_PROBABILITY_THRESHOLD * 100): vol.All(
selector.NumberSelector(
selector.NumberSelectorConfig(
mode=selector.NumberSelectorMode.SLIDER,
step=1.0,
min=0,
max=100,
unit_of_measurement="%",
),
),
vol.Range(
min=0,
max=100,
min_included=False,
max_included=False,
msg="extreme_prior_error",
),
),
vol.Optional(CONF_DEVICE_CLASS): selector.SelectSelector(
selector.SelectSelectorConfig(
options=[cls.value for cls in BinarySensorDeviceClass],
mode=selector.SelectSelectorMode.DROPDOWN,
translation_key="binary_sensor_device_class",
sort=True,
),
),
}
)
CONFIG_SCHEMA = vol.Schema(
{
vol.Required(CONF_NAME, default=DEFAULT_NAME): selector.TextSelector(),
}
).extend(OPTIONS_SCHEMA.schema)
OBSERVATION_BOILERPLATE = vol.Schema(
{
vol.Required(CONF_P_GIVEN_T): vol.All(
selector.NumberSelector(
selector.NumberSelectorConfig(
mode=selector.NumberSelectorMode.SLIDER,
step=1.0,
min=0,
max=100,
unit_of_measurement="%",
),
),
vol.Range(
min=0,
max=100,
min_included=False,
max_included=False,
msg="extreme_prob_given_error",
),
),
vol.Required(CONF_P_GIVEN_F): vol.All(
selector.NumberSelector(
selector.NumberSelectorConfig(
mode=selector.NumberSelectorMode.SLIDER,
step=1.0,
min=0,
max=100,
unit_of_measurement="%",
),
),
vol.Range(
min=0,
max=100,
min_included=False,
max_included=False,
msg="extreme_prob_given_error",
),
),
vol.Required(CONF_NAME): selector.TextSelector(),
}
)
STATE_SUBSCHEMA = vol.Schema(
{
vol.Required(CONF_ENTITY_ID): selector.EntitySelector(
selector.EntitySelectorConfig(domain=ALLOWED_STATE_DOMAINS)
),
vol.Required(CONF_TO_STATE): selector.TextSelector(
selector.TextSelectorConfig(
multiline=False, type=selector.TextSelectorType.TEXT, multiple=False
) # ideally this would be a state selector context-linked to the above entity.
),
},
).extend(OBSERVATION_BOILERPLATE.schema)
NUMERIC_STATE_SUBSCHEMA = vol.Schema(
{
vol.Required(CONF_ENTITY_ID): selector.EntitySelector(
selector.EntitySelectorConfig(domain=ALLOWED_NUMERIC_DOMAINS)
),
vol.Optional(CONF_ABOVE): selector.NumberSelector(
selector.NumberSelectorConfig(
mode=selector.NumberSelectorMode.BOX, step="any"
),
),
vol.Optional(CONF_BELOW): selector.NumberSelector(
selector.NumberSelectorConfig(
mode=selector.NumberSelectorMode.BOX, step="any"
),
),
},
).extend(OBSERVATION_BOILERPLATE.schema)
TEMPLATE_SUBSCHEMA = vol.Schema(
{
vol.Required(CONF_VALUE_TEMPLATE): selector.TemplateSelector(
selector.TemplateSelectorConfig(),
),
},
).extend(OBSERVATION_BOILERPLATE.schema)
def _convert_percentages_to_fractions(
data: dict[str, str | float | int],
) -> dict[str, str | float]:
"""Convert percentage probability values in a dictionary to fractions for storing in the config entry."""
probabilities = [
CONF_P_GIVEN_T,
CONF_P_GIVEN_F,
CONF_PRIOR,
CONF_PROBABILITY_THRESHOLD,
]
return {
key: (
value / 100
if isinstance(value, (int, float)) and key in probabilities
else value
)
for key, value in data.items()
}
def _convert_fractions_to_percentages(
data: dict[str, str | float],
) -> dict[str, str | float]:
"""Convert fraction probability values in a dictionary to percentages for loading into the UI."""
probabilities = [
CONF_P_GIVEN_T,
CONF_P_GIVEN_F,
CONF_PRIOR,
CONF_PROBABILITY_THRESHOLD,
]
return {
key: (
value * 100
if isinstance(value, (int, float)) and key in probabilities
else value
)
for key, value in data.items()
}
def _select_observation_schema(
obs_type: ObservationTypes,
) -> vol.Schema:
"""Return the schema for editing the correct observation (SubEntry) type."""
if obs_type == str(ObservationTypes.STATE):
return STATE_SUBSCHEMA
if obs_type == str(ObservationTypes.NUMERIC_STATE):
return NUMERIC_STATE_SUBSCHEMA
return TEMPLATE_SUBSCHEMA
async def _get_base_suggested_values(
handler: SchemaCommonFlowHandler,
) -> dict[str, Any]:
"""Return suggested values for the base sensor options."""
return _convert_fractions_to_percentages(dict(handler.options))
def _get_observation_values_for_editing(
subentry: ConfigSubentry,
) -> dict[str, Any]:
"""Return the values for editing in the observation subentry."""
return _convert_fractions_to_percentages(dict(subentry.data))
async def _validate_user(
handler: SchemaCommonFlowHandler, user_input: dict[str, Any]
) -> dict[str, Any]:
"""Modify user input to convert to fractions for storage. Validation is done entirely by the schemas."""
user_input = _convert_percentages_to_fractions(user_input)
return {**user_input}
def _validate_observation_subentry(
obs_type: ObservationTypes,
user_input: dict[str, Any],
other_subentries: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""Validate an observation input and manually update options with observations as they are nested items."""
if user_input[CONF_P_GIVEN_T] == user_input[CONF_P_GIVEN_F]:
raise SchemaFlowError("equal_probabilities")
user_input = _convert_percentages_to_fractions(user_input)
# Save the observation type in the user input as it is needed in binary_sensor.py
user_input[CONF_PLATFORM] = str(obs_type)
# Additional validation for multiple numeric state observations
if (
user_input[CONF_PLATFORM] == ObservationTypes.NUMERIC_STATE
and other_subentries is not None
):
_LOGGER.debug(
"Comparing with other subentries: %s", [*other_subentries, user_input]
)
try:
above_greater_than_below(user_input)
no_overlapping([*other_subentries, user_input])
except vol.Invalid as err:
raise SchemaFlowError(err) from err
_LOGGER.debug("Processed observation with settings: %s", user_input)
return user_input
async def _validate_subentry_from_config_entry(
handler: SchemaCommonFlowHandler, user_input: dict[str, Any]
) -> dict[str, Any]:
# Standard behavior is to merge the result with the options.
# In this case, we want to add a subentry so we update the options directly.
observations: list[dict[str, Any]] = handler.options.setdefault(
CONF_OBSERVATIONS, []
)
if handler.parent_handler.cur_step is not None:
user_input[CONF_PLATFORM] = handler.parent_handler.cur_step["step_id"]
user_input = _validate_observation_subentry(
user_input[CONF_PLATFORM],
user_input,
other_subentries=handler.options[CONF_OBSERVATIONS],
)
observations.append(user_input)
return {}
async def _get_description_placeholders(
handler: SchemaCommonFlowHandler,
) -> dict[str, str]:
# Current step is None when were are about to start the first step
if handler.parent_handler.cur_step is None:
return {"url": "https://www.home-assistant.io/integrations/bayesian/"}
return {
"parent_sensor_name": handler.options[CONF_NAME],
"device_class_on": translation.async_translate_state(
handler.parent_handler.hass,
"on",
BINARY_SENSOR_DOMAIN,
platform=None,
translation_key=None,
device_class=handler.options.get(CONF_DEVICE_CLASS, None),
),
"device_class_off": translation.async_translate_state(
handler.parent_handler.hass,
"off",
BINARY_SENSOR_DOMAIN,
platform=None,
translation_key=None,
device_class=handler.options.get(CONF_DEVICE_CLASS, None),
),
}
async def _get_observation_menu_options(handler: SchemaCommonFlowHandler) -> list[str]:
"""Return the menu options for the observation selector."""
options = [typ.value for typ in ObservationTypes]
if handler.options.get(CONF_OBSERVATIONS):
options.append("finish")
return options
CONFIG_FLOW: dict[str, SchemaFlowMenuStep | SchemaFlowFormStep] = {
str(USER): SchemaFlowFormStep(
CONFIG_SCHEMA,
validate_user_input=_validate_user,
next_step=str(OBSERVATION_SELECTOR),
description_placeholders=_get_description_placeholders,
),
str(OBSERVATION_SELECTOR): SchemaFlowMenuStep(
_get_observation_menu_options,
),
str(ObservationTypes.STATE): SchemaFlowFormStep(
STATE_SUBSCHEMA,
next_step=str(OBSERVATION_SELECTOR),
validate_user_input=_validate_subentry_from_config_entry,
# Prevent the name of the bayesian sensor from being used as the suggested
# name of the observations
suggested_values=None,
description_placeholders=_get_description_placeholders,
),
str(ObservationTypes.NUMERIC_STATE): SchemaFlowFormStep(
NUMERIC_STATE_SUBSCHEMA,
next_step=str(OBSERVATION_SELECTOR),
validate_user_input=_validate_subentry_from_config_entry,
suggested_values=None,
description_placeholders=_get_description_placeholders,
),
str(ObservationTypes.TEMPLATE): SchemaFlowFormStep(
TEMPLATE_SUBSCHEMA,
next_step=str(OBSERVATION_SELECTOR),
validate_user_input=_validate_subentry_from_config_entry,
suggested_values=None,
description_placeholders=_get_description_placeholders,
),
"finish": SchemaFlowFormStep(),
}
OPTIONS_FLOW: dict[str, SchemaFlowMenuStep | SchemaFlowFormStep] = {
str(OptionsFlowSteps.INIT): SchemaFlowFormStep(
OPTIONS_SCHEMA,
suggested_values=_get_base_suggested_values,
validate_user_input=_validate_user,
description_placeholders=_get_description_placeholders,
),
}
class BayesianConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN):
"""Bayesian config flow."""
VERSION = 1
MINOR_VERSION = 1
config_flow = CONFIG_FLOW
options_flow = OPTIONS_FLOW
@classmethod
@callback
def async_get_supported_subentry_types(
cls, config_entry: ConfigEntry
) -> dict[str, type[ConfigSubentryFlow]]:
"""Return subentries supported by this integration."""
return {"observation": ObservationSubentryFlowHandler}
def async_config_entry_title(self, options: Mapping[str, str]) -> str:
"""Return config entry title."""
name: str = options[CONF_NAME]
return name
@callback
def async_create_entry(
self,
data: Mapping[str, Any],
**kwargs: Any,
) -> ConfigFlowResult:
"""Finish config flow and create a config entry."""
data = dict(data)
observations = data.pop(CONF_OBSERVATIONS)
subentries: list[ConfigSubentryData] = [
ConfigSubentryData(
data=observation,
title=observation[CONF_NAME],
subentry_type="observation",
unique_id=None,
)
for observation in observations
]
self.async_config_flow_finished(data)
return super().async_create_entry(data=data, subentries=subentries, **kwargs)
class ObservationSubentryFlowHandler(ConfigSubentryFlow):
"""Handle subentry flow for adding and modifying a topic."""
async def step_common(
self,
user_input: dict[str, Any] | None,
obs_type: ObservationTypes,
reconfiguring: bool = False,
) -> SubentryFlowResult:
"""Use common logic within the named steps."""
errors: dict[str, str] = {}
other_subentries = None
if obs_type == str(ObservationTypes.NUMERIC_STATE):
other_subentries = [
dict(se.data) for se in self._get_entry().subentries.values()
]
# If we are reconfiguring a subentry we don't want to compare with self
if reconfiguring:
sub_entry = self._get_reconfigure_subentry()
if other_subentries is not None:
other_subentries.remove(dict(sub_entry.data))
if user_input is not None:
try:
user_input = _validate_observation_subentry(
obs_type,
user_input,
other_subentries=other_subentries,
)
if reconfiguring:
return self.async_update_and_abort(
self._get_entry(),
sub_entry,
title=user_input.get(CONF_NAME, sub_entry.data[CONF_NAME]),
data_updates=user_input,
)
return self.async_create_entry(
title=user_input.get(CONF_NAME),
data=user_input,
)
except SchemaFlowError as err:
errors["base"] = str(err)
return self.async_show_form(
step_id="reconfigure" if reconfiguring else str(obs_type),
data_schema=self.add_suggested_values_to_schema(
data_schema=_select_observation_schema(obs_type),
suggested_values=_get_observation_values_for_editing(sub_entry)
if reconfiguring
else None,
),
errors=errors,
description_placeholders={
"parent_sensor_name": self._get_entry().title,
"device_class_on": translation.async_translate_state(
self.hass,
"on",
BINARY_SENSOR_DOMAIN,
platform=None,
translation_key=None,
device_class=self._get_entry().options.get(CONF_DEVICE_CLASS, None),
),
"device_class_off": translation.async_translate_state(
self.hass,
"off",
BINARY_SENSOR_DOMAIN,
platform=None,
translation_key=None,
device_class=self._get_entry().options.get(CONF_DEVICE_CLASS, None),
),
},
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""User flow to add a new observation."""
return self.async_show_menu(
step_id="user",
menu_options=[typ.value for typ in ObservationTypes],
)
async def async_step_state(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""User flow to add a state observation. Function name must be in the format async_step_{observation_type}."""
return await self.step_common(
user_input=user_input, obs_type=ObservationTypes.STATE
)
async def async_step_numeric_state(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""User flow to add a new numeric state observation, (a numeric range). Function name must be in the format async_step_{observation_type}."""
return await self.step_common(
user_input=user_input, obs_type=ObservationTypes.NUMERIC_STATE
)
async def async_step_template(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""User flow to add a new template observation. Function name must be in the format async_step_{observation_type}."""
return await self.step_common(
user_input=user_input, obs_type=ObservationTypes.TEMPLATE
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""Enable the reconfigure button for observations. Function name must be async_step_reconfigure to be recognised by hass."""
sub_entry = self._get_reconfigure_subentry()
return await self.step_common(
user_input=user_input,
obs_type=ObservationTypes(sub_entry.data[CONF_PLATFORM]),
reconfiguring=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/bayesian/config_flow.py",
"license": "Apache License 2.0",
"lines": 569,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/fan/intent.py | """Intents for the fan integration."""
import voluptuous as vol
from homeassistant.core import HomeAssistant
from homeassistant.helpers import intent
from . import ATTR_PERCENTAGE, DOMAIN, SERVICE_TURN_ON
INTENT_FAN_SET_SPEED = "HassFanSetSpeed"
async def async_setup_intents(hass: HomeAssistant) -> None:
"""Set up the fan intents."""
intent.async_register(
hass,
intent.ServiceIntentHandler(
INTENT_FAN_SET_SPEED,
DOMAIN,
SERVICE_TURN_ON,
description="Sets a fan's speed by percentage",
required_domains={DOMAIN},
platforms={DOMAIN},
required_slots={
ATTR_PERCENTAGE: intent.IntentSlotInfo(
description="The speed percentage of the fan",
value_schema=vol.All(vol.Coerce(int), vol.Range(min=0, max=100)),
)
},
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/fan/intent.py",
"license": "Apache License 2.0",
"lines": 25,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/husqvarna_automower/event.py | """Creates the event entities for supported mowers."""
from collections.abc import Callable
import logging
from aioautomower.model import SingleMessageData
from homeassistant.components.event import (
DOMAIN as EVENT_DOMAIN,
EventEntity,
EventEntityDescription,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import AutomowerConfigEntry
from .const import ERROR_KEYS
from .coordinator import AutomowerDataUpdateCoordinator
from .entity import AutomowerBaseEntity
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 1
ATTR_SEVERITY = "severity"
ATTR_LATITUDE = "latitude"
ATTR_LONGITUDE = "longitude"
ATTR_DATE_TIME = "date_time"
async def async_setup_entry(
hass: HomeAssistant,
config_entry: AutomowerConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Automower message event entities.
Entities are created dynamically based on messages received from the API,
but only for mowers that support message events after the WebSocket connection
is ready.
"""
coordinator = config_entry.runtime_data
entity_registry = er.async_get(hass)
restored_mowers: set[str] = {
entry.unique_id.removesuffix("_message")
for entry in er.async_entries_for_config_entry(
entity_registry, config_entry.entry_id
)
if entry.domain == EVENT_DOMAIN
}
@callback
def _on_ws_ready() -> None:
async_add_entities(
AutomowerMessageEventEntity(mower_id, coordinator, websocket_alive=True)
for mower_id in restored_mowers
if mower_id in coordinator.data
)
coordinator.api.unregister_ws_ready_callback(_on_ws_ready)
coordinator.api.register_ws_ready_callback(_on_ws_ready)
@callback
def _handle_message(msg: SingleMessageData) -> None:
"""Add entity dynamically if a new mower sends messages."""
if msg.id in restored_mowers:
return
restored_mowers.add(msg.id)
async_add_entities([AutomowerMessageEventEntity(msg.id, coordinator)])
coordinator.api.register_single_message_callback(_handle_message)
class AutomowerMessageEventEntity(AutomowerBaseEntity, EventEntity):
"""EventEntity for Automower message events."""
entity_description: EventEntityDescription
_message_cb: Callable[[SingleMessageData], None]
_attr_translation_key = "message"
_attr_event_types = ERROR_KEYS
def __init__(
self,
mower_id: str,
coordinator: AutomowerDataUpdateCoordinator,
*,
websocket_alive: bool | None = None,
) -> None:
"""Initialize Automower message event entity."""
super().__init__(mower_id, coordinator)
self._attr_unique_id = f"{mower_id}_message"
self.websocket_alive: bool = (
websocket_alive
if websocket_alive is not None
else coordinator.websocket_alive
)
@property
def available(self) -> bool:
"""Return True if the entity is available."""
return self.websocket_alive and self.mower_id in self.coordinator.data
@callback
def _handle(self, msg: SingleMessageData) -> None:
"""Handle a message event from the API and trigger the event entity if it matches the entity's mower ID."""
if msg.id != self.mower_id:
return
message = msg.attributes.message
self._trigger_event(
message.code,
{
ATTR_SEVERITY: message.severity,
ATTR_LATITUDE: message.latitude,
ATTR_LONGITUDE: message.longitude,
ATTR_DATE_TIME: message.time,
},
)
self.async_write_ha_state()
async def async_added_to_hass(self) -> None:
"""Register callback when entity is added to hass."""
await super().async_added_to_hass()
self.coordinator.api.register_single_message_callback(self._handle)
self.coordinator.websocket_callbacks.append(self._handle_websocket_update)
async def async_will_remove_from_hass(self) -> None:
"""Unregister WebSocket callback when entity is removed."""
self.coordinator.api.unregister_single_message_callback(self._handle)
self.coordinator.websocket_callbacks.remove(self._handle_websocket_update)
def _handle_websocket_update(self, is_alive: bool) -> None:
"""Handle websocket status changes."""
if self.websocket_alive == is_alive:
return
self.websocket_alive = is_alive
_LOGGER.debug("WebSocket status changed to %s, updating entity state", is_alive)
self.async_write_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/husqvarna_automower/event.py",
"license": "Apache License 2.0",
"lines": 115,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/huum/number.py | """Control for steamer."""
from __future__ import annotations
import logging
from huum.const import SaunaStatus
from homeassistant.components.number import NumberEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import CONFIG_STEAMER, CONFIG_STEAMER_AND_LIGHT
from .coordinator import HuumConfigEntry, HuumDataUpdateCoordinator
from .entity import HuumBaseEntity
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: HuumConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up steamer if applicable."""
coordinator = config_entry.runtime_data
# Light is configured for this sauna.
if coordinator.data.config in [CONFIG_STEAMER, CONFIG_STEAMER_AND_LIGHT]:
async_add_entities([HuumSteamer(coordinator)])
class HuumSteamer(HuumBaseEntity, NumberEntity):
"""Representation of a steamer."""
_attr_translation_key = "humidity"
_attr_native_max_value = 10
_attr_native_min_value = 0
_attr_native_step = 1
def __init__(self, coordinator: HuumDataUpdateCoordinator) -> None:
"""Initialize the steamer."""
super().__init__(coordinator)
self._attr_unique_id = coordinator.config_entry.entry_id
@property
def native_value(self) -> float:
"""Return the current value."""
return self.coordinator.data.target_humidity
async def async_set_native_value(self, value: float) -> None:
"""Update the current value."""
target_temperature = self.coordinator.data.target_temperature
if (
not target_temperature
or self.coordinator.data.status != SaunaStatus.ONLINE_HEATING
):
return
await self.coordinator.huum.turn_on(
temperature=target_temperature, humidity=int(value)
)
await self.coordinator.async_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/huum/number.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/knx/storage/serialize.py | """Custom serializer for KNX schemas."""
from typing import Any, cast
import voluptuous as vol
from voluptuous_serialize import UNSUPPORTED, UnsupportedType, convert
from homeassistant.const import Platform
from homeassistant.helpers import selector
from .entity_store_schema import KNX_SCHEMA_FOR_PLATFORM
from .knx_selector import AllSerializeFirst, GroupSelectSchema, KNXSelectorBase
def knx_serializer(
schema: vol.Schema,
) -> dict[str, Any] | list[dict[str, Any]] | UnsupportedType:
"""Serialize KNX schema."""
if isinstance(schema, GroupSelectSchema):
return [
cast(
dict[str, Any], # GroupSelectOption converts to a dict with subschema
convert(option, custom_serializer=knx_serializer),
)
for option in schema.validators
]
if isinstance(schema, KNXSelectorBase):
result = schema.serialize()
if schema.serialize_subschema:
result["schema"] = convert(schema.schema, custom_serializer=knx_serializer)
return result
if isinstance(schema, AllSerializeFirst):
return convert(schema.validators[0], custom_serializer=knx_serializer)
if isinstance(schema, selector.Selector):
return schema.serialize() | {"type": "ha_selector"}
return UNSUPPORTED
def get_serialized_schema(
platform: Platform,
) -> dict[str, Any] | list[dict[str, Any]] | None:
"""Get the schema for a specific platform."""
if knx_schema := KNX_SCHEMA_FOR_PLATFORM.get(platform):
return convert(knx_schema, custom_serializer=knx_serializer)
return None
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/knx/storage/serialize.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/letpot/select.py | """Support for LetPot select entities."""
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from letpot.deviceclient import LetPotDeviceClient
from letpot.models import DeviceFeature, LightMode, TemperatureUnit
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import LetPotConfigEntry, LetPotDeviceCoordinator
from .entity import LetPotEntity, LetPotEntityDescription, exception_handler
# Each change pushes a 'full' device status with the change. The library will cache
# pending changes to avoid overwriting, but try to avoid a lot of parallelism.
PARALLEL_UPDATES = 1
class LightBrightnessLowHigh(StrEnum):
"""Light brightness low/high model."""
LOW = "low"
HIGH = "high"
def _get_brightness_low_high_value(coordinator: LetPotDeviceCoordinator) -> str | None:
"""Return brightness as low/high for a device which only has a low and high value."""
brightness = coordinator.data.light_brightness
levels = coordinator.device_client.get_light_brightness_levels(
coordinator.device.serial_number
)
return (
LightBrightnessLowHigh.LOW.value
if levels[0] == brightness
else LightBrightnessLowHigh.HIGH.value
)
async def _set_brightness_low_high_value(
device_client: LetPotDeviceClient, serial: str, option: str
) -> None:
"""Set brightness from low/high for a device which only has a low and high value."""
levels = device_client.get_light_brightness_levels(serial)
await device_client.set_light_brightness(
serial, levels[0] if option == LightBrightnessLowHigh.LOW.value else levels[1]
)
@dataclass(frozen=True, kw_only=True)
class LetPotSelectEntityDescription(LetPotEntityDescription, SelectEntityDescription):
"""Describes a LetPot select entity."""
value_fn: Callable[[LetPotDeviceCoordinator], str | None]
set_value_fn: Callable[[LetPotDeviceClient, str, str], Coroutine[Any, Any, None]]
SELECTORS: tuple[LetPotSelectEntityDescription, ...] = (
LetPotSelectEntityDescription(
key="display_temperature_unit",
translation_key="display_temperature_unit",
options=[x.name.lower() for x in TemperatureUnit],
value_fn=(
lambda coordinator: (
coordinator.data.temperature_unit.name.lower()
if coordinator.data.temperature_unit is not None
else None
)
),
set_value_fn=(
lambda device_client, serial, option: device_client.set_temperature_unit(
serial, TemperatureUnit[option.upper()]
)
),
supported_fn=(
lambda coordinator: (
DeviceFeature.TEMPERATURE_SET_UNIT
in coordinator.device_client.device_info(
coordinator.device.serial_number
).features
)
),
entity_category=EntityCategory.CONFIG,
),
LetPotSelectEntityDescription(
key="light_brightness_low_high",
translation_key="light_brightness",
options=[
LightBrightnessLowHigh.LOW.value,
LightBrightnessLowHigh.HIGH.value,
],
value_fn=_get_brightness_low_high_value,
set_value_fn=_set_brightness_low_high_value,
supported_fn=(
lambda coordinator: (
DeviceFeature.LIGHT_BRIGHTNESS_LOW_HIGH
in coordinator.device_client.device_info(
coordinator.device.serial_number
).features
)
),
entity_category=EntityCategory.CONFIG,
),
LetPotSelectEntityDescription(
key="light_mode",
translation_key="light_mode",
options=[x.name.lower() for x in LightMode],
value_fn=(
lambda coordinator: (
coordinator.data.light_mode.name.lower()
if coordinator.data.light_mode is not None
else None
)
),
set_value_fn=(
lambda device_client, serial, option: device_client.set_light_mode(
serial, LightMode[option.upper()]
)
),
entity_category=EntityCategory.CONFIG,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: LetPotConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up LetPot select entities based on a config entry and device status/features."""
coordinators = entry.runtime_data
async_add_entities(
LetPotSelectEntity(coordinator, description)
for description in SELECTORS
for coordinator in coordinators
if description.supported_fn(coordinator)
)
class LetPotSelectEntity(LetPotEntity, SelectEntity):
"""Defines a LetPot select entity."""
entity_description: LetPotSelectEntityDescription
def __init__(
self,
coordinator: LetPotDeviceCoordinator,
description: LetPotSelectEntityDescription,
) -> None:
"""Initialize LetPot select entity."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.config_entry.unique_id}_{coordinator.device.serial_number}_{description.key}"
@property
def current_option(self) -> str | None:
"""Return the selected entity option."""
return self.entity_description.value_fn(self.coordinator)
@exception_handler
async def async_select_option(self, option: str) -> None:
"""Change the selected option."""
return await self.entity_description.set_value_fn(
self.coordinator.device_client,
self.coordinator.device.serial_number,
option,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/letpot/select.py",
"license": "Apache License 2.0",
"lines": 146,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/nina/diagnostics.py | """Diagnostics for the Nina integration."""
from dataclasses import asdict
from typing import Any
from homeassistant.core import HomeAssistant
from .coordinator import NinaConfigEntry
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: NinaConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
runtime_data_dict = {
region_key: [asdict(warning) for warning in region_data]
for region_key, region_data in entry.runtime_data.data.items()
}
return {
"entry_data": dict(entry.data),
"data": runtime_data_dict,
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/nina/diagnostics.py",
"license": "Apache License 2.0",
"lines": 17,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/opower/repairs.py | """Repairs for Opower."""
from __future__ import annotations
from homeassistant.components.repairs import RepairsFlow
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
class UnsupportedUtilityFixFlow(RepairsFlow):
"""Handler for removing a configuration entry that uses an unsupported utility."""
def __init__(self, data: dict[str, str]) -> None:
"""Initialize."""
self._entry_id = data["entry_id"]
self._placeholders = data.copy()
self._placeholders.pop("entry_id")
async def async_step_init(
self, user_input: dict[str, str] | None = None
) -> FlowResult:
"""Handle the first step of a fix flow."""
return await self.async_step_confirm()
async def async_step_confirm(
self, user_input: dict[str, str] | None = None
) -> FlowResult:
"""Handle the confirm step of a fix flow."""
if user_input is not None:
await self.hass.config_entries.async_remove(self._entry_id)
return self.async_create_entry(title="", data={})
return self.async_show_form(
step_id="confirm", description_placeholders=self._placeholders
)
async def async_create_fix_flow(
hass: HomeAssistant, issue_id: str, data: dict[str, str] | None
) -> RepairsFlow:
"""Create flow."""
assert issue_id.startswith("unsupported_utility")
assert data
return UnsupportedUtilityFixFlow(data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/opower/repairs.py",
"license": "Apache License 2.0",
"lines": 34,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/pooldose/config_flow.py | """Config flow for the Seko PoolDose integration."""
from __future__ import annotations
import logging
from typing import Any
from pooldose.client import PooldoseClient
from pooldose.request_status import RequestStatus
from pooldose.type_definitions import APIVersionResponse
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_HOST, CONF_MAC
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
SCHEMA_DEVICE = vol.Schema(
{
vol.Required(CONF_HOST): cv.string,
}
)
class PooldoseConfigFlow(ConfigFlow, domain=DOMAIN):
"""Config flow for the Pooldose integration including DHCP discovery."""
VERSION = 1
MINOR_VERSION = 2
def __init__(self) -> None:
"""Initialize the config flow and store the discovered IP address and MAC."""
super().__init__()
self._discovered_ip: str | None = None
self._discovered_mac: str | None = None
async def _validate_host(
self, host: str
) -> tuple[str | None, APIVersionResponse | None, dict[str, str] | None]:
"""Validate the host and return (serial_number, api_versions, errors)."""
client = PooldoseClient(host, websession=async_get_clientsession(self.hass))
client_status = await client.connect()
if client_status == RequestStatus.HOST_UNREACHABLE:
return None, None, {"base": "cannot_connect"}
if client_status == RequestStatus.PARAMS_FETCH_FAILED:
return None, None, {"base": "params_fetch_failed"}
if client_status != RequestStatus.SUCCESS:
return None, None, {"base": "cannot_connect"}
api_status, api_versions = client.check_apiversion_supported()
if api_status == RequestStatus.NO_DATA:
return None, None, {"base": "api_not_set"}
if api_status == RequestStatus.API_VERSION_UNSUPPORTED:
return None, api_versions, {"base": "api_not_supported"}
device_info = client.device_info
if not device_info:
return None, None, {"base": "no_device_info"}
serial_number = device_info.get("SERIAL_NUMBER")
if not serial_number:
return None, None, {"base": "no_serial_number"}
return serial_number, None, None
async def async_step_dhcp(
self, discovery_info: DhcpServiceInfo
) -> ConfigFlowResult:
"""Handle DHCP discovery: validate device and update IP if needed."""
serial_number, _, _ = await self._validate_host(discovery_info.ip)
if not serial_number:
return self.async_abort(reason="no_serial_number")
# If an existing entry is found
existing_entry = await self.async_set_unique_id(serial_number)
if existing_entry:
# Only update the MAC if it's not already set
if CONF_MAC not in existing_entry.data:
self.hass.config_entries.async_update_entry(
existing_entry,
data={**existing_entry.data, CONF_MAC: discovery_info.macaddress},
)
self._abort_if_unique_id_configured(updates={CONF_HOST: discovery_info.ip})
# Else: Continue with new flow
self._discovered_ip = discovery_info.ip
self._discovered_mac = discovery_info.macaddress
return self.async_show_form(
step_id="dhcp_confirm",
description_placeholders={
"ip": discovery_info.ip,
"mac": discovery_info.macaddress,
"name": f"PoolDose {serial_number}",
},
)
async def async_step_dhcp_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Create the entry after the confirmation dialog."""
return self.async_create_entry(
title=f"PoolDose {self.unique_id}",
data={
CONF_HOST: self._discovered_ip,
CONF_MAC: self._discovered_mac,
},
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
if user_input is not None:
host = user_input[CONF_HOST]
serial_number, api_versions, errors = await self._validate_host(host)
if errors:
return self.async_show_form(
step_id="user",
data_schema=SCHEMA_DEVICE,
errors=errors,
# Handle API version info for error display; pass version info when available
# or None when api_versions is None to avoid displaying version details
description_placeholders={
"api_version_is": api_versions.get("api_version_is") or "",
"api_version_should": api_versions.get("api_version_should")
or "",
}
if api_versions
else None,
)
await self.async_set_unique_id(serial_number, raise_on_progress=False)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"PoolDose {serial_number}",
data={CONF_HOST: host},
)
return self.async_show_form(
step_id="user",
data_schema=SCHEMA_DEVICE,
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reconfigure to change the device host/IP for an existing entry."""
if user_input is not None:
host = user_input[CONF_HOST]
serial_number, api_versions, errors = await self._validate_host(host)
if errors:
return self.async_show_form(
step_id="reconfigure",
data_schema=SCHEMA_DEVICE,
errors=errors,
# Handle API version info for error display identical to other steps
description_placeholders={
"api_version_is": api_versions.get("api_version_is") or "",
"api_version_should": api_versions.get("api_version_should")
or "",
}
if api_versions
else None,
)
# Ensure new serial number matches the existing entry unique_id (serial number)
if serial_number != self._get_reconfigure_entry().unique_id:
return self.async_abort(reason="wrong_device")
# Update the existing config entry with the new host and schedule reload
return self.async_update_reload_and_abort(
self._get_reconfigure_entry(), data_updates={CONF_HOST: host}
)
return self.async_show_form(
step_id="reconfigure",
# Pre-fill with current host from the entry being reconfigured
data_schema=self.add_suggested_values_to_schema(
SCHEMA_DEVICE, self._get_reconfigure_entry().data
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/pooldose/config_flow.py",
"license": "Apache License 2.0",
"lines": 159,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/pooldose/const.py | """Constants for the Seko Pooldose integration."""
from __future__ import annotations
from homeassistant.const import UnitOfTemperature, UnitOfVolume, UnitOfVolumeFlowRate
DOMAIN = "pooldose"
MANUFACTURER = "SEKO"
# Unit mappings for select entities (water meter and flow rate)
# Keys match API values exactly: lowercase for m3/m3/h, uppercase L for L/L/s
UNIT_MAPPING: dict[str, str] = {
# Temperature units
"°C": UnitOfTemperature.CELSIUS,
"°F": UnitOfTemperature.FAHRENHEIT,
# Volume flow rate units
"m3/h": UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR,
"L/s": UnitOfVolumeFlowRate.LITERS_PER_SECOND,
# Volume units
"L": UnitOfVolume.LITERS,
"m3": UnitOfVolume.CUBIC_METERS,
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/pooldose/const.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/pooldose/coordinator.py | """Data update coordinator for the PoolDose integration."""
from __future__ import annotations
from datetime import timedelta
import logging
from pooldose.client import PooldoseClient
from pooldose.request_status import RequestStatus
from pooldose.type_definitions import DeviceInfoDict, StructuredValuesDict
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
_LOGGER = logging.getLogger(__name__)
type PooldoseConfigEntry = ConfigEntry[PooldoseCoordinator]
class PooldoseCoordinator(DataUpdateCoordinator[StructuredValuesDict]):
"""Coordinator for PoolDose integration."""
device_info: DeviceInfoDict
config_entry: PooldoseConfigEntry
def __init__(
self,
hass: HomeAssistant,
client: PooldoseClient,
config_entry: PooldoseConfigEntry,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
name="Pooldose",
update_interval=timedelta(seconds=600), # Default update interval
config_entry=config_entry,
)
self.client = client
async def _async_setup(self) -> None:
"""Set up the coordinator."""
# Update device info after successful connection
self.device_info = self.client.device_info
_LOGGER.debug("Device info: %s", self.device_info)
async def _async_update_data(self) -> StructuredValuesDict:
"""Fetch data from the PoolDose API."""
try:
status, instant_values = await self.client.instant_values_structured()
except TimeoutError as err:
raise UpdateFailed(
f"Timeout fetching data from PoolDose device: {err}"
) from err
except (ConnectionError, OSError) as err:
raise UpdateFailed(
f"Failed to connect to PoolDose device while fetching data: {err}"
) from err
if status != RequestStatus.SUCCESS:
raise UpdateFailed(f"API returned status: {status}")
if not instant_values:
raise UpdateFailed("No data received from API")
_LOGGER.debug("Instant values structured: %s", instant_values)
return instant_values
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/pooldose/coordinator.py",
"license": "Apache License 2.0",
"lines": 54,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/pooldose/entity.py | """Base entity for Seko Pooldose integration."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from typing import Any, Literal
from pooldose.type_definitions import DeviceInfoDict, ValueDict
from homeassistant.const import CONF_MAC
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, MANUFACTURER
from .coordinator import PooldoseCoordinator
def device_info(
info: DeviceInfoDict | None, unique_id: str, mac: str | None = None
) -> DeviceInfo:
"""Create device info for PoolDose devices."""
if info is None:
info = {}
api_version = (info.get("API_VERSION") or "").removesuffix("/")
return DeviceInfo(
identifiers={(DOMAIN, unique_id)},
manufacturer=MANUFACTURER,
model=info.get("MODEL") or None,
model_id=info.get("MODEL_ID") or None,
name=info.get("NAME") or None,
serial_number=unique_id,
sw_version=(
f"{info.get('FW_VERSION')} (SW v{info.get('SW_VERSION')}, API {api_version})"
if info.get("FW_VERSION") and info.get("SW_VERSION") and api_version
else None
),
hw_version=info.get("FW_CODE") or None,
configuration_url=(
f"http://{info['IP']}/index.html" if info.get("IP") else None
),
connections={(CONNECTION_NETWORK_MAC, mac)} if mac else set(),
)
class PooldoseEntity(CoordinatorEntity[PooldoseCoordinator]):
"""Base class for all PoolDose entities."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: PooldoseCoordinator,
serial_number: str,
device_properties: DeviceInfoDict,
entity_description: EntityDescription,
platform_name: Literal["sensor", "switch", "number", "binary_sensor", "select"],
) -> None:
"""Initialize PoolDose entity."""
super().__init__(coordinator)
self.entity_description = entity_description
self.platform_name = platform_name
self._attr_unique_id = f"{serial_number}_{entity_description.key}"
self._attr_device_info = device_info(
device_properties,
serial_number,
coordinator.config_entry.data.get(CONF_MAC),
)
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and self.get_data() is not None
def get_data(self) -> ValueDict | None:
"""Get data for this entity, only if available."""
platform_data = self.coordinator.data[self.platform_name]
return platform_data.get(self.entity_description.key)
async def _async_perform_write(
self,
api_call: Callable[[str, Any], Coroutine[Any, Any, bool]],
key: str,
value: bool | str | float,
) -> None:
"""Perform a write call to the API with unified error handling.
- `api_call` should be a bound coroutine function like
`self.coordinator.client.set_number`.
- Raises ServiceValidationError on connection errors or when the API
returns False.
"""
if not await api_call(key, value):
if not self.coordinator.client.is_connected:
raise ServiceValidationError(
translation_domain=DOMAIN, translation_key="cannot_connect"
)
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="write_rejected",
translation_placeholders={
"entity": self.entity_description.key,
"value": str(value),
},
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/pooldose/entity.py",
"license": "Apache License 2.0",
"lines": 91,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/pooldose/sensor.py | """Sensors for the Seko PoolDose integration."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from typing import TYPE_CHECKING
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import (
CONCENTRATION_PARTS_PER_MILLION,
EntityCategory,
UnitOfElectricPotential,
UnitOfTime,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import PooldoseConfigEntry
from .const import UNIT_MAPPING
from .entity import PooldoseEntity
_LOGGER = logging.getLogger(__name__)
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class PooldoseSensorEntityDescription(SensorEntityDescription):
"""Describes PoolDose sensor entity."""
use_unit_conversion: bool = False
SENSOR_DESCRIPTIONS: tuple[PooldoseSensorEntityDescription, ...] = (
PooldoseSensorEntityDescription(
key="temperature",
device_class=SensorDeviceClass.TEMPERATURE,
use_unit_conversion=True,
),
PooldoseSensorEntityDescription(key="ph", device_class=SensorDeviceClass.PH),
PooldoseSensorEntityDescription(
key="orp",
translation_key="orp",
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.MILLIVOLT,
),
PooldoseSensorEntityDescription(
key="cl",
translation_key="cl",
native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION,
),
PooldoseSensorEntityDescription(
key="flow_rate",
translation_key="flow_rate",
device_class=SensorDeviceClass.VOLUME_FLOW_RATE,
use_unit_conversion=True,
),
PooldoseSensorEntityDescription(
key="water_meter_total_permanent",
translation_key="water_meter_total_permanent",
device_class=SensorDeviceClass.VOLUME,
state_class=SensorStateClass.TOTAL_INCREASING,
use_unit_conversion=True,
),
PooldoseSensorEntityDescription(
key="ph_type_dosing",
translation_key="ph_type_dosing",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.ENUM,
options=["alcalyne", "acid"],
),
PooldoseSensorEntityDescription(
key="peristaltic_ph_dosing",
translation_key="peristaltic_ph_dosing",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
device_class=SensorDeviceClass.ENUM,
options=["proportional", "on_off", "timed"],
),
PooldoseSensorEntityDescription(
key="ofa_ph_time",
translation_key="ofa_ph_time",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.DURATION,
entity_registry_enabled_default=False,
native_unit_of_measurement=UnitOfTime.MINUTES,
),
PooldoseSensorEntityDescription(
key="orp_type_dosing",
translation_key="orp_type_dosing",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
device_class=SensorDeviceClass.ENUM,
options=["low", "high"],
),
PooldoseSensorEntityDescription(
key="peristaltic_orp_dosing",
translation_key="peristaltic_orp_dosing",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
device_class=SensorDeviceClass.ENUM,
options=["off", "proportional", "on_off", "timed"],
),
PooldoseSensorEntityDescription(
key="cl_type_dosing",
translation_key="cl_type_dosing",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
device_class=SensorDeviceClass.ENUM,
options=["low", "high"],
),
PooldoseSensorEntityDescription(
key="peristaltic_cl_dosing",
translation_key="peristaltic_cl_dosing",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
device_class=SensorDeviceClass.ENUM,
options=["off", "proportional", "on_off", "timed"],
),
PooldoseSensorEntityDescription(
key="ofa_orp_time",
translation_key="ofa_orp_time",
device_class=SensorDeviceClass.DURATION,
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
native_unit_of_measurement=UnitOfTime.MINUTES,
),
PooldoseSensorEntityDescription(
key="ph_calibration_type",
translation_key="ph_calibration_type",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
device_class=SensorDeviceClass.ENUM,
options=["off", "reference", "1_point", "2_points"],
),
PooldoseSensorEntityDescription(
key="ph_calibration_offset",
translation_key="ph_calibration_offset",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.VOLTAGE,
suggested_display_precision=2,
entity_registry_enabled_default=False,
native_unit_of_measurement=UnitOfElectricPotential.MILLIVOLT,
),
PooldoseSensorEntityDescription(
key="ph_calibration_slope",
translation_key="ph_calibration_slope",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.VOLTAGE,
suggested_display_precision=2,
entity_registry_enabled_default=False,
native_unit_of_measurement=UnitOfElectricPotential.MILLIVOLT,
),
PooldoseSensorEntityDescription(
key="orp_calibration_type",
translation_key="orp_calibration_type",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
device_class=SensorDeviceClass.ENUM,
options=["off", "reference", "1_point"],
),
PooldoseSensorEntityDescription(
key="orp_calibration_offset",
translation_key="orp_calibration_offset",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.VOLTAGE,
suggested_display_precision=2,
entity_registry_enabled_default=False,
native_unit_of_measurement=UnitOfElectricPotential.MILLIVOLT,
),
PooldoseSensorEntityDescription(
key="orp_calibration_slope",
translation_key="orp_calibration_slope",
entity_category=EntityCategory.DIAGNOSTIC,
device_class=SensorDeviceClass.VOLTAGE,
suggested_display_precision=2,
entity_registry_enabled_default=False,
native_unit_of_measurement=UnitOfElectricPotential.MILLIVOLT,
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: PooldoseConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up PoolDose sensor entities from a config entry."""
if TYPE_CHECKING:
assert config_entry.unique_id is not None
coordinator = config_entry.runtime_data
sensor_data = coordinator.data["sensor"]
serial_number = config_entry.unique_id
async_add_entities(
PooldoseSensor(
coordinator,
serial_number,
coordinator.device_info,
description,
"sensor",
)
for description in SENSOR_DESCRIPTIONS
if description.key in sensor_data
)
class PooldoseSensor(PooldoseEntity, SensorEntity):
"""Sensor entity for the Seko PoolDose Python API."""
entity_description: PooldoseSensorEntityDescription
@property
def native_value(self) -> float | int | str | None:
"""Return the current value of the sensor."""
data = self.get_data()
if data is not None:
return data["value"]
return None
@property
def native_unit_of_measurement(self) -> str | None:
"""Return the unit of measurement."""
if (
self.entity_description.use_unit_conversion
and (data := self.get_data()) is not None
and (device_unit := data.get("unit"))
):
# Map device unit to Home Assistant unit, return None if unknown
return UNIT_MAPPING.get(device_unit)
# Fall back to static unit from entity description
return super().native_unit_of_measurement
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/pooldose/sensor.py",
"license": "Apache License 2.0",
"lines": 219,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/qbus/binary_sensor.py | """Support for Qbus binary sensor."""
from dataclasses import dataclass
from typing import cast
from qbusmqttapi.discovery import QbusMqttDevice, QbusMqttOutput
from qbusmqttapi.factory import QbusMqttTopicFactory
from qbusmqttapi.state import QbusMqttDeviceState, QbusMqttWeatherState
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN
from .coordinator import QbusConfigEntry
from .entity import (
QbusEntity,
create_device_identifier,
create_unique_id,
determine_new_outputs,
)
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class QbusWeatherDescription(BinarySensorEntityDescription):
"""Description for Qbus weather entities."""
property: str
_WEATHER_DESCRIPTIONS = (
QbusWeatherDescription(
key="raining",
property="raining",
translation_key="raining",
),
QbusWeatherDescription(
key="twilight",
property="twilight",
translation_key="twilight",
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: QbusConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up binary sensor entities."""
coordinator = entry.runtime_data
added_outputs: list[QbusMqttOutput] = []
added_controllers: list[str] = []
def _create_weather_entities() -> list[BinarySensorEntity]:
new_outputs = determine_new_outputs(
coordinator, added_outputs, lambda output: output.type == "weatherstation"
)
return [
QbusWeatherBinarySensor(output, description)
for output in new_outputs
for description in _WEATHER_DESCRIPTIONS
]
def _create_controller_entities() -> list[BinarySensorEntity]:
if coordinator.data and coordinator.data.id not in added_controllers:
added_controllers.extend(coordinator.data.id)
return [QbusControllerConnectedBinarySensor(coordinator.data)]
return []
def _check_outputs() -> None:
entities = [*_create_weather_entities(), *_create_controller_entities()]
async_add_entities(entities)
_check_outputs()
entry.async_on_unload(coordinator.async_add_listener(_check_outputs))
class QbusWeatherBinarySensor(QbusEntity, BinarySensorEntity):
"""Representation of a Qbus weather binary sensor."""
_state_cls = QbusMqttWeatherState
entity_description: QbusWeatherDescription
def __init__(
self, mqtt_output: QbusMqttOutput, description: QbusWeatherDescription
) -> None:
"""Initialize binary sensor entity."""
super().__init__(mqtt_output, id_suffix=description.key)
self.entity_description = description
async def _handle_state_received(self, state: QbusMqttWeatherState) -> None:
if value := state.read_property(self.entity_description.property, None):
self._attr_is_on = (
None if value is None else cast(str, value).lower() == "true"
)
class QbusControllerConnectedBinarySensor(BinarySensorEntity):
"""Representation of the Qbus controller connected sensor."""
_attr_has_entity_name = True
_attr_name = None
_attr_should_poll = False
_attr_device_class = BinarySensorDeviceClass.CONNECTIVITY
def __init__(self, controller: QbusMqttDevice) -> None:
"""Initialize binary sensor entity."""
self._controller = controller
self._attr_unique_id = create_unique_id(controller.serial_number, "connected")
self._attr_device_info = DeviceInfo(
identifiers={create_device_identifier(controller)}
)
async def async_added_to_hass(self) -> None:
"""Run when entity about to be added to hass."""
topic = QbusMqttTopicFactory().get_device_state_topic(self._controller.id)
self.async_on_remove(
async_dispatcher_connect(
self.hass,
f"{DOMAIN}_{topic}",
self._state_received,
)
)
@callback
def _state_received(self, state: QbusMqttDeviceState) -> None:
self._attr_is_on = state.properties.connected if state.properties else None
self.async_schedule_update_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/qbus/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 110,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/qbus/sensor.py | """Support for Qbus sensor."""
from dataclasses import dataclass
from qbusmqttapi.discovery import QbusMqttOutput
from qbusmqttapi.state import (
GaugeStateProperty,
QbusMqttGaugeState,
QbusMqttHumidityState,
QbusMqttThermoState,
QbusMqttVentilationState,
QbusMqttWeatherState,
)
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import (
CONCENTRATION_PARTS_PER_MILLION,
LIGHT_LUX,
PERCENTAGE,
UnitOfElectricCurrent,
UnitOfElectricPotential,
UnitOfEnergy,
UnitOfLength,
UnitOfPower,
UnitOfPressure,
UnitOfSoundPressure,
UnitOfSpeed,
UnitOfTemperature,
UnitOfVolume,
UnitOfVolumeFlowRate,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import QbusConfigEntry
from .entity import QbusEntity, create_new_entities, determine_new_outputs
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class QbusWeatherDescription(SensorEntityDescription):
"""Description for Qbus weather entities."""
property: str
_WEATHER_DESCRIPTIONS = (
QbusWeatherDescription(
key="daylight",
property="dayLight",
translation_key="daylight",
device_class=SensorDeviceClass.ILLUMINANCE,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=LIGHT_LUX,
),
QbusWeatherDescription(
key="light",
property="light",
device_class=SensorDeviceClass.ILLUMINANCE,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=LIGHT_LUX,
),
QbusWeatherDescription(
key="light_east",
property="lightEast",
translation_key="light_east",
device_class=SensorDeviceClass.ILLUMINANCE,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=LIGHT_LUX,
),
QbusWeatherDescription(
key="light_south",
property="lightSouth",
translation_key="light_south",
device_class=SensorDeviceClass.ILLUMINANCE,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=LIGHT_LUX,
),
QbusWeatherDescription(
key="light_west",
property="lightWest",
translation_key="light_west",
device_class=SensorDeviceClass.ILLUMINANCE,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=LIGHT_LUX,
),
QbusWeatherDescription(
key="temperature",
property="temperature",
device_class=SensorDeviceClass.TEMPERATURE,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
),
QbusWeatherDescription(
key="wind",
property="wind",
device_class=SensorDeviceClass.WIND_SPEED,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=UnitOfSpeed.KILOMETERS_PER_HOUR,
),
)
_GAUGE_VARIANT_DESCRIPTIONS = {
"AIRPRESSURE": SensorEntityDescription(
key="airpressure",
device_class=SensorDeviceClass.PRESSURE,
native_unit_of_measurement=UnitOfPressure.MBAR,
state_class=SensorStateClass.MEASUREMENT,
),
"AIRQUALITY": SensorEntityDescription(
key="airquality",
device_class=SensorDeviceClass.CO2,
native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION,
state_class=SensorStateClass.MEASUREMENT,
),
"CURRENT": SensorEntityDescription(
key="current",
device_class=SensorDeviceClass.CURRENT,
native_unit_of_measurement=UnitOfElectricCurrent.AMPERE,
state_class=SensorStateClass.MEASUREMENT,
),
"ENERGY": SensorEntityDescription(
key="energy",
device_class=SensorDeviceClass.ENERGY,
native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR,
state_class=SensorStateClass.TOTAL,
),
"GAS": SensorEntityDescription(
key="gas",
device_class=SensorDeviceClass.VOLUME_FLOW_RATE,
native_unit_of_measurement=UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR,
state_class=SensorStateClass.MEASUREMENT,
),
"GASFLOW": SensorEntityDescription(
key="gasflow",
device_class=SensorDeviceClass.VOLUME_FLOW_RATE,
native_unit_of_measurement=UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR,
state_class=SensorStateClass.MEASUREMENT,
),
"HUMIDITY": SensorEntityDescription(
key="humidity",
device_class=SensorDeviceClass.HUMIDITY,
native_unit_of_measurement=PERCENTAGE,
state_class=SensorStateClass.MEASUREMENT,
),
"LIGHT": SensorEntityDescription(
key="light",
device_class=SensorDeviceClass.ILLUMINANCE,
native_unit_of_measurement=LIGHT_LUX,
state_class=SensorStateClass.MEASUREMENT,
),
"LOUDNESS": SensorEntityDescription(
key="loudness",
device_class=SensorDeviceClass.SOUND_PRESSURE,
native_unit_of_measurement=UnitOfSoundPressure.DECIBEL,
state_class=SensorStateClass.MEASUREMENT,
),
"POWER": SensorEntityDescription(
key="power",
device_class=SensorDeviceClass.POWER,
native_unit_of_measurement=UnitOfPower.KILO_WATT,
state_class=SensorStateClass.MEASUREMENT,
),
"PRESSURE": SensorEntityDescription(
key="pressure",
device_class=SensorDeviceClass.PRESSURE,
native_unit_of_measurement=UnitOfPressure.KPA,
state_class=SensorStateClass.MEASUREMENT,
),
"TEMPERATURE": SensorEntityDescription(
key="temperature",
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
state_class=SensorStateClass.MEASUREMENT,
),
"VOLTAGE": SensorEntityDescription(
key="voltage",
device_class=SensorDeviceClass.VOLTAGE,
native_unit_of_measurement=UnitOfElectricPotential.VOLT,
state_class=SensorStateClass.MEASUREMENT,
),
"VOLUME": SensorEntityDescription(
key="volume",
device_class=SensorDeviceClass.VOLUME_STORAGE,
native_unit_of_measurement=UnitOfVolume.LITERS,
state_class=SensorStateClass.MEASUREMENT,
),
"WATER": SensorEntityDescription(
key="water",
device_class=SensorDeviceClass.WATER,
native_unit_of_measurement=UnitOfVolume.LITERS,
state_class=SensorStateClass.TOTAL,
),
"WATERFLOW": SensorEntityDescription(
key="waterflow",
device_class=SensorDeviceClass.VOLUME_FLOW_RATE,
native_unit_of_measurement=UnitOfVolumeFlowRate.LITERS_PER_HOUR,
state_class=SensorStateClass.MEASUREMENT,
),
"WATERLEVEL": SensorEntityDescription(
key="waterlevel",
device_class=SensorDeviceClass.DISTANCE,
native_unit_of_measurement=UnitOfLength.METERS,
state_class=SensorStateClass.MEASUREMENT,
),
"WATERPRESSURE": SensorEntityDescription(
key="waterpressure",
device_class=SensorDeviceClass.PRESSURE,
native_unit_of_measurement=UnitOfPressure.MBAR,
state_class=SensorStateClass.MEASUREMENT,
),
"WIND": SensorEntityDescription(
key="wind",
device_class=SensorDeviceClass.WIND_SPEED,
native_unit_of_measurement=UnitOfSpeed.KILOMETERS_PER_HOUR,
state_class=SensorStateClass.MEASUREMENT,
),
}
def _is_gauge_with_variant(output: QbusMqttOutput) -> bool:
return (
output.type == "gauge"
and isinstance(output.variant, str)
and _GAUGE_VARIANT_DESCRIPTIONS.get(output.variant.upper()) is not None
)
def _is_ventilation_with_co2(output: QbusMqttOutput) -> bool:
return output.type == "ventilation" and output.properties.get("co2") is not None
async def async_setup_entry(
hass: HomeAssistant,
entry: QbusConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up sensor entities."""
coordinator = entry.runtime_data
added_outputs: list[QbusMqttOutput] = []
def _create_weather_entities() -> list[QbusEntity]:
new_outputs = determine_new_outputs(
coordinator, added_outputs, lambda output: output.type == "weatherstation"
)
return [
QbusWeatherSensor(output, description)
for output in new_outputs
for description in _WEATHER_DESCRIPTIONS
]
def _check_outputs() -> None:
entities: list[QbusEntity] = [
*create_new_entities(
coordinator,
added_outputs,
_is_gauge_with_variant,
QbusGaugeVariantSensor,
),
*create_new_entities(
coordinator,
added_outputs,
lambda output: output.type == "humidity",
QbusHumiditySensor,
),
*create_new_entities(
coordinator,
added_outputs,
lambda output: output.type == "thermo",
QbusThermoSensor,
),
*create_new_entities(
coordinator,
added_outputs,
_is_ventilation_with_co2,
QbusVentilationSensor,
),
*_create_weather_entities(),
]
async_add_entities(entities)
_check_outputs()
entry.async_on_unload(coordinator.async_add_listener(_check_outputs))
class QbusGaugeVariantSensor(QbusEntity, SensorEntity):
"""Representation of a Qbus sensor entity for gauges with variant."""
_state_cls = QbusMqttGaugeState
_attr_name = None
_attr_suggested_display_precision = 2
def __init__(self, mqtt_output: QbusMqttOutput) -> None:
"""Initialize sensor entity."""
super().__init__(mqtt_output)
variant = str(mqtt_output.variant)
self.entity_description = _GAUGE_VARIANT_DESCRIPTIONS[variant.upper()]
async def _handle_state_received(self, state: QbusMqttGaugeState) -> None:
self._attr_native_value = state.read_value(GaugeStateProperty.CURRENT_VALUE)
class QbusHumiditySensor(QbusEntity, SensorEntity):
"""Representation of a Qbus sensor entity for humidity modules."""
_state_cls = QbusMqttHumidityState
_attr_device_class = SensorDeviceClass.HUMIDITY
_attr_name = None
_attr_native_unit_of_measurement = PERCENTAGE
_attr_state_class = SensorStateClass.MEASUREMENT
async def _handle_state_received(self, state: QbusMqttHumidityState) -> None:
self._attr_native_value = state.read_value()
class QbusThermoSensor(QbusEntity, SensorEntity):
"""Representation of a Qbus sensor entity for thermostats."""
_state_cls = QbusMqttThermoState
_attr_device_class = SensorDeviceClass.TEMPERATURE
_attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
_attr_state_class = SensorStateClass.MEASUREMENT
async def _handle_state_received(self, state: QbusMqttThermoState) -> None:
self._attr_native_value = state.read_current_temperature()
class QbusVentilationSensor(QbusEntity, SensorEntity):
"""Representation of a Qbus sensor entity for ventilations."""
_state_cls = QbusMqttVentilationState
_attr_device_class = SensorDeviceClass.CO2
_attr_name = None
_attr_native_unit_of_measurement = CONCENTRATION_PARTS_PER_MILLION
_attr_state_class = SensorStateClass.MEASUREMENT
_attr_suggested_display_precision = 0
async def _handle_state_received(self, state: QbusMqttVentilationState) -> None:
self._attr_native_value = state.read_co2()
class QbusWeatherSensor(QbusEntity, SensorEntity):
"""Representation of a Qbus weather sensor."""
_state_cls = QbusMqttWeatherState
entity_description: QbusWeatherDescription
def __init__(
self, mqtt_output: QbusMqttOutput, description: QbusWeatherDescription
) -> None:
"""Initialize sensor entity."""
super().__init__(mqtt_output, id_suffix=description.key)
self.entity_description = description
if description.key == "temperature":
self._attr_name = None
async def _handle_state_received(self, state: QbusMqttWeatherState) -> None:
if value := state.read_property(self.entity_description.property, None):
self.native_value = value
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/qbus/sensor.py",
"license": "Apache License 2.0",
"lines": 323,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/russound_rio/media_browser.py | """Support for Russound media browsing."""
from aiorussound import RussoundClient, Zone
from aiorussound.const import FeatureFlag
from aiorussound.util import is_feature_supported
from homeassistant.components.media_player import BrowseMedia, MediaClass
from homeassistant.core import HomeAssistant
async def async_browse_media(
hass: HomeAssistant,
client: RussoundClient,
media_content_id: str | None,
media_content_type: str | None,
zone: Zone,
) -> BrowseMedia:
"""Browse media."""
if media_content_type == "presets":
return await _presets_payload(_find_presets_by_zone(client, zone))
return await _root_payload(hass, _find_presets_by_zone(client, zone))
async def _root_payload(
hass: HomeAssistant, presets_by_zone: dict[int, dict[int, str]]
) -> BrowseMedia:
"""Return root payload for Russound RIO."""
children: list[BrowseMedia] = []
if presets_by_zone:
children.append(
BrowseMedia(
title="Presets",
media_class=MediaClass.DIRECTORY,
media_content_id="",
media_content_type="presets",
thumbnail="/api/brands/integration/russound_rio/logo.png",
can_play=False,
can_expand=True,
)
)
return BrowseMedia(
title="Russound",
media_class=MediaClass.DIRECTORY,
media_content_id="",
media_content_type="root",
can_play=False,
can_expand=True,
children=children,
)
async def _presets_payload(presets_by_zone: dict[int, dict[int, str]]) -> BrowseMedia:
"""Create payload to list presets."""
children: list[BrowseMedia] = []
for source_id, presets in presets_by_zone.items():
for preset_id, preset_name in presets.items():
children.append(
BrowseMedia(
title=preset_name,
media_class=MediaClass.CHANNEL,
media_content_id=f"{source_id},{preset_id}",
media_content_type="preset",
can_play=True,
can_expand=False,
)
)
return BrowseMedia(
title="Presets",
media_class=MediaClass.DIRECTORY,
media_content_id="",
media_content_type="presets",
can_play=False,
can_expand=True,
children=children,
)
def _find_presets_by_zone(
client: RussoundClient, zone: Zone
) -> dict[int, dict[int, str]]:
"""Returns a dict by {source_id: {preset_id: preset_name}}."""
assert client.rio_version
return {
source_id: source.presets
for source_id, source in client.sources.items()
if source.presets
and (
not is_feature_supported(
client.rio_version, FeatureFlag.SUPPORT_ZONE_SOURCE_EXCLUSION
)
or source_id in zone.enabled_sources
)
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/russound_rio/media_browser.py",
"license": "Apache License 2.0",
"lines": 83,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sleep_as_android/config_flow.py | """Config flow for the Sleep as Android integration."""
from __future__ import annotations
from homeassistant.helpers import config_entry_flow
from .const import DOMAIN
config_entry_flow.register_webhook_flow(
DOMAIN,
"Sleep as Android",
{"docs_url": "https://www.home-assistant.io/integrations/sleep_as_android"},
allow_multiple=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sleep_as_android/config_flow.py",
"license": "Apache License 2.0",
"lines": 10,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sleep_as_android/const.py | """Constants for the Sleep as Android integration."""
DOMAIN = "sleep_as_android"
ATTR_EVENT = "event"
ATTR_VALUE1 = "value1"
ATTR_VALUE2 = "value2"
ATTR_VALUE3 = "value3"
MAP_EVENTS = {
"sleep_tracking_paused": "paused",
"sleep_tracking_resumed": "resumed",
"sleep_tracking_started": "started",
"sleep_tracking_stopped": "stopped",
"alarm_alert_dismiss": "alert_dismiss",
"alarm_alert_start": "alert_start",
"alarm_rescheduled": "rescheduled",
"alarm_skip_next": "skip_next",
"alarm_snooze_canceled": "snooze_canceled",
"alarm_snooze_clicked": "snooze_clicked",
"alarm_wake_up_check": "wake_up_check",
"sound_event_baby": "baby",
"sound_event_cough": "cough",
"sound_event_laugh": "laugh",
"sound_event_snore": "snore",
"sound_event_talk": "talk",
"lullaby_start": "start",
"lullaby_stop": "stop",
"lullaby_volume_down": "volume_down",
}
ALARM_LABEL_DEFAULT = "alarm"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sleep_as_android/const.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/sleep_as_android/diagnostics.py | """Diagnostics platform for Sleep as Android integration."""
from __future__ import annotations
from typing import Any
from homeassistant.core import HomeAssistant
from . import SleepAsAndroidConfigEntry
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: SleepAsAndroidConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return {
"config_entry_data": {"cloudhook": config_entry.data["cloudhook"]},
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sleep_as_android/diagnostics.py",
"license": "Apache License 2.0",
"lines": 12,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sleep_as_android/entity.py | """Base entity for Sleep as Android integration."""
from __future__ import annotations
from abc import abstractmethod
from homeassistant.const import CONF_WEBHOOK_ID
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity, EntityDescription
from . import SleepAsAndroidConfigEntry
from .const import DOMAIN
class SleepAsAndroidEntity(Entity):
"""Base entity."""
_attr_has_entity_name = True
def __init__(
self,
config_entry: SleepAsAndroidConfigEntry,
entity_description: EntityDescription,
) -> None:
"""Initialize the entity."""
self._attr_unique_id = f"{config_entry.entry_id}_{entity_description.key}"
self.entity_description = entity_description
self.webhook_id = config_entry.data[CONF_WEBHOOK_ID]
self._attr_device_info = DeviceInfo(
connections={(DOMAIN, config_entry.entry_id)},
manufacturer="Urbandroid",
model="Sleep as Android",
name=config_entry.title,
)
@abstractmethod
def _async_handle_event(self, webhook_id: str, data: dict[str, str]) -> None:
"""Handle the Sleep as Android event."""
async def async_added_to_hass(self) -> None:
"""Register event callback."""
self.async_on_remove(
async_dispatcher_connect(self.hass, DOMAIN, self._async_handle_event)
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sleep_as_android/entity.py",
"license": "Apache License 2.0",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sleep_as_android/event.py | """Event platform for Sleep as Android integration."""
from __future__ import annotations
from dataclasses import dataclass
from enum import StrEnum
from homeassistant.components.event import (
EventDeviceClass,
EventEntity,
EventEntityDescription,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import SleepAsAndroidConfigEntry
from .const import ATTR_EVENT, MAP_EVENTS
from .entity import SleepAsAndroidEntity
PARALLEL_UPDATES = 0
@dataclass(kw_only=True, frozen=True)
class SleepAsAndroidEventEntityDescription(EventEntityDescription):
"""Sleep as Android sensor description."""
event_types: list[str]
class SleepAsAndroidEvent(StrEnum):
"""Sleep as Android events."""
ALARM_CLOCK = "alarm_clock"
USER_NOTIFICATION = "user_notification"
SMART_WAKEUP = "smart_wakeup"
SLEEP_HEALTH = "sleep_health"
LULLABY = "lullaby"
SLEEP_PHASE = "sleep_phase"
SLEEP_TRACKING = "sleep_tracking"
SOUND_EVENT = "sound_event"
JET_LAG_PREVENTION = "jet_lag_prevention"
EVENT_DESCRIPTIONS: tuple[SleepAsAndroidEventEntityDescription, ...] = (
SleepAsAndroidEventEntityDescription(
key=SleepAsAndroidEvent.SLEEP_TRACKING,
translation_key=SleepAsAndroidEvent.SLEEP_TRACKING,
device_class=EventDeviceClass.BUTTON,
event_types=[
"paused",
"resumed",
"started",
"stopped",
],
),
SleepAsAndroidEventEntityDescription(
key=SleepAsAndroidEvent.ALARM_CLOCK,
translation_key=SleepAsAndroidEvent.ALARM_CLOCK,
event_types=[
"alert_dismiss",
"alert_start",
"rescheduled",
"skip_next",
"snooze_canceled",
"snooze_clicked",
],
),
SleepAsAndroidEventEntityDescription(
key=SleepAsAndroidEvent.SMART_WAKEUP,
translation_key=SleepAsAndroidEvent.SMART_WAKEUP,
event_types=[
"before_smart_period",
"smart_period",
],
),
SleepAsAndroidEventEntityDescription(
key=SleepAsAndroidEvent.USER_NOTIFICATION,
translation_key=SleepAsAndroidEvent.USER_NOTIFICATION,
event_types=[
"wake_up_check",
"show_skip_next_alarm",
"time_to_bed_alarm_alert",
],
),
SleepAsAndroidEventEntityDescription(
key=SleepAsAndroidEvent.SLEEP_PHASE,
translation_key=SleepAsAndroidEvent.SLEEP_PHASE,
event_types=[
"awake",
"deep_sleep",
"light_sleep",
"not_awake",
"rem",
],
),
SleepAsAndroidEventEntityDescription(
key=SleepAsAndroidEvent.SOUND_EVENT,
translation_key=SleepAsAndroidEvent.SOUND_EVENT,
event_types=[
"baby",
"cough",
"laugh",
"snore",
"talk",
],
),
SleepAsAndroidEventEntityDescription(
key=SleepAsAndroidEvent.LULLABY,
translation_key=SleepAsAndroidEvent.LULLABY,
event_types=[
"start",
"stop",
"volume_down",
],
),
SleepAsAndroidEventEntityDescription(
key=SleepAsAndroidEvent.SLEEP_HEALTH,
translation_key=SleepAsAndroidEvent.SLEEP_HEALTH,
event_types=[
"antisnoring",
"apnea_alarm",
],
),
SleepAsAndroidEventEntityDescription(
key=SleepAsAndroidEvent.JET_LAG_PREVENTION,
translation_key=SleepAsAndroidEvent.JET_LAG_PREVENTION,
event_types=[
"jet_lag_start",
"jet_lag_stop",
],
entity_registry_enabled_default=False,
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: SleepAsAndroidConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the event platform."""
async_add_entities(
SleepAsAndroidEventEntity(config_entry, description)
for description in EVENT_DESCRIPTIONS
)
class SleepAsAndroidEventEntity(SleepAsAndroidEntity, EventEntity):
"""An event entity."""
entity_description: SleepAsAndroidEventEntityDescription
@callback
def _async_handle_event(self, webhook_id: str, data: dict[str, str]) -> None:
"""Handle the Sleep as Android event."""
event = MAP_EVENTS.get(data[ATTR_EVENT], data[ATTR_EVENT])
if (
webhook_id == self.webhook_id
and event in self.entity_description.event_types
):
self._trigger_event(event)
self.async_write_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sleep_as_android/event.py",
"license": "Apache License 2.0",
"lines": 143,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sleep_as_android/sensor.py | """Sensor platform for Sleep as Android integration."""
from __future__ import annotations
from datetime import datetime
from enum import StrEnum
from homeassistant.components.sensor import (
RestoreSensor,
SensorDeviceClass,
SensorEntityDescription,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util import dt as dt_util
from . import SleepAsAndroidConfigEntry
from .const import ALARM_LABEL_DEFAULT, ATTR_EVENT, ATTR_VALUE1, ATTR_VALUE2
from .entity import SleepAsAndroidEntity
PARALLEL_UPDATES = 0
class SleepAsAndroidSensor(StrEnum):
"""Sleep as Android sensors."""
NEXT_ALARM = "next_alarm"
ALARM_LABEL = "alarm_label"
SENSOR_DESCRIPTIONS: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key=SleepAsAndroidSensor.NEXT_ALARM,
translation_key=SleepAsAndroidSensor.NEXT_ALARM,
device_class=SensorDeviceClass.TIMESTAMP,
),
SensorEntityDescription(
key=SleepAsAndroidSensor.ALARM_LABEL,
translation_key=SleepAsAndroidSensor.ALARM_LABEL,
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: SleepAsAndroidConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the sensor platform."""
async_add_entities(
SleepAsAndroidSensorEntity(config_entry, description)
for description in SENSOR_DESCRIPTIONS
)
class SleepAsAndroidSensorEntity(SleepAsAndroidEntity, RestoreSensor):
"""A sensor entity."""
entity_description: SensorEntityDescription
@callback
def _async_handle_event(self, webhook_id: str, data: dict[str, str]) -> None:
"""Handle the Sleep as Android event."""
if webhook_id == self.webhook_id and data[ATTR_EVENT] in (
"alarm_snooze_clicked",
"alarm_snooze_canceled",
"alarm_skip_next",
"show_skip_next_alarm",
"alarm_rescheduled",
):
if (
self.entity_description.key is SleepAsAndroidSensor.NEXT_ALARM
and (alarm_time := data.get(ATTR_VALUE1))
and alarm_time.isnumeric()
):
self._attr_native_value = datetime.fromtimestamp(
int(alarm_time) / 1000, tz=dt_util.get_default_time_zone()
)
if self.entity_description.key is SleepAsAndroidSensor.ALARM_LABEL and (
label := data.get(ATTR_VALUE2, ALARM_LABEL_DEFAULT)
):
self._attr_native_value = label
if (
data[ATTR_EVENT] == "alarm_rescheduled"
and data.get(ATTR_VALUE1) is None
):
self._attr_native_value = None
self.async_write_ha_state()
async def async_added_to_hass(self) -> None:
"""Restore entity state."""
state = await self.async_get_last_sensor_data()
if state:
self._attr_native_value = state.native_value
await super().async_added_to_hass()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sleep_as_android/sensor.py",
"license": "Apache License 2.0",
"lines": 78,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/smarla/sensor.py | """Support for the Swing2Sleep Smarla sensor entities."""
from dataclasses import dataclass
from pysmarlaapi.federwiege.services.classes import Property
from homeassistant.components.sensor import (
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import UnitOfLength, UnitOfTime
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import FederwiegeConfigEntry
from .entity import SmarlaBaseEntity, SmarlaEntityDescription
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class SmarlaSensorEntityDescription(SmarlaEntityDescription, SensorEntityDescription):
"""Class describing Swing2Sleep Smarla sensor entities."""
multiple: bool = False
value_pos: int = 0
SENSORS: list[SmarlaSensorEntityDescription] = [
SmarlaSensorEntityDescription(
key="amplitude",
translation_key="amplitude",
service="analyser",
property="oscillation",
multiple=True,
value_pos=0,
native_unit_of_measurement=UnitOfLength.MILLIMETERS,
state_class=SensorStateClass.MEASUREMENT,
),
SmarlaSensorEntityDescription(
key="period",
translation_key="period",
service="analyser",
property="oscillation",
multiple=True,
value_pos=1,
native_unit_of_measurement=UnitOfTime.MILLISECONDS,
state_class=SensorStateClass.MEASUREMENT,
),
SmarlaSensorEntityDescription(
key="activity",
translation_key="activity",
service="analyser",
property="activity",
state_class=SensorStateClass.MEASUREMENT,
),
SmarlaSensorEntityDescription(
key="swing_count",
translation_key="swing_count",
service="analyser",
property="swing_count",
state_class=SensorStateClass.TOTAL_INCREASING,
),
]
async def async_setup_entry(
hass: HomeAssistant,
config_entry: FederwiegeConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Smarla sensors from config entry."""
federwiege = config_entry.runtime_data
async_add_entities(
(
SmarlaSensor(federwiege, desc)
if not desc.multiple
else SmarlaSensorMultiple(federwiege, desc)
)
for desc in SENSORS
)
class SmarlaSensor(SmarlaBaseEntity, SensorEntity):
"""Representation of Smarla sensor."""
entity_description: SmarlaSensorEntityDescription
_property: Property[int]
@property
def native_value(self) -> int | None:
"""Return the entity value to represent the entity state."""
return self._property.get()
class SmarlaSensorMultiple(SmarlaBaseEntity, SensorEntity):
"""Representation of Smarla sensor with multiple values inside property."""
entity_description: SmarlaSensorEntityDescription
_property: Property[list[int]]
@property
def native_value(self) -> int | None:
"""Return the entity value to represent the entity state."""
v = self._property.get()
return v[self.entity_description.value_pos] if v is not None else None
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/smarla/sensor.py",
"license": "Apache License 2.0",
"lines": 87,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/sonos/select.py | """Select entities for Sonos."""
from __future__ import annotations
from dataclasses import dataclass
import logging
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import (
ATTR_DIALOG_LEVEL,
ATTR_DIALOG_LEVEL_ENUM,
MODEL_SONOS_ARC_ULTRA,
SONOS_CREATE_SELECTS,
SPEECH_DIALOG_LEVEL,
)
from .entity import SonosEntity
from .helpers import SonosConfigEntry, soco_error
from .speaker import SonosSpeaker
@dataclass(frozen=True, kw_only=True)
class SonosSelectEntityDescription(SelectEntityDescription):
"""Describes AirGradient select entity."""
soco_attribute: str
speaker_attribute: str
speaker_model: str
SELECT_TYPES: list[SonosSelectEntityDescription] = [
SonosSelectEntityDescription(
key=SPEECH_DIALOG_LEVEL,
translation_key=SPEECH_DIALOG_LEVEL,
soco_attribute=ATTR_DIALOG_LEVEL,
speaker_attribute=ATTR_DIALOG_LEVEL_ENUM,
speaker_model=MODEL_SONOS_ARC_ULTRA,
options=["off", "low", "medium", "high", "max"],
),
]
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: SonosConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the Sonos select platform from a config entry."""
def available_soco_attributes(
speaker: SonosSpeaker,
) -> list[SonosSelectEntityDescription]:
features: list[SonosSelectEntityDescription] = []
for select_data in SELECT_TYPES:
if select_data.speaker_model == speaker.model_name.upper():
if (
speaker.update_soco_int_attribute(
select_data.soco_attribute, select_data.speaker_attribute
)
is not None
):
features.append(select_data)
return features
async def _async_create_entities(speaker: SonosSpeaker) -> None:
available_features = await hass.async_add_executor_job(
available_soco_attributes, speaker
)
async_add_entities(
SonosSelectEntity(speaker, config_entry, select_data)
for select_data in available_features
)
config_entry.async_on_unload(
async_dispatcher_connect(hass, SONOS_CREATE_SELECTS, _async_create_entities)
)
class SonosSelectEntity(SonosEntity, SelectEntity):
"""Representation of a Sonos select entity."""
def __init__(
self,
speaker: SonosSpeaker,
config_entry: SonosConfigEntry,
select_data: SonosSelectEntityDescription,
) -> None:
"""Initialize the select entity."""
super().__init__(speaker, config_entry)
self._attr_unique_id = f"{self.soco.uid}-{select_data.key}"
self._attr_translation_key = select_data.translation_key
assert select_data.options is not None
self._attr_options = select_data.options
self.speaker_attribute = select_data.speaker_attribute
self.soco_attribute = select_data.soco_attribute
async def _async_fallback_poll(self) -> None:
"""Poll the value if subscriptions are not working."""
await self.hass.async_add_executor_job(self.poll_state)
self.async_write_ha_state()
@soco_error()
def poll_state(self) -> None:
"""Poll the device for the current state."""
self.speaker.update_soco_int_attribute(
self.soco_attribute, self.speaker_attribute
)
@property
def current_option(self) -> str | None:
"""Return the current option for the entity."""
option = getattr(self.speaker, self.speaker_attribute, None)
if not isinstance(option, int) or not (0 <= option < len(self._attr_options)):
_LOGGER.error(
"Invalid option %s for %s on %s",
option,
self.soco_attribute,
self.speaker.zone_name,
)
return None
return self._attr_options[option]
@soco_error()
def select_option(self, option: str) -> None:
"""Set a new value."""
dialog_level = self._attr_options.index(option)
setattr(self.soco, self.soco_attribute, dialog_level)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/sonos/select.py",
"license": "Apache License 2.0",
"lines": 110,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/switchbot_cloud/cover.py | """Support for the Switchbot BlindTilt, Curtain, Curtain3, RollerShade as Cover."""
import asyncio
from typing import Any
from switchbot_api import (
BlindTiltCommands,
CommonCommands,
CurtainCommands,
Device,
Remote,
RollerShadeCommands,
SwitchBotAPI,
)
from homeassistant.components.cover import (
CoverDeviceClass,
CoverEntity,
CoverEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import SwitchbotCloudData, SwitchBotCoordinator
from .const import COVER_ENTITY_AFTER_COMMAND_REFRESH, DOMAIN
from .entity import SwitchBotCloudEntity
async def async_setup_entry(
hass: HomeAssistant,
config: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up SwitchBot Cloud entry."""
data: SwitchbotCloudData = hass.data[DOMAIN][config.entry_id]
async_add_entities(
_async_make_entity(data.api, device, coordinator)
for device, coordinator in data.devices.covers
)
class SwitchBotCloudCover(SwitchBotCloudEntity, CoverEntity):
"""Representation of a SwitchBot Cover."""
_attr_name = None
_attr_is_closed: bool | None = None
def _set_attributes(self) -> None:
if self.coordinator.data is None:
return
position: int | None = self.coordinator.data.get("slidePosition")
if position is None:
return
self._attr_current_cover_position = 100 - position
self._attr_current_cover_tilt_position = 100 - position
self._attr_is_closed = position == 100
class SwitchBotCloudCoverCurtain(SwitchBotCloudCover):
"""Representation of a SwitchBot Curtain & Curtain3."""
_attr_device_class = CoverDeviceClass.CURTAIN
_attr_supported_features: CoverEntityFeature = (
CoverEntityFeature.OPEN
| CoverEntityFeature.CLOSE
| CoverEntityFeature.STOP
| CoverEntityFeature.SET_POSITION
)
async def async_open_cover(self, **kwargs: Any) -> None:
"""Open the cover."""
await self.send_api_command(CommonCommands.ON)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_close_cover(self, **kwargs: Any) -> None:
"""Close the cover."""
await self.send_api_command(CommonCommands.OFF)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_set_cover_position(self, **kwargs: Any) -> None:
"""Move the cover to a specific position."""
position: int | None = kwargs.get("position")
if position is not None:
await self.send_api_command(
CurtainCommands.SET_POSITION,
parameters=f"{0},ff,{100 - position}",
)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_stop_cover(self, **kwargs: Any) -> None:
"""Stop the cover."""
await self.send_api_command(CurtainCommands.PAUSE)
await self.coordinator.async_request_refresh()
class SwitchBotCloudCoverRollerShade(SwitchBotCloudCover):
"""Representation of a SwitchBot RollerShade."""
_attr_device_class = CoverDeviceClass.SHADE
_attr_supported_features: CoverEntityFeature = (
CoverEntityFeature.SET_POSITION
| CoverEntityFeature.OPEN
| CoverEntityFeature.CLOSE
)
async def async_open_cover(self, **kwargs: Any) -> None:
"""Open the cover."""
await self.send_api_command(RollerShadeCommands.SET_POSITION, parameters=0)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_close_cover(self, **kwargs: Any) -> None:
"""Close the cover."""
await self.send_api_command(RollerShadeCommands.SET_POSITION, parameters=100)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_set_cover_position(self, **kwargs: Any) -> None:
"""Move the cover to a specific position."""
position: int | None = kwargs.get("position")
if position is not None:
await self.send_api_command(
RollerShadeCommands.SET_POSITION, parameters=(100 - position)
)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
class SwitchBotCloudCoverBlindTilt(SwitchBotCloudCover):
"""Representation of a SwitchBot Blind Tilt."""
_attr_direction: str | None = None
_attr_device_class = CoverDeviceClass.BLIND
_attr_supported_features: CoverEntityFeature = (
CoverEntityFeature.SET_TILT_POSITION
| CoverEntityFeature.OPEN_TILT
| CoverEntityFeature.CLOSE_TILT
)
def _set_attributes(self) -> None:
if self.coordinator.data is None:
return
position: int | None = self.coordinator.data.get("slidePosition")
if position is None:
return
self._attr_is_closed = position in [0, 100]
if position > 50:
percent = 100 - ((position - 50) * 2)
else:
percent = 100 - (50 - position) * 2
self._attr_current_cover_position = percent
self._attr_current_cover_tilt_position = percent
direction = self.coordinator.data.get("direction")
self._attr_direction = direction.lower() if direction else None
async def async_set_cover_tilt_position(self, **kwargs: Any) -> None:
"""Move the cover to a specific position."""
percent: int | None = kwargs.get("tilt_position")
if percent is not None:
await self.send_api_command(
BlindTiltCommands.SET_POSITION,
parameters=f"{self._attr_direction};{percent}",
)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_open_cover_tilt(self, **kwargs: Any) -> None:
"""Open the cover."""
await self.send_api_command(BlindTiltCommands.FULLY_OPEN)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_close_cover_tilt(self, **kwargs: Any) -> None:
"""Close the cover."""
if self._attr_direction is not None:
if "up" in self._attr_direction:
await self.send_api_command(BlindTiltCommands.CLOSE_UP)
else:
await self.send_api_command(BlindTiltCommands.CLOSE_DOWN)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
class SwitchBotCloudCoverGarageDoorOpener(SwitchBotCloudCover):
"""Representation of a SwitchBot Garage Door Opener."""
_attr_device_class = CoverDeviceClass.GARAGE
_attr_supported_features: CoverEntityFeature = (
CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE
)
def _set_attributes(self) -> None:
if self.coordinator.data is None:
return
door_status: int | None = self.coordinator.data.get("doorStatus")
self._attr_is_closed = None if door_status is None else door_status == 1
async def async_open_cover(self, **kwargs: Any) -> None:
"""Open the cover."""
await self.send_api_command(CommonCommands.ON)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
async def async_close_cover(self, **kwargs: Any) -> None:
"""Close the cover."""
await self.send_api_command(CommonCommands.OFF)
await asyncio.sleep(COVER_ENTITY_AFTER_COMMAND_REFRESH)
await self.coordinator.async_request_refresh()
@callback
def _async_make_entity(
api: SwitchBotAPI, device: Device | Remote, coordinator: SwitchBotCoordinator
) -> (
SwitchBotCloudCoverBlindTilt
| SwitchBotCloudCoverRollerShade
| SwitchBotCloudCoverCurtain
| SwitchBotCloudCoverGarageDoorOpener
):
"""Make a SwitchBotCloudCover device."""
if device.device_type == "Blind Tilt":
return SwitchBotCloudCoverBlindTilt(api, device, coordinator)
if device.device_type == "Roller Shade":
return SwitchBotCloudCoverRollerShade(api, device, coordinator)
if device.device_type == "Garage Door Opener":
return SwitchBotCloudCoverGarageDoorOpener(api, device, coordinator)
return SwitchBotCloudCoverCurtain(api, device, coordinator)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/switchbot_cloud/cover.py",
"license": "Apache License 2.0",
"lines": 193,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/telegram_bot/notify.py | """Telegram bot notification entity."""
from typing import Any
from homeassistant.components.notify import (
NotifyEntity,
NotifyEntityDescription,
NotifyEntityFeature,
)
from homeassistant.config_entries import ConfigSubentry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import TelegramBotConfigEntry
from .const import ATTR_TITLE, CONF_CHAT_ID
from .entity import TelegramBotEntity
async def async_setup_entry(
hass: HomeAssistant,
config_entry: TelegramBotConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the telegram bot notification entity platform."""
for subentry_id, subentry in config_entry.subentries.items():
async_add_entities(
[TelegramBotNotifyEntity(config_entry, subentry)],
config_subentry_id=subentry_id,
)
class TelegramBotNotifyEntity(TelegramBotEntity, NotifyEntity):
"""Representation of a telegram bot notification entity."""
_attr_supported_features = NotifyEntityFeature.TITLE
def __init__(
self,
config_entry: TelegramBotConfigEntry,
subentry: ConfigSubentry,
) -> None:
"""Initialize a notification entity."""
super().__init__(
config_entry, NotifyEntityDescription(key=subentry.data[CONF_CHAT_ID])
)
self.chat_id = subentry.data[CONF_CHAT_ID]
self._attr_name = subentry.title
async def async_send_message(self, message: str, title: str | None = None) -> None:
"""Send a message."""
kwargs: dict[str, Any] = {ATTR_TITLE: title}
await self.service.send_message(message, self.chat_id, self._context, **kwargs)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/telegram_bot/notify.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/template/event.py | """Support for events which integrates with other components."""
from __future__ import annotations
import logging
from typing import Any, Final
import voluptuous as vol
from homeassistant.components.event import (
DOMAIN as EVENT_DOMAIN,
ENTITY_ID_FORMAT,
EventDeviceClass,
EventEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_DEVICE_CLASS
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import (
AddConfigEntryEntitiesCallback,
AddEntitiesCallback,
)
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from . import TriggerUpdateCoordinator
from .entity import AbstractTemplateEntity
from .helpers import (
async_setup_template_entry,
async_setup_template_platform,
async_setup_template_preview,
)
from .schemas import (
TEMPLATE_ENTITY_COMMON_CONFIG_ENTRY_SCHEMA,
make_template_entity_common_modern_attributes_schema,
)
from .template_entity import TemplateEntity
from .trigger_entity import TriggerEntity
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = "Template Event"
CONF_EVENT_TYPE = "event_type"
CONF_EVENT_TYPES = "event_types"
DEVICE_CLASS_SCHEMA: Final = vol.All(vol.Lower, vol.Coerce(EventDeviceClass))
EVENT_COMMON_SCHEMA = vol.Schema(
{
vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASS_SCHEMA,
vol.Required(CONF_EVENT_TYPE): cv.template,
vol.Required(CONF_EVENT_TYPES): cv.template,
}
)
EVENT_YAML_SCHEMA = EVENT_COMMON_SCHEMA.extend(
make_template_entity_common_modern_attributes_schema(
EVENT_DOMAIN, DEFAULT_NAME
).schema
)
EVENT_CONFIG_ENTRY_SCHEMA = EVENT_COMMON_SCHEMA.extend(
TEMPLATE_ENTITY_COMMON_CONFIG_ENTRY_SCHEMA.schema
)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
"""Set up the template event."""
await async_setup_template_platform(
hass,
EVENT_DOMAIN,
config,
StateEventEntity,
TriggerEventEntity,
async_add_entities,
discovery_info,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Initialize config entry."""
await async_setup_template_entry(
hass,
config_entry,
async_add_entities,
StateEventEntity,
EVENT_CONFIG_ENTRY_SCHEMA,
True,
)
@callback
def async_create_preview_event(
hass: HomeAssistant, name: str, config: dict[str, Any]
) -> StateEventEntity:
"""Create a preview event."""
return async_setup_template_preview(
hass,
name,
config,
StateEventEntity,
EVENT_CONFIG_ENTRY_SCHEMA,
)
class AbstractTemplateEvent(AbstractTemplateEntity, EventEntity):
"""Representation of a template event features."""
_entity_id_format = ENTITY_ID_FORMAT
# The super init is not called because TemplateEntity and TriggerEntity will call AbstractTemplateEntity.__init__.
# This ensures that the __init__ on AbstractTemplateEntity is not called twice.
def __init__(self, config: dict[str, Any]) -> None: # pylint: disable=super-init-not-called
"""Initialize the features."""
self._attr_device_class = config.get(CONF_DEVICE_CLASS)
self._event_type = None
self._attr_event_types = []
self.setup_template(
CONF_EVENT_TYPES,
"_attr_event_types",
None,
self._update_event_types,
)
self.setup_template(
CONF_EVENT_TYPE,
"_event_type",
None,
self._update_event_type,
)
@callback
def _update_event_types(self, event_types: Any) -> None:
"""Update the event types from the template."""
if event_types in (None, "None", ""):
self._attr_event_types = []
return
if not isinstance(event_types, list):
_LOGGER.error(
("Received invalid event_types list: %s for entity %s. Expected list"),
event_types,
self.entity_id,
)
self._attr_event_types = []
return
self._attr_event_types = [str(event_type) for event_type in event_types]
@callback
def _update_event_type(self, event_type: Any) -> None:
"""Update the effect from the template."""
try:
self._trigger_event(event_type)
except ValueError:
_LOGGER.error(
"Received invalid event_type: %s for entity %s. Expected one of: %s",
event_type,
self.entity_id,
self._attr_event_types,
)
class StateEventEntity(TemplateEntity, AbstractTemplateEvent):
"""Representation of a template event."""
_attr_should_poll = False
def __init__(
self,
hass: HomeAssistant,
config: dict[str, Any],
unique_id: str | None,
) -> None:
"""Initialize the select."""
TemplateEntity.__init__(self, hass, config, unique_id)
AbstractTemplateEvent.__init__(self, config)
class TriggerEventEntity(TriggerEntity, AbstractTemplateEvent, RestoreEntity):
"""Event entity based on trigger data."""
domain = EVENT_DOMAIN
extra_template_keys_complex = (
CONF_EVENT_TYPE,
CONF_EVENT_TYPES,
)
def __init__(
self,
hass: HomeAssistant,
coordinator: TriggerUpdateCoordinator,
config: ConfigType,
) -> None:
"""Initialize the entity."""
TriggerEntity.__init__(self, hass, coordinator, config)
AbstractTemplateEvent.__init__(self, config)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/template/event.py",
"license": "Apache License 2.0",
"lines": 173,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/template/schemas.py | """Shared schemas for config entry and YAML config items."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import (
CONF_DEVICE_ID,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON,
CONF_ICON_TEMPLATE,
CONF_NAME,
CONF_OPTIMISTIC,
CONF_UNIQUE_ID,
CONF_VARIABLES,
)
from homeassistant.helpers import config_validation as cv, selector
from .const import (
CONF_ATTRIBUTE_TEMPLATES,
CONF_ATTRIBUTES,
CONF_AVAILABILITY,
CONF_AVAILABILITY_TEMPLATE,
CONF_DEFAULT_ENTITY_ID,
CONF_PICTURE,
)
TEMPLATE_ENTITY_AVAILABILITY_SCHEMA = vol.Schema(
{
vol.Optional(CONF_AVAILABILITY): cv.template,
}
)
TEMPLATE_ENTITY_ATTRIBUTES_SCHEMA = vol.Schema(
{
vol.Optional(CONF_ATTRIBUTES): vol.Schema({cv.string: cv.template}),
}
)
TEMPLATE_ENTITY_COMMON_CONFIG_ENTRY_SCHEMA = vol.Schema(
{
vol.Required(CONF_NAME): cv.template,
vol.Optional(CONF_DEVICE_ID): selector.DeviceSelector(),
}
).extend(TEMPLATE_ENTITY_AVAILABILITY_SCHEMA.schema)
TEMPLATE_ENTITY_OPTIMISTIC_SCHEMA = {
vol.Optional(CONF_OPTIMISTIC): cv.boolean,
}
TEMPLATE_ENTITY_ATTRIBUTES_SCHEMA_LEGACY = vol.Schema(
{
vol.Optional(CONF_ATTRIBUTE_TEMPLATES, default={}): vol.Schema(
{cv.string: cv.template}
),
}
)
TEMPLATE_ENTITY_AVAILABILITY_SCHEMA_LEGACY = vol.Schema(
{
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
}
)
TEMPLATE_ENTITY_COMMON_SCHEMA_LEGACY = vol.Schema(
{
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
}
).extend(TEMPLATE_ENTITY_AVAILABILITY_SCHEMA_LEGACY.schema)
def make_template_entity_base_schema(domain: str, default_name: str) -> vol.Schema:
"""Return a schema with default name."""
return vol.Schema(
{
vol.Optional(CONF_DEFAULT_ENTITY_ID): vol.All(
cv.entity_id, cv.entity_domain(domain)
),
vol.Optional(CONF_ICON): cv.template,
vol.Optional(CONF_NAME, default=default_name): cv.template,
vol.Optional(CONF_PICTURE): cv.template,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
def make_template_entity_common_modern_schema(
domain: str,
default_name: str,
) -> vol.Schema:
"""Return a schema with default name."""
return vol.Schema(
{
vol.Optional(CONF_AVAILABILITY): cv.template,
vol.Optional(CONF_VARIABLES): cv.SCRIPT_VARIABLES_SCHEMA,
}
).extend(make_template_entity_base_schema(domain, default_name).schema)
def make_template_entity_common_modern_attributes_schema(
domain: str,
default_name: str,
) -> vol.Schema:
"""Return a schema with default name."""
return make_template_entity_common_modern_schema(domain, default_name).extend(
TEMPLATE_ENTITY_ATTRIBUTES_SCHEMA.schema
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/template/schemas.py",
"license": "Apache License 2.0",
"lines": 91,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.