sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
home-assistant/core:tests/components/velux/test_diagnostics.py | """Tests for the diagnostics data provided by the Velux integration."""
from unittest.mock import MagicMock, patch
import pytest
from pyvlx.const import GatewayState, GatewaySubState
from pyvlx.dataobjects import DtoState
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
@pytest.mark.freeze_time("2025-01-01T00:00:00+00:00")
@pytest.mark.parametrize("mock_pyvlx", ["mock_window"], indirect=True)
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
mock_pyvlx: MagicMock,
mock_window: MagicMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics for Velux config entry."""
mock_window.node_id = 1
mock_pyvlx.connection.connected = True
mock_pyvlx.connection.connection_counter = 3
mock_pyvlx.connection.frame_received_cbs = []
mock_pyvlx.connection.connection_opened_cbs = []
mock_pyvlx.connection.connection_closed_cbs = []
mock_pyvlx.klf200.state = DtoState(
GatewayState.GATEWAY_MODE_WITH_ACTUATORS, GatewaySubState.IDLE
)
mock_pyvlx.klf200.version = None
mock_pyvlx.klf200.protocol_version = None
mock_config_entry.add_to_hass(hass)
with patch("homeassistant.components.velux.PLATFORMS", [Platform.COVER]):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert (
await get_diagnostics_for_config_entry(hass, hass_client, mock_config_entry)
== snapshot
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/velux/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/openai_conversation/stt.py | """Speech to text support for OpenAI."""
from __future__ import annotations
from collections.abc import AsyncIterable
import io
import logging
from typing import TYPE_CHECKING
import wave
from openai import OpenAIError
from homeassistant.components import stt
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import (
CONF_CHAT_MODEL,
CONF_PROMPT,
DEFAULT_STT_PROMPT,
RECOMMENDED_STT_MODEL,
)
from .entity import OpenAIBaseLLMEntity
if TYPE_CHECKING:
from . import OpenAIConfigEntry
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: OpenAIConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up STT entities."""
for subentry in config_entry.subentries.values():
if subentry.subentry_type != "stt":
continue
async_add_entities(
[OpenAISTTEntity(config_entry, subentry)],
config_subentry_id=subentry.subentry_id,
)
class OpenAISTTEntity(stt.SpeechToTextEntity, OpenAIBaseLLMEntity):
"""OpenAI Speech to text entity."""
@property
def supported_languages(self) -> list[str]:
"""Return a list of supported languages."""
# https://developers.openai.com/api/docs/guides/speech-to-text#supported-languages
# The model may also transcribe the audio in other languages but with lower quality
return [
"af-ZA", # Afrikaans
"ar-SA", # Arabic
"hy-AM", # Armenian
"az-AZ", # Azerbaijani
"be-BY", # Belarusian
"bs-BA", # Bosnian
"bg-BG", # Bulgarian
"ca-ES", # Catalan
"zh-CN", # Chinese (Mandarin)
"hr-HR", # Croatian
"cs-CZ", # Czech
"da-DK", # Danish
"nl-NL", # Dutch
"en-US", # English
"et-EE", # Estonian
"fi-FI", # Finnish
"fr-FR", # French
"gl-ES", # Galician
"de-DE", # German
"el-GR", # Greek
"he-IL", # Hebrew
"hi-IN", # Hindi
"hu-HU", # Hungarian
"is-IS", # Icelandic
"id-ID", # Indonesian
"it-IT", # Italian
"ja-JP", # Japanese
"kn-IN", # Kannada
"kk-KZ", # Kazakh
"ko-KR", # Korean
"lv-LV", # Latvian
"lt-LT", # Lithuanian
"mk-MK", # Macedonian
"ms-MY", # Malay
"mr-IN", # Marathi
"mi-NZ", # Maori
"ne-NP", # Nepali
"no-NO", # Norwegian
"fa-IR", # Persian
"pl-PL", # Polish
"pt-PT", # Portuguese
"ro-RO", # Romanian
"ru-RU", # Russian
"sr-RS", # Serbian
"sk-SK", # Slovak
"sl-SI", # Slovenian
"es-ES", # Spanish
"sw-KE", # Swahili
"sv-SE", # Swedish
"fil-PH", # Tagalog (Filipino)
"ta-IN", # Tamil
"th-TH", # Thai
"tr-TR", # Turkish
"uk-UA", # Ukrainian
"ur-PK", # Urdu
"vi-VN", # Vietnamese
"cy-GB", # Welsh
]
@property
def supported_formats(self) -> list[stt.AudioFormats]:
"""Return a list of supported formats."""
# https://developers.openai.com/api/docs/guides/speech-to-text#transcriptions
return [stt.AudioFormats.WAV, stt.AudioFormats.OGG]
@property
def supported_codecs(self) -> list[stt.AudioCodecs]:
"""Return a list of supported codecs."""
return [stt.AudioCodecs.PCM, stt.AudioCodecs.OPUS]
@property
def supported_bit_rates(self) -> list[stt.AudioBitRates]:
"""Return a list of supported bit rates."""
return [
stt.AudioBitRates.BITRATE_8,
stt.AudioBitRates.BITRATE_16,
stt.AudioBitRates.BITRATE_24,
stt.AudioBitRates.BITRATE_32,
]
@property
def supported_sample_rates(self) -> list[stt.AudioSampleRates]:
"""Return a list of supported sample rates."""
return [
stt.AudioSampleRates.SAMPLERATE_8000,
stt.AudioSampleRates.SAMPLERATE_11000,
stt.AudioSampleRates.SAMPLERATE_16000,
stt.AudioSampleRates.SAMPLERATE_18900,
stt.AudioSampleRates.SAMPLERATE_22000,
stt.AudioSampleRates.SAMPLERATE_32000,
stt.AudioSampleRates.SAMPLERATE_37800,
stt.AudioSampleRates.SAMPLERATE_44100,
stt.AudioSampleRates.SAMPLERATE_48000,
]
@property
def supported_channels(self) -> list[stt.AudioChannels]:
"""Return a list of supported channels."""
return [stt.AudioChannels.CHANNEL_MONO, stt.AudioChannels.CHANNEL_STEREO]
async def async_process_audio_stream(
self, metadata: stt.SpeechMetadata, stream: AsyncIterable[bytes]
) -> stt.SpeechResult:
"""Process an audio stream to STT service."""
audio_bytes = bytearray()
async for chunk in stream:
audio_bytes.extend(chunk)
audio_data = bytes(audio_bytes)
if metadata.format == stt.AudioFormats.WAV:
# Add missing wav header
wav_buffer = io.BytesIO()
with wave.open(wav_buffer, "wb") as wf:
wf.setnchannels(metadata.channel.value)
wf.setsampwidth(metadata.bit_rate.value // 8)
wf.setframerate(metadata.sample_rate.value)
wf.writeframes(audio_data)
audio_data = wav_buffer.getvalue()
options = self.subentry.data
client = self.entry.runtime_data
try:
response = await client.audio.transcriptions.create(
model=options.get(CONF_CHAT_MODEL, RECOMMENDED_STT_MODEL),
file=(f"a.{metadata.format.value}", audio_data),
response_format="json",
language=metadata.language.split("-")[0],
prompt=options.get(CONF_PROMPT, DEFAULT_STT_PROMPT),
)
except OpenAIError:
_LOGGER.exception("Error during STT")
else:
if response.text:
return stt.SpeechResult(
response.text,
stt.SpeechResultState.SUCCESS,
)
return stt.SpeechResult(None, stt.SpeechResultState.ERROR)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/openai_conversation/stt.py",
"license": "Apache License 2.0",
"lines": 172,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/openai_conversation/test_stt.py | """Test STT platform of OpenAI Conversation integration."""
from collections.abc import AsyncIterable
from unittest.mock import AsyncMock, MagicMock, patch
import httpx
from openai import RateLimitError
import pytest
from homeassistant.components import stt
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def _async_get_audio_stream(data: bytes) -> AsyncIterable[bytes]:
"""Yield the audio data."""
yield data
@pytest.mark.usefixtures("mock_init_component")
async def test_stt_entity_properties(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test STT entity properties."""
entity: stt.SpeechToTextEntity = hass.data[stt.DOMAIN].get_entity("stt.openai_stt")
assert entity is not None
assert isinstance(entity.supported_languages, list)
assert len(entity.supported_languages)
assert stt.AudioFormats.WAV in entity.supported_formats
assert stt.AudioFormats.OGG in entity.supported_formats
assert stt.AudioCodecs.PCM in entity.supported_codecs
assert stt.AudioCodecs.OPUS in entity.supported_codecs
assert stt.AudioBitRates.BITRATE_8 in entity.supported_bit_rates
assert stt.AudioBitRates.BITRATE_16 in entity.supported_bit_rates
assert stt.AudioBitRates.BITRATE_24 in entity.supported_bit_rates
assert stt.AudioBitRates.BITRATE_32 in entity.supported_bit_rates
assert stt.AudioSampleRates.SAMPLERATE_8000 in entity.supported_sample_rates
assert stt.AudioSampleRates.SAMPLERATE_11000 in entity.supported_sample_rates
assert stt.AudioSampleRates.SAMPLERATE_16000 in entity.supported_sample_rates
assert stt.AudioSampleRates.SAMPLERATE_18900 in entity.supported_sample_rates
assert stt.AudioSampleRates.SAMPLERATE_22000 in entity.supported_sample_rates
assert stt.AudioSampleRates.SAMPLERATE_32000 in entity.supported_sample_rates
assert stt.AudioSampleRates.SAMPLERATE_37800 in entity.supported_sample_rates
assert stt.AudioSampleRates.SAMPLERATE_44100 in entity.supported_sample_rates
assert stt.AudioSampleRates.SAMPLERATE_48000 in entity.supported_sample_rates
assert stt.AudioChannels.CHANNEL_MONO in entity.supported_channels
assert stt.AudioChannels.CHANNEL_STEREO in entity.supported_channels
@pytest.mark.usefixtures("mock_init_component")
async def test_stt_process_audio_stream_success_wav(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_transcription: AsyncMock,
) -> None:
"""Test STT processing audio stream successfully."""
entity = hass.data[stt.DOMAIN].get_entity("stt.openai_stt")
mock_create_transcription.return_value = "This is a test transcription."
metadata = stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.WAV,
codec=stt.AudioCodecs.PCM,
bit_rate=stt.AudioBitRates.BITRATE_16,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
)
audio_stream = _async_get_audio_stream(b"test_audio_bytes")
wav_buffer = None
mock_wf = MagicMock()
mock_wf.writeframes.side_effect = lambda data: wav_buffer.write(
b"converted_wav_bytes"
)
def mock_open(buffer, mode):
nonlocal wav_buffer
wav_buffer = buffer
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_wf
return mock_cm
with patch(
"homeassistant.components.openai_conversation.stt.wave.open",
side_effect=mock_open,
) as mock_wave_open:
result = await entity.async_process_audio_stream(metadata, audio_stream)
assert result.result == stt.SpeechResultState.SUCCESS
assert result.text == "This is a test transcription."
mock_wave_open.assert_called_once()
mock_wf.setnchannels.assert_called_once_with(1)
mock_wf.setsampwidth.assert_called_once_with(2)
mock_wf.setframerate.assert_called_once_with(16000)
mock_create_transcription.assert_called_once()
call_args = mock_create_transcription.call_args
assert call_args.kwargs["model"] == "gpt-4o-mini-transcribe"
contents = call_args.kwargs["file"]
assert contents[0].endswith(".wav")
assert contents[1] == b"converted_wav_bytes"
@pytest.mark.usefixtures("mock_init_component")
async def test_stt_process_audio_stream_success_ogg(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_transcription: AsyncMock,
) -> None:
"""Test STT processing audio stream successfully."""
entity = hass.data[stt.DOMAIN].get_entity("stt.openai_stt")
mock_create_transcription.return_value = "This is a test transcription."
metadata = stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.OGG,
codec=stt.AudioCodecs.PCM,
bit_rate=stt.AudioBitRates.BITRATE_16,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
)
audio_stream = _async_get_audio_stream(b"test_audio_bytes")
wav_buffer = None
mock_wf = MagicMock()
mock_wf.writeframes.side_effect = lambda data: wav_buffer.write(
b"converted_wav_bytes"
)
def mock_open(buffer, mode):
nonlocal wav_buffer
wav_buffer = buffer
mock_cm = MagicMock()
mock_cm.__enter__.return_value = mock_wf
return mock_cm
with patch(
"homeassistant.components.openai_conversation.stt.wave.open",
side_effect=mock_open,
) as mock_wave_open:
result = await entity.async_process_audio_stream(metadata, audio_stream)
assert result.result == stt.SpeechResultState.SUCCESS
assert result.text == "This is a test transcription."
mock_wave_open.assert_not_called()
mock_create_transcription.assert_called_once()
call_args = mock_create_transcription.call_args
assert call_args.kwargs["model"] == "gpt-4o-mini-transcribe"
contents = call_args.kwargs["file"]
assert contents[0].endswith(".ogg")
assert contents[1] == b"test_audio_bytes"
@pytest.mark.usefixtures("mock_init_component")
async def test_stt_process_audio_stream_api_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_transcription: AsyncMock,
) -> None:
"""Test STT processing audio stream with API errors."""
entity = hass.data[stt.DOMAIN].get_entity("stt.openai_stt")
mock_create_transcription.side_effect = RateLimitError(
response=httpx.Response(status_code=429, request=""),
body=None,
message=None,
)
metadata = stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.OGG,
codec=stt.AudioCodecs.OPUS,
bit_rate=stt.AudioBitRates.BITRATE_16,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
)
audio_stream = _async_get_audio_stream(b"test_audio_bytes")
result = await entity.async_process_audio_stream(metadata, audio_stream)
assert result.result == stt.SpeechResultState.ERROR
assert result.text is None
@pytest.mark.usefixtures("mock_init_component")
async def test_stt_process_audio_stream_empty_response(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_create_transcription: AsyncMock,
) -> None:
"""Test STT processing with an empty response from the API."""
entity = hass.data[stt.DOMAIN].get_entity("stt.openai_stt")
mock_create_transcription.return_value = ""
metadata = stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.OGG,
codec=stt.AudioCodecs.OPUS,
bit_rate=stt.AudioBitRates.BITRATE_16,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
)
audio_stream = _async_get_audio_stream(b"test_audio_bytes")
result = await entity.async_process_audio_stream(metadata, audio_stream)
assert result.result == stt.SpeechResultState.ERROR
assert result.text is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openai_conversation/test_stt.py",
"license": "Apache License 2.0",
"lines": 175,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/compit/binary_sensor.py | """Binary sensor platform for Compit integration."""
from dataclasses import dataclass
from compit_inext_api.consts import CompitParameter
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, MANUFACTURER_NAME
from .coordinator import CompitConfigEntry, CompitDataUpdateCoordinator
PARALLEL_UPDATES = 0
NO_SENSOR = "no_sensor"
ON_STATES = ["on", "yes", "charging", "alert", "exceeded"]
DESCRIPTIONS: dict[CompitParameter, BinarySensorEntityDescription] = {
CompitParameter.AIRING: BinarySensorEntityDescription(
key=CompitParameter.AIRING.value,
translation_key="airing",
device_class=BinarySensorDeviceClass.WINDOW,
entity_category=EntityCategory.DIAGNOSTIC,
),
CompitParameter.BATTERY_CHARGE_STATUS: BinarySensorEntityDescription(
key=CompitParameter.BATTERY_CHARGE_STATUS.value,
device_class=BinarySensorDeviceClass.BATTERY_CHARGING,
entity_category=EntityCategory.DIAGNOSTIC,
),
CompitParameter.CO2_ALERT: BinarySensorEntityDescription(
key=CompitParameter.CO2_ALERT.value,
translation_key="co2_alert",
device_class=BinarySensorDeviceClass.PROBLEM,
entity_category=EntityCategory.DIAGNOSTIC,
),
CompitParameter.CO2_LEVEL: BinarySensorEntityDescription(
key=CompitParameter.CO2_LEVEL.value,
translation_key="co2_level",
device_class=BinarySensorDeviceClass.PROBLEM,
entity_category=EntityCategory.DIAGNOSTIC,
),
CompitParameter.DUST_ALERT: BinarySensorEntityDescription(
key=CompitParameter.DUST_ALERT.value,
translation_key="dust_alert",
device_class=BinarySensorDeviceClass.PROBLEM,
entity_category=EntityCategory.DIAGNOSTIC,
),
CompitParameter.PUMP_STATUS: BinarySensorEntityDescription(
key=CompitParameter.PUMP_STATUS.value,
translation_key="pump_status",
device_class=BinarySensorDeviceClass.RUNNING,
entity_category=EntityCategory.DIAGNOSTIC,
),
CompitParameter.TEMPERATURE_ALERT: BinarySensorEntityDescription(
key=CompitParameter.TEMPERATURE_ALERT.value,
translation_key="temperature_alert",
device_class=BinarySensorDeviceClass.PROBLEM,
entity_category=EntityCategory.DIAGNOSTIC,
),
}
@dataclass(frozen=True, kw_only=True)
class CompitDeviceDescription:
"""Class to describe a Compit device."""
name: str
parameters: dict[CompitParameter, BinarySensorEntityDescription]
DEVICE_DEFINITIONS: dict[int, CompitDeviceDescription] = {
12: CompitDeviceDescription(
name="Nano Color",
parameters={
CompitParameter.CO2_LEVEL: DESCRIPTIONS[CompitParameter.CO2_LEVEL],
},
),
78: CompitDeviceDescription(
name="SPM - Nano Color 2",
parameters={
CompitParameter.DUST_ALERT: DESCRIPTIONS[CompitParameter.DUST_ALERT],
CompitParameter.TEMPERATURE_ALERT: DESCRIPTIONS[
CompitParameter.TEMPERATURE_ALERT
],
CompitParameter.CO2_ALERT: DESCRIPTIONS[CompitParameter.CO2_ALERT],
},
),
223: CompitDeviceDescription(
name="Nano Color 2",
parameters={
CompitParameter.AIRING: DESCRIPTIONS[CompitParameter.AIRING],
CompitParameter.CO2_LEVEL: DESCRIPTIONS[CompitParameter.CO2_LEVEL],
},
),
225: CompitDeviceDescription(
name="SPM - Nano Color",
parameters={
CompitParameter.CO2_LEVEL: DESCRIPTIONS[CompitParameter.CO2_LEVEL],
},
),
226: CompitDeviceDescription(
name="AF-1",
parameters={
CompitParameter.BATTERY_CHARGE_STATUS: DESCRIPTIONS[
CompitParameter.BATTERY_CHARGE_STATUS
],
CompitParameter.PUMP_STATUS: DESCRIPTIONS[CompitParameter.PUMP_STATUS],
},
),
}
async def async_setup_entry(
hass: HomeAssistant,
entry: CompitConfigEntry,
async_add_devices: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Compit binary sensor entities from a config entry."""
coordinator = entry.runtime_data
async_add_devices(
CompitBinarySensor(
coordinator,
device_id,
device_definition.name,
code,
entity_description,
)
for device_id, device in coordinator.connector.all_devices.items()
if (device_definition := DEVICE_DEFINITIONS.get(device.definition.code))
for code, entity_description in device_definition.parameters.items()
if coordinator.connector.get_current_value(device_id, code) != NO_SENSOR
)
class CompitBinarySensor(
CoordinatorEntity[CompitDataUpdateCoordinator], BinarySensorEntity
):
"""Representation of a Compit binary sensor entity."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: CompitDataUpdateCoordinator,
device_id: int,
device_name: str,
parameter_code: CompitParameter,
entity_description: BinarySensorEntityDescription,
) -> None:
"""Initialize the binary sensor entity."""
super().__init__(coordinator)
self.device_id = device_id
self.entity_description = entity_description
self._attr_unique_id = f"{device_id}_{entity_description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, str(device_id))},
name=device_name,
manufacturer=MANUFACTURER_NAME,
model=device_name,
)
self.parameter_code = parameter_code
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
super().available
and self.coordinator.connector.get_device(self.device_id) is not None
)
@property
def is_on(self) -> bool | None:
"""Return the state of the binary sensor."""
value = self.coordinator.connector.get_current_value(
self.device_id, self.parameter_code
)
if value is None:
return None
return value in ON_STATES
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/compit/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 167,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/compit/test_binary_sensor.py | """Tests for the Compit binary sensor platform."""
from typing import Any
from unittest.mock import MagicMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration, snapshot_compit_entities
from tests.common import MockConfigEntry
async def test_binary_sensor_entities_snapshot(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_connector: MagicMock,
snapshot: SnapshotAssertion,
) -> None:
"""Snapshot test for binary sensor entities creation, unique IDs, and device info."""
await setup_integration(hass, mock_config_entry)
snapshot_compit_entities(hass, entity_registry, snapshot, Platform.BINARY_SENSOR)
@pytest.mark.parametrize(
("mock_return_value", "expected_state"),
[
(None, "unknown"),
("on", "on"),
("off", "off"),
("yes", "on"),
("no", "off"),
("charging", "on"),
("not_charging", "off"),
("alert", "on"),
("no_alert", "off"),
],
)
async def test_binary_sensor_return_value(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connector: MagicMock,
mock_return_value: Any | None,
expected_state: str,
) -> None:
"""Test that binary sensor entity shows correct state for various values."""
mock_connector.get_current_value.side_effect = lambda device_id, parameter_code: (
mock_return_value
)
await setup_integration(hass, mock_config_entry)
state = hass.states.get("binary_sensor.nano_color_2_airing")
assert state.state == expected_state
async def test_binary_sensor_no_sensor(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
mock_connector: MagicMock,
) -> None:
"""Test that binary sensor entities with NO_SENSOR value are not created."""
mock_connector.get_current_value.side_effect = lambda device_id, parameter_code: (
"no_sensor"
)
await setup_integration(hass, mock_config_entry)
# Check that airing sensor is not created
airing_entity = entity_registry.async_get("binary_sensor.nano_color_2_airing")
assert airing_entity is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/compit/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 62,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/bsblan/button.py | """Button platform for BSB-Lan integration."""
from __future__ import annotations
from homeassistant.components.button import ButtonEntity, ButtonEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import BSBLanConfigEntry, BSBLanData
from .coordinator import BSBLanFastCoordinator
from .entity import BSBLanEntity
from .helpers import async_sync_device_time
PARALLEL_UPDATES = 1
BUTTON_DESCRIPTIONS: tuple[ButtonEntityDescription, ...] = (
ButtonEntityDescription(
key="sync_time",
translation_key="sync_time",
entity_category=EntityCategory.CONFIG,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: BSBLanConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up BSB-Lan button entities from a config entry."""
data = entry.runtime_data
async_add_entities(
BSBLanButtonEntity(data.fast_coordinator, data, description)
for description in BUTTON_DESCRIPTIONS
)
class BSBLanButtonEntity(BSBLanEntity, ButtonEntity):
"""Defines a BSB-Lan button entity."""
entity_description: ButtonEntityDescription
def __init__(
self,
coordinator: BSBLanFastCoordinator,
data: BSBLanData,
description: ButtonEntityDescription,
) -> None:
"""Initialize BSB-Lan button entity."""
super().__init__(coordinator, data)
self.entity_description = description
self._attr_unique_id = f"{data.device.MAC}-{description.key}"
self._data = data
async def async_press(self) -> None:
"""Handle the button press."""
await async_sync_device_time(self._data.client, self._data.device.name)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/bsblan/button.py",
"license": "Apache License 2.0",
"lines": 46,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/bsblan/helpers.py | """Helper functions for BSB-Lan integration."""
from __future__ import annotations
from bsblan import BSBLAN, BSBLANError
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util import dt as dt_util
from .const import DOMAIN
async def async_sync_device_time(client: BSBLAN, device_name: str) -> None:
"""Synchronize BSB-LAN device time with Home Assistant.
Only updates if device time differs from Home Assistant time.
Args:
client: The BSB-LAN client instance.
device_name: The name of the device (used in error messages).
Raises:
HomeAssistantError: If the time sync operation fails.
"""
try:
device_time = await client.time()
current_time = dt_util.now()
current_time_str = current_time.strftime("%d.%m.%Y %H:%M:%S")
# Only sync if device time differs from HA time
if device_time.time.value != current_time_str:
await client.set_time(current_time_str)
except BSBLANError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="sync_time_failed",
translation_placeholders={
"device_name": device_name,
"error": str(err),
},
) from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/bsblan/helpers.py",
"license": "Apache License 2.0",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/bsblan/test_button.py | """Tests for the BSB-Lan button platform."""
from unittest.mock import MagicMock
from bsblan import BSBLANError, DeviceTime
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from . import setup_with_selected_platforms
from tests.common import MockConfigEntry, snapshot_platform
ENTITY_SYNC_TIME = "button.bsb_lan_sync_time"
async def test_button_entity_properties(
hass: HomeAssistant,
mock_bsblan: MagicMock,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the button entity properties."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.BUTTON])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_button_press_syncs_time(
hass: HomeAssistant,
mock_bsblan: MagicMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test pressing the sync time button syncs the device time."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.BUTTON])
# Mock device time that differs from HA time
mock_bsblan.time.return_value = DeviceTime.model_validate_json(
'{"time": {"name": "Time", "value": "01.01.2020 00:00:00", "unit": "", "desc": "", "dataType": 0, "readonly": 0, "error": 0}}'
)
# Press the button
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: ENTITY_SYNC_TIME},
blocking=True,
)
# Verify time() was called to check current device time
assert mock_bsblan.time.called
# Verify set_time() was called with current HA time
current_time_str = dt_util.now().strftime("%d.%m.%Y %H:%M:%S")
mock_bsblan.set_time.assert_called_once_with(current_time_str)
async def test_button_press_no_update_when_same(
hass: HomeAssistant,
mock_bsblan: MagicMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test button press doesn't update when time matches."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.BUTTON])
# Mock device time that matches HA time
current_time_str = dt_util.now().strftime("%d.%m.%Y %H:%M:%S")
mock_bsblan.time.return_value = DeviceTime.model_validate_json(
f'{{"time": {{"name": "Time", "value": "{current_time_str}", "unit": "", "desc": "", "dataType": 0, "readonly": 0, "error": 0}}}}'
)
# Press the button
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: ENTITY_SYNC_TIME},
blocking=True,
)
# Verify time() was called
assert mock_bsblan.time.called
# Verify set_time() was NOT called since times match
assert not mock_bsblan.set_time.called
async def test_button_press_error_handling(
hass: HomeAssistant,
mock_bsblan: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test button press handles errors gracefully."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.BUTTON])
# Mock time() to raise an error
mock_bsblan.time.side_effect = BSBLANError("Connection failed")
# Press the button - should raise HomeAssistantError
with pytest.raises(HomeAssistantError, match="Failed to sync time"):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: ENTITY_SYNC_TIME},
blocking=True,
)
async def test_button_press_set_time_error(
hass: HomeAssistant,
mock_bsblan: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test button press handles set_time errors."""
await setup_with_selected_platforms(hass, mock_config_entry, [Platform.BUTTON])
# Mock device time that differs
mock_bsblan.time.return_value = DeviceTime.model_validate_json(
'{"time": {"name": "Time", "value": "01.01.2020 00:00:00", "unit": "", "desc": "", "dataType": 0, "readonly": 0, "error": 0}}'
)
# Mock set_time() to raise an error
mock_bsblan.set_time.side_effect = BSBLANError("Write failed")
# Press the button - should raise HomeAssistantError
with pytest.raises(HomeAssistantError, match="Failed to sync time"):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: ENTITY_SYNC_TIME},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/bsblan/test_button.py",
"license": "Apache License 2.0",
"lines": 111,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/homematicip_cloud/diagnostics.py | """Diagnostics support for HomematicIP Cloud."""
from __future__ import annotations
import json
from typing import Any
from homematicip.base.helpers import handle_config
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.core import HomeAssistant
from .hap import HomematicIPConfigEntry
TO_REDACT_CONFIG = {"city", "latitude", "longitude", "refreshToken"}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: HomematicIPConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
hap = config_entry.runtime_data
json_state = await hap.home.download_configuration_async()
anonymized = handle_config(json_state, anonymize=True)
config = json.loads(anonymized)
return async_redact_data(config, TO_REDACT_CONFIG)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/homematicip_cloud/diagnostics.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/homematicip_cloud/test_diagnostics.py | """Tests for HomematicIP Cloud diagnostics."""
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.homematicip_cloud.const import DOMAIN
from homeassistant.core import HomeAssistant
from tests.common import async_load_json_object_fixture
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_hap_with_service,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics for config entry."""
mock_hap_with_service.home.download_configuration_async.return_value = (
await async_load_json_object_fixture(hass, "diagnostics.json", DOMAIN)
)
entry = hass.config_entries.async_entries(DOMAIN)[0]
result = await get_diagnostics_for_config_entry(hass, hass_client, entry)
assert result == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homematicip_cloud/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/econet/select.py | """Support for Rheem EcoNet thermostats with variable fan speeds and fan modes."""
from __future__ import annotations
from pyeconet.equipment import EquipmentType
from pyeconet.equipment.thermostat import Thermostat, ThermostatFanMode
from homeassistant.components.select import SelectEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import EconetConfigEntry
from .entity import EcoNetEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: EconetConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the econet thermostat select entity."""
equipment = entry.runtime_data
async_add_entities(
EconetFanModeSelect(thermostat)
for thermostat in equipment[EquipmentType.THERMOSTAT]
if thermostat.supports_fan_mode
)
class EconetFanModeSelect(EcoNetEntity[Thermostat], SelectEntity):
"""Select entity."""
def __init__(self, thermostat: Thermostat) -> None:
"""Initialize EcoNet platform."""
super().__init__(thermostat)
self._attr_name = f"{thermostat.device_name} fan mode"
self._attr_unique_id = (
f"{thermostat.device_id}_{thermostat.device_name}_fan_mode"
)
@property
def options(self) -> list[str]:
"""Return available select options."""
return [e.value for e in self._econet.fan_modes]
@property
def current_option(self) -> str:
"""Return current select option."""
return self._econet.fan_mode.value
def select_option(self, option: str) -> None:
"""Set the selected option."""
self._econet.set_fan_mode(ThermostatFanMode.by_string(option))
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/econet/select.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/proxmoxve/button.py | """Button platform for Proxmox VE."""
from __future__ import annotations
from abc import abstractmethod
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any
from proxmoxer import AuthenticationError
from proxmoxer.core import ResourceException
import requests
from requests.exceptions import ConnectTimeout, SSLError
from homeassistant.components.button import (
ButtonDeviceClass,
ButtonEntity,
ButtonEntityDescription,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN
from .coordinator import ProxmoxConfigEntry, ProxmoxCoordinator, ProxmoxNodeData
from .entity import ProxmoxContainerEntity, ProxmoxNodeEntity, ProxmoxVMEntity
@dataclass(frozen=True, kw_only=True)
class ProxmoxNodeButtonNodeEntityDescription(ButtonEntityDescription):
"""Class to hold Proxmox node button description."""
press_action: Callable[[ProxmoxCoordinator, str], None]
@dataclass(frozen=True, kw_only=True)
class ProxmoxVMButtonEntityDescription(ButtonEntityDescription):
"""Class to hold Proxmox VM button description."""
press_action: Callable[[ProxmoxCoordinator, str, int], None]
@dataclass(frozen=True, kw_only=True)
class ProxmoxContainerButtonEntityDescription(ButtonEntityDescription):
"""Class to hold Proxmox container button description."""
press_action: Callable[[ProxmoxCoordinator, str, int], None]
NODE_BUTTONS: tuple[ProxmoxNodeButtonNodeEntityDescription, ...] = (
ProxmoxNodeButtonNodeEntityDescription(
key="reboot",
press_action=lambda coordinator, node: coordinator.proxmox.nodes(
node
).status.post(command="reboot"),
entity_category=EntityCategory.CONFIG,
device_class=ButtonDeviceClass.RESTART,
),
ProxmoxNodeButtonNodeEntityDescription(
key="shutdown",
translation_key="shutdown",
press_action=lambda coordinator, node: coordinator.proxmox.nodes(
node
).status.post(command="shutdown"),
entity_category=EntityCategory.CONFIG,
),
ProxmoxNodeButtonNodeEntityDescription(
key="start_all",
translation_key="start_all",
press_action=lambda coordinator, node: coordinator.proxmox.nodes(
node
).startall.post(),
entity_category=EntityCategory.CONFIG,
),
ProxmoxNodeButtonNodeEntityDescription(
key="stop_all",
translation_key="stop_all",
press_action=lambda coordinator, node: coordinator.proxmox.nodes(
node
).stopall.post(),
entity_category=EntityCategory.CONFIG,
),
)
VM_BUTTONS: tuple[ProxmoxVMButtonEntityDescription, ...] = (
ProxmoxVMButtonEntityDescription(
key="start",
translation_key="start",
press_action=lambda coordinator, node, vmid: (
coordinator.proxmox.nodes(node).qemu(vmid).status.start.post()
),
entity_category=EntityCategory.CONFIG,
),
ProxmoxVMButtonEntityDescription(
key="stop",
translation_key="stop",
press_action=lambda coordinator, node, vmid: (
coordinator.proxmox.nodes(node).qemu(vmid).status.stop.post()
),
entity_category=EntityCategory.CONFIG,
),
ProxmoxVMButtonEntityDescription(
key="restart",
press_action=lambda coordinator, node, vmid: (
coordinator.proxmox.nodes(node).qemu(vmid).status.restart.post()
),
entity_category=EntityCategory.CONFIG,
device_class=ButtonDeviceClass.RESTART,
),
ProxmoxVMButtonEntityDescription(
key="hibernate",
translation_key="hibernate",
press_action=lambda coordinator, node, vmid: (
coordinator.proxmox.nodes(node).qemu(vmid).status.hibernate.post()
),
entity_category=EntityCategory.CONFIG,
),
ProxmoxVMButtonEntityDescription(
key="reset",
translation_key="reset",
press_action=lambda coordinator, node, vmid: (
coordinator.proxmox.nodes(node).qemu(vmid).status.reset.post()
),
entity_category=EntityCategory.CONFIG,
),
)
CONTAINER_BUTTONS: tuple[ProxmoxContainerButtonEntityDescription, ...] = (
ProxmoxContainerButtonEntityDescription(
key="start",
translation_key="start",
press_action=lambda coordinator, node, vmid: (
coordinator.proxmox.nodes(node).lxc(vmid).status.start.post()
),
entity_category=EntityCategory.CONFIG,
),
ProxmoxContainerButtonEntityDescription(
key="stop",
translation_key="stop",
press_action=lambda coordinator, node, vmid: (
coordinator.proxmox.nodes(node).lxc(vmid).status.stop.post()
),
entity_category=EntityCategory.CONFIG,
),
ProxmoxContainerButtonEntityDescription(
key="restart",
press_action=lambda coordinator, node, vmid: (
coordinator.proxmox.nodes(node).lxc(vmid).status.restart.post()
),
entity_category=EntityCategory.CONFIG,
device_class=ButtonDeviceClass.RESTART,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: ProxmoxConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up ProxmoxVE buttons."""
coordinator = entry.runtime_data
def _async_add_new_nodes(nodes: list[ProxmoxNodeData]) -> None:
"""Add new node buttons."""
async_add_entities(
ProxmoxNodeButtonEntity(coordinator, entity_description, node)
for node in nodes
for entity_description in NODE_BUTTONS
)
def _async_add_new_vms(
vms: list[tuple[ProxmoxNodeData, dict[str, Any]]],
) -> None:
"""Add new VM buttons."""
async_add_entities(
ProxmoxVMButtonEntity(coordinator, entity_description, vm, node_data)
for (node_data, vm) in vms
for entity_description in VM_BUTTONS
)
def _async_add_new_containers(
containers: list[tuple[ProxmoxNodeData, dict[str, Any]]],
) -> None:
"""Add new container buttons."""
async_add_entities(
ProxmoxContainerButtonEntity(
coordinator, entity_description, container, node_data
)
for (node_data, container) in containers
for entity_description in CONTAINER_BUTTONS
)
coordinator.new_nodes_callbacks.append(_async_add_new_nodes)
coordinator.new_vms_callbacks.append(_async_add_new_vms)
coordinator.new_containers_callbacks.append(_async_add_new_containers)
_async_add_new_nodes(
[
node_data
for node_data in coordinator.data.values()
if node_data.node["node"] in coordinator.known_nodes
]
)
_async_add_new_vms(
[
(node_data, vm_data)
for node_data in coordinator.data.values()
for vmid, vm_data in node_data.vms.items()
if (node_data.node["node"], vmid) in coordinator.known_vms
]
)
_async_add_new_containers(
[
(node_data, container_data)
for node_data in coordinator.data.values()
for vmid, container_data in node_data.containers.items()
if (node_data.node["node"], vmid) in coordinator.known_containers
]
)
class ProxmoxBaseButton(ButtonEntity):
"""Common base for Proxmox buttons. Basically to ensure the async_press logic isn't duplicated."""
entity_description: ButtonEntityDescription
coordinator: ProxmoxCoordinator
@abstractmethod
async def _async_press_call(self) -> None:
"""Abstract method used per Proxmox button class."""
async def async_press(self) -> None:
"""Trigger the Proxmox button press service."""
try:
await self._async_press_call()
except AuthenticationError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="cannot_connect_no_details",
) from err
except SSLError as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="invalid_auth_no_details",
) from err
except ConnectTimeout as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="timeout_connect_no_details",
) from err
except (ResourceException, requests.exceptions.ConnectionError) as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="api_error_no_details",
) from err
class ProxmoxNodeButtonEntity(ProxmoxNodeEntity, ProxmoxBaseButton):
"""Represents a Proxmox Node button entity."""
entity_description: ProxmoxNodeButtonNodeEntityDescription
async def _async_press_call(self) -> None:
"""Execute the node button action via executor."""
await self.hass.async_add_executor_job(
self.entity_description.press_action,
self.coordinator,
self._node_data.node["node"],
)
class ProxmoxVMButtonEntity(ProxmoxVMEntity, ProxmoxBaseButton):
"""Represents a Proxmox VM button entity."""
entity_description: ProxmoxVMButtonEntityDescription
async def _async_press_call(self) -> None:
"""Execute the VM button action via executor."""
await self.hass.async_add_executor_job(
self.entity_description.press_action,
self.coordinator,
self._node_name,
self.vm_data["vmid"],
)
class ProxmoxContainerButtonEntity(ProxmoxContainerEntity, ProxmoxBaseButton):
"""Represents a Proxmox Container button entity."""
entity_description: ProxmoxContainerButtonEntityDescription
async def _async_press_call(self) -> None:
"""Execute the container button action via executor."""
await self.hass.async_add_executor_job(
self.entity_description.press_action,
self.coordinator,
self._node_name,
self.container_data["vmid"],
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/proxmoxve/button.py",
"license": "Apache License 2.0",
"lines": 259,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/proxmoxve/test_button.py | """Tests for the ProxmoxVE button platform."""
from __future__ import annotations
from unittest.mock import MagicMock, patch
from proxmoxer import AuthenticationError
from proxmoxer.core import ResourceException
import pytest
from requests.exceptions import ConnectTimeout, SSLError
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.button import SERVICE_PRESS
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
BUTTON_DOMAIN = "button"
@pytest.fixture(autouse=True)
def enable_all_entities(entity_registry_enabled_by_default: None) -> None:
"""Enable all entities for button tests."""
async def test_all_button_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Snapshot test for all ProxmoxVE button entities."""
with patch(
"homeassistant.components.proxmoxve.PLATFORMS",
[Platform.BUTTON],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
@pytest.mark.parametrize(
("entity_id", "command"),
[
("button.pve1_restart", "reboot"),
("button.pve1_shutdown", "shutdown"),
],
)
async def test_node_buttons(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
command: str,
) -> None:
"""Test pressing a ProxmoxVE node action button triggers the correct API call."""
await setup_integration(hass, mock_config_entry)
method_mock = mock_proxmox_client._node_mock.status.post
pre_calls = len(method_mock.mock_calls)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert len(method_mock.mock_calls) == pre_calls + 1
method_mock.assert_called_with(command=command)
@pytest.mark.parametrize(
("entity_id", "attr"),
[
("button.pve1_start_all", "startall"),
("button.pve1_stop_all", "stopall"),
],
)
async def test_node_startall_stopall_buttons(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
attr: str,
) -> None:
"""Test pressing a ProxmoxVE node start all / stop all button triggers the correct API call."""
await setup_integration(hass, mock_config_entry)
method_mock = getattr(mock_proxmox_client._node_mock, attr).post
pre_calls = len(method_mock.mock_calls)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert len(method_mock.mock_calls) == pre_calls + 1
@pytest.mark.parametrize(
("entity_id", "vmid", "action"),
[
("button.vm_web_start", 100, "start"),
("button.vm_web_stop", 100, "stop"),
("button.vm_web_restart", 100, "restart"),
("button.vm_web_hibernate", 100, "hibernate"),
("button.vm_web_reset", 100, "reset"),
],
)
async def test_vm_buttons(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
vmid: int,
action: str,
) -> None:
"""Test pressing a ProxmoxVE VM action button triggers the correct API call."""
await setup_integration(hass, mock_config_entry)
mock_proxmox_client._node_mock.qemu(vmid)
method_mock = getattr(mock_proxmox_client._qemu_mocks[vmid].status, action).post
pre_calls = len(method_mock.mock_calls)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert len(method_mock.mock_calls) == pre_calls + 1
@pytest.mark.parametrize(
("entity_id", "vmid", "action"),
[
("button.ct_nginx_start", 200, "start"),
("button.ct_nginx_stop", 200, "stop"),
("button.ct_nginx_restart", 200, "restart"),
],
)
async def test_container_buttons(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
vmid: int,
action: str,
) -> None:
"""Test pressing a ProxmoxVE container action button triggers the correct API call."""
await setup_integration(hass, mock_config_entry)
mock_proxmox_client._node_mock.lxc(vmid)
method_mock = getattr(mock_proxmox_client._lxc_mocks[vmid].status, action).post
pre_calls = len(method_mock.mock_calls)
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert len(method_mock.mock_calls) == pre_calls + 1
@pytest.mark.parametrize(
("entity_id", "exception"),
[
("button.pve1_restart", AuthenticationError("auth failed")),
("button.pve1_restart", SSLError("ssl error")),
("button.pve1_restart", ConnectTimeout("timeout")),
("button.pve1_shutdown", ResourceException(500, "error", {})),
],
)
async def test_node_buttons_exceptions(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
exception: Exception,
) -> None:
"""Test that ProxmoxVE node button errors are raised as HomeAssistantError."""
await setup_integration(hass, mock_config_entry)
mock_proxmox_client._node_mock.status.post.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
@pytest.mark.parametrize(
("entity_id", "vmid", "action", "exception"),
[
(
"button.vm_web_start",
100,
"start",
AuthenticationError("auth failed"),
),
(
"button.vm_web_start",
100,
"start",
SSLError("ssl error"),
),
(
"button.vm_web_hibernate",
100,
"hibernate",
ConnectTimeout("timeout"),
),
(
"button.vm_web_reset",
100,
"reset",
ResourceException(500, "error", {}),
),
],
)
async def test_vm_buttons_exceptions(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
vmid: int,
action: str,
exception: Exception,
) -> None:
"""Test that ProxmoxVE VM button errors are raised as HomeAssistantError."""
await setup_integration(hass, mock_config_entry)
mock_proxmox_client._node_mock.qemu(vmid)
getattr(
mock_proxmox_client._qemu_mocks[vmid].status, action
).post.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
@pytest.mark.parametrize(
("entity_id", "vmid", "action", "exception"),
[
(
"button.ct_nginx_start",
200,
"start",
AuthenticationError("auth failed"),
),
(
"button.ct_nginx_start",
200,
"start",
SSLError("ssl error"),
),
(
"button.ct_nginx_restart",
200,
"restart",
ConnectTimeout("timeout"),
),
(
"button.ct_nginx_stop",
200,
"stop",
ResourceException(500, "error", {}),
),
],
)
async def test_container_buttons_exceptions(
hass: HomeAssistant,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
vmid: int,
action: str,
exception: Exception,
) -> None:
"""Test that ProxmoxVE container button errors are raised as HomeAssistantError."""
await setup_integration(hass, mock_config_entry)
mock_proxmox_client._node_mock.lxc(vmid)
getattr(
mock_proxmox_client._lxc_mocks[vmid].status, action
).post.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/proxmoxve/test_button.py",
"license": "Apache License 2.0",
"lines": 272,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/ecovacs/test_vacuum.py | """Tests for Ecovacs vacuum entities."""
from dataclasses import asdict
import logging
from deebot_client.events import CachedMapInfoEvent, Event, RoomsEvent
from deebot_client.events.map import Map
from deebot_client.models import CleanMode, Room
from deebot_client.rs.map import RotationAngle # pylint: disable=no-name-in-module
import pytest
from homeassistant.components import vacuum
from homeassistant.components.ecovacs.controller import EcovacsController
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from .util import notify_and_wait
from tests.typing import WebSocketGenerator
pytestmark = [pytest.mark.usefixtures("init_integration")]
@pytest.fixture
def platforms() -> Platform | list[Platform]:
"""Platforms, which should be loaded during the test."""
return Platform.VACUUM
def _prepare_test(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
entity_id: str,
) -> None:
entity_registry.async_update_entity_options(
entity_id,
vacuum.DOMAIN,
{
"area_mapping": {
"area_kitchen": ["1_1"],
"area_living_room": ["1_2"],
"area_bedroom": ["2_1"],
},
"last_seen_segments": [
{"id": "1_1", "name": "Kitchen", "group": "Main map"},
{"id": "1_2", "name": "Living room", "group": "Main map"},
{"id": "2_1", "name": "Bedroom", "group": "Second map"},
],
},
)
vacuum_obj = hass.data[vacuum.DATA_COMPONENT].get_entity(entity_id)
assert vacuum_obj.last_seen_segments == [
vacuum.Segment(id="1_1", name="Kitchen", group="Main map"),
vacuum.Segment(id="1_2", name="Living room", group="Main map"),
vacuum.Segment(id="2_1", name="Bedroom", group="Second map"),
]
assert vacuum_obj.supported_features & vacuum.VacuumEntityFeature.CLEAN_AREA
@pytest.mark.parametrize(("device_fixture", "entity_id"), [("qhe2o2", "vacuum.dusty")])
async def test_clean_area(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
controller: EcovacsController,
entity_id: str,
) -> None:
"""Test clean_area service call."""
_prepare_test(hass, entity_registry, entity_id)
device = controller.devices[0]
event_bus = device.events
await notify_and_wait(
hass,
event_bus,
CachedMapInfoEvent(
{
Map(
id="1",
name="Main map",
using=True,
built=True,
angle=RotationAngle.DEG_0,
),
Map(
id="2",
name="Second map",
using=False,
built=True,
angle=RotationAngle.DEG_0,
),
}
),
)
device._execute_command.reset_mock()
await hass.services.async_call(
vacuum.DOMAIN,
vacuum.SERVICE_CLEAN_AREA,
{
ATTR_ENTITY_ID: entity_id,
"cleaning_area_id": ["area_living_room", "area_kitchen"],
},
blocking=True,
)
assert device._execute_command.call_count == 1
command = device._execute_command.call_args.args[0]
expected_command = device.capabilities.clean.action.area(
CleanMode.SPOT_AREA, [2, 1], 1
)
assert command == expected_command
@pytest.mark.parametrize(("device_fixture", "entity_id"), [("qhe2o2", "vacuum.dusty")])
async def test_clean_area_no_map(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
caplog: pytest.LogCaptureFixture,
controller: EcovacsController,
entity_id: str,
) -> None:
"""Test clean_area service call logs warning when no map info is available."""
_prepare_test(hass, entity_registry, entity_id)
device = controller.devices[0]
device._execute_command.reset_mock()
await hass.services.async_call(
vacuum.DOMAIN,
vacuum.SERVICE_CLEAN_AREA,
{
ATTR_ENTITY_ID: entity_id,
"cleaning_area_id": ["area_living_room", "area_kitchen"],
},
blocking=True,
)
assert caplog.record_tuples == [
(
"homeassistant.components.ecovacs.vacuum",
logging.WARNING,
"No map information available, cannot clean segments",
),
]
assert device._execute_command.call_count == 0
@pytest.mark.parametrize(("device_fixture", "entity_id"), [("qhe2o2", "vacuum.dusty")])
async def test_clean_area_invalid_map_id(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
caplog: pytest.LogCaptureFixture,
controller: EcovacsController,
entity_id: str,
) -> None:
"""Test clean_area service call logs warning when invalid map ID is provided."""
_prepare_test(hass, entity_registry, entity_id)
device = controller.devices[0]
event_bus = device.events
await notify_and_wait(
hass,
event_bus,
CachedMapInfoEvent(
{
Map(
id="2",
name="Second map",
using=False,
built=True,
angle=RotationAngle.DEG_0,
),
}
),
)
device._execute_command.reset_mock()
caplog.clear()
await hass.services.async_call(
vacuum.DOMAIN,
vacuum.SERVICE_CLEAN_AREA,
{
ATTR_ENTITY_ID: entity_id,
"cleaning_area_id": ["area_living_room", "area_kitchen"],
},
blocking=True,
)
assert caplog.record_tuples == [
(
"homeassistant.components.ecovacs.vacuum",
logging.WARNING,
"Map ID 1 not found in available maps",
),
# twice as both areas reference the same missing map ID
(
"homeassistant.components.ecovacs.vacuum",
logging.WARNING,
"Map ID 1 not found in available maps",
),
(
"homeassistant.components.ecovacs.vacuum",
logging.WARNING,
"No valid segments to clean after validation, skipping clean segments command",
),
]
assert device._execute_command.call_count == 0
@pytest.mark.parametrize(("device_fixture", "entity_id"), [("qhe2o2", "vacuum.dusty")])
async def test_clean_area_room_from_not_current_map(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
caplog: pytest.LogCaptureFixture,
controller: EcovacsController,
entity_id: str,
) -> None:
"""Test clean_area service call logs warning when room is from a not current map."""
_prepare_test(hass, entity_registry, entity_id)
device = controller.devices[0]
event_bus = device.events
await notify_and_wait(
hass,
event_bus,
CachedMapInfoEvent(
{
Map(
id="1",
name="Main map",
using=True,
built=True,
angle=RotationAngle.DEG_0,
),
Map(
id="2",
name="Second map",
using=False,
built=True,
angle=RotationAngle.DEG_0,
),
}
),
)
await notify_and_wait(
hass,
event_bus,
RoomsEvent(
map_id="1",
rooms=[
Room(name="Kitchen", id=1, coordinates=""),
Room(name="Living room", id=2, coordinates=""),
],
),
)
device._execute_command.reset_mock()
caplog.clear()
await hass.services.async_call(
vacuum.DOMAIN,
vacuum.SERVICE_CLEAN_AREA,
{
ATTR_ENTITY_ID: entity_id,
"cleaning_area_id": ["area_bedroom", "area_kitchen"],
},
blocking=True,
)
assert caplog.record_tuples == [
(
"homeassistant.components.ecovacs.vacuum",
logging.WARNING,
'Map "Second map" is not currently selected, skipping segment "Bedroom" (1)',
),
]
assert device._execute_command.call_count == 1
command = device._execute_command.call_args.args[0]
expected_command = device.capabilities.clean.action.area(
CleanMode.SPOT_AREA, [1], 1
)
assert command == expected_command
@pytest.mark.parametrize(
"events",
[
(
CachedMapInfoEvent(
{
Map(
id="1",
name="Main map",
using=True,
built=True,
angle=RotationAngle.DEG_0,
),
Map(
id="2",
name="Second map",
using=False,
built=True,
angle=RotationAngle.DEG_0,
),
}
),
RoomsEvent(
map_id="1",
rooms=[
Room(name="Kitchen", id=1, coordinates=""),
],
),
),
(
CachedMapInfoEvent(
{
Map(
id="1",
name="Main map",
using=True,
built=True,
angle=RotationAngle.DEG_0,
),
}
),
RoomsEvent(
map_id="1",
rooms=[
Room(name="Kitchen", id=1, coordinates=""),
Room(name="Living room", id=2, coordinates=""),
],
),
),
(
CachedMapInfoEvent(
{
Map(
id="1",
name="Main map",
using=True,
built=True,
angle=RotationAngle.DEG_0,
),
Map(
id="2",
name="Second map",
using=False,
built=True,
angle=RotationAngle.DEG_0,
),
}
),
RoomsEvent(
map_id="1",
rooms=[
Room(name="Kitchen", id=1, coordinates=""),
Room(name="Living room", id=2, coordinates=""),
Room(name="Bedroom", id=3, coordinates=""),
],
),
),
],
ids=[
"room removed",
"map removed",
"room added",
],
)
@pytest.mark.parametrize(("device_fixture", "entity_id"), [("qhe2o2", "vacuum.dusty")])
async def test_raise_segment_changed_issue(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
controller: EcovacsController,
entity_id: str,
events: tuple[Event, ...],
) -> None:
"""Test that the issue is raised on segment changes."""
_prepare_test(hass, entity_registry, entity_id)
device = controller.devices[0]
event_bus = device.events
for event in events:
await notify_and_wait(hass, event_bus, event)
entity_entry = entity_registry.async_get(entity_id)
issue_id = f"{vacuum.ISSUE_SEGMENTS_CHANGED}_{entity_entry.id}"
issue = ir.async_get(hass).async_get_issue(vacuum.DOMAIN, issue_id)
assert issue is not None
@pytest.mark.parametrize(
("events", "expected_segments", "expected_log_messages"),
[
((), [], []),
(
(
CachedMapInfoEvent(
{
Map(
id="1",
name="Main map",
using=True,
built=True,
angle=RotationAngle.DEG_0,
),
}
),
RoomsEvent(
map_id="2",
rooms=[
Room(name="Kitchen", id=1, coordinates=""),
Room(name="Living room", id=2, coordinates=""),
],
),
),
[],
[
(
"homeassistant.components.ecovacs.vacuum",
logging.WARNING,
"Map ID 2 not found in available maps",
)
],
),
(
(
CachedMapInfoEvent(
{
Map(
id="1",
name="Main map",
using=True,
built=True,
angle=RotationAngle.DEG_0,
),
}
),
RoomsEvent(
map_id="1",
rooms=[
Room(name="Kitchen", id=1, coordinates=""),
Room(name="Living room", id=2, coordinates=""),
],
),
),
[
vacuum.Segment(id="1_1", name="Kitchen", group="Main map"),
vacuum.Segment(id="1_2", name="Living room", group="Main map"),
],
[],
),
],
ids=[
"no room event available",
"invalid map ID in room event",
"room added",
],
)
@pytest.mark.parametrize(("device_fixture", "entity_id"), [("qhe2o2", "vacuum.dusty")])
async def test_get_segments(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
caplog: pytest.LogCaptureFixture,
controller: EcovacsController,
entity_id: str,
events: tuple[Event, ...],
expected_segments: list[vacuum.Segment],
expected_log_messages: list[tuple[str, int, str]],
) -> None:
"""Test vacuum/get_segments websocket command."""
device = controller.devices[0]
event_bus = device.events
for event in events:
await notify_and_wait(hass, event_bus, event)
caplog.clear()
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "vacuum/get_segments", "entity_id": entity_id}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {"segments": [asdict(seg) for seg in expected_segments]}
for log_message in expected_log_messages:
assert log_message in caplog.record_tuples
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ecovacs/test_vacuum.py",
"license": "Apache License 2.0",
"lines": 448,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/liebherr/select.py | """Select platform for Liebherr integration."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from dataclasses import dataclass
from enum import StrEnum
from typing import TYPE_CHECKING, Any
from pyliebherrhomeapi import (
BioFreshPlusControl,
BioFreshPlusMode,
HydroBreezeControl,
HydroBreezeMode,
IceMakerControl,
IceMakerMode,
ZonePosition,
)
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN
from .coordinator import LiebherrConfigEntry, LiebherrCoordinator
from .entity import ZONE_POSITION_MAP, LiebherrEntity
PARALLEL_UPDATES = 1
type SelectControl = IceMakerControl | HydroBreezeControl | BioFreshPlusControl
@dataclass(frozen=True, kw_only=True)
class LiebherrSelectEntityDescription(SelectEntityDescription):
"""Describes a Liebherr select entity."""
control_type: type[SelectControl]
mode_enum: type[StrEnum]
current_mode_fn: Callable[[SelectControl], StrEnum | str | None]
options_fn: Callable[[SelectControl], list[str]]
set_fn: Callable[[LiebherrCoordinator, int, StrEnum], Coroutine[Any, Any, None]]
def _ice_maker_options(control: SelectControl) -> list[str]:
"""Return available ice maker options."""
if TYPE_CHECKING:
assert isinstance(control, IceMakerControl)
options = [IceMakerMode.OFF.value, IceMakerMode.ON.value]
if control.has_max_ice:
options.append(IceMakerMode.MAX_ICE.value)
return options
def _hydro_breeze_options(control: SelectControl) -> list[str]:
"""Return available HydroBreeze options."""
return [mode.value for mode in HydroBreezeMode]
def _bio_fresh_plus_options(control: SelectControl) -> list[str]:
"""Return available BioFresh-Plus options."""
if TYPE_CHECKING:
assert isinstance(control, BioFreshPlusControl)
return [
mode.value
for mode in control.supported_modes
if isinstance(mode, BioFreshPlusMode)
]
SELECT_TYPES: list[LiebherrSelectEntityDescription] = [
LiebherrSelectEntityDescription(
key="ice_maker",
translation_key="ice_maker",
control_type=IceMakerControl,
mode_enum=IceMakerMode,
current_mode_fn=lambda c: c.ice_maker_mode, # type: ignore[union-attr]
options_fn=_ice_maker_options,
set_fn=lambda coordinator, zone_id, mode: coordinator.client.set_ice_maker(
device_id=coordinator.device_id,
zone_id=zone_id,
mode=mode, # type: ignore[arg-type]
),
),
LiebherrSelectEntityDescription(
key="hydro_breeze",
translation_key="hydro_breeze",
control_type=HydroBreezeControl,
mode_enum=HydroBreezeMode,
current_mode_fn=lambda c: c.current_mode, # type: ignore[union-attr]
options_fn=_hydro_breeze_options,
set_fn=lambda coordinator, zone_id, mode: coordinator.client.set_hydro_breeze(
device_id=coordinator.device_id,
zone_id=zone_id,
mode=mode, # type: ignore[arg-type]
),
),
LiebherrSelectEntityDescription(
key="bio_fresh_plus",
translation_key="bio_fresh_plus",
control_type=BioFreshPlusControl,
mode_enum=BioFreshPlusMode,
current_mode_fn=lambda c: c.current_mode, # type: ignore[union-attr]
options_fn=_bio_fresh_plus_options,
set_fn=lambda coordinator, zone_id, mode: coordinator.client.set_bio_fresh_plus(
device_id=coordinator.device_id,
zone_id=zone_id,
mode=mode, # type: ignore[arg-type]
),
),
]
def _create_select_entities(
coordinators: list[LiebherrCoordinator],
) -> list[LiebherrSelectEntity]:
"""Create select entities for the given coordinators."""
entities: list[LiebherrSelectEntity] = []
for coordinator in coordinators:
has_multiple_zones = len(coordinator.data.get_temperature_controls()) > 1
for control in coordinator.data.controls:
for description in SELECT_TYPES:
if isinstance(control, description.control_type):
if TYPE_CHECKING:
assert isinstance(
control,
IceMakerControl | HydroBreezeControl | BioFreshPlusControl,
)
entities.append(
LiebherrSelectEntity(
coordinator=coordinator,
description=description,
zone_id=control.zone_id,
has_multiple_zones=has_multiple_zones,
)
)
return entities
async def async_setup_entry(
hass: HomeAssistant,
entry: LiebherrConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Liebherr select entities."""
async_add_entities(
_create_select_entities(list(entry.runtime_data.coordinators.values()))
)
@callback
def _async_new_device(coordinators: list[LiebherrCoordinator]) -> None:
"""Add select entities for new devices."""
async_add_entities(_create_select_entities(coordinators))
entry.async_on_unload(
async_dispatcher_connect(
hass, f"{DOMAIN}_new_device_{entry.entry_id}", _async_new_device
)
)
class LiebherrSelectEntity(LiebherrEntity, SelectEntity):
"""Representation of a Liebherr select entity."""
entity_description: LiebherrSelectEntityDescription
def __init__(
self,
coordinator: LiebherrCoordinator,
description: LiebherrSelectEntityDescription,
zone_id: int,
has_multiple_zones: bool,
) -> None:
"""Initialize the select entity."""
super().__init__(coordinator)
self.entity_description = description
self._zone_id = zone_id
self._attr_unique_id = f"{coordinator.device_id}_{description.key}_{zone_id}"
# Set options from the control
control = self._select_control
if control is not None:
self._attr_options = description.options_fn(control)
# Add zone suffix only for multi-zone devices
if has_multiple_zones:
temp_controls = coordinator.data.get_temperature_controls()
if (
(tc := temp_controls.get(zone_id))
and isinstance(tc.zone_position, ZonePosition)
and (zone_key := ZONE_POSITION_MAP.get(tc.zone_position))
):
self._attr_translation_key = f"{description.translation_key}_{zone_key}"
@property
def _select_control(self) -> SelectControl | None:
"""Get the select control for this entity."""
for control in self.coordinator.data.controls:
if (
isinstance(control, self.entity_description.control_type)
and control.zone_id == self._zone_id
):
if TYPE_CHECKING:
assert isinstance(
control,
IceMakerControl | HydroBreezeControl | BioFreshPlusControl,
)
return control
return None
@property
def current_option(self) -> str | None:
"""Return the current selected option."""
control = self._select_control
if TYPE_CHECKING:
assert isinstance(
control,
IceMakerControl | HydroBreezeControl | BioFreshPlusControl,
)
mode = self.entity_description.current_mode_fn(control)
if isinstance(mode, StrEnum):
return mode.value
return None
@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and self._select_control is not None
async def async_select_option(self, option: str) -> None:
"""Change the selected option."""
mode = self.entity_description.mode_enum(option)
await self._async_send_command(
self.entity_description.set_fn(self.coordinator, self._zone_id, mode),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/liebherr/select.py",
"license": "Apache License 2.0",
"lines": 201,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/liebherr/test_select.py | """Test the Liebherr select platform."""
import copy
from datetime import timedelta
from typing import Any
from unittest.mock import MagicMock, patch
from freezegun.api import FrozenDateTimeFactory
from pyliebherrhomeapi import (
BioFreshPlusMode,
Device,
DeviceState,
DeviceType,
HydroBreezeControl,
HydroBreezeMode,
IceMakerControl,
IceMakerMode,
TemperatureControl,
TemperatureUnit,
ZonePosition,
)
from pyliebherrhomeapi.exceptions import LiebherrConnectionError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.select import (
ATTR_OPTION,
DOMAIN as SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from .conftest import MOCK_DEVICE, MOCK_DEVICE_STATE
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Fixture to specify platforms to test."""
return [Platform.SELECT]
@pytest.fixture(autouse=True)
def enable_all_entities(entity_registry_enabled_by_default: None) -> None:
"""Make sure all entities are enabled."""
@pytest.mark.usefixtures("init_integration")
async def test_selects(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test all select entities with multi-zone device."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("entity_id", "option", "method", "kwargs"),
[
(
"select.test_fridge_bottom_zone_icemaker",
"on",
"set_ice_maker",
{
"device_id": "test_device_id",
"zone_id": 2,
"mode": IceMakerMode.ON,
},
),
(
"select.test_fridge_bottom_zone_icemaker",
"max_ice",
"set_ice_maker",
{
"device_id": "test_device_id",
"zone_id": 2,
"mode": IceMakerMode.MAX_ICE,
},
),
(
"select.test_fridge_top_zone_hydrobreeze",
"high",
"set_hydro_breeze",
{
"device_id": "test_device_id",
"zone_id": 1,
"mode": HydroBreezeMode.HIGH,
},
),
(
"select.test_fridge_top_zone_hydrobreeze",
"off",
"set_hydro_breeze",
{
"device_id": "test_device_id",
"zone_id": 1,
"mode": HydroBreezeMode.OFF,
},
),
(
"select.test_fridge_top_zone_biofresh_plus",
"zero_minus_two",
"set_bio_fresh_plus",
{
"device_id": "test_device_id",
"zone_id": 1,
"mode": BioFreshPlusMode.ZERO_MINUS_TWO,
},
),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_select_service_calls(
hass: HomeAssistant,
mock_liebherr_client: MagicMock,
entity_id: str,
option: str,
method: str,
kwargs: dict[str, Any],
) -> None:
"""Test select option service calls."""
initial_call_count = mock_liebherr_client.get_device_state.call_count
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: option},
blocking=True,
)
getattr(mock_liebherr_client, method).assert_called_once_with(**kwargs)
# Verify coordinator refresh was triggered
assert mock_liebherr_client.get_device_state.call_count > initial_call_count
@pytest.mark.parametrize(
("entity_id", "method", "option"),
[
("select.test_fridge_bottom_zone_icemaker", "set_ice_maker", "off"),
("select.test_fridge_top_zone_hydrobreeze", "set_hydro_breeze", "off"),
(
"select.test_fridge_top_zone_biofresh_plus",
"set_bio_fresh_plus",
"zero_zero",
),
],
)
@pytest.mark.usefixtures("init_integration")
async def test_select_failure(
hass: HomeAssistant,
mock_liebherr_client: MagicMock,
entity_id: str,
method: str,
option: str,
) -> None:
"""Test select fails gracefully on connection error."""
getattr(mock_liebherr_client, method).side_effect = LiebherrConnectionError(
"Connection failed"
)
with pytest.raises(
HomeAssistantError,
match="An error occurred while communicating with the device",
):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: option},
blocking=True,
)
@pytest.mark.usefixtures("init_integration")
async def test_select_when_control_missing(
hass: HomeAssistant,
mock_liebherr_client: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test select entity behavior when control is removed."""
entity_id = "select.test_fridge_bottom_zone_icemaker"
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "off"
# Device stops reporting select controls
mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: DeviceState(
device=MOCK_DEVICE, controls=[]
)
freezer.tick(timedelta(seconds=61))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_UNAVAILABLE
async def test_single_zone_select(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_liebherr_client: MagicMock,
mock_config_entry: MockConfigEntry,
platforms: list[Platform],
) -> None:
"""Test single zone device uses name without zone suffix."""
device = Device(
device_id="single_zone_id",
nickname="Single Zone Fridge",
device_type=DeviceType.FRIDGE,
device_name="K2601",
)
mock_liebherr_client.get_devices.return_value = [device]
single_zone_state = DeviceState(
device=device,
controls=[
TemperatureControl(
zone_id=1,
zone_position=ZonePosition.TOP,
name="Fridge",
type="fridge",
value=4,
target=4,
min=2,
max=8,
unit=TemperatureUnit.CELSIUS,
),
IceMakerControl(
name="icemaker",
type="IceMakerControl",
zone_id=1,
zone_position=ZonePosition.TOP,
ice_maker_mode=IceMakerMode.ON,
has_max_ice=False,
),
HydroBreezeControl(
name="hydrobreeze",
type="HydroBreezeControl",
zone_id=1,
current_mode=HydroBreezeMode.OFF,
),
],
)
mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: copy.deepcopy(
single_zone_state
)
mock_config_entry.add_to_hass(hass)
with patch("homeassistant.components.liebherr.PLATFORMS", platforms):
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.usefixtures("init_integration")
async def test_select_current_option_none_mode(
hass: HomeAssistant,
mock_liebherr_client: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test select entity state when control mode returns None."""
entity_id = "select.test_fridge_top_zone_hydrobreeze"
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "low"
# Simulate update where mode is None
state_with_none_mode = copy.deepcopy(MOCK_DEVICE_STATE)
for control in state_with_none_mode.controls:
if isinstance(control, HydroBreezeControl):
control.current_mode = None
break
mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: copy.deepcopy(
state_with_none_mode
)
freezer.tick(timedelta(seconds=61))
async_fire_time_changed(hass)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_UNKNOWN
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/liebherr/test_select.py",
"license": "Apache License 2.0",
"lines": 264,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/homevolt/entity.py | """Shared entity helpers for Homevolt."""
from __future__ import annotations
from collections.abc import Callable, Coroutine
from typing import Any, Concatenate
from homevolt import HomevoltAuthenticationError, HomevoltConnectionError, HomevoltError
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, MANUFACTURER
from .coordinator import HomevoltDataUpdateCoordinator
class HomevoltEntity(CoordinatorEntity[HomevoltDataUpdateCoordinator]):
"""Base Homevolt entity."""
_attr_has_entity_name = True
def __init__(
self, coordinator: HomevoltDataUpdateCoordinator, device_identifier: str
) -> None:
"""Initialize the Homevolt entity."""
super().__init__(coordinator)
device_id = coordinator.data.unique_id
device_metadata = coordinator.data.device_metadata.get(device_identifier)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, f"{device_id}_{device_identifier}")},
configuration_url=coordinator.client.base_url,
manufacturer=MANUFACTURER,
model=device_metadata.model if device_metadata else None,
name=device_metadata.name if device_metadata else None,
)
def homevolt_exception_handler[_HomevoltEntityT: HomevoltEntity, **_P](
func: Callable[Concatenate[_HomevoltEntityT, _P], Coroutine[Any, Any, Any]],
) -> Callable[Concatenate[_HomevoltEntityT, _P], Coroutine[Any, Any, None]]:
"""Decorate Homevolt calls to handle exceptions."""
async def handler(
self: _HomevoltEntityT, *args: _P.args, **kwargs: _P.kwargs
) -> None:
try:
await func(self, *args, **kwargs)
except HomevoltAuthenticationError as error:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="auth_failed",
) from error
except HomevoltConnectionError as error:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="communication_error",
translation_placeholders={"error": str(error)},
) from error
except HomevoltError as error:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="unknown_error",
translation_placeholders={"error": str(error)},
) from error
return handler
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/homevolt/entity.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/homevolt/switch.py | """Support for Homevolt switch entities."""
from __future__ import annotations
from typing import Any
from homeassistant.components.switch import SwitchEntity
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import HomevoltConfigEntry, HomevoltDataUpdateCoordinator
from .entity import HomevoltEntity, homevolt_exception_handler
PARALLEL_UPDATES = 0 # Coordinator-based updates
async def async_setup_entry(
hass: HomeAssistant,
entry: HomevoltConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Homevolt switch entities."""
coordinator = entry.runtime_data
async_add_entities([HomevoltLocalModeSwitch(coordinator)])
class HomevoltLocalModeSwitch(HomevoltEntity, SwitchEntity):
"""Switch entity for Homevolt local mode."""
_attr_entity_category = EntityCategory.CONFIG
_attr_translation_key = "local_mode"
def __init__(self, coordinator: HomevoltDataUpdateCoordinator) -> None:
"""Initialize the switch entity."""
self._attr_unique_id = f"{coordinator.data.unique_id}_local_mode"
device_id = coordinator.data.unique_id
super().__init__(coordinator, f"ems_{device_id}")
@property
def is_on(self) -> bool:
"""Return true if local mode is enabled."""
return self.coordinator.client.local_mode_enabled
@homevolt_exception_handler
async def async_turn_on(self, **kwargs: Any) -> None:
"""Enable local mode."""
await self.coordinator.client.enable_local_mode()
await self.coordinator.async_request_refresh()
@homevolt_exception_handler
async def async_turn_off(self, **kwargs: Any) -> None:
"""Disable local mode."""
await self.coordinator.client.disable_local_mode()
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/homevolt/switch.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:tests/components/homevolt/test_entity.py | """Tests for the Homevolt entity."""
from __future__ import annotations
from unittest.mock import MagicMock
from homevolt import DeviceMetadata
from homeassistant.components.homevolt.const import DOMAIN, MANUFACTURER
from homeassistant.components.homevolt.switch import HomevoltLocalModeSwitch
from homeassistant.core import HomeAssistant
from .conftest import DEVICE_IDENTIFIER
async def test_homevolt_entity_device_info_with_metadata(
hass: HomeAssistant,
) -> None:
"""Test HomevoltEntity device info when device_metadata is present."""
coordinator = MagicMock()
coordinator.data.unique_id = "40580137858664"
coordinator.data.device_metadata = {
DEVICE_IDENTIFIER: DeviceMetadata(name="Homevolt EMS", model="EMS-1000"),
}
coordinator.client.base_url = "http://127.0.0.1"
entity = HomevoltLocalModeSwitch(coordinator)
assert entity.device_info is not None
assert entity.device_info["identifiers"] == {
(DOMAIN, f"40580137858664_{DEVICE_IDENTIFIER}")
}
assert entity.device_info["configuration_url"] == "http://127.0.0.1"
assert entity.device_info["manufacturer"] == MANUFACTURER
assert entity.device_info["model"] == "EMS-1000"
assert entity.device_info["name"] == "Homevolt EMS"
async def test_homevolt_entity_device_info_without_metadata(
hass: HomeAssistant,
) -> None:
"""Test HomevoltEntity device info when device_metadata has no entry for device."""
coordinator = MagicMock()
coordinator.data.unique_id = "40580137858664"
coordinator.data.device_metadata = {}
coordinator.client.base_url = "http://127.0.0.1"
entity = HomevoltLocalModeSwitch(coordinator)
assert entity.device_info is not None
assert entity.device_info["identifiers"] == {
(DOMAIN, f"40580137858664_{DEVICE_IDENTIFIER}")
}
assert entity.device_info["manufacturer"] == MANUFACTURER
assert entity.device_info["model"] is None
assert entity.device_info["name"] is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homevolt/test_entity.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/homevolt/test_switch.py | """Tests for the Homevolt switch platform."""
from __future__ import annotations
from unittest.mock import MagicMock
from homevolt import HomevoltAuthenticationError, HomevoltConnectionError, HomevoltError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Override platforms to load only the switch platform."""
return [Platform.SWITCH]
@pytest.fixture
def switch_entity_id(
entity_registry: er.EntityRegistry,
init_integration: MockConfigEntry,
) -> str:
"""Return the switch entity id for the config entry."""
entity_entries = er.async_entries_for_config_entry(
entity_registry, init_integration.entry_id
)
assert len(entity_entries) == 1, "Expected exactly one switch entity"
return entity_entries[0].entity_id
async def test_switch_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
init_integration: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test switch entity and state when local mode is disabled."""
await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id)
@pytest.mark.parametrize(
("service", "client_method_name"),
[
(SERVICE_TURN_ON, "enable_local_mode"),
(SERVICE_TURN_OFF, "disable_local_mode"),
],
)
async def test_switch_turn_on_off(
hass: HomeAssistant,
mock_homevolt_client: MagicMock,
snapshot: SnapshotAssertion,
switch_entity_id: str,
service: str,
client_method_name: str,
) -> None:
"""Test turning the switch on or off calls client, refreshes coordinator, and updates state."""
client_method = getattr(mock_homevolt_client, client_method_name)
async def update_local_mode(*args: object, **kwargs: object) -> None:
mock_homevolt_client.local_mode_enabled = service == SERVICE_TURN_ON
client_method.side_effect = update_local_mode
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: switch_entity_id},
blocking=True,
)
client_method.assert_called_once()
state = hass.states.get(switch_entity_id)
assert state is not None
assert state == snapshot(name=f"state-after-{service}")
@pytest.mark.parametrize(
("service", "client_method_name", "exception", "expected_exception"),
[
(
SERVICE_TURN_ON,
"enable_local_mode",
HomevoltAuthenticationError("auth failed"),
ConfigEntryAuthFailed,
),
(
SERVICE_TURN_ON,
"enable_local_mode",
HomevoltConnectionError("connection failed"),
HomeAssistantError,
),
(
SERVICE_TURN_ON,
"enable_local_mode",
HomevoltError("unknown error"),
HomeAssistantError,
),
(
SERVICE_TURN_OFF,
"disable_local_mode",
HomevoltAuthenticationError("auth failed"),
ConfigEntryAuthFailed,
),
(
SERVICE_TURN_OFF,
"disable_local_mode",
HomevoltConnectionError("connection failed"),
HomeAssistantError,
),
(
SERVICE_TURN_OFF,
"disable_local_mode",
HomevoltError("unknown error"),
HomeAssistantError,
),
],
)
async def test_switch_turn_on_off_exception_handler(
hass: HomeAssistant,
mock_homevolt_client: MagicMock,
switch_entity_id: str,
service: str,
client_method_name: str,
exception: Exception,
expected_exception: type[Exception],
) -> None:
"""Test homevolt_exception_handler raises correct exception on turn_on/turn_off."""
getattr(mock_homevolt_client, client_method_name).side_effect = exception
with pytest.raises(expected_exception):
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: switch_entity_id},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homevolt/test_switch.py",
"license": "Apache License 2.0",
"lines": 128,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/intelliclima/select.py | """Select platform for IntelliClima VMC."""
from pyintelliclima.const import FanMode, FanSpeed
from pyintelliclima.intelliclima_types import IntelliClimaECO
from homeassistant.components.select import SelectEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import IntelliClimaConfigEntry, IntelliClimaCoordinator
from .entity import IntelliClimaECOEntity
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
FAN_MODE_TO_INTELLICLIMA_MODE = {
"forward": FanMode.inward,
"reverse": FanMode.outward,
"alternate": FanMode.alternate,
"sensor": FanMode.sensor,
}
INTELLICLIMA_MODE_TO_FAN_MODE = {v: k for k, v in FAN_MODE_TO_INTELLICLIMA_MODE.items()}
async def async_setup_entry(
hass: HomeAssistant,
entry: IntelliClimaConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up IntelliClima VMC fan mode select."""
coordinator = entry.runtime_data
entities: list[IntelliClimaVMCFanModeSelect] = [
IntelliClimaVMCFanModeSelect(
coordinator=coordinator,
device=ecocomfort2,
)
for ecocomfort2 in coordinator.data.ecocomfort2_devices.values()
]
async_add_entities(entities)
class IntelliClimaVMCFanModeSelect(IntelliClimaECOEntity, SelectEntity):
"""Representation of an IntelliClima VMC fan mode selector."""
_attr_translation_key = "fan_mode"
_attr_options = ["forward", "reverse", "alternate", "sensor"]
def __init__(
self,
coordinator: IntelliClimaCoordinator,
device: IntelliClimaECO,
) -> None:
"""Class initializer."""
super().__init__(coordinator, device)
self._attr_unique_id = f"{device.id}_fan_mode"
@property
def current_option(self) -> str | None:
"""Return the current fan mode."""
device_data = self._device_data
if device_data.mode_set == FanMode.off:
return None
# If in auto mode (sensor mode with auto speed), return None (handled by fan entity preset mode)
if (
device_data.speed_set == FanSpeed.auto
and device_data.mode_set == FanMode.sensor
):
return None
return INTELLICLIMA_MODE_TO_FAN_MODE.get(FanMode(device_data.mode_set))
async def async_select_option(self, option: str) -> None:
"""Set the fan mode."""
device_data = self._device_data
mode = FAN_MODE_TO_INTELLICLIMA_MODE[option]
# Determine speed: keep current speed if available, otherwise default to sleep
if (
device_data.speed_set == FanSpeed.auto
or device_data.mode_set == FanMode.off
):
speed = FanSpeed.sleep
else:
speed = device_data.speed_set
await self.coordinator.api.ecocomfort.set_mode_speed(
self._device_sn, mode, speed
)
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/intelliclima/select.py",
"license": "Apache License 2.0",
"lines": 73,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/intelliclima/test_select.py | """Test IntelliClima Select."""
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
from pyintelliclima.const import FanMode, FanSpeed
import pytest
from syrupy.assertion import SnapshotAssertion
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 device_registry as dr, entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
SELECT_ENTITY_ID = "select.test_vmc_fan_direction_mode"
@pytest.fixture(autouse=True)
async def setup_intelliclima_select_only(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_cloud_interface: AsyncMock,
) -> AsyncGenerator[None]:
"""Set up IntelliClima integration with only the select platform."""
with (
patch("homeassistant.components.intelliclima.PLATFORMS", [Platform.SELECT]),
):
await setup_integration(hass, mock_config_entry)
# Let tests run against this initialized state
yield
async def test_all_select_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
mock_cloud_interface: AsyncMock,
) -> None:
"""Test all entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
# There should be exactly one select entity
select_entries = [
entry
for entry in entity_registry.entities.values()
if entry.platform == "intelliclima" and entry.domain == SELECT_DOMAIN
]
assert len(select_entries) == 1
entity_entry = select_entries[0]
assert entity_entry.device_id
assert (device_entry := device_registry.async_get(entity_entry.device_id))
assert device_entry == snapshot
@pytest.mark.parametrize(
("option", "expected_mode"),
[
("forward", FanMode.inward),
("reverse", FanMode.outward),
("alternate", FanMode.alternate),
("sensor", FanMode.sensor),
],
)
async def test_select_option_keeps_current_speed(
hass: HomeAssistant,
mock_cloud_interface: AsyncMock,
option: str,
expected_mode: FanMode,
) -> None:
"""Selecting any valid option retains the current speed and calls set_mode_speed."""
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: SELECT_ENTITY_ID, ATTR_OPTION: option},
blocking=True,
)
# Device starts with speed_set="3" (from single_eco_device in conftest),
# mode is not off and not auto, so current speed is preserved.
mock_cloud_interface.ecocomfort.set_mode_speed.assert_awaited_once_with(
"11223344", expected_mode, "3"
)
async def test_select_option_when_off_defaults_speed_to_sleep(
hass: HomeAssistant,
mock_cloud_interface: AsyncMock,
single_eco_device,
) -> None:
"""When the device is off, selecting an option defaults the speed to FanSpeed.sleep."""
# Mutate the shared fixture object – coordinator.data points to the same reference.
eco = list(single_eco_device.ecocomfort2_devices.values())[0]
eco.mode_set = FanMode.off
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: SELECT_ENTITY_ID, ATTR_OPTION: "forward"},
blocking=True,
)
mock_cloud_interface.ecocomfort.set_mode_speed.assert_awaited_once_with(
"11223344", FanMode.inward, FanSpeed.sleep
)
async def test_select_option_in_auto_mode_defaults_speed_to_sleep(
hass: HomeAssistant,
mock_cloud_interface: AsyncMock,
single_eco_device,
) -> None:
"""When speed_set is FanSpeed.auto (auto preset), selecting an option defaults to sleep speed."""
eco = list(single_eco_device.ecocomfort2_devices.values())[0]
eco.speed_set = FanSpeed.auto
eco.mode_set = FanMode.sensor
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: SELECT_ENTITY_ID, ATTR_OPTION: "reverse"},
blocking=True,
)
mock_cloud_interface.ecocomfort.set_mode_speed.assert_awaited_once_with(
"11223344", FanMode.outward, FanSpeed.sleep
)
@pytest.mark.parametrize("option", ["forward", "reverse", "alternate", "sensor"])
async def test_select_option_does_not_call_turn_off(
hass: HomeAssistant,
mock_cloud_interface: AsyncMock,
option: str,
) -> None:
"""Selecting an option should never call turn_off."""
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: SELECT_ENTITY_ID, ATTR_OPTION: option},
blocking=True,
)
mock_cloud_interface.ecocomfort.turn_off.assert_not_awaited()
async def test_select_option_triggers_coordinator_refresh(
hass: HomeAssistant,
mock_cloud_interface: AsyncMock,
) -> None:
"""Selecting an option should trigger a coordinator refresh after the API call."""
initial_call_count = mock_cloud_interface.get_all_device_status.call_count
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: SELECT_ENTITY_ID, ATTR_OPTION: "sensor"},
blocking=True,
)
# A refresh must have been requested, so the status fetch count increases.
assert mock_cloud_interface.get_all_device_status.call_count > initial_call_count
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/intelliclima/test_select.py",
"license": "Apache License 2.0",
"lines": 142,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/proxmoxve/diagnostics.py | """Diagnostics support for Proxmox VE."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from . import ProxmoxConfigEntry
TO_REDACT = [CONF_USERNAME, CONF_PASSWORD, CONF_HOST]
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ProxmoxConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a Proxmox VE config entry."""
return {
"config_entry": async_redact_data(config_entry.as_dict(), TO_REDACT),
"devices": {
node: asdict(node_data)
for node, node_data in config_entry.runtime_data.data.items()
},
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/proxmoxve/diagnostics.py",
"license": "Apache License 2.0",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/proxmoxve/test_diagnostics.py | """Test the Proxmox VE component diagnostics."""
from unittest.mock import MagicMock
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_get_config_entry_diagnostics(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_proxmox_client: MagicMock,
mock_config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
) -> None:
"""Test if get_config_entry_diagnostics returns the correct data."""
await setup_integration(hass, mock_config_entry)
diagnostics_entry = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
assert diagnostics_entry == snapshot(
exclude=props(
"created_at",
"modified_at",
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/proxmoxve/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 27,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/trane/climate.py | """Climate platform for the Trane Local integration."""
from __future__ import annotations
from typing import Any
from steamloop import FanMode, HoldType, ThermostatConnection, ZoneMode
from homeassistant.components.climate import (
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
ClimateEntity,
ClimateEntityFeature,
HVACAction,
HVACMode,
)
from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .entity import TraneZoneEntity
from .types import TraneConfigEntry
PARALLEL_UPDATES = 0
HA_TO_ZONE_MODE = {
HVACMode.OFF: ZoneMode.OFF,
HVACMode.HEAT: ZoneMode.HEAT,
HVACMode.COOL: ZoneMode.COOL,
HVACMode.HEAT_COOL: ZoneMode.AUTO,
HVACMode.AUTO: ZoneMode.AUTO,
}
ZONE_MODE_TO_HA = {
ZoneMode.OFF: HVACMode.OFF,
ZoneMode.HEAT: HVACMode.HEAT,
ZoneMode.COOL: HVACMode.COOL,
ZoneMode.AUTO: HVACMode.AUTO,
}
HA_TO_FAN_MODE = {
"auto": FanMode.AUTO,
"on": FanMode.ALWAYS_ON,
"circulate": FanMode.CIRCULATE,
}
FAN_MODE_TO_HA = {v: k for k, v in HA_TO_FAN_MODE.items()}
SINGLE_SETPOINT_MODES = frozenset({ZoneMode.COOL, ZoneMode.HEAT})
async def async_setup_entry(
hass: HomeAssistant,
config_entry: TraneConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Trane Local climate entities."""
conn = config_entry.runtime_data
async_add_entities(
TraneClimateEntity(conn, config_entry.entry_id, zone_id)
for zone_id in conn.state.zones
)
class TraneClimateEntity(TraneZoneEntity, ClimateEntity):
"""Climate entity for a Trane thermostat zone."""
_attr_name = None
_attr_translation_key = "zone"
_attr_fan_modes = list(HA_TO_FAN_MODE)
_attr_supported_features = (
ClimateEntityFeature.TARGET_TEMPERATURE
| ClimateEntityFeature.TARGET_TEMPERATURE_RANGE
| ClimateEntityFeature.FAN_MODE
| ClimateEntityFeature.TURN_OFF
| ClimateEntityFeature.TURN_ON
)
_attr_temperature_unit = UnitOfTemperature.FAHRENHEIT
_attr_target_temperature_step = 1.0
def __init__(self, conn: ThermostatConnection, entry_id: str, zone_id: str) -> None:
"""Initialize the climate entity."""
super().__init__(conn, entry_id, zone_id, "zone")
modes: list[HVACMode] = []
for zone_mode in conn.state.supported_modes:
ha_mode = ZONE_MODE_TO_HA.get(zone_mode)
if ha_mode is None:
continue
modes.append(ha_mode)
# AUTO in steamloop maps to both AUTO (schedule) and HEAT_COOL (manual hold)
if zone_mode == ZoneMode.AUTO:
modes.append(HVACMode.HEAT_COOL)
self._attr_hvac_modes = modes
@property
def current_temperature(self) -> float | None:
"""Return the current temperature."""
# indoor_temperature is a string from the protocol (e.g. "72.00")
# or empty string if not yet received
if temp := self._zone.indoor_temperature:
return float(temp)
return None
@property
def current_humidity(self) -> int | None:
"""Return the current humidity."""
# relative_humidity is a string from the protocol (e.g. "45")
# or empty string if not yet received
if humidity := self._conn.state.relative_humidity:
return int(humidity)
return None
@property
def hvac_mode(self) -> HVACMode:
"""Return the current HVAC mode."""
zone = self._zone
if zone.mode == ZoneMode.AUTO and zone.hold_type == HoldType.MANUAL:
return HVACMode.HEAT_COOL
return ZONE_MODE_TO_HA.get(zone.mode, HVACMode.OFF)
@property
def hvac_action(self) -> HVACAction:
"""Return the current HVAC action."""
# heating_active and cooling_active are system-level strings from the
# protocol ("0"=off, "1"=idle, "2"=running); filter by zone mode so
# a zone in COOL never reports HEATING and vice versa
zone_mode = self._zone.mode
if zone_mode == ZoneMode.OFF:
return HVACAction.OFF
state = self._conn.state
if zone_mode != ZoneMode.HEAT and state.cooling_active == "2":
return HVACAction.COOLING
if zone_mode != ZoneMode.COOL and state.heating_active == "2":
return HVACAction.HEATING
return HVACAction.IDLE
@property
def target_temperature(self) -> float | None:
"""Return target temperature for single-setpoint modes."""
# Setpoints are strings from the protocol or empty string if not yet received
zone = self._zone
if zone.mode == ZoneMode.COOL:
return float(zone.cool_setpoint) if zone.cool_setpoint else None
if zone.mode == ZoneMode.HEAT:
return float(zone.heat_setpoint) if zone.heat_setpoint else None
return None
@property
def target_temperature_high(self) -> float | None:
"""Return the upper bound target temperature."""
zone = self._zone
if zone.mode in SINGLE_SETPOINT_MODES:
return None
return float(zone.cool_setpoint) if zone.cool_setpoint else None
@property
def target_temperature_low(self) -> float | None:
"""Return the lower bound target temperature."""
zone = self._zone
if zone.mode in SINGLE_SETPOINT_MODES:
return None
return float(zone.heat_setpoint) if zone.heat_setpoint else None
@property
def fan_mode(self) -> str:
"""Return the current fan mode."""
return FAN_MODE_TO_HA.get(self._conn.state.fan_mode, "auto")
async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
"""Set the HVAC mode."""
if hvac_mode == HVACMode.OFF:
self._conn.set_zone_mode(self._zone_id, ZoneMode.OFF)
return
hold_type = HoldType.SCHEDULE if hvac_mode == HVACMode.AUTO else HoldType.MANUAL
self._conn.set_temperature_setpoint(self._zone_id, hold_type=hold_type)
self._conn.set_zone_mode(self._zone_id, HA_TO_ZONE_MODE[hvac_mode])
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set target temperature."""
heat_temp = kwargs.get(ATTR_TARGET_TEMP_LOW)
cool_temp = kwargs.get(ATTR_TARGET_TEMP_HIGH)
set_temp = kwargs.get(ATTR_TEMPERATURE)
if set_temp is not None:
if self._zone.mode == ZoneMode.COOL:
cool_temp = set_temp
elif self._zone.mode == ZoneMode.HEAT:
heat_temp = set_temp
self._conn.set_temperature_setpoint(
self._zone_id,
heat_setpoint=str(round(heat_temp)) if heat_temp is not None else None,
cool_setpoint=str(round(cool_temp)) if cool_temp is not None else None,
)
async def async_set_fan_mode(self, fan_mode: str) -> None:
"""Set the fan mode."""
self._conn.set_fan_mode(HA_TO_FAN_MODE[fan_mode])
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/trane/climate.py",
"license": "Apache License 2.0",
"lines": 168,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/trane/test_climate.py | """Tests for the Trane Local climate platform."""
from unittest.mock import MagicMock
import pytest
from steamloop import FanMode, HoldType, ZoneMode
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.climate import (
ATTR_FAN_MODE,
ATTR_HVAC_MODE,
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
DOMAIN as CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_TEMPERATURE,
HVACAction,
HVACMode,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_TEMPERATURE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Platforms, which should be loaded during the test."""
return [Platform.CLIMATE]
@pytest.fixture(autouse=True)
def set_us_customary(hass: HomeAssistant) -> None:
"""Set US customary unit system for Trane (Fahrenheit thermostats)."""
hass.config.units = US_CUSTOMARY_SYSTEM
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_climate_entities(
hass: HomeAssistant,
init_integration: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Snapshot all climate entities."""
await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id)
async def test_hvac_mode_auto(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test HVAC mode is AUTO when following schedule."""
mock_connection.state.zones["1"].hold_type = HoldType.SCHEDULE
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.living_room")
assert state is not None
assert state.state == HVACMode.AUTO
async def test_current_temperature_not_available(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test current temperature is None when not yet received."""
mock_connection.state.zones["1"].indoor_temperature = ""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.living_room")
assert state is not None
assert state.attributes["current_temperature"] is None
async def test_current_humidity_not_available(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test current humidity is omitted when not yet received."""
mock_connection.state.relative_humidity = ""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.living_room")
assert state is not None
assert "current_humidity" not in state.attributes
async def test_set_hvac_mode_off(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test setting HVAC mode to off."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: "climate.living_room", ATTR_HVAC_MODE: HVACMode.OFF},
blocking=True,
)
mock_connection.set_temperature_setpoint.assert_not_called()
mock_connection.set_zone_mode.assert_called_once_with("1", ZoneMode.OFF)
@pytest.mark.parametrize(
("hvac_mode", "expected_hold", "expected_zone_mode"),
[
(HVACMode.AUTO, HoldType.SCHEDULE, ZoneMode.AUTO),
(HVACMode.HEAT_COOL, HoldType.MANUAL, ZoneMode.AUTO),
(HVACMode.HEAT, HoldType.MANUAL, ZoneMode.HEAT),
(HVACMode.COOL, HoldType.MANUAL, ZoneMode.COOL),
],
)
async def test_set_hvac_mode(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_connection: MagicMock,
hvac_mode: HVACMode,
expected_hold: HoldType,
expected_zone_mode: ZoneMode,
) -> None:
"""Test setting HVAC mode."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: "climate.living_room", ATTR_HVAC_MODE: hvac_mode},
blocking=True,
)
mock_connection.set_temperature_setpoint.assert_called_once_with(
"1", hold_type=expected_hold
)
mock_connection.set_zone_mode.assert_called_once_with("1", expected_zone_mode)
async def test_set_temperature_range(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test setting temperature range in heat_cool mode."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "climate.living_room",
ATTR_TARGET_TEMP_LOW: 65,
ATTR_TARGET_TEMP_HIGH: 78,
},
blocking=True,
)
mock_connection.set_temperature_setpoint.assert_called_once_with(
"1",
heat_setpoint="65",
cool_setpoint="78",
)
async def test_set_temperature_single_heat(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test setting single temperature in heat mode."""
mock_connection.state.zones["1"].mode = ZoneMode.HEAT
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "climate.living_room",
ATTR_TEMPERATURE: 70,
},
blocking=True,
)
mock_connection.set_temperature_setpoint.assert_called_once_with(
"1",
heat_setpoint="70",
cool_setpoint=None,
)
async def test_set_temperature_single_cool(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test setting single temperature in cool mode."""
mock_connection.state.zones["1"].mode = ZoneMode.COOL
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: "climate.living_room",
ATTR_TEMPERATURE: 78,
},
blocking=True,
)
mock_connection.set_temperature_setpoint.assert_called_once_with(
"1",
heat_setpoint=None,
cool_setpoint="78",
)
@pytest.mark.parametrize(
("fan_mode", "expected_fan_mode"),
[
("auto", FanMode.AUTO),
("on", FanMode.ALWAYS_ON),
("circulate", FanMode.CIRCULATE),
],
)
async def test_set_fan_mode(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_connection: MagicMock,
fan_mode: str,
expected_fan_mode: FanMode,
) -> None:
"""Test setting fan mode."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: "climate.living_room", ATTR_FAN_MODE: fan_mode},
blocking=True,
)
mock_connection.set_fan_mode.assert_called_once_with(expected_fan_mode)
@pytest.mark.parametrize(
("cooling_active", "heating_active", "zone_mode", "expected_action"),
[
("0", "0", ZoneMode.OFF, HVACAction.OFF),
("0", "2", ZoneMode.AUTO, HVACAction.HEATING),
("2", "0", ZoneMode.AUTO, HVACAction.COOLING),
("0", "0", ZoneMode.AUTO, HVACAction.IDLE),
("0", "1", ZoneMode.AUTO, HVACAction.IDLE),
("1", "0", ZoneMode.AUTO, HVACAction.IDLE),
("0", "2", ZoneMode.COOL, HVACAction.IDLE),
("2", "0", ZoneMode.HEAT, HVACAction.IDLE),
("2", "2", ZoneMode.AUTO, HVACAction.COOLING),
],
)
async def test_hvac_action(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
cooling_active: str,
heating_active: str,
zone_mode: ZoneMode,
expected_action: HVACAction,
) -> None:
"""Test HVAC action reflects thermostat state."""
mock_connection.state.cooling_active = cooling_active
mock_connection.state.heating_active = heating_active
mock_connection.state.zones["1"].mode = zone_mode
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("climate.living_room")
assert state is not None
assert state.attributes["hvac_action"] == expected_action
async def test_turn_on(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test turn on defaults to heat_cool mode."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "climate.living_room"},
blocking=True,
)
mock_connection.set_temperature_setpoint.assert_called_once_with(
"1", hold_type=HoldType.MANUAL
)
mock_connection.set_zone_mode.assert_called_once_with("1", ZoneMode.AUTO)
async def test_turn_off(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test turn off sets mode to off."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "climate.living_room"},
blocking=True,
)
mock_connection.set_temperature_setpoint.assert_not_called()
mock_connection.set_zone_mode.assert_called_once_with("1", ZoneMode.OFF)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/trane/test_climate.py",
"license": "Apache License 2.0",
"lines": 281,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/whirlpool/select.py | """The select platform for Whirlpool Appliances."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import Final, override
from whirlpool.appliance import Appliance
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.const import UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import WhirlpoolConfigEntry
from .const import DOMAIN
from .entity import WhirlpoolEntity
PARALLEL_UPDATES = 1
@dataclass(frozen=True, kw_only=True)
class WhirlpoolSelectDescription(SelectEntityDescription):
"""Class describing Whirlpool select entities."""
value_fn: Callable[[Appliance], str | None]
set_fn: Callable[[Appliance, str], Awaitable[bool]]
REFRIGERATOR_DESCRIPTIONS: Final[tuple[WhirlpoolSelectDescription, ...]] = (
WhirlpoolSelectDescription(
key="refrigerator_temperature_level",
translation_key="refrigerator_temperature_level",
options=["-4", "-2", "0", "3", "5"],
unit_of_measurement=UnitOfTemperature.CELSIUS,
value_fn=lambda fridge: (
str(val) if (val := fridge.get_offset_temp()) is not None else None
),
set_fn=lambda fridge, option: fridge.set_offset_temp(int(option)),
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: WhirlpoolConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the select platform."""
appliances_manager = config_entry.runtime_data
async_add_entities(
WhirlpoolSelectEntity(refrigerator, description)
for refrigerator in appliances_manager.refrigerators
for description in REFRIGERATOR_DESCRIPTIONS
)
class WhirlpoolSelectEntity(WhirlpoolEntity, SelectEntity):
"""Whirlpool select entity."""
def __init__(
self, appliance: Appliance, description: WhirlpoolSelectDescription
) -> None:
"""Initialize the select entity."""
super().__init__(appliance, unique_id_suffix=f"-{description.key}")
self.entity_description: WhirlpoolSelectDescription = description
@override
@property
def current_option(self) -> str | None:
"""Retrieve currently selected option."""
return self.entity_description.value_fn(self._appliance)
@override
async def async_select_option(self, option: str) -> None:
"""Set the selected option."""
try:
WhirlpoolSelectEntity._check_service_request(
await self.entity_description.set_fn(self._appliance, option)
)
except ValueError as err:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="invalid_value_set",
) from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/whirlpool/select.py",
"license": "Apache License 2.0",
"lines": 69,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/whirlpool/test_select.py | """Test the Whirlpool select domain."""
from unittest.mock import MagicMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.select import ATTR_OPTION, DOMAIN as SELECT_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_SELECT_OPTION, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from . import init_integration, snapshot_whirlpool_entities, trigger_attr_callback
async def test_all_entities(
hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry
) -> None:
"""Test all entities."""
await init_integration(hass)
snapshot_whirlpool_entities(hass, entity_registry, snapshot, Platform.SELECT)
@pytest.mark.parametrize(
(
"entity_id",
"mock_fixture",
"mock_getter_method_name",
"mock_setter_method_name",
"values",
),
[
(
"select.beer_fridge_temperature_level",
"mock_refrigerator_api",
"get_offset_temp",
"set_offset_temp",
[(-4, "-4"), (-2, "-2"), (0, "0"), (3, "3"), (5, "5")],
),
],
)
async def test_select_entities(
hass: HomeAssistant,
entity_id: str,
mock_fixture: str,
mock_getter_method_name: str,
mock_setter_method_name: str,
values: list[tuple[int, str]],
request: pytest.FixtureRequest,
) -> None:
"""Test reading and setting select options."""
await init_integration(hass)
mock_instance = request.getfixturevalue(mock_fixture)
# Test reading current option
mock_getter_method = getattr(mock_instance, mock_getter_method_name)
for raw_value, expected_state in values:
mock_getter_method.return_value = raw_value
await trigger_attr_callback(hass, mock_instance)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == expected_state
# Test changing option
mock_setter_method = getattr(mock_instance, mock_setter_method_name)
for raw_value, selected_option in values:
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{ATTR_ENTITY_ID: entity_id, ATTR_OPTION: selected_option},
blocking=True,
)
assert mock_setter_method.call_count == 1
mock_setter_method.assert_called_with(raw_value)
mock_setter_method.reset_mock()
async def test_select_option_value_error(
hass: HomeAssistant, mock_refrigerator_api: MagicMock
) -> None:
"""Test handling of ValueError exception when selecting an option."""
await init_integration(hass)
mock_refrigerator_api.set_offset_temp.side_effect = ValueError
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
SELECT_DOMAIN,
SERVICE_SELECT_OPTION,
{
ATTR_ENTITY_ID: "select.beer_fridge_temperature_level",
ATTR_OPTION: "something",
},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/whirlpool/test_select.py",
"license": "Apache License 2.0",
"lines": 82,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/airos/button.py | """AirOS button component for Home Assistant."""
from __future__ import annotations
from airos.exceptions import AirOSException
from homeassistant.components.button import (
ButtonDeviceClass,
ButtonEntity,
ButtonEntityDescription,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import DOMAIN, AirOSConfigEntry, AirOSDataUpdateCoordinator
from .entity import AirOSEntity
PARALLEL_UPDATES = 0
REBOOT_BUTTON = ButtonEntityDescription(
key="reboot",
device_class=ButtonDeviceClass.RESTART,
entity_registry_enabled_default=False,
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: AirOSConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the AirOS button from a config entry."""
async_add_entities([AirOSRebootButton(config_entry.runtime_data, REBOOT_BUTTON)])
class AirOSRebootButton(AirOSEntity, ButtonEntity):
"""Button to reboot device."""
entity_description: ButtonEntityDescription
def __init__(
self,
coordinator: AirOSDataUpdateCoordinator,
description: ButtonEntityDescription,
) -> None:
"""Initialize the AirOS client button."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.data.derived.mac}_{description.key}"
async def async_press(self) -> None:
"""Handle the button press to reboot the device."""
try:
await self.coordinator.airos_device.login()
result = await self.coordinator.airos_device.reboot()
except AirOSException as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="cannot_connect",
) from err
if not result:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="reboot_failed",
) from None
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/airos/button.py",
"license": "Apache License 2.0",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/airos/test_button.py | """Test the Ubiquiti airOS buttons."""
from unittest.mock import AsyncMock
from airos.exceptions import AirOSDataMissingError, AirOSDeviceConnectionError
import pytest
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
REBOOT_ENTITY_ID = "button.nanostation_5ac_ap_name_restart"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_reboot_button_press_success(
hass: HomeAssistant,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that pressing the reboot button utilizes the correct calls."""
await setup_integration(hass, mock_config_entry, [Platform.BUTTON])
entity = entity_registry.async_get(REBOOT_ENTITY_ID)
assert entity
assert entity.unique_id == f"{mock_config_entry.unique_id}_reboot"
await hass.services.async_call(
"button",
"press",
{ATTR_ENTITY_ID: REBOOT_ENTITY_ID},
blocking=True,
)
mock_airos_client.reboot.assert_awaited_once()
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_reboot_button_press_fail(
hass: HomeAssistant,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that pressing the reboot button utilizes the correct calls."""
await setup_integration(hass, mock_config_entry, [Platform.BUTTON])
mock_airos_client.reboot.return_value = False
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
"button",
"press",
{ATTR_ENTITY_ID: REBOOT_ENTITY_ID},
blocking=True,
)
mock_airos_client.reboot.assert_awaited_once()
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize(
"exception",
[
AirOSDeviceConnectionError,
AirOSDataMissingError,
],
)
async def test_reboot_button_press_exceptions(
hass: HomeAssistant,
mock_airos_client: AsyncMock,
mock_async_get_firmware_data: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
) -> None:
"""Test reboot failure is handled gracefully."""
await setup_integration(hass, mock_config_entry, [Platform.BUTTON])
mock_airos_client.login.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
"button",
"press",
{ATTR_ENTITY_ID: REBOOT_ENTITY_ID},
blocking=True,
)
mock_airos_client.reboot.assert_not_awaited()
mock_airos_client.login.side_effect = None
mock_airos_client.reboot.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
"button",
"press",
{ATTR_ENTITY_ID: REBOOT_ENTITY_ID},
blocking=True,
)
mock_airos_client.reboot.assert_awaited_once()
mock_airos_client.reboot.side_effect = None
await hass.services.async_call(
"button",
"press",
{ATTR_ENTITY_ID: REBOOT_ENTITY_ID},
blocking=True,
)
mock_airos_client.reboot.assert_awaited()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/airos/test_button.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:homeassistant/components/myneomitis/config_flow.py | """Config flow for MyNeomitis integration."""
import logging
from typing import Any
import aiohttp
from pyaxencoapi import PyAxencoAPI
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import CONF_USER_ID, DOMAIN
_LOGGER = logging.getLogger(__name__)
class MyNeoConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle the configuration flow for the MyNeomitis integration."""
VERSION = 1
MINOR_VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step of the configuration flow."""
errors: dict[str, str] = {}
if user_input is not None:
email: str = user_input[CONF_EMAIL]
password: str = user_input[CONF_PASSWORD]
session = async_get_clientsession(self.hass)
api = PyAxencoAPI(session)
try:
await api.login(email, password)
except aiohttp.ClientResponseError as e:
if e.status == 401:
errors["base"] = "invalid_auth"
elif e.status >= 500:
errors["base"] = "cannot_connect"
else:
errors["base"] = "unknown"
except aiohttp.ClientConnectionError:
errors["base"] = "cannot_connect"
except aiohttp.ClientError:
errors["base"] = "unknown"
except Exception:
_LOGGER.exception("Unexpected error during login")
errors["base"] = "unknown"
if not errors:
# Prevent duplicate configuration with the same user ID
await self.async_set_unique_id(api.user_id)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=f"MyNeomitis ({email})",
data={
CONF_EMAIL: email,
CONF_PASSWORD: password,
CONF_USER_ID: api.user_id,
},
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_EMAIL): str,
vol.Required(CONF_PASSWORD): str,
}
),
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/myneomitis/config_flow.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/myneomitis/select.py | """Select entities for MyNeomitis integration.
This module defines and sets up the select entities for the MyNeomitis integration.
"""
from __future__ import annotations
from dataclasses import dataclass
import logging
from typing import Any
from pyaxencoapi import PyAxencoAPI
from homeassistant.components.select import SelectEntity, SelectEntityDescription
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import MyNeomitisConfigEntry
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
SUPPORTED_MODELS: frozenset[str] = frozenset({"EWS"})
SUPPORTED_SUB_MODELS: frozenset[str] = frozenset({"UFH"})
PRESET_MODE_MAP = {
"comfort": 1,
"eco": 2,
"antifrost": 3,
"standby": 4,
"boost": 6,
"setpoint": 8,
"comfort_plus": 20,
"eco_1": 40,
"eco_2": 41,
"auto": 60,
}
PRESET_MODE_MAP_RELAIS = {
"on": 1,
"off": 2,
"auto": 60,
}
PRESET_MODE_MAP_UFH = {
"heating": 0,
"cooling": 1,
}
REVERSE_PRESET_MODE_MAP = {v: k for k, v in PRESET_MODE_MAP.items()}
REVERSE_PRESET_MODE_MAP_RELAIS = {v: k for k, v in PRESET_MODE_MAP_RELAIS.items()}
REVERSE_PRESET_MODE_MAP_UFH = {v: k for k, v in PRESET_MODE_MAP_UFH.items()}
@dataclass(frozen=True, kw_only=True)
class MyNeoSelectEntityDescription(SelectEntityDescription):
"""Describe MyNeomitis select entity."""
preset_mode_map: dict[str, int]
reverse_preset_mode_map: dict[int, str]
state_key: str
SELECT_TYPES: dict[str, MyNeoSelectEntityDescription] = {
"relais": MyNeoSelectEntityDescription(
key="relais",
translation_key="relais",
options=list(PRESET_MODE_MAP_RELAIS),
preset_mode_map=PRESET_MODE_MAP_RELAIS,
reverse_preset_mode_map=REVERSE_PRESET_MODE_MAP_RELAIS,
state_key="targetMode",
),
"pilote": MyNeoSelectEntityDescription(
key="pilote",
translation_key="pilote",
options=list(PRESET_MODE_MAP),
preset_mode_map=PRESET_MODE_MAP,
reverse_preset_mode_map=REVERSE_PRESET_MODE_MAP,
state_key="targetMode",
),
"ufh": MyNeoSelectEntityDescription(
key="ufh",
translation_key="ufh",
options=list(PRESET_MODE_MAP_UFH),
preset_mode_map=PRESET_MODE_MAP_UFH,
reverse_preset_mode_map=REVERSE_PRESET_MODE_MAP_UFH,
state_key="changeOverUser",
),
}
async def async_setup_entry(
hass: HomeAssistant,
config_entry: MyNeomitisConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Select entities from a config entry."""
api = config_entry.runtime_data.api
devices = config_entry.runtime_data.devices
def _create_entity(device: dict) -> MyNeoSelect:
"""Create a select entity for a device."""
if device["model"] == "EWS":
# According to the MyNeomitis API, EWS "relais" devices expose a "relayMode"
# field in their state, while "pilote" devices do not. We therefore use the
# presence of "relayMode" as an explicit heuristic to distinguish relais
# from pilote devices. If the upstream API changes this behavior, this
# detection logic must be revisited.
if "relayMode" in device.get("state", {}):
description = SELECT_TYPES["relais"]
else:
description = SELECT_TYPES["pilote"]
else: # UFH
description = SELECT_TYPES["ufh"]
return MyNeoSelect(api, device, description)
select_entities = [
_create_entity(device)
for device in devices
if device["model"] in SUPPORTED_MODELS | SUPPORTED_SUB_MODELS
]
async_add_entities(select_entities)
class MyNeoSelect(SelectEntity):
"""Select entity for MyNeomitis devices."""
entity_description: MyNeoSelectEntityDescription
_attr_has_entity_name = True
_attr_name = None # Entity represents the device itself
_attr_should_poll = False
def __init__(
self,
api: PyAxencoAPI,
device: dict[str, Any],
description: MyNeoSelectEntityDescription,
) -> None:
"""Initialize the MyNeoSelect entity."""
self.entity_description = description
self._api = api
self._device = device
self._attr_unique_id = device["_id"]
self._attr_available = device["connected"]
self._attr_device_info = dr.DeviceInfo(
identifiers={(DOMAIN, device["_id"])},
name=device["name"],
manufacturer="Axenco",
model=device["model"],
)
# Set current option based on device state
current_mode = device.get("state", {}).get(description.state_key)
self._attr_current_option = description.reverse_preset_mode_map.get(
current_mode
)
self._unavailable_logged: bool = False
async def async_added_to_hass(self) -> None:
"""Register listener when entity is added to hass."""
await super().async_added_to_hass()
if unsubscribe := self._api.register_listener(
self._device["_id"], self.handle_ws_update
):
self.async_on_remove(unsubscribe)
@callback
def handle_ws_update(self, new_state: dict[str, Any]) -> None:
"""Handle WebSocket updates for the device."""
if not new_state:
return
if "connected" in new_state:
self._attr_available = new_state["connected"]
if not self._attr_available:
if not self._unavailable_logged:
_LOGGER.info("The entity %s is unavailable", self.entity_id)
self._unavailable_logged = True
elif self._unavailable_logged:
_LOGGER.info("The entity %s is back online", self.entity_id)
self._unavailable_logged = False
# Check for state updates using the description's state_key
state_key = self.entity_description.state_key
if state_key in new_state:
mode = new_state.get(state_key)
if mode is not None:
self._attr_current_option = (
self.entity_description.reverse_preset_mode_map.get(mode)
)
self.async_write_ha_state()
async def async_select_option(self, option: str) -> None:
"""Send the new mode via the API."""
mode_code = self.entity_description.preset_mode_map.get(option)
if mode_code is None:
_LOGGER.warning("Unknown mode selected: %s", option)
return
await self._api.set_device_mode(self._device["_id"], mode_code)
self._attr_current_option = option
self.async_write_ha_state()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/myneomitis/select.py",
"license": "Apache License 2.0",
"lines": 171,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/myneomitis/test_config_flow.py | """Test the configuration flow for MyNeomitis integration."""
from unittest.mock import AsyncMock
from aiohttp import ClientConnectionError, ClientError, ClientResponseError, RequestInfo
import pytest
from yarl import URL
from homeassistant.components.myneomitis.const import CONF_USER_ID, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
TEST_EMAIL = "test@example.com"
TEST_PASSWORD = "password123"
def make_client_response_error(status: int) -> ClientResponseError:
"""Create a mock ClientResponseError with the given status code."""
request_info = RequestInfo(
url=URL("https://api.fake"),
method="POST",
headers={},
real_url=URL("https://api.fake"),
)
return ClientResponseError(
request_info=request_info,
history=(),
status=status,
message="error",
headers=None,
)
async def test_user_flow_success(
hass: HomeAssistant,
mock_pyaxenco_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test successful user flow for MyNeomitis integration."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_EMAIL: TEST_EMAIL, CONF_PASSWORD: TEST_PASSWORD},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"MyNeomitis ({TEST_EMAIL})"
assert result["data"] == {
CONF_EMAIL: TEST_EMAIL,
CONF_PASSWORD: TEST_PASSWORD,
CONF_USER_ID: "user-123",
}
assert result["result"].unique_id == "user-123"
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(ClientConnectionError(), "cannot_connect"),
(make_client_response_error(401), "invalid_auth"),
(make_client_response_error(403), "unknown"),
(make_client_response_error(500), "cannot_connect"),
(ClientError("Network error"), "unknown"),
(RuntimeError("boom"), "unknown"),
],
)
async def test_flow_errors(
hass: HomeAssistant,
mock_pyaxenco_client: AsyncMock,
mock_setup_entry: AsyncMock,
side_effect: Exception,
expected_error: str,
) -> None:
"""Test flow errors and recovery to CREATE_ENTRY."""
mock_pyaxenco_client.login.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={CONF_EMAIL: TEST_EMAIL, CONF_PASSWORD: TEST_PASSWORD},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == expected_error
mock_pyaxenco_client.login.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_EMAIL: TEST_EMAIL, CONF_PASSWORD: TEST_PASSWORD},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_abort_if_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""Test abort when an entry for the same user_id already exists."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_EMAIL: TEST_EMAIL, CONF_PASSWORD: TEST_PASSWORD},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/myneomitis/test_config_flow.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/myneomitis/test_init.py | """Tests for the MyNeomitis integration."""
from unittest.mock import AsyncMock
import pytest
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_minimal_setup(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""Test the minimal setup of the MyNeomitis integration."""
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
async def test_setup_entry_raises_on_login_fail(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""Test that async_setup_entry sets entry to retry if login fails."""
mock_pyaxenco_client.login.side_effect = TimeoutError("fail-login")
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_unload_entry_success(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""Test that unloading via hass.config_entries.async_unload disconnects cleanly."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(mock_config_entry.entry_id)
mock_pyaxenco_client.disconnect_websocket.assert_awaited_once()
async def test_unload_entry_logs_on_disconnect_error(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""When disconnecting the websocket fails, an error is logged."""
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
mock_pyaxenco_client.disconnect_websocket.side_effect = TimeoutError("to")
caplog.set_level("ERROR")
result = await hass.config_entries.async_unload(mock_config_entry.entry_id)
assert result is True
assert "Error while disconnecting WebSocket" in caplog.text
async def test_homeassistant_stop_disconnects_websocket(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""Test that WebSocket is disconnected on Home Assistant stop event."""
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
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
await hass.async_block_till_done()
mock_pyaxenco_client.disconnect_websocket.assert_awaited_once()
async def test_homeassistant_stop_logs_on_disconnect_error(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""Test that WebSocket disconnect errors are logged on HA stop."""
mock_pyaxenco_client.disconnect_websocket.side_effect = TimeoutError(
"disconnect failed"
)
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
caplog.set_level("ERROR")
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
await hass.async_block_till_done()
assert "Error while disconnecting WebSocket" in caplog.text
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/myneomitis/test_init.py",
"license": "Apache License 2.0",
"lines": 86,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/myneomitis/test_select.py | """Tests for the MyNeomitis select component."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import ATTR_ENTITY_ID
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
RELAIS_DEVICE = {
"_id": "relais1",
"name": "Relais Device",
"model": "EWS",
"state": {"relayMode": 1, "targetMode": 2},
"connected": True,
"program": {"data": {}},
}
PILOTE_DEVICE = {
"_id": "pilote1",
"name": "Pilote Device",
"model": "EWS",
"state": {"targetMode": 1},
"connected": True,
"program": {"data": {}},
}
UFH_DEVICE = {
"_id": "ufh1",
"name": "UFH Device",
"model": "UFH",
"state": {"changeOverUser": 0},
"connected": True,
"program": {"data": {}},
}
async def test_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all select entities are created for supported devices."""
mock_pyaxenco_client.get_devices.return_value = [
RELAIS_DEVICE,
PILOTE_DEVICE,
UFH_DEVICE,
{
"_id": "unsupported",
"name": "Unsupported Device",
"model": "UNKNOWN",
"state": {},
"connected": True,
"program": {"data": {}},
},
]
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_select_option(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""Test that selecting an option propagates to the library correctly."""
mock_pyaxenco_client.get_devices.return_value = [RELAIS_DEVICE]
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
"select",
"select_option",
{ATTR_ENTITY_ID: "select.relais_device", "option": "on"},
blocking=True,
)
mock_pyaxenco_client.set_device_mode.assert_awaited_once_with("relais1", 1)
state = hass.states.get("select.relais_device")
assert state is not None
assert state.state == "on"
async def test_websocket_state_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""Test that entity updates when source data changes via WebSocket."""
mock_pyaxenco_client.get_devices.return_value = [RELAIS_DEVICE]
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("select.relais_device")
assert state is not None
assert state.state == "off"
mock_pyaxenco_client.register_listener.assert_called_once()
callback = mock_pyaxenco_client.register_listener.call_args[0][1]
callback({"targetMode": 1})
await hass.async_block_till_done()
state = hass.states.get("select.relais_device")
assert state is not None
assert state.state == "on"
async def test_device_becomes_unavailable(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_pyaxenco_client: AsyncMock,
) -> None:
"""Test that entity becomes unavailable when device connection is lost."""
mock_pyaxenco_client.get_devices.return_value = [RELAIS_DEVICE]
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("select.relais_device")
assert state is not None
assert state.state == "off"
callback = mock_pyaxenco_client.register_listener.call_args[0][1]
callback({"connected": False})
await hass.async_block_till_done()
state = hass.states.get("select.relais_device")
assert state is not None
assert state.state == "unavailable"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/myneomitis/test_select.py",
"license": "Apache License 2.0",
"lines": 115,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/zinvolt/config_flow.py | """Config flow for the Zinvolt integration."""
from __future__ import annotations
import logging
from typing import Any
import jwt
import voluptuous as vol
from zinvolt import ZinvoltClient
from zinvolt.exceptions import ZinvoltAuthenticationError, ZinvoltError
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_EMAIL, CONF_PASSWORD
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
class ZinvoltConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Zinvolt."""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
session = async_get_clientsession(self.hass)
client = ZinvoltClient(session=session)
try:
token = await client.login(
user_input[CONF_EMAIL], user_input[CONF_PASSWORD]
)
except ZinvoltAuthenticationError:
errors["base"] = "invalid_auth"
except ZinvoltError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
# Extract the user ID from the JWT token's 'sub' field
decoded_token = jwt.decode(token, options={"verify_signature": False})
user_id = decoded_token["sub"]
await self.async_set_unique_id(user_id)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=user_input[CONF_EMAIL], data={CONF_ACCESS_TOKEN: token}
)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_EMAIL): str,
vol.Required(CONF_PASSWORD): str,
}
),
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zinvolt/config_flow.py",
"license": "Apache License 2.0",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/zinvolt/coordinator.py | """Coordinator for Zinvolt."""
from datetime import timedelta
import logging
from zinvolt import ZinvoltClient
from zinvolt.exceptions import ZinvoltError
from zinvolt.models import Battery, BatteryState
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
type ZinvoltConfigEntry = ConfigEntry[dict[str, ZinvoltDeviceCoordinator]]
class ZinvoltDeviceCoordinator(DataUpdateCoordinator[BatteryState]):
"""Class for Zinvolt devices."""
def __init__(
self,
hass: HomeAssistant,
config_entry: ZinvoltConfigEntry,
client: ZinvoltClient,
battery: Battery,
) -> None:
"""Initialize the Zinvolt device."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name=f"Zinvolt {battery.identifier}",
update_interval=timedelta(minutes=5),
)
self.battery = battery
self.client = client
async def _async_update_data(self) -> BatteryState:
"""Update data from Zinvolt."""
try:
return await self.client.get_battery_status(self.battery.identifier)
except ZinvoltError as err:
raise UpdateFailed(
translation_key="update_failed",
translation_domain=DOMAIN,
) from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zinvolt/coordinator.py",
"license": "Apache License 2.0",
"lines": 40,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/zinvolt/sensor.py | """Sensor platform for Zinvolt integration."""
from collections.abc import Callable
from dataclasses import dataclass
from zinvolt.models import BatteryState
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import PERCENTAGE, UnitOfPower
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import ZinvoltConfigEntry, ZinvoltDeviceCoordinator
from .entity import ZinvoltEntity
@dataclass(kw_only=True, frozen=True)
class ZinvoltBatteryStateDescription(SensorEntityDescription):
"""Sensor description for Zinvolt battery state."""
value_fn: Callable[[BatteryState], float]
SENSORS: tuple[ZinvoltBatteryStateDescription, ...] = (
ZinvoltBatteryStateDescription(
key="state_of_charge",
device_class=SensorDeviceClass.BATTERY,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=PERCENTAGE,
value_fn=lambda state: state.current_power.state_of_charge,
),
ZinvoltBatteryStateDescription(
key="power",
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
native_unit_of_measurement=UnitOfPower.WATT,
value_fn=lambda state: 0 - state.current_power.power_socket_output,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: ZinvoltConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Initialize the entries."""
async_add_entities(
ZinvoltBatteryStateSensor(coordinator, description)
for description in SENSORS
for coordinator in entry.runtime_data.values()
)
class ZinvoltBatteryStateSensor(ZinvoltEntity, SensorEntity):
"""Zinvolt battery state sensor."""
entity_description: ZinvoltBatteryStateDescription
def __init__(
self,
coordinator: ZinvoltDeviceCoordinator,
description: ZinvoltBatteryStateDescription,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.data.serial_number}.{description.key}"
@property
def native_value(self) -> float:
"""Return the state of the sensor."""
return self.entity_description.value_fn(self.coordinator.data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zinvolt/sensor.py",
"license": "Apache License 2.0",
"lines": 62,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/zinvolt/test_config_flow.py | """Test the Zinvolt config flow."""
from unittest.mock import AsyncMock
import pytest
from zinvolt.exceptions import ZinvoltAuthenticationError, ZinvoltError
from homeassistant.components.zinvolt.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_EMAIL, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import TOKEN
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_zinvolt_client")
async def test_full_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test the full flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_EMAIL: "test@test.com",
CONF_PASSWORD: "yes",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test@test.com"
assert result["data"] == {CONF_ACCESS_TOKEN: TOKEN}
assert result["result"].unique_id == "a0226b8f-98fe-4524-b369-272b466b8797"
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("exception", "error"),
[
(ZinvoltAuthenticationError, "invalid_auth"),
(ZinvoltError, "cannot_connect"),
(Exception, "unknown"),
],
)
async def test_form_errors(
hass: HomeAssistant,
mock_zinvolt_client: AsyncMock,
mock_setup_entry: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test we handle invalid auth."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_zinvolt_client.login.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_EMAIL: "test@test.com",
CONF_PASSWORD: "yes",
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error}
mock_zinvolt_client.login.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_EMAIL: "test@test.com",
CONF_PASSWORD: "yes",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_zinvolt_client")
async def test_duplicate_entry(
hass: HomeAssistant, 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}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_EMAIL: "test@test.com",
CONF_PASSWORD: "yes",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/zinvolt/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 88,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/zinvolt/test_init.py | """Test the Zinvolt initialization."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.zinvolt.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from . import setup_integration
from tests.common import MockConfigEntry
async def test_device(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_config_entry: MockConfigEntry,
mock_zinvolt_client: AsyncMock,
snapshot: SnapshotAssertion,
) -> None:
"""Test the Zinvolt device."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device({(DOMAIN, "ZVG011025120088")})
assert device
assert device == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/zinvolt/test_init.py",
"license": "Apache License 2.0",
"lines": 20,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/zinvolt/test_sensor.py | """Tests for the Zinvolt sensor."""
from unittest.mock import AsyncMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_zinvolt_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.zinvolt._PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/zinvolt/test_sensor.py",
"license": "Apache License 2.0",
"lines": 19,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/touchline_sl/test_climate.py | """Tests for the Roth Touchline SL climate platform."""
from unittest.mock import AsyncMock, MagicMock
import pytest
from homeassistant.components.climate import HVACMode
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from .conftest import make_mock_module, make_mock_zone
from tests.common import MockConfigEntry
ENTITY_ID = "climate.zone_1"
async def test_climate_zone_available(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_touchlinesl_client: MagicMock,
) -> None:
"""Test that the climate entity is available when zone has no alarm."""
zone = make_mock_zone(alarm=None)
module = make_mock_module([zone])
mock_touchlinesl_client.modules = AsyncMock(return_value=[module])
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == HVACMode.HEAT
@pytest.mark.parametrize("alarm", ["no_communication", "sensor_damaged"])
async def test_climate_zone_unavailable_on_alarm(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_touchlinesl_client: MagicMock,
alarm: str,
) -> None:
"""Test that the climate entity is unavailable when zone reports an alarm state."""
zone = make_mock_zone(alarm=alarm)
module = make_mock_module([zone])
mock_touchlinesl_client.modules = AsyncMock(return_value=[module])
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/touchline_sl/test_climate.py",
"license": "Apache License 2.0",
"lines": 41,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/velux/number.py | """Support for Velux exterior heating number entities."""
from __future__ import annotations
from pyvlx import ExteriorHeating, Intensity
from homeassistant.components.number import NumberEntity
from homeassistant.const import PERCENTAGE
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import VeluxConfigEntry
from .entity import VeluxEntity, wrap_pyvlx_call_exceptions
PARALLEL_UPDATES = 1
async def async_setup_entry(
hass: HomeAssistant,
config_entry: VeluxConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up number entities for the Velux platform."""
pyvlx = config_entry.runtime_data
async_add_entities(
VeluxExteriorHeatingNumber(node, config_entry.entry_id)
for node in pyvlx.nodes
if isinstance(node, ExteriorHeating)
)
class VeluxExteriorHeatingNumber(VeluxEntity, NumberEntity):
"""Representation of an exterior heating intensity control."""
_attr_native_min_value = 0
_attr_native_max_value = 100
_attr_native_step = 1
_attr_native_unit_of_measurement = PERCENTAGE
_attr_name = None
node: ExteriorHeating
@property
def native_value(self) -> float | None:
"""Return the current heating intensity in percent."""
return (
self.node.intensity.intensity_percent if self.node.intensity.known else None
)
@wrap_pyvlx_call_exceptions
async def async_set_native_value(self, value: float) -> None:
"""Set the heating intensity."""
await self.node.set_intensity(
Intensity(intensity_percent=round(value)),
wait_for_completion=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/velux/number.py",
"license": "Apache License 2.0",
"lines": 43,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/velux/test_number.py | """Test Velux number entities."""
from __future__ import annotations
from unittest.mock import AsyncMock
import pytest
from pyvlx import Intensity
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.components.velux.const import DOMAIN
from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
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
pytestmark = pytest.mark.usefixtures("setup_integration")
@pytest.fixture
def platform() -> Platform:
"""Fixture to specify platform to test."""
return Platform.NUMBER
def get_number_entity_id(mock: AsyncMock) -> str:
"""Helper to get the entity ID for a given mock node."""
return f"number.{mock.name.lower().replace(' ', '_')}"
async def test_number_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,
)
async def test_number_device_association(
hass: HomeAssistant,
mock_exterior_heating: AsyncMock,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Ensure exterior heating number entity is associated with a device."""
entity_id = get_number_entity_id(mock_exterior_heating)
entry = entity_registry.async_get(entity_id)
assert entry is not None
assert entry.device_id is not None
device_entry = device_registry.async_get(entry.device_id)
assert device_entry is not None
assert (DOMAIN, mock_exterior_heating.serial_number) in device_entry.identifiers
async def test_get_intensity(
hass: HomeAssistant,
mock_exterior_heating: AsyncMock,
) -> None:
"""Entity state follows intensity value and becomes unknown when not known."""
entity_id = get_number_entity_id(mock_exterior_heating)
# Set initial intensity values
mock_exterior_heating.intensity.intensity_percent = 20
await update_callback_entity(hass, mock_exterior_heating)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "20"
mock_exterior_heating.intensity.known = False
await update_callback_entity(hass, mock_exterior_heating)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == STATE_UNKNOWN
async def test_set_value_sets_intensity(
hass: HomeAssistant,
mock_exterior_heating: AsyncMock,
) -> None:
"""Calling set_value forwards to set_intensity."""
entity_id = get_number_entity_id(mock_exterior_heating)
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_VALUE: 30, "entity_id": entity_id},
blocking=True,
)
mock_exterior_heating.set_intensity.assert_awaited_once()
args, kwargs = mock_exterior_heating.set_intensity.await_args
intensity = args[0]
assert isinstance(intensity, Intensity)
assert intensity.intensity_percent == 30
assert kwargs.get("wait_for_completion") is True
async def test_set_invalid_value_fails(
hass: HomeAssistant,
mock_exterior_heating: AsyncMock,
) -> None:
"""Values outside the valid range raise ServiceValidationError and do not call set_intensity."""
entity_id = get_number_entity_id(mock_exterior_heating)
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_VALUE: 101, "entity_id": entity_id},
blocking=True,
)
mock_exterior_heating.set_intensity.assert_not_awaited()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/velux/test_number.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:homeassistant/components/trane/config_flow.py | """Config flow for the Trane Local integration."""
from __future__ import annotations
import logging
from typing import Any
from steamloop import PairingError, SteamloopConnectionError, ThermostatConnection
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_HOST
from .const import CONF_SECRET_KEY, DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_HOST): str,
}
)
class TraneConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Trane Local."""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the user step."""
errors: dict[str, str] = {}
if user_input is not None:
host = user_input[CONF_HOST]
self._async_abort_entries_match({CONF_HOST: host})
conn = ThermostatConnection(host, secret_key="")
try:
await conn.connect()
await conn.pair()
except SteamloopConnectionError, PairingError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception during pairing")
errors["base"] = "unknown"
else:
return self.async_create_entry(
title=f"Thermostat ({host})",
data={
CONF_HOST: host,
CONF_SECRET_KEY: conn.secret_key,
},
)
finally:
await conn.disconnect()
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/trane/config_flow.py",
"license": "Apache License 2.0",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/trane/entity.py | """Base entity for the Trane Local integration."""
from __future__ import annotations
from typing import Any
from steamloop import ThermostatConnection, Zone
from homeassistant.core import callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity import Entity
from .const import DOMAIN, MANUFACTURER
class TraneEntity(Entity):
"""Base class for all Trane entities."""
_attr_has_entity_name = True
_attr_should_poll = False
def __init__(self, conn: ThermostatConnection) -> None:
"""Initialize the entity."""
self._conn = conn
async def async_added_to_hass(self) -> None:
"""Register event callback when added to hass."""
self.async_on_remove(self._conn.add_event_callback(self._handle_event))
@callback
def _handle_event(self, _event: dict[str, Any]) -> None:
"""Handle a thermostat event."""
self.async_write_ha_state()
class TraneZoneEntity(TraneEntity):
"""Base class for Trane zone-level entities."""
def __init__(
self,
conn: ThermostatConnection,
entry_id: str,
zone_id: str,
unique_id_suffix: str,
) -> None:
"""Initialize the entity."""
super().__init__(conn)
self._zone_id = zone_id
self._attr_unique_id = f"{entry_id}_{zone_id}_{unique_id_suffix}"
zone_name = self._zone.name or f"Zone {zone_id}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, f"{entry_id}_{zone_id}")},
manufacturer=MANUFACTURER,
name=zone_name,
suggested_area=zone_name,
via_device=(DOMAIN, entry_id),
)
@property
def available(self) -> bool:
"""Return True if the zone is available."""
return self._zone_id in self._conn.state.zones
@property
def _zone(self) -> Zone:
"""Return the current zone state."""
return self._conn.state.zones[self._zone_id]
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/trane/entity.py",
"license": "Apache License 2.0",
"lines": 51,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/trane/switch.py | """Switch platform for the Trane Local integration."""
from __future__ import annotations
from typing import Any
from steamloop import HoldType, ThermostatConnection
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .entity import TraneZoneEntity
from .types import TraneConfigEntry
PARALLEL_UPDATES = 0
async def async_setup_entry(
hass: HomeAssistant,
config_entry: TraneConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Trane Local switch entities."""
conn = config_entry.runtime_data
async_add_entities(
TraneHoldSwitch(conn, config_entry.entry_id, zone_id)
for zone_id in conn.state.zones
)
class TraneHoldSwitch(TraneZoneEntity, SwitchEntity):
"""Switch to control the hold mode of a thermostat zone."""
_attr_translation_key = "hold"
def __init__(self, conn: ThermostatConnection, entry_id: str, zone_id: str) -> None:
"""Initialize the hold switch."""
super().__init__(conn, entry_id, zone_id, "hold")
@property
def is_on(self) -> bool:
"""Return true if the zone is in permanent hold."""
return self._zone.hold_type == HoldType.MANUAL
async def async_turn_on(self, **kwargs: Any) -> None:
"""Enable permanent hold."""
self._conn.set_temperature_setpoint(self._zone_id, hold_type=HoldType.MANUAL)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Return to schedule."""
self._conn.set_temperature_setpoint(self._zone_id, hold_type=HoldType.SCHEDULE)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/trane/switch.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:tests/components/trane/test_config_flow.py | """Tests for the Trane Local config flow."""
from unittest.mock import MagicMock
import pytest
from steamloop import PairingError, SteamloopConnectionError
from homeassistant.components.trane.const import CONF_SECRET_KEY, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import MOCK_HOST, MOCK_SECRET_KEY
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_setup_entry")
async def test_full_user_flow(
hass: HomeAssistant,
mock_connection: MagicMock,
) -> None:
"""Test the full 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"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: MOCK_HOST},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"Thermostat ({MOCK_HOST})"
assert result["data"] == {
CONF_HOST: MOCK_HOST,
CONF_SECRET_KEY: MOCK_SECRET_KEY,
}
assert result["result"].unique_id is None
@pytest.mark.usefixtures("mock_setup_entry")
@pytest.mark.parametrize(
("side_effect", "error_key"),
[
(SteamloopConnectionError, "cannot_connect"),
(PairingError, "cannot_connect"),
(RuntimeError, "unknown"),
],
)
async def test_form_errors_can_recover(
hass: HomeAssistant,
mock_connection: MagicMock,
side_effect: Exception,
error_key: str,
) -> None:
"""Test errors and recovery during config flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_connection.pair.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: MOCK_HOST},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_key}
mock_connection.pair.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: MOCK_HOST},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"Thermostat ({MOCK_HOST})"
assert result["data"] == {
CONF_HOST: MOCK_HOST,
CONF_SECRET_KEY: MOCK_SECRET_KEY,
}
@pytest.mark.usefixtures("mock_setup_entry")
async def test_already_configured(
hass: HomeAssistant,
mock_connection: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test config flow aborts when already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: MOCK_HOST},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/trane/test_config_flow.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/trane/test_init.py | """Tests for the Trane Local integration setup."""
from unittest.mock import MagicMock
from steamloop import AuthenticationError, SteamloopConnectionError
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_load_unload(
hass: HomeAssistant,
init_integration: MockConfigEntry,
) -> None:
"""Test loading and unloading the integration."""
entry = init_integration
assert entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.NOT_LOADED
async def test_setup_connection_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test setup retries on connection error."""
mock_connection.connect.side_effect = SteamloopConnectionError
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_setup_auth_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test setup fails on authentication error."""
mock_connection.login.side_effect = AuthenticationError
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_setup_timeout_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test setup retries on timeout."""
mock_connection.connect.side_effect = TimeoutError
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/trane/test_init.py",
"license": "Apache License 2.0",
"lines": 49,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/trane/test_switch.py | """Tests for the Trane Local switch platform."""
from unittest.mock import MagicMock
import pytest
from steamloop import HoldType
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Platforms, which should be loaded during the test."""
return [Platform.SWITCH]
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_switch_entities(
hass: HomeAssistant,
init_integration: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Snapshot all switch entities."""
await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id)
async def test_hold_switch_off(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_connection: MagicMock,
) -> None:
"""Test hold switch reports off when following schedule."""
mock_connection.state.zones["1"].hold_type = HoldType.SCHEDULE
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get("switch.living_room_hold")
assert state is not None
assert state.state == STATE_OFF
@pytest.mark.parametrize(
("service", "expected_hold_type"),
[
(SERVICE_TURN_ON, HoldType.MANUAL),
(SERVICE_TURN_OFF, HoldType.SCHEDULE),
],
)
async def test_hold_switch_service(
hass: HomeAssistant,
init_integration: MockConfigEntry,
mock_connection: MagicMock,
service: str,
expected_hold_type: HoldType,
) -> None:
"""Test turning on and off the hold switch."""
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: "switch.living_room_hold"},
blocking=True,
)
mock_connection.set_temperature_setpoint.assert_called_once_with(
"1", hold_type=expected_hold_type
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/trane/test_switch.py",
"license": "Apache License 2.0",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/cambridge_audio/number.py | """Support for Cambridge Audio number entities."""
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING
from aiostreammagic import StreamMagicClient
from homeassistant.components.number import NumberEntity, NumberEntityDescription
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import CambridgeAudioConfigEntry
from .entity import CambridgeAudioEntity, command
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class CambridgeAudioNumberEntityDescription(NumberEntityDescription):
"""Describes Cambridge Audio number entity."""
exists_fn: Callable[[StreamMagicClient], bool] = lambda _: True
value_fn: Callable[[StreamMagicClient], int]
set_value_fn: Callable[[StreamMagicClient, int], Awaitable[None]]
def room_correction_intensity(client: StreamMagicClient) -> int:
"""Get room correction intensity."""
if TYPE_CHECKING:
assert client.audio.tilt_eq is not None
return client.audio.tilt_eq.intensity
CONTROL_ENTITIES: tuple[CambridgeAudioNumberEntityDescription, ...] = (
CambridgeAudioNumberEntityDescription(
key="room_correction_intensity",
translation_key="room_correction_intensity",
entity_category=EntityCategory.CONFIG,
native_min_value=-15,
native_max_value=15,
native_step=1,
exists_fn=lambda client: client.audio.tilt_eq is not None,
value_fn=room_correction_intensity,
set_value_fn=lambda client, value: client.set_room_correction_intensity(value),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: CambridgeAudioConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Cambridge Audio number entities based on a config entry."""
client = entry.runtime_data
async_add_entities(
CambridgeAudioNumber(entry.runtime_data, description)
for description in CONTROL_ENTITIES
if description.exists_fn(client)
)
class CambridgeAudioNumber(CambridgeAudioEntity, NumberEntity):
"""Defines a Cambridge Audio number entity."""
entity_description: CambridgeAudioNumberEntityDescription
def __init__(
self,
client: StreamMagicClient,
description: CambridgeAudioNumberEntityDescription,
) -> None:
"""Initialize Cambridge Audio number entity."""
super().__init__(client)
self.entity_description = description
self._attr_unique_id = f"{client.info.unit_id}-{description.key}"
@property
def native_value(self) -> int | None:
"""Return the state of the number."""
return self.entity_description.value_fn(self.client)
@command
async def async_set_native_value(self, value: float) -> None:
"""Set the selected value."""
await self.entity_description.set_value_fn(self.client, int(value))
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/cambridge_audio/number.py",
"license": "Apache License 2.0",
"lines": 68,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/cambridge_audio/test_number.py | """Tests for the Cambridge Audio number platform."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_stream_magic_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.cambridge_audio.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_setting_value(
hass: HomeAssistant,
mock_stream_magic_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test setting value."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
service_data={ATTR_VALUE: 13},
target={
ATTR_ENTITY_ID: "number.cambridge_audio_cxnv2_room_correction_intensity"
},
blocking=True,
)
mock_stream_magic_client.set_room_correction_intensity.assert_called_once_with(13)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/cambridge_audio/test_number.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/enocean/test_init.py | """Test the EnOcean integration."""
from unittest.mock import patch
from serial import SerialException
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_device_not_connected(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test that a config entry is not ready if the device is not connected."""
mock_config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.enocean.dongle.SerialCommunicator",
side_effect=SerialException("Device not found"),
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/enocean/test_init.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/energy/test_validate_flow_rate.py | """Test flow rate (stat_rate) validation for gas and water sources."""
import pytest
from homeassistant.components.energy import validate
from homeassistant.components.energy.data import EnergyManager
from homeassistant.const import UnitOfVolumeFlowRate
from homeassistant.core import HomeAssistant
FLOW_RATE_UNITS_STRING = ", ".join(tuple(UnitOfVolumeFlowRate))
@pytest.fixture(autouse=True)
async def setup_energy_for_validation(
mock_energy_manager: EnergyManager,
) -> EnergyManager:
"""Ensure energy manager is set up for validation tests."""
return mock_energy_manager
async def test_validation_gas_flow_rate_valid(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating gas with valid flow rate sensor."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption",
"stat_rate": "sensor.gas_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.gas_consumption",
"10.10",
{
"device_class": "gas",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
hass.states.async_set(
"sensor.gas_flow_rate",
"1.5",
{
"device_class": "volume_flow_rate",
"unit_of_measurement": UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR,
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [[]],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_gas_flow_rate_wrong_unit(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating gas with flow rate sensor having wrong unit."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption",
"stat_rate": "sensor.gas_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.gas_consumption",
"10.10",
{
"device_class": "gas",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
hass.states.async_set(
"sensor.gas_flow_rate",
"1.5",
{
"device_class": "volume_flow_rate",
"unit_of_measurement": "beers",
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "entity_unexpected_unit_volume_flow_rate",
"affected_entities": {("sensor.gas_flow_rate", "beers")},
"translation_placeholders": {
"flow_rate_units": FLOW_RATE_UNITS_STRING
},
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_gas_flow_rate_wrong_state_class(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating gas with flow rate sensor having wrong state class."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption",
"stat_rate": "sensor.gas_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.gas_consumption",
"10.10",
{
"device_class": "gas",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
hass.states.async_set(
"sensor.gas_flow_rate",
"1.5",
{
"device_class": "volume_flow_rate",
"unit_of_measurement": UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR,
"state_class": "total_increasing",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "entity_unexpected_state_class",
"affected_entities": {("sensor.gas_flow_rate", "total_increasing")},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_gas_flow_rate_entity_missing(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating gas with missing flow rate sensor."""
mock_get_metadata["sensor.missing_flow_rate"] = None
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption",
"stat_rate": "sensor.missing_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.gas_consumption",
"10.10",
{
"device_class": "gas",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "statistics_not_defined",
"affected_entities": {("sensor.missing_flow_rate", None)},
"translation_placeholders": None,
},
{
"type": "entity_not_defined",
"affected_entities": {("sensor.missing_flow_rate", None)},
"translation_placeholders": None,
},
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_gas_without_flow_rate(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating gas without flow rate sensor still works."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption",
}
]
}
)
hass.states.async_set(
"sensor.gas_consumption",
"10.10",
{
"device_class": "gas",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [[]],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_water_flow_rate_valid(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating water with valid flow rate sensor."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "water",
"stat_energy_from": "sensor.water_consumption",
"stat_rate": "sensor.water_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.water_consumption",
"10.10",
{
"device_class": "water",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
hass.states.async_set(
"sensor.water_flow_rate",
"2.5",
{
"device_class": "volume_flow_rate",
"unit_of_measurement": UnitOfVolumeFlowRate.LITERS_PER_MINUTE,
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [[]],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_water_flow_rate_wrong_unit(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating water with flow rate sensor having wrong unit."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "water",
"stat_energy_from": "sensor.water_consumption",
"stat_rate": "sensor.water_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.water_consumption",
"10.10",
{
"device_class": "water",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
hass.states.async_set(
"sensor.water_flow_rate",
"2.5",
{
"device_class": "volume_flow_rate",
"unit_of_measurement": "beers",
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "entity_unexpected_unit_volume_flow_rate",
"affected_entities": {("sensor.water_flow_rate", "beers")},
"translation_placeholders": {
"flow_rate_units": FLOW_RATE_UNITS_STRING
},
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_water_flow_rate_wrong_state_class(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating water with flow rate sensor having wrong state class."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "water",
"stat_energy_from": "sensor.water_consumption",
"stat_rate": "sensor.water_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.water_consumption",
"10.10",
{
"device_class": "water",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
hass.states.async_set(
"sensor.water_flow_rate",
"2.5",
{
"device_class": "volume_flow_rate",
"unit_of_measurement": UnitOfVolumeFlowRate.LITERS_PER_MINUTE,
"state_class": "total_increasing",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "entity_unexpected_state_class",
"affected_entities": {
("sensor.water_flow_rate", "total_increasing")
},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_water_flow_rate_entity_missing(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating water with missing flow rate sensor."""
mock_get_metadata["sensor.missing_flow_rate"] = None
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "water",
"stat_energy_from": "sensor.water_consumption",
"stat_rate": "sensor.missing_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.water_consumption",
"10.10",
{
"device_class": "water",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "statistics_not_defined",
"affected_entities": {("sensor.missing_flow_rate", None)},
"translation_placeholders": None,
},
{
"type": "entity_not_defined",
"affected_entities": {("sensor.missing_flow_rate", None)},
"translation_placeholders": None,
},
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_water_without_flow_rate(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating water without flow rate sensor still works."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "water",
"stat_energy_from": "sensor.water_consumption",
}
]
}
)
hass.states.async_set(
"sensor.water_consumption",
"10.10",
{
"device_class": "water",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [[]],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_gas_flow_rate_different_units(
hass: HomeAssistant, mock_energy_manager, mock_get_metadata
) -> None:
"""Test validating gas with flow rate sensors using different valid units."""
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption_1",
"stat_rate": "sensor.gas_flow_m3h",
},
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption_2",
"stat_rate": "sensor.gas_flow_lmin",
},
]
}
)
hass.states.async_set(
"sensor.gas_consumption_1",
"10.10",
{
"device_class": "gas",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
hass.states.async_set(
"sensor.gas_consumption_2",
"20.20",
{
"device_class": "gas",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
hass.states.async_set(
"sensor.gas_flow_m3h",
"1.5",
{
"device_class": "volume_flow_rate",
"unit_of_measurement": UnitOfVolumeFlowRate.CUBIC_METERS_PER_HOUR,
"state_class": "measurement",
},
)
hass.states.async_set(
"sensor.gas_flow_lmin",
"25.0",
{
"device_class": "volume_flow_rate",
"unit_of_measurement": UnitOfVolumeFlowRate.LITERS_PER_MINUTE,
"state_class": "measurement",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [[], []],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_gas_flow_rate_recorder_untracked(
hass: HomeAssistant, mock_energy_manager, mock_is_entity_recorded, mock_get_metadata
) -> None:
"""Test validating gas with flow rate sensor not tracked by recorder."""
mock_is_entity_recorded["sensor.untracked_flow_rate"] = False
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "gas",
"stat_energy_from": "sensor.gas_consumption",
"stat_rate": "sensor.untracked_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.gas_consumption",
"10.10",
{
"device_class": "gas",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "recorder_untracked",
"affected_entities": {("sensor.untracked_flow_rate", None)},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
async def test_validation_water_flow_rate_recorder_untracked(
hass: HomeAssistant, mock_energy_manager, mock_is_entity_recorded, mock_get_metadata
) -> None:
"""Test validating water with flow rate sensor not tracked by recorder."""
mock_is_entity_recorded["sensor.untracked_flow_rate"] = False
await mock_energy_manager.async_update(
{
"energy_sources": [
{
"type": "water",
"stat_energy_from": "sensor.water_consumption",
"stat_rate": "sensor.untracked_flow_rate",
}
]
}
)
hass.states.async_set(
"sensor.water_consumption",
"10.10",
{
"device_class": "water",
"unit_of_measurement": "m³",
"state_class": "total_increasing",
},
)
result = await validate.async_validate(hass)
assert result.as_dict() == {
"energy_sources": [
[
{
"type": "recorder_untracked",
"affected_entities": {("sensor.untracked_flow_rate", None)},
"translation_placeholders": None,
}
]
],
"device_consumption": [],
"device_consumption_water": [],
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/energy/test_validate_flow_rate.py",
"license": "Apache License 2.0",
"lines": 571,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/indevolt/switch.py | """Switch platform for Indevolt integration."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Final
from homeassistant.components.switch import (
SwitchDeviceClass,
SwitchEntity,
SwitchEntityDescription,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import IndevoltConfigEntry
from .coordinator import IndevoltCoordinator
from .entity import IndevoltEntity
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class IndevoltSwitchEntityDescription(SwitchEntityDescription):
"""Custom entity description class for Indevolt switch entities."""
read_key: str
write_key: str
read_on_value: int = 1
read_off_value: int = 0
generation: list[int] = field(default_factory=lambda: [1, 2])
SWITCHES: Final = (
IndevoltSwitchEntityDescription(
key="grid_charging",
translation_key="grid_charging",
generation=[2],
read_key="2618",
write_key="1143",
read_on_value=1001,
read_off_value=1000,
device_class=SwitchDeviceClass.SWITCH,
),
IndevoltSwitchEntityDescription(
key="light",
translation_key="light",
generation=[2],
read_key="7171",
write_key="7265",
device_class=SwitchDeviceClass.SWITCH,
),
IndevoltSwitchEntityDescription(
key="bypass",
translation_key="bypass",
generation=[2],
read_key="680",
write_key="7266",
device_class=SwitchDeviceClass.SWITCH,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: IndevoltConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the switch platform for Indevolt."""
coordinator = entry.runtime_data
device_gen = coordinator.generation
# Switch initialization
async_add_entities(
IndevoltSwitchEntity(coordinator=coordinator, description=description)
for description in SWITCHES
if device_gen in description.generation
)
class IndevoltSwitchEntity(IndevoltEntity, SwitchEntity):
"""Represents a switch entity for Indevolt devices."""
entity_description: IndevoltSwitchEntityDescription
def __init__(
self,
coordinator: IndevoltCoordinator,
description: IndevoltSwitchEntityDescription,
) -> None:
"""Initialize the Indevolt switch entity."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{self.serial_number}_{description.key}"
@property
def is_on(self) -> bool | None:
"""Return true if switch is on."""
raw_value = self.coordinator.data.get(self.entity_description.read_key)
if raw_value is None:
return None
if raw_value == self.entity_description.read_on_value:
return True
if raw_value == self.entity_description.read_off_value:
return False
return None
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn the switch on."""
await self._async_toggle(1)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn the switch off."""
await self._async_toggle(0)
async def _async_toggle(self, value: int) -> None:
"""Toggle the switch on/off."""
success = await self.coordinator.async_push_data(
self.entity_description.write_key, value
)
if success:
await self.coordinator.async_request_refresh()
else:
raise HomeAssistantError(f"Failed to set value {value} for {self.name}")
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/indevolt/switch.py",
"license": "Apache License 2.0",
"lines": 104,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/indevolt/test_switch.py | """Tests for the Indevolt switch platform."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.indevolt.coordinator import SCAN_INTERVAL
from homeassistant.components.switch import SERVICE_TURN_OFF, SERVICE_TURN_ON
from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE, 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, async_fire_time_changed, snapshot_platform
KEY_READ_GRID_CHARGING = "2618"
KEY_WRITE_GRID_CHARGING = "1143"
KEY_READ_LIGHT = "7171"
KEY_WRITE_LIGHT = "7265"
KEY_READ_BYPASS = "680"
KEY_WRITE_BYPASS = "7266"
DEFAULT_STATE_ON = 1
DEFAULT_STATE_OFF = 0
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize("generation", [2], indirect=True)
async def test_switch(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_indevolt: AsyncMock,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test switch entity registration and states."""
with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.SWITCH]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize("generation", [2], indirect=True)
@pytest.mark.parametrize(
("entity_id", "read_key", "write_key", "on_value"),
[
(
"switch.cms_sf2000_allow_grid_charging",
KEY_READ_GRID_CHARGING,
KEY_WRITE_GRID_CHARGING,
1001,
),
(
"switch.cms_sf2000_led_indicator",
KEY_READ_LIGHT,
KEY_WRITE_LIGHT,
DEFAULT_STATE_ON,
),
(
"switch.cms_sf2000_bypass_socket",
KEY_READ_BYPASS,
KEY_WRITE_BYPASS,
DEFAULT_STATE_ON,
),
],
)
async def test_switch_turn_on(
hass: HomeAssistant,
mock_indevolt: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
read_key: str,
write_key: str,
on_value: int,
) -> None:
"""Test turning switches on."""
with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.SWITCH]):
await setup_integration(hass, mock_config_entry)
# Reset mock call count for this iteration
mock_indevolt.set_data.reset_mock()
# Update mock data to reflect the new value
mock_indevolt.fetch_data.return_value[read_key] = on_value
# Call the service to turn on
await hass.services.async_call(
Platform.SWITCH,
SERVICE_TURN_ON,
{"entity_id": entity_id},
blocking=True,
)
# Verify set_data was called with correct parameters
mock_indevolt.set_data.assert_called_with(write_key, 1)
# Verify updated state
assert (state := hass.states.get(entity_id)) is not None
assert state.state == STATE_ON
@pytest.mark.parametrize("generation", [2], indirect=True)
@pytest.mark.parametrize(
("entity_id", "read_key", "write_key", "off_value"),
[
(
"switch.cms_sf2000_allow_grid_charging",
KEY_READ_GRID_CHARGING,
KEY_WRITE_GRID_CHARGING,
1000,
),
(
"switch.cms_sf2000_led_indicator",
KEY_READ_LIGHT,
KEY_WRITE_LIGHT,
DEFAULT_STATE_OFF,
),
(
"switch.cms_sf2000_bypass_socket",
KEY_READ_BYPASS,
KEY_WRITE_BYPASS,
DEFAULT_STATE_OFF,
),
],
)
async def test_switch_turn_off(
hass: HomeAssistant,
mock_indevolt: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
read_key: str,
write_key: str,
off_value: int,
) -> None:
"""Test turning switches off."""
with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.SWITCH]):
await setup_integration(hass, mock_config_entry)
# Reset mock call count for this iteration
mock_indevolt.set_data.reset_mock()
# Update mock data to reflect the new value
mock_indevolt.fetch_data.return_value[read_key] = off_value
# Call the service to turn off
await hass.services.async_call(
Platform.SWITCH,
SERVICE_TURN_OFF,
{"entity_id": entity_id},
blocking=True,
)
# Verify set_data was called with correct parameters
mock_indevolt.set_data.assert_called_with(write_key, 0)
# Verify updated state
assert (state := hass.states.get(entity_id)) is not None
assert state.state == STATE_OFF
@pytest.mark.parametrize("generation", [2], indirect=True)
async def test_switch_set_value_error(
hass: HomeAssistant,
mock_indevolt: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test error handling when toggling a switch."""
with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.SWITCH]):
await setup_integration(hass, mock_config_entry)
# Mock set_data to raise an error
mock_indevolt.set_data.side_effect = HomeAssistantError(
"Device communication failed"
)
# Attempt to switch on
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
Platform.SWITCH,
SERVICE_TURN_ON,
{"entity_id": "switch.cms_sf2000_allow_grid_charging"},
blocking=True,
)
# Verify set_data was called before failing
mock_indevolt.set_data.assert_called_once()
@pytest.mark.parametrize("generation", [2], indirect=True)
async def test_switch_availability(
hass: HomeAssistant,
mock_indevolt: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test switch entity availability / non-availability."""
with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.SWITCH]):
await setup_integration(hass, mock_config_entry)
# Confirm current state is "on"
assert (state := hass.states.get("switch.cms_sf2000_allow_grid_charging"))
assert state.state == STATE_ON
# Simulate fetch_data error
mock_indevolt.fetch_data.side_effect = ConnectionError
freezer.tick(delta=timedelta(seconds=SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Confirm current state is "unavailable"
assert (state := hass.states.get("switch.cms_sf2000_allow_grid_charging"))
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/indevolt/test_switch.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:homeassistant/components/indevolt/number.py | """Number platform for Indevolt integration."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Final
from homeassistant.components.number import (
NumberDeviceClass,
NumberEntity,
NumberEntityDescription,
NumberMode,
)
from homeassistant.const import PERCENTAGE, UnitOfPower
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import IndevoltConfigEntry
from .coordinator import IndevoltCoordinator
from .entity import IndevoltEntity
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class IndevoltNumberEntityDescription(NumberEntityDescription):
"""Custom entity description class for Indevolt number entities."""
generation: list[int] = field(default_factory=lambda: [1, 2])
read_key: str
write_key: str
NUMBERS: Final = (
IndevoltNumberEntityDescription(
key="discharge_limit",
generation=[2],
translation_key="discharge_limit",
read_key="6105",
write_key="1142",
native_min_value=0,
native_max_value=100,
native_step=1,
native_unit_of_measurement=PERCENTAGE,
device_class=NumberDeviceClass.BATTERY,
),
IndevoltNumberEntityDescription(
key="max_ac_output_power",
generation=[2],
translation_key="max_ac_output_power",
read_key="11011",
write_key="1147",
native_min_value=0,
native_max_value=2400,
native_step=100,
native_unit_of_measurement=UnitOfPower.WATT,
device_class=NumberDeviceClass.POWER,
),
IndevoltNumberEntityDescription(
key="inverter_input_limit",
generation=[2],
translation_key="inverter_input_limit",
read_key="11009",
write_key="1138",
native_min_value=100,
native_max_value=2400,
native_step=100,
native_unit_of_measurement=UnitOfPower.WATT,
device_class=NumberDeviceClass.POWER,
),
IndevoltNumberEntityDescription(
key="feedin_power_limit",
generation=[2],
translation_key="feedin_power_limit",
read_key="11010",
write_key="1146",
native_min_value=0,
native_max_value=2400,
native_step=100,
native_unit_of_measurement=UnitOfPower.WATT,
device_class=NumberDeviceClass.POWER,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: IndevoltConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the number platform for Indevolt."""
coordinator = entry.runtime_data
device_gen = coordinator.generation
# Number initialization
async_add_entities(
IndevoltNumberEntity(coordinator, description)
for description in NUMBERS
if device_gen in description.generation
)
class IndevoltNumberEntity(IndevoltEntity, NumberEntity):
"""Represents a number entity for Indevolt devices."""
entity_description: IndevoltNumberEntityDescription
_attr_mode = NumberMode.BOX
def __init__(
self,
coordinator: IndevoltCoordinator,
description: IndevoltNumberEntityDescription,
) -> None:
"""Initialize the Indevolt number entity."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{self.serial_number}_{description.key}"
@property
def native_value(self) -> int | None:
"""Return the current value of the entity."""
raw_value = self.coordinator.data.get(self.entity_description.read_key)
if raw_value is None:
return None
return int(raw_value)
async def async_set_native_value(self, value: float) -> None:
"""Set a new value for the entity."""
int_value = int(value)
success = await self.coordinator.async_push_data(
self.entity_description.write_key, int_value
)
if success:
await self.coordinator.async_request_refresh()
else:
raise HomeAssistantError(f"Failed to set value {int_value} for {self.name}")
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/indevolt/number.py",
"license": "Apache License 2.0",
"lines": 118,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/indevolt/test_number.py | """Tests for the Indevolt number platform."""
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.indevolt.coordinator import SCAN_INTERVAL
from homeassistant.components.number import SERVICE_SET_VALUE
from homeassistant.const import STATE_UNAVAILABLE, 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, async_fire_time_changed, snapshot_platform
KEY_READ_DISCHARGE_LIMIT = "6105"
KEY_WRITE_DISCHARGE_LIMIT = "1142"
KEY_READ_MAX_AC_OUTPUT_POWER = "11011"
KEY_WRITE_MAX_AC_OUTPUT_POWER = "1147"
KEY_READ_INVERTER_INPUT_LIMIT = "11009"
KEY_WRITE_INVERTER_INPUT_LIMIT = "1138"
KEY_READ_FEEDIN_POWER_LIMIT = "11010"
KEY_WRITE_FEEDIN_POWER_LIMIT = "1146"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize("generation", [2], indirect=True)
async def test_number(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
mock_indevolt: AsyncMock,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test number entity registration and values."""
with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.NUMBER]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize("generation", [2], indirect=True)
@pytest.mark.parametrize(
("entity_id", "read_key", "write_key", "test_value"),
[
(
"number.cms_sf2000_discharge_limit",
KEY_READ_DISCHARGE_LIMIT,
KEY_WRITE_DISCHARGE_LIMIT,
50,
),
(
"number.cms_sf2000_max_ac_output_power",
KEY_READ_MAX_AC_OUTPUT_POWER,
KEY_WRITE_MAX_AC_OUTPUT_POWER,
1500,
),
(
"number.cms_sf2000_inverter_input_limit",
KEY_READ_INVERTER_INPUT_LIMIT,
KEY_WRITE_INVERTER_INPUT_LIMIT,
800,
),
(
"number.cms_sf2000_feed_in_power_limit",
KEY_READ_FEEDIN_POWER_LIMIT,
KEY_WRITE_FEEDIN_POWER_LIMIT,
1200,
),
],
)
async def test_number_set_values(
hass: HomeAssistant,
mock_indevolt: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
read_key: str,
write_key: str,
test_value: int,
) -> None:
"""Test setting number values for all configurable parameters."""
with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.NUMBER]):
await setup_integration(hass, mock_config_entry)
# Reset mock call count for this iteration
mock_indevolt.set_data.reset_mock()
# Update mock data to reflect the new value
mock_indevolt.fetch_data.return_value[read_key] = test_value
# Call the service to set the value
await hass.services.async_call(
Platform.NUMBER,
SERVICE_SET_VALUE,
{"entity_id": entity_id, "value": test_value},
blocking=True,
)
# Verify set_data was called with correct parameters
mock_indevolt.set_data.assert_called_with(write_key, test_value)
# Verify updated state
assert (state := hass.states.get(entity_id)) is not None
assert int(float(state.state)) == test_value
@pytest.mark.parametrize("generation", [2], indirect=True)
async def test_number_set_value_error(
hass: HomeAssistant,
mock_indevolt: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test error handling when setting number values."""
with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.NUMBER]):
await setup_integration(hass, mock_config_entry)
# Mock set_data to raise an error
mock_indevolt.set_data.side_effect = HomeAssistantError(
"Device communication failed"
)
# Attempt to set value
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
Platform.NUMBER,
SERVICE_SET_VALUE,
{
"entity_id": "number.cms_sf2000_discharge_limit",
"value": 50,
},
blocking=True,
)
# Verify set_data was called before failing
mock_indevolt.set_data.assert_called_once()
@pytest.mark.parametrize("generation", [2], indirect=True)
async def test_number_availability(
hass: HomeAssistant,
mock_indevolt: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test number entity availability / non-availability."""
with patch("homeassistant.components.indevolt.PLATFORMS", [Platform.NUMBER]):
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get("number.cms_sf2000_discharge_limit"))
assert int(float(state.state)) == 5
# Simulate fetch_data error
mock_indevolt.fetch_data.side_effect = ConnectionError
freezer.tick(delta=timedelta(seconds=SCAN_INTERVAL))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get("number.cms_sf2000_discharge_limit"))
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/indevolt/test_number.py",
"license": "Apache License 2.0",
"lines": 138,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/splunk/diagnostics.py | """Diagnostics support for Splunk."""
from __future__ import annotations
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_TOKEN
from homeassistant.core import HomeAssistant
from . import DATA_FILTER
TO_REDACT = {CONF_TOKEN}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: ConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
return {
"entry_data": async_redact_data(dict(entry.data), TO_REDACT),
"entity_filter": hass.data[DATA_FILTER].config,
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/splunk/diagnostics.py",
"license": "Apache License 2.0",
"lines": 18,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/splunk/test_diagnostics.py | """Test Splunk diagnostics."""
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_hass_splunk: ...,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics for config entry."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
result = await get_diagnostics_for_config_entry(
hass, hass_client, mock_config_entry
)
assert result == snapshot(exclude=props("created_at", "modified_at", "entry_id"))
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/splunk/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:homeassistant/components/systemnexa2/config_flow.py | """Config flow for the SystemNexa2 integration."""
from dataclasses import dataclass
import logging
import socket
from typing import Any
import aiohttp
from sn2.device import Device
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import (
ATTR_MODEL,
ATTR_SW_VERSION,
CONF_DEVICE_ID,
CONF_HOST,
CONF_MODEL,
CONF_NAME,
)
from homeassistant.data_entry_flow import AbortFlow
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from homeassistant.util.network import is_ip_address
from . import DOMAIN
_LOGGER = logging.getLogger(__name__)
_SCHEMA = vol.Schema(
{
vol.Required(CONF_HOST): str,
}
)
def _is_valid_host(ip_or_hostname: str) -> bool:
if not ip_or_hostname:
return False
if is_ip_address(ip_or_hostname):
return True
try:
socket.gethostbyname(ip_or_hostname)
except socket.gaierror:
return False
return True
@dataclass(kw_only=True)
class _DiscoveryInfo:
name: str
host: str
model: str
device_id: str
device_version: str
class SystemNexa2ConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for the devices."""
VERSION = 1
def __init__(self) -> None:
"""Initialize the config flow."""
self._discovered_device: _DiscoveryInfo
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle user-initiated flow."""
errors: dict[str, str] = {}
if user_input is None:
return self.async_show_form(step_id="user", data_schema=_SCHEMA)
host_or_ip = user_input[CONF_HOST]
if not _is_valid_host(host_or_ip):
errors["base"] = "invalid_host"
else:
temp_dev = await Device.initiate_device(
host=host_or_ip,
session=async_get_clientsession(self.hass),
)
try:
info = await temp_dev.get_info()
except TimeoutError, aiohttp.ClientError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
if errors:
return self.async_show_form(
step_id="user", data_schema=_SCHEMA, errors=errors
)
device_id = info.information.unique_id
device_model = info.information.model
device_version = info.information.sw_version
if device_id is None or device_model is None or device_version is None:
return self.async_abort(
reason="unsupported_model",
description_placeholders={
ATTR_MODEL: str(device_model),
ATTR_SW_VERSION: str(device_version),
},
)
self._discovered_device = _DiscoveryInfo(
name=info.information.name,
host=host_or_ip,
device_id=device_id,
model=device_model,
device_version=device_version,
)
supported, error = Device.is_device_supported(
model=self._discovered_device.model,
device_version=self._discovered_device.device_version,
)
if not supported:
_LOGGER.error("Unsupported model: %s", error)
raise AbortFlow(
reason="unsupported_model",
description_placeholders={
ATTR_MODEL: str(self._discovered_device.model),
ATTR_SW_VERSION: str(self._discovered_device.device_version),
},
)
await self._async_set_unique_id()
return await self._async_create_device_entry()
async def async_step_zeroconf(
self, discovery_info: ZeroconfServiceInfo
) -> ConfigFlowResult:
"""Handle zeroconf discovery."""
device_id = discovery_info.properties.get("id")
device_model = discovery_info.properties.get("model")
device_version = discovery_info.properties.get("version")
supported, error = Device.is_device_supported(
model=device_model,
device_version=device_version,
)
if (
device_id is None
or device_model is None
or device_version is None
or not supported
):
_LOGGER.error("Unsupported model: %s", error)
return self.async_abort(reason="unsupported_model")
self._discovered_device = _DiscoveryInfo(
name=discovery_info.name.split(".")[0],
host=discovery_info.host,
device_id=device_id,
model=device_model,
device_version=device_version,
)
await self._async_set_unique_id()
return await self.async_step_discovery_confirm()
async def _async_set_unique_id(self) -> None:
await self.async_set_unique_id(self._discovered_device.device_id)
self._abort_if_unique_id_configured(
updates={CONF_HOST: self._discovered_device.host}
)
self.context["title_placeholders"] = {
"name": self._discovered_device.name,
"model": self._discovered_device.model or "Unknown model",
}
async def async_step_discovery_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm discovery."""
if user_input is not None and self._discovered_device is not None:
return await self._async_create_device_entry()
self._set_confirm_only()
return self.async_show_form(
step_id="discovery_confirm",
description_placeholders={"name": self._discovered_device.name},
)
async def _async_create_device_entry(self) -> ConfigFlowResult:
device_name = self._discovered_device.name
device_model = self._discovered_device.model
return self.async_create_entry(
title=f"{device_name} ({device_model})",
data={
CONF_HOST: self._discovered_device.host,
CONF_NAME: self._discovered_device.name,
CONF_MODEL: self._discovered_device.model,
CONF_DEVICE_ID: self._discovered_device.device_id,
},
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/systemnexa2/config_flow.py",
"license": "Apache License 2.0",
"lines": 170,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/systemnexa2/const.py | """Constants for the systemnexa2 integration."""
from typing import Final
from homeassistant.const import Platform
DOMAIN = "systemnexa2"
MANUFACTURER = "NEXA"
PLATFORMS: Final = [Platform.LIGHT, Platform.SENSOR, Platform.SWITCH]
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/systemnexa2/const.py",
"license": "Apache License 2.0",
"lines": 6,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/systemnexa2/coordinator.py | """Data coordinator for System Nexa 2 integration."""
from collections.abc import Awaitable
import logging
import aiohttp
from sn2 import (
ConnectionStatus,
Device,
DeviceInitializationError,
InformationData,
NotConnectedError,
OnOffSetting,
SettingsUpdate,
StateChange,
)
from sn2.device import Setting, UpdateEvent
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
type SystemNexa2ConfigEntry = ConfigEntry[SystemNexa2DataUpdateCoordinator]
class InsufficientDeviceInformation(Exception):
"""Exception raised when device does not provide sufficient information."""
class SystemNexa2Data:
"""Data container for System Nexa 2 device information."""
__slots__ = (
"info_data",
"on_off_settings",
"state",
"unique_id",
)
info_data: InformationData
unique_id: str
on_off_settings: dict[str, OnOffSetting]
state: float | None
def __init__(self) -> None:
"""Initialize the data container."""
self.state = None
self.on_off_settings = {}
def update_settings(self, settings: list[Setting]) -> None:
"""Update the on/off settings from a list of settings."""
self.on_off_settings = {
setting.name: setting
for setting in settings
if isinstance(setting, OnOffSetting)
}
class SystemNexa2DataUpdateCoordinator(DataUpdateCoordinator[SystemNexa2Data]):
"""Data update coordinator for System Nexa 2 devices."""
config_entry: SystemNexa2ConfigEntry
info_data: InformationData
device: Device
def __init__(
self,
hass: HomeAssistant,
config_entry: SystemNexa2ConfigEntry,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
config_entry=config_entry,
update_interval=None,
update_method=None,
always_update=False,
)
self._state_received_once = False
self.data = SystemNexa2Data()
async def async_setup(self) -> None:
"""Set up the coordinator and initialize the device connection."""
try:
self.device = await Device.initiate_device(
host=self.config_entry.data[CONF_HOST],
on_update=self._async_handle_update,
session=async_get_clientsession(self.hass),
)
except DeviceInitializationError as e:
_LOGGER.error(
"Failed to initialize device with IP/Hostname %s, please verify that the device is powered on and reachable on port 3000",
self.config_entry.data[CONF_HOST],
)
raise ConfigEntryNotReady(
translation_domain=DOMAIN,
translation_key="failed_to_initiate_connection",
translation_placeholders={CONF_HOST: self.config_entry.data[CONF_HOST]},
) from e
self.data.unique_id = self.device.info_data.unique_id
self.data.info_data = self.device.info_data
self.data.update_settings(self.device.settings)
await self.device.connect()
async def _async_handle_update(self, event: UpdateEvent) -> None:
data = self.data or SystemNexa2Data()
_is_connected = True
match event:
case ConnectionStatus(connected):
_is_connected = connected
case StateChange(state):
data.state = state
self._state_received_once = True
case SettingsUpdate(settings):
data.update_settings(settings)
if not _is_connected:
self.async_set_update_error(ConnectionError("No connection to device"))
elif (
data.on_off_settings is not None
and self._state_received_once
and data.state is not None
):
self.async_set_updated_data(data)
async def _async_sn2_call_with_error_handling(self, coro: Awaitable[None]) -> None:
"""Execute a coroutine with error handling."""
try:
await coro
except (TimeoutError, NotConnectedError, aiohttp.ClientError) as err:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="device_communication_error",
) from err
async def async_turn_on(self) -> None:
"""Turn on the device."""
await self._async_sn2_call_with_error_handling(self.device.turn_on())
async def async_turn_off(self) -> None:
"""Turn off the device."""
await self._async_sn2_call_with_error_handling(self.device.turn_off())
async def async_toggle(self) -> None:
"""Toggle the device."""
await self._async_sn2_call_with_error_handling(self.device.toggle())
async def async_set_brightness(self, value: float) -> None:
"""Set the brightness of the device (0.0 to 1.0)."""
await self._async_sn2_call_with_error_handling(
self.device.set_brightness(value)
)
async def async_setting_enable(self, setting: OnOffSetting) -> None:
"""Enable a device setting."""
await self._async_sn2_call_with_error_handling(setting.enable(self.device))
async def async_setting_disable(self, setting: OnOffSetting) -> None:
"""Disable a device setting."""
await self._async_sn2_call_with_error_handling(setting.disable(self.device))
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/systemnexa2/coordinator.py",
"license": "Apache License 2.0",
"lines": 141,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/systemnexa2/entity.py | """Base entity for SystemNexa2 integration."""
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN, MANUFACTURER
from .coordinator import SystemNexa2DataUpdateCoordinator
class SystemNexa2Entity(CoordinatorEntity[SystemNexa2DataUpdateCoordinator]):
"""Base entity class for SystemNexa2 devices."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: SystemNexa2DataUpdateCoordinator,
key: str,
) -> None:
"""Initialize the SystemNexa2 entity."""
super().__init__(coordinator)
self._attr_unique_id = f"{coordinator.data.unique_id}-{key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, coordinator.data.unique_id)},
manufacturer=MANUFACTURER,
name=coordinator.data.info_data.name,
model=coordinator.data.info_data.model,
sw_version=coordinator.data.info_data.sw_version,
hw_version=str(coordinator.data.info_data.hw_version),
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/systemnexa2/entity.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/systemnexa2/switch.py | """Switch entity for the SystemNexa2 integration."""
from dataclasses import dataclass
from typing import Any, Final
from sn2.device import OnOffSetting
from homeassistant.components.switch import (
SwitchDeviceClass,
SwitchEntity,
SwitchEntityDescription,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import SystemNexa2ConfigEntry, SystemNexa2DataUpdateCoordinator
from .entity import SystemNexa2Entity
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class SystemNexa2SwitchEntityDescription(SwitchEntityDescription):
"""Entity description for SystemNexa switch entities."""
SWITCH_TYPES: Final = [
SystemNexa2SwitchEntityDescription(
key="433Mhz",
translation_key="433mhz",
entity_category=EntityCategory.CONFIG,
),
SystemNexa2SwitchEntityDescription(
key="Cloud Access",
translation_key="cloud_access",
entity_category=EntityCategory.CONFIG,
),
SystemNexa2SwitchEntityDescription(
key="Led",
translation_key="led",
entity_category=EntityCategory.CONFIG,
),
SystemNexa2SwitchEntityDescription(
key="Physical Button",
translation_key="physical_button",
entity_category=EntityCategory.CONFIG,
),
]
async def async_setup_entry(
hass: HomeAssistant,
entry: SystemNexa2ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up switch and configuration options based on a config entry."""
coordinator = entry.runtime_data
entities: list[SystemNexa2Entity] = [
SystemNexa2ConfigurationSwitch(coordinator, switch_type, setting)
for setting_name, setting in coordinator.data.on_off_settings.items()
for switch_type in SWITCH_TYPES
if switch_type.key == setting_name
]
if coordinator.data.info_data.dimmable is False:
entities.append(
SystemNexa2SwitchPlug(
coordinator=coordinator,
)
)
async_add_entities(entities)
class SystemNexa2ConfigurationSwitch(SystemNexa2Entity, SwitchEntity):
"""Configuration switch entity for SystemNexa2 devices."""
_attr_device_class = SwitchDeviceClass.SWITCH
entity_description: SystemNexa2SwitchEntityDescription
def __init__(
self,
coordinator: SystemNexa2DataUpdateCoordinator,
description: SystemNexa2SwitchEntityDescription,
setting: OnOffSetting,
) -> None:
"""Initialize the configuration switch."""
super().__init__(coordinator, description.key)
self.entity_description = description
self._setting = setting
async def async_turn_on(self, **_kwargs: Any) -> None:
"""Turn on the switch."""
await self.coordinator.async_setting_enable(self._setting)
async def async_turn_off(self, **_kwargs: Any) -> None:
"""Turn off the switch."""
await self.coordinator.async_setting_disable(self._setting)
@property
def is_on(self) -> bool:
"""Return true if the switch is on."""
return self.coordinator.data.on_off_settings[
self.entity_description.key
].is_enabled()
class SystemNexa2SwitchPlug(SystemNexa2Entity, SwitchEntity):
"""Representation of a Switch."""
_attr_translation_key = "relay_1"
def __init__(
self,
coordinator: SystemNexa2DataUpdateCoordinator,
) -> None:
"""Initialize the switch."""
super().__init__(
coordinator=coordinator,
key="relay_1",
)
async def async_turn_on(self, **_kwargs: Any) -> None:
"""Turn on the switch."""
await self.coordinator.async_turn_on()
async def async_turn_off(self, **_kwargs: Any) -> None:
"""Turn off the switch."""
await self.coordinator.async_turn_off()
async def async_toggle(self, **_kwargs: Any) -> None:
"""Toggle the switch."""
await self.coordinator.async_toggle()
@property
def is_on(self) -> bool | None:
"""Return true if the switch is on."""
if self.coordinator.data.state is None:
return None
return bool(self.coordinator.data.state)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/systemnexa2/switch.py",
"license": "Apache License 2.0",
"lines": 113,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/systemnexa2/test_config_flow.py | """Test the SystemNexa2 config flow."""
from ipaddress import ip_address
import socket
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from sn2 import InformationData, InformationUpdate
from homeassistant.components.systemnexa2 import DOMAIN
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.const import CONF_DEVICE_ID, CONF_HOST, CONF_MODEL, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_system_nexa_2_device")
async def test_full_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test full flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Outdoor Smart Plug (WPO-01)"
assert result["data"] == {
CONF_HOST: "10.0.0.131",
CONF_NAME: "Outdoor Smart Plug",
CONF_DEVICE_ID: "aabbccddee02",
CONF_MODEL: "WPO-01",
}
assert result["result"].unique_id == "aabbccddee02"
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_system_nexa_2_device")
async def test_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test we abort if the device is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("exception", "error_key"),
[
(TimeoutError, "cannot_connect"),
(RuntimeError, "unknown"),
],
)
async def test_connection_error_and_recovery(
hass: HomeAssistant,
mock_system_nexa_2_device: MagicMock,
mock_setup_entry: AsyncMock,
exception: type[Exception],
error_key: str,
) -> None:
"""Test connection error handling and recovery."""
mock_system_nexa_2_device.return_value.get_info.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_key}
# Remove the side effect and retry - should succeed now
device = mock_system_nexa_2_device.return_value
device.get_info.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Outdoor Smart Plug (WPO-01)"
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_system_nexa_2_device")
async def test_empty_host(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test invalid hostname/IP address handling."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: ""}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "invalid_host"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.usefixtures("mock_system_nexa_2_device")
async def test_invalid_host(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test invalid hostname/IP address handling."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
with patch(
"homeassistant.components.systemnexa2.config_flow.socket.gethostbyname",
side_effect=socket.gaierror(-2, "Name or service not known"),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "invalid-hostname.local"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "invalid_host"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.usefixtures("mock_system_nexa_2_device")
@pytest.mark.usefixtures("mock_patch_get_host")
async def test_valid_hostname(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None:
"""Test valid hostname handling."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "valid-hostname.local"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Outdoor Smart Plug (WPO-01)"
assert result["data"] == {
CONF_HOST: "valid-hostname.local",
CONF_NAME: "Outdoor Smart Plug",
CONF_DEVICE_ID: "aabbccddee02",
CONF_MODEL: "WPO-01",
}
assert len(mock_setup_entry.mock_calls) == 1
async def test_unsupported_device(
hass: HomeAssistant, mock_system_nexa_2_device: MagicMock
) -> None:
"""Test unsupported device model handling."""
mock_system_nexa_2_device.is_device_supported.return_value = (False, "Err")
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unsupported_model"
assert result["description_placeholders"] == {
"model": "WPO-01",
"sw_version": "Test Model Version",
}
@pytest.mark.usefixtures("mock_system_nexa_2_device")
async def test_zeroconf_discovery(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_zeroconf_discovery_info: ZeroconfServiceInfo,
) -> None:
"""Test zeroconf discovery."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=mock_zeroconf_discovery_info
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "discovery_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "systemnexa2_test (WPO-01)"
assert result["data"] == {
CONF_HOST: "10.0.0.131",
CONF_NAME: "systemnexa2_test",
CONF_DEVICE_ID: "aabbccddee02",
CONF_MODEL: "WPO-01",
}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_system_nexa_2_device")
async def test_zeroconf_discovery_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_zeroconf_discovery_info: ZeroconfServiceInfo,
) -> None:
"""Test we abort zeroconf discovery if the device is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=mock_zeroconf_discovery_info
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_device_with_none_values(
hass: HomeAssistant, mock_system_nexa_2_device: MagicMock
) -> None:
"""Test device with None values in info is rejected."""
device = mock_system_nexa_2_device.return_value
# Create new InformationData with None unique_id
device.info_data = InformationData(
name="Outdoor Smart Plug",
model="WPO-01",
unique_id=None,
sw_version="Test Model Version",
hw_version="Test HW Version",
wifi_dbm=-50,
wifi_ssid="Test WiFi SSID",
dimmable=False,
)
device.get_info.return_value = InformationUpdate(information=device.info_data)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "10.0.0.131"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unsupported_model"
async def test_zeroconf_discovery_none_values(hass: HomeAssistant) -> None:
"""Test zeroconf discovery with None property values is rejected."""
discovery_info = ZeroconfServiceInfo(
ip_address=ip_address("10.0.0.131"),
ip_addresses=[ip_address("10.0.0.131")],
hostname="systemnexa2_test.local.",
name="systemnexa2_test._systemnexa2._tcp.local.",
port=80,
type="_systemnexa2._tcp.local.",
properties={
"id": None,
"model": "WPO-01",
"version": "1.0.0",
},
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_ZEROCONF}, data=discovery_info
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unsupported_model"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/systemnexa2/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 245,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/systemnexa2/test_init.py | """Test the System Nexa 2 integration setup and unload."""
from unittest.mock import AsyncMock, MagicMock
from sn2 import DeviceInitializationError
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_system_nexa_2_device: MagicMock,
) -> None:
"""Test loading and unloading the integration."""
mock_config_entry.add_to_hass(hass)
device = mock_system_nexa_2_device.return_value
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 len(hass.config_entries.async_entries()) == 1
device.connect.assert_called_once()
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
device.disconnect.assert_called_once()
async def test_setup_failure_device_initialization_error(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_system_nexa_2_device: MagicMock,
) -> None:
"""Test setup failure when device initialization fails."""
mock_config_entry.add_to_hass(hass)
mock_system_nexa_2_device.initiate_device = AsyncMock(
side_effect=DeviceInitializationError("Test error")
)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/systemnexa2/test_init.py",
"license": "Apache License 2.0",
"lines": 36,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/systemnexa2/test_switch.py | """Test the System Nexa 2 switch platform."""
from unittest.mock import MagicMock, patch
import pytest
from sn2 import ConnectionStatus, SettingsUpdate, StateChange
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TOGGLE,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
import homeassistant.helpers.entity_registry as er
from . import find_update_callback
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("mock_system_nexa_2_device")
async def test_switch_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the switch entities."""
mock_config_entry.add_to_hass(hass)
# Only load the switch platform for snapshot testing
with patch(
"homeassistant.components.systemnexa2.PLATFORMS",
[Platform.SWITCH],
):
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
async def test_switch_turn_on_off_toggle(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_system_nexa_2_device,
) -> None:
"""Test switch turn on, turn off, and toggle."""
device = mock_system_nexa_2_device.return_value
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Find the callback that was registered with the device
update_callback = find_update_callback(mock_system_nexa_2_device)
await update_callback(StateChange(state=0.0))
await hass.async_block_till_done()
# Test turn on
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.outdoor_smart_plug_relay"},
blocking=True,
)
device.turn_on.assert_called_once()
# Test turn off
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.outdoor_smart_plug_relay"},
blocking=True,
)
device.turn_off.assert_called_once()
# Test toggle
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TOGGLE,
{ATTR_ENTITY_ID: "switch.outdoor_smart_plug_relay"},
blocking=True,
)
device.toggle.assert_called_once()
async def test_switch_is_on_property(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_system_nexa_2_device,
) -> None:
"""Test switch is_on property."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Find the callback that was registered with the device
update_callback = find_update_callback(mock_system_nexa_2_device)
# Test with state = 1.0 (on)
await update_callback(StateChange(state=1.0))
await hass.async_block_till_done()
state = hass.states.get("switch.outdoor_smart_plug_relay")
assert state is not None
assert state.state == "on"
# Test with state = 0.0 (off)
await update_callback(StateChange(state=0.0))
await hass.async_block_till_done()
state = hass.states.get("switch.outdoor_smart_plug_relay")
assert state is not None
assert state.state == "off"
async def test_configuration_switches(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_system_nexa_2_device,
) -> None:
"""Test configuration switch entities."""
device = mock_system_nexa_2_device.return_value
# Settings are already configured in the fixture
mock_setting_433mhz = device.settings[0] # 433Mhz
mock_setting_cloud = device.settings[1] # Cloud Access
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Find the callback that was registered with the device
update_callback = find_update_callback(mock_system_nexa_2_device)
await update_callback(StateChange(state=1.0))
await hass.async_block_till_done()
# Check 433mhz switch state (should be on)
state = hass.states.get("switch.outdoor_smart_plug_433_mhz")
assert state is not None
assert state.state == "on"
# Check cloud_access switch state (should be off)
state = hass.states.get("switch.outdoor_smart_plug_cloud_access")
assert state is not None
assert state.state == "off"
# Test turn off 433mhz
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "switch.outdoor_smart_plug_433_mhz"},
blocking=True,
)
mock_setting_433mhz.disable.assert_called_once_with(device)
# Test turn on cloud_access
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "switch.outdoor_smart_plug_cloud_access"},
blocking=True,
)
mock_setting_cloud.enable.assert_called_once_with(device)
async def test_coordinator_connection_status(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_system_nexa_2_device: MagicMock,
) -> None:
"""Test coordinator handles connection status updates."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Find the callback that was registered with the device
update_callback = find_update_callback(mock_system_nexa_2_device)
# Initially, the relay switch should be on (state=1.0 from fixture)
state = hass.states.get("switch.outdoor_smart_plug_relay")
assert state is not None
assert state.state == STATE_ON
# Simulate device disconnection
await update_callback(ConnectionStatus(connected=False))
await hass.async_block_till_done()
state = hass.states.get("switch.outdoor_smart_plug_relay")
assert state is not None
assert state.state == STATE_UNAVAILABLE
# Simulate reconnection and state update
await update_callback(ConnectionStatus(connected=True))
await update_callback(StateChange(state=1.0))
await hass.async_block_till_done()
state = hass.states.get("switch.outdoor_smart_plug_relay")
assert state is not None
assert state.state == STATE_ON
async def test_coordinator_state_change(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_system_nexa_2_device: MagicMock,
) -> None:
"""Test coordinator handles state change updates."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Find the callback that was registered with the device
update_callback = find_update_callback(mock_system_nexa_2_device)
# Change state to off (0.0)
await update_callback(StateChange(state=0.0))
await hass.async_block_till_done()
state = hass.states.get("switch.outdoor_smart_plug_relay")
assert state is not None
assert state.state == STATE_OFF
# Change state to on (1.0)
await update_callback(StateChange(state=1.0))
await hass.async_block_till_done()
state = hass.states.get("switch.outdoor_smart_plug_relay")
assert state is not None
assert state.state == STATE_ON
async def test_coordinator_settings_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_system_nexa_2_device: MagicMock,
) -> None:
"""Test coordinator handles settings updates."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Find the callback that was registered with the device
update_callback = find_update_callback(mock_system_nexa_2_device)
# Get initial state of 433Mhz switch (should be on from fixture)
state = hass.states.get("switch.outdoor_smart_plug_433_mhz")
assert state is not None
assert state.state == STATE_ON
# Get the settings from the device mock and change 433Mhz to disabled
device = mock_system_nexa_2_device.return_value
device.settings[0].is_enabled.return_value = False # 433Mhz
# Simulate settings update where 433Mhz is now disabled
await update_callback(SettingsUpdate(settings=device.settings))
# Need state update to trigger coordinator data update
await update_callback(StateChange(state=1.0))
await hass.async_block_till_done()
state = hass.states.get("switch.outdoor_smart_plug_433_mhz")
assert state is not None
assert state.state == STATE_OFF
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/systemnexa2/test_switch.py",
"license": "Apache License 2.0",
"lines": 218,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/influxdb/config_flow.py | """Config flow for InfluxDB integration."""
import logging
from pathlib import Path
import shutil
from typing import Any
import voluptuous as vol
from yarl import URL
from homeassistant.components.file_upload import process_uploaded_file
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PATH,
CONF_PORT,
CONF_SSL,
CONF_TOKEN,
CONF_URL,
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.selector import (
FileSelector,
FileSelectorConfig,
TextSelector,
TextSelectorConfig,
TextSelectorType,
)
from homeassistant.helpers.storage import STORAGE_DIR
from . import DOMAIN, get_influx_connection
from .const import (
API_VERSION_2,
CONF_API_VERSION,
CONF_BUCKET,
CONF_DB_NAME,
CONF_ORG,
CONF_SSL_CA_CERT,
DEFAULT_API_VERSION,
DEFAULT_HOST,
DEFAULT_PORT,
)
_LOGGER = logging.getLogger(__name__)
INFLUXDB_V1_SCHEMA = vol.Schema(
{
vol.Required(
CONF_URL, default=f"http://{DEFAULT_HOST}:{DEFAULT_PORT}"
): TextSelector(
TextSelectorConfig(
type=TextSelectorType.URL,
autocomplete="url",
),
),
vol.Required(CONF_VERIFY_SSL, default=False): bool,
vol.Required(CONF_DB_NAME): TextSelector(
TextSelectorConfig(
type=TextSelectorType.TEXT,
),
),
vol.Optional(CONF_USERNAME): TextSelector(
TextSelectorConfig(
type=TextSelectorType.TEXT,
autocomplete="username",
),
),
vol.Optional(CONF_PASSWORD): TextSelector(
TextSelectorConfig(
type=TextSelectorType.PASSWORD,
autocomplete="current-password",
),
),
vol.Optional(CONF_SSL_CA_CERT): FileSelector(
FileSelectorConfig(accept=".pem,.crt,.cer,.der")
),
}
)
INFLUXDB_V2_SCHEMA = vol.Schema(
{
vol.Required(CONF_URL, default="https://"): TextSelector(
TextSelectorConfig(
type=TextSelectorType.URL,
autocomplete="url",
),
),
vol.Required(CONF_VERIFY_SSL, default=False): bool,
vol.Required(CONF_ORG): TextSelector(
TextSelectorConfig(
type=TextSelectorType.TEXT,
),
),
vol.Required(CONF_BUCKET): TextSelector(
TextSelectorConfig(
type=TextSelectorType.TEXT,
),
),
vol.Required(CONF_TOKEN): TextSelector(
TextSelectorConfig(
type=TextSelectorType.PASSWORD,
),
),
vol.Optional(CONF_SSL_CA_CERT): FileSelector(
FileSelectorConfig(accept=".pem,.crt,.cer,.der")
),
}
)
async def _validate_influxdb_connection(
hass: HomeAssistant, data: dict[str, Any]
) -> dict[str, str]:
"""Validate connection to influxdb."""
def _test_connection() -> None:
influx = get_influx_connection(data, test_write=True)
influx.close()
errors = {}
try:
await hass.async_add_executor_job(_test_connection)
except ConnectionError as ex:
_LOGGER.error(ex)
if "SSLError" in ex.args[0]:
errors = {"base": "ssl_error"}
elif "database not found" in ex.args[0]:
errors = {"base": "invalid_database"}
elif "authorization failed" in ex.args[0]:
errors = {"base": "invalid_auth"}
elif "token" in ex.args[0]:
errors = {"base": "invalid_config"}
else:
errors = {"base": "cannot_connect"}
except Exception:
_LOGGER.exception("Unknown error")
errors = {"base": "unknown"}
return errors
async def _save_uploaded_cert_file(hass: HomeAssistant, uploaded_file_id: str) -> Path:
"""Move the uploaded file to storage directory."""
def _process_upload() -> Path:
with process_uploaded_file(hass, uploaded_file_id) as file_path:
dest_path = Path(hass.config.path(STORAGE_DIR, DOMAIN))
dest_path.mkdir(exist_ok=True)
file_name = f"influxdb{file_path.suffix}"
dest_file = dest_path / file_name
shutil.move(file_path, dest_file)
return dest_file
return await hass.async_add_executor_job(_process_upload)
class InfluxDBConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for InfluxDB."""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Step when user initializes an integration."""
return self.async_show_menu(
step_id="user",
menu_options=["configure_v1", "configure_v2"],
)
async def async_step_configure_v1(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Step when user configures InfluxDB v1."""
errors: dict[str, str] = {}
if user_input is not None:
url = URL(user_input[CONF_URL])
data = {
CONF_API_VERSION: DEFAULT_API_VERSION,
CONF_HOST: url.host,
CONF_PORT: url.port,
CONF_USERNAME: user_input.get(CONF_USERNAME),
CONF_PASSWORD: user_input.get(CONF_PASSWORD),
CONF_DB_NAME: user_input[CONF_DB_NAME],
CONF_SSL: url.scheme == "https",
CONF_PATH: url.path,
CONF_VERIFY_SSL: user_input[CONF_VERIFY_SSL],
}
if (cert := user_input.get(CONF_SSL_CA_CERT)) is not None:
path = await _save_uploaded_cert_file(self.hass, cert)
data[CONF_SSL_CA_CERT] = str(path)
errors = await _validate_influxdb_connection(self.hass, data)
if not errors:
title = f"{data[CONF_DB_NAME]} ({data[CONF_HOST]})"
return self.async_create_entry(title=title, data=data)
schema = INFLUXDB_V1_SCHEMA
return self.async_show_form(
step_id="configure_v1",
data_schema=self.add_suggested_values_to_schema(schema, user_input),
errors=errors,
)
async def async_step_configure_v2(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Step when user configures InfluxDB v2."""
errors: dict[str, str] = {}
if user_input is not None:
data = {
CONF_API_VERSION: API_VERSION_2,
CONF_URL: user_input[CONF_URL],
CONF_TOKEN: user_input[CONF_TOKEN],
CONF_ORG: user_input[CONF_ORG],
CONF_BUCKET: user_input[CONF_BUCKET],
CONF_VERIFY_SSL: user_input[CONF_VERIFY_SSL],
}
if (cert := user_input.get(CONF_SSL_CA_CERT)) is not None:
path = await _save_uploaded_cert_file(self.hass, cert)
data[CONF_SSL_CA_CERT] = str(path)
errors = await _validate_influxdb_connection(self.hass, data)
if not errors:
title = f"{data[CONF_BUCKET]} ({data[CONF_URL]})"
return self.async_create_entry(title=title, data=data)
schema = INFLUXDB_V2_SCHEMA
return self.async_show_form(
step_id="configure_v2",
data_schema=self.add_suggested_values_to_schema(schema, user_input),
errors=errors,
)
async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
"""Handle the initial step."""
host = import_data.get(CONF_HOST)
database = import_data.get(CONF_DB_NAME)
bucket = import_data.get(CONF_BUCKET)
api_version = import_data.get(CONF_API_VERSION)
ssl = import_data.get(CONF_SSL)
if api_version == DEFAULT_API_VERSION:
title = f"{database} ({host})"
data = {
CONF_API_VERSION: api_version,
CONF_HOST: host,
CONF_PORT: import_data.get(CONF_PORT),
CONF_USERNAME: import_data.get(CONF_USERNAME),
CONF_PASSWORD: import_data.get(CONF_PASSWORD),
CONF_DB_NAME: database,
CONF_SSL: ssl,
CONF_PATH: import_data.get(CONF_PATH),
CONF_VERIFY_SSL: import_data.get(CONF_VERIFY_SSL),
CONF_SSL_CA_CERT: import_data.get(CONF_SSL_CA_CERT),
}
else:
url = import_data.get(CONF_URL)
title = f"{bucket} ({url})"
data = {
CONF_API_VERSION: api_version,
CONF_URL: import_data.get(CONF_URL),
CONF_TOKEN: import_data.get(CONF_TOKEN),
CONF_ORG: import_data.get(CONF_ORG),
CONF_BUCKET: bucket,
CONF_VERIFY_SSL: import_data.get(CONF_VERIFY_SSL),
CONF_SSL_CA_CERT: import_data.get(CONF_SSL_CA_CERT),
}
errors = await _validate_influxdb_connection(self.hass, data)
if errors:
return self.async_abort(reason=errors["base"])
return self.async_create_entry(title=title, data=data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/influxdb/config_flow.py",
"license": "Apache License 2.0",
"lines": 246,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/influxdb/test_config_flow.py | """Test the influxdb config flow."""
from collections.abc import Generator
from contextlib import contextmanager
from pathlib import Path
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
from influxdb.exceptions import InfluxDBClientError, InfluxDBServerError
import pytest
from homeassistant import config_entries
from homeassistant.components.influxdb import (
API_VERSION_2,
CONF_API_VERSION,
CONF_BUCKET,
CONF_DB_NAME,
CONF_ORG,
CONF_SSL_CA_CERT,
DEFAULT_API_VERSION,
DOMAIN,
ApiException,
)
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PATH,
CONF_PORT,
CONF_SSL,
CONF_TOKEN,
CONF_URL,
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import (
BASE_V1_CONFIG,
BASE_V2_CONFIG,
INFLUX_CLIENT_PATH,
_get_write_api_mock_v1,
_get_write_api_mock_v2,
)
from tests.common import MockConfigEntry
PATH_FIXTURE = Path("/influxdb.crt")
FIXTURE_UPLOAD_UUID = "0123456789abcdef0123456789abcdef"
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.influxdb.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry
@pytest.fixture(name="mock_client")
def mock_client_fixture(
request: pytest.FixtureRequest,
) -> Generator[MagicMock]:
"""Patch the InfluxDBClient object with mock for version under test."""
if request.param == API_VERSION_2:
client_target = f"{INFLUX_CLIENT_PATH}V2"
else:
client_target = INFLUX_CLIENT_PATH
with patch(client_target) as client:
yield client
@contextmanager
def patch_file_upload(return_value=PATH_FIXTURE, side_effect=None):
"""Patch file upload. Yields the Path (return_value)."""
with (
patch(
"homeassistant.components.influxdb.config_flow.process_uploaded_file"
) as file_upload_mock,
patch("homeassistant.core_config.Config.path", return_value="/.storage"),
patch(
"pathlib.Path.mkdir",
) as mkdir_mock,
patch(
"shutil.move",
) as shutil_move_mock,
):
file_upload_mock.return_value.__enter__.return_value = PATH_FIXTURE
yield return_value
if side_effect:
mkdir_mock.assert_not_called()
shutil_move_mock.assert_not_called()
else:
mkdir_mock.assert_called_once()
shutil_move_mock.assert_called_once()
@pytest.mark.parametrize(
("mock_client", "config_base", "config_url", "get_write_api"),
[
(
DEFAULT_API_VERSION,
{
CONF_URL: "http://localhost:8086",
CONF_VERIFY_SSL: False,
CONF_DB_NAME: "home_assistant",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
},
{
CONF_HOST: "localhost",
CONF_PORT: 8086,
CONF_SSL: False,
CONF_PATH: "/",
},
_get_write_api_mock_v1,
),
(
DEFAULT_API_VERSION,
{
CONF_URL: "http://localhost:8086",
CONF_VERIFY_SSL: False,
CONF_DB_NAME: "home_assistant",
},
{
CONF_HOST: "localhost",
CONF_PORT: 8086,
CONF_SSL: False,
CONF_PATH: "/",
},
_get_write_api_mock_v1,
),
(
DEFAULT_API_VERSION,
{
CONF_URL: "https://influxdb.mydomain.com",
CONF_VERIFY_SSL: True,
CONF_DB_NAME: "home_assistant",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
},
{
CONF_HOST: "influxdb.mydomain.com",
CONF_PORT: 443,
CONF_SSL: True,
CONF_PATH: "/",
},
_get_write_api_mock_v1,
),
],
indirect=["mock_client"],
)
async def test_setup_v1(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_client: MagicMock,
config_base: dict[str, Any],
config_url: dict[str, Any],
get_write_api: Any,
) -> None:
"""Test we can setup an InfluxDB v1."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"next_step_id": "configure_v1"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "configure_v1"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
config_base,
)
data = {
CONF_API_VERSION: "1",
CONF_HOST: config_url[CONF_HOST],
CONF_PORT: config_url[CONF_PORT],
CONF_USERNAME: config_base.get(CONF_USERNAME),
CONF_PASSWORD: config_base.get(CONF_PASSWORD),
CONF_DB_NAME: config_base[CONF_DB_NAME],
CONF_SSL: config_url[CONF_SSL],
CONF_PATH: config_url[CONF_PATH],
CONF_VERIFY_SSL: config_base[CONF_VERIFY_SSL],
}
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"{config_base['database']} ({config_url['host']})"
assert result["data"] == data
@pytest.mark.parametrize(
("mock_client", "config_base", "config_url", "get_write_api"),
[
(
DEFAULT_API_VERSION,
{
CONF_URL: "https://influxdb.mydomain.com",
CONF_VERIFY_SSL: True,
CONF_DB_NAME: "home_assistant",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
CONF_SSL_CA_CERT: FIXTURE_UPLOAD_UUID,
},
{
CONF_HOST: "influxdb.mydomain.com",
CONF_PORT: 443,
CONF_SSL: True,
CONF_PATH: "/",
},
_get_write_api_mock_v1,
),
],
indirect=["mock_client"],
)
async def test_setup_v1_ssl_cert(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_client: MagicMock,
config_base: dict[str, Any],
config_url: dict[str, Any],
get_write_api: Any,
) -> None:
"""Test we can setup an InfluxDB v1 with SSL Certificate."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"next_step_id": "configure_v1"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "configure_v1"
assert result["errors"] == {}
with (
patch_file_upload(),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
config_base,
)
data = {
CONF_API_VERSION: "1",
CONF_HOST: config_url[CONF_HOST],
CONF_PORT: config_url[CONF_PORT],
CONF_USERNAME: config_base.get(CONF_USERNAME),
CONF_PASSWORD: config_base.get(CONF_PASSWORD),
CONF_DB_NAME: config_base[CONF_DB_NAME],
CONF_SSL: config_url[CONF_SSL],
CONF_PATH: config_url[CONF_PATH],
CONF_VERIFY_SSL: config_base[CONF_VERIFY_SSL],
CONF_SSL_CA_CERT: "/.storage/influxdb.crt",
}
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"{config_base['database']} ({config_url['host']})"
assert result["data"] == data
@pytest.mark.parametrize(
("mock_client", "config_base", "get_write_api"),
[
(
API_VERSION_2,
{
CONF_URL: "http://localhost:8086",
CONF_VERIFY_SSL: True,
CONF_ORG: "my_org",
CONF_BUCKET: "home_assistant",
CONF_TOKEN: "token",
},
_get_write_api_mock_v2,
),
],
indirect=["mock_client"],
)
async def test_setup_v2(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_client: MagicMock,
config_base: dict[str, Any],
get_write_api: Any,
) -> None:
"""Test we can setup an InfluxDB v2."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"next_step_id": "configure_v2"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "configure_v2"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
config_base,
)
data = {
CONF_API_VERSION: "2",
CONF_URL: config_base[CONF_URL],
CONF_ORG: config_base[CONF_ORG],
CONF_BUCKET: config_base.get(CONF_BUCKET),
CONF_TOKEN: config_base.get(CONF_TOKEN),
CONF_VERIFY_SSL: config_base[CONF_VERIFY_SSL],
}
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"{config_base['bucket']} ({config_base['url']})"
assert result["data"] == data
@pytest.mark.parametrize(
("mock_client", "config_base", "get_write_api"),
[
(
API_VERSION_2,
{
CONF_URL: "http://localhost:8086",
CONF_VERIFY_SSL: True,
CONF_ORG: "my_org",
CONF_BUCKET: "home_assistant",
CONF_TOKEN: "token",
CONF_SSL_CA_CERT: FIXTURE_UPLOAD_UUID,
},
_get_write_api_mock_v2,
),
],
indirect=["mock_client"],
)
async def test_setup_v2_ssl_cert(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_client: MagicMock,
config_base: dict[str, Any],
get_write_api: Any,
) -> None:
"""Test we can setup an InfluxDB v2 with SSL Certificate."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"next_step_id": "configure_v2"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "configure_v2"
assert result["errors"] == {}
with (
patch_file_upload(),
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
config_base,
)
data = {
CONF_API_VERSION: "2",
CONF_URL: config_base[CONF_URL],
CONF_ORG: config_base[CONF_ORG],
CONF_BUCKET: config_base.get(CONF_BUCKET),
CONF_TOKEN: config_base.get(CONF_TOKEN),
CONF_VERIFY_SSL: config_base[CONF_VERIFY_SSL],
CONF_SSL_CA_CERT: "/.storage/influxdb.crt",
}
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"{config_base['bucket']} ({config_base['url']})"
assert result["data"] == data
@pytest.mark.parametrize(
(
"mock_client",
"config_base",
"api_version",
"get_write_api",
"test_exception",
"reason",
),
[
(
DEFAULT_API_VERSION,
{
CONF_URL: "http://localhost:8086",
CONF_VERIFY_SSL: False,
CONF_DB_NAME: "home_assistant",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
},
DEFAULT_API_VERSION,
_get_write_api_mock_v1,
InfluxDBClientError("SSLError"),
"ssl_error",
),
(
DEFAULT_API_VERSION,
{
CONF_URL: "http://localhost:8086",
CONF_VERIFY_SSL: False,
CONF_DB_NAME: "home_assistant",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
},
DEFAULT_API_VERSION,
_get_write_api_mock_v1,
InfluxDBClientError("database not found"),
"invalid_database",
),
(
DEFAULT_API_VERSION,
{
CONF_URL: "http://localhost:8086",
CONF_VERIFY_SSL: False,
CONF_DB_NAME: "home_assistant",
CONF_USERNAME: "user",
CONF_PASSWORD: "pass",
},
DEFAULT_API_VERSION,
_get_write_api_mock_v1,
InfluxDBClientError("authorization failed"),
"invalid_auth",
),
(
API_VERSION_2,
{
CONF_URL: "http://localhost:8086",
CONF_VERIFY_SSL: True,
CONF_ORG: "my_org",
CONF_BUCKET: "home_assistant",
CONF_TOKEN: "token",
},
API_VERSION_2,
_get_write_api_mock_v2,
ApiException("SSLError"),
"ssl_error",
),
(
API_VERSION_2,
{
CONF_URL: "http://localhost:8086",
CONF_VERIFY_SSL: True,
CONF_ORG: "my_org",
CONF_BUCKET: "home_assistant",
CONF_TOKEN: "token",
},
API_VERSION_2,
_get_write_api_mock_v2,
ApiException("token"),
"invalid_config",
),
],
indirect=["mock_client"],
)
async def test_setup_connection_error(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_client: MagicMock,
config_base: dict[str, Any],
api_version: str,
get_write_api: Any,
test_exception: Exception,
reason: str,
) -> None:
"""Test connection error during setup of InfluxDB v2."""
write_api = get_write_api(mock_client)
write_api.side_effect = test_exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.MENU
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{"next_step_id": f"configure_v{api_version}"},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == f"configure_v{api_version}"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
config_base,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
write_api.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
config_base,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
@pytest.mark.parametrize(
("mock_client", "config_base", "get_write_api"),
[
(
DEFAULT_API_VERSION,
BASE_V1_CONFIG,
_get_write_api_mock_v1,
),
],
indirect=["mock_client"],
)
async def test_single_instance(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_client: MagicMock,
config_base: dict[str, Any],
get_write_api: Any,
) -> None:
"""Test we cannot setup a second entry for InfluxDB."""
mock_entry = MockConfigEntry(
domain="influxdb",
data=config_base,
)
mock_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "single_instance_allowed"
@pytest.mark.parametrize(
("mock_client", "config_base", "get_write_api", "db_name", "host"),
[
(
DEFAULT_API_VERSION,
BASE_V1_CONFIG,
_get_write_api_mock_v1,
BASE_V1_CONFIG[CONF_DB_NAME],
BASE_V1_CONFIG[CONF_HOST],
),
(
API_VERSION_2,
BASE_V2_CONFIG,
_get_write_api_mock_v2,
BASE_V2_CONFIG[CONF_BUCKET],
BASE_V2_CONFIG[CONF_URL],
),
],
indirect=["mock_client"],
)
async def test_import(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_client: MagicMock,
config_base: dict[str, Any],
get_write_api: Any,
db_name: str,
host: str,
) -> None:
"""Test we can import."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=config_base,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == f"{db_name} ({host})"
assert result["data"] == config_base
assert get_write_api(mock_client).call_count == 1
@pytest.mark.parametrize(
("mock_client", "config_base", "get_write_api", "test_exception", "reason"),
[
(
DEFAULT_API_VERSION,
BASE_V1_CONFIG,
_get_write_api_mock_v1,
ConnectionError("fail"),
"cannot_connect",
),
(
DEFAULT_API_VERSION,
BASE_V1_CONFIG,
_get_write_api_mock_v1,
InfluxDBClientError("fail"),
"cannot_connect",
),
(
DEFAULT_API_VERSION,
BASE_V1_CONFIG,
_get_write_api_mock_v1,
InfluxDBServerError("fail"),
"cannot_connect",
),
(
API_VERSION_2,
BASE_V2_CONFIG,
_get_write_api_mock_v2,
ConnectionError("fail"),
"cannot_connect",
),
(
API_VERSION_2,
BASE_V2_CONFIG,
_get_write_api_mock_v2,
ApiException(http_resp=MagicMock()),
"invalid_config",
),
(
API_VERSION_2,
BASE_V2_CONFIG,
_get_write_api_mock_v2,
Exception(),
"unknown",
),
],
indirect=["mock_client"],
)
async def test_import_connection_error(
hass: HomeAssistant,
mock_client: MagicMock,
config_base: dict[str, Any],
get_write_api: Any,
test_exception: Exception,
reason: str,
) -> None:
"""Test abort on connection error."""
write_api = get_write_api(mock_client)
write_api.side_effect = test_exception
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=config_base,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == reason
@pytest.mark.parametrize(
("mock_client", "config_base", "get_write_api"),
[
(
DEFAULT_API_VERSION,
BASE_V1_CONFIG,
_get_write_api_mock_v1,
),
],
indirect=["mock_client"],
)
async def test_single_instance_import(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_client: MagicMock,
config_base: dict[str, Any],
get_write_api: Any,
) -> None:
"""Test we cannot setup a second entry for InfluxDB."""
mock_entry = MockConfigEntry(
domain="influxdb",
data=config_base,
)
mock_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=config_base,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "single_instance_allowed"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/influxdb/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 643,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/nrgkick/number.py | """Number platform for NRGkick."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any
from nrgkick_api.const import (
CONTROL_KEY_CURRENT_SET,
CONTROL_KEY_ENERGY_LIMIT,
CONTROL_KEY_PHASE_COUNT,
)
from homeassistant.components.number import (
NumberDeviceClass,
NumberEntity,
NumberEntityDescription,
NumberMode,
)
from homeassistant.const import UnitOfElectricCurrent, UnitOfEnergy
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import NRGkickConfigEntry, NRGkickData, NRGkickDataUpdateCoordinator
from .entity import NRGkickEntity
PARALLEL_UPDATES = 1
MIN_CHARGING_CURRENT = 6
def _get_current_set_max(data: NRGkickData) -> float:
"""Return the maximum current setpoint.
Uses the lower of the device rated current and the connector max current.
The device always has a rated current; the connector may be absent.
"""
rated: float = data.info["general"]["rated_current"]
connector_max = data.info.get("connector", {}).get("max_current")
if connector_max is None:
return rated
return min(rated, float(connector_max))
def _get_phase_count_max(data: NRGkickData) -> float:
"""Return the maximum phase count based on the attached connector."""
connector_phases = data.info.get("connector", {}).get("phase_count")
if connector_phases is None:
return 3.0
return float(connector_phases)
@dataclass(frozen=True, kw_only=True)
class NRGkickNumberEntityDescription(NumberEntityDescription):
"""Class describing NRGkick number entities."""
value_fn: Callable[[NRGkickData], float | None]
set_value_fn: Callable[[NRGkickDataUpdateCoordinator, float], Awaitable[Any]]
max_value_fn: Callable[[NRGkickData], float] | None = None
NUMBERS: tuple[NRGkickNumberEntityDescription, ...] = (
NRGkickNumberEntityDescription(
key="current_set",
translation_key="current_set",
device_class=NumberDeviceClass.CURRENT,
native_unit_of_measurement=UnitOfElectricCurrent.AMPERE,
native_min_value=MIN_CHARGING_CURRENT,
native_step=0.1,
mode=NumberMode.SLIDER,
value_fn=lambda data: data.control.get(CONTROL_KEY_CURRENT_SET),
set_value_fn=lambda coordinator, value: coordinator.api.set_current(value),
max_value_fn=_get_current_set_max,
),
NRGkickNumberEntityDescription(
key="energy_limit",
translation_key="energy_limit",
device_class=NumberDeviceClass.ENERGY,
native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
native_min_value=0,
native_max_value=100000,
native_step=1,
mode=NumberMode.BOX,
value_fn=lambda data: data.control.get(CONTROL_KEY_ENERGY_LIMIT),
set_value_fn=lambda coordinator, value: coordinator.api.set_energy_limit(
int(value)
),
),
NRGkickNumberEntityDescription(
key="phase_count",
translation_key="phase_count",
native_min_value=1,
native_max_value=3,
native_step=1,
mode=NumberMode.SLIDER,
value_fn=lambda data: data.control.get(CONTROL_KEY_PHASE_COUNT),
set_value_fn=lambda coordinator, value: coordinator.api.set_phase_count(
int(value)
),
max_value_fn=_get_phase_count_max,
),
)
async def async_setup_entry(
_hass: HomeAssistant,
entry: NRGkickConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up NRGkick number entities based on a config entry."""
coordinator = entry.runtime_data
async_add_entities(
NRGkickNumber(coordinator, description) for description in NUMBERS
)
class NRGkickNumber(NRGkickEntity, NumberEntity):
"""Representation of an NRGkick number entity."""
entity_description: NRGkickNumberEntityDescription
def __init__(
self,
coordinator: NRGkickDataUpdateCoordinator,
description: NRGkickNumberEntityDescription,
) -> None:
"""Initialize the number entity."""
self.entity_description = description
super().__init__(coordinator, description.key)
@property
def native_max_value(self) -> float:
"""Return the maximum value."""
if self.entity_description.max_value_fn is not None:
data = self.coordinator.data
if TYPE_CHECKING:
assert data is not None
return self.entity_description.max_value_fn(data)
return super().native_max_value
@property
def native_value(self) -> float | None:
"""Return the current value."""
data = self.coordinator.data
if TYPE_CHECKING:
assert data is not None
return self.entity_description.value_fn(data)
async def async_set_native_value(self, value: float) -> None:
"""Set the value."""
await self._async_call_api(
self.entity_description.set_value_fn(self.coordinator, value)
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/nrgkick/number.py",
"license": "Apache License 2.0",
"lines": 128,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/nrgkick/test_number.py | """Tests for the NRGkick number platform."""
from __future__ import annotations
from unittest.mock import AsyncMock
from nrgkick_api import NRGkickCommandRejectedError
from nrgkick_api.const import (
CONTROL_KEY_CURRENT_SET,
CONTROL_KEY_ENERGY_LIMIT,
CONTROL_KEY_PHASE_COUNT,
)
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
pytestmark = pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_number_entities(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test number entities."""
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_set_charging_current(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test setting charging current calls the API and updates state."""
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
entity_id = "number.nrgkick_test_charging_current"
assert (state := hass.states.get(entity_id))
assert state.state == "16.0"
# Set current to 10A
control_data = mock_nrgkick_api.get_control.return_value.copy()
control_data[CONTROL_KEY_CURRENT_SET] = 10.0
mock_nrgkick_api.get_control.return_value = control_data
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 10.0},
blocking=True,
)
assert (state := hass.states.get(entity_id))
assert state.state == "10.0"
mock_nrgkick_api.set_current.assert_awaited_once_with(10.0)
async def test_set_energy_limit(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test setting energy limit calls the API and updates state."""
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
entity_id = "number.nrgkick_test_energy_limit"
assert (state := hass.states.get(entity_id))
assert state.state == "0"
# Set energy limit to 5000 Wh
control_data = mock_nrgkick_api.get_control.return_value.copy()
control_data[CONTROL_KEY_ENERGY_LIMIT] = 5000
mock_nrgkick_api.get_control.return_value = control_data
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 5000},
blocking=True,
)
assert (state := hass.states.get(entity_id))
assert state.state == "5000"
mock_nrgkick_api.set_energy_limit.assert_awaited_once_with(5000)
async def test_set_phase_count(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test setting phase count calls the API and updates state."""
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
entity_id = "number.nrgkick_test_phase_count"
assert (state := hass.states.get(entity_id))
assert state.state == "3"
# Set to 1 phase
control_data = mock_nrgkick_api.get_control.return_value.copy()
control_data[CONTROL_KEY_PHASE_COUNT] = 1
mock_nrgkick_api.get_control.return_value = control_data
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 1},
blocking=True,
)
assert (state := hass.states.get(entity_id))
assert state.state == "1"
mock_nrgkick_api.set_phase_count.assert_awaited_once_with(1)
async def test_number_command_rejected_by_device(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test number entity surfaces device rejection messages."""
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
entity_id = "number.nrgkick_test_charging_current"
mock_nrgkick_api.set_current.side_effect = NRGkickCommandRejectedError(
"Current change blocked by solar-charging"
)
with pytest.raises(HomeAssistantError) as err:
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 10.0},
blocking=True,
)
assert err.value.translation_key == "command_rejected"
assert err.value.translation_placeholders == {
"reason": "Current change blocked by solar-charging"
}
# State should reflect actual device control data (unchanged).
assert (state := hass.states.get(entity_id))
assert state.state == "16.0"
async def test_charging_current_max_limited_by_connector(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nrgkick_api: AsyncMock,
) -> None:
"""Test that the charging current max is limited by the connector."""
# Device rated at 32A, but connector only supports 16A.
mock_nrgkick_api.get_info.return_value["general"]["rated_current"] = 32.0
mock_nrgkick_api.get_info.return_value["connector"]["max_current"] = 16.0
await setup_integration(hass, mock_config_entry, platforms=[Platform.NUMBER])
entity_id = "number.nrgkick_test_charging_current"
assert (state := hass.states.get(entity_id))
assert state.attributes["max"] == 16.0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nrgkick/test_number.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:homeassistant/components/aws_s3/coordinator.py | """DataUpdateCoordinator for AWS S3."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import timedelta
import logging
from aiobotocore.client import AioBaseClient as S3Client
from botocore.exceptions import BotoCoreError
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_BUCKET, CONF_PREFIX, DOMAIN
from .helpers import async_list_backups_from_s3
SCAN_INTERVAL = timedelta(hours=6)
type S3ConfigEntry = ConfigEntry[S3DataUpdateCoordinator]
_LOGGER = logging.getLogger(__name__)
@dataclass
class SensorData:
"""Class to represent sensor data."""
all_backups_size: int
class S3DataUpdateCoordinator(DataUpdateCoordinator[SensorData]):
"""Class to manage fetching AWS S3 data from single endpoint."""
config_entry: S3ConfigEntry
client: S3Client
def __init__(
self,
hass: HomeAssistant,
*,
entry: S3ConfigEntry,
client: S3Client,
) -> None:
"""Initialize AWS S3 data updater."""
super().__init__(
hass,
_LOGGER,
config_entry=entry,
name=DOMAIN,
update_interval=SCAN_INTERVAL,
)
self.client = client
self._bucket: str = entry.data[CONF_BUCKET]
self._prefix: str = entry.data.get(CONF_PREFIX, "")
async def _async_update_data(self) -> SensorData:
"""Fetch data from AWS S3."""
try:
backups = await async_list_backups_from_s3(
self.client, self._bucket, self._prefix
)
except BotoCoreError as error:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="error_fetching_data",
) from error
all_backups_size = sum(b.size for b in backups)
return SensorData(
all_backups_size=all_backups_size,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/aws_s3/coordinator.py",
"license": "Apache License 2.0",
"lines": 56,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/aws_s3/entity.py | """Define the AWS S3 entity."""
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
from homeassistant.helpers.entity import EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import CONF_BUCKET, DOMAIN
from .coordinator import S3DataUpdateCoordinator
class S3Entity(CoordinatorEntity[S3DataUpdateCoordinator]):
"""Defines a base AWS S3 entity."""
_attr_has_entity_name = True
def __init__(
self, coordinator: S3DataUpdateCoordinator, description: EntityDescription
) -> None:
"""Initialize an AWS S3 entity."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.config_entry.entry_id}_{description.key}"
@property
def device_info(self) -> DeviceInfo:
"""Return device information about this AWS S3 device."""
return DeviceInfo(
identifiers={(DOMAIN, self.coordinator.config_entry.entry_id)},
name=f"Bucket {self.coordinator.config_entry.data[CONF_BUCKET]}",
manufacturer="AWS",
model="AWS S3",
entry_type=DeviceEntryType.SERVICE,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/aws_s3/entity.py",
"license": "Apache License 2.0",
"lines": 26,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/aws_s3/helpers.py | """Helpers for the AWS S3 integration."""
from __future__ import annotations
import json
import logging
from typing import Any
from aiobotocore.client import AioBaseClient as S3Client
from botocore.exceptions import BotoCoreError
from homeassistant.components.backup import AgentBackup
_LOGGER = logging.getLogger(__name__)
async def async_list_backups_from_s3(
client: S3Client,
bucket: str,
prefix: str,
) -> list[AgentBackup]:
"""List backups from an S3 bucket by reading metadata files."""
paginator = client.get_paginator("list_objects_v2")
metadata_files: list[dict[str, Any]] = []
list_kwargs: dict[str, Any] = {"Bucket": bucket}
if prefix:
list_kwargs["Prefix"] = prefix + "/"
async for page in paginator.paginate(**list_kwargs):
metadata_files.extend(
obj
for obj in page.get("Contents", [])
if obj["Key"].endswith(".metadata.json")
)
backups: list[AgentBackup] = []
for metadata_file in metadata_files:
try:
metadata_response = await client.get_object(
Bucket=bucket, Key=metadata_file["Key"]
)
metadata_content = await metadata_response["Body"].read()
metadata_json = json.loads(metadata_content)
except (BotoCoreError, json.JSONDecodeError) as err:
_LOGGER.warning(
"Failed to process metadata file %s: %s",
metadata_file["Key"],
err,
)
continue
try:
backup = AgentBackup.from_dict(metadata_json)
except (KeyError, TypeError, ValueError) as err:
_LOGGER.warning(
"Failed to parse metadata in file %s: %s",
metadata_file["Key"],
err,
)
continue
backups.append(backup)
return backups
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/aws_s3/helpers.py",
"license": "Apache License 2.0",
"lines": 52,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/aws_s3/sensor.py | """Support for AWS S3 sensors."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.const import EntityCategory, UnitOfInformation
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.typing import StateType
from .coordinator import S3ConfigEntry, SensorData
from .entity import S3Entity
# Coordinator is used to centralize the data updates
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class S3SensorEntityDescription(SensorEntityDescription):
"""Describes an AWS S3 sensor entity."""
value_fn: Callable[[SensorData], StateType]
SENSORS: tuple[S3SensorEntityDescription, ...] = (
S3SensorEntityDescription(
key="backups_size",
translation_key="backups_size",
native_unit_of_measurement=UnitOfInformation.BYTES,
suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES,
suggested_display_precision=0,
device_class=SensorDeviceClass.DATA_SIZE,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda data: data.all_backups_size,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: S3ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up AWS S3 sensor based on a config entry."""
coordinator = entry.runtime_data
async_add_entities(
S3SensorEntity(coordinator, description) for description in SENSORS
)
class S3SensorEntity(S3Entity, SensorEntity):
"""Defines an AWS S3 sensor entity."""
entity_description: S3SensorEntityDescription
@property
def native_value(self) -> StateType:
"""Return the state of the sensor."""
return self.entity_description.value_fn(self.coordinator.data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/aws_s3/sensor.py",
"license": "Apache License 2.0",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/aws_s3/test_sensor.py | """Tests for the AWS S3 sensor platform."""
from __future__ import annotations
import json
from unittest.mock import AsyncMock
from botocore.exceptions import BotoCoreError
from freezegun.api import FrozenDateTimeFactory
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.aws_s3.coordinator import SCAN_INTERVAL
from homeassistant.components.backup import AgentBackup
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_sensor(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
mock_client: AsyncMock,
) -> None:
"""Test the creation and values of the AWS S3 sensors."""
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
assert (
entity_entry := entity_registry.async_get(
"sensor.bucket_test_total_size_of_backups"
)
)
assert entity_entry.device_id
assert (device_entry := device_registry.async_get(entity_entry.device_id))
assert device_entry == snapshot
async def test_sensor_availability(
hass: HomeAssistant,
mock_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test the availability handling of the AWS S3 sensors."""
await setup_integration(hass, mock_config_entry)
mock_client.get_paginator.return_value.paginate.side_effect = BotoCoreError()
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get("sensor.bucket_test_total_size_of_backups"))
assert state.state == STATE_UNAVAILABLE
mock_client.get_paginator.return_value.paginate.side_effect = None
mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [
{"Contents": []}
]
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get("sensor.bucket_test_total_size_of_backups"))
assert state.state != STATE_UNAVAILABLE
@pytest.mark.parametrize(
("config_entry_extra_data", "expected_pagination_call"),
[
({}, {"Bucket": "test"}),
(
{"prefix": "backups/home"},
{"Bucket": "test", "Prefix": "backups/home/"},
),
],
)
async def test_calculate_backups_size(
hass: HomeAssistant,
mock_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
test_backup: AgentBackup,
config_entry_extra_data: dict,
expected_pagination_call: dict,
) -> None:
"""Test the total size of backups calculation with and without prefix."""
mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [
{"Contents": []}
]
await setup_integration(hass, mock_config_entry)
assert (state := hass.states.get("sensor.bucket_test_total_size_of_backups"))
assert state.state == "0.0"
# Add a backup
metadata_content = json.dumps(test_backup.as_dict())
mock_body = AsyncMock()
mock_body.read.return_value = metadata_content.encode()
mock_client.get_object.return_value = {"Body": mock_body}
mock_client.get_paginator.return_value.paginate.return_value.__aiter__.return_value = [
{
"Contents": [
{"Key": "backup.tar"},
{"Key": "backup.metadata.json"},
]
}
]
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get("sensor.bucket_test_total_size_of_backups"))
assert float(state.state) > 0
# Verify prefix was used in API call if expected
mock_client.get_paginator.return_value.paginate.assert_called_with(
**expected_pagination_call,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/aws_s3/test_sensor.py",
"license": "Apache License 2.0",
"lines": 105,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/iometer/test_sensor.py | """Test the sensors provided by the Powerfox integration."""
from __future__ import annotations
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_platform
from tests.common import MockConfigEntry, snapshot_platform
from tests.components.conftest import AsyncMock
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_sensors(
hass: HomeAssistant,
mock_iometer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the Iometer sensors."""
await setup_platform(hass, mock_config_entry, [Platform.SENSOR])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/iometer/test_sensor.py",
"license": "Apache License 2.0",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/ness_alarm/config_flow.py | """Config flow for Ness Alarm integration."""
from __future__ import annotations
import asyncio
import logging
from types import MappingProxyType
from typing import Any
from nessclient import Client
import voluptuous as vol
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
from homeassistant.config_entries import (
ConfigEntry,
ConfigFlow,
ConfigFlowResult,
ConfigSubentryData,
ConfigSubentryFlow,
OptionsFlow,
SubentryFlowResult,
)
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TYPE
from homeassistant.core import callback
from homeassistant.helpers import config_validation as cv, selector
from .const import (
CONF_INFER_ARMING_STATE,
CONF_SHOW_HOME_MODE,
CONF_ZONE_ID,
CONF_ZONE_NAME,
CONF_ZONE_NUMBER,
CONF_ZONE_TYPE,
CONF_ZONES,
CONNECTION_TIMEOUT,
DEFAULT_INFER_ARMING_STATE,
DEFAULT_PORT,
DEFAULT_ZONE_TYPE,
DOMAIN,
POST_CONNECTION_DELAY,
SUBENTRY_TYPE_ZONE,
)
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port,
vol.Optional(CONF_INFER_ARMING_STATE, default=DEFAULT_INFER_ARMING_STATE): bool,
}
)
ZONE_SCHEMA = vol.Schema(
{
vol.Required(CONF_TYPE, default=DEFAULT_ZONE_TYPE): selector.SelectSelector(
selector.SelectSelectorConfig(
options=[cls.value for cls in BinarySensorDeviceClass],
mode=selector.SelectSelectorMode.DROPDOWN,
translation_key="binary_sensor_device_class",
sort=True,
),
),
}
)
class NessAlarmConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Ness Alarm."""
VERSION = 1
@classmethod
@callback
def async_get_supported_subentry_types(
cls, config_entry: ConfigEntry
) -> dict[str, type[ConfigSubentryFlow]]:
"""Return subentries supported by this integration."""
return {
SUBENTRY_TYPE_ZONE: ZoneSubentryFlowHandler,
}
@staticmethod
@callback
def async_get_options_flow(
config_entry: ConfigEntry,
) -> OptionsFlow:
"""Create the options flow."""
return NessAlarmOptionsFlowHandler()
async def _test_connection(self, host: str, port: int) -> None:
"""Test connection to the alarm panel.
Raises OSError on connection failure.
"""
client = Client(host=host, port=port)
try:
await asyncio.wait_for(client.update(), timeout=CONNECTION_TIMEOUT)
except TimeoutError as err:
raise OSError(f"Timed out connecting to {host}:{port}") from err
finally:
await client.close()
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
host = user_input[CONF_HOST]
port = user_input[CONF_PORT]
# Check if already configured
self._async_abort_entries_match({CONF_HOST: host})
# Test connection to the alarm panel
try:
await self._test_connection(host, port)
except OSError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected error connecting to %s:%s", host, port)
errors["base"] = "unknown"
if not errors:
# Brief delay to ensure the panel releases the test connection
await asyncio.sleep(POST_CONNECTION_DELAY)
return self.async_create_entry(
title=f"Ness Alarm {host}:{port}",
data=user_input,
)
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
)
async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult:
"""Import YAML configuration."""
host = import_data[CONF_HOST]
port = import_data[CONF_PORT]
# Check if already configured
self._async_abort_entries_match({CONF_HOST: host})
# Test connection to the alarm panel
try:
await self._test_connection(host, port)
except OSError:
return self.async_abort(reason="cannot_connect")
except Exception:
_LOGGER.exception(
"Unexpected error connecting to %s:%s during import", host, port
)
return self.async_abort(reason="unknown")
# Brief delay to ensure the panel releases the test connection
await asyncio.sleep(POST_CONNECTION_DELAY)
# Prepare subentries for zones
subentries: list[ConfigSubentryData] = []
zones = import_data.get(CONF_ZONES, [])
for zone_config in zones:
zone_id = zone_config[CONF_ZONE_ID]
zone_name = zone_config.get(CONF_ZONE_NAME)
zone_type = zone_config.get(CONF_ZONE_TYPE, DEFAULT_ZONE_TYPE)
# Subentry title is always "Zone {zone_id}"
title = f"Zone {zone_id}"
# Build subentry data
subentry_data = {
CONF_ZONE_NUMBER: zone_id,
CONF_TYPE: zone_type,
}
# Include zone name in data if provided (for device naming)
if zone_name:
subentry_data[CONF_ZONE_NAME] = zone_name
subentries.append(
{
"subentry_type": SUBENTRY_TYPE_ZONE,
"title": title,
"unique_id": f"{SUBENTRY_TYPE_ZONE}_{zone_id}",
"data": MappingProxyType(subentry_data),
}
)
return self.async_create_entry(
title=f"Ness Alarm {host}:{port}",
data={
CONF_HOST: host,
CONF_PORT: port,
CONF_INFER_ARMING_STATE: import_data.get(
CONF_INFER_ARMING_STATE, DEFAULT_INFER_ARMING_STATE
),
},
subentries=subentries,
)
class NessAlarmOptionsFlowHandler(OptionsFlow):
"""Handle options flow for Ness Alarm."""
async def async_step_init(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Manage the options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
return self.async_show_form(
step_id="init",
data_schema=self.add_suggested_values_to_schema(
vol.Schema(
{
vol.Required(CONF_SHOW_HOME_MODE, default=True): bool,
}
),
self.config_entry.options,
),
)
class ZoneSubentryFlowHandler(ConfigSubentryFlow):
"""Handle subentry flow for adding and modifying a zone."""
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""User flow to add new zone."""
errors: dict[str, str] = {}
if user_input is not None:
zone_number = int(user_input[CONF_ZONE_NUMBER])
unique_id = f"{SUBENTRY_TYPE_ZONE}_{zone_number}"
# Check if zone already exists
for existing_subentry in self._get_entry().subentries.values():
if existing_subentry.unique_id == unique_id:
errors[CONF_ZONE_NUMBER] = "already_configured"
if not errors:
# Store zone_number as int in data
user_input[CONF_ZONE_NUMBER] = zone_number
return self.async_create_entry(
title=f"Zone {zone_number}",
data=user_input,
unique_id=unique_id,
)
return self.async_show_form(
step_id="user",
errors=errors,
data_schema=vol.Schema(
{
vol.Required(CONF_ZONE_NUMBER): selector.NumberSelector(
selector.NumberSelectorConfig(
min=1,
max=32,
mode=selector.NumberSelectorMode.BOX,
)
),
}
).extend(ZONE_SCHEMA.schema),
)
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> SubentryFlowResult:
"""Reconfigure existing zone."""
subconfig_entry = self._get_reconfigure_subentry()
if user_input is not None:
return self.async_update_and_abort(
self._get_entry(),
subconfig_entry,
title=f"Zone {subconfig_entry.data[CONF_ZONE_NUMBER]}",
data_updates=user_input,
)
return self.async_show_form(
step_id="reconfigure",
data_schema=self.add_suggested_values_to_schema(
ZONE_SCHEMA,
subconfig_entry.data,
),
description_placeholders={
CONF_ZONE_NUMBER: str(subconfig_entry.data[CONF_ZONE_NUMBER])
},
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ness_alarm/config_flow.py",
"license": "Apache License 2.0",
"lines": 249,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/ness_alarm/const.py | """Constants for the Ness Alarm integration."""
from datetime import timedelta
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
from homeassistant.const import Platform
DOMAIN = "ness_alarm"
# Platforms
PLATFORMS = [Platform.ALARM_CONTROL_PANEL, Platform.BINARY_SENSOR]
# Configuration constants
CONF_INFER_ARMING_STATE = "infer_arming_state"
CONF_ZONES = "zones"
CONF_ZONE_NAME = "name"
CONF_ZONE_TYPE = "type"
CONF_ZONE_ID = "id"
CONF_ZONE_NUMBER = "zone_number"
CONF_SHOW_HOME_MODE = "show_home_mode"
# Subentry types
SUBENTRY_TYPE_ZONE = "zone"
# Defaults
DEFAULT_PORT = 4999
DEFAULT_SCAN_INTERVAL = timedelta(minutes=1)
DEFAULT_INFER_ARMING_STATE = False
DEFAULT_ZONE_TYPE = BinarySensorDeviceClass.MOTION
# Connection
CONNECTION_TIMEOUT = 5
POST_CONNECTION_DELAY = 1
# Signals
SIGNAL_ZONE_CHANGED = "ness_alarm.zone_changed"
SIGNAL_ARMING_STATE_CHANGED = "ness_alarm.arming_state_changed"
# Services
SERVICE_PANIC = "panic"
SERVICE_AUX = "aux"
ATTR_OUTPUT_ID = "output_id"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ness_alarm/const.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/ness_alarm/services.py | """Services for the Ness Alarm integration."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.const import ATTR_CODE, ATTR_STATE
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import config_validation as cv
from .const import ATTR_OUTPUT_ID, DOMAIN, SERVICE_AUX, SERVICE_PANIC
SERVICE_SCHEMA_PANIC = vol.Schema({vol.Required(ATTR_CODE): cv.string})
SERVICE_SCHEMA_AUX = vol.Schema(
{
vol.Required(ATTR_OUTPUT_ID): cv.positive_int,
vol.Optional(ATTR_STATE, default=True): cv.boolean,
}
)
def async_setup_services(hass: HomeAssistant) -> None:
"""Register Ness Alarm services."""
async def handle_panic(call: ServiceCall) -> None:
"""Handle panic service call."""
entries = call.hass.config_entries.async_loaded_entries(DOMAIN)
if not entries:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="no_config_entry",
)
client = entries[0].runtime_data
await client.panic(call.data[ATTR_CODE])
async def handle_aux(call: ServiceCall) -> None:
"""Handle aux service call."""
entries = call.hass.config_entries.async_loaded_entries(DOMAIN)
if not entries:
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="no_config_entry",
)
client = entries[0].runtime_data
await client.aux(call.data[ATTR_OUTPUT_ID], call.data[ATTR_STATE])
hass.services.async_register(
DOMAIN, SERVICE_PANIC, handle_panic, schema=SERVICE_SCHEMA_PANIC
)
hass.services.async_register(
DOMAIN, SERVICE_AUX, handle_aux, schema=SERVICE_SCHEMA_AUX
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/ness_alarm/services.py",
"license": "Apache License 2.0",
"lines": 43,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/ness_alarm/test_config_flow.py | """Test the Ness Alarm config flow."""
from types import MappingProxyType
from unittest.mock import AsyncMock
import pytest
from homeassistant.components.binary_sensor import BinarySensorDeviceClass
from homeassistant.components.ness_alarm.const import (
CONF_INFER_ARMING_STATE,
CONF_SHOW_HOME_MODE,
CONF_ZONE_ID,
CONF_ZONE_NAME,
CONF_ZONE_NUMBER,
CONF_ZONE_TYPE,
CONF_ZONES,
DOMAIN,
SUBENTRY_TYPE_ZONE,
)
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER, ConfigSubentry
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TYPE
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_user_flow(
hass: HomeAssistant, mock_client: 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["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
CONF_INFER_ARMING_STATE: False,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Ness Alarm 192.168.1.100:1992"
assert result["data"] == {
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
CONF_INFER_ARMING_STATE: False,
}
assert len(mock_setup_entry.mock_calls) == 1
mock_client.close.assert_awaited_once()
async def test_user_flow_with_infer_arming_state(
hass: HomeAssistant, mock_client: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test user flow with infer_arming_state enabled."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
CONF_INFER_ARMING_STATE: True,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"][CONF_INFER_ARMING_STATE] is True
async def test_user_flow_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test we abort if already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
CONF_INFER_ARMING_STATE: False,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(OSError("Connection refused"), "cannot_connect"),
(TimeoutError, "cannot_connect"),
(RuntimeError("Unexpected"), "unknown"),
],
)
async def test_user_flow_connection_error_recovery(
hass: HomeAssistant,
mock_client: AsyncMock,
mock_setup_entry: AsyncMock,
side_effect: Exception,
expected_error: str,
) -> None:
"""Test connection error handling and recovery."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
# First attempt fails
mock_client.update.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
CONF_INFER_ARMING_STATE: False,
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": expected_error}
mock_client.close.assert_awaited_once()
# Second attempt succeeds
mock_client.update.side_effect = None
mock_client.close.reset_mock()
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
CONF_INFER_ARMING_STATE: False,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
async def test_import_yaml_config(
hass: HomeAssistant, mock_client: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test importing YAML configuration."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_HOST: "192.168.1.72",
CONF_PORT: 4999,
CONF_INFER_ARMING_STATE: False,
CONF_ZONES: [
{CONF_ZONE_NAME: "Garage", CONF_ZONE_ID: 1},
{
CONF_ZONE_NAME: "Front Door",
CONF_ZONE_ID: 5,
CONF_ZONE_TYPE: BinarySensorDeviceClass.DOOR,
},
],
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Ness Alarm 192.168.1.72:4999"
assert result["data"] == {
CONF_HOST: "192.168.1.72",
CONF_PORT: 4999,
CONF_INFER_ARMING_STATE: False,
}
# Check that subentries were created for zones with names preserved
assert len(result["subentries"]) == 2
assert result["subentries"][0]["title"] == "Zone 1"
assert result["subentries"][0]["unique_id"] == "zone_1"
assert result["subentries"][0]["data"][CONF_TYPE] == BinarySensorDeviceClass.MOTION
assert result["subentries"][0]["data"][CONF_ZONE_NAME] == "Garage"
assert result["subentries"][1]["title"] == "Zone 5"
assert result["subentries"][1]["unique_id"] == "zone_5"
assert result["subentries"][1]["data"][CONF_TYPE] == BinarySensorDeviceClass.DOOR
assert result["subentries"][1]["data"][CONF_ZONE_NAME] == "Front Door"
assert len(mock_setup_entry.mock_calls) == 1
mock_client.close.assert_awaited_once()
@pytest.mark.parametrize(
("side_effect", "expected_reason"),
[
(OSError("Connection refused"), "cannot_connect"),
(TimeoutError, "cannot_connect"),
(RuntimeError("Unexpected"), "unknown"),
],
)
async def test_import_yaml_config_errors(
hass: HomeAssistant,
mock_client: AsyncMock,
mock_setup_entry: AsyncMock,
side_effect: Exception,
expected_reason: str,
) -> None:
"""Test importing YAML configuration."""
mock_client.update.side_effect = side_effect
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_HOST: "192.168.1.72",
CONF_PORT: 4999,
CONF_INFER_ARMING_STATE: False,
CONF_ZONES: [
{CONF_ZONE_NAME: "Garage", CONF_ZONE_ID: 1},
{
CONF_ZONE_NAME: "Front Door",
CONF_ZONE_ID: 5,
CONF_ZONE_TYPE: BinarySensorDeviceClass.DOOR,
},
],
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == expected_reason
async def test_import_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test we abort import if already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_HOST: "192.168.1.100",
CONF_PORT: 4999,
CONF_ZONES: [],
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("side_effect", "expected_reason"),
[
(OSError("Connection refused"), "cannot_connect"),
(TimeoutError, "cannot_connect"),
(RuntimeError("Unexpected"), "unknown"),
],
)
async def test_import_connection_errors(
hass: HomeAssistant,
mock_client: AsyncMock,
side_effect: Exception,
expected_reason: str,
) -> None:
"""Test import aborts on connection errors."""
mock_client.update.side_effect = side_effect
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={
CONF_HOST: "192.168.1.72",
CONF_PORT: 4999,
CONF_ZONES: [],
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == expected_reason
mock_client.close.assert_awaited_once()
async def test_zone_subentry_flow(hass: HomeAssistant) -> None:
"""Test adding a zone through subentry flow."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
},
)
entry.add_to_hass(hass)
result = await hass.config_entries.subentries.async_init(
(entry.entry_id, SUBENTRY_TYPE_ZONE),
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"],
{
CONF_ZONE_NUMBER: 1,
CONF_TYPE: BinarySensorDeviceClass.DOOR,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Zone 1"
assert result["data"][CONF_ZONE_NUMBER] == 1
assert result["data"][CONF_TYPE] == BinarySensorDeviceClass.DOOR
async def test_zone_subentry_already_configured(hass: HomeAssistant) -> None:
"""Test adding a zone that already exists."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
},
)
entry.add_to_hass(hass)
entry.subentries = {
"zone_1_id": ConfigSubentry(
subentry_type=SUBENTRY_TYPE_ZONE,
subentry_id="zone_1_id",
unique_id="zone_1",
title="Zone 1",
data=MappingProxyType(
{
CONF_ZONE_NUMBER: 1,
CONF_TYPE: BinarySensorDeviceClass.MOTION,
}
),
)
}
result = await hass.config_entries.subentries.async_init(
(entry.entry_id, SUBENTRY_TYPE_ZONE),
context={"source": SOURCE_USER},
)
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_ZONE_NUMBER: 1,
CONF_TYPE: BinarySensorDeviceClass.DOOR,
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {CONF_ZONE_NUMBER: "already_configured"}
async def test_zone_subentry_reconfigure(hass: HomeAssistant) -> None:
"""Test reconfiguring an existing zone."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
},
)
entry.add_to_hass(hass)
zone_subentry = ConfigSubentry(
subentry_type=SUBENTRY_TYPE_ZONE,
subentry_id="zone_1_id",
unique_id="zone_1",
title="Zone 1",
data=MappingProxyType(
{
CONF_ZONE_NUMBER: 1,
CONF_TYPE: BinarySensorDeviceClass.MOTION,
}
),
)
entry.subentries = {"zone_1_id": zone_subentry}
result = await entry.start_subentry_reconfigure_flow(hass, "zone_1_id")
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["description_placeholders"][CONF_ZONE_NUMBER] == "1"
result = await hass.config_entries.subentries.async_configure(
result["flow_id"],
{
CONF_TYPE: BinarySensorDeviceClass.DOOR,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
async def test_options_flow(hass: HomeAssistant) -> None:
"""Test options flow to configure alarm panel settings."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
},
)
entry.add_to_hass(hass)
result = await hass.config_entries.options.async_init(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"],
{
CONF_SHOW_HOME_MODE: False,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert entry.options[CONF_SHOW_HOME_MODE] is False
async def test_options_flow_enable_home_mode(hass: HomeAssistant) -> None:
"""Test options flow to enable home mode."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HOST: "192.168.1.100",
CONF_PORT: 1992,
},
options={CONF_SHOW_HOME_MODE: False},
)
entry.add_to_hass(hass)
result = await hass.config_entries.options.async_init(entry.entry_id)
result = await hass.config_entries.options.async_configure(
result["flow_id"],
{
CONF_SHOW_HOME_MODE: True,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert entry.options[CONF_SHOW_HOME_MODE] is True
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/ness_alarm/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 386,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/powerfox_local/config_flow.py | """Config flow for Powerfox Local integration."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from powerfox import PowerfoxAuthenticationError, PowerfoxConnectionError, PowerfoxLocal
import voluptuous as vol
from homeassistant.config_entries import (
SOURCE_RECONFIGURE,
SOURCE_USER,
ConfigFlow,
ConfigFlowResult,
)
from homeassistant.const import CONF_API_KEY, CONF_HOST
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from .const import DOMAIN
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_HOST): str,
vol.Required(CONF_API_KEY): str,
}
)
STEP_REAUTH_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_API_KEY): str,
}
)
class PowerfoxLocalConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Powerfox Local."""
_host: str
_api_key: str
_device_id: str
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the user step."""
errors = {}
if user_input is not None:
self._host = user_input[CONF_HOST]
self._api_key = user_input[CONF_API_KEY]
self._device_id = self._api_key
try:
await self._async_validate_connection()
except PowerfoxAuthenticationError:
errors["base"] = "invalid_auth"
except PowerfoxConnectionError:
errors["base"] = "cannot_connect"
else:
if self.source == SOURCE_USER:
return self._async_create_entry()
return self.async_update_reload_and_abort(
self._get_reconfigure_entry(),
data={
CONF_HOST: self._host,
CONF_API_KEY: self._api_key,
},
)
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
)
async def async_step_zeroconf(
self, discovery_info: ZeroconfServiceInfo
) -> ConfigFlowResult:
"""Handle zeroconf discovery."""
self._host = discovery_info.host
self._device_id = discovery_info.properties["id"]
self._api_key = self._device_id
try:
await self._async_validate_connection()
except PowerfoxAuthenticationError, PowerfoxConnectionError:
return self.async_abort(reason="cannot_connect")
self.context["title_placeholders"] = {
"name": f"Poweropti ({self._device_id[-5:]})"
}
self._set_confirm_only()
return self.async_show_form(
step_id="zeroconf_confirm",
description_placeholders={"host": self._host},
)
async def async_step_zeroconf_confirm(
self, _: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a confirmation flow for zeroconf discovery."""
return self._async_create_entry()
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Handle re-authentication flow."""
self._host = entry_data[CONF_HOST]
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle re-authentication confirmation."""
errors = {}
if user_input is not None:
self._api_key = user_input[CONF_API_KEY]
reauth_entry = self._get_reauth_entry()
client = PowerfoxLocal(
host=reauth_entry.data[CONF_HOST],
api_key=user_input[CONF_API_KEY],
session=async_get_clientsession(self.hass),
)
try:
await client.value()
except PowerfoxAuthenticationError:
errors["base"] = "invalid_auth"
except PowerfoxConnectionError:
errors["base"] = "cannot_connect"
else:
return self.async_update_reload_and_abort(
reauth_entry,
data_updates=user_input,
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=STEP_REAUTH_DATA_SCHEMA,
errors=errors,
)
async def async_step_reconfigure(
self, user_input: Mapping[str, Any]
) -> ConfigFlowResult:
"""Handle reconfiguration."""
return await self.async_step_user()
def _async_create_entry(self) -> ConfigFlowResult:
"""Create a config entry."""
return self.async_create_entry(
title=f"Poweropti ({self._device_id[-5:]})",
data={
CONF_HOST: self._host,
CONF_API_KEY: self._api_key,
},
)
async def _async_validate_connection(self) -> None:
"""Validate the connection and set unique ID."""
client = PowerfoxLocal(
host=self._host,
api_key=self._api_key,
session=async_get_clientsession(self.hass),
)
await client.value()
await self.async_set_unique_id(self._device_id, raise_on_progress=False)
if self.source == SOURCE_RECONFIGURE:
self._abort_if_unique_id_mismatch()
else:
self._abort_if_unique_id_configured(updates={CONF_HOST: self._host})
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/powerfox_local/config_flow.py",
"license": "Apache License 2.0",
"lines": 148,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/powerfox_local/const.py | """Constants for the Powerfox Local integration."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Final
DOMAIN: Final = "powerfox_local"
LOGGER = logging.getLogger(__package__)
SCAN_INTERVAL = timedelta(seconds=5)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/powerfox_local/const.py",
"license": "Apache License 2.0",
"lines": 8,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/powerfox_local/coordinator.py | """Coordinator for Powerfox Local integration."""
from __future__ import annotations
from powerfox import (
LocalResponse,
PowerfoxAuthenticationError,
PowerfoxConnectionError,
PowerfoxLocal,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY, CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN, LOGGER, SCAN_INTERVAL
type PowerfoxLocalConfigEntry = ConfigEntry[PowerfoxLocalDataUpdateCoordinator]
class PowerfoxLocalDataUpdateCoordinator(DataUpdateCoordinator[LocalResponse]):
"""Class to manage fetching Powerfox local data."""
config_entry: PowerfoxLocalConfigEntry
def __init__(self, hass: HomeAssistant, entry: PowerfoxLocalConfigEntry) -> None:
"""Initialize the coordinator."""
self.client = PowerfoxLocal(
host=entry.data[CONF_HOST],
api_key=entry.data[CONF_API_KEY],
session=async_get_clientsession(hass),
)
self.device_id: str = entry.data[CONF_API_KEY]
super().__init__(
hass,
LOGGER,
config_entry=entry,
name=f"{DOMAIN}_{entry.data[CONF_HOST]}",
update_interval=SCAN_INTERVAL,
)
async def _async_update_data(self) -> LocalResponse:
"""Fetch data from the local poweropti."""
try:
return await self.client.value()
except PowerfoxAuthenticationError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="auth_failed",
translation_placeholders={"host": self.config_entry.data[CONF_HOST]},
) from err
except PowerfoxConnectionError as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="connection_error",
translation_placeholders={"host": self.config_entry.data[CONF_HOST]},
) from err
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/powerfox_local/coordinator.py",
"license": "Apache License 2.0",
"lines": 50,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/powerfox_local/entity.py | """Base entity for Powerfox Local."""
from __future__ import annotations
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import PowerfoxLocalDataUpdateCoordinator
class PowerfoxLocalEntity(CoordinatorEntity[PowerfoxLocalDataUpdateCoordinator]):
"""Base entity for Powerfox Local."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: PowerfoxLocalDataUpdateCoordinator,
) -> None:
"""Initialize Powerfox Local entity."""
super().__init__(coordinator)
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, coordinator.device_id)},
manufacturer="Powerfox",
model="Poweropti",
serial_number=coordinator.device_id,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/powerfox_local/entity.py",
"license": "Apache License 2.0",
"lines": 21,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/powerfox_local/sensor.py | """Sensors for Powerfox Local integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from powerfox import LocalResponse
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.const import UnitOfEnergy, UnitOfPower
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import PowerfoxLocalConfigEntry, PowerfoxLocalDataUpdateCoordinator
from .entity import PowerfoxLocalEntity
PARALLEL_UPDATES = 0
@dataclass(frozen=True, kw_only=True)
class PowerfoxLocalSensorEntityDescription(SensorEntityDescription):
"""Describes Powerfox Local sensor entity."""
value_fn: Callable[[LocalResponse], float | int | None]
SENSORS: tuple[PowerfoxLocalSensorEntityDescription, ...] = (
PowerfoxLocalSensorEntityDescription(
key="power",
native_unit_of_measurement=UnitOfPower.WATT,
device_class=SensorDeviceClass.POWER,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: data.power,
),
PowerfoxLocalSensorEntityDescription(
key="energy_usage",
translation_key="energy_usage",
native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
value_fn=lambda data: data.energy_usage,
),
PowerfoxLocalSensorEntityDescription(
key="energy_usage_high_tariff",
translation_key="energy_usage_high_tariff",
native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
value_fn=lambda data: data.energy_usage_high_tariff,
),
PowerfoxLocalSensorEntityDescription(
key="energy_usage_low_tariff",
translation_key="energy_usage_low_tariff",
native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
value_fn=lambda data: data.energy_usage_low_tariff,
),
PowerfoxLocalSensorEntityDescription(
key="energy_return",
translation_key="energy_return",
native_unit_of_measurement=UnitOfEnergy.WATT_HOUR,
device_class=SensorDeviceClass.ENERGY,
state_class=SensorStateClass.TOTAL_INCREASING,
value_fn=lambda data: data.energy_return,
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: PowerfoxLocalConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Powerfox Local sensors based on a config entry."""
coordinator = entry.runtime_data
async_add_entities(
PowerfoxLocalSensorEntity(
coordinator=coordinator,
description=description,
)
for description in SENSORS
if description.value_fn(coordinator.data) is not None
)
class PowerfoxLocalSensorEntity(PowerfoxLocalEntity, SensorEntity):
"""Defines a Powerfox Local sensor."""
entity_description: PowerfoxLocalSensorEntityDescription
def __init__(
self,
coordinator: PowerfoxLocalDataUpdateCoordinator,
description: PowerfoxLocalSensorEntityDescription,
) -> None:
"""Initialize the Powerfox Local sensor."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.device_id}_{description.key}"
@property
def native_value(self) -> float | int | None:
"""Return the state of the entity."""
return self.entity_description.value_fn(self.coordinator.data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/powerfox_local/sensor.py",
"license": "Apache License 2.0",
"lines": 93,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/powerfox_local/test_config_flow.py | """Test the Powerfox Local config flow."""
from datetime import UTC, datetime
from unittest.mock import AsyncMock
from powerfox import LocalResponse, PowerfoxAuthenticationError, PowerfoxConnectionError
import pytest
from homeassistant.components.powerfox_local.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF
from homeassistant.const import CONF_API_KEY, CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from . import MOCK_API_KEY, MOCK_DEVICE_ID, MOCK_HOST
from tests.common import MockConfigEntry
MOCK_ZEROCONF_DISCOVERY_INFO = ZeroconfServiceInfo(
ip_address=MOCK_HOST,
ip_addresses=[MOCK_HOST],
hostname="powerfox.local",
name="Powerfox",
port=443,
type="_http._tcp",
properties={"id": MOCK_DEVICE_ID},
)
async def test_full_user_flow(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> 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"
assert not result.get("errors")
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: MOCK_HOST, CONF_API_KEY: MOCK_API_KEY},
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result.get("title") == f"Poweropti ({MOCK_DEVICE_ID[-5:]})"
assert result.get("data") == {
CONF_HOST: MOCK_HOST,
CONF_API_KEY: MOCK_API_KEY,
}
assert result["result"].unique_id == MOCK_DEVICE_ID
assert len(mock_powerfox_local_client.value.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_zeroconf_discovery(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test zeroconf discovery."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=MOCK_ZEROCONF_DISCOVERY_INFO,
)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "zeroconf_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={},
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
assert result.get("title") == f"Poweropti ({MOCK_DEVICE_ID[-5:]})"
assert result.get("data") == {
CONF_HOST: MOCK_HOST,
CONF_API_KEY: MOCK_API_KEY,
}
assert result["result"].unique_id == MOCK_DEVICE_ID
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
"exception",
[
PowerfoxConnectionError,
PowerfoxAuthenticationError,
],
)
async def test_zeroconf_discovery_errors(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
exception: Exception,
) -> None:
"""Test zeroconf discovery aborts on connection/auth errors."""
mock_powerfox_local_client.value.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=MOCK_ZEROCONF_DISCOVERY_INFO,
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "cannot_connect"
async def test_zeroconf_already_configured(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test zeroconf discovery aborts when already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_ZEROCONF},
data=MOCK_ZEROCONF_DISCOVERY_INFO,
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "already_configured"
async def test_duplicate_entry(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test abort when setting up duplicate entry."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result.get("type") is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: MOCK_HOST, CONF_API_KEY: MOCK_API_KEY},
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "already_configured"
@pytest.mark.parametrize(
("exception", "error"),
[
(PowerfoxConnectionError, "cannot_connect"),
(PowerfoxAuthenticationError, "invalid_auth"),
],
)
async def test_user_flow_exceptions(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_setup_entry: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test exceptions during user config flow."""
mock_powerfox_local_client.value.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: MOCK_HOST, CONF_API_KEY: MOCK_API_KEY},
)
assert result.get("type") is FlowResultType.FORM
assert result.get("errors") == {"base": error}
# Recover from error
mock_powerfox_local_client.value.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: MOCK_HOST, CONF_API_KEY: MOCK_API_KEY},
)
assert result.get("type") is FlowResultType.CREATE_ENTRY
async def test_step_reauth(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test re-authentication flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_API_KEY: "new-api-key"},
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == "new-api-key"
@pytest.mark.parametrize(
("exception", "error"),
[
(PowerfoxConnectionError, "cannot_connect"),
(PowerfoxAuthenticationError, "invalid_auth"),
],
)
async def test_step_reauth_exceptions(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test exceptions during re-authentication flow."""
mock_powerfox_local_client.value.side_effect = exception
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_API_KEY: "new-api-key"},
)
assert result.get("type") is FlowResultType.FORM
assert result.get("errors") == {"base": error}
# Recover from error
mock_powerfox_local_client.value.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_API_KEY: "new-api-key"},
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == "new-api-key"
async def test_reconfigure_flow(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test reconfiguration flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
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_HOST: "192.168.1.200", CONF_API_KEY: MOCK_API_KEY},
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "192.168.1.200"
assert mock_config_entry.data[CONF_API_KEY] == MOCK_API_KEY
@pytest.mark.parametrize(
("exception", "error"),
[
(PowerfoxConnectionError, "cannot_connect"),
(PowerfoxAuthenticationError, "invalid_auth"),
],
)
async def test_reconfigure_flow_exceptions(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
exception: Exception,
error: str,
) -> None:
"""Test exceptions during reconfiguration flow."""
mock_powerfox_local_client.value.side_effect = exception
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
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_HOST: "192.168.1.200", CONF_API_KEY: MOCK_API_KEY},
)
assert result.get("type") is FlowResultType.FORM
assert result.get("errors") == {"base": error}
# Recover from error
mock_powerfox_local_client.value.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "192.168.1.200", CONF_API_KEY: MOCK_API_KEY},
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "192.168.1.200"
async def test_reconfigure_flow_unique_id_mismatch(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test reconfiguration aborts on unique ID mismatch."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result.get("type") is FlowResultType.FORM
assert result.get("step_id") == "user"
# Return response with different API key (which serves as device_id)
mock_powerfox_local_client.value.return_value = LocalResponse(
timestamp=datetime(2026, 2, 25, 10, 48, 51, tzinfo=UTC),
power=111,
energy_usage=1111111,
energy_return=111111,
energy_usage_high_tariff=111111,
energy_usage_low_tariff=111111,
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "192.168.1.200", CONF_API_KEY: "different_api_key"},
)
assert result.get("type") is FlowResultType.ABORT
assert result.get("reason") == "unique_id_mismatch"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/powerfox_local/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/powerfox_local/test_init.py | """Test the Powerfox Local init module."""
from __future__ import annotations
from unittest.mock import AsyncMock
from powerfox import PowerfoxAuthenticationError, PowerfoxConnectionError
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
async def test_load_unload_entry(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test load and unload entry."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
async def test_config_entry_not_ready(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test config entry not ready on connection error."""
mock_powerfox_local_client.value.side_effect = PowerfoxConnectionError
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_setup_entry_exception(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test ConfigEntryNotReady when API raises an exception during entry setup."""
mock_config_entry.add_to_hass(hass)
mock_powerfox_local_client.value.side_effect = PowerfoxAuthenticationError
await hass.config_entries.async_setup(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["step_id"] == "reauth_confirm"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/powerfox_local/test_init.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/powerfox_local/test_sensor.py | """Test the sensors provided by the Powerfox Local integration."""
from __future__ import annotations
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from powerfox import PowerfoxConnectionError
import pytest
from syrupy.assertion import SnapshotAssertion
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 . import MOCK_DEVICE_ID, setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_sensors(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the Powerfox Local sensors."""
with patch("homeassistant.components.powerfox_local.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_update_failed(
hass: HomeAssistant,
mock_powerfox_local_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test entities become unavailable after failed update."""
entity_id = f"sensor.poweropti_{MOCK_DEVICE_ID[-5:]}_energy_usage"
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
assert hass.states.get(entity_id).state is not None
mock_powerfox_local_client.value.side_effect = PowerfoxConnectionError
freezer.tick(timedelta(seconds=15))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/powerfox_local/test_sensor.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:homeassistant/components/onkyo/coordinator.py | """Onkyo coordinators."""
from __future__ import annotations
import asyncio
from enum import StrEnum
import logging
from typing import TYPE_CHECKING, cast
from aioonkyo import Kind, Status, Zone, command, query, status
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import DOMAIN
from .receiver import ReceiverManager
if TYPE_CHECKING:
from . import OnkyoConfigEntry
_LOGGER = logging.getLogger(__name__)
POWER_ON_QUERY_DELAY = 4
class Channel(StrEnum):
"""Audio channel."""
FRONT_LEFT = "front_left"
FRONT_RIGHT = "front_right"
CENTER = "center"
SURROUND_LEFT = "surround_left"
SURROUND_RIGHT = "surround_right"
SURROUND_BACK_LEFT = "surround_back_left"
SURROUND_BACK_RIGHT = "surround_back_right"
SUBWOOFER = "subwoofer"
HEIGHT_1_LEFT = "height_1_left"
HEIGHT_1_RIGHT = "height_1_right"
HEIGHT_2_LEFT = "height_2_left"
HEIGHT_2_RIGHT = "height_2_right"
SUBWOOFER_2 = "subwoofer_2"
ChannelMutingData = dict[Channel, status.ChannelMuting.Param]
ChannelMutingDesired = dict[Channel, command.ChannelMuting.Param]
class ChannelMutingCoordinator(DataUpdateCoordinator[ChannelMutingData]):
"""Coordinator for channel muting state."""
config_entry: OnkyoConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: OnkyoConfigEntry,
manager: ReceiverManager,
) -> None:
"""Initialize the coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name="onkyo_channel_muting",
update_interval=None,
)
self.manager = manager
self.data = ChannelMutingData()
self._desired = ChannelMutingDesired()
self._entities_added = False
self._query_state_task: asyncio.Task[None] | None = None
manager.callbacks.connect.append(self._connect_callback)
manager.callbacks.disconnect.append(self._disconnect_callback)
manager.callbacks.update.append(self._update_callback)
config_entry.async_on_unload(self._cancel_tasks)
async def _connect_callback(self, _reconnect: bool) -> None:
"""Receiver (re)connected."""
await self.manager.write(query.ChannelMuting())
async def _disconnect_callback(self) -> None:
"""Receiver disconnected."""
self._cancel_tasks()
self.async_set_updated_data(self.data)
def _cancel_tasks(self) -> None:
"""Cancel the tasks."""
if self._query_state_task is not None:
self._query_state_task.cancel()
self._query_state_task = None
def _query_state(self, delay: float = 0) -> None:
"""Query the receiver for all the info, that we care about."""
if self._query_state_task is not None:
self._query_state_task.cancel()
self._query_state_task = None
async def coro() -> None:
if delay:
await asyncio.sleep(delay)
await self.manager.write(query.ChannelMuting())
self._query_state_task = None
self._query_state_task = asyncio.create_task(coro())
async def _async_update_data(self) -> ChannelMutingData:
"""Respond to a data update request."""
self._query_state()
return self.data
async def async_send_command(
self, channel: Channel, param: command.ChannelMuting.Param
) -> None:
"""Send muting command for a channel."""
self._desired[channel] = param
message_data: ChannelMutingDesired = self.data | self._desired
message = command.ChannelMuting(**message_data) # type: ignore[misc]
await self.manager.write(message)
async def _update_callback(self, message: Status) -> None:
"""New message from the receiver."""
match message:
case status.NotAvailable(kind=Kind.CHANNEL_MUTING):
not_available = True
case status.ChannelMuting():
not_available = False
case status.Power(zone=Zone.MAIN, param=status.Power.Param.ON):
self._query_state(POWER_ON_QUERY_DELAY)
return
case _:
return
if not self._entities_added:
_LOGGER.debug(
"Discovered %s on %s (%s)",
self.name,
self.manager.info.model_name,
self.manager.info.host,
)
self._entities_added = True
async_dispatcher_send(
self.hass,
f"{DOMAIN}_{self.config_entry.entry_id}_channel_muting",
self,
)
if not_available:
self.data.clear()
self._desired.clear()
self.async_set_updated_data(self.data)
else:
message = cast(status.ChannelMuting, message)
self.data = {channel: getattr(message, channel) for channel in Channel}
self._desired = {
channel: desired
for channel, desired in self._desired.items()
if self.data[channel] != desired
}
self.async_set_updated_data(self.data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/onkyo/coordinator.py",
"license": "Apache License 2.0",
"lines": 132,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/onkyo/switch.py | """Switch platform."""
from __future__ import annotations
import logging
from typing import TYPE_CHECKING, Any
from aioonkyo import command, status
from homeassistant.components.switch import SwitchEntity
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import Channel, ChannelMutingCoordinator
if TYPE_CHECKING:
from . import OnkyoConfigEntry
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
entry: OnkyoConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up switch platform for config entry."""
@callback
def async_add_channel_muting_entities(
coordinator: ChannelMutingCoordinator,
) -> None:
"""Add channel muting switch entities."""
async_add_entities(
OnkyoChannelMutingSwitch(coordinator, channel) for channel in Channel
)
entry.async_on_unload(
async_dispatcher_connect(
hass,
f"{DOMAIN}_{entry.entry_id}_channel_muting",
async_add_channel_muting_entities,
)
)
class OnkyoChannelMutingSwitch(
CoordinatorEntity[ChannelMutingCoordinator], SwitchEntity
):
"""Onkyo Receiver Channel Muting Switch (one per channel)."""
_attr_has_entity_name = True
def __init__(
self,
coordinator: ChannelMutingCoordinator,
channel: Channel,
) -> None:
"""Initialize the switch entity."""
super().__init__(coordinator)
self._channel = channel
name = coordinator.manager.info.model_name
channel_name = channel.replace("_", " ")
identifier = coordinator.manager.info.identifier
self._attr_name = f"{name} Mute {channel_name}"
self._attr_unique_id = f"{identifier}-channel_muting-{channel}"
@property
def available(self) -> bool:
"""Return if entity is available."""
return self.coordinator.manager.connected
async def async_turn_on(self, **kwargs: Any) -> None:
"""Mute the channel."""
await self.coordinator.async_send_command(
self._channel, command.ChannelMuting.Param.ON
)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Unmute the channel."""
await self.coordinator.async_send_command(
self._channel, command.ChannelMuting.Param.OFF
)
def _handle_coordinator_update(self) -> None:
"""Handle updated data from the coordinator."""
value = self.coordinator.data.get(self._channel)
self._attr_is_on = (
None if value is None else value == status.ChannelMuting.Param.ON
)
super()._handle_coordinator_update()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/onkyo/switch.py",
"license": "Apache License 2.0",
"lines": 75,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/onkyo/test_switch.py | """Test Onkyo switch platform."""
import asyncio
from collections.abc import AsyncGenerator
from unittest.mock import AsyncMock, patch
from aioonkyo import Code, Instruction, Kind, Zone, command, query, status
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.homeassistant import (
DOMAIN as HOMEASSISTANT_DOMAIN,
SERVICE_UPDATE_ENTITY,
)
from homeassistant.components.onkyo.coordinator import Channel
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
ENTITY_ID = "switch.tx_nr7100_mute_front_left"
def _channel_muting_status(
**overrides: status.ChannelMuting.Param,
) -> status.ChannelMuting:
"""Create a ChannelMuting status with all channels OFF, with overrides."""
params = dict.fromkeys(Channel, status.ChannelMuting.Param.OFF)
params.update(overrides)
return status.ChannelMuting(
Code.from_kind_zone(Kind.CHANNEL_MUTING, Zone.MAIN),
None,
**params,
)
@pytest.fixture(autouse=True)
async def auto_setup_integration(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_receiver: AsyncMock,
read_queue: asyncio.Queue,
writes: list[Instruction],
) -> AsyncGenerator[None]:
"""Auto setup integration."""
read_queue.put_nowait(
_channel_muting_status(
front_right=status.ChannelMuting.Param.ON,
center=status.ChannelMuting.Param.ON,
)
)
with (
patch(
"homeassistant.components.onkyo.coordinator.POWER_ON_QUERY_DELAY",
0,
),
patch("homeassistant.components.onkyo.PLATFORMS", [Platform.SWITCH]),
):
await setup_integration(hass, mock_config_entry)
writes.clear()
yield
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_state_changes(hass: HomeAssistant, read_queue: asyncio.Queue) -> None:
"""Test NotAvailable message clears channel muting state."""
assert (state := hass.states.get(ENTITY_ID)) is not None
assert state.state == STATE_OFF
read_queue.put_nowait(
_channel_muting_status(front_left=status.ChannelMuting.Param.ON)
)
await asyncio.sleep(0)
assert (state := hass.states.get(ENTITY_ID)) is not None
assert state.state == STATE_ON
read_queue.put_nowait(
status.NotAvailable(
Code.from_kind_zone(Kind.CHANNEL_MUTING, Zone.MAIN),
None,
Kind.CHANNEL_MUTING,
)
)
await asyncio.sleep(0)
assert (state := hass.states.get(ENTITY_ID)) is not None
assert state.state == STATE_UNKNOWN
async def test_availability(hass: HomeAssistant, read_queue: asyncio.Queue) -> None:
"""Test entity availability on disconnect and reconnect."""
assert (state := hass.states.get(ENTITY_ID)) is not None
assert state.state != STATE_UNAVAILABLE
# Simulate a disconnect
read_queue.put_nowait(None)
await asyncio.sleep(0)
assert (state := hass.states.get(ENTITY_ID)) is not None
assert state.state == STATE_UNAVAILABLE
# Simulate first status update after reconnect
read_queue.put_nowait(
_channel_muting_status(front_left=status.ChannelMuting.Param.ON)
)
await asyncio.sleep(0)
assert (state := hass.states.get(ENTITY_ID)) is not None
assert state.state != STATE_UNAVAILABLE
@pytest.mark.parametrize(
("action", "message"),
[
(
SERVICE_TURN_ON,
command.ChannelMuting(
front_left=command.ChannelMuting.Param.ON,
front_right=command.ChannelMuting.Param.ON,
center=command.ChannelMuting.Param.ON,
),
),
(
SERVICE_TURN_OFF,
command.ChannelMuting(
front_right=command.ChannelMuting.Param.ON,
center=command.ChannelMuting.Param.ON,
),
),
],
)
async def test_actions(
hass: HomeAssistant,
writes: list[Instruction],
action: str,
message: Instruction,
) -> None:
"""Test actions."""
await hass.services.async_call(
SWITCH_DOMAIN,
action,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
assert writes[0] == message
async def test_query_state_task(
read_queue: asyncio.Queue, writes: list[Instruction]
) -> None:
"""Test query state task."""
read_queue.put_nowait(
status.Power(
Code.from_kind_zone(Kind.POWER, Zone.MAIN), None, status.Power.Param.STANDBY
)
)
read_queue.put_nowait(
status.Power(
Code.from_kind_zone(Kind.POWER, Zone.MAIN), None, status.Power.Param.ON
)
)
read_queue.put_nowait(
status.Power(
Code.from_kind_zone(Kind.POWER, Zone.MAIN), None, status.Power.Param.STANDBY
)
)
read_queue.put_nowait(
status.Power(
Code.from_kind_zone(Kind.POWER, Zone.MAIN), None, status.Power.Param.ON
)
)
await asyncio.sleep(0.1)
queries = [w for w in writes if isinstance(w, query.ChannelMuting)]
assert len(queries) == 1
async def test_update_entity(
hass: HomeAssistant,
writes: list[Instruction],
) -> None:
"""Test manual entity update."""
await async_setup_component(hass, HOMEASSISTANT_DOMAIN, {})
await hass.services.async_call(
HOMEASSISTANT_DOMAIN,
SERVICE_UPDATE_ENTITY,
{ATTR_ENTITY_ID: ENTITY_ID},
blocking=True,
)
await asyncio.sleep(0)
queries = [w for w in writes if isinstance(w, query.ChannelMuting)]
assert len(queries) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/onkyo/test_switch.py",
"license": "Apache License 2.0",
"lines": 185,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/hdfury/number.py | """Number platform for HDFury Integration."""
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from hdfury import HDFuryAPI, HDFuryError
from homeassistant.components.number import (
NumberDeviceClass,
NumberEntity,
NumberEntityDescription,
NumberMode,
)
from homeassistant.const import EntityCategory, UnitOfTime
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN
from .coordinator import HDFuryConfigEntry
from .entity import HDFuryEntity
PARALLEL_UPDATES = 1
@dataclass(kw_only=True, frozen=True)
class HDFuryNumberEntityDescription(NumberEntityDescription):
"""Description for HDFury number entities."""
set_value_fn: Callable[[HDFuryAPI, str], Awaitable[None]]
NUMBERS: tuple[HDFuryNumberEntityDescription, ...] = (
HDFuryNumberEntityDescription(
key="unmutecnt",
translation_key="audio_unmute",
entity_registry_enabled_default=False,
mode=NumberMode.BOX,
native_min_value=50,
native_max_value=1000,
native_step=1,
device_class=NumberDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.MILLISECONDS,
entity_category=EntityCategory.CONFIG,
set_value_fn=lambda client, value: client.set_audio_unmute(value),
),
HDFuryNumberEntityDescription(
key="earcunmutecnt",
translation_key="earc_unmute",
entity_registry_enabled_default=False,
mode=NumberMode.BOX,
native_min_value=0,
native_max_value=1000,
native_step=1,
device_class=NumberDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.MILLISECONDS,
entity_category=EntityCategory.CONFIG,
set_value_fn=lambda client, value: client.set_earc_unmute(value),
),
HDFuryNumberEntityDescription(
key="oledfade",
translation_key="oled_fade",
mode=NumberMode.BOX,
native_min_value=1,
native_max_value=100,
native_step=1,
device_class=NumberDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.SECONDS,
entity_category=EntityCategory.CONFIG,
set_value_fn=lambda client, value: client.set_oled_fade(value),
),
HDFuryNumberEntityDescription(
key="reboottimer",
translation_key="reboot_timer",
mode=NumberMode.BOX,
native_min_value=0,
native_max_value=100,
native_step=1,
device_class=NumberDeviceClass.DURATION,
native_unit_of_measurement=UnitOfTime.HOURS,
entity_category=EntityCategory.CONFIG,
set_value_fn=lambda client, value: client.set_reboot_timer(value),
),
)
async def async_setup_entry(
hass: HomeAssistant,
entry: HDFuryConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up numbers using the platform schema."""
coordinator = entry.runtime_data
async_add_entities(
HDFuryNumber(coordinator, description)
for description in NUMBERS
if description.key in coordinator.data.config
)
class HDFuryNumber(HDFuryEntity, NumberEntity):
"""Base HDFury Number Class."""
entity_description: HDFuryNumberEntityDescription
@property
def native_value(self) -> float:
"""Return the current number value."""
return float(self.coordinator.data.config[self.entity_description.key])
async def async_set_native_value(self, value: float) -> None:
"""Set Number Value Event."""
try:
await self.entity_description.set_value_fn(
self.coordinator.client, str(int(value))
)
except HDFuryError as error:
raise HomeAssistantError(
translation_domain=DOMAIN,
translation_key="communication_error",
) from error
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/hdfury/number.py",
"license": "Apache License 2.0",
"lines": 105,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/hdfury/test_number.py | """Tests for the HDFury number platform."""
from datetime import timedelta
from unittest.mock import AsyncMock
from freezegun.api import FrozenDateTimeFactory
from hdfury import HDFuryError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
import homeassistant.helpers.entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_number_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test HDFury number entities."""
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("entity_id", "method"),
[
("number.hdfury_vrroom_02_oled_fade_timer", "set_oled_fade"),
("number.hdfury_vrroom_02_restart_timer", "set_reboot_timer"),
("number.hdfury_vrroom_02_unmute_delay", "set_audio_unmute"),
("number.hdfury_vrroom_02_earc_unmute_delay", "set_earc_unmute"),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_number_set_value(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
method: str,
) -> None:
"""Test setting a device number value."""
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 50},
blocking=True,
)
getattr(mock_hdfury_client, method).assert_awaited_once_with("50")
@pytest.mark.parametrize(
("entity_id", "method"),
[
("number.hdfury_vrroom_02_oled_fade_timer", "set_oled_fade"),
("number.hdfury_vrroom_02_restart_timer", "set_reboot_timer"),
("number.hdfury_vrroom_02_unmute_delay", "set_audio_unmute"),
("number.hdfury_vrroom_02_earc_unmute_delay", "set_earc_unmute"),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_number_error(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
method: str,
) -> None:
"""Test set number value raises HomeAssistantError on API failure."""
getattr(mock_hdfury_client, method).side_effect = HDFuryError()
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
with pytest.raises(
HomeAssistantError,
match="An error occurred while communicating with HDFury device",
):
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 50},
blocking=True,
)
@pytest.mark.parametrize(
("entity_id"),
[
("number.hdfury_vrroom_02_oled_fade_timer"),
("number.hdfury_vrroom_02_restart_timer"),
("number.hdfury_vrroom_02_unmute_delay"),
("number.hdfury_vrroom_02_earc_unmute_delay"),
],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_number_entities_unavailable_on_error(
hass: HomeAssistant,
mock_hdfury_client: AsyncMock,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
entity_id: str,
) -> None:
"""Test API error causes entities to become unavailable."""
await setup_integration(hass, mock_config_entry, [Platform.NUMBER])
mock_hdfury_client.get_info.side_effect = HDFuryError()
freezer.tick(timedelta(seconds=61))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(entity_id).state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hdfury/test_number.py",
"license": "Apache License 2.0",
"lines": 108,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/onedrive_for_business/diagnostics.py | """Diagnostics support for OneDrive for Business."""
from __future__ import annotations
from dataclasses import asdict
from typing import Any
from homeassistant.components.diagnostics import async_redact_data
from homeassistant.const import CONF_ACCESS_TOKEN, CONF_TOKEN
from homeassistant.core import HomeAssistant
from .coordinator import OneDriveConfigEntry
TO_REDACT = {"display_name", "email", CONF_ACCESS_TOKEN, CONF_TOKEN}
async def async_get_config_entry_diagnostics(
hass: HomeAssistant,
entry: OneDriveConfigEntry,
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
coordinator = entry.runtime_data.coordinator
data = {
"drive": asdict(coordinator.data),
"config": {
**entry.data,
**entry.options,
},
}
return async_redact_data(data, TO_REDACT)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/onedrive_for_business/diagnostics.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:tests/components/onedrive_for_business/test_diagnostics.py | """Tests for the diagnostics data provided by the OneDrive for Business integration."""
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics."""
await setup_integration(hass, mock_config_entry)
assert (
await get_diagnostics_for_config_entry(hass, hass_client, mock_config_entry)
== snapshot
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/onedrive_for_business/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 19,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/vacuum/websocket.py | """Websocket commands for the Vacuum integration."""
from __future__ import annotations
from typing import Any
import voluptuous as vol
from homeassistant.components import websocket_api
from homeassistant.components.websocket_api import ERR_NOT_FOUND, ERR_NOT_SUPPORTED
from homeassistant.core import HomeAssistant, callback
import homeassistant.helpers.config_validation as cv
from .const import DATA_COMPONENT, VacuumEntityFeature
@callback
def async_register_websocket_handlers(hass: HomeAssistant) -> None:
"""Register websocket commands."""
websocket_api.async_register_command(hass, handle_get_segments)
@websocket_api.require_admin
@websocket_api.websocket_command(
{
vol.Required("type"): "vacuum/get_segments",
vol.Required("entity_id"): cv.strict_entity_id,
}
)
@websocket_api.async_response
async def handle_get_segments(
hass: HomeAssistant,
connection: websocket_api.ActiveConnection,
msg: dict[str, Any],
) -> None:
"""Get segments for a vacuum."""
entity_id = msg["entity_id"]
entity = hass.data[DATA_COMPONENT].get_entity(entity_id)
if entity is None:
connection.send_error(msg["id"], ERR_NOT_FOUND, f"Entity {entity_id} not found")
return
if VacuumEntityFeature.CLEAN_AREA not in entity.supported_features:
connection.send_error(
msg["id"], ERR_NOT_SUPPORTED, f"Entity {entity_id} not supported"
)
return
segments = await entity.async_get_segments()
connection.send_result(msg["id"], {"segments": segments})
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/vacuum/websocket.py",
"license": "Apache License 2.0",
"lines": 39,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:tests/components/vacuum/test_websocket.py | """Tests for vacuum websocket API."""
from __future__ import annotations
from dataclasses import asdict
import pytest
from homeassistant.components.vacuum import (
DOMAIN,
Segment,
StateVacuumEntity,
VacuumActivity,
VacuumEntityFeature,
)
from homeassistant.components.websocket_api import ERR_NOT_FOUND, ERR_NOT_SUPPORTED
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import (
MockVacuumWithCleanArea,
help_async_setup_entry_init,
help_async_unload_entry,
)
from tests.common import (
MockConfigEntry,
MockEntity,
MockModule,
mock_integration,
setup_test_component_platform,
)
from tests.typing import WebSocketGenerator
@pytest.mark.usefixtures("config_flow_fixture")
async def test_get_segments(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test vacuum/get_segments websocket command."""
segments = [
Segment(id="seg_1", name="Kitchen"),
Segment(id="seg_2", name="Living Room"),
Segment(id="seg_3", name="Bedroom", group="Upstairs"),
]
entity = MockVacuumWithCleanArea(
name="Testing",
entity_id="vacuum.testing",
segments=segments,
)
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
mock_integration(
hass,
MockModule(
"test",
async_setup_entry=help_async_setup_entry_init,
async_unload_entry=help_async_unload_entry,
),
)
setup_test_component_platform(hass, DOMAIN, [entity], from_config_entry=True)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "vacuum/get_segments", "entity_id": entity.entity_id}
)
msg = await client.receive_json()
assert msg["success"]
assert msg["result"] == {"segments": [asdict(seg) for seg in segments]}
async def test_get_segments_entity_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test vacuum/get_segments with unknown entity."""
assert await async_setup_component(hass, DOMAIN, {})
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "vacuum/get_segments", "entity_id": "vacuum.unknown"}
)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == ERR_NOT_FOUND
@pytest.mark.usefixtures("config_flow_fixture")
async def test_get_segments_not_supported(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test vacuum/get_segments with entity not supporting CLEAN_AREA."""
class MockVacuumNoCleanArea(MockEntity, StateVacuumEntity):
_attr_supported_features = VacuumEntityFeature.STATE | VacuumEntityFeature.START
_attr_activity = VacuumActivity.DOCKED
entity = MockVacuumNoCleanArea(name="Testing", entity_id="vacuum.testing")
config_entry = MockConfigEntry(domain="test")
config_entry.add_to_hass(hass)
mock_integration(
hass,
MockModule(
"test",
async_setup_entry=help_async_setup_entry_init,
async_unload_entry=help_async_unload_entry,
),
)
setup_test_component_platform(hass, DOMAIN, [entity], from_config_entry=True)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
client = await hass_ws_client(hass)
await client.send_json_auto_id(
{"type": "vacuum/get_segments", "entity_id": entity.entity_id}
)
msg = await client.receive_json()
assert not msg["success"]
assert msg["error"]["code"] == ERR_NOT_SUPPORTED
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/vacuum/test_websocket.py",
"license": "Apache License 2.0",
"lines": 106,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/proxmoxve/coordinator.py | """Data Update Coordinator for Proxmox VE integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass, field
from datetime import timedelta
import logging
from typing import Any
from proxmoxer import AuthenticationError, ProxmoxAPI
from proxmoxer.core import ResourceException
import requests
from requests.exceptions import ConnectTimeout, SSLError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONF_HOST,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
CONF_VERIFY_SSL,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryError,
ConfigEntryNotReady,
)
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONF_NODE, CONF_REALM, DEFAULT_VERIFY_SSL, DOMAIN
type ProxmoxConfigEntry = ConfigEntry[ProxmoxCoordinator]
DEFAULT_UPDATE_INTERVAL = timedelta(seconds=60)
_LOGGER = logging.getLogger(__name__)
@dataclass(slots=True, kw_only=True)
class ProxmoxNodeData:
"""All resources for a single Proxmox node."""
node: dict[str, str] = field(default_factory=dict)
vms: dict[int, dict[str, Any]] = field(default_factory=dict)
containers: dict[int, dict[str, Any]] = field(default_factory=dict)
class ProxmoxCoordinator(DataUpdateCoordinator[dict[str, ProxmoxNodeData]]):
"""Data Update Coordinator for Proxmox VE integration."""
config_entry: ProxmoxConfigEntry
def __init__(
self,
hass: HomeAssistant,
config_entry: ProxmoxConfigEntry,
) -> None:
"""Initialize the Proxmox VE coordinator."""
super().__init__(
hass,
_LOGGER,
config_entry=config_entry,
name=DOMAIN,
update_interval=DEFAULT_UPDATE_INTERVAL,
)
self.proxmox: ProxmoxAPI
self.known_nodes: set[str] = set()
self.known_vms: set[tuple[str, int]] = set()
self.known_containers: set[tuple[str, int]] = set()
self.new_nodes_callbacks: list[Callable[[list[ProxmoxNodeData]], None]] = []
self.new_vms_callbacks: list[
Callable[[list[tuple[ProxmoxNodeData, dict[str, Any]]]], None]
] = []
self.new_containers_callbacks: list[
Callable[[list[tuple[ProxmoxNodeData, dict[str, Any]]]], None]
] = []
async def _async_setup(self) -> None:
"""Set up the coordinator."""
try:
await self.hass.async_add_executor_job(self._init_proxmox)
except AuthenticationError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="invalid_auth",
translation_placeholders={"error": repr(err)},
) from err
except SSLError as err:
raise ConfigEntryError(
translation_domain=DOMAIN,
translation_key="ssl_error",
translation_placeholders={"error": repr(err)},
) from err
except ConnectTimeout as err:
raise ConfigEntryNotReady(
translation_domain=DOMAIN,
translation_key="timeout_connect",
translation_placeholders={"error": repr(err)},
) from err
except ResourceException as err:
raise ConfigEntryError(
translation_domain=DOMAIN,
translation_key="no_nodes_found",
translation_placeholders={"error": repr(err)},
) from err
except requests.exceptions.ConnectionError as err:
raise ConfigEntryError(
translation_domain=DOMAIN,
translation_key="cannot_connect",
translation_placeholders={"error": repr(err)},
) from err
async def _async_update_data(self) -> dict[str, ProxmoxNodeData]:
"""Fetch data from Proxmox VE API."""
try:
nodes, vms_containers = await self.hass.async_add_executor_job(
self._fetch_all_nodes
)
except AuthenticationError as err:
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="invalid_auth",
translation_placeholders={"error": repr(err)},
) from err
except SSLError as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="ssl_error",
translation_placeholders={"error": repr(err)},
) from err
except ConnectTimeout as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="timeout_connect",
translation_placeholders={"error": repr(err)},
) from err
except ResourceException as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="no_nodes_found",
translation_placeholders={"error": repr(err)},
) from err
except requests.exceptions.ConnectionError as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="cannot_connect",
translation_placeholders={"error": repr(err)},
) from err
data: dict[str, ProxmoxNodeData] = {}
for node, (vms, containers) in zip(nodes, vms_containers, strict=True):
data[node[CONF_NODE]] = ProxmoxNodeData(
node=node,
vms={int(vm["vmid"]): vm for vm in vms},
containers={
int(container["vmid"]): container for container in containers
},
)
self._async_add_remove_nodes(data)
return data
def _init_proxmox(self) -> None:
"""Initialize ProxmoxAPI instance."""
user_id = (
self.config_entry.data[CONF_USERNAME]
if "@" in self.config_entry.data[CONF_USERNAME]
else f"{self.config_entry.data[CONF_USERNAME]}@{self.config_entry.data[CONF_REALM]}"
)
self.proxmox = ProxmoxAPI(
host=self.config_entry.data[CONF_HOST],
port=self.config_entry.data[CONF_PORT],
user=user_id,
password=self.config_entry.data[CONF_PASSWORD],
verify_ssl=self.config_entry.data.get(CONF_VERIFY_SSL, DEFAULT_VERIFY_SSL),
)
self.proxmox.nodes.get()
def _fetch_all_nodes(
self,
) -> tuple[
list[dict[str, Any]], list[tuple[list[dict[str, Any]], list[dict[str, Any]]]]
]:
"""Fetch all nodes, and then proceed to the VMs and containers."""
nodes = self.proxmox.nodes.get() or []
vms_containers = [self._get_vms_containers(node) for node in nodes]
return nodes, vms_containers
def _get_vms_containers(
self,
node: dict[str, Any],
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Get vms and containers for a node."""
vms = self.proxmox.nodes(node[CONF_NODE]).qemu.get()
containers = self.proxmox.nodes(node[CONF_NODE]).lxc.get()
assert vms is not None and containers is not None
return vms, containers
def _async_add_remove_nodes(self, data: dict[str, ProxmoxNodeData]) -> None:
"""Add new nodes/VMs/containers, track removals."""
current_nodes = set(data.keys())
new_nodes = current_nodes - self.known_nodes
if new_nodes:
_LOGGER.debug("New nodes found: %s", new_nodes)
self.known_nodes.update(new_nodes)
# And yes, track new VM's and containers as well
current_vms = {
(node_name, vmid)
for node_name, node_data in data.items()
for vmid in node_data.vms
}
new_vms = current_vms - self.known_vms
if new_vms:
_LOGGER.debug("New VMs found: %s", new_vms)
self.known_vms.update(new_vms)
current_containers = {
(node_name, vmid)
for node_name, node_data in data.items()
for vmid in node_data.containers
}
new_containers = current_containers - self.known_containers
if new_containers:
_LOGGER.debug("New containers found: %s", new_containers)
self.known_containers.update(new_containers)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/proxmoxve/coordinator.py",
"license": "Apache License 2.0",
"lines": 203,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.