sample_id stringlengths 21 196 | text stringlengths 105 936k | metadata dict | category stringclasses 6
values |
|---|---|---|---|
home-assistant/core:homeassistant/components/yardian/binary_sensor.py | """Binary sensors for Yardian integration."""
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from homeassistant.components.binary_sensor import (
BinarySensorDeviceClass,
BinarySensorEntity,
BinarySensorEntityDescription,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import YardianUpdateCoordinator
@dataclass(kw_only=True, frozen=True)
class YardianBinarySensorEntityDescription(BinarySensorEntityDescription):
"""Entity description for Yardian binary sensors."""
value_fn: Callable[[YardianUpdateCoordinator], bool | None]
def _zone_enabled_value(
coordinator: YardianUpdateCoordinator, zone_id: int
) -> bool | None:
"""Return True if zone is enabled on controller."""
try:
return coordinator.data.zones[zone_id].is_enabled
except IndexError:
return None
def _zone_value_factory(
zone_id: int,
) -> Callable[[YardianUpdateCoordinator], bool | None]:
"""Return a callable evaluating whether a zone is enabled."""
def value(coordinator: YardianUpdateCoordinator) -> bool | None:
return _zone_enabled_value(coordinator, zone_id)
return value
SENSOR_DESCRIPTIONS: tuple[YardianBinarySensorEntityDescription, ...] = (
YardianBinarySensorEntityDescription(
key="watering_running",
translation_key="watering_running",
device_class=BinarySensorDeviceClass.RUNNING,
value_fn=lambda coordinator: bool(coordinator.data.active_zones),
),
YardianBinarySensorEntityDescription(
key="standby",
translation_key="standby",
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda coordinator: bool(
coordinator.data.oper_info.get("iStandby", 0)
),
),
YardianBinarySensorEntityDescription(
key="freeze_prevent",
translation_key="freeze_prevent",
device_class=BinarySensorDeviceClass.PROBLEM,
entity_category=EntityCategory.DIAGNOSTIC,
value_fn=lambda coordinator: bool(
coordinator.data.oper_info.get("fFreezePrevent", 0)
),
),
)
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Yardian binary sensors."""
coordinator: YardianUpdateCoordinator = hass.data[DOMAIN][config_entry.entry_id]
entities: list[BinarySensorEntity] = [
YardianBinarySensor(coordinator, description)
for description in SENSOR_DESCRIPTIONS
]
zone_descriptions = [
YardianBinarySensorEntityDescription(
key=f"zone_enabled_{zone_id}",
translation_key="zone_enabled",
entity_category=EntityCategory.DIAGNOSTIC,
entity_registry_enabled_default=False,
value_fn=_zone_value_factory(zone_id),
translation_placeholders={"zone": str(zone_id + 1)},
)
for zone_id in range(len(coordinator.data.zones))
]
entities.extend(
YardianBinarySensor(coordinator, description)
for description in zone_descriptions
)
async_add_entities(entities)
class YardianBinarySensor(
CoordinatorEntity[YardianUpdateCoordinator], BinarySensorEntity
):
"""Representation of a Yardian binary sensor based on a description."""
entity_description: YardianBinarySensorEntityDescription
_attr_has_entity_name = True
def __init__(
self,
coordinator: YardianUpdateCoordinator,
description: YardianBinarySensorEntityDescription,
) -> None:
"""Initialize the Yardian binary sensor."""
super().__init__(coordinator)
self.entity_description = description
self._attr_unique_id = f"{coordinator.yid}-{description.key}"
self._attr_device_info = coordinator.device_info
@property
def is_on(self) -> bool | None:
"""Return the current state based on the description's value function."""
return self.entity_description.value_fn(self.coordinator)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/yardian/binary_sensor.py",
"license": "Apache License 2.0",
"lines": 107,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/zeroconf/repairs.py | """Repairs for the zeroconf integration."""
from __future__ import annotations
from homeassistant import data_entry_flow
from homeassistant.components.homeassistant import (
DOMAIN as HOMEASSISTANT_DOMAIN,
SERVICE_HOMEASSISTANT_RESTART,
)
from homeassistant.components.repairs import RepairsFlow
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import instance_id, issue_registry as ir
class DuplicateInstanceIDRepairFlow(RepairsFlow):
"""Handler for duplicate instance ID repair."""
@callback
def _async_get_placeholders(self) -> dict[str, str]:
issue_registry = ir.async_get(self.hass)
issue = issue_registry.async_get_issue(self.handler, self.issue_id)
assert issue is not None
return issue.translation_placeholders or {}
async def async_step_init(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the initial step."""
return await self.async_step_confirm_recreate()
async def async_step_confirm_recreate(
self, user_input: dict[str, str] | None = None
) -> data_entry_flow.FlowResult:
"""Handle the confirm step."""
if user_input is not None:
await instance_id.async_recreate(self.hass)
await self.hass.services.async_call(
HOMEASSISTANT_DOMAIN, SERVICE_HOMEASSISTANT_RESTART
)
return self.async_create_entry(title="", data={})
return self.async_show_form(
step_id="confirm_recreate",
description_placeholders=self._async_get_placeholders(),
)
async def async_create_fix_flow(
hass: HomeAssistant,
issue_id: str,
data: dict[str, str | int | float | None] | None,
) -> RepairsFlow:
"""Create flow."""
if issue_id == "duplicate_instance_id":
return DuplicateInstanceIDRepairFlow()
# If Zeroconf adds confirm-only repairs in the future, this should be changed
# to return a ConfirmRepairFlow instead of raising a ValueError
raise ValueError(f"unknown repair {issue_id}")
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/zeroconf/repairs.py",
"license": "Apache License 2.0",
"lines": 48,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/util/async_iterator.py | """Async iterator utilities."""
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator
from concurrent.futures import CancelledError, Future
from typing import Self
class Abort(Exception):
"""Raised when abort is requested."""
class AsyncIteratorReader:
"""Allow reading from an AsyncIterator using blocking I/O.
The class implements a blocking read method reading from the async iterator,
and a close method.
In addition, the abort method can be used to abort any ongoing read operation.
"""
def __init__(
self,
loop: asyncio.AbstractEventLoop,
stream: AsyncIterator[bytes],
) -> None:
"""Initialize the wrapper."""
self._aborted = False
self._exhausted = False
self._loop = loop
self._stream = stream
self._buffer: bytes | None = None
self._next_future: Future[bytes | None] | None = None
self._pos: int = 0
async def _next(self) -> bytes | None:
"""Get the next chunk from the iterator."""
return await anext(self._stream, None)
def abort(self) -> None:
"""Abort the reader."""
self._aborted = True
if self._next_future is not None:
self._next_future.cancel()
def read(self, n: int = -1, /) -> bytes:
"""Read up to n bytes of data from the iterator.
The read method returns 0 bytes when the iterator is exhausted.
"""
result = bytearray()
while n < 0 or len(result) < n:
if self._exhausted:
break
if not self._buffer:
self._next_future = asyncio.run_coroutine_threadsafe(
self._next(), self._loop
)
if self._aborted:
self._next_future.cancel()
raise Abort
try:
self._buffer = self._next_future.result()
except CancelledError as err:
raise Abort from err
self._pos = 0
if not self._buffer:
# The stream is exhausted
self._exhausted = True
break
chunk = self._buffer[self._pos : self._pos + n]
result.extend(chunk)
n -= len(chunk)
self._pos += len(chunk)
if self._pos == len(self._buffer):
self._buffer = None
return bytes(result)
def close(self) -> None:
"""Close the iterator."""
class AsyncIteratorWriter:
"""Allow writing to an AsyncIterator using blocking I/O.
The class implements a blocking write method writing to the async iterator,
as well as a close and tell methods.
In addition, the abort method can be used to abort any ongoing write operation.
"""
def __init__(self, loop: asyncio.AbstractEventLoop) -> None:
"""Initialize the wrapper."""
self._aborted = False
self._loop = loop
self._pos: int = 0
self._queue: asyncio.Queue[bytes | None] = asyncio.Queue(maxsize=1)
self._write_future: Future[bytes | None] | None = None
def __aiter__(self) -> Self:
"""Return the iterator."""
return self
async def __anext__(self) -> bytes:
"""Get the next chunk from the iterator."""
if data := await self._queue.get():
return data
raise StopAsyncIteration
def abort(self) -> None:
"""Abort the writer."""
self._aborted = True
if self._write_future is not None:
self._write_future.cancel()
def tell(self) -> int:
"""Return the current position in the iterator."""
return self._pos
def write(self, s: bytes, /) -> int:
"""Write data to the iterator.
To signal the end of the stream, write a zero-length bytes object.
"""
self._write_future = asyncio.run_coroutine_threadsafe(
self._queue.put(s), self._loop
)
if self._aborted:
self._write_future.cancel()
raise Abort
try:
self._write_future.result()
except CancelledError as err:
raise Abort from err
self._pos += len(s)
return len(s)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/util/async_iterator.py",
"license": "Apache License 2.0",
"lines": 113,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:tests/components/actron_air/test_config_flow.py | """Config flow tests for the Actron Air Integration."""
import asyncio
from unittest.mock import AsyncMock
from actron_neo_api import ActronAirAuthError
from homeassistant import config_entries
from homeassistant.components.actron_air.const import DOMAIN
from homeassistant.const import CONF_API_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_user_flow_oauth2_success(
hass: HomeAssistant, mock_actron_api: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test successful OAuth2 device code flow."""
# Start the config flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Should start with a progress step
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "user"
assert result["progress_action"] == "wait_for_authorization"
assert result["description_placeholders"] is not None
assert "user_code" in result["description_placeholders"]
assert result["description_placeholders"]["user_code"] == "ABC123"
# Wait for the progress to complete
await hass.async_block_till_done()
# Continue the flow after progress is done - this should complete the entire flow
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# Should create entry on successful token exchange
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test@example.com"
assert result["data"] == {
CONF_API_TOKEN: "test_refresh_token",
}
assert result["result"].unique_id == "test_user_id"
async def test_user_flow_oauth2_pending(hass: HomeAssistant, mock_actron_api) -> None:
"""Test OAuth2 flow when authorization is still pending."""
# Make poll_for_token hang indefinitely to simulate pending state
async def hang_forever(device_code):
await asyncio.Event().wait() # This will never complete
mock_actron_api.poll_for_token = hang_forever
# Start the config flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Should start with a progress step since the task will never complete
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "user"
assert result["progress_action"] == "wait_for_authorization"
assert result["description_placeholders"] is not None
assert "user_code" in result["description_placeholders"]
assert result["description_placeholders"]["user_code"] == "ABC123"
# The background task should be running but not completed
# In a real scenario, the user would wait for authorization on their device
async def test_user_flow_oauth2_error(hass: HomeAssistant, mock_actron_api) -> None:
"""Test OAuth2 flow with authentication error during device code request."""
# Override the default mock to raise an error
mock_actron_api.request_device_code = AsyncMock(
side_effect=ActronAirAuthError("OAuth2 error")
)
# Start the flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Should abort with oauth2_error
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "oauth2_error"
async def test_user_flow_token_polling_error(
hass: HomeAssistant, mock_actron_api, mock_setup_entry: AsyncMock
) -> None:
"""Test OAuth2 flow with error during token polling."""
# Override the default mock to raise an error during token polling
mock_actron_api.poll_for_token = AsyncMock(
side_effect=ActronAirAuthError("Token polling error")
)
# Start the config flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Since the error occurs immediately, the task completes and we get progress_done
assert result["type"] is FlowResultType.SHOW_PROGRESS_DONE
assert result["step_id"] == "connection_error"
# Continue to the connection_error step
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# Should show the connection error form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "connection_error"
# Now fix the mock to allow successful token polling for recovery
async def successful_poll_for_token(device_code):
await asyncio.sleep(0.1) # Small delay to allow progress state
return {
"access_token": "test_access_token",
"refresh_token": "test_refresh_token",
}
mock_actron_api.poll_for_token = successful_poll_for_token
# User clicks retry button - this should restart the flow and succeed
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
# Should start progress again
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "user"
assert result["progress_action"] == "wait_for_authorization"
# Wait for the progress to complete
await hass.async_block_till_done()
# Continue the flow after progress is done - this should complete successfully
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# Should create entry on successful recovery
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test@example.com"
assert result["data"] == {
CONF_API_TOKEN: "test_refresh_token",
}
assert result["result"].unique_id == "test_user_id"
async def test_user_flow_duplicate_account(
hass: HomeAssistant, mock_actron_api: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test duplicate account handling - should abort when same account is already configured."""
# Create an existing config entry for the same user account
mock_config_entry.add_to_hass(hass)
# Start the config flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
# Should start with a progress step
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "user"
assert result["progress_action"] == "wait_for_authorization"
assert result["description_placeholders"] is not None
assert "user_code" in result["description_placeholders"]
assert result["description_placeholders"]["user_code"] == "ABC123"
# Wait for the progress to complete
await hass.async_block_till_done()
# Continue the flow after progress is done
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# Should abort because the account is already configured
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_reauth_flow_success(
hass: HomeAssistant,
mock_actron_api: AsyncMock,
mock_config_entry: MockConfigEntry,
mock_setup_entry: AsyncMock,
) -> None:
"""Test successful reauthentication flow."""
# Create an existing config entry
mock_config_entry.add_to_hass(hass)
existing_entry = mock_config_entry
# Start the reauth flow
result = await mock_config_entry.start_reauth_flow(hass)
# Should show the reauth confirmation form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
# Submit the confirmation form to start the OAuth flow
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
# Should start with a progress step
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "user"
assert result["progress_action"] == "wait_for_authorization"
# Wait for the progress to complete
await hass.async_block_till_done()
# Continue the flow after progress is done
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# Should update the existing entry with new token
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert existing_entry.data[CONF_API_TOKEN] == "test_refresh_token"
async def test_reauth_flow_wrong_account(
hass: HomeAssistant, mock_actron_api: AsyncMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test reauthentication flow with wrong account."""
# Create an existing config entry
mock_config_entry.add_to_hass(hass)
# Mock the API to return a different user ID
mock_actron_api.get_user_info = AsyncMock(
return_value={"id": "different_user_id", "email": "different@example.com"}
)
# Start the reauth flow
result = await mock_config_entry.start_reauth_flow(hass)
# Should show the reauth confirmation form
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
# Submit the confirmation form
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
# Should start with a progress step
assert result["type"] is FlowResultType.SHOW_PROGRESS
assert result["step_id"] == "user"
assert result["progress_action"] == "wait_for_authorization"
# Wait for the progress to complete
await hass.async_block_till_done()
# Continue the flow after progress is done
result = await hass.config_entries.flow.async_configure(result["flow_id"])
# Should abort because of wrong account
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "wrong_account"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/actron_air/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 194,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/control4/test_climate.py | """Test Control4 Climate."""
from typing import Any
from unittest.mock import MagicMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.climate import (
ATTR_FAN_MODE,
ATTR_HVAC_MODE,
ATTR_TARGET_TEMP_HIGH,
ATTR_TARGET_TEMP_LOW,
ATTR_TEMPERATURE,
DOMAIN as CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
SERVICE_SET_HVAC_MODE,
SERVICE_SET_TEMPERATURE,
ClimateEntityFeature,
HVACAction,
HVACMode,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
ENTITY_ID = "climate.test_controller_residential_thermostat_v2"
def _make_climate_data(
hvac_state: str = "off",
hvac_mode: str = "Heat",
temperature: float = 72.0,
humidity: int = 50,
cool_setpoint: float = 75.0,
heat_setpoint: float = 68.0,
scale: str = "FAHRENHEIT",
) -> dict[int, dict[str, Any]]:
"""Build mock climate variable data for item ID 123 (Fahrenheit)."""
return {
123: {
"HVAC_STATE": hvac_state,
"HVAC_MODE": hvac_mode,
"TEMPERATURE_F": temperature,
"HUMIDITY": humidity,
"COOL_SETPOINT_F": cool_setpoint,
"HEAT_SETPOINT_F": heat_setpoint,
"SCALE": scale,
}
}
@pytest.fixture
def platforms() -> list[Platform]:
"""Platforms which should be loaded during the test."""
return [Platform.CLIMATE]
@pytest.fixture
async def init_integration(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> MockConfigEntry:
"""Set up the Control4 integration for testing."""
hass.config.units = US_CUSTOMARY_SYSTEM
await setup_integration(hass, mock_config_entry)
return mock_config_entry
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_climate_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test climate entities are set up correctly with proper attributes."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("mock_climate_variables", "expected_action"),
[
pytest.param(
_make_climate_data(hvac_state="Off", hvac_mode="Off"),
HVACAction.OFF,
id="off",
),
pytest.param(
_make_climate_data(hvac_state="Heat"),
HVACAction.HEATING,
id="heat",
),
pytest.param(
_make_climate_data(hvac_state="Cool", hvac_mode="Cool"),
HVACAction.COOLING,
id="cool",
),
pytest.param(
_make_climate_data(hvac_state="Dry"),
HVACAction.DRYING,
id="dry",
),
pytest.param(
_make_climate_data(hvac_state="Fan"),
HVACAction.FAN,
id="fan",
),
pytest.param(
_make_climate_data(hvac_state="Idle"),
HVACAction.IDLE,
id="idle",
),
pytest.param(
_make_climate_data(hvac_state="Stage 1 Heat"),
HVACAction.HEATING,
id="stage_1_heat",
),
pytest.param(
_make_climate_data(hvac_state="Stage 2 Cool", hvac_mode="Cool"),
HVACAction.COOLING,
id="stage_2_cool",
),
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_hvac_action_mapping(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
expected_action: HVACAction,
) -> None:
"""Test all 5 official Control4 HVAC states map to correct HA actions."""
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes["hvac_action"] == expected_action
@pytest.mark.parametrize(
(
"mock_climate_variables",
"expected_hvac_mode",
"expected_hvac_action",
"expected_temperature",
"expected_temp_high",
"expected_temp_low",
),
[
pytest.param(
_make_climate_data(hvac_state="Off", hvac_mode="Off"),
HVACMode.OFF,
HVACAction.OFF,
None,
None,
None,
id="off",
),
pytest.param(
_make_climate_data(
hvac_state="Cool",
hvac_mode="Cool",
temperature=74.0,
humidity=55,
cool_setpoint=72.0,
),
HVACMode.COOL,
HVACAction.COOLING,
72.0,
None,
None,
id="cool",
),
pytest.param(
_make_climate_data(
hvac_state="Heat",
hvac_mode="Auto",
temperature=65.0,
humidity=40,
),
HVACMode.HEAT_COOL,
HVACAction.HEATING,
None,
75.0,
68.0,
id="auto",
),
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_climate_states(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
expected_hvac_mode: HVACMode,
expected_hvac_action: HVACAction,
expected_temperature: float | None,
expected_temp_high: float | None,
expected_temp_low: float | None,
) -> None:
"""Test climate entity in different states."""
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == expected_hvac_mode
assert state.attributes["hvac_action"] == expected_hvac_action
assert state.attributes.get("temperature") == expected_temperature
assert state.attributes.get("target_temp_high") == expected_temp_high
assert state.attributes.get("target_temp_low") == expected_temp_low
@pytest.mark.parametrize(
("hvac_mode", "expected_c4_mode"),
[
pytest.param(HVACMode.COOL, "Cool", id="cool"),
pytest.param(HVACMode.OFF, "Off", id="off"),
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_set_hvac_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_c4_climate: MagicMock,
hvac_mode: HVACMode,
expected_c4_mode: str,
) -> None:
"""Test setting HVAC mode."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_HVAC_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_HVAC_MODE: hvac_mode},
blocking=True,
)
mock_c4_climate.setHvacMode.assert_called_once_with(expected_c4_mode)
@pytest.mark.parametrize(
("mock_climate_variables", "method_name"),
[
pytest.param(
_make_climate_data(
hvac_state="Off",
temperature=72.5,
humidity=45,
),
"setHeatSetpointF",
id="heat",
),
pytest.param(
_make_climate_data(
hvac_state="Cool",
hvac_mode="Cool",
temperature=74.0,
cool_setpoint=72.0,
),
"setCoolSetpointF",
id="cool",
),
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_set_temperature(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_c4_climate: MagicMock,
method_name: str,
) -> None:
"""Test setting temperature in different modes."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_TEMPERATURE: 70.0},
blocking=True,
)
getattr(mock_c4_climate, method_name).assert_called_once_with(70.0)
@pytest.mark.parametrize(
"mock_climate_variables",
[
_make_climate_data(hvac_state="Off", hvac_mode="Auto"),
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_set_temperature_range_auto_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_c4_climate: MagicMock,
) -> None:
"""Test setting temperature range in auto mode."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{
ATTR_ENTITY_ID: ENTITY_ID,
ATTR_TARGET_TEMP_LOW: 65.0,
ATTR_TARGET_TEMP_HIGH: 78.0,
},
blocking=True,
)
mock_c4_climate.setHeatSetpointF.assert_called_once_with(65.0)
mock_c4_climate.setCoolSetpointF.assert_called_once_with(78.0)
@pytest.mark.parametrize("mock_climate_variables", [{}])
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_climate_not_created_when_no_initial_data(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test climate entity is not created when coordinator has no initial data."""
# Entity should not be created if there's no data during initial setup
state = hass.states.get(ENTITY_ID)
assert state is None
@pytest.mark.parametrize(
"mock_climate_variables",
[
{
123: {
"HVAC_STATE": "Off",
"HVAC_MODE": "Heat",
# Missing TEMPERATURE_F and HUMIDITY
"COOL_SETPOINT_F": 75.0,
"HEAT_SETPOINT_F": 68.0,
"SCALE": "FAHRENHEIT",
}
}
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_climate_missing_variables(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test climate entity handles missing variables gracefully."""
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == HVACMode.HEAT
assert state.attributes.get("current_temperature") is None
assert state.attributes.get("current_humidity") is None
assert state.attributes["temperature"] == 68.0
@pytest.mark.parametrize(
"mock_climate_variables",
[
_make_climate_data(hvac_state="off", hvac_mode="UnknownMode"),
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_climate_unknown_hvac_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test climate entity handles unknown HVAC mode."""
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == HVACMode.OFF # Defaults to OFF for unknown modes
@pytest.mark.parametrize(
"mock_climate_variables",
[
_make_climate_data(hvac_state="unknown_state"),
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_climate_unknown_hvac_state(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test climate entity handles unknown HVAC state."""
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get("hvac_action") is None
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_set_fan_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_c4_climate: MagicMock,
) -> None:
"""Test setting fan mode."""
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_FAN_MODE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_FAN_MODE: "on"},
blocking=True,
)
# Verify the Control4 API is called with the C4 format ("On" not "on")
mock_c4_climate.setFanMode.assert_called_once_with("On")
@pytest.mark.parametrize(
"mock_climate_variables",
[
{
123: {
"HVAC_STATE": "idle",
"HVAC_MODE": "Heat",
"TEMPERATURE_F": 72.0,
"HUMIDITY": 50,
"COOL_SETPOINT_F": 75.0,
"HEAT_SETPOINT_F": 68.0,
"SCALE": "FAHRENHEIT",
# No FAN_MODE or FAN_MODES_LIST
}
}
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_fan_mode_not_supported(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test fan mode feature not set when device doesn't support it."""
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.attributes.get("fan_mode") is None
assert state.attributes.get("fan_modes") is None
assert not (
state.attributes.get("supported_features") & ClimateEntityFeature.FAN_MODE
)
# Temperature unit tests - verify correct API methods are called based on SCALE
@pytest.mark.parametrize(
("mock_climate_variables", "expected_method", "unexpected_method"),
[
pytest.param(
_make_climate_data(hvac_state="Off", hvac_mode="Heat"),
"setHeatSetpointF",
"setHeatSetpointC",
id="fahrenheit_heat_calls_F_not_C",
),
pytest.param(
_make_climate_data(hvac_state="Cool", hvac_mode="Cool"),
"setCoolSetpointF",
"setCoolSetpointC",
id="fahrenheit_cool_calls_F_not_C",
),
],
)
@pytest.mark.usefixtures(
"mock_c4_account",
"mock_c4_director",
"mock_climate_update_variables",
"init_integration",
)
async def test_set_temperature_calls_correct_api(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_c4_climate: MagicMock,
expected_method: str,
unexpected_method: str,
) -> None:
"""Test setting temperature calls correct API method based on SCALE.
Verifies that when setting temperature:
- The correct method for the scale is called
- The wrong scale's method is NOT called
"""
# Reset mock to clear any calls from previous parametrized test runs
mock_c4_climate.reset_mock()
await hass.services.async_call(
CLIMATE_DOMAIN,
SERVICE_SET_TEMPERATURE,
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_TEMPERATURE: 70.0},
blocking=True,
)
getattr(mock_c4_climate, expected_method).assert_called_once_with(70.0)
getattr(mock_c4_climate, unexpected_method).assert_not_called()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/control4/test_climate.py",
"license": "Apache License 2.0",
"lines": 496,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/control4/test_media_player.py | """Test Control4 Media Player."""
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platforms() -> list[Platform]:
"""Platforms which should be loaded during the test."""
return [Platform.MEDIA_PLAYER]
@pytest.mark.usefixtures("mock_c4_account", "mock_c4_director", "mock_update_variables")
async def test_media_player_with_and_without_sources(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test that rooms with sources create entities and rooms without are skipped."""
# The default mock_c4_director fixture provides multi-room data:
# Room 1 has video source, Room 2 has no sources (thermostat-only room)
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/control4/test_media_player.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/elevenlabs/test_stt.py | """Tests for the ElevenLabs STT integration."""
from unittest.mock import AsyncMock
from elevenlabs.core import ApiError
import pytest
from homeassistant.components import stt
from homeassistant.components.elevenlabs.const import (
CONF_MODEL,
CONF_STT_AUTO_LANGUAGE,
CONF_VOICE,
)
from homeassistant.core import HomeAssistant
# === Fixtures ===
@pytest.fixture
def default_metadata() -> stt.SpeechMetadata:
"""Return default metadata for valid PCM WAV input."""
return stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.WAV,
codec=stt.AudioCodecs.PCM,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
bit_rate=stt.AudioBitRates.BITRATE_16,
)
# === Stream Fixtures ===
@pytest.fixture
def two_chunk_stream():
"""Return a stream that yields two chunks of audio."""
async def _stream():
yield b"chunk1"
yield b"chunk2"
return _stream
@pytest.fixture
def simple_stream():
"""Return a basic stream yielding one audio chunk."""
async def _stream():
yield b"data"
return _stream
@pytest.fixture
def empty_stream():
"""Return an empty stream."""
async def _stream():
return
yield # This makes it an async generator
return _stream
# === Metadata Fixtures for Edge Cases ===
@pytest.fixture
def unsupported_language_metadata() -> stt.SpeechMetadata:
"""Return metadata with unsupported language code."""
return stt.SpeechMetadata(
language="xx-XX",
format=stt.AudioFormats.WAV,
codec=stt.AudioCodecs.PCM,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
bit_rate=stt.AudioBitRates.BITRATE_16,
)
@pytest.fixture
def incompatible_pcm_metadata() -> stt.SpeechMetadata:
"""Return metadata that is PCM but not raw-compatible (e.g., stereo)."""
return stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.WAV,
codec=stt.AudioCodecs.PCM,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_STEREO,
bit_rate=stt.AudioBitRates.BITRATE_16,
)
@pytest.fixture
def opus_metadata() -> stt.SpeechMetadata:
"""Return valid metadata using OPUS codec."""
return stt.SpeechMetadata(
language="en-US",
format=stt.AudioFormats.OGG,
codec=stt.AudioCodecs.OPUS,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
bit_rate=stt.AudioBitRates.BITRATE_16,
)
# === SUCCESS TESTS ===
async def test_stt_transcription_success(
hass: HomeAssistant,
setup: AsyncMock,
default_metadata: stt.SpeechMetadata,
two_chunk_stream,
) -> None:
"""Test successful transcription with valid PCM/WAV input."""
entity = stt.async_get_speech_to_text_engine(hass, "stt.elevenlabs_speech_to_text")
assert entity is not None
result = await entity.async_process_audio_stream(
default_metadata, two_chunk_stream()
)
assert result.result == stt.SpeechResultState.SUCCESS
assert result.text == "hello world"
entity._client.speech_to_text.convert.assert_called_once()
@pytest.mark.parametrize(
"config_options",
[
{
CONF_VOICE: "voice1",
CONF_MODEL: "model1",
CONF_STT_AUTO_LANGUAGE: True,
}
],
)
async def test_stt_transcription_success_auto_language(
hass: HomeAssistant,
setup: AsyncMock,
simple_stream,
) -> None:
"""Test successful transcription when auto language detection is enabled."""
metadata = stt.SpeechMetadata(
language="na",
format=stt.AudioFormats.WAV,
codec=stt.AudioCodecs.PCM,
sample_rate=stt.AudioSampleRates.SAMPLERATE_16000,
channel=stt.AudioChannels.CHANNEL_MONO,
bit_rate=stt.AudioBitRates.BITRATE_16,
)
entity = stt.async_get_speech_to_text_engine(hass, "stt.elevenlabs_speech_to_text")
assert entity is not None
result = await entity.async_process_audio_stream(metadata, simple_stream())
assert result.result == stt.SpeechResultState.SUCCESS
assert result.text == "hello world"
entity._client.speech_to_text.convert.assert_called_once()
# Verify language_code is NOT passed when auto-detect is enabled
call_kwargs = entity._client.speech_to_text.convert.call_args.kwargs
assert "language_code" not in call_kwargs
async def test_stt_transcription_passes_language_code(
hass: HomeAssistant,
setup: AsyncMock,
default_metadata: stt.SpeechMetadata,
simple_stream,
) -> None:
"""Test that language_code is passed when auto-detect is disabled."""
entity = stt.async_get_speech_to_text_engine(hass, "stt.elevenlabs_speech_to_text")
assert entity is not None
assert not entity._auto_detect_language
result = await entity.async_process_audio_stream(default_metadata, simple_stream())
assert result.result == stt.SpeechResultState.SUCCESS
# Verify language_code IS passed when auto-detect is disabled
call_kwargs = entity._client.speech_to_text.convert.call_args.kwargs
assert call_kwargs["language_code"] == "en"
# === ERROR CASES (PARAMETRIZED) ===
@pytest.mark.parametrize(
("metadata_fixture", "stream_fixture"),
[
("unsupported_language_metadata", "simple_stream"),
("incompatible_pcm_metadata", "simple_stream"),
("opus_metadata", "empty_stream"),
],
)
async def test_stt_edge_cases(
hass: HomeAssistant,
setup: AsyncMock,
request: pytest.FixtureRequest,
metadata_fixture: str,
stream_fixture: str,
) -> None:
"""Test various error scenarios like unsupported language or bad format."""
entity = stt.async_get_speech_to_text_engine(hass, "stt.elevenlabs_speech_to_text")
assert entity is not None
metadata = request.getfixturevalue(metadata_fixture)
stream = request.getfixturevalue(stream_fixture)
assert not entity._auto_detect_language
result = await entity.async_process_audio_stream(metadata, stream())
assert result.result == stt.SpeechResultState.ERROR
assert result.text is None
async def test_stt_convert_api_error(
hass: HomeAssistant,
setup: AsyncMock,
default_metadata: stt.SpeechMetadata,
simple_stream,
) -> None:
"""Test that API errors during convert are handled properly."""
entity = stt.async_get_speech_to_text_engine(hass, "stt.elevenlabs_speech_to_text")
assert entity is not None
entity._client.speech_to_text.convert.side_effect = ApiError()
result = await entity.async_process_audio_stream(default_metadata, simple_stream())
assert result.result == stt.SpeechResultState.ERROR
assert result.text is None
# === SUPPORTED PROPERTIES ===
async def test_supported_properties(
hass: HomeAssistant,
setup: AsyncMock,
) -> None:
"""Test the advertised capabilities of the ElevenLabs STT entity."""
entity = stt.async_get_speech_to_text_engine(hass, "stt.elevenlabs_speech_to_text")
assert entity is not None
assert set(entity.supported_formats) == {stt.AudioFormats.WAV, stt.AudioFormats.OGG}
assert set(entity.supported_codecs) == {stt.AudioCodecs.PCM, stt.AudioCodecs.OPUS}
assert set(entity.supported_bit_rates) == {stt.AudioBitRates.BITRATE_16}
assert set(entity.supported_sample_rates) == {stt.AudioSampleRates.SAMPLERATE_16000}
assert set(entity.supported_channels) == {
stt.AudioChannels.CHANNEL_MONO,
stt.AudioChannels.CHANNEL_STEREO,
}
assert "en-US" in entity.supported_languages
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/elevenlabs/test_stt.py",
"license": "Apache License 2.0",
"lines": 197,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/fing/test_config_flow.py | """Tests for Fing config flow."""
import httpx
import pytest
from homeassistant.components.fing.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_IP_ADDRESS, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import AsyncMock
from tests.conftest import MockConfigEntry
async def test_verify_connection_success(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mocked_fing_agent: AsyncMock,
) -> None:
"""Test successful connection verification."""
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_IP_ADDRESS: "192.168.1.1",
CONF_PORT: "49090",
CONF_API_KEY: "test_key",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == dict(mock_config_entry.data)
entry = result["result"]
assert entry.unique_id == "0000000000XX"
assert entry.domain == DOMAIN
@pytest.mark.parametrize("api_type", ["old"])
async def test_verify_api_version_outdated(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mocked_fing_agent: AsyncMock,
) -> None:
"""Test connection verification failure."""
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_IP_ADDRESS: "192.168.1.1",
CONF_PORT: "49090",
CONF_API_KEY: "test_key",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "api_version_error"
@pytest.mark.parametrize(
("exception", "error"),
[
(httpx.NetworkError("Network error"), "cannot_connect"),
(httpx.TimeoutException("Timeout error"), "timeout_connect"),
(
httpx.HTTPStatusError(
"HTTP status error - 500", request=None, response=httpx.Response(500)
),
"http_status_error",
),
(
httpx.HTTPStatusError(
"HTTP status error - 401", request=None, response=httpx.Response(401)
),
"invalid_api_key",
),
(httpx.HTTPError("HTTP error"), "unknown"),
(httpx.InvalidURL("Invalid URL"), "url_error"),
(httpx.CookieConflict("Cookie conflict"), "unknown"),
(httpx.StreamError("Stream error"), "unknown"),
],
)
async def test_http_error_handling(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mocked_fing_agent: AsyncMock,
error: str,
exception: Exception,
) -> None:
"""Test handling of HTTP-related errors during connection verification."""
mocked_fing_agent.get_devices.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_IP_ADDRESS: "192.168.1.1",
CONF_PORT: "49090",
CONF_API_KEY: "test_key",
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == error
# Simulate a successful connection after the error
mocked_fing_agent.get_devices.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_IP_ADDRESS: "192.168.1.1",
CONF_PORT: "49090",
CONF_API_KEY: "test_key",
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == dict(mock_config_entry.data)
async def test_duplicate_entries(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mocked_fing_agent: AsyncMock,
) -> None:
"""Test detecting 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"],
user_input={
CONF_IP_ADDRESS: "192.168.1.1",
CONF_PORT: "49090",
CONF_API_KEY: "test_key",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/fing/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 131,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/fing/test_device_tracker.py | """Test Fing Agent device tracker entity."""
from datetime import timedelta
from fing_agent_api.models import DeviceResponse
from freezegun.api import FrozenDateTimeFactory
from homeassistant.components.fing.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import init_integration
from tests.common import (
AsyncMock,
async_fire_time_changed,
async_load_json_object_fixture,
snapshot_platform,
)
from tests.conftest import MockConfigEntry, SnapshotAssertion
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
mocked_fing_agent: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities created by Fing with snapshot."""
entry = await init_integration(hass, mock_config_entry, mocked_fing_agent)
await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
async def test_new_device_found(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mocked_fing_agent: AsyncMock,
entity_registry: er.EntityRegistry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test Fing device tracker setup."""
delta_time = timedelta(seconds=35) # 30 seconds + 5 delta seconds
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
entry = await init_integration(hass, mock_config_entry, mocked_fing_agent)
# First check -> there are 3 devices in total
assert len(er.async_entries_for_config_entry(entity_registry, entry.entry_id)) == 3
mocked_fing_agent.get_devices.return_value = DeviceResponse(
await async_load_json_object_fixture(
hass, "device_resp_device_added.json", DOMAIN
)
)
freezer.tick(delta_time)
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Second check -> added one device
assert len(er.async_entries_for_config_entry(entity_registry, entry.entry_id)) == 4
mocked_fing_agent.get_devices.return_value = DeviceResponse(
await async_load_json_object_fixture(
hass, "device_resp_device_deleted.json", DOMAIN
)
)
freezer.tick(delta_time)
async_fire_time_changed(hass)
await hass.async_block_till_done()
# Third check -> removed two devices (old devices)
assert len(er.async_entries_for_config_entry(entity_registry, entry.entry_id)) == 2
async def test_device_modified(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mocked_fing_agent: AsyncMock,
entity_registry: er.EntityRegistry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test Fing device modified."""
delta_time = timedelta(seconds=35) # 30 seconds + 5 delta seconds
# ----------------------------------------------------
await hass.config.async_set_time_zone("UTC")
freezer.move_to("2021-01-09 12:00:00+00:00")
entry = await init_integration(hass, mock_config_entry, mocked_fing_agent)
old_entries = er.async_entries_for_config_entry(entity_registry, entry.entry_id)
# ----------------------------------------------------
mocked_fing_agent.get_devices.return_value = DeviceResponse(
await async_load_json_object_fixture(
hass, "device_resp_device_modified.json", DOMAIN
)
)
freezer.tick(delta_time)
async_fire_time_changed(hass)
await hass.async_block_till_done()
new_entries = er.async_entries_for_config_entry(entity_registry, entry.entry_id)
# ----------------------------------------------------
assert len(old_entries) == len(new_entries)
old_entries_by_ids = {e.unique_id: e for e in old_entries}
new_entries_by_ids = {e.unique_id: e for e in new_entries}
unique_id = "0000000000XX-00:00:00:00:00:03"
old_entry = old_entries_by_ids[unique_id]
new_entry = new_entries_by_ids[unique_id]
assert old_entry.original_name != new_entry.original_name
assert old_entry.original_icon != new_entry.original_icon
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/fing/test_device_tracker.py",
"license": "Apache License 2.0",
"lines": 92,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/fing/test_init.py | """Test the Fing integration init."""
import pytest
from homeassistant.components.fing.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import init_integration
from tests.common import AsyncMock
from tests.conftest import MockConfigEntry
@pytest.mark.parametrize("api_type", ["new", "old"])
async def test_setup_entry_new_api(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mocked_fing_agent: AsyncMock,
api_type: str,
) -> None:
"""Test setup Fing Agent /w New API."""
entry = await init_integration(hass, mock_config_entry, mocked_fing_agent)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
if api_type == "new":
assert entry.state is ConfigEntryState.LOADED
elif api_type == "old":
assert entry.state is ConfigEntryState.SETUP_ERROR
@pytest.mark.parametrize("api_type", ["new"])
async def test_unload_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mocked_fing_agent: AsyncMock,
) -> None:
"""Test unload of entry."""
entry = await init_integration(hass, mock_config_entry, mocked_fing_agent)
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
assert entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.NOT_LOADED
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/fing/test_init.py",
"license": "Apache License 2.0",
"lines": 35,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/firefly_iii/test_config_flow.py | """Test the Firefly III config flow."""
from unittest.mock import AsyncMock, MagicMock
from pyfirefly.exceptions import (
FireflyAuthenticationError,
FireflyConnectionError,
FireflyTimeoutError,
)
import pytest
from homeassistant.components.firefly_iii.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import MOCK_TEST_CONFIG
from tests.common import MockConfigEntry
MOCK_USER_SETUP = {
CONF_URL: "https://127.0.0.1:8080/",
CONF_API_KEY: "test_api_key",
CONF_VERIFY_SSL: True,
}
USER_INPUT_RECONFIGURE = {
CONF_URL: "https://new_domain:9000/",
CONF_API_KEY: "new_api_key",
CONF_VERIFY_SSL: True,
}
async def test_form_and_flow(
hass: HomeAssistant,
mock_firefly_client: MagicMock,
mock_setup_entry: MagicMock,
) -> None:
"""Test we get the form and can complete the 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=MOCK_USER_SETUP,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "https://127.0.0.1:8080/"
assert result["data"] == MOCK_TEST_CONFIG
@pytest.mark.parametrize(
("exception", "reason"),
[
(
FireflyAuthenticationError,
"invalid_auth",
),
(
FireflyConnectionError,
"cannot_connect",
),
(
FireflyTimeoutError,
"timeout_connect",
),
(
Exception("Some other error"),
"unknown",
),
],
)
async def test_form_exceptions(
hass: HomeAssistant,
mock_firefly_client: AsyncMock,
mock_setup_entry: MagicMock,
exception: Exception,
reason: str,
) -> None:
"""Test we handle all exceptions."""
mock_firefly_client.get_about.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_SETUP,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
mock_firefly_client.get_about.side_effect = None
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_SETUP,
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "https://127.0.0.1:8080/"
assert result["data"] == MOCK_TEST_CONFIG
async def test_duplicate_entry(
hass: HomeAssistant,
mock_firefly_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test we handle duplicate entries."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_USER_SETUP,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_full_flow_reauth(
hass: HomeAssistant,
mock_firefly_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full flow of the config flow."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
# There is no user input
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_API_KEY: "new_api_key"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == "new_api_key"
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("exception", "reason"),
[
(
FireflyAuthenticationError,
"invalid_auth",
),
(
FireflyConnectionError,
"cannot_connect",
),
(
FireflyTimeoutError,
"timeout_connect",
),
(
Exception("Some other error"),
"unknown",
),
],
)
async def test_reauth_flow_exceptions(
hass: HomeAssistant,
mock_firefly_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test we handle all exceptions in the reauth flow."""
mock_config_entry.add_to_hass(hass)
mock_firefly_client.get_about.side_effect = exception
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_API_KEY: "new_api_key"},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
# Now test that we can recover from the error
mock_firefly_client.get_about.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_API_KEY: "new_api_key"},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_API_KEY] == "new_api_key"
assert len(mock_setup_entry.mock_calls) == 1
async def test_full_flow_reconfigure(
hass: HomeAssistant,
mock_firefly_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full flow of the config flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=USER_INPUT_RECONFIGURE,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_API_KEY] == "new_api_key"
assert mock_config_entry.data[CONF_URL] == "https://new_domain:9000/"
assert mock_config_entry.data[CONF_VERIFY_SSL] is True
assert len(mock_setup_entry.mock_calls) == 1
async def test_full_flow_reconfigure_unique_id(
hass: HomeAssistant,
mock_firefly_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full flow of the config flow, this time with a known unique ID."""
mock_config_entry.add_to_hass(hass)
duplicate_entry = MockConfigEntry(
domain="firefly_iii",
data={
CONF_URL: "https://duplicate-url/",
CONF_API_KEY: "other_key",
CONF_VERIFY_SSL: True,
},
unique_id="very-annoying-duplicate",
)
duplicate_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_URL: "https://duplicate-url/",
CONF_API_KEY: "new_key",
CONF_VERIFY_SSL: True,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("exception", "reason"),
[
(
FireflyAuthenticationError,
"invalid_auth",
),
(
FireflyConnectionError,
"cannot_connect",
),
(
FireflyTimeoutError,
"timeout_connect",
),
(
Exception("Some other error"),
"unknown",
),
],
)
async def test_full_flow_reconfigure_exceptions(
hass: HomeAssistant,
mock_firefly_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test the full flow of the config flow, this time with exceptions."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
mock_firefly_client.get_about.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=USER_INPUT_RECONFIGURE,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
mock_firefly_client.get_about.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=USER_INPUT_RECONFIGURE,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_API_KEY] == "new_api_key"
assert mock_config_entry.data[CONF_URL] == "https://new_domain:9000/"
assert mock_config_entry.data[CONF_VERIFY_SSL] is True
assert len(mock_setup_entry.mock_calls) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/firefly_iii/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 298,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/firefly_iii/test_diagnostics.py | """Test the Firefly III component diagnostics."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_get_config_entry_diagnostics(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_firefly_client: AsyncMock,
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/firefly_iii/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:tests/components/firefly_iii/test_init.py | """Tests for the Firefly III integration."""
from unittest.mock import AsyncMock
from pyfirefly.exceptions import (
FireflyAuthenticationError,
FireflyConnectionError,
FireflyTimeoutError,
)
import pytest
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
("exception", "expected_state"),
[
(FireflyAuthenticationError("bad creds"), ConfigEntryState.SETUP_ERROR),
(FireflyConnectionError("cannot connect"), ConfigEntryState.SETUP_RETRY),
(FireflyTimeoutError("timeout"), ConfigEntryState.SETUP_RETRY),
],
)
async def test_setup_exceptions(
hass: HomeAssistant,
mock_firefly_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
expected_state: ConfigEntryState,
) -> None:
"""Test the _async_setup."""
mock_firefly_client.get_about.side_effect = exception
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state == expected_state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/firefly_iii/test_init.py",
"license": "Apache License 2.0",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/firefly_iii/test_sensor.py | """Tests for the Firefly III sensor platform."""
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from pyfirefly.exceptions import (
FireflyAuthenticationError,
FireflyConnectionError,
FireflyTimeoutError,
)
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.firefly_iii.coordinator import DEFAULT_SCAN_INTERVAL
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import dt as dt_util
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_firefly_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.firefly_iii._PLATFORMS",
[Platform.SENSOR],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry.entry_id
)
@pytest.mark.parametrize(
("exception"),
[
FireflyAuthenticationError("bad creds"),
FireflyConnectionError("cannot connect"),
FireflyTimeoutError("timeout"),
],
)
async def test_refresh_exceptions(
hass: HomeAssistant,
mock_firefly_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test entities go unavailable after coordinator refresh failures."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
mock_firefly_client.get_accounts.side_effect = exception
freezer.tick(DEFAULT_SCAN_INTERVAL)
async_fire_time_changed(hass, dt_util.utcnow())
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("sensor.credit_card_account_balance")
assert state is not None
assert state.state == STATE_UNAVAILABLE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/firefly_iii/test_sensor.py",
"license": "Apache License 2.0",
"lines": 59,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/group/test_valve.py | """The tests for the group valve platform."""
import asyncio
from datetime import timedelta
from typing import Any
from unittest.mock import patch
import pytest
from homeassistant.components.group.valve import DEFAULT_NAME
from homeassistant.components.valve import (
ATTR_CURRENT_POSITION,
ATTR_POSITION,
DOMAIN as VALVE_DOMAIN,
ValveState,
)
from homeassistant.const import (
ATTR_ASSUMED_STATE,
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
ATTR_SUPPORTED_FEATURES,
CONF_ENTITIES,
CONF_UNIQUE_ID,
SERVICE_CLOSE_VALVE,
SERVICE_OPEN_VALVE,
SERVICE_SET_VALVE_POSITION,
SERVICE_STOP_VALVE,
SERVICE_TOGGLE,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.common import assert_setup_component, async_fire_time_changed
VALVE_GROUP = "valve.valve_group"
DEMO_VALVE1 = "valve.front_garden"
DEMO_VALVE2 = "valve.orchard"
DEMO_VALVE_POS1 = "valve.back_garden"
DEMO_VALVE_POS2 = "valve.trees"
CONFIG_ALL = {
VALVE_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
CONF_ENTITIES: [DEMO_VALVE1, DEMO_VALVE2, DEMO_VALVE_POS1, DEMO_VALVE_POS2],
},
]
}
CONFIG_POS = {
VALVE_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
CONF_ENTITIES: [DEMO_VALVE_POS1, DEMO_VALVE_POS2],
},
]
}
CONFIG_ATTRIBUTES = {
VALVE_DOMAIN: {
"platform": "group",
CONF_ENTITIES: [DEMO_VALVE1, DEMO_VALVE2, DEMO_VALVE_POS1, DEMO_VALVE_POS2],
CONF_UNIQUE_ID: "unique_identifier",
}
}
@pytest.fixture(scope="module", autouse=True)
def patch_demo_open_close_delay():
"""Patch demo valve open/close delay."""
with patch("homeassistant.components.demo.valve.OPEN_CLOSE_DELAY", 0):
yield
@pytest.fixture
async def setup_comp(
hass: HomeAssistant, config_count: tuple[dict[str, Any], int]
) -> None:
"""Set up group valve component."""
config, count = config_count
with assert_setup_component(count, VALVE_DOMAIN):
await async_setup_component(hass, VALVE_DOMAIN, config)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
@pytest.mark.parametrize("config_count", [(CONFIG_ATTRIBUTES, 1)])
@pytest.mark.usefixtures("setup_comp")
async def test_state(hass: HomeAssistant) -> None:
"""Test handling of state.
The group state is unknown if all group members are unknown or unavailable.
Otherwise, the group state is opening if at least one group member is opening.
Otherwise, the group state is closing if at least one group member is closing.
Otherwise, the group state is open if at least one group member is open.
Otherwise, the group state is closed.
"""
state = hass.states.get(VALVE_GROUP)
# No entity has a valid state -> group state unavailable
assert state.state == STATE_UNAVAILABLE
assert state.attributes[ATTR_FRIENDLY_NAME] == DEFAULT_NAME
assert ATTR_ENTITY_ID not in state.attributes
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
assert ATTR_CURRENT_POSITION not in state.attributes
# Test group members exposed as attribute
hass.states.async_set(DEMO_VALVE1, STATE_UNKNOWN, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.attributes[ATTR_ENTITY_ID] == [
DEMO_VALVE1,
DEMO_VALVE2,
DEMO_VALVE_POS1,
DEMO_VALVE_POS2,
]
# The group state is unavailable if all group members are unavailable.
hass.states.async_set(DEMO_VALVE1, STATE_UNAVAILABLE, {})
hass.states.async_set(DEMO_VALVE_POS1, STATE_UNAVAILABLE, {})
hass.states.async_set(DEMO_VALVE_POS2, STATE_UNAVAILABLE, {})
hass.states.async_set(DEMO_VALVE2, STATE_UNAVAILABLE, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == STATE_UNAVAILABLE
# The group state is unknown if all group members are unknown or unavailable.
for state_1 in (STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_2 in (STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_3 in (STATE_UNAVAILABLE, STATE_UNKNOWN):
hass.states.async_set(DEMO_VALVE1, state_1, {})
hass.states.async_set(DEMO_VALVE_POS1, state_2, {})
hass.states.async_set(DEMO_VALVE_POS2, state_3, {})
hass.states.async_set(DEMO_VALVE2, STATE_UNKNOWN, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == STATE_UNKNOWN
# At least one member opening -> group opening
for state_1 in (
ValveState.CLOSED,
ValveState.CLOSING,
ValveState.OPEN,
ValveState.OPENING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_2 in (
ValveState.CLOSED,
ValveState.CLOSING,
ValveState.OPEN,
ValveState.OPENING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_3 in (
ValveState.CLOSED,
ValveState.CLOSING,
ValveState.OPEN,
ValveState.OPENING,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
hass.states.async_set(DEMO_VALVE1, state_1, {})
hass.states.async_set(DEMO_VALVE_POS1, state_2, {})
hass.states.async_set(DEMO_VALVE_POS2, state_3, {})
hass.states.async_set(DEMO_VALVE2, ValveState.OPENING, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPENING
# At least one member closing -> group closing
for state_1 in (
ValveState.CLOSED,
ValveState.CLOSING,
ValveState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_2 in (
ValveState.CLOSED,
ValveState.CLOSING,
ValveState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_3 in (
ValveState.CLOSED,
ValveState.CLOSING,
ValveState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
hass.states.async_set(DEMO_VALVE1, state_1, {})
hass.states.async_set(DEMO_VALVE_POS1, state_2, {})
hass.states.async_set(DEMO_VALVE_POS2, state_3, {})
hass.states.async_set(DEMO_VALVE2, ValveState.CLOSING, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.CLOSING
# At least one member open -> group open
for state_1 in (
ValveState.CLOSED,
ValveState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_2 in (
ValveState.CLOSED,
ValveState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
for state_3 in (
ValveState.CLOSED,
ValveState.OPEN,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
):
hass.states.async_set(DEMO_VALVE1, state_1, {})
hass.states.async_set(DEMO_VALVE_POS1, state_2, {})
hass.states.async_set(DEMO_VALVE_POS2, state_3, {})
hass.states.async_set(DEMO_VALVE2, ValveState.OPEN, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPEN
# At least one member closed -> group closed
for state_1 in (ValveState.CLOSED, STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_2 in (ValveState.CLOSED, STATE_UNAVAILABLE, STATE_UNKNOWN):
for state_3 in (ValveState.CLOSED, STATE_UNAVAILABLE, STATE_UNKNOWN):
hass.states.async_set(DEMO_VALVE1, state_1, {})
hass.states.async_set(DEMO_VALVE_POS1, state_2, {})
hass.states.async_set(DEMO_VALVE_POS2, state_3, {})
hass.states.async_set(DEMO_VALVE2, ValveState.CLOSED, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.CLOSED
# All group members removed from the state machine -> unavailable
hass.states.async_remove(DEMO_VALVE1)
hass.states.async_remove(DEMO_VALVE_POS1)
hass.states.async_remove(DEMO_VALVE_POS2)
hass.states.async_remove(DEMO_VALVE2)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == STATE_UNAVAILABLE
@pytest.mark.parametrize("config_count", [(CONFIG_ATTRIBUTES, 1)])
@pytest.mark.usefixtures("setup_comp")
async def test_attributes(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test handling of state attributes."""
state = hass.states.get(VALVE_GROUP)
assert state.state == STATE_UNAVAILABLE
assert state.attributes[ATTR_FRIENDLY_NAME] == DEFAULT_NAME
assert ATTR_ENTITY_ID not in state.attributes
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 0
assert ATTR_CURRENT_POSITION not in state.attributes
# Set entity as closed
hass.states.async_set(DEMO_VALVE1, ValveState.CLOSED, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.CLOSED
assert state.attributes[ATTR_ENTITY_ID] == [
DEMO_VALVE1,
DEMO_VALVE2,
DEMO_VALVE_POS1,
DEMO_VALVE_POS2,
]
# Set entity as opening
hass.states.async_set(DEMO_VALVE1, ValveState.OPENING, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPENING
# Set entity as closing
hass.states.async_set(DEMO_VALVE1, ValveState.CLOSING, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.CLOSING
# Set entity as unknown again
hass.states.async_set(DEMO_VALVE1, STATE_UNKNOWN, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == STATE_UNKNOWN
# Add Entity that supports open / close / stop
hass.states.async_set(DEMO_VALVE1, ValveState.OPEN, {ATTR_SUPPORTED_FEATURES: 11})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 11
assert ATTR_CURRENT_POSITION not in state.attributes
# Add Entity that supports set_valve_position
hass.states.async_set(
DEMO_VALVE_POS1,
ValveState.OPEN,
{ATTR_SUPPORTED_FEATURES: 4, ATTR_CURRENT_POSITION: 70},
)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 15
assert state.attributes[ATTR_CURRENT_POSITION] == 70
### Test state when group members have different states ###
# Valves
hass.states.async_remove(DEMO_VALVE_POS1)
hass.states.async_remove(DEMO_VALVE_POS2)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPEN
assert ATTR_ASSUMED_STATE not in state.attributes
assert state.attributes[ATTR_SUPPORTED_FEATURES] == 11
assert ATTR_CURRENT_POSITION not in state.attributes
# Test entity registry integration
entry = entity_registry.async_get(VALVE_GROUP)
assert entry
assert entry.unique_id == "unique_identifier"
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_open_valves(hass: HomeAssistant) -> None:
"""Test open valve function."""
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_OPEN_VALVE, {ATTR_ENTITY_ID: VALVE_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPEN
assert state.attributes[ATTR_CURRENT_POSITION] == 100
assert hass.states.get(DEMO_VALVE1).state == ValveState.OPEN
assert hass.states.get(DEMO_VALVE_POS1).attributes[ATTR_CURRENT_POSITION] == 100
assert hass.states.get(DEMO_VALVE_POS2).attributes[ATTR_CURRENT_POSITION] == 100
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_close_valves(hass: HomeAssistant) -> None:
"""Test close valve function."""
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_CLOSE_VALVE, {ATTR_ENTITY_ID: VALVE_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.CLOSED
assert state.attributes[ATTR_CURRENT_POSITION] == 0
assert hass.states.get(DEMO_VALVE1).state == ValveState.CLOSED
assert hass.states.get(DEMO_VALVE_POS1).attributes[ATTR_CURRENT_POSITION] == 0
assert hass.states.get(DEMO_VALVE_POS2).attributes[ATTR_CURRENT_POSITION] == 0
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_toggle_valves(hass: HomeAssistant) -> None:
"""Test toggle valve function."""
# Start valves in open state
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_OPEN_VALVE, {ATTR_ENTITY_ID: VALVE_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPEN
# Toggle will close valves
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: VALVE_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.CLOSED
assert state.attributes[ATTR_CURRENT_POSITION] == 0
assert hass.states.get(DEMO_VALVE1).state == ValveState.CLOSED
assert hass.states.get(DEMO_VALVE_POS1).attributes[ATTR_CURRENT_POSITION] == 0
assert hass.states.get(DEMO_VALVE_POS2).attributes[ATTR_CURRENT_POSITION] == 0
# Toggle again will open valves
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: VALVE_GROUP}, blocking=True
)
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPEN
assert state.attributes[ATTR_CURRENT_POSITION] == 100
assert hass.states.get(DEMO_VALVE1).state == ValveState.OPEN
assert hass.states.get(DEMO_VALVE_POS1).attributes[ATTR_CURRENT_POSITION] == 100
assert hass.states.get(DEMO_VALVE_POS2).attributes[ATTR_CURRENT_POSITION] == 100
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_stop_valves(hass: HomeAssistant) -> None:
"""Test stop valve function."""
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_OPEN_VALVE, {ATTR_ENTITY_ID: VALVE_GROUP}, blocking=True
)
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPENING
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_STOP_VALVE, {ATTR_ENTITY_ID: VALVE_GROUP}, blocking=True
)
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPEN
assert state.attributes[ATTR_CURRENT_POSITION] == 60 # (40 + 80) / 2
assert hass.states.get(DEMO_VALVE1).state == ValveState.OPEN
assert hass.states.get(DEMO_VALVE_POS1).attributes[ATTR_CURRENT_POSITION] == 80
assert hass.states.get(DEMO_VALVE_POS2).attributes[ATTR_CURRENT_POSITION] == 40
@pytest.mark.parametrize("config_count", [(CONFIG_ALL, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_set_valve_position(hass: HomeAssistant) -> None:
"""Test set valve position function."""
await hass.services.async_call(
VALVE_DOMAIN,
SERVICE_SET_VALVE_POSITION,
{ATTR_ENTITY_ID: VALVE_GROUP, ATTR_POSITION: 50},
blocking=True,
)
for _ in range(4):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.state == ValveState.OPEN
assert state.attributes[ATTR_CURRENT_POSITION] == 50
assert hass.states.get(DEMO_VALVE1).state == ValveState.OPEN
assert hass.states.get(DEMO_VALVE_POS1).attributes[ATTR_CURRENT_POSITION] == 50
assert hass.states.get(DEMO_VALVE_POS2).attributes[ATTR_CURRENT_POSITION] == 50
@pytest.mark.parametrize("config_count", [(CONFIG_POS, 2)])
@pytest.mark.usefixtures("setup_comp")
async def test_is_opening_closing(hass: HomeAssistant) -> None:
"""Test is_opening property."""
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_OPEN_VALVE, {ATTR_ENTITY_ID: VALVE_GROUP}, blocking=True
)
await hass.async_block_till_done()
# Both valves opening -> opening
assert hass.states.get(DEMO_VALVE_POS1).state == ValveState.OPENING
assert hass.states.get(DEMO_VALVE_POS2).state == ValveState.OPENING
assert hass.states.get(VALVE_GROUP).state == ValveState.OPENING
for _ in range(10):
future = dt_util.utcnow() + timedelta(seconds=1)
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
await hass.services.async_call(
VALVE_DOMAIN, SERVICE_CLOSE_VALVE, {ATTR_ENTITY_ID: VALVE_GROUP}, blocking=True
)
# Both valves closing -> closing
assert hass.states.get(DEMO_VALVE_POS1).state == ValveState.CLOSING
assert hass.states.get(DEMO_VALVE_POS2).state == ValveState.CLOSING
assert hass.states.get(VALVE_GROUP).state == ValveState.CLOSING
hass.states.async_set(
DEMO_VALVE_POS1, ValveState.OPENING, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
# Closing + Opening -> Opening
assert hass.states.get(DEMO_VALVE_POS2).state == ValveState.CLOSING
assert hass.states.get(DEMO_VALVE_POS1).state == ValveState.OPENING
assert hass.states.get(VALVE_GROUP).state == ValveState.OPENING
hass.states.async_set(
DEMO_VALVE_POS1, ValveState.CLOSING, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
# Both valves closing -> closing
assert hass.states.get(DEMO_VALVE_POS2).state == ValveState.CLOSING
assert hass.states.get(DEMO_VALVE_POS1).state == ValveState.CLOSING
assert hass.states.get(VALVE_GROUP).state == ValveState.CLOSING
# Closed + Closing -> Closing
hass.states.async_set(
DEMO_VALVE_POS1, ValveState.CLOSED, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
assert hass.states.get(DEMO_VALVE_POS2).state == ValveState.CLOSING
assert hass.states.get(DEMO_VALVE_POS1).state == ValveState.CLOSED
assert hass.states.get(VALVE_GROUP).state == ValveState.CLOSING
# Open + Closing -> Closing
hass.states.async_set(
DEMO_VALVE_POS1, ValveState.OPEN, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
assert hass.states.get(DEMO_VALVE_POS2).state == ValveState.CLOSING
assert hass.states.get(DEMO_VALVE_POS1).state == ValveState.OPEN
assert hass.states.get(VALVE_GROUP).state == ValveState.CLOSING
# Closed + Opening -> Closing
hass.states.async_set(
DEMO_VALVE_POS2, ValveState.OPENING, {ATTR_SUPPORTED_FEATURES: 11}
)
hass.states.async_set(
DEMO_VALVE_POS1, ValveState.CLOSED, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
assert hass.states.get(DEMO_VALVE_POS2).state == ValveState.OPENING
assert hass.states.get(DEMO_VALVE_POS1).state == ValveState.CLOSED
assert hass.states.get(VALVE_GROUP).state == ValveState.OPENING
# Open + Opening -> Closing
hass.states.async_set(
DEMO_VALVE_POS1, ValveState.OPEN, {ATTR_SUPPORTED_FEATURES: 11}
)
await hass.async_block_till_done()
assert hass.states.get(DEMO_VALVE_POS2).state == ValveState.OPENING
assert hass.states.get(DEMO_VALVE_POS1).state == ValveState.OPEN
assert hass.states.get(VALVE_GROUP).state == ValveState.OPENING
@pytest.mark.parametrize("config_count", [(CONFIG_ATTRIBUTES, 1)])
@pytest.mark.usefixtures("setup_comp")
async def test_assumed_state(hass: HomeAssistant) -> None:
"""Test assumed_state attribute behavior."""
# No members with assumed_state -> group doesn't have assumed_state in attributes
hass.states.async_set(DEMO_VALVE1, ValveState.OPEN, {})
hass.states.async_set(DEMO_VALVE_POS1, ValveState.OPEN, {})
hass.states.async_set(DEMO_VALVE_POS2, ValveState.CLOSED, {})
hass.states.async_set(DEMO_VALVE2, ValveState.CLOSED, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert ATTR_ASSUMED_STATE not in state.attributes
# One member with assumed_state=True -> group has assumed_state=True
hass.states.async_set(DEMO_VALVE1, ValveState.OPEN, {ATTR_ASSUMED_STATE: True})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.attributes.get(ATTR_ASSUMED_STATE) is True
# Multiple members with assumed_state=True -> group has assumed_state=True
hass.states.async_set(
DEMO_VALVE_POS2, ValveState.CLOSED, {ATTR_ASSUMED_STATE: True}
)
hass.states.async_set(DEMO_VALVE2, ValveState.CLOSED, {ATTR_ASSUMED_STATE: True})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.attributes.get(ATTR_ASSUMED_STATE) is True
# Unavailable member with assumed_state=True -> group has assumed_state=True
hass.states.async_set(DEMO_VALVE1, ValveState.OPEN, {})
hass.states.async_set(DEMO_VALVE_POS2, ValveState.CLOSED, {})
hass.states.async_set(DEMO_VALVE2, STATE_UNAVAILABLE, {ATTR_ASSUMED_STATE: True})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.attributes.get(ATTR_ASSUMED_STATE) is True
# Unknown member with assumed_state=True -> group has assumed_state=True
hass.states.async_set(DEMO_VALVE2, STATE_UNKNOWN, {ATTR_ASSUMED_STATE: True})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert state.attributes.get(ATTR_ASSUMED_STATE) is True
# All members without assumed_state -> group doesn't have assumed_state in attributes
hass.states.async_set(DEMO_VALVE2, ValveState.CLOSED, {})
await hass.async_block_till_done()
state = hass.states.get(VALVE_GROUP)
assert ATTR_ASSUMED_STATE not in state.attributes
async def test_nested_group(hass: HomeAssistant) -> None:
"""Test nested valve group."""
await async_setup_component(
hass,
VALVE_DOMAIN,
{
VALVE_DOMAIN: [
{"platform": "demo"},
{
"platform": "group",
"entities": ["valve.bedroom_group"],
"name": "Nested Group",
},
{
"platform": "group",
CONF_ENTITIES: [DEMO_VALVE_POS1, DEMO_VALVE_POS2],
"name": "Bedroom Group",
},
]
},
)
await hass.async_block_till_done()
await hass.async_start()
await hass.async_block_till_done()
state = hass.states.get("valve.bedroom_group")
assert state is not None
assert state.state == ValveState.OPEN
assert state.attributes.get(ATTR_ENTITY_ID) == [DEMO_VALVE_POS1, DEMO_VALVE_POS2]
state = hass.states.get("valve.nested_group")
assert state is not None
assert state.state == ValveState.OPEN
assert state.attributes.get(ATTR_ENTITY_ID) == ["valve.bedroom_group"]
# Test controlling the nested group
async with asyncio.timeout(0.5):
await hass.services.async_call(
VALVE_DOMAIN,
SERVICE_CLOSE_VALVE,
{ATTR_ENTITY_ID: "valve.nested_group"},
blocking=True,
)
assert hass.states.get(DEMO_VALVE_POS1).state == ValveState.CLOSING
assert hass.states.get(DEMO_VALVE_POS2).state == ValveState.CLOSING
assert hass.states.get("valve.bedroom_group").state == ValveState.CLOSING
assert hass.states.get("valve.nested_group").state == ValveState.CLOSING
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/group/test_valve.py",
"license": "Apache License 2.0",
"lines": 585,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/growatt_server/test_init.py | """Tests for the Growatt Server integration."""
from datetime import timedelta
import json
from freezegun.api import FrozenDateTimeFactory
import growattServer
import pytest
import requests
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.growatt_server import async_migrate_entry
from homeassistant.components.growatt_server.const import (
AUTH_API_TOKEN,
AUTH_PASSWORD,
CACHED_API_KEY,
CONF_AUTH_TYPE,
CONF_PLANT_ID,
DEFAULT_PLANT_ID,
DOMAIN,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
CONF_NAME,
CONF_PASSWORD,
CONF_TOKEN,
CONF_URL,
CONF_USERNAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from . import setup_integration
from tests.common import MockConfigEntry, async_fire_time_changed
@pytest.mark.usefixtures("init_integration")
async def test_load_unload_config_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test loading and unloading the integration."""
assert mock_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.usefixtures("init_integration")
async def test_device_info(
snapshot: SnapshotAssertion,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test device registry integration."""
device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "MIN123456")})
assert device_entry is not None
assert device_entry == snapshot
@pytest.mark.parametrize(
("exception", "expected_state"),
[
(growattServer.GrowattV1ApiError("API Error"), ConfigEntryState.SETUP_ERROR),
(
json.decoder.JSONDecodeError("Invalid JSON", "", 0),
ConfigEntryState.SETUP_ERROR,
),
],
)
async def test_setup_error_on_api_failure(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
exception: Exception,
expected_state: ConfigEntryState,
) -> None:
"""Test setup error on API failures during device list."""
mock_growatt_v1_api.device_list.side_effect = exception
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is expected_state
@pytest.mark.usefixtures("init_integration")
async def test_coordinator_update_failed(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test coordinator handles update failures gracefully."""
# Integration should be loaded
assert mock_config_entry.state is ConfigEntryState.LOADED
# Cause coordinator update to fail
mock_growatt_v1_api.min_detail.side_effect = growattServer.GrowattV1ApiError(
"Connection timeout"
)
# Trigger coordinator refresh
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Integration should remain loaded despite coordinator error
assert mock_config_entry.state is ConfigEntryState.LOADED
async def test_classic_api_setup(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_growatt_classic_api,
mock_config_entry_classic: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test integration setup with Classic API (password auth)."""
# Classic API doesn't support MIN devices - use TLX device instead
mock_growatt_classic_api.device_list.return_value = [
{"deviceSn": "TLX123456", "deviceType": "tlx"}
]
await setup_integration(hass, mock_config_entry_classic)
assert mock_config_entry_classic.state is ConfigEntryState.LOADED
# Verify Classic API login was called
mock_growatt_classic_api.login.assert_called()
# Verify device was created
device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "TLX123456")})
assert device_entry is not None
assert device_entry == snapshot
@pytest.mark.parametrize(
("config_data", "expected_auth_type"),
[
(
{
CONF_TOKEN: "test_token_123",
CONF_URL: "https://openapi.growatt.com/",
"plant_id": "plant_123",
},
AUTH_API_TOKEN,
),
(
{
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
CONF_URL: "https://server.growatt.com/",
"plant_id": "plant_456",
},
AUTH_PASSWORD,
),
],
)
async def test_migrate_config_without_auth_type(
hass: HomeAssistant,
config_data: dict[str, str],
expected_auth_type: str,
) -> None:
"""Test migration adds auth_type field to legacy configs and bumps version.
This test verifies that config entries created before auth_type was introduced
are properly migrated by:
- Adding CONF_AUTH_TYPE with the correct value (AUTH_API_TOKEN or AUTH_PASSWORD)
- Bumping version from 1.0 to 1.1
"""
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data=config_data,
unique_id=config_data["plant_id"],
version=1,
minor_version=0,
)
mock_config_entry.add_to_hass(hass)
# Execute migration
migration_result = await async_migrate_entry(hass, mock_config_entry)
assert migration_result is True
# Verify version was updated to 1.1
assert mock_config_entry.version == 1
assert mock_config_entry.minor_version == 1
# Verify auth_type field was added during migration
assert mock_config_entry.data[CONF_AUTH_TYPE] == expected_auth_type
async def test_migrate_legacy_config_no_auth_fields(
hass: HomeAssistant,
) -> None:
"""Test migration succeeds but setup fails for config without auth fields."""
# Create a config entry without any auth fields
invalid_config = {
CONF_URL: "https://openapi.growatt.com/",
"plant_id": "plant_789",
}
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data=invalid_config,
unique_id="plant_789",
version=1,
minor_version=0,
)
mock_config_entry.add_to_hass(hass)
# Migration should succeed (only updates version)
migration_result = await async_migrate_entry(hass, mock_config_entry)
assert migration_result is True
# Verify version was updated
assert mock_config_entry.version == 1
assert mock_config_entry.minor_version == 1
# Note: Setup will fail later due to missing auth fields in async_setup_entry
@pytest.mark.parametrize(
"exception",
[
requests.exceptions.RequestException("Connection error"),
json.decoder.JSONDecodeError("Invalid JSON", "", 0),
],
ids=["network_error", "json_error"],
)
async def test_classic_api_login_exceptions(
hass: HomeAssistant,
mock_growatt_classic_api,
mock_config_entry_classic: MockConfigEntry,
exception: Exception,
) -> None:
"""Test Classic API setup with login exceptions."""
mock_growatt_classic_api.login.side_effect = exception
await setup_integration(hass, mock_config_entry_classic)
assert mock_config_entry_classic.state is ConfigEntryState.SETUP_ERROR
@pytest.mark.parametrize(
"login_response",
[
{"success": False, "msg": "502"},
{"success": False, "msg": "Server maintenance"},
],
ids=["invalid_auth", "other_login_error"],
)
async def test_classic_api_login_failures(
hass: HomeAssistant,
mock_growatt_classic_api,
mock_config_entry_classic: MockConfigEntry,
login_response: dict,
) -> None:
"""Test Classic API setup with login failures."""
mock_growatt_classic_api.login.return_value = login_response
await setup_integration(hass, mock_config_entry_classic)
assert mock_config_entry_classic.state is ConfigEntryState.SETUP_ERROR
@pytest.mark.parametrize(
"exception",
[
requests.exceptions.RequestException("Connection error"),
json.decoder.JSONDecodeError("Invalid JSON", "", 0),
],
ids=["network_error", "json_error"],
)
async def test_classic_api_device_list_exceptions(
hass: HomeAssistant,
mock_growatt_classic_api,
exception: Exception,
) -> None:
"""Test Classic API setup with device_list exceptions."""
# Create a config entry that won't trigger migration
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_AUTH_TYPE: AUTH_PASSWORD,
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
CONF_URL: "https://server.growatt.com/",
CONF_PLANT_ID: "specific_plant_123", # Specific ID to avoid migration
},
unique_id="plant_123",
)
# device_list raises exception during setup
mock_growatt_classic_api.device_list.side_effect = exception
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_classic_api_device_list_no_devices(
hass: HomeAssistant,
mock_growatt_classic_api,
) -> None:
"""Test Classic API setup when device list returns no devices."""
# Create a config entry that won't trigger migration
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_AUTH_TYPE: AUTH_PASSWORD,
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
CONF_URL: "https://server.growatt.com/",
CONF_PLANT_ID: "specific_plant_456", # Specific ID to avoid migration
},
unique_id="plant_456",
)
# device_list returns empty list (no devices)
mock_growatt_classic_api.device_list.return_value = []
await setup_integration(hass, mock_config_entry)
# Should still load successfully even with no devices
assert mock_config_entry.state is ConfigEntryState.LOADED
@pytest.mark.parametrize(
"exception",
[
requests.exceptions.RequestException("Connection error"),
json.decoder.JSONDecodeError("Invalid JSON", "", 0),
],
ids=["network_error", "json_error"],
)
async def test_classic_api_device_list_errors(
hass: HomeAssistant,
mock_growatt_classic_api,
mock_config_entry_classic: MockConfigEntry,
exception: Exception,
) -> None:
"""Test Classic API setup with device list errors."""
mock_growatt_classic_api.device_list.side_effect = exception
await setup_integration(hass, mock_config_entry_classic)
assert mock_config_entry_classic.state is ConfigEntryState.SETUP_ERROR
async def test_unknown_api_version(
hass: HomeAssistant,
) -> None:
"""Test setup with unknown API version."""
# Create a config entry with invalid auth type
config = {
CONF_URL: "https://openapi.growatt.com/",
"plant_id": "plant_123",
CONF_AUTH_TYPE: "unknown_auth", # Invalid auth type
}
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data=config,
unique_id="plant_123",
)
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_classic_api_auto_select_plant(
hass: HomeAssistant,
mock_growatt_classic_api,
mock_config_entry_classic_default_plant: MockConfigEntry,
) -> None:
"""Test Classic API setup with default plant ID (auto-selects first plant)."""
# Login succeeds and plant_list returns a plant
mock_growatt_classic_api.login.return_value = {
"success": True,
"user": {"id": 123456},
}
mock_growatt_classic_api.plant_list.return_value = {
"data": [{"plantId": "AUTO_PLANT_123", "plantName": "Auto Plant"}]
}
mock_growatt_classic_api.device_list.return_value = [
{"deviceSn": "TLX999999", "deviceType": "tlx"}
]
await setup_integration(hass, mock_config_entry_classic_default_plant)
# Should be loaded successfully with auto-selected plant
assert mock_config_entry_classic_default_plant.state is ConfigEntryState.LOADED
async def test_v1_api_unsupported_device_type(
hass: HomeAssistant,
mock_growatt_v1_api,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test V1 API logs warning for unsupported device types (non-MIN)."""
config = {
CONF_TOKEN: "test_token_123",
CONF_URL: "https://openapi.growatt.com/",
"plant_id": "plant_123",
CONF_AUTH_TYPE: AUTH_API_TOKEN,
}
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data=config,
unique_id="plant_123",
)
# Return mix of MIN (type 7) and other device types
mock_growatt_v1_api.device_list.return_value = {
"devices": [
{"device_sn": "MIN123456", "type": 7}, # Supported
{"device_sn": "TLX789012", "type": 5}, # Unsupported
]
}
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
# Verify warning was logged for unsupported device
assert "Device TLX789012 with type 5 not supported in Open API V1" in caplog.text
async def test_migrate_version_bump(
hass: HomeAssistant,
mock_growatt_classic_api,
) -> None:
"""Test migration from 1.0 to 1.1 resolves DEFAULT_PLANT_ID and bumps version.
This test verifies that:
- Migration successfully resolves DEFAULT_PLANT_ID ("0") to actual plant_id
- Config entry version is bumped from 1.0 to 1.1
- API instance is cached for setup to reuse (rate limit optimization)
"""
# Create a version 1.0 config entry with DEFAULT_PLANT_ID
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_AUTH_TYPE: AUTH_PASSWORD,
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
CONF_URL: "https://server.growatt.com/",
CONF_PLANT_ID: DEFAULT_PLANT_ID,
CONF_NAME: "Test Plant",
},
unique_id="plant_default",
version=1,
minor_version=0,
)
# Mock successful API responses for migration
mock_growatt_classic_api.login.return_value = {
"success": True,
"user": {"id": 123456},
}
mock_growatt_classic_api.plant_list.return_value = {
"data": [{"plantId": "RESOLVED_PLANT_789", "plantName": "My Plant"}]
}
mock_config_entry.add_to_hass(hass)
# Execute migration
migration_result = await async_migrate_entry(hass, mock_config_entry)
assert migration_result is True
# Verify version was updated to 1.1
assert mock_config_entry.version == 1
assert mock_config_entry.minor_version == 1
# Verify plant_id was resolved to actual plant_id (not DEFAULT_PLANT_ID)
assert mock_config_entry.data[CONF_PLANT_ID] == "RESOLVED_PLANT_789"
# Verify API instance was cached for setup to reuse
assert f"{CACHED_API_KEY}{mock_config_entry.entry_id}" in hass.data[DOMAIN]
async def test_setup_reuses_cached_api_from_migration(
hass: HomeAssistant,
mock_growatt_classic_api,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test that setup reuses cached API instance from migration.
This test verifies the rate limit optimization where:
1. Migration calls login() and caches the authenticated API instance
2. Setup retrieves and reuses the cached API (avoiding a second login())
3. The cached API is removed after use (one-time use pattern)
Without this caching, we would call login() twice within seconds:
Migration: login() → plant_list()
Setup: login() → device_list()
This would trigger Growatt API rate limiting (5-minute window per endpoint).
With caching, we only call login() once:
Migration: login() → plant_list() → [cache API]
Setup: [reuse API] → device_list()
"""
# Create a version 1.0 config entry with DEFAULT_PLANT_ID
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_AUTH_TYPE: AUTH_PASSWORD,
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
CONF_URL: "https://server.growatt.com/",
CONF_PLANT_ID: DEFAULT_PLANT_ID,
CONF_NAME: "Test Plant",
},
unique_id="plant_default",
version=1,
minor_version=0,
)
# Mock successful API responses
mock_growatt_classic_api.login.return_value = {
"success": True,
"user": {"id": 123456},
}
mock_growatt_classic_api.plant_list.return_value = {
"data": [{"plantId": "RESOLVED_PLANT_789", "plantName": "My Plant"}]
}
mock_growatt_classic_api.device_list.return_value = [
{"deviceSn": "TLX123456", "deviceType": "tlx"}
]
mock_growatt_classic_api.plant_info.return_value = {
"deviceList": [],
"totalEnergy": 1250.0,
"todayEnergy": 12.5,
"invTodayPpv": 2500,
"plantMoneyText": "123.45/USD",
}
mock_growatt_classic_api.tlx_detail.return_value = {
"data": {"deviceSn": "TLX123456"}
}
mock_config_entry.add_to_hass(hass)
# Run migration first (resolves plant_id and caches authenticated API)
await async_migrate_entry(hass, mock_config_entry)
# Verify migration successfully resolved plant_id
assert mock_config_entry.data[CONF_PLANT_ID] == "RESOLVED_PLANT_789"
# Now setup the integration (should reuse cached API from migration)
await setup_integration(hass, mock_config_entry)
# Verify integration loaded successfully
assert mock_config_entry.state is ConfigEntryState.LOADED
# Verify log message confirms API reuse (rate limit optimization)
assert "Reusing logged-in session from migration" in caplog.text
# Verify login was called with correct credentials
# Note: Coordinators also call login() during refresh, so we verify
# the call was made but don't assert it was called exactly once
mock_growatt_classic_api.login.assert_called_with("test_user", "test_password")
# Verify plant_list was called only once (during migration, not during setup)
# This confirms setup did NOT resolve plant_id again (optimization working)
mock_growatt_classic_api.plant_list.assert_called_once_with(123456)
# Verify the cached API was removed after use (should not be in hass.data anymore)
assert f"{CACHED_API_KEY}{mock_config_entry.entry_id}" not in hass.data.get(
DOMAIN, {}
)
async def test_migrate_failure_returns_false(
hass: HomeAssistant,
mock_growatt_classic_api,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test migration returns False on API failure to allow retry.
When migration fails due to API errors (network issues, etc.),
it should return False and NOT bump the version. This allows Home Assistant
to retry the migration on the next restart.
"""
# Create a version 1.0 config entry with DEFAULT_PLANT_ID
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_AUTH_TYPE: AUTH_PASSWORD,
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
CONF_URL: "https://server.growatt.com/",
CONF_PLANT_ID: DEFAULT_PLANT_ID,
CONF_NAME: "Test Plant",
},
unique_id="plant_default",
version=1,
minor_version=0,
)
# Mock API failure (e.g., network error during login)
mock_growatt_classic_api.login.side_effect = requests.exceptions.RequestException(
"Network error"
)
mock_config_entry.add_to_hass(hass)
# Execute migration (should fail gracefully)
migration_result = await async_migrate_entry(hass, mock_config_entry)
# Verify migration returned False (will retry on next restart)
assert migration_result is False
# Verify version was NOT bumped (remains 1.0)
assert mock_config_entry.version == 1
assert mock_config_entry.minor_version == 0
# Verify plant_id was NOT changed (remains DEFAULT_PLANT_ID)
assert mock_config_entry.data[CONF_PLANT_ID] == DEFAULT_PLANT_ID
# Verify error was logged
assert "Failed to resolve plant_id during migration" in caplog.text
assert "Migration will retry on next restart" in caplog.text
async def test_migrate_already_migrated(
hass: HomeAssistant,
) -> None:
"""Test migration is skipped for already migrated entries."""
# Create a config entry already at version 1.1
mock_config_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_AUTH_TYPE: AUTH_PASSWORD,
CONF_USERNAME: "test_user",
CONF_PASSWORD: "test_password",
CONF_URL: "https://server.growatt.com/",
CONF_PLANT_ID: "specific_plant_123",
},
unique_id="plant_specific",
version=1,
minor_version=1,
)
mock_config_entry.add_to_hass(hass)
# Call migration function
migration_result = await async_migrate_entry(hass, mock_config_entry)
assert migration_result is True
# Verify version remains 1.1 (no change)
assert mock_config_entry.version == 1
assert mock_config_entry.minor_version == 1
# Plant ID should remain unchanged
assert mock_config_entry.data[CONF_PLANT_ID] == "specific_plant_123"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/growatt_server/test_init.py",
"license": "Apache License 2.0",
"lines": 543,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/growatt_server/test_number.py | """Tests for the Growatt Server number platform."""
from collections.abc import AsyncGenerator
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
from growattServer import GrowattV1ApiError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.growatt_server.coordinator import SCAN_INTERVAL
from homeassistant.components.number import (
ATTR_VALUE,
DOMAIN as NUMBER_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
DOMAIN = "growatt_server"
@pytest.fixture(autouse=True)
async def number_only() -> AsyncGenerator[None]:
"""Enable only the number platform."""
with patch(
"homeassistant.components.growatt_server.PLATFORMS",
[Platform.NUMBER],
):
yield
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_number_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that number entities are created for MIN devices."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_set_number_value_api_error(
hass: HomeAssistant,
mock_growatt_v1_api,
) -> None:
"""Test handling API error when setting number value."""
# Mock API to raise error
mock_growatt_v1_api.min_write_parameter.side_effect = GrowattV1ApiError("API Error")
with pytest.raises(HomeAssistantError, match="Error while setting parameter"):
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{
"entity_id": "number.min123456_battery_charge_power_limit",
ATTR_VALUE: 75,
},
blocking=True,
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_all_number_entities_service_calls(
hass: HomeAssistant,
mock_growatt_v1_api,
) -> None:
"""Test service calls work for all number entities."""
# Test all five number entities
test_cases = [
("number.min123456_battery_charge_power_limit", "charge_power", 75),
("number.min123456_battery_charge_soc_limit", "charge_stop_soc", 85),
("number.min123456_battery_discharge_power_limit", "discharge_power", 90),
(
"number.min123456_battery_discharge_soc_limit_off_grid",
"discharge_stop_soc",
25,
),
(
"number.min123456_battery_discharge_soc_limit_on_grid",
"on_grid_discharge_stop_soc",
30,
),
]
for entity_id, expected_write_key, test_value in test_cases:
mock_growatt_v1_api.reset_mock()
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{"entity_id": entity_id, ATTR_VALUE: test_value},
blocking=True,
)
# Verify API was called with correct parameters
mock_growatt_v1_api.min_write_parameter.assert_called_once_with(
"MIN123456", expected_write_key, test_value
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_number_missing_data(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test number entity when coordinator data is missing."""
# Set up API with missing data for one entity
mock_growatt_v1_api.min_detail.return_value = {
"deviceSn": "MIN123456",
# Missing 'chargePowerCommand' key to test None case
"wchargeSOCLowLimit": 10,
"disChargePowerCommand": 80,
"wdisChargeSOCLowLimit": 20,
"onGridDischargeStopSOC": 15,
}
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Entity should exist but have unknown state due to missing data
state = hass.states.get("number.min123456_battery_charge_power_limit")
assert state is not None
assert state.state == STATE_UNKNOWN
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_no_number_entities_for_non_min_devices(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that number entities are not created for non-MIN devices."""
# Mock a different device type (not MIN) - type 7 is MIN, type 8 is non-MIN
mock_growatt_v1_api.device_list.return_value = {
"devices": [
{
"device_sn": "TLX123456",
"type": 8, # Non-MIN device type (MIN is type 7)
}
]
}
# Mock TLX API response to prevent coordinator errors
mock_growatt_v1_api.tlx_detail.return_value = {"data": {}}
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Should have no number entities for TLX devices
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
number_entities = [entry for entry in entity_entries if entry.domain == "number"]
assert len(number_entities) == 0
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_no_number_entities_for_classic_api(
hass: HomeAssistant,
mock_growatt_classic_api,
mock_config_entry_classic: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that number entities are not created for Classic API."""
# Mock device list to return no devices
mock_growatt_classic_api.device_list.return_value = []
mock_config_entry_classic.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry_classic.entry_id)
await hass.async_block_till_done()
# Should have no number entities for classic API (no devices)
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry_classic.entry_id
)
number_entities = [entry for entry in entity_entries if entry.domain == "number"]
assert len(number_entities) == 0
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_float_to_int_conversion(
hass: HomeAssistant,
mock_growatt_v1_api,
) -> None:
"""Test that float values are converted to integers when setting."""
# Test setting a float value gets converted to int
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{"entity_id": "number.min123456_battery_charge_power_limit", ATTR_VALUE: 75.7},
blocking=True,
)
# Verify API was called with integer value
mock_growatt_v1_api.min_write_parameter.assert_called_once_with(
"MIN123456",
"charge_power",
75, # Should be converted to int
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_number_coordinator_data_update(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that number state updates when coordinator data changes."""
# Set up 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()
# Initial state should be 50 (based on mock data)
state = hass.states.get("number.min123456_battery_charge_power_limit")
assert state is not None
assert float(state.state) == 50.0
# Change mock data and trigger coordinator update
mock_growatt_v1_api.min_detail.return_value = {
"deviceSn": "MIN123456",
"chargePowerCommand": 75, # Changed value
"wchargeSOCLowLimit": 10,
"disChargePowerCommand": 80,
"wdisChargeSOCLowLimit": 20,
"onGridDischargeStopSOC": 15,
}
# Advance time to trigger coordinator refresh
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# State should now be 75
state = hass.states.get("number.min123456_battery_charge_power_limit")
assert state is not None
assert float(state.state) == 75.0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/growatt_server/test_number.py",
"license": "Apache License 2.0",
"lines": 210,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/growatt_server/test_sensor.py | """Tests for the Growatt Server sensor platform."""
from datetime import timedelta
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
import growattServer
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import STATE_UNAVAILABLE, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . 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_min_sensors_v1_api(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test MIN device sensor entities with V1 API."""
# V1 API only supports MIN devices (type 7)
mock_growatt_v1_api.device_list.return_value = {
"devices": [{"device_sn": "MIN123456", "type": 7}]
}
with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("device_type", "device_sn"),
[
("tlx", "TLX123456"),
("inverter", "INV123456"),
("storage", "STO123456"),
("mix", "MIX123456"),
],
ids=["tlx", "inverter", "storage", "mix"],
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.freeze_time("2023-10-21")
async def test_sensors_classic_api(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_growatt_classic_api,
mock_config_entry_classic: MockConfigEntry,
entity_registry: er.EntityRegistry,
device_type: str,
device_sn: str,
) -> None:
"""Test sensor entities for non-MIN device types with Classic API."""
# Classic API supports all device types
mock_growatt_classic_api.device_list.return_value = [
{"deviceSn": device_sn, "deviceType": device_type}
]
# Device detail methods (inverter_detail, storage_detail, mix_detail, tlx_detail)
# are already configured in the default mock_growatt_classic_api fixture
with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry_classic)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry_classic.entry_id
)
async def test_sensor_coordinator_updates(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test sensors update when coordinator refreshes."""
with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
# Verify sensor exists
state = hass.states.get("sensor.test_plant_total_energy_today")
assert state is not None
assert state.state == "12.5"
# Update mock data
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 25.0, # Changed from 12.5
"total_energy": 1250.0,
"current_power": 2500,
}
# Trigger coordinator refresh
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Verify state updated
state = hass.states.get("sensor.test_plant_total_energy_today")
assert state is not None
assert state.state == "25.0"
async def test_sensor_unavailable_on_coordinator_error(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test sensors become unavailable when coordinator fails."""
with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
# Verify sensor is initially available
state = hass.states.get("sensor.min123456_all_batteries_charged_today")
assert state is not None
assert state.state != STATE_UNAVAILABLE
# Cause coordinator update to fail
mock_growatt_v1_api.min_detail.side_effect = growattServer.GrowattV1ApiError(
"Connection timeout"
)
# Trigger coordinator refresh
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Verify sensor becomes unavailable
state = hass.states.get("sensor.min123456_all_batteries_charged_today")
assert state is not None
assert state.state == STATE_UNAVAILABLE
async def test_midnight_bounce_suppression(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that stale yesterday values after midnight reset are suppressed.
The Growatt API sometimes delivers stale yesterday values after a midnight
reset (9.5 → 0 → 9.5 → 0), causing TOTAL_INCREASING double-counting.
"""
with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
entity_id = "sensor.test_plant_total_energy_today"
# Initial state: 12.5 kWh produced today
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "12.5"
# Step 1: Midnight reset — API returns 0 (legitimate reset)
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 0,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "0"
# Step 2: Stale bounce — API returns yesterday's value (12.5) after reset
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 12.5,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Bounce should be suppressed — state stays at 0
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "0"
# Step 3: Another reset arrives — still 0 (no double-counting)
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 0,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "0"
# Step 4: Genuine new production — small value passes through
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 0.1,
"total_energy": 1250.1,
"current_power": 500,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "0.1"
async def test_normal_reset_no_bounce(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that normal midnight reset without bounce passes through correctly."""
with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
entity_id = "sensor.test_plant_total_energy_today"
# Initial state: 9.5 kWh
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 9.5,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "9.5"
# Midnight reset — API returns 0
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 0,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "0"
# No bounce — genuine new production starts
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 0.1,
"total_energy": 1250.1,
"current_power": 500,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "0.1"
# Production continues normally
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 1.5,
"total_energy": 1251.5,
"current_power": 2000,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "1.5"
async def test_midnight_bounce_repeated(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test multiple consecutive stale bounces are all suppressed."""
with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
entity_id = "sensor.test_plant_total_energy_today"
# Set up a known pre-reset value
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 8.0,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(entity_id).state == "8.0"
# Midnight reset
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 0,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(entity_id).state == "0"
# First stale bounce — suppressed
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 8.0,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(entity_id).state == "0"
# Back to 0
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 0,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(entity_id).state == "0"
# Second stale bounce — also suppressed
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 8.0,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(entity_id).state == "0"
# Back to 0 again
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 0,
"total_energy": 1250.0,
"current_power": 0,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(entity_id).state == "0"
# Finally, genuine new production passes through
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 0.2,
"total_energy": 1250.2,
"current_power": 1000,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get(entity_id).state == "0.2"
async def test_non_total_increasing_sensor_unaffected_by_bounce_suppression(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that non-TOTAL_INCREASING sensors are not affected by bounce suppression.
The total_energy_output sensor (totalEnergy) has state_class=TOTAL,
so bounce suppression (which only targets TOTAL_INCREASING) should not apply.
"""
with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry)
# total_energy_output uses state_class=TOTAL (not TOTAL_INCREASING)
entity_id = "sensor.test_plant_total_lifetime_energy_output"
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "1250.0"
# Simulate API returning 0 — no bounce suppression on TOTAL sensors
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 12.5,
"total_energy": 0,
"current_power": 2500,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "0"
# Value recovers — passes through without suppression
mock_growatt_v1_api.plant_energy_overview.return_value = {
"today_energy": 12.5,
"total_energy": 1250.0,
"current_power": 2500,
}
freezer.tick(timedelta(minutes=5))
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "1250.0"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_total_sensors_classic_api(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_growatt_classic_api,
mock_config_entry_classic: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test total sensors with Classic API."""
# Classic API uses TLX devices
mock_growatt_classic_api.device_list.return_value = [
{"deviceSn": "TLX123456", "deviceType": "tlx"}
]
with patch("homeassistant.components.growatt_server.PLATFORMS", [Platform.SENSOR]):
await setup_integration(hass, mock_config_entry_classic)
await snapshot_platform(
hass, entity_registry, snapshot, mock_config_entry_classic.entry_id
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/growatt_server/test_sensor.py",
"license": "Apache License 2.0",
"lines": 376,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/growatt_server/test_switch.py | """Tests for the Growatt Server switch platform."""
from collections.abc import AsyncGenerator
from unittest.mock import patch
from freezegun.api import FrozenDateTimeFactory
from growattServer import GrowattV1ApiError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.growatt_server.coordinator import SCAN_INTERVAL
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_UNKNOWN,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
DOMAIN = "growatt_server"
@pytest.fixture(autouse=True)
async def switch_only() -> AsyncGenerator[None]:
"""Enable only the switch platform."""
with patch(
"homeassistant.components.growatt_server.PLATFORMS",
[Platform.SWITCH],
):
yield
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
async def test_switch_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that switch entities are created for MIN devices."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
@pytest.mark.parametrize(
("service", "expected_value"),
[
(SERVICE_TURN_ON, 1),
(SERVICE_TURN_OFF, 0),
],
)
async def test_switch_service_call_success(
hass: HomeAssistant,
mock_growatt_v1_api,
service: str,
expected_value: int,
) -> None:
"""Test switch service calls successfully."""
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: "switch.min123456_charge_from_grid"},
blocking=True,
)
# Verify API was called with correct parameters
mock_growatt_v1_api.min_write_parameter.assert_called_once_with(
"MIN123456", "ac_charge", expected_value
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration")
@pytest.mark.parametrize(
"service",
[SERVICE_TURN_ON, SERVICE_TURN_OFF],
)
async def test_switch_service_call_api_error(
hass: HomeAssistant,
mock_growatt_v1_api,
service: str,
) -> None:
"""Test handling API error when calling switch services."""
# Mock API to raise error
mock_growatt_v1_api.min_write_parameter.side_effect = GrowattV1ApiError("API Error")
with pytest.raises(HomeAssistantError, match="Error while setting switch state"):
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{"entity_id": "switch.min123456_charge_from_grid"},
blocking=True,
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_switch_state_handling_integer_values(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_growatt_v1_api,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test switch state handling with integer values from API."""
# Set up 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()
# Should interpret 1 as ON (from default mock data)
state = hass.states.get("switch.min123456_charge_from_grid")
assert state is not None
assert state.state == STATE_ON
# Test with 0 integer value
mock_growatt_v1_api.min_detail.return_value = {
"deviceSn": "MIN123456",
"acChargeEnable": 0, # Integer value
}
# Advance time to trigger coordinator refresh
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Should interpret 0 as OFF
state = hass.states.get("switch.min123456_charge_from_grid")
assert state is not None
assert state.state == STATE_OFF
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_switch_missing_data(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test switch entity when coordinator data is missing."""
# Set up API with missing data for switch entity
mock_growatt_v1_api.min_detail.return_value = {
"deviceSn": "MIN123456",
# Missing 'acChargeEnable' key to test None case
}
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Entity should exist but have unknown state due to missing data
state = hass.states.get("switch.min123456_charge_from_grid")
assert state is not None
assert state.state == STATE_UNKNOWN
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_no_switch_entities_for_non_min_devices(
hass: HomeAssistant,
mock_growatt_v1_api,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that switch entities are not created for non-MIN devices."""
# Mock a different device type (not MIN) - type 7 is MIN, type 8 is non-MIN
mock_growatt_v1_api.device_list.return_value = {
"devices": [
{
"device_sn": "TLX123456",
"type": 8, # Non-MIN device type (MIN is type 7)
}
]
}
# Mock TLX API response to prevent coordinator errors
mock_growatt_v1_api.tlx_detail.return_value = {"data": {}}
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Should have no switch entities for TLX devices
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
switch_entities = [entry for entry in entity_entries if entry.domain == "switch"]
assert len(switch_entities) == 0
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_no_switch_entities_for_classic_api(
hass: HomeAssistant,
mock_growatt_classic_api,
mock_config_entry_classic: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test that switch entities are not created for Classic API."""
# Mock device list to return no devices
mock_growatt_classic_api.device_list.return_value = []
mock_config_entry_classic.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry_classic.entry_id)
await hass.async_block_till_done()
# Should have no switch entities for classic API (no devices)
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry_classic.entry_id
)
switch_entities = [entry for entry in entity_entries if entry.domain == "switch"]
assert len(switch_entities) == 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/growatt_server/test_switch.py",
"license": "Apache License 2.0",
"lines": 180,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/habitica/test_notify.py | """Tests for the Habitica notify platform."""
from collections.abc import AsyncGenerator
from datetime import timedelta
from typing import Any
from unittest.mock import AsyncMock, patch
from uuid import UUID
from aiohttp import ClientError
from freezegun.api import FrozenDateTimeFactory
from habiticalib import HabiticaGroupMembersResponse
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.habitica.const import DOMAIN
from homeassistant.components.notify import (
ATTR_MESSAGE,
DOMAIN as NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from .conftest import (
ERROR_BAD_REQUEST,
ERROR_NOT_AUTHORIZED,
ERROR_NOT_FOUND,
ERROR_TOO_MANY_REQUESTS,
)
from tests.common import (
MockConfigEntry,
async_fire_time_changed,
async_load_fixture,
snapshot_platform,
)
@pytest.fixture(autouse=True)
async def notify_only() -> AsyncGenerator[None]:
"""Enable only the notify platform."""
with patch(
"homeassistant.components.habitica.PLATFORMS",
[Platform.NOTIFY],
):
yield
@pytest.mark.usefixtures("habitica")
async def test_notify_platform(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test setup of the notify platform."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize(
("entity_id", "call_method", "call_args"),
[
(
"notify.test_user_party_chat",
"send_group_message",
{"group_id": UUID("1e87097c-4c03-4f8c-a475-67cc7da7f409")},
),
(
"notify.test_user_private_message_test_partymember_displayname",
"send_private_message",
{"to_user_id": UUID("ffce870c-3ff3-4fa4-bad1-87612e52b8e7")},
),
],
)
@pytest.mark.freeze_time("2025-08-13T00:00:00+00:00")
async def test_send_message(
hass: HomeAssistant,
config_entry: MockConfigEntry,
habitica: AsyncMock,
entity_id: str,
call_method: str,
call_args: dict[str, Any],
) -> None:
"""Test send message."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNKNOWN
await hass.services.async_call(
NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
{
ATTR_ENTITY_ID: entity_id,
ATTR_MESSAGE: "Greetings, fellow adventurer",
},
blocking=True,
)
state = hass.states.get(entity_id)
assert state
assert state.state == "2025-08-13T00:00:00+00:00"
getattr(habitica, call_method).assert_called_once_with(
message="Greetings, fellow adventurer", **call_args
)
@pytest.mark.parametrize(
"exception",
[
ERROR_BAD_REQUEST,
ERROR_NOT_AUTHORIZED,
ERROR_NOT_FOUND,
ERROR_TOO_MANY_REQUESTS,
ClientError,
],
)
async def test_send_message_exceptions(
hass: HomeAssistant,
config_entry: MockConfigEntry,
habitica: AsyncMock,
exception: Exception,
) -> None:
"""Test send message exceptions."""
habitica.send_group_message.side_effect = exception
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
NOTIFY_DOMAIN,
SERVICE_SEND_MESSAGE,
{
ATTR_ENTITY_ID: "notify.test_user_party_chat",
ATTR_MESSAGE: "Greetings, fellow adventurer",
},
blocking=True,
)
async def test_remove_stale_entities(
hass: HomeAssistant,
config_entry: MockConfigEntry,
habitica: AsyncMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test removing stale private message entities."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
assert hass.states.get(
"notify.test_user_private_message_test_partymember_displayname"
)
habitica.get_group_members.return_value = HabiticaGroupMembersResponse.from_json(
await async_load_fixture(hass, "party_members_2.json", DOMAIN)
)
freezer.tick(timedelta(minutes=15))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (
hass.states.get("notify.test_user_private_message_test_partymember_displayname")
is None
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/habitica/test_notify.py",
"license": "Apache License 2.0",
"lines": 158,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/hassio/test_jobs.py | """Test supervisor jobs manager."""
from collections.abc import Generator
from datetime import datetime
import os
from unittest.mock import AsyncMock, patch
from uuid import uuid4
from aiohasupervisor.models import Job, JobsInfo
import pytest
from homeassistant.components.hassio.const import ADDONS_COORDINATOR
from homeassistant.components.hassio.coordinator import HassioDataUpdateCoordinator
from homeassistant.components.hassio.jobs import JobSubscription
from homeassistant.core import HomeAssistant, callback
from homeassistant.setup import async_setup_component
from .test_init import MOCK_ENVIRON
from tests.typing import WebSocketGenerator
@pytest.fixture(autouse=True)
def fixture_supervisor_environ() -> Generator[None]:
"""Mock os environ for supervisor."""
with patch.dict(os.environ, MOCK_ENVIRON):
yield
@pytest.mark.usefixtures("all_setup_requests")
async def test_job_manager_setup(hass: HomeAssistant, jobs_info: AsyncMock) -> None:
"""Test setup of job manager."""
jobs_info.return_value = JobsInfo(
ignore_conditions=[],
jobs=[
Job(
name="test_job",
reference=None,
uuid=uuid4(),
progress=0,
stage=None,
done=False,
errors=[],
created=datetime.now(),
extra=None,
child_jobs=[
Job(
name="test_inner_job",
reference=None,
uuid=uuid4(),
progress=0,
stage=None,
done=False,
errors=[],
created=datetime.now(),
extra=None,
child_jobs=[],
)
],
)
],
)
result = await async_setup_component(hass, "hassio", {})
assert result
jobs_info.assert_called_once()
data_coordinator: HassioDataUpdateCoordinator = hass.data[ADDONS_COORDINATOR]
assert len(data_coordinator.jobs.current_jobs) == 2
assert data_coordinator.jobs.current_jobs[0].name == "test_job"
assert data_coordinator.jobs.current_jobs[1].name == "test_inner_job"
@pytest.mark.usefixtures("all_setup_requests")
async def test_disconnect_on_config_entry_reload(
hass: HomeAssistant, jobs_info: AsyncMock
) -> None:
"""Test dispatcher subscription disconnects on config entry reload."""
result = await async_setup_component(hass, "hassio", {})
assert result
jobs_info.assert_called_once()
jobs_info.reset_mock()
data_coordinator: HassioDataUpdateCoordinator = hass.data[ADDONS_COORDINATOR]
await hass.config_entries.async_reload(data_coordinator.entry_id)
await hass.async_block_till_done()
jobs_info.assert_called_once()
@pytest.mark.usefixtures("all_setup_requests")
async def test_job_manager_ws_updates(
hass: HomeAssistant, jobs_info: AsyncMock, hass_ws_client: WebSocketGenerator
) -> None:
"""Test job updates sync from Supervisor WS messages."""
result = await async_setup_component(hass, "hassio", {})
assert result
jobs_info.assert_called_once()
jobs_info.reset_mock()
client = await hass_ws_client(hass)
data_coordinator: HassioDataUpdateCoordinator = hass.data[ADDONS_COORDINATOR]
assert not data_coordinator.jobs.current_jobs
# Make an example listener
job_data: Job | None = None
@callback
def mock_subcription_callback(job: Job) -> None:
nonlocal job_data
job_data = job
subscription = JobSubscription(
mock_subcription_callback, name="test_job", reference="test"
)
unsubscribe = data_coordinator.jobs.subscribe(subscription)
# Send start of job update
await client.send_json(
{
"id": 1,
"type": "supervisor/event",
"data": {
"event": "job",
"data": {
"name": "test_job",
"reference": "test",
"uuid": (uuid := uuid4().hex),
"progress": 0,
"stage": None,
"done": False,
"errors": [],
"created": (created := datetime.now().isoformat()),
"extra": None,
},
},
}
)
msg = await client.receive_json()
assert msg["success"]
await hass.async_block_till_done()
assert job_data.name == "test_job"
assert job_data.reference == "test"
assert job_data.progress == 0
assert job_data.done is False
# One job in the cache
assert len(data_coordinator.jobs.current_jobs) == 1
# Example progress update
await client.send_json(
{
"id": 2,
"type": "supervisor/event",
"data": {
"event": "job",
"data": {
"name": "test_job",
"reference": "test",
"uuid": uuid,
"progress": 50,
"stage": None,
"done": False,
"errors": [],
"created": created,
"extra": None,
},
},
}
)
msg = await client.receive_json()
assert msg["success"]
await hass.async_block_till_done()
assert job_data.name == "test_job"
assert job_data.reference == "test"
assert job_data.progress == 50
assert job_data.done is False
# Same job, same number of jobs in cache
assert len(data_coordinator.jobs.current_jobs) == 1
# Unrelated job update - name change, subscriber should not receive
await client.send_json(
{
"id": 3,
"type": "supervisor/event",
"data": {
"event": "job",
"data": {
"name": "bad_job",
"reference": "test",
"uuid": uuid4().hex,
"progress": 0,
"stage": None,
"done": False,
"errors": [],
"created": created,
"extra": None,
},
},
}
)
msg = await client.receive_json()
assert msg["success"]
await hass.async_block_till_done()
assert job_data.name == "test_job"
assert job_data.reference == "test"
# New job, cache increases
assert len(data_coordinator.jobs.current_jobs) == 2
# Unrelated job update - reference change, subscriber should not receive
await client.send_json(
{
"id": 4,
"type": "supervisor/event",
"data": {
"event": "job",
"data": {
"name": "test_job",
"reference": "bad",
"uuid": uuid4().hex,
"progress": 0,
"stage": None,
"done": False,
"errors": [],
"created": created,
"extra": None,
},
},
}
)
msg = await client.receive_json()
assert msg["success"]
await hass.async_block_till_done()
assert job_data.name == "test_job"
assert job_data.reference == "test"
# New job, cache increases
assert len(data_coordinator.jobs.current_jobs) == 3
# Unsubscribe mock listener, should not receive final update
unsubscribe()
await client.send_json(
{
"id": 5,
"type": "supervisor/event",
"data": {
"event": "job",
"data": {
"name": "test_job",
"reference": "test",
"uuid": uuid,
"progress": 100,
"stage": None,
"done": True,
"errors": [],
"created": created,
"extra": None,
},
},
}
)
msg = await client.receive_json()
assert msg["success"]
await hass.async_block_till_done()
assert job_data.name == "test_job"
assert job_data.reference == "test"
assert job_data.progress == 50
assert job_data.done is False
# Job ended, cache decreases
assert len(data_coordinator.jobs.current_jobs) == 2
# REST API should not be used during this sequence
jobs_info.assert_not_called()
@pytest.mark.usefixtures("all_setup_requests")
async def test_job_manager_reload_on_supervisor_restart(
hass: HomeAssistant, jobs_info: AsyncMock, hass_ws_client: WebSocketGenerator
) -> None:
"""Test job manager reloads cache on supervisor restart."""
jobs_info.return_value = JobsInfo(
ignore_conditions=[],
jobs=[
Job(
name="test_job",
reference="test",
uuid=uuid4(),
progress=0,
stage=None,
done=False,
errors=[],
created=datetime.now(),
extra=None,
child_jobs=[],
)
],
)
result = await async_setup_component(hass, "hassio", {})
assert result
jobs_info.assert_called_once()
data_coordinator: HassioDataUpdateCoordinator = hass.data[ADDONS_COORDINATOR]
assert len(data_coordinator.jobs.current_jobs) == 1
assert data_coordinator.jobs.current_jobs[0].name == "test_job"
jobs_info.reset_mock()
jobs_info.return_value = JobsInfo(ignore_conditions=[], jobs=[])
client = await hass_ws_client(hass)
# Make an example listener
job_data: Job | None = None
@callback
def mock_subcription_callback(job: Job) -> None:
nonlocal job_data
job_data = job
subscription = JobSubscription(mock_subcription_callback, name="test_job")
data_coordinator.jobs.subscribe(subscription)
# Send supervisor restart signal
await client.send_json(
{
"id": 1,
"type": "supervisor/event",
"data": {
"event": "supervisor_update",
"update_key": "supervisor",
"data": {"startup": "complete"},
},
}
)
msg = await client.receive_json()
assert msg["success"]
await hass.async_block_till_done()
# Listener should be told job is done and cache cleared out
jobs_info.assert_called_once()
assert job_data.name == "test_job"
assert job_data.reference == "test"
assert job_data.done is True
assert not data_coordinator.jobs.current_jobs
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/hassio/test_jobs.py",
"license": "Apache License 2.0",
"lines": 304,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homeassistant_connect_zbt2/test_switch.py | """Test Connect ZBT-2 beta firmware switch entity."""
from unittest.mock import Mock, call, patch
from ha_silabs_firmware_client import FirmwareManifest, FirmwareMetadata
import pytest
from yarl import URL
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import HomeAssistant, State
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from .common import USB_DATA_ZBT2
from tests.common import MockConfigEntry, mock_restore_cache
SWITCH_ENTITY_ID = (
"switch.home_assistant_connect_zbt_2_80b54eefae18_beta_firmware_updates"
)
TEST_MANIFEST = FirmwareManifest(
url=URL("https://example.org/firmware"),
html_url=URL("https://example.org/release_notes"),
created_at=dt_util.utcnow(),
firmwares=(
FirmwareMetadata(
filename="skyconnect_zigbee_ncp_test.gbl",
checksum="aaa",
size=123,
release_notes="Some release notes go here",
metadata={
"baudrate": 115200,
"ezsp_version": "7.4.4.0",
"fw_type": "zigbee_ncp",
"fw_variant": None,
"metadata_version": 2,
"sdk_version": "4.4.4",
},
url=URL("https://example.org/firmwares/skyconnect_zigbee_ncp_test.gbl"),
),
),
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize(
("service", "target_state", "expected_prerelease"),
[
(SERVICE_TURN_ON, STATE_ON, True),
(SERVICE_TURN_OFF, STATE_OFF, False),
],
)
async def test_switch_turn_on_off(
hass: HomeAssistant,
service: str,
target_state: str,
expected_prerelease: bool,
) -> None:
"""Test turning switch on/off updates state and coordinator."""
await async_setup_component(hass, "homeassistant", {})
# Start with opposite state
mock_restore_cache(
hass,
[
State(
SWITCH_ENTITY_ID,
STATE_ON if service == SERVICE_TURN_OFF else STATE_OFF,
)
],
)
# Set up the ZBT-2 integration
zbt2_config_entry = MockConfigEntry(
title="Home Assistant Connect ZBT-2",
domain="homeassistant_connect_zbt2",
data={
"firmware": "ezsp",
"firmware_version": "7.3.1.0 build 0",
"device": USB_DATA_ZBT2.device,
"manufacturer": USB_DATA_ZBT2.manufacturer,
"pid": USB_DATA_ZBT2.pid,
"product": USB_DATA_ZBT2.description,
"serial_number": USB_DATA_ZBT2.serial_number,
"vid": USB_DATA_ZBT2.vid,
},
version=1,
minor_version=1,
)
zbt2_config_entry.add_to_hass(hass)
with (
patch(
"homeassistant.components.homeassistant_hardware.coordinator.FirmwareUpdateClient"
) as mock_client,
patch(
"homeassistant.components.homeassistant_hardware.coordinator.FirmwareUpdateCoordinator.async_refresh"
) as mock_refresh,
):
mock_client.return_value.async_update_data.return_value = TEST_MANIFEST
mock_client.return_value.update_prerelease = Mock()
assert await hass.config_entries.async_setup(zbt2_config_entry.entry_id)
await hass.async_block_till_done()
# Reset mocks after setup
mock_client.return_value.update_prerelease.reset_mock()
mock_refresh.reset_mock()
# Call the service
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: SWITCH_ENTITY_ID},
blocking=True,
)
# Verify state changed
state = hass.states.get(SWITCH_ENTITY_ID)
assert state is not None
assert state.state == target_state
# Verify coordinator methods were called
assert mock_client.return_value.update_prerelease.mock_calls == [
call(expected_prerelease)
]
assert len(mock_refresh.mock_calls) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_connect_zbt2/test_switch.py",
"license": "Apache License 2.0",
"lines": 118,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homeassistant_hardware/common.py | """Common test constants for homeassistant_hardware tests."""
from ha_silabs_firmware_client import FirmwareManifest, FirmwareMetadata
from yarl import URL
from homeassistant.util import dt as dt_util
TEST_DOMAIN = "test"
TEST_FIRMWARE_RELEASES_URL = "https://example.org/firmware"
TEST_MANIFEST = FirmwareManifest(
url=URL("https://example.org/firmware"),
html_url=URL("https://example.org/release_notes"),
created_at=dt_util.utcnow(),
firmwares=(
FirmwareMetadata(
filename="skyconnect_zigbee_ncp_test.gbl",
checksum="aaa",
size=123,
release_notes="Some release notes go here",
metadata={
"baudrate": 115200,
"ezsp_version": "7.4.4.0",
"fw_type": "zigbee_ncp",
"fw_variant": None,
"metadata_version": 2,
"sdk_version": "4.4.4",
},
url=URL("https://example.org/firmwares/skyconnect_zigbee_ncp_test.gbl"),
),
),
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_hardware/common.py",
"license": "Apache License 2.0",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homeassistant_hardware/test_switch.py | """Test Home Assistant Hardware beta firmware switch entity."""
from __future__ import annotations
from collections.abc import AsyncGenerator
from unittest.mock import Mock, call, patch
import pytest
from homeassistant.components.homeassistant import DOMAIN as HOMEASSISTANT_DOMAIN
from homeassistant.components.homeassistant_hardware import DOMAIN
from homeassistant.components.homeassistant_hardware.coordinator import (
FirmwareUpdateCoordinator,
)
from homeassistant.components.homeassistant_hardware.switch import (
BaseBetaFirmwareSwitch,
)
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.config_entries import ConfigEntry, ConfigFlow
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
EntityCategory,
Platform,
)
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.setup import async_setup_component
from .common import TEST_DOMAIN, TEST_FIRMWARE_RELEASES_URL, TEST_MANIFEST
from tests.common import (
MockConfigEntry,
MockModule,
MockPlatform,
mock_config_flow,
mock_integration,
mock_platform,
mock_restore_cache,
)
TEST_DEVICE = "/dev/serial/by-id/test-device-12345"
TEST_SWITCH_ENTITY_ID = "switch.mock_device_beta_firmware_updates"
class MockBetaFirmwareSwitch(BaseBetaFirmwareSwitch):
"""Mock beta firmware switch for testing."""
def __init__(
self,
coordinator: FirmwareUpdateCoordinator,
config_entry: ConfigEntry,
) -> None:
"""Initialize the mock beta firmware switch."""
super().__init__(coordinator, config_entry)
self._attr_unique_id = "beta_firmware"
self._attr_name = "Beta firmware updates"
self._attr_device_info = DeviceInfo(
identifiers={(TEST_DOMAIN, "test_device")},
name="Mock Device",
model="Mock Model",
manufacturer="Mock Manufacturer",
)
def _mock_async_create_switch_entity(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> MockBetaFirmwareSwitch:
"""Create a mock switch entity."""
session = async_get_clientsession(hass)
coordinator = FirmwareUpdateCoordinator(
hass,
config_entry,
session,
TEST_FIRMWARE_RELEASES_URL,
)
entity = MockBetaFirmwareSwitch(coordinator, config_entry)
async_add_entities([entity])
return entity
async def mock_async_setup_entry(
hass: HomeAssistant, config_entry: ConfigEntry
) -> bool:
"""Set up test config entry."""
await hass.config_entries.async_forward_entry_setups(
config_entry, [Platform.SWITCH]
)
return True
async def mock_async_setup_switch_entities(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the beta firmware switch config entry."""
_mock_async_create_switch_entity(hass, config_entry, async_add_entities)
@pytest.fixture(name="mock_firmware_client")
def mock_firmware_client_fixture():
"""Create a mock firmware update client."""
with patch(
"homeassistant.components.homeassistant_hardware.coordinator.FirmwareUpdateClient",
autospec=True,
) as mock_client:
mock_client.return_value.async_update_data.return_value = TEST_MANIFEST
mock_client.return_value.update_prerelease = Mock()
yield mock_client.return_value
@pytest.fixture(name="switch_config_entry")
async def mock_switch_config_entry(
hass: HomeAssistant,
mock_firmware_client,
) -> AsyncGenerator[ConfigEntry]:
"""Set up a mock config entry for testing."""
await async_setup_component(hass, HOMEASSISTANT_DOMAIN, {})
await async_setup_component(hass, DOMAIN, {})
mock_integration(
hass,
MockModule(
TEST_DOMAIN,
async_setup_entry=mock_async_setup_entry,
),
built_in=False,
)
mock_platform(hass, "test.config_flow")
mock_platform(
hass,
"test.switch",
MockPlatform(async_setup_entry=mock_async_setup_switch_entities),
)
# Set up a mock integration using the hardware switch entity
config_entry = MockConfigEntry(
domain=TEST_DOMAIN,
data={
"device": TEST_DEVICE,
},
)
config_entry.add_to_hass(hass)
with mock_config_flow(TEST_DOMAIN, ConfigFlow):
yield config_entry
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_switch_default_off_state(
hass: HomeAssistant,
switch_config_entry: ConfigEntry,
mock_firmware_client,
) -> None:
"""Test switch defaults to off when no previous state."""
assert await hass.config_entries.async_setup(switch_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(TEST_SWITCH_ENTITY_ID)
assert state is not None
assert state.state == STATE_OFF
# Verify coordinator was called with False during setup
assert mock_firmware_client.update_prerelease.mock_calls == [call(False)]
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize(
("initial_state", "expected_state", "expected_prerelease"),
[
(STATE_ON, STATE_ON, True),
(STATE_OFF, STATE_OFF, False),
],
)
async def test_switch_restore_state(
hass: HomeAssistant,
switch_config_entry: ConfigEntry,
mock_firmware_client,
initial_state: str,
expected_state: str,
expected_prerelease: bool,
) -> None:
"""Test switch restores previous state and has correct entity attributes."""
mock_restore_cache(hass, [State(TEST_SWITCH_ENTITY_ID, initial_state)])
assert await hass.config_entries.async_setup(switch_config_entry.entry_id)
await hass.async_block_till_done()
state = hass.states.get(TEST_SWITCH_ENTITY_ID)
assert state is not None
assert state.state == expected_state
assert state.attributes.get("friendly_name") == "Mock Device Beta firmware updates"
# Verify coordinator was called with correct value during setup
assert mock_firmware_client.update_prerelease.mock_calls == [
call(expected_prerelease)
]
# Verify entity registry attributes
entity_registry = er.async_get(hass)
entity_entry = entity_registry.async_get(TEST_SWITCH_ENTITY_ID)
assert entity_entry is not None
assert entity_entry.entity_category == EntityCategory.CONFIG
assert entity_entry.translation_key == "beta_firmware"
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize(
("service", "target_state", "expected_prerelease"),
[
(SERVICE_TURN_ON, STATE_ON, True),
(SERVICE_TURN_OFF, STATE_OFF, False),
],
)
async def test_switch_turn_on_off(
hass: HomeAssistant,
switch_config_entry: ConfigEntry,
mock_firmware_client,
service: str,
target_state: str,
expected_prerelease: bool,
) -> None:
"""Test turning switch on/off updates state and coordinator."""
# Start with opposite state
mock_restore_cache(
hass,
[
State(
TEST_SWITCH_ENTITY_ID,
STATE_ON if service == SERVICE_TURN_OFF else STATE_OFF,
)
],
)
# Track async_refresh calls
with patch(
"homeassistant.components.homeassistant_hardware.coordinator.FirmwareUpdateCoordinator.async_refresh"
) as mock_refresh:
assert await hass.config_entries.async_setup(switch_config_entry.entry_id)
await hass.async_block_till_done()
# Reset mocks after setup
mock_firmware_client.update_prerelease.reset_mock()
mock_refresh.reset_mock()
# Call the service
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: TEST_SWITCH_ENTITY_ID},
blocking=True,
)
# Verify state changed
state = hass.states.get(TEST_SWITCH_ENTITY_ID)
assert state is not None
assert state.state == target_state
# Verify coordinator methods were called
assert mock_firmware_client.update_prerelease.mock_calls == [
call(expected_prerelease)
]
assert len(mock_refresh.mock_calls) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_hardware/test_switch.py",
"license": "Apache License 2.0",
"lines": 232,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homeassistant_sky_connect/test_switch.py | """Test SkyConnect beta firmware switch entity."""
from unittest.mock import Mock, call, patch
from ha_silabs_firmware_client import FirmwareManifest, FirmwareMetadata
import pytest
from yarl import URL
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import HomeAssistant, State
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from .common import USB_DATA_ZBT1
from tests.common import MockConfigEntry, mock_restore_cache
SWITCH_ENTITY_ID = "switch.home_assistant_connect_zbt_1_9e2adbd7_beta_firmware_updates"
TEST_MANIFEST = FirmwareManifest(
url=URL("https://example.org/firmware"),
html_url=URL("https://example.org/release_notes"),
created_at=dt_util.utcnow(),
firmwares=(
FirmwareMetadata(
filename="skyconnect_zigbee_ncp_test.gbl",
checksum="aaa",
size=123,
release_notes="Some release notes go here",
metadata={
"baudrate": 115200,
"ezsp_version": "7.4.4.0",
"fw_type": "zigbee_ncp",
"fw_variant": None,
"metadata_version": 2,
"sdk_version": "4.4.4",
},
url=URL("https://example.org/firmwares/skyconnect_zigbee_ncp_test.gbl"),
),
),
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize(
("service", "target_state", "expected_prerelease"),
[
(SERVICE_TURN_ON, STATE_ON, True),
(SERVICE_TURN_OFF, STATE_OFF, False),
],
)
async def test_switch_turn_on_off(
hass: HomeAssistant,
service: str,
target_state: str,
expected_prerelease: bool,
) -> None:
"""Test turning switch on/off updates state and coordinator."""
await async_setup_component(hass, "homeassistant", {})
# Start with opposite state
mock_restore_cache(
hass,
[
State(
SWITCH_ENTITY_ID,
STATE_ON if service == SERVICE_TURN_OFF else STATE_OFF,
)
],
)
# Set up the ZBT-1 integration
zbt1_config_entry = MockConfigEntry(
title="Home Assistant Connect ZBT-1",
domain="homeassistant_sky_connect",
data={
"firmware": "ezsp",
"firmware_version": "7.3.1.0 build 0",
"device": USB_DATA_ZBT1.device,
"manufacturer": USB_DATA_ZBT1.manufacturer,
"pid": USB_DATA_ZBT1.pid,
"product": USB_DATA_ZBT1.description,
"serial_number": USB_DATA_ZBT1.serial_number,
"vid": USB_DATA_ZBT1.vid,
},
version=1,
minor_version=3,
)
zbt1_config_entry.add_to_hass(hass)
with (
patch(
"homeassistant.components.homeassistant_hardware.coordinator.FirmwareUpdateClient"
) as mock_client,
patch(
"homeassistant.components.homeassistant_hardware.coordinator.FirmwareUpdateCoordinator.async_refresh"
) as mock_refresh,
):
mock_client.return_value.async_update_data.return_value = TEST_MANIFEST
mock_client.return_value.update_prerelease = Mock()
assert await hass.config_entries.async_setup(zbt1_config_entry.entry_id)
await hass.async_block_till_done()
# Reset mocks after setup
mock_client.return_value.update_prerelease.reset_mock()
mock_refresh.reset_mock()
# Call the service
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: SWITCH_ENTITY_ID},
blocking=True,
)
# Verify state changed
state = hass.states.get(SWITCH_ENTITY_ID)
assert state is not None
assert state.state == target_state
# Verify coordinator methods were called
assert mock_client.return_value.update_prerelease.mock_calls == [
call(expected_prerelease)
]
assert len(mock_refresh.mock_calls) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_sky_connect/test_switch.py",
"license": "Apache License 2.0",
"lines": 116,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/homeassistant_yellow/test_switch.py | """Test Yellow beta firmware switch entity."""
from unittest.mock import Mock, call, patch
from ha_silabs_firmware_client import FirmwareManifest, FirmwareMetadata
import pytest
from yarl import URL
from homeassistant.components.homeassistant_yellow.const import RADIO_DEVICE
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import HomeAssistant, State
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.common import MockConfigEntry, mock_restore_cache
SWITCH_ENTITY_ID = "switch.home_assistant_yellow_radio_beta_firmware_updates"
TEST_MANIFEST = FirmwareManifest(
url=URL("https://example.org/firmware"),
html_url=URL("https://example.org/release_notes"),
created_at=dt_util.utcnow(),
firmwares=(
FirmwareMetadata(
filename="skyconnect_zigbee_ncp_test.gbl",
checksum="aaa",
size=123,
release_notes="Some release notes go here",
metadata={
"baudrate": 115200,
"ezsp_version": "7.4.4.0",
"fw_type": "zigbee_ncp",
"fw_variant": None,
"metadata_version": 2,
"sdk_version": "4.4.4",
},
url=URL("https://example.org/firmwares/skyconnect_zigbee_ncp_test.gbl"),
),
),
)
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
@pytest.mark.parametrize(
("service", "target_state", "expected_prerelease"),
[
(SERVICE_TURN_ON, STATE_ON, True),
(SERVICE_TURN_OFF, STATE_OFF, False),
],
)
async def test_switch_turn_on_off(
hass: HomeAssistant,
service: str,
target_state: str,
expected_prerelease: bool,
) -> None:
"""Test turning switch on/off updates state and coordinator."""
await async_setup_component(hass, "homeassistant", {})
# Start with opposite state
mock_restore_cache(
hass,
[
State(
SWITCH_ENTITY_ID,
STATE_ON if service == SERVICE_TURN_OFF else STATE_OFF,
)
],
)
# Set up the Yellow integration
yellow_config_entry = MockConfigEntry(
title="Home Assistant Yellow",
domain="homeassistant_yellow",
data={
"firmware": "ezsp",
"firmware_version": "7.3.1.0 build 0",
"device": RADIO_DEVICE,
},
version=1,
minor_version=3,
)
yellow_config_entry.add_to_hass(hass)
with (
patch(
"homeassistant.components.homeassistant_yellow.is_hassio", return_value=True
),
patch(
"homeassistant.components.homeassistant_yellow.get_os_info",
return_value={"board": "yellow"},
),
patch(
"homeassistant.components.homeassistant_hardware.coordinator.FirmwareUpdateClient"
) as mock_client,
patch(
"homeassistant.components.homeassistant_hardware.coordinator.FirmwareUpdateCoordinator.async_refresh"
) as mock_refresh,
):
mock_client.return_value.async_update_data.return_value = TEST_MANIFEST
mock_client.return_value.update_prerelease = Mock()
assert await hass.config_entries.async_setup(yellow_config_entry.entry_id)
await hass.async_block_till_done()
# Reset mocks after setup
mock_client.return_value.update_prerelease.reset_mock()
mock_refresh.reset_mock()
# Call the service
await hass.services.async_call(
SWITCH_DOMAIN,
service,
{ATTR_ENTITY_ID: SWITCH_ENTITY_ID},
blocking=True,
)
# Verify state changed
state = hass.states.get(SWITCH_ENTITY_ID)
assert state is not None
assert state.state == target_state
# Verify coordinator methods were called
assert mock_client.return_value.update_prerelease.mock_calls == [
call(expected_prerelease)
]
assert len(mock_refresh.mock_calls) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/homeassistant_yellow/test_switch.py",
"license": "Apache License 2.0",
"lines": 118,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/inels/common.py | """Common methods used across tests."""
from homeassistant.components import inels
from homeassistant.components.inels.const import DOMAIN
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry
__all__ = [
"MockConfigEntry",
"get_entity_id",
"get_entity_state",
"inels",
"old_entity_and_device_removal",
"set_mock_mqtt",
]
MAC_ADDRESS = "001122334455"
UNIQUE_ID = "C0FFEE"
CONNECTED_INELS_VALUE = b"on\n"
DISCONNECTED_INELS_VALUE = b"off\n"
def get_entity_id(entity_config: dict, index: int) -> str:
"""Construct the entity_id based on the entity_config."""
unique_id = entity_config["unique_id"].lower()
base_id = f"{entity_config['entity_type']}.{MAC_ADDRESS}_{unique_id}_{entity_config['device_type']}"
return f"{base_id}{f'_{index:03}'}" if index is not None else base_id
def get_entity_state(
hass: HomeAssistant, entity_config: dict, index: int
) -> State | None:
"""Return the state of the entity from the state machine."""
entity_id = get_entity_id(entity_config, index)
return hass.states.get(entity_id)
def set_mock_mqtt(
mqtt,
config: dict,
status_value: bytes,
device_available: bool = True,
gw_available: bool = True,
last_value=None,
):
"""Set mock mqtt communication."""
gw_connected_value = '{"status":true}' if gw_available else '{"status":false}'
device_connected_value = (
CONNECTED_INELS_VALUE if device_available else DISCONNECTED_INELS_VALUE
)
mqtt.mock_messages = {
config["gw_connected_topic"]: gw_connected_value,
config["connected_topic"]: device_connected_value,
config["status_topic"]: status_value,
}
mqtt.mock_discovery_all = {config["base_topic"]: status_value}
if last_value is not None:
mqtt.mock_last_value = {config["status_topic"]: last_value}
else:
mqtt.mock_last_value = {}
async def old_entity_and_device_removal(
hass: HomeAssistant, mock_mqtt, platform, entity_config, value_key, index
):
"""Test that old entities are correctly identified and removed across different platforms."""
set_mock_mqtt(
mock_mqtt,
config=entity_config,
status_value=entity_config[value_key],
gw_available=True,
device_available=True,
)
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
title="iNELS",
)
config_entry.add_to_hass(hass)
# Create an old entity
entity_registry = er.async_get(hass)
old_entity = entity_registry.async_get_or_create(
domain=platform,
platform=DOMAIN,
unique_id=f"old_{entity_config['unique_id']}",
suggested_object_id=f"old_inels_{platform}_{entity_config['device_type']}",
config_entry=config_entry,
)
# Create a device and associate it with the old entity
device_registry = dr.async_get(hass)
device = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
identifiers={(DOMAIN, f"old_{entity_config['unique_id']}")},
name=f"iNELS {platform.capitalize()} {entity_config['device_type']}",
manufacturer="iNELS",
model=entity_config["device_type"],
)
# Associate the old entity with the device
entity_registry.async_update_entity(old_entity.entity_id, device_id=device.id)
assert (
device_registry.async_get_device({(DOMAIN, old_entity.unique_id)}) is not None
)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
# The device was discovered, and at this point, the async_remove_old_entities function was called
assert config_entry.runtime_data.devices
assert old_entity.entity_id not in config_entry.runtime_data.old_entities[platform]
# Get the new entity
new_entity = entity_registry.async_get(get_entity_id(entity_config, index).lower())
assert new_entity is not None
# Verify that the new entity is in the registry
assert entity_registry.async_get(new_entity.entity_id) is not None
# Verify that the old entity is no longer in the registry
assert entity_registry.async_get(old_entity.entity_id) is None
# Verify that the device no longer exists in the registry
assert device_registry.async_get_device({(DOMAIN, old_entity.unique_id)}) is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/inels/common.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:tests/components/inels/test_config_flow.py | """Test the iNELS config flow."""
from unittest.mock import patch
from homeassistant.components.inels.const import DOMAIN, TITLE
from homeassistant.components.mqtt import MQTT_CONNECTION_STATE
from homeassistant.config_entries import SOURCE_MQTT, SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.service_info.mqtt import MqttServiceInfo
from tests.common import MockConfigEntry
from tests.typing import MqttMockHAClient
async def test_mqtt_config_single_instance(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""The MQTT test flow is aborted if an entry already exists."""
MockConfigEntry(domain=DOMAIN).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_MQTT}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "single_instance_allowed"
async def test_mqtt_setup(hass: HomeAssistant, mqtt_mock: MqttMockHAClient) -> None:
"""When an MQTT message is received on the discovery topic, it triggers a config flow."""
discovery_info = MqttServiceInfo(
topic="inels/status/MAC_ADDRESS/gw",
payload='{"CUType":"CU3-08M","Status":"Runfast","FW":"02.97.18"}',
qos=0,
retain=False,
subscribed_topic="inels/status/#",
timestamp=None,
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_MQTT}, data=discovery_info
)
assert result["type"] is FlowResultType.FORM
with patch(
"homeassistant.components.inels.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == TITLE
assert result["result"].data == {}
mock_setup_entry.assert_called_once()
async def test_mqtt_abort_invalid_topic(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Check MQTT flow aborts if discovery topic is invalid."""
discovery_info = MqttServiceInfo(
topic="inels/status/MAC_ADDRESS/wrong_topic",
payload='{"CUType":"CU3-08M","Status":"Runfast","FW":"02.97.18"}',
qos=0,
retain=False,
subscribed_topic="inels/status/#",
timestamp=None,
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_MQTT}, data=discovery_info
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "invalid_discovery_info"
async def test_mqtt_abort_empty_payload(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Check MQTT flow aborts if discovery payload is empty."""
discovery_info = MqttServiceInfo(
topic="inels/status/MAC_ADDRESS/gw",
payload="",
qos=0,
retain=False,
subscribed_topic="inels/status/#",
timestamp=None,
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_MQTT}, data=discovery_info
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "invalid_discovery_info"
async def test_mqtt_abort_already_in_progress(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that a second MQTT flow is aborted when one is already in progress."""
discovery_info = MqttServiceInfo(
topic="inels/status/MAC_ADDRESS/gw",
payload='{"CUType":"CU3-08M","Status":"Runfast","FW":"02.97.18"}',
qos=0,
retain=False,
subscribed_topic="inels/status/#",
timestamp=None,
)
# Start first MQTT flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_MQTT}, data=discovery_info
)
assert result["type"] is FlowResultType.FORM
# Try to start second MQTT flow while first is in progress
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_MQTT}, data=discovery_info
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_in_progress"
async def test_user_setup(hass: HomeAssistant, mqtt_mock: MqttMockHAClient) -> None:
"""Test if the user can finish a config flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
with patch(
"homeassistant.components.inels.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == TITLE
assert result["result"].data == {}
mock_setup_entry.assert_called_once()
async def test_user_config_single_instance(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""The user test flow is aborted if an entry already exists."""
MockConfigEntry(domain=DOMAIN).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "single_instance_allowed"
async def test_user_setup_mqtt_not_connected(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""The user setup test flow is aborted when MQTT is not connected."""
mqtt_mock.connected = False
async_dispatcher_send(hass, MQTT_CONNECTION_STATE, False)
await hass.async_block_till_done()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "mqtt_not_connected"
async def test_user_setup_mqtt_not_configured(hass: HomeAssistant) -> None:
"""The user setup test flow is aborted when MQTT is not configured."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "mqtt_not_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/inels/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 145,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/inels/test_init.py | """Tests for iNELS integration."""
from unittest.mock import ANY, AsyncMock, patch
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from . import HA_INELS_PATH
from .common import DOMAIN, inels
from tests.common import MockConfigEntry
from tests.typing import MqttMockHAClient
async def test_ha_mqtt_publish(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that MQTT publish function works correctly."""
config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass)
with (
patch(f"{HA_INELS_PATH}.InelsDiscovery") as mock_discovery_class,
patch(
"homeassistant.config_entries.ConfigEntries.async_forward_entry_setups",
return_value=None,
),
):
mock_discovery = AsyncMock()
mock_discovery.start.return_value = []
mock_discovery_class.return_value = mock_discovery
await inels.async_setup_entry(hass, config_entry)
topic, payload, qos, retain = "test/topic", "test_payload", 1, True
await config_entry.runtime_data.mqtt.publish(topic, payload, qos, retain)
mqtt_mock.async_publish.assert_called_once_with(topic, payload, qos, retain)
async def test_ha_mqtt_subscribe(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that MQTT subscribe function works correctly."""
config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass)
with (
patch(f"{HA_INELS_PATH}.InelsDiscovery") as mock_discovery_class,
patch(
"homeassistant.config_entries.ConfigEntries.async_forward_entry_setups",
return_value=None,
),
):
mock_discovery = AsyncMock()
mock_discovery.start.return_value = []
mock_discovery_class.return_value = mock_discovery
await inels.async_setup_entry(hass, config_entry)
topic = "test/topic"
await config_entry.runtime_data.mqtt.subscribe(topic)
mqtt_mock.async_subscribe.assert_any_call(topic, ANY, 0, "utf-8", None)
async def test_ha_mqtt_not_available(
hass: HomeAssistant, mqtt_mock: MqttMockHAClient
) -> None:
"""Test that ConfigEntryNotReady is raised when MQTT is not available."""
config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass)
with (
patch(
"homeassistant.components.mqtt.async_wait_for_mqtt_client",
return_value=False,
),
pytest.raises(ConfigEntryNotReady, match="MQTT integration not available"),
):
await inels.async_setup_entry(hass, config_entry)
async def test_unload_entry(hass: HomeAssistant, mock_mqtt) -> None:
"""Test unload entry."""
config_entry = MockConfigEntry(domain=DOMAIN, data={})
config_entry.add_to_hass(hass)
config_entry.runtime_data = inels.InelsData(mqtt=mock_mqtt, devices=[])
with patch(
"homeassistant.config_entries.ConfigEntries.async_unload_platforms",
return_value=True,
) as mock_unload_platforms:
result = await inels.async_unload_entry(hass, config_entry)
assert result is True
mock_mqtt.unsubscribe_topics.assert_called_once()
mock_mqtt.unsubscribe_listeners.assert_called_once()
mock_unload_platforms.assert_called_once()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/inels/test_init.py",
"license": "Apache License 2.0",
"lines": 77,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/inels/test_switch.py | """iNELS switch platform testing."""
from unittest.mock import patch
import pytest
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from .common import MAC_ADDRESS, UNIQUE_ID, get_entity_id
DT_07 = "07"
DT_100 = "100"
DT_BITS = "bits"
@pytest.fixture(params=["simple_relay", "relay", "bit"])
def entity_config(request: pytest.FixtureRequest):
"""Fixture to provide parameterized entity configuration for switch tests."""
configs = {
"simple_relay": {
"entity_type": "switch",
"device_type": "simple_relay",
"dev_type": DT_07,
"unique_id": UNIQUE_ID,
"gw_connected_topic": f"inels/connected/{MAC_ADDRESS}/gw",
"connected_topic": f"inels/connected/{MAC_ADDRESS}/{DT_07}/{UNIQUE_ID}",
"status_topic": f"inels/status/{MAC_ADDRESS}/{DT_07}/{UNIQUE_ID}",
"base_topic": f"{MAC_ADDRESS}/{DT_07}/{UNIQUE_ID}",
"switch_on_value": "07\n01\n92\n09\n",
"switch_off_value": "07\n00\n92\n09\n",
},
"relay": {
"entity_type": "switch",
"device_type": "relay",
"dev_type": DT_100,
"unique_id": UNIQUE_ID,
"gw_connected_topic": f"inels/connected/{MAC_ADDRESS}/gw",
"connected_topic": f"inels/connected/{MAC_ADDRESS}/{DT_100}/{UNIQUE_ID}",
"status_topic": f"inels/status/{MAC_ADDRESS}/{DT_100}/{UNIQUE_ID}",
"base_topic": f"{MAC_ADDRESS}/{DT_100}/{UNIQUE_ID}",
"switch_on_value": "07\n00\n0A\n28\n00\n",
"switch_off_value": "06\n00\n0A\n28\n00\n",
"alerts": {
"overflow": "06\n00\n0A\n28\n01\n",
},
},
"bit": {
"entity_type": "switch",
"device_type": "bit",
"dev_type": DT_BITS,
"unique_id": UNIQUE_ID,
"gw_connected_topic": f"inels/connected/{MAC_ADDRESS}/gw",
"connected_topic": f"inels/connected/{MAC_ADDRESS}/{DT_BITS}/{UNIQUE_ID}",
"status_topic": f"inels/status/{MAC_ADDRESS}/{DT_BITS}/{UNIQUE_ID}",
"base_topic": f"{MAC_ADDRESS}/{DT_BITS}/{UNIQUE_ID}",
"switch_on_value": b'{"state":{"000":1,"001":1}}',
"switch_off_value": b'{"state":{"000":0,"001":0}}',
},
}
return configs[request.param]
@pytest.mark.parametrize(
"entity_config", ["simple_relay", "relay", "bit"], indirect=True
)
@pytest.mark.parametrize(
("gw_available", "device_available", "expected_state"),
[
(True, False, STATE_UNAVAILABLE),
(False, True, STATE_UNAVAILABLE),
(True, True, STATE_ON),
],
)
async def test_switch_availability(
hass: HomeAssistant,
setup_entity,
entity_config,
gw_available,
device_available,
expected_state,
) -> None:
"""Test switch availability and state under different gateway and device availability conditions."""
switch_state = await setup_entity(
entity_config,
status_value=entity_config["switch_on_value"],
gw_available=gw_available,
device_available=device_available,
index=0 if entity_config["device_type"] == "bit" else None,
)
assert switch_state is not None
assert switch_state.state == expected_state
@pytest.mark.parametrize(
("entity_config", "index"),
[
("simple_relay", None),
("relay", None),
("bit", 0),
],
indirect=["entity_config"],
)
async def test_switch_turn_on(
hass: HomeAssistant, setup_entity, entity_config, index
) -> None:
"""Test turning on a switch."""
switch_state = await setup_entity(
entity_config, status_value=entity_config["switch_off_value"], index=index
)
assert switch_state is not None
assert switch_state.state == STATE_OFF
with patch("inelsmqtt.devices.Device.set_ha_value") as mock_set_state:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: get_entity_id(entity_config, index)},
blocking=True,
)
await hass.async_block_till_done()
mock_set_state.assert_called_once()
ha_value = mock_set_state.call_args.args[0]
assert getattr(ha_value, entity_config["device_type"])[0].is_on is True
@pytest.mark.parametrize(
("entity_config", "index"),
[
("simple_relay", None),
("relay", None),
("bit", 0),
],
indirect=["entity_config"],
)
async def test_switch_turn_off(
hass: HomeAssistant, setup_entity, entity_config, index
) -> None:
"""Test turning off a switch."""
switch_state = await setup_entity(
entity_config, status_value=entity_config["switch_on_value"], index=index
)
assert switch_state is not None
assert switch_state.state == STATE_ON
with patch("inelsmqtt.devices.Device.set_ha_value") as mock_set_state:
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: get_entity_id(entity_config, index)},
blocking=True,
)
await hass.async_block_till_done()
mock_set_state.assert_called_once()
ha_value = mock_set_state.call_args.args[0]
assert getattr(ha_value, entity_config["device_type"])[0].is_on is False
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/inels/test_switch.py",
"license": "Apache License 2.0",
"lines": 146,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/libre_hardware_monitor/test_init.py | """Tests for the LibreHardwareMonitor init."""
import pytest
from homeassistant.components.libre_hardware_monitor.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import init_integration
from .conftest import VALID_CONFIG
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_lhm_client")
async def test_migration_to_unique_ids(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test that non-unique legacy entity and device IDs are updated."""
legacy_config_entry_v1 = MockConfigEntry(
domain=DOMAIN,
title="192.168.0.20:8085",
data=VALID_CONFIG,
entry_id="test_entry_id",
version=1,
)
legacy_config_entry_v1.add_to_hass(hass)
# Set up devices with legacy device ID
legacy_device_ids = ["amdcpu-0", "gpu-nvidia-0", "motherboard"]
for device_id in legacy_device_ids:
device_registry.async_get_or_create(
config_entry_id=legacy_config_entry_v1.entry_id,
identifiers={(DOMAIN, device_id)}, # Old format without entry_id prefix
name=f"Test Device {device_id}",
)
# Set up entity with legacy entity ID
existing_sensor_id = "lpc-nct6687d-0-voltage-0"
legacy_entity_id = f"lhm-{existing_sensor_id}"
entity_object_id = "sensor.msi_mag_b650m_mortar_wifi_ms_7d76_12v_voltage"
entity_registry.async_get_or_create(
"sensor",
DOMAIN,
legacy_entity_id,
suggested_object_id="msi_mag_b650m_mortar_wifi_ms_7d76_12v_voltage",
config_entry=legacy_config_entry_v1,
)
# Verify state before migration
device_entries_before = dr.async_entries_for_config_entry(
registry=device_registry, config_entry_id=legacy_config_entry_v1.entry_id
)
assert {
next(iter(device.identifiers))[1] for device in device_entries_before
} == set(legacy_device_ids)
assert (
entity_registry.async_get_entity_id("sensor", DOMAIN, legacy_entity_id)
== entity_object_id
)
await init_integration(hass, legacy_config_entry_v1)
# Verify state after migration
device_entries_after = dr.async_entries_for_config_entry(
registry=device_registry, config_entry_id=legacy_config_entry_v1.entry_id
)
expected_unique_device_ids = [
f"{legacy_config_entry_v1.entry_id}_{device_id}"
for device_id in legacy_device_ids
]
assert {
next(iter(device.identifiers))[1] for device in device_entries_after
} == set(expected_unique_device_ids)
entity_entry = entity_registry.async_get(entity_object_id)
assert entity_entry is not None, "Entity should exist after migration"
new_unique_entity_id = f"{legacy_config_entry_v1.entry_id}_{existing_sensor_id}"
assert entity_entry.unique_id == new_unique_entity_id, (
f"Unique ID not migrated: {entity_entry.unique_id}"
)
assert (
entity_registry.async_get_entity_id("sensor", DOMAIN, legacy_entity_id) is None
)
updated_config_entry = hass.config_entries.async_get_entry(
legacy_config_entry_v1.entry_id
)
assert updated_config_entry.version == 2
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/libre_hardware_monitor/test_init.py",
"license": "Apache License 2.0",
"lines": 78,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/london_underground/test_config_flow.py | """Test the London Underground config flow."""
import asyncio
import pytest
from homeassistant.components.london_underground.const import (
CONF_LINE,
DEFAULT_LINES,
DOMAIN,
)
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import issue_registry as ir
async def test_validate_input_success(
hass: HomeAssistant, mock_setup_entry, mock_london_underground_client
) -> None:
"""Test successful validation of TfL API."""
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_LINE: ["Bakerloo", "Central"]},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "London Underground"
assert result["data"] == {}
assert result["options"] == {CONF_LINE: ["Bakerloo", "Central"]}
async def test_options(
hass: HomeAssistant, mock_setup_entry, mock_config_entry
) -> None:
"""Test updating options."""
result = await hass.config_entries.options.async_init(mock_config_entry.entry_id)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={
CONF_LINE: ["Bakerloo", "Central"],
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["data"] == {
CONF_LINE: ["Bakerloo", "Central"],
}
@pytest.mark.parametrize(
("side_effect", "expected_error"),
[
(Exception, "cannot_connect"),
(asyncio.TimeoutError, "timeout_connect"),
],
)
async def test_validate_input_exceptions(
hass: HomeAssistant,
mock_setup_entry,
mock_london_underground_client,
side_effect,
expected_error,
) -> None:
"""Test validation with connection and timeout errors."""
mock_london_underground_client.update.side_effect = side_effect
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_LINE: ["Bakerloo", "Central"]},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"]["base"] == expected_error
# confirm recovery after error
mock_london_underground_client.update.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "London Underground"
assert result["data"] == {}
assert result["options"] == {CONF_LINE: DEFAULT_LINES}
async def test_already_configured(
hass: HomeAssistant,
mock_london_underground_client,
mock_setup_entry,
mock_config_entry,
) -> None:
"""Try (and fail) setting up a config entry when one already exists."""
# Try to start the flow
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "single_instance_allowed"
async def test_yaml_import(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
mock_london_underground_client,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test a YAML sensor is imported and becomes an operational config entry."""
# Set up via YAML which will trigger import and set up the config entry
IMPORT_DATA = {
"platform": "london_underground",
"line": ["Central", "Piccadilly", "Victoria", "Bakerloo", "Northern"],
}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=IMPORT_DATA
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "London Underground"
assert result["data"] == {}
assert result["options"] == {
CONF_LINE: ["Central", "Piccadilly", "Victoria", "Bakerloo", "Northern"]
}
async def test_failed_yaml_import_connection(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
mock_london_underground_client,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test a YAML sensor is imported and becomes an operational config entry."""
# Set up via YAML which will trigger import and set up the config entry
mock_london_underground_client.update.side_effect = asyncio.TimeoutError
IMPORT_DATA = {
"platform": "london_underground",
"line": ["Central", "Piccadilly", "Victoria", "Bakerloo", "Northern"],
}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=IMPORT_DATA
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_failed_yaml_import_already_configured(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
mock_london_underground_client,
caplog: pytest.LogCaptureFixture,
mock_config_entry,
) -> None:
"""Test a YAML sensor is imported and becomes an operational config entry."""
# Set up via YAML which will trigger import and set up the config entry
IMPORT_DATA = {
"platform": "london_underground",
"line": ["Central", "Piccadilly", "Victoria", "Bakerloo", "Northern"],
}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=IMPORT_DATA
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "single_instance_allowed"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/london_underground/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 151,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/london_underground/test_init.py | """Test the London Underground init."""
from homeassistant.core import HomeAssistant
async def test_reload_entry(
hass: HomeAssistant, mock_london_underground_client, mock_config_entry
) -> None:
"""Test reloading the config entry."""
# Test reloading with updated options
hass.config_entries.async_update_entry(
mock_config_entry,
data={},
options={"line": ["Bakerloo", "Central"]},
)
await hass.async_block_till_done()
# Verify that setup was called for each reload
assert len(mock_london_underground_client.mock_calls) > 0
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/london_underground/test_init.py",
"license": "Apache License 2.0",
"lines": 15,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/lunatone/test_config_flow.py | """Define tests for the Lunatone config flow."""
from unittest.mock import AsyncMock
import aiohttp
import pytest
from homeassistant.components.lunatone.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_URL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from . import BASE_URL
from tests.common import MockConfigEntry
async def test_full_flow(
hass: HomeAssistant, mock_lunatone_info: AsyncMock, mock_setup_entry: AsyncMock
) -> None:
"""Test full user flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_URL: BASE_URL},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == BASE_URL
assert result["data"] == {CONF_URL: BASE_URL}
async def test_full_flow_fail_because_of_missing_device_infos(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
) -> None:
"""Test full flow."""
mock_lunatone_info.serial_number = None
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_URL: BASE_URL},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "missing_device_info"}
async def test_device_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test that the flow is aborted when 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.get("type") is FlowResultType.FORM
assert result.get("step_id") == "user"
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_URL: BASE_URL},
)
assert result2.get("type") is FlowResultType.ABORT
assert result2.get("reason") == "already_configured"
@pytest.mark.parametrize(
("exception", "expected_error"),
[
(aiohttp.InvalidUrlClientError(BASE_URL), "invalid_url"),
(aiohttp.ClientConnectionError(), "cannot_connect"),
],
)
async def test_user_step_fail_with_error(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_setup_entry: AsyncMock,
exception: Exception,
expected_error: str,
) -> None:
"""Test user step with an error."""
mock_lunatone_info.async_update.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_URL: BASE_URL},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": expected_error}
mock_lunatone_info.async_update.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{CONF_URL: BASE_URL},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == BASE_URL
assert result["data"] == {CONF_URL: BASE_URL}
async def test_reconfigure(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfigure flow."""
url = "http://10.0.0.100"
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_URL: url}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data == {CONF_URL: url}
@pytest.mark.parametrize(
("exception", "expected_error"),
[
(aiohttp.InvalidUrlClientError(BASE_URL), "invalid_url"),
(aiohttp.ClientConnectionError(), "cannot_connect"),
],
)
async def test_reconfigure_fail_with_error(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
expected_error: str,
) -> None:
"""Test reconfigure flow with an error."""
url = "http://10.0.0.100"
mock_lunatone_info.async_update.side_effect = exception
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_URL: url}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": expected_error}
mock_lunatone_info.async_update.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_URL: url}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data == {CONF_URL: url}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/lunatone/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 150,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/lunatone/test_init.py | """Tests for the Lunatone integration."""
from unittest.mock import AsyncMock
import aiohttp
from homeassistant.components.lunatone.const import DOMAIN, MANUFACTURER
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from . import BASE_URL, PRODUCT_NAME, VERSION, setup_integration
from tests.common import MockConfigEntry
async def test_load_unload_config_entry(
hass: HomeAssistant,
mock_lunatone_devices: AsyncMock,
mock_lunatone_info: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test the Lunatone configuration entry loading/unloading."""
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is ConfigEntryState.LOADED
assert mock_config_entry.unique_id
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, mock_config_entry.unique_id)}
)
assert device_entry is not None
assert device_entry.manufacturer == MANUFACTURER
assert device_entry.sw_version == VERSION
assert device_entry.configuration_url == BASE_URL
assert device_entry.model == PRODUCT_NAME
await hass.config_entries.async_unload(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert not hass.data.get(DOMAIN)
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
async def test_config_entry_not_ready_info_api_fail(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_lunatone_devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Lunatone configuration entry not ready due to a failure in the info API."""
mock_lunatone_info.async_update.side_effect = aiohttp.ClientConnectionError()
await setup_integration(hass, mock_config_entry)
mock_lunatone_info.async_update.assert_called_once()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
mock_lunatone_info.async_update.side_effect = None
await hass.config_entries.async_reload(mock_config_entry.entry_id)
await hass.async_block_till_done()
mock_lunatone_info.async_update.assert_called()
assert mock_config_entry.state is ConfigEntryState.LOADED
async def test_config_entry_not_ready_devices_api_fail(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_lunatone_devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Lunatone configuration entry not ready due to a failure in the devices API."""
mock_lunatone_devices.async_update.side_effect = aiohttp.ClientConnectionError()
await setup_integration(hass, mock_config_entry)
mock_lunatone_info.async_update.assert_called_once()
mock_lunatone_devices.async_update.assert_called_once()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
mock_lunatone_devices.async_update.side_effect = None
await hass.config_entries.async_reload(mock_config_entry.entry_id)
await hass.async_block_till_done()
mock_lunatone_info.async_update.assert_called()
mock_lunatone_devices.async_update.assert_called()
assert mock_config_entry.state is ConfigEntryState.LOADED
async def test_config_entry_not_ready_no_info_data(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Lunatone configuration entry not ready due to missing info data."""
mock_lunatone_info.data = None
await setup_integration(hass, mock_config_entry)
mock_lunatone_info.async_update.assert_called_once()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_config_entry_not_ready_no_devices_data(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_lunatone_devices: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Lunatone configuration entry not ready due to missing devices data."""
mock_lunatone_devices.data = None
await setup_integration(hass, mock_config_entry)
mock_lunatone_info.async_update.assert_called_once()
mock_lunatone_devices.async_update.assert_called_once()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
async def test_config_entry_not_ready_no_serial_number(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the Lunatone configuration entry not ready due to a missing serial number."""
mock_lunatone_info.serial_number = None
await setup_integration(hass, mock_config_entry)
mock_lunatone_info.async_update.assert_called_once()
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/lunatone/test_init.py",
"license": "Apache License 2.0",
"lines": 98,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/lunatone/test_light.py | """Tests for the Lunatone integration."""
import copy
from unittest.mock import AsyncMock
from lunatone_rest_api_client.models import LineStatus
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.light import ATTR_BRIGHTNESS, DOMAIN as LIGHT_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr, entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry
async def test_setup(
hass: HomeAssistant,
mock_lunatone_devices: AsyncMock,
mock_lunatone_info: AsyncMock,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test the Lunatone configuration entry loading/unloading."""
await setup_integration(hass, mock_config_entry)
entities = hass.states.async_all(Platform.LIGHT)
for entity_state in entities:
entity_entry = entity_registry.async_get(entity_state.entity_id)
assert entity_entry
assert entity_entry == snapshot(name=f"{entity_entry.entity_id}-entry")
assert entity_state == snapshot(name=f"{entity_entry.entity_id}-state")
async def test_turn_on_off(
hass: HomeAssistant,
mock_lunatone_devices: AsyncMock,
mock_lunatone_info: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the light can be turned on and off."""
device_id = 1
entity_id = f"light.device_{device_id}"
await setup_integration(hass, mock_config_entry)
async def fake_update():
device = mock_lunatone_devices.data.devices[device_id - 1]
device.features.switchable.status = not device.features.switchable.status
mock_lunatone_devices.async_update.side_effect = fake_update
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
async def test_turn_on_off_with_brightness(
hass: HomeAssistant,
mock_lunatone_devices: AsyncMock,
mock_lunatone_info: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the light can be turned on with brightness."""
device_id = 2
entity_id = f"light.device_{device_id}"
expected_brightness = 128
brightness_percentages = iter([50.0, 0.0, 50.0])
await setup_integration(hass, mock_config_entry)
async def fake_update():
brightness = next(brightness_percentages)
device = mock_lunatone_devices.data.devices[device_id - 1]
device.features.switchable.status = brightness > 0
device.features.dimmable.status = brightness
mock_lunatone_devices.async_update.side_effect = fake_update
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: expected_brightness},
blocking=True,
)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
assert state.attributes["brightness"] == expected_brightness
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_OFF
assert not state.attributes["brightness"]
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_ON
assert state.attributes["brightness"] == expected_brightness
async def test_turn_on_off_broadcast(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_lunatone_devices: AsyncMock,
mock_lunatone_dali_broadcast: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the broadcast light can be turned on and off."""
entity_id = (
f"light.{mock_config_entry.domain}_{mock_config_entry.unique_id}"
f"_line{mock_lunatone_dali_broadcast.line}"
)
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert mock_lunatone_dali_broadcast.fade_to_brightness.await_count == 1
mock_lunatone_dali_broadcast.fade_to_brightness.assert_awaited()
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id, ATTR_BRIGHTNESS: 128},
blocking=True,
)
assert mock_lunatone_dali_broadcast.fade_to_brightness.await_count == 2
mock_lunatone_dali_broadcast.fade_to_brightness.assert_awaited()
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert mock_lunatone_dali_broadcast.fade_to_brightness.await_count == 3
mock_lunatone_dali_broadcast.fade_to_brightness.assert_awaited()
async def test_line_broadcast_available_status(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_lunatone_devices: AsyncMock,
mock_lunatone_dali_broadcast: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test if the broadcast light is available."""
entity_id = (
f"light.{mock_config_entry.domain}_{mock_config_entry.unique_id}"
f"_line{mock_lunatone_dali_broadcast.line}"
)
await setup_integration(hass, mock_config_entry)
async def fake_update():
info_data = copy.deepcopy(mock_lunatone_info.data)
info_data.lines["0"].line_status = LineStatus.NOT_REACHABLE
mock_lunatone_info.data = info_data
mock_lunatone_info.async_update.side_effect = fake_update
state = hass.states.get(entity_id)
assert state
assert state.state != "unavailable"
await mock_config_entry.runtime_data.coordinator_info.async_refresh()
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == "unavailable"
async def test_line_broadcast_line_present(
hass: HomeAssistant,
mock_lunatone_info: AsyncMock,
mock_lunatone_devices: AsyncMock,
mock_lunatone_dali_broadcast: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test if the broadcast light line is present."""
mock_lunatone_dali_broadcast.line = None
await setup_integration(hass, mock_config_entry)
assert not hass.states.async_entity_ids("light")
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/lunatone/test_light.py",
"license": "Apache License 2.0",
"lines": 189,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/matrix/test_react.py | """Test the react service."""
import pytest
from homeassistant.components.matrix import DOMAIN, MatrixBot
from homeassistant.components.matrix.const import (
ATTR_MESSAGE_ID,
ATTR_REACTION,
ATTR_ROOM,
SERVICE_REACT,
)
from homeassistant.core import Event, HomeAssistant
from .conftest import TEST_JOINABLE_ROOMS
async def test_send_message(
hass: HomeAssistant,
matrix_bot: MatrixBot,
image_path,
matrix_events: list[Event],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test the send_message service."""
await hass.async_start()
assert len(matrix_events) == 0
await matrix_bot._login()
# Send a reaction.
room = list(TEST_JOINABLE_ROOMS)[0]
data = {ATTR_MESSAGE_ID: "message_id", ATTR_ROOM: room, ATTR_REACTION: "👍"}
await hass.services.async_call(DOMAIN, SERVICE_REACT, data, blocking=True)
assert f"Message delivered to room '{room}'" in caplog.messages
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/matrix/test_react.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:tests/components/meteo_lt/test_config_flow.py | """Test the Meteo.lt config flow."""
from unittest.mock import AsyncMock
import aiohttp
from homeassistant.components.meteo_lt.const import CONF_PLACE_CODE, DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_user_flow_success(
hass: HomeAssistant, mock_setup_entry: AsyncMock
) -> None:
"""Test user flow shows form and completes successfully."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_PLACE_CODE: "vilnius"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Vilnius"
assert result["data"] == {CONF_PLACE_CODE: "vilnius"}
assert result["result"].unique_id == "vilnius"
assert len(mock_setup_entry.mock_calls) == 1
async def test_duplicate_entry(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test duplicate entry prevention."""
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_PLACE_CODE: "vilnius"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
assert len(mock_setup_entry.mock_calls) == 0
async def test_api_connection_error(
hass: HomeAssistant, mock_meteo_lt_api: AsyncMock
) -> None:
"""Test API connection error during place fetching."""
mock_meteo_lt_api.places = []
mock_meteo_lt_api.fetch_places.side_effect = aiohttp.ClientError(
"Connection failed"
)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_api_timeout_error(
hass: HomeAssistant, mock_meteo_lt_api: AsyncMock
) -> None:
"""Test API timeout error during place fetching."""
mock_meteo_lt_api.places = []
mock_meteo_lt_api.fetch_places.side_effect = TimeoutError("Request timed out")
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "cannot_connect"
async def test_no_places_found(
hass: HomeAssistant, mock_meteo_lt_api: AsyncMock
) -> None:
"""Test when API returns no places."""
mock_meteo_lt_api.places = []
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_places_found"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/meteo_lt/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 76,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/meteo_lt/test_weather.py | """Test Meteo.lt weather entity."""
from collections.abc import Generator
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture(autouse=True)
def override_platforms() -> Generator[None]:
"""Override PLATFORMS."""
with patch("homeassistant.components.meteo_lt.PLATFORMS", [Platform.WEATHER]):
yield
@pytest.mark.freeze_time("2025-09-25 10:00:00")
async def test_weather_entity(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test weather entity."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.freeze_time("2025-09-25 9:00:00")
async def test_forecast_no_limits(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that forecast returns all available data from API without limits."""
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 hass.services.async_call(
"weather",
"get_forecasts",
{"entity_id": "weather.vilnius", "type": "hourly"},
blocking=True,
return_response=True,
)
hourly_forecasts = result["weather.vilnius"]["forecast"]
assert len(hourly_forecasts) == 9
result = await hass.services.async_call(
"weather",
"get_forecasts",
{"entity_id": "weather.vilnius", "type": "daily"},
blocking=True,
return_response=True,
)
daily_forecasts = result["weather.vilnius"]["forecast"]
assert len(daily_forecasts) == 7
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/meteo_lt/test_weather.py",
"license": "Apache License 2.0",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nederlandse_spoorwegen/test_init.py | """Test the Nederlandse Spoorwegen init."""
from syrupy.assertion import SnapshotAssertion
from homeassistant.core import HomeAssistant
import homeassistant.helpers.device_registry as dr
from . import setup_integration
from tests.common import MockConfigEntry
async def test_device_registry_integration(
hass: HomeAssistant,
mock_nsapi,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test device registry integration creates correct devices."""
await setup_integration(hass, mock_config_entry)
await hass.async_block_till_done()
# Get all devices created for this config entry
device_entries = dr.async_entries_for_config_entry(
device_registry, mock_config_entry.entry_id
)
# Snapshot the devices to ensure they have the correct structure
assert device_entries == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nederlandse_spoorwegen/test_init.py",
"license": "Apache License 2.0",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/niko_home_control/test_scene.py | """Tests for the Niko Home Control Scene platform."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.scene import DOMAIN as SCENE_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_ON, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import find_update_callback, setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.freeze_time("2025-10-10 21:00:00")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_niko_home_control_connection: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.niko_home_control.PLATFORMS", [Platform.SCENE]
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize("scene_id", [0])
async def test_activate_scene(
hass: HomeAssistant,
mock_niko_home_control_connection: AsyncMock,
mock_config_entry: MockConfigEntry,
scene_id: int,
entity_registry: er.EntityRegistry,
) -> None:
"""Test activating the scene."""
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
SCENE_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "scene.scene"},
blocking=True,
)
mock_niko_home_control_connection.scenes[scene_id].activate.assert_called_once()
async def test_updating(
hass: HomeAssistant,
mock_niko_home_control_connection: AsyncMock,
mock_config_entry: MockConfigEntry,
scene: AsyncMock,
) -> None:
"""Test scene state recording after activation."""
await setup_integration(hass, mock_config_entry)
# Resolve the created scene entity dynamically
entity_entries = er.async_entries_for_config_entry(
er.async_get(hass), mock_config_entry.entry_id
)
scene_entities = [e for e in entity_entries if e.domain == SCENE_DOMAIN]
assert scene_entities, "No scene entities registered"
entity_id = scene_entities[0].entity_id
# Capture current state (could be unknown or a timestamp depending on implementation)
before = hass.states.get(entity_id)
assert before is not None
# Simulate a device-originated update for the scene (controller callback)
await find_update_callback(mock_niko_home_control_connection, scene.id)(0)
await hass.async_block_till_done()
after = hass.states.get(entity_id)
assert after is not None
assert after.state != before.state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/niko_home_control/test_scene.py",
"license": "Apache License 2.0",
"lines": 65,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nintendo_parental_controls/test_config_flow.py | """Test the Nintendo Switch parental controls config flow."""
from unittest.mock import AsyncMock
from pynintendoauth.exceptions import HttpException, InvalidSessionTokenException
from homeassistant import config_entries
from homeassistant.components.nintendo_parental_controls.const import (
CONF_SESSION_TOKEN,
DOMAIN,
)
from homeassistant.const import CONF_API_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .const import ACCOUNT_ID, API_TOKEN, LOGIN_URL
from tests.common import MockConfigEntry
async def test_full_flow(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_nintendo_authenticator: AsyncMock,
mock_nintendo_api: AsyncMock,
) -> None:
"""Test a full and successful config flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result is not None
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert "link" in result["description_placeholders"]
assert result["description_placeholders"]["link"] == LOGIN_URL
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: API_TOKEN}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == ACCOUNT_ID
assert result["data"][CONF_SESSION_TOKEN] == API_TOKEN
assert result["result"].unique_id == ACCOUNT_ID
async def test_already_configured(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_authenticator: AsyncMock,
mock_nintendo_api: AsyncMock,
) -> None:
"""Test that the flow aborts if the account is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: API_TOKEN}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_invalid_auth(
hass: HomeAssistant,
mock_nintendo_authenticator: AsyncMock,
mock_nintendo_api: AsyncMock,
) -> None:
"""Test handling of invalid authentication."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result is not None
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert "link" in result["description_placeholders"]
# Simulate invalid authentication by raising an exception
mock_nintendo_authenticator.async_complete_login.side_effect = (
InvalidSessionTokenException(status_code=401, message="Test")
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: "invalid_token"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "invalid_auth"}
# Now ensure that the flow can be recovered
mock_nintendo_authenticator.async_complete_login.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: API_TOKEN}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == ACCOUNT_ID
assert result["data"][CONF_SESSION_TOKEN] == API_TOKEN
assert result["result"].unique_id == ACCOUNT_ID
async def test_missing_devices(
hass: HomeAssistant,
mock_nintendo_authenticator: AsyncMock,
mock_nintendo_api: AsyncMock,
) -> None:
"""Test handling of no devices found."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result is not None
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert "link" in result["description_placeholders"]
mock_nintendo_authenticator.async_complete_login.side_effect = None
mock_nintendo_api.async_get_account_devices.side_effect = HttpException(
status_code=404, message="TEST"
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: API_TOKEN}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "no_devices_found"
async def test_cannot_connect(
hass: HomeAssistant,
mock_nintendo_authenticator: AsyncMock,
mock_nintendo_api: AsyncMock,
) -> None:
"""Test handling of connection errors during device discovery."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result is not None
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert "link" in result["description_placeholders"]
mock_nintendo_authenticator.async_complete_login.side_effect = None
mock_nintendo_api.async_get_account_devices.side_effect = HttpException(
status_code=500, message="TEST"
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: API_TOKEN}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
# Test we can recover from the error
mock_nintendo_api.async_get_account_devices.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: API_TOKEN}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == ACCOUNT_ID
assert result["data"][CONF_SESSION_TOKEN] == API_TOKEN
assert result["result"].unique_id == ACCOUNT_ID
async def test_reauthentication_success(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_authenticator: AsyncMock,
) -> None:
"""Test successful reauthentication."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["step_id"] == "reauth_confirm"
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: API_TOKEN}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
async def test_reauthentication_fail(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_authenticator: AsyncMock,
) -> None:
"""Test failed reauthentication."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
assert result["step_id"] == "reauth_confirm"
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {}
# Simulate invalid authentication by raising an exception
mock_nintendo_authenticator.async_complete_login.side_effect = (
InvalidSessionTokenException(status_code=401, message="Test")
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: API_TOKEN}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {"base": "invalid_auth"}
# Now ensure that the flow can be recovered
mock_nintendo_authenticator.async_complete_login.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={CONF_API_TOKEN: API_TOKEN}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nintendo_parental_controls/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 183,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nintendo_parental_controls/test_coordinator.py | """Test coordinator error handling."""
from unittest.mock import AsyncMock
from pynintendoauth.exceptions import (
HttpException,
InvalidOAuthConfigurationException,
InvalidSessionTokenException,
)
from pynintendoparental.exceptions import NoDevicesFoundException
import pytest
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
("exception", "translation_key", "expected_state", "expected_log_message"),
[
(
InvalidOAuthConfigurationException(
status_code=401, message="Authentication failed"
),
"invalid_auth",
ConfigEntryState.SETUP_ERROR,
None,
),
(
NoDevicesFoundException(),
"no_devices_found",
ConfigEntryState.SETUP_ERROR,
None,
),
(
HttpException(
status_code=400, error_code="update_required", message="Update required"
),
"update_required",
ConfigEntryState.SETUP_ERROR,
None,
),
(
HttpException(
status_code=500, error_code="unknown", message="Unknown error"
),
None,
ConfigEntryState.SETUP_RETRY,
None,
),
(
InvalidSessionTokenException(
status_code=403, error_code="invalid_token", message="Invalid token"
),
None,
ConfigEntryState.SETUP_RETRY,
"Session token invalid, will renew on next update",
),
],
)
async def test_update_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
entity_registry: er.EntityRegistry,
caplog: pytest.LogCaptureFixture,
exception: Exception,
translation_key: str,
expected_state: ConfigEntryState,
expected_log_message: str | None,
) -> None:
"""Test handling of update errors."""
mock_nintendo_client.update.side_effect = exception
await setup_integration(hass, mock_config_entry)
# Ensure no entities are created
entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert len(entries) == 0
# Ensure the config entry is marked as expected state
assert mock_config_entry.state is expected_state
# Ensure the correct translation key is used in the error
assert mock_config_entry.error_reason_translation_key == translation_key
# If there's an expected log message, check that it was logged
if expected_log_message:
assert expected_log_message in caplog.text
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nintendo_parental_controls/test_coordinator.py",
"license": "Apache License 2.0",
"lines": 83,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nintendo_parental_controls/test_init.py | """Test __init__ error handling."""
from unittest.mock import AsyncMock
from pynintendoauth.exceptions import InvalidOAuthConfigurationException
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry
async def test_invalid_authentication(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_authenticator: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test handling of invalid authentication."""
mock_nintendo_authenticator.async_complete_login.side_effect = ValueError
await setup_integration(hass, mock_config_entry)
# Ensure no entities are created
entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert len(entries) == 0
# Ensure the config entry is marked as error
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
async def test_reauth_flow(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_authenticator: AsyncMock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the reauth flow is triggered."""
mock_nintendo_authenticator.async_complete_login.side_effect = (
InvalidOAuthConfigurationException(
status_code=401, message="Authentication failed"
)
)
await setup_integration(hass, mock_config_entry)
# Ensure no entities are created
entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
assert len(entries) == 0
# Ensure the config entry is marked as needing reauth
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
assert mock_config_entry.error_reason_translation_key == "auth_expired"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nintendo_parental_controls/test_init.py",
"license": "Apache License 2.0",
"lines": 45,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nintendo_parental_controls/test_number.py | """Test number platform for Nintendo Parental Controls."""
from unittest.mock import AsyncMock, patch
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
async def test_number(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test number platform."""
with patch(
"homeassistant.components.nintendo_parental_controls._PLATFORMS",
[Platform.NUMBER],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_set_number(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
mock_nintendo_device: AsyncMock,
) -> None:
"""Test number platform service."""
with patch(
"homeassistant.components.nintendo_parental_controls._PLATFORMS",
[Platform.NUMBER],
):
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
service_data={ATTR_VALUE: "120"},
target={ATTR_ENTITY_ID: "number.home_assistant_test_max_screentime_today"},
blocking=True,
)
assert len(mock_nintendo_device.update_max_daily_playtime.mock_calls) == 1
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nintendo_parental_controls/test_number.py",
"license": "Apache License 2.0",
"lines": 47,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nintendo_parental_controls/test_sensor.py | """Test sensor platform."""
from unittest.mock import AsyncMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_sensor(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test sensor platform."""
with patch(
"homeassistant.components.nintendo_parental_controls._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/nintendo_parental_controls/test_sensor.py",
"license": "Apache License 2.0",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nintendo_parental_controls/test_services.py | """Test Nintendo Parental Controls service calls."""
from unittest.mock import AsyncMock
import pytest
from homeassistant.components.nintendo_parental_controls.const import (
ATTR_BONUS_TIME,
DOMAIN,
)
from homeassistant.components.nintendo_parental_controls.services import (
NintendoParentalServices,
)
from homeassistant.const import ATTR_DEVICE_ID
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import device_registry as dr
from . import setup_integration
from tests.common import MockConfigEntry
async def test_add_bonus_time(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
mock_nintendo_device: AsyncMock,
) -> None:
"""Test add bonus time service."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "testdevid")})
assert device_entry
await hass.services.async_call(
DOMAIN,
NintendoParentalServices.ADD_BONUS_TIME,
{
ATTR_DEVICE_ID: device_entry.id,
ATTR_BONUS_TIME: 15,
},
blocking=True,
)
assert len(mock_nintendo_device.add_extra_time.mock_calls) == 1
async def test_add_bonus_time_invalid_device(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
) -> None:
"""Test add bonus time service."""
await setup_integration(hass, mock_config_entry)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
NintendoParentalServices.ADD_BONUS_TIME,
{
ATTR_DEVICE_ID: "invalid_device_id",
ATTR_BONUS_TIME: 15,
},
blocking=True,
)
assert err.value.translation_domain == DOMAIN
assert err.value.translation_key == "device_not_found"
async def test_add_bonus_time_device_id_not_nintendo(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
) -> None:
"""Test add bonus time service with a device that is not a valid Nintendo device."""
await setup_integration(hass, mock_config_entry)
# Create a device that does not have a Nintendo identifier
device_entry = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "00:11:22:33:44:55")},
)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
DOMAIN,
NintendoParentalServices.ADD_BONUS_TIME,
{
ATTR_DEVICE_ID: device_entry.id,
ATTR_BONUS_TIME: 15,
},
blocking=True,
)
assert err.value.translation_domain == DOMAIN
assert err.value.translation_key == "invalid_device"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nintendo_parental_controls/test_services.py",
"license": "Apache License 2.0",
"lines": 81,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nintendo_parental_controls/test_switch.py | """Test switch platform."""
from unittest.mock import AsyncMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.switch import (
DOMAIN as SWITCH_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_switch(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test switch platform."""
with patch(
"homeassistant.components.nintendo_parental_controls._PLATFORMS",
[Platform.SWITCH],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_suspend_software(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
mock_nintendo_device: AsyncMock,
) -> None:
"""Test switch platform."""
with patch(
"homeassistant.components.nintendo_parental_controls._PLATFORMS",
[Platform.SWITCH],
):
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
target={ATTR_ENTITY_ID: "switch.home_assistant_test_suspend_software"},
blocking=True,
)
assert len(mock_nintendo_device.set_restriction_mode.mock_calls) == 1
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
target={ATTR_ENTITY_ID: "switch.home_assistant_test_suspend_software"},
blocking=True,
)
assert len(mock_nintendo_device.set_restriction_mode.mock_calls) == 2
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nintendo_parental_controls/test_switch.py",
"license": "Apache License 2.0",
"lines": 53,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nintendo_parental_controls/test_time.py | """Test the time platform."""
from unittest.mock import AsyncMock, patch
from pynintendoparental.exceptions import BedtimeOutOfRangeError
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.time import (
ATTR_TIME,
DOMAIN as TIME_DOMAIN,
SERVICE_SET_VALUE,
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
async def test_time(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test time platform."""
with patch(
"homeassistant.components.nintendo_parental_controls._PLATFORMS",
[Platform.TIME],
):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.parametrize(
("entity_id", "new_value", "called_function_name"),
[
("time.home_assistant_test_bedtime_alarm", "20:00:00", "set_bedtime_alarm"),
(
"time.home_assistant_test_bedtime_end_time",
"06:30:00",
"set_bedtime_end_time",
),
],
)
async def test_set_time(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
mock_nintendo_device: AsyncMock,
entity_id: str,
new_value: str,
called_function_name: str,
) -> None:
"""Test time platform service validation errors."""
with patch(
"homeassistant.components.nintendo_parental_controls._PLATFORMS",
[Platform.TIME],
):
await setup_integration(hass, mock_config_entry)
await hass.services.async_call(
TIME_DOMAIN,
SERVICE_SET_VALUE,
service_data={ATTR_TIME: new_value},
target={ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert len(getattr(mock_nintendo_device, called_function_name).mock_calls) == 1
@pytest.mark.parametrize(
("entity_id", "new_value", "translation_key", "called_function_name"),
[
(
"time.home_assistant_test_bedtime_alarm",
"03:00:00",
"bedtime_alarm_out_of_range",
"set_bedtime_alarm",
),
(
"time.home_assistant_test_bedtime_end_time",
"10:00:00",
"bedtime_end_time_out_of_range",
"set_bedtime_end_time",
),
],
)
async def test_set_time_service_exceptions(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_nintendo_client: AsyncMock,
mock_nintendo_device: AsyncMock,
entity_id: str,
new_value: str,
translation_key: str,
called_function_name: str,
) -> None:
"""Test time platform service validation errors."""
getattr(
mock_nintendo_device, called_function_name
).side_effect = BedtimeOutOfRangeError(None)
with patch(
"homeassistant.components.nintendo_parental_controls._PLATFORMS",
[Platform.TIME],
):
await setup_integration(hass, mock_config_entry)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
TIME_DOMAIN,
SERVICE_SET_VALUE,
service_data={ATTR_TIME: new_value},
target={ATTR_ENTITY_ID: entity_id},
blocking=True,
)
assert len(getattr(mock_nintendo_device, called_function_name).mock_calls) == 1
assert err.value.translation_key == translation_key
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nintendo_parental_controls/test_time.py",
"license": "Apache License 2.0",
"lines": 110,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/nmap_tracker/test_init.py | """Tests for the nmap_tracker component."""
from unittest.mock import patch
from homeassistant.components.nmap_tracker.const import (
CONF_HOME_INTERVAL,
CONF_HOSTS_EXCLUDE,
CONF_HOSTS_LIST,
CONF_MAC_EXCLUDE,
CONF_OPTIONS,
DEFAULT_OPTIONS,
DOMAIN,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_EXCLUDE, CONF_HOSTS
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
async def test_migrate_entry(hass: HomeAssistant) -> None:
"""Test migrating a config entry from version 1 to version 2."""
mock_entry = MockConfigEntry(
unique_id="test_nmap_tracker",
domain=DOMAIN,
version=1,
options={
CONF_HOSTS: "192.168.1.0/24,192.168.2.0/24",
CONF_HOME_INTERVAL: 3,
CONF_OPTIONS: DEFAULT_OPTIONS,
CONF_EXCLUDE: "192.168.1.1,192.168.2.2",
},
title="Nmap Test Tracker",
)
mock_entry.add_to_hass(hass)
# Prevent the scanner from starting
with patch(
"homeassistant.components.nmap_tracker.NmapDeviceScanner._async_start_scanner",
return_value=None,
):
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
# Check that it has a source_id now
updated_entry = hass.config_entries.async_get_entry(mock_entry.entry_id)
assert updated_entry
assert updated_entry.version == 1
assert updated_entry.minor_version == 2
assert updated_entry.options == {
CONF_EXCLUDE: "192.168.1.1,192.168.2.2",
CONF_HOME_INTERVAL: 3,
CONF_HOSTS: "192.168.1.0/24,192.168.2.0/24",
CONF_HOSTS_EXCLUDE: ["192.168.1.1", "192.168.2.2"],
CONF_HOSTS_LIST: ["192.168.1.0/24", "192.168.2.0/24"],
CONF_MAC_EXCLUDE: [],
CONF_OPTIONS: DEFAULT_OPTIONS,
}
assert updated_entry.state is ConfigEntryState.LOADED
async def test_migrate_entry_fails_on_downgrade(hass: HomeAssistant) -> None:
"""Test that migration fails when user downgrades from a future version."""
mock_entry = MockConfigEntry(
unique_id="test_nmap_tracker",
domain=DOMAIN,
version=2,
options={
CONF_HOSTS: ["192.168.1.0/24"],
CONF_HOME_INTERVAL: 3,
CONF_OPTIONS: DEFAULT_OPTIONS,
CONF_EXCLUDE: ["192.168.1.1"],
},
title="Nmap Test Tracker",
)
mock_entry.add_to_hass(hass)
# Prevent the scanner from starting
with patch(
"homeassistant.components.nmap_tracker.NmapDeviceScanner._async_start_scanner",
return_value=None,
):
assert await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
# Check that entry is in migration error state
updated_entry = hass.config_entries.async_get_entry(mock_entry.entry_id)
assert updated_entry
assert updated_entry.version == 2
assert updated_entry.state is ConfigEntryState.MIGRATION_ERROR
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/nmap_tracker/test_init.py",
"license": "Apache License 2.0",
"lines": 80,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/octoprint/test_number.py | """The tests for OctoPrint number module."""
from datetime import UTC, datetime
from typing import Any
from unittest.mock import 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, STATE_UNKNOWN, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture
def platform() -> Platform:
"""Fixture to specify platform."""
return Platform.NUMBER
@pytest.fixture
def job() -> dict[str, Any]:
"""Job fixture."""
return __standard_job()
@pytest.mark.parametrize(
"printer",
[
{
"state": {
"flags": {"printing": True},
"text": "Operational",
},
"temperature": {
"tool0": {"actual": 18.83136, "target": 37.83136},
"tool1": {"actual": 21.0, "target": 31.0},
"bed": {"actual": 25.5, "target": 60.0},
},
},
],
)
@pytest.mark.freeze_time(datetime(2020, 2, 20, 9, 10, 13, 543, tzinfo=UTC))
async def test_numbers(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
init_integration: MockConfigEntry,
) -> None:
"""Test the underlying number entities."""
await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id)
@pytest.mark.parametrize(
"printer",
[
{
"state": {
"flags": {"printing": True, "paused": False},
"text": "Operational",
},
"temperature": {
"tool0": {"actual": 18.83136, "target": None},
"bed": {"actual": 25.5, "target": None},
},
},
],
)
@pytest.mark.freeze_time(datetime(2020, 2, 20, 9, 10, 0))
@pytest.mark.usefixtures("init_integration")
async def test_numbers_no_target_temp(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
) -> None:
"""Test the number entities when target temperature is None."""
state = hass.states.get("number.octoprint_extruder_temperature")
assert state is not None
assert state.state == STATE_UNKNOWN
assert state.name == "OctoPrint Extruder temperature"
entry = entity_registry.async_get("number.octoprint_extruder_temperature")
assert entry.unique_id == "uuid_tool0_temperature"
state = hass.states.get("number.octoprint_bed_temperature")
assert state is not None
assert state.state == STATE_UNKNOWN
assert state.name == "OctoPrint Bed temperature"
entry = entity_registry.async_get("number.octoprint_bed_temperature")
assert entry.unique_id == "uuid_bed_temperature"
@pytest.mark.parametrize(
"printer",
[
{
"state": {
"flags": {"printing": False},
"text": "Operational",
},
"temperature": {"tool0": {"actual": 18.83136, "target": 25.0}},
},
],
)
@pytest.mark.freeze_time(datetime(2020, 2, 20, 9, 10, 0))
@pytest.mark.usefixtures("init_integration")
async def test_set_tool_temp(
hass: HomeAssistant,
) -> None:
"""Test setting tool temperature via number entity."""
with patch(
"pyoctoprintapi.OctoprintClient.set_tool_temperature"
) as mock_set_tool_temp:
entity_component = hass.data[NUMBER_DOMAIN]
entity = entity_component.get_entity("number.octoprint_extruder_temperature")
assert entity is not None
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity.entity_id, ATTR_VALUE: 200.4},
blocking=True,
)
assert len(mock_set_tool_temp.mock_calls) == 1
# Verify that we pass integer, expected by the pyoctoprintapi
mock_set_tool_temp.assert_called_with("tool0", 200)
@pytest.mark.parametrize(
"printer",
[
{
"state": {
"flags": {"printing": False},
"text": "Operational",
},
"temperature": {"bed": {"actual": 20.0, "target": 50.0}},
},
],
)
@pytest.mark.freeze_time(datetime(2020, 2, 20, 9, 10, 0))
@pytest.mark.usefixtures("init_integration")
async def test_set_bed_temp(
hass: HomeAssistant,
) -> None:
"""Test setting bed temperature via number entity."""
with patch(
"pyoctoprintapi.OctoprintClient.set_bed_temperature"
) as mock_set_bed_temp:
entity_component = hass.data[NUMBER_DOMAIN]
entity = entity_component.get_entity("number.octoprint_bed_temperature")
assert entity is not None
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity.entity_id, ATTR_VALUE: 80.6},
blocking=True,
)
assert len(mock_set_bed_temp.mock_calls) == 1
# Verify that we pass integer, expected by the pyoctoprintapi, and that it's rounded down
mock_set_bed_temp.assert_called_with(80)
@pytest.mark.parametrize(
"printer",
[
{
"state": {
"flags": {"printing": False},
"text": "Operational",
},
"temperature": {
"tool0": {"actual": 20.0, "target": 30.0},
"tool1": {"actual": 21.0, "target": 31.0},
},
},
],
)
@pytest.mark.freeze_time(datetime(2020, 2, 20, 9, 10, 0))
@pytest.mark.usefixtures("init_integration")
async def test_set_tool_n_temp(
hass: HomeAssistant,
) -> None:
"""Test setting tool temperature via number entity when multiple tools are present."""
with patch(
"pyoctoprintapi.OctoprintClient.set_tool_temperature"
) as mock_set_tool_temp:
entity_component = hass.data[NUMBER_DOMAIN]
entity = entity_component.get_entity("number.octoprint_extruder_1_temperature")
assert entity is not None
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity.entity_id, ATTR_VALUE: 41.0},
blocking=True,
)
assert len(mock_set_tool_temp.mock_calls) == 1
# Verify that we pass integer, expected by the pyoctoprintapi
mock_set_tool_temp.assert_called_with("tool1", 41)
@pytest.mark.parametrize("printer", [None])
@pytest.mark.freeze_time(datetime(2020, 2, 20, 9, 10, 0))
@pytest.mark.usefixtures("init_integration")
async def test_numbers_printer_disconnected(
hass: HomeAssistant,
) -> None:
"""Test number entities when printer is disconnected."""
# When printer is disconnected, no number entities should be created
state = hass.states.get("number.octoprint_tool0_temperature")
assert state is None
state = hass.states.get("number.octoprint_bed_temperature")
assert state is None
def __standard_job():
return {
"job": {
"averagePrintTime": 6500,
"estimatedPrintTime": 6000,
"filament": {"tool0": {"length": 3000, "volume": 7}},
"file": {
"date": 1577836800,
"display": "Test File Name",
"name": "Test_File_Name.gcode",
"origin": "local",
"path": "Folder1/Folder2/Test_File_Name.gcode",
"size": 123456789,
},
"lastPrintTime": 12345.678,
"user": "testUser",
},
"progress": {"completion": 50, "printTime": 600, "printTimeLeft": 6000},
"state": "Printing",
}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/octoprint/test_number.py",
"license": "Apache License 2.0",
"lines": 216,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/onvif/test_util.py | """Test ONVIF util functions."""
from homeassistant.components.onvif.models import Event
from homeassistant.components.onvif.util import build_event_entity_names
# Example device UID that would be used as prefix
TEST_DEVICE_UID = "aa:bb:cc:dd:ee:ff"
def test_build_event_entity_names_unique_names() -> None:
"""Test build_event_entity_names with unique event names."""
events = [
Event(
uid=f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/Motion_00000_00000_00000",
name="Cell Motion Detection",
platform="binary_sensor",
),
Event(
uid=f"{TEST_DEVICE_UID}_tns1:RuleEngine/PeopleDetector/People_00000_00000_00000",
name="Person Detection",
platform="binary_sensor",
),
Event(
uid=f"{TEST_DEVICE_UID}_tns1:RuleEngine/MyRuleDetector/VehicleDetect_00000",
name="Vehicle Detection",
platform="binary_sensor",
),
]
result = build_event_entity_names(events)
assert result == {
f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/Motion_00000_00000_00000": "Cell Motion Detection",
f"{TEST_DEVICE_UID}_tns1:RuleEngine/PeopleDetector/People_00000_00000_00000": "Person Detection",
f"{TEST_DEVICE_UID}_tns1:RuleEngine/MyRuleDetector/VehicleDetect_00000": "Vehicle Detection",
}
def test_build_event_entity_names_duplicated() -> None:
"""Test with multiple motion detection zones (realistic camera scenario)."""
# Realistic scenario: Camera with motion detection on multiple source tokens
events = [
Event(
uid=f"{TEST_DEVICE_UID}_tns1:VideoSource/MotionAlarm_00200",
name="Motion Alarm",
platform="binary_sensor",
),
Event(
uid=f"{TEST_DEVICE_UID}_tns1:VideoSource/MotionAlarm_00100",
name="Motion Alarm",
platform="binary_sensor",
),
Event(
uid=f"{TEST_DEVICE_UID}_tns1:VideoSource/MotionAlarm_00000",
name="Motion Alarm",
platform="binary_sensor",
),
]
result = build_event_entity_names(events)
# Should be sorted by UID (source tokens: 00000, 00100, 00200)
assert result == {
f"{TEST_DEVICE_UID}_tns1:VideoSource/MotionAlarm_00000": "Motion Alarm 1",
f"{TEST_DEVICE_UID}_tns1:VideoSource/MotionAlarm_00100": "Motion Alarm 2",
f"{TEST_DEVICE_UID}_tns1:VideoSource/MotionAlarm_00200": "Motion Alarm 3",
}
def test_build_event_entity_names_mixed_events() -> None:
"""Test realistic mix of unique and duplicate event names."""
events = [
# Multiple person detection with different rules
Event(
uid=f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/People_00000_00000_00000",
name="Person Detection",
platform="binary_sensor",
),
Event(
uid=f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/People_00000_00000_00100",
name="Person Detection",
platform="binary_sensor",
),
# Unique tamper detection
Event(
uid=f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/Tamper_00000_00000_00000",
name="Tamper Detection",
platform="binary_sensor",
),
# Multiple line crossings with different rules
Event(
uid=f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/LineCross_00000_00000_00000",
name="Line Detector Crossed",
platform="binary_sensor",
),
Event(
uid=f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/LineCross_00000_00000_00100",
name="Line Detector Crossed",
platform="binary_sensor",
),
]
result = build_event_entity_names(events)
assert result == {
f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/People_00000_00000_00000": "Person Detection 1",
f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/People_00000_00000_00100": "Person Detection 2",
f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/Tamper_00000_00000_00000": "Tamper Detection",
f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/LineCross_00000_00000_00000": "Line Detector Crossed 1",
f"{TEST_DEVICE_UID}_tns1:RuleEngine/CellMotionDetector/LineCross_00000_00000_00100": "Line Detector Crossed 2",
}
def test_build_event_entity_names_empty() -> None:
"""Test build_event_entity_names with empty list."""
assert build_event_entity_names([]) == {}
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/onvif/test_util.py",
"license": "Apache License 2.0",
"lines": 100,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/openrgb/test_config_flow.py | """Tests for the OpenRGB config flow."""
import socket
from openrgb.utils import OpenRGBDisconnected, SDKVersionError
import pytest
from homeassistant.components.openrgb.const import DOMAIN
from homeassistant.config_entries import SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
@pytest.mark.usefixtures("mock_setup_entry", "mock_openrgb_client")
async def test_full_user_flow(hass: HomeAssistant) -> None:
"""Test the full user flow from start to finish."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_NAME: "Test Computer",
CONF_HOST: "127.0.0.1",
CONF_PORT: 6742,
},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Test Computer"
assert result["data"] == {
CONF_NAME: "Test Computer",
CONF_HOST: "127.0.0.1",
CONF_PORT: 6742,
}
@pytest.mark.parametrize(
("exception", "error_key"),
[
(ConnectionRefusedError, "cannot_connect"),
(OpenRGBDisconnected, "cannot_connect"),
(TimeoutError, "cannot_connect"),
(socket.gaierror, "cannot_connect"),
(SDKVersionError, "cannot_connect"),
(RuntimeError("Test error"), "unknown"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_user_flow_errors(
hass: HomeAssistant, exception: Exception, error_key: str, mock_openrgb_client
) -> None:
"""Test user flow with various errors."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
mock_openrgb_client.client_class_mock.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_NAME: "Test Server", CONF_HOST: "127.0.0.1", CONF_PORT: 6742},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": error_key}
# Test recovery from error
mock_openrgb_client.client_class_mock.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_NAME: "Test Server", CONF_HOST: "127.0.0.1", CONF_PORT: 6742},
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Test Server"
assert result["data"] == {
CONF_NAME: "Test Server",
CONF_HOST: "127.0.0.1",
CONF_PORT: 6742,
}
@pytest.mark.usefixtures("mock_setup_entry", "mock_openrgb_client")
async def test_user_flow_already_configured(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test user flow when device is already configured."""
mock_config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_NAME: "Test Server", CONF_HOST: "127.0.0.1", CONF_PORT: 6742},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("mock_setup_entry", "mock_openrgb_client")
async def test_user_flow_duplicate_entry(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test user flow when trying to add duplicate host/port combination."""
mock_config_entry.add_to_hass(hass)
# Create another config entry with different host/port
other_entry = MockConfigEntry(
domain=DOMAIN,
title="Other Computer",
data={
CONF_NAME: "Other Computer",
CONF_HOST: "192.168.1.200",
CONF_PORT: 6743,
},
entry_id="01J0EXAMPLE0CONFIGENTRY01",
)
other_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
)
# Try to add entry with same host/port as other_entry
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_NAME: "Yet Another Computer",
CONF_HOST: "192.168.1.200",
CONF_PORT: 6743,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.usefixtures("mock_setup_entry", "mock_openrgb_client")
async def test_reconfigure_flow(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test the reconfiguration flow."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "192.168.1.100",
CONF_PORT: 6743,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "192.168.1.100"
assert mock_config_entry.data[CONF_PORT] == 6743
@pytest.mark.parametrize(
("exception", "error_key"),
[
(ConnectionRefusedError, "cannot_connect"),
(OpenRGBDisconnected, "cannot_connect"),
(TimeoutError, "cannot_connect"),
(socket.gaierror, "cannot_connect"),
(SDKVersionError, "cannot_connect"),
(RuntimeError("Test error"), "unknown"),
],
)
@pytest.mark.usefixtures("mock_setup_entry")
async def test_reconfigure_flow_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
exception: Exception,
error_key: str,
mock_openrgb_client,
) -> None:
"""Test reconfiguration flow with various errors."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
mock_openrgb_client.client_class_mock.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "192.168.1.100", CONF_PORT: 6743},
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {"base": error_key}
# Test recovery from error
mock_openrgb_client.client_class_mock.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_HOST: "192.168.1.100", CONF_PORT: 6743},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "192.168.1.100"
assert mock_config_entry.data[CONF_PORT] == 6743
@pytest.mark.usefixtures("mock_setup_entry", "mock_openrgb_client")
async def test_reconfigure_flow_duplicate_entry(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test reconfiguration flow when new config matches another existing entry."""
mock_config_entry.add_to_hass(hass)
# Create another config entry with different host/port
other_entry = MockConfigEntry(
domain=DOMAIN,
title="Other Computer",
data={
CONF_NAME: "Other Computer",
CONF_HOST: "192.168.1.200",
CONF_PORT: 6743,
},
entry_id="01J0EXAMPLE0CONFIGENTRY01",
)
other_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
# Try to reconfigure to match the other entry
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={
CONF_HOST: "192.168.1.200",
CONF_PORT: 6743,
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openrgb/test_config_flow.py",
"license": "Apache License 2.0",
"lines": 214,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/openrgb/test_init.py | """Tests for the OpenRGB integration init."""
import socket
from unittest.mock import MagicMock
from freezegun.api import FrozenDateTimeFactory
from openrgb.utils import ControllerParsingError, OpenRGBDisconnected, SDKVersionError
import pytest
from homeassistant.components.openrgb import async_remove_config_entry_device
from homeassistant.components.openrgb.const import DOMAIN, SCAN_INTERVAL, UID_SEPARATOR
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_ON, STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
from homeassistant.helpers import device_registry as dr
from tests.common import MockConfigEntry, async_fire_time_changed
async def test_entry_setup_unload(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_client: MagicMock,
) -> None:
"""Test entry setup and unload."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.LOADED
assert mock_config_entry.runtime_data is not None
await hass.config_entries.async_unload(mock_config_entry.entry_id)
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
assert mock_openrgb_client.disconnect.called
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_remove_config_entry_device_server(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that server device cannot be removed."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
device_registry = dr.async_get(hass)
server_device = device_registry.async_get_device(
identifiers={(DOMAIN, mock_config_entry.entry_id)}
)
assert server_device is not None
# Try to remove server device - should be blocked
result = await async_remove_config_entry_device(
hass, mock_config_entry, server_device
)
assert result is False
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_remove_config_entry_device_still_connected(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that connected devices cannot be removed."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
device_registry = dr.async_get(hass)
# Get a device that's in coordinator.data (still connected)
devices = dr.async_entries_for_config_entry(
device_registry, mock_config_entry.entry_id
)
rgb_device = next(
(d for d in devices if d.identifiers != {(DOMAIN, mock_config_entry.entry_id)}),
None,
)
if rgb_device:
# Try to remove device that's still connected - should be blocked
result = await async_remove_config_entry_device(
hass, mock_config_entry, rgb_device
)
assert result is False
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_remove_config_entry_device_disconnected(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test that disconnected devices can be removed."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Create a device that's not in coordinator.data (disconnected)
entry_id = mock_config_entry.entry_id
disconnected_device = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={
(
DOMAIN,
UID_SEPARATOR.join(
[
entry_id,
"KEYBOARD",
"Old Vendor",
"Old Device",
"OLD123",
"Old Location",
]
),
)
},
name="Old Disconnected Device",
via_device=(DOMAIN, entry_id),
)
# Try to remove disconnected device - should succeed
result = await async_remove_config_entry_device(
hass, mock_config_entry, disconnected_device
)
assert result is True
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_remove_config_entry_device_with_multiple_identifiers(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test device removal with multiple domain identifiers."""
mock_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
entry_id = mock_config_entry.entry_id
# Create a device with identifiers from multiple domains
device_with_multiple_identifiers = device_registry.async_get_or_create(
config_entry_id=mock_config_entry.entry_id,
identifiers={
("other_domain", "some_other_id"), # This should be skipped
(
DOMAIN,
UID_SEPARATOR.join(
[
entry_id,
"DEVICE",
"Vendor",
"Name",
"SERIAL123",
"Location",
]
),
), # This is a disconnected OpenRGB device
},
name="Multi-Domain Device",
via_device=(DOMAIN, entry_id),
)
# Try to remove device - should succeed because the OpenRGB identifier is disconnected
result = await async_remove_config_entry_device(
hass, mock_config_entry, device_with_multiple_identifiers
)
assert result is True
@pytest.mark.parametrize(
("exception", "expected_state"),
[
(ConnectionRefusedError, ConfigEntryState.SETUP_RETRY),
(OpenRGBDisconnected, ConfigEntryState.SETUP_RETRY),
(ControllerParsingError, ConfigEntryState.SETUP_RETRY),
(TimeoutError, ConfigEntryState.SETUP_RETRY),
(socket.gaierror, ConfigEntryState.SETUP_RETRY),
(SDKVersionError, ConfigEntryState.SETUP_RETRY),
(RuntimeError("Test error"), ConfigEntryState.SETUP_RETRY),
],
)
async def test_setup_entry_exceptions(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_client: MagicMock,
exception: Exception,
expected_state: ConfigEntryState,
) -> None:
"""Test setup entry with various exceptions."""
mock_config_entry.add_to_hass(hass)
mock_openrgb_client.client_class_mock.side_effect = exception
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is expected_state
async def test_reconnection_on_update_failure(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_client: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that coordinator reconnects when update fails."""
mock_config_entry.add_to_hass(hass)
# Set up the integration
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Verify initial state
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
# Reset mock call counts after initial setup
mock_openrgb_client.update.reset_mock()
mock_openrgb_client.connect.reset_mock()
# Simulate the first update call failing, then second succeeding
mock_openrgb_client.update.side_effect = [
OpenRGBDisconnected(),
None, # Second call succeeds after reconnect
]
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
await hass.async_block_till_done()
# Verify that disconnect and connect were called (reconnection happened)
mock_openrgb_client.disconnect.assert_called_once()
mock_openrgb_client.connect.assert_called_once()
# Verify that update was called twice (once failed, once after reconnect)
assert mock_openrgb_client.update.call_count == 2
# Verify that the light is still available after successful reconnect
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
async def test_reconnection_fails_second_attempt(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_client: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that coordinator fails when reconnection also fails."""
mock_config_entry.add_to_hass(hass)
# Set up the integration
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Verify initial state
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
# Reset mock call counts after initial setup
mock_openrgb_client.update.reset_mock()
mock_openrgb_client.connect.reset_mock()
# Simulate the first update call failing, and reconnection also failing
mock_openrgb_client.update.side_effect = [
OpenRGBDisconnected(),
None, # Second call would succeed if reconnect worked
]
# Simulate connect raising an exception to mimic failed reconnection
mock_openrgb_client.connect.side_effect = ConnectionRefusedError()
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
await hass.async_block_till_done()
await hass.async_block_till_done()
# Verify that the light became unavailable after failed reconnection
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_UNAVAILABLE
# Verify that disconnect and connect were called (reconnection was attempted)
mock_openrgb_client.disconnect.assert_called_once()
mock_openrgb_client.connect.assert_called_once()
# Verify that update was only called in the first attempt
mock_openrgb_client.update.assert_called_once()
async def test_normal_update_without_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_client: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that normal updates work without triggering reconnection."""
mock_config_entry.add_to_hass(hass)
# Set up the integration
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
# Verify initial state
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
# Reset mock call counts after initial setup
mock_openrgb_client.update.reset_mock()
mock_openrgb_client.connect.reset_mock()
# Simulate successful update
mock_openrgb_client.update.side_effect = None
mock_openrgb_client.update.return_value = None
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done()
await hass.async_block_till_done()
# Verify that disconnect and connect were NOT called (no reconnection needed)
mock_openrgb_client.disconnect.assert_not_called()
mock_openrgb_client.connect.assert_not_called()
# Verify that update was called only once
mock_openrgb_client.update.assert_called_once()
# Verify that the light is still available
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openrgb/test_init.py",
"license": "Apache License 2.0",
"lines": 279,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/openrgb/test_light.py | """Tests for the OpenRGB light platform."""
from collections.abc import Generator
import copy
from unittest.mock import MagicMock, patch
from freezegun.api import FrozenDateTimeFactory
from openrgb.utils import OpenRGBDisconnected, RGBColor
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_MODE,
ATTR_EFFECT,
ATTR_RGB_COLOR,
ATTR_SUPPORTED_COLOR_MODES,
DOMAIN as LIGHT_DOMAIN,
EFFECT_OFF,
ColorMode,
LightEntityFeature,
)
from homeassistant.components.openrgb.const import (
DEFAULT_COLOR,
DOMAIN,
OFF_COLOR,
SCAN_INTERVAL,
UID_SEPARATOR,
OpenRGBMode,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_SUPPORTED_FEATURES,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers import device_registry as dr, entity_registry as er
from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform
@pytest.fixture(autouse=True)
def light_only() -> Generator[None]:
"""Enable only the light platform."""
with patch(
"homeassistant.components.openrgb.PLATFORMS",
[Platform.LIGHT],
):
yield
# Test basic entity setup and configuration
@pytest.mark.usefixtures("init_integration")
async def test_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
device_registry: dr.DeviceRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the light entities."""
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
# Ensure entities are correctly assigned to device
device_entry = device_registry.async_get_device(
identifiers={
(
DOMAIN,
UID_SEPARATOR.join(
[
mock_config_entry.entry_id,
"DRAM",
"ENE",
"ENE SMBus Device",
"none",
"I2C: PIIX4, address 0x70",
]
),
)
}
)
assert device_entry
entity_entries = er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
)
# Filter out the server device
entity_entries = [e for e in entity_entries if e.device_id == device_entry.id]
assert len(entity_entries) == 1
assert entity_entries[0].device_id == device_entry.id
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_light_with_black_leds(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
) -> None:
"""Test light state when all LEDs are black (off by color)."""
# Set all LEDs to black
mock_openrgb_device.colors = [RGBColor(*OFF_COLOR), RGBColor(*OFF_COLOR)]
mock_openrgb_device.active_mode = 0 # Direct mode (supports colors)
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
# Verify light is off by color
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_OFF
assert state.attributes.get(ATTR_RGB_COLOR) is None
assert state.attributes.get(ATTR_BRIGHTNESS) is None
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_light_with_one_non_black_led(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
) -> None:
"""Test light state when one LED is non-black among black LEDs (on by color)."""
# Set one LED to red, others to black
mock_openrgb_device.colors = [RGBColor(*OFF_COLOR), RGBColor(255, 0, 0)]
mock_openrgb_device.active_mode = 0 # Direct mode (supports colors)
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
# Verify light is on with the non-black LED color
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
assert state.attributes.get(ATTR_COLOR_MODE) == ColorMode.RGB
assert state.attributes.get(ATTR_SUPPORTED_COLOR_MODES) == [ColorMode.RGB]
assert state.attributes.get(ATTR_RGB_COLOR) == (255, 0, 0)
assert state.attributes.get(ATTR_BRIGHTNESS) == 255
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_light_with_non_color_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
) -> None:
"""Test light state with a mode that doesn't support colors."""
# Set to Rainbow mode (doesn't support colors)
mock_openrgb_device.active_mode = 6
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
# Verify light is on with ON/OFF mode
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == LightEntityFeature.EFFECT
assert state.attributes.get(ATTR_EFFECT) == "rainbow"
assert state.attributes.get(ATTR_COLOR_MODE) == ColorMode.ONOFF
assert state.attributes.get(ATTR_SUPPORTED_COLOR_MODES) == [ColorMode.ONOFF]
assert state.attributes.get(ATTR_RGB_COLOR) is None
assert state.attributes.get(ATTR_BRIGHTNESS) is None
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_light_with_no_effects(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
) -> None:
"""Test light with a device that has no effects."""
# Keep only no-effect modes in the device
mock_openrgb_device.modes = [
mode
for mode in mock_openrgb_device.modes
if mode.name in {OpenRGBMode.OFF, OpenRGBMode.DIRECT, OpenRGBMode.STATIC}
]
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
# Verify light entity doesn't have EFFECT feature
state = hass.states.get("light.ene_dram")
assert state
assert state.attributes.get(ATTR_SUPPORTED_FEATURES) == 0
assert state.attributes.get(ATTR_EFFECT) is None
# Verify the light is still functional (can be turned on/off)
assert state.state == STATE_ON
# Test basic turn on/off functionality
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_turn_on_light(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
) -> None:
"""Test turning on the light."""
# Initialize device in Off mode
mock_openrgb_device.active_mode = 1
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
# Verify light is initially off
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_OFF
# Turn on without parameters
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "light.ene_dram"},
blocking=True,
)
# Verify that set_mode was called to restore to Direct mode (preferred over Static)
mock_openrgb_device.set_mode.assert_called_once_with(OpenRGBMode.DIRECT)
# And set_color was called with default color
mock_openrgb_device.set_color.assert_called_once_with(
RGBColor(*DEFAULT_COLOR), True
)
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_turn_on_light_with_color(
hass: HomeAssistant,
mock_openrgb_device: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test turning on the light with color."""
# Start with color Red at half brightness
mock_openrgb_device.colors = [RGBColor(128, 0, 0), RGBColor(128, 0, 0)]
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
# Verify initial state
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
assert state.attributes.get(ATTR_RGB_COLOR) == (255, 0, 0) # Red
assert state.attributes.get(ATTR_BRIGHTNESS) == 128
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.ene_dram",
ATTR_RGB_COLOR: (0, 255, 0), # Green
},
blocking=True,
)
# Check that set_color was called with Green color scaled with half brightness
mock_openrgb_device.set_color.assert_called_once_with(RGBColor(0, 128, 0), True)
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_turn_on_light_with_brightness(
hass: HomeAssistant,
mock_openrgb_device: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test turning on the light with brightness."""
# Start with color Red at full brightness
mock_openrgb_device.colors = [RGBColor(255, 0, 0), RGBColor(255, 0, 0)]
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
# Verify initial state
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
assert state.attributes.get(ATTR_RGB_COLOR) == (255, 0, 0) # Red
assert state.attributes.get(ATTR_BRIGHTNESS) == 255
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.ene_dram",
ATTR_BRIGHTNESS: 128,
},
blocking=True,
)
# Check that set_color was called with Red color scaled with half brightness
mock_openrgb_device.set_color.assert_called_once_with(RGBColor(128, 0, 0), True)
@pytest.mark.usefixtures("init_integration")
async def test_turn_on_light_with_effect(
hass: HomeAssistant,
mock_openrgb_device: MagicMock,
) -> None:
"""Test turning on the light with effect."""
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.ene_dram",
ATTR_EFFECT: "rainbow",
},
blocking=True,
)
mock_openrgb_device.set_mode.assert_called_once_with("Rainbow")
@pytest.mark.usefixtures("init_integration")
async def test_turn_on_light_with_effect_off(
hass: HomeAssistant,
mock_openrgb_device: MagicMock,
) -> None:
"""Test turning on the light with effect Off."""
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.ene_dram",
ATTR_EFFECT: EFFECT_OFF,
},
blocking=True,
)
# Should switch to Direct mode (preferred over Static)
mock_openrgb_device.set_mode.assert_called_once_with(OpenRGBMode.DIRECT)
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_turn_on_restores_previous_values(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test turning on after off restores previous brightness, color, and mode."""
# Start with device in Static mode with blue color
mock_openrgb_device.active_mode = 2
mock_openrgb_device.colors = [RGBColor(0, 0, 128), RGBColor(0, 0, 128)]
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
# Verify initial state
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
# Now device is in Off mode
mock_openrgb_device.active_mode = 1
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_OFF
# Turn on without parameters - should restore previous mode and values
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "light.ene_dram"},
blocking=True,
)
# Should restore to Static mode (previous mode) even though Direct is preferred
mock_openrgb_device.set_mode.assert_called_once_with(OpenRGBMode.STATIC)
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_previous_values_updated_on_refresh(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that previous values are updated when device state changes externally."""
# Start with device in Direct mode with red color at full brightness
mock_openrgb_device.active_mode = 0
mock_openrgb_device.colors = [RGBColor(255, 0, 0), RGBColor(255, 0, 0)]
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
# Verify initial state
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
assert state.attributes.get(ATTR_RGB_COLOR) == (255, 0, 0) # Red
assert state.attributes.get(ATTR_BRIGHTNESS) == 255
assert state.attributes.get(ATTR_EFFECT) == EFFECT_OFF # Direct mode
# Simulate external change to green at 50% brightness in Breathing mode
# (e.g., via the OpenRGB application)
mock_openrgb_device.active_mode = 3 # Breathing mode
mock_openrgb_device.colors = [RGBColor(0, 128, 0), RGBColor(0, 128, 0)]
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Verify new state
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
assert state.attributes.get(ATTR_RGB_COLOR) == (0, 255, 0) # Green
assert state.attributes.get(ATTR_BRIGHTNESS) == 128 # 50% brightness
assert state.attributes.get(ATTR_EFFECT) == "breathing"
# Simulate external change to Off mode
mock_openrgb_device.active_mode = 1
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Verify light is off
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_OFF
# Turn on without parameters - should restore most recent state (green, 50%, Breathing)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "light.ene_dram"},
blocking=True,
)
mock_openrgb_device.set_mode.assert_called_once_with("Breathing")
mock_openrgb_device.set_color.assert_called_once_with(RGBColor(0, 128, 0), True)
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_turn_on_restores_rainbow_after_off(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test turning on after off restores Rainbow effect (non-color mode)."""
# Start with device in Rainbow mode (doesn't support colors)
mock_openrgb_device.active_mode = 6
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
# Verify initial state - Rainbow mode active
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
assert state.attributes.get(ATTR_EFFECT) == "rainbow"
# Turn off the light by switching to Off mode
mock_openrgb_device.active_mode = 1
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Verify light is off
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_OFF
# Turn on without parameters - should restore Rainbow mode
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "light.ene_dram"},
blocking=True,
)
# Should restore to Rainbow mode (previous mode)
mock_openrgb_device.set_mode.assert_called_once_with("Rainbow")
# set_color should NOT be called since Rainbow doesn't support colors
mock_openrgb_device.set_color.assert_not_called()
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_turn_on_restores_rainbow_after_off_by_color(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test turning on after off by color restores Rainbow effect (non-color mode)."""
# Start with device in Rainbow mode (doesn't support colors)
mock_openrgb_device.active_mode = 6
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
# Verify initial state - Rainbow mode active
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
assert state.attributes.get(ATTR_EFFECT) == "rainbow"
# Turn off the light by setting all LEDs to black in Direct mode
mock_openrgb_device.active_mode = 0 # Direct mode
mock_openrgb_device.colors = [RGBColor(*OFF_COLOR), RGBColor(*OFF_COLOR)]
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Verify light is off
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_OFF
# Turn on without parameters - should restore Rainbow mode, not Direct
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "light.ene_dram"},
blocking=True,
)
# Should restore to Rainbow mode (previous mode), not Direct
mock_openrgb_device.set_mode.assert_called_once_with("Rainbow")
# set_color should NOT be called since Rainbow doesn't support colors
mock_openrgb_device.set_color.assert_not_called()
@pytest.mark.usefixtures("init_integration")
async def test_turn_off_light(
hass: HomeAssistant,
mock_openrgb_device: MagicMock,
) -> None:
"""Test turning off the light."""
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "light.ene_dram"},
blocking=True,
)
# Device supports "Off" mode
mock_openrgb_device.set_mode.assert_called_once_with(OpenRGBMode.OFF)
@pytest.mark.usefixtures("mock_openrgb_client")
async def test_turn_off_light_without_off_mode(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_device: MagicMock,
) -> None:
"""Test turning off a light that doesn't support Off mode."""
# Modify the device to not have Off mode
mock_openrgb_device.modes = [
mode_data
for mode_data in mock_openrgb_device.modes
if mode_data.name != OpenRGBMode.OFF
]
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
# Verify light is initially on
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
# Turn off the light
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "light.ene_dram"},
blocking=True,
)
# Device should have set_color called with black/off color instead
mock_openrgb_device.set_color.assert_called_once_with(RGBColor(*OFF_COLOR), True)
# Test error handling
@pytest.mark.usefixtures("init_integration")
@pytest.mark.parametrize(
"exception",
[OpenRGBDisconnected(), ValueError("Invalid color")],
)
async def test_turn_on_light_with_color_exceptions(
hass: HomeAssistant,
mock_openrgb_device: MagicMock,
exception: Exception,
) -> None:
"""Test turning on the light with exceptions when setting color."""
mock_openrgb_device.set_color.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.ene_dram",
ATTR_RGB_COLOR: (0, 255, 0),
},
blocking=True,
)
@pytest.mark.usefixtures("init_integration")
@pytest.mark.parametrize(
"exception",
[OpenRGBDisconnected(), ValueError("Invalid mode")],
)
async def test_turn_on_light_with_mode_exceptions(
hass: HomeAssistant,
mock_openrgb_device: MagicMock,
exception: Exception,
) -> None:
"""Test turning on the light with exceptions when setting mode."""
mock_openrgb_device.set_mode.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.ene_dram",
ATTR_EFFECT: "rainbow",
},
blocking=True,
)
@pytest.mark.usefixtures("init_integration")
async def test_turn_on_light_with_unsupported_effect(
hass: HomeAssistant,
) -> None:
"""Test turning on the light with an invalid effect."""
with pytest.raises(
ServiceValidationError,
match="Effect `InvalidEffect` is not supported by ENE DRAM",
):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.ene_dram",
ATTR_EFFECT: "InvalidEffect",
},
blocking=True,
)
@pytest.mark.usefixtures("init_integration")
async def test_turn_on_light_with_color_and_non_color_effect(
hass: HomeAssistant,
) -> None:
"""Test turning on the light with color/brightness and a non-color effect."""
with pytest.raises(
ServiceValidationError,
match="Effect `rainbow` does not support color control on ENE DRAM",
):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.ene_dram",
ATTR_EFFECT: "rainbow",
ATTR_RGB_COLOR: (255, 0, 0),
},
blocking=True,
)
@pytest.mark.usefixtures("init_integration")
async def test_turn_on_light_with_brightness_and_non_color_effect(
hass: HomeAssistant,
) -> None:
"""Test turning on the light with brightness and a non-color effect."""
with pytest.raises(
ServiceValidationError,
match="Effect `rainbow` does not support color control on ENE DRAM",
):
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.ene_dram",
ATTR_EFFECT: "rainbow",
ATTR_BRIGHTNESS: 128,
},
blocking=True,
)
# Test device management
async def test_dynamic_device_addition(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_client: MagicMock,
mock_openrgb_device: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test that new devices are added dynamically."""
mock_config_entry.add_to_hass(hass)
# Start with one device
mock_openrgb_client.devices = [mock_openrgb_device]
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
# Check that one light entity exists
state = hass.states.get("light.ene_dram")
assert state
# Add a second device
new_device = MagicMock()
new_device.id = 1 # Different device ID
new_device.name = "New RGB Device"
new_device.type = MagicMock()
new_device.type.name = "KEYBOARD"
new_device.metadata = MagicMock()
new_device.metadata.vendor = "New Vendor"
new_device.metadata.description = "New Keyboard"
new_device.metadata.serial = "NEW123"
new_device.metadata.location = "New Location"
new_device.metadata.version = "2.0.0"
new_device.active_mode = 0
new_device.modes = mock_openrgb_device.modes
new_device.colors = [RGBColor(0, 255, 0)]
new_device.set_color = MagicMock()
new_device.set_mode = MagicMock()
mock_openrgb_client.devices = [mock_openrgb_device, new_device]
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
# Check that second light entity was added
state = hass.states.get("light.new_rgb_device")
assert state
@pytest.mark.usefixtures("init_integration")
async def test_light_availability(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_client: MagicMock,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test light becomes unavailable when device is unplugged."""
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_ON
# Simulate device being momentarily unplugged
mock_openrgb_client.devices = []
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("light.ene_dram")
assert state
assert state.state == STATE_UNAVAILABLE
async def test_duplicate_device_names(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_openrgb_client: MagicMock,
mock_openrgb_device: MagicMock,
device_registry: dr.DeviceRegistry,
) -> None:
"""Test that devices with duplicate names get numeric suffixes."""
device1 = copy.deepcopy(mock_openrgb_device)
device1.id = 3 # Should get suffix "1"
device1.metadata.location = "I2C: PIIX4, address 0x71"
# Create a true copy of the first device for device2 to ensure they are separate instances
device2 = copy.deepcopy(mock_openrgb_device)
device2.id = 4 # Should get suffix "2"
device2.metadata.location = "I2C: PIIX4, address 0x72"
mock_openrgb_client.devices = [device1, device2]
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
# The device key format is: entry_id||type||vendor||description||serial||location
device1_key = f"{mock_config_entry.entry_id}||DRAM||ENE||ENE SMBus Device||none||I2C: PIIX4, address 0x71"
device2_key = f"{mock_config_entry.entry_id}||DRAM||ENE||ENE SMBus Device||none||I2C: PIIX4, address 0x72"
# Verify devices exist with correct names (suffix based on device.id position)
device1_entry = device_registry.async_get_device(
identifiers={(DOMAIN, device1_key)}
)
device2_entry = device_registry.async_get_device(
identifiers={(DOMAIN, device2_key)}
)
assert device1_entry
assert device2_entry
# device1 has lower device.id, so it gets suffix "1"
# device2 has higher device.id, so it gets suffix "2"
assert device1_entry.name == "ENE DRAM 1"
assert device2_entry.name == "ENE DRAM 2"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/openrgb/test_light.py",
"license": "Apache License 2.0",
"lines": 711,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/portainer/test_button.py | """Tests for the Portainer button platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
from pyportainer.exceptions import (
PortainerAuthenticationError,
PortainerConnectionError,
PortainerTimeoutError,
)
import pytest
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"
async def test_all_button_entities_snapshot(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Snapshot test for all Portainer button entities."""
with patch(
"homeassistant.components.portainer._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(
("action", "client_method"),
[
("restart", "restart_container"),
],
)
async def test_buttons_containers(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
action: str,
client_method: str,
) -> None:
"""Test pressing a Portainer container action button triggers client call. Click, click!"""
await setup_integration(hass, mock_config_entry)
entity_id = f"button.practical_morse_{action}_container"
method_mock = getattr(mock_portainer_client, client_method)
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(
("exception", "client_method"),
[
(PortainerAuthenticationError("auth"), "restart_container"),
(PortainerConnectionError("conn"), "restart_container"),
(PortainerTimeoutError("timeout"), "restart_container"),
],
)
async def test_buttons_containers_exceptions(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
client_method: str,
) -> None:
"""Test that Portainer buttons, but this time when they will do boom for sure."""
await setup_integration(hass, mock_config_entry)
action = client_method.split("_", maxsplit=1)[0]
entity_id = f"button.practical_morse_{action}_container"
method_mock = getattr(mock_portainer_client, client_method)
method_mock.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(
("action", "client_method"),
[
("prune", "images_prune"),
],
)
async def test_buttons_endpoint(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
action: str,
client_method: str,
) -> None:
"""Test pressing a Portainer endpoint action button triggers client call. Click, click!"""
await setup_integration(hass, mock_config_entry)
entity_id = f"button.my_environment_{action}_unused_images"
method_mock = getattr(mock_portainer_client, client_method)
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(
("exception", "client_method"),
[
(PortainerAuthenticationError("auth"), "images_prune"),
(PortainerConnectionError("conn"), "images_prune"),
(PortainerTimeoutError("timeout"), "images_prune"),
],
)
async def test_buttons_endpoints_exceptions(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
client_method: str,
) -> None:
"""Test that Portainer buttons, but this time when they will do boom for sure."""
await setup_integration(hass, mock_config_entry)
method_mock = getattr(mock_portainer_client, client_method)
method_mock.side_effect = exception
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: "button.my_environment_prune_unused_images"},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/portainer/test_button.py",
"license": "Apache License 2.0",
"lines": 138,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/portainer/test_diagnostics.py | """Test the Portainer component diagnostics."""
from unittest.mock import AsyncMock
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_get_config_entry_diagnostics(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_portainer_client: AsyncMock,
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/portainer/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 24,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/portainer/test_sensor.py | """Tests for the Portainer sensor platform."""
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture(autouse=True)
def enable_all_entities(entity_registry_enabled_by_default: None) -> None:
"""Make sure all entities are enabled."""
@pytest.mark.usefixtures("mock_portainer_client")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch(
"homeassistant.components.portainer._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/portainer/test_sensor.py",
"license": "Apache License 2.0",
"lines": 31,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/portainer/test_switch.py | """Tests for the Portainer switch platform."""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
from pyportainer.exceptions import (
PortainerAuthenticationError,
PortainerConnectionError,
PortainerTimeoutError,
)
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 HomeAssistantError
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("mock_portainer_client")
async def test_all_switch_entities_snapshot(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Snapshot test for all Portainer switch entities."""
with patch(
"homeassistant.components.portainer._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(
("entity_id", "turn_on_method", "turn_off_method", "expected_args"),
[
(
"switch.practical_morse_container",
"start_container",
"stop_container",
(1, "ee20facfb3b3ed4cd362c1e88fc89a53908ad05fb3a4103bca3f9b28292d14bf"),
),
(
"switch.webstack_stack",
"start_stack",
"stop_stack",
(1, 1),
),
],
)
@pytest.mark.parametrize("service_call", [SERVICE_TURN_ON, SERVICE_TURN_OFF])
async def test_turn_off_on(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
turn_on_method: str,
turn_off_method: str,
expected_args: tuple,
service_call: str,
) -> None:
"""Test the switches. Have you tried to turn it off and on again?"""
await setup_integration(hass, mock_config_entry)
client_method = (
turn_on_method if service_call == SERVICE_TURN_ON else turn_off_method
)
method_mock = getattr(mock_portainer_client, client_method)
await hass.services.async_call(
SWITCH_DOMAIN,
service_call,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
method_mock.assert_called_once_with(*expected_args)
@pytest.mark.parametrize(
("entity_id", "turn_on_method", "turn_off_method"),
[
(
"switch.practical_morse_container",
"start_container",
"stop_container",
),
(
"switch.webstack_stack",
"start_stack",
"stop_stack",
),
],
)
@pytest.mark.parametrize("service_call", [SERVICE_TURN_ON, SERVICE_TURN_OFF])
@pytest.mark.parametrize(
("raise_exception", "expected_exception"),
[
(PortainerAuthenticationError, HomeAssistantError),
(PortainerConnectionError, HomeAssistantError),
(PortainerTimeoutError, HomeAssistantError),
],
)
async def test_turn_off_on_exceptions(
hass: HomeAssistant,
mock_portainer_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_id: str,
turn_on_method: str,
turn_off_method: str,
service_call: str,
raise_exception: Exception,
expected_exception: Exception,
) -> None:
"""Test the switches. Have you tried to turn it off and on again? This time they will do boom!"""
await setup_integration(hass, mock_config_entry)
client_method = (
turn_on_method if service_call == SERVICE_TURN_ON else turn_off_method
)
method_mock = getattr(mock_portainer_client, client_method)
method_mock.side_effect = raise_exception
with pytest.raises(expected_exception):
await hass.services.async_call(
SWITCH_DOMAIN,
service_call,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/portainer/test_switch.py",
"license": "Apache License 2.0",
"lines": 127,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/prowl/test_config_flow.py | """Test Prowl config flow."""
from unittest.mock import AsyncMock
import prowlpy
from homeassistant import config_entries
from homeassistant.components.prowl.const import DOMAIN
from homeassistant.const import CONF_API_KEY, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import BAD_API_RESPONSE, CONF_INPUT, INVALID_API_KEY_ERROR, TIMEOUT_ERROR
async def test_flow_user(hass: HomeAssistant, mock_prowlpy: AsyncMock) -> None:
"""Test user initialized flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert mock_prowlpy.verify_key.call_count > 0
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == CONF_INPUT[CONF_NAME]
assert result["data"] == {CONF_API_KEY: CONF_INPUT[CONF_API_KEY]}
async def test_flow_duplicate_api_key(
hass: HomeAssistant, mock_prowlpy: AsyncMock
) -> None:
"""Test user initialized flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert result["type"] is FlowResultType.ABORT
async def test_flow_user_bad_key(hass: HomeAssistant, mock_prowlpy: AsyncMock) -> None:
"""Test user submitting a bad API key."""
mock_prowlpy.verify_key.side_effect = prowlpy.APIError("Invalid API key")
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert mock_prowlpy.verify_key.call_count > 0
assert result["type"] is FlowResultType.FORM
assert result["errors"] == INVALID_API_KEY_ERROR
async def test_flow_user_prowl_timeout(
hass: HomeAssistant, mock_prowlpy: AsyncMock
) -> None:
"""Test Prowl API timeout."""
mock_prowlpy.verify_key.side_effect = TimeoutError
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert mock_prowlpy.verify_key.call_count > 0
assert result["type"] is FlowResultType.FORM
assert result["errors"] == TIMEOUT_ERROR
async def test_flow_api_failure(hass: HomeAssistant, mock_prowlpy: AsyncMock) -> None:
"""Test Prowl API failure."""
mock_prowlpy.verify_key.side_effect = prowlpy.APIError(BAD_API_RESPONSE)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=CONF_INPUT,
)
assert mock_prowlpy.verify_key.call_count > 0
assert result["type"] is FlowResultType.FORM
assert result["errors"] == BAD_API_RESPONSE
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/prowl/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/prowl/test_init.py | """Testing the Prowl initialisation."""
from unittest.mock import AsyncMock
import prowlpy
import pytest
from homeassistant.components import notify
from homeassistant.components.prowl.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from .conftest import ENTITY_ID, TEST_API_KEY
from tests.common import MockConfigEntry
async def test_load_reload_unload_config_entry(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
mock_prowlpy: AsyncMock,
) -> None:
"""Test the Prowl configuration entry loading/reloading/unloading."""
mock_prowlpy_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_prowlpy_config_entry.state is ConfigEntryState.LOADED
assert mock_prowlpy.verify_key.call_count > 0
await hass.config_entries.async_reload(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_prowlpy_config_entry.state is ConfigEntryState.LOADED
await hass.config_entries.async_unload(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
assert not hass.data.get(DOMAIN)
assert mock_prowlpy_config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
("prowlpy_side_effect", "expected_config_state"),
[
(TimeoutError, ConfigEntryState.SETUP_RETRY),
(
prowlpy.APIError(f"Invalid API key: {TEST_API_KEY}"),
ConfigEntryState.SETUP_ERROR,
),
(
prowlpy.APIError("Not accepted: exceeded rate limit"),
ConfigEntryState.SETUP_RETRY,
),
(prowlpy.APIError("Internal server error"), ConfigEntryState.SETUP_ERROR),
],
)
async def test_config_entry_failures(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
mock_prowlpy: AsyncMock,
prowlpy_side_effect,
expected_config_state: ConfigEntryState,
) -> None:
"""Test the Prowl configuration entry dealing with bad API key."""
mock_prowlpy.verify_key.side_effect = prowlpy_side_effect
mock_prowlpy_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_prowlpy_config_entry.state is expected_config_state
assert mock_prowlpy.verify_key.call_count > 0
@pytest.mark.usefixtures("configure_prowl_through_yaml")
async def test_both_yaml_and_config_entry(
hass: HomeAssistant,
mock_prowlpy_config_entry: MockConfigEntry,
) -> None:
"""Test having both YAML config and a config entry works."""
mock_prowlpy_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_prowlpy_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_prowlpy_config_entry.state is ConfigEntryState.LOADED
# Ensure we have the YAML entity service
assert hass.services.has_service(notify.DOMAIN, DOMAIN)
# Ensure we have the config entry entity service
assert hass.states.get(ENTITY_ID) is not None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/prowl/test_init.py",
"license": "Apache License 2.0",
"lines": 71,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/qbittorrent/test_sensor.py | """Tests for the qBittorrent sensor platform, including errored torrents."""
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
import homeassistant.helpers.entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_entities(
hass: HomeAssistant,
mock_qbittorrent: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test that sensors are created."""
with patch("homeassistant.components.qbittorrent.PLATFORMS", [Platform.SENSOR]):
mock_config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/qbittorrent/test_sensor.py",
"license": "Apache License 2.0",
"lines": 22,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/recorder/db_schema_50.py | """Models for SQLAlchemy.
This file contains the model definitions for schema version 50.
It is used to test the schema migration logic.
"""
from __future__ import annotations
from collections.abc import Callable
from datetime import datetime, timedelta
import logging
import time
from typing import Any, Final, Protocol, Self
import ciso8601
from fnv_hash_fast import fnv1a_32
from sqlalchemy import (
CHAR,
JSON,
BigInteger,
Boolean,
ColumnElement,
DateTime,
Float,
ForeignKey,
Identity,
Index,
Integer,
LargeBinary,
SmallInteger,
String,
Text,
case,
type_coerce,
)
from sqlalchemy.dialects import mysql, oracle, postgresql, sqlite
from sqlalchemy.engine.interfaces import Dialect
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import DeclarativeBase, Mapped, aliased, mapped_column, relationship
from sqlalchemy.types import TypeDecorator
from homeassistant.components.recorder.const import (
ALL_DOMAIN_EXCLUDE_ATTRS,
SupportedDialect,
)
from homeassistant.components.recorder.models import (
StatisticData,
StatisticDataTimestamp,
StatisticMeanType,
StatisticMetaData,
datetime_to_timestamp_or_none,
process_timestamp,
ulid_to_bytes_or_none,
uuid_hex_to_bytes_or_none,
)
from homeassistant.components.sensor import ATTR_STATE_CLASS
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_FRIENDLY_NAME,
ATTR_UNIT_OF_MEASUREMENT,
MATCH_ALL,
MAX_LENGTH_EVENT_EVENT_TYPE,
MAX_LENGTH_STATE_ENTITY_ID,
MAX_LENGTH_STATE_STATE,
)
from homeassistant.core import Event, EventStateChangedData
from homeassistant.helpers.json import JSON_DUMP, json_bytes, json_bytes_strip_null
from homeassistant.util import dt as dt_util
# SQLAlchemy Schema
class Base(DeclarativeBase):
"""Base class for tables."""
class LegacyBase(DeclarativeBase):
"""Base class for tables, used for schema migration."""
SCHEMA_VERSION = 50
_LOGGER = logging.getLogger(__name__)
TABLE_EVENTS = "events"
TABLE_EVENT_DATA = "event_data"
TABLE_EVENT_TYPES = "event_types"
TABLE_STATES = "states"
TABLE_STATE_ATTRIBUTES = "state_attributes"
TABLE_STATES_META = "states_meta"
TABLE_RECORDER_RUNS = "recorder_runs"
TABLE_SCHEMA_CHANGES = "schema_changes"
TABLE_STATISTICS = "statistics"
TABLE_STATISTICS_META = "statistics_meta"
TABLE_STATISTICS_RUNS = "statistics_runs"
TABLE_STATISTICS_SHORT_TERM = "statistics_short_term"
TABLE_MIGRATION_CHANGES = "migration_changes"
STATISTICS_TABLES = ("statistics", "statistics_short_term")
MAX_STATE_ATTRS_BYTES = 16384
MAX_EVENT_DATA_BYTES = 32768
PSQL_DIALECT = SupportedDialect.POSTGRESQL
ALL_TABLES = [
TABLE_STATES,
TABLE_STATE_ATTRIBUTES,
TABLE_EVENTS,
TABLE_EVENT_DATA,
TABLE_EVENT_TYPES,
TABLE_RECORDER_RUNS,
TABLE_SCHEMA_CHANGES,
TABLE_MIGRATION_CHANGES,
TABLE_STATES_META,
TABLE_STATISTICS,
TABLE_STATISTICS_META,
TABLE_STATISTICS_RUNS,
TABLE_STATISTICS_SHORT_TERM,
]
TABLES_TO_CHECK = [
TABLE_STATES,
TABLE_EVENTS,
TABLE_RECORDER_RUNS,
TABLE_SCHEMA_CHANGES,
]
LAST_UPDATED_INDEX_TS = "ix_states_last_updated_ts"
METADATA_ID_LAST_UPDATED_INDEX_TS = "ix_states_metadata_id_last_updated_ts"
EVENTS_CONTEXT_ID_BIN_INDEX = "ix_events_context_id_bin"
STATES_CONTEXT_ID_BIN_INDEX = "ix_states_context_id_bin"
LEGACY_STATES_EVENT_ID_INDEX = "ix_states_event_id"
LEGACY_STATES_ENTITY_ID_LAST_UPDATED_TS_INDEX = "ix_states_entity_id_last_updated_ts"
LEGACY_MAX_LENGTH_EVENT_CONTEXT_ID: Final = 36
CONTEXT_ID_BIN_MAX_LENGTH = 16
MYSQL_COLLATE = "utf8mb4_unicode_ci"
MYSQL_DEFAULT_CHARSET = "utf8mb4"
MYSQL_ENGINE = "InnoDB"
_DEFAULT_TABLE_ARGS = {
"mysql_default_charset": MYSQL_DEFAULT_CHARSET,
"mysql_collate": MYSQL_COLLATE,
"mysql_engine": MYSQL_ENGINE,
"mariadb_default_charset": MYSQL_DEFAULT_CHARSET,
"mariadb_collate": MYSQL_COLLATE,
"mariadb_engine": MYSQL_ENGINE,
}
_MATCH_ALL_KEEP = {
ATTR_DEVICE_CLASS,
ATTR_STATE_CLASS,
ATTR_UNIT_OF_MEASUREMENT,
ATTR_FRIENDLY_NAME,
}
class UnusedDateTime(DateTime):
"""An unused column type that behaves like a datetime."""
class Unused(CHAR):
"""An unused column type that behaves like a string."""
@compiles(UnusedDateTime, "mysql", "mariadb", "sqlite")
@compiles(Unused, "mysql", "mariadb", "sqlite")
def compile_char_zero(type_: TypeDecorator, compiler: Any, **kw: Any) -> str:
"""Compile UnusedDateTime and Unused as CHAR(0) on mysql, mariadb, and sqlite."""
return "CHAR(0)" # Uses 1 byte on MySQL (no change on sqlite)
@compiles(Unused, "postgresql")
def compile_char_one(type_: TypeDecorator, compiler: Any, **kw: Any) -> str:
"""Compile Unused as CHAR(1) on postgresql."""
return "CHAR(1)" # Uses 1 byte
class FAST_PYSQLITE_DATETIME(sqlite.DATETIME):
"""Use ciso8601 to parse datetimes instead of sqlalchemy built-in regex."""
def result_processor(self, dialect: Dialect, coltype: Any) -> Callable | None:
"""Offload the datetime parsing to ciso8601."""
return lambda value: None if value is None else ciso8601.parse_datetime(value)
class NativeLargeBinary(LargeBinary):
"""A faster version of LargeBinary for engines that support python bytes natively."""
def result_processor(self, dialect: Dialect, coltype: Any) -> Callable | None:
"""No conversion needed for engines that support native bytes."""
return None
# Although all integers are same in SQLite, it does not allow an identity column to be BIGINT
# https://sqlite.org/forum/info/2dfa968a702e1506e885cb06d92157d492108b22bf39459506ab9f7125bca7fd
ID_TYPE = BigInteger().with_variant(sqlite.INTEGER, "sqlite")
# For MariaDB and MySQL we can use an unsigned integer type since it will fit 2**32
# for sqlite and postgresql we use a bigint
UINT_32_TYPE = BigInteger().with_variant(
mysql.INTEGER(unsigned=True), # type: ignore[no-untyped-call]
"mysql",
"mariadb",
)
JSON_VARIANT_CAST = Text().with_variant(
postgresql.JSON(none_as_null=True),
"postgresql",
)
JSONB_VARIANT_CAST = Text().with_variant(
postgresql.JSONB(none_as_null=True),
"postgresql",
)
DATETIME_TYPE = (
DateTime(timezone=True)
.with_variant(mysql.DATETIME(timezone=True, fsp=6), "mysql", "mariadb") # type: ignore[no-untyped-call]
.with_variant(FAST_PYSQLITE_DATETIME(), "sqlite") # type: ignore[no-untyped-call]
)
DOUBLE_TYPE = (
Float()
.with_variant(mysql.DOUBLE(asdecimal=False), "mysql", "mariadb") # type: ignore[no-untyped-call]
.with_variant(oracle.DOUBLE_PRECISION(), "oracle")
.with_variant(postgresql.DOUBLE_PRECISION(), "postgresql")
)
UNUSED_LEGACY_COLUMN = Unused(0)
UNUSED_LEGACY_DATETIME_COLUMN = UnusedDateTime(timezone=True)
UNUSED_LEGACY_INTEGER_COLUMN = SmallInteger()
DOUBLE_PRECISION_TYPE_SQL = "DOUBLE PRECISION"
BIG_INTEGER_SQL = "BIGINT"
CONTEXT_BINARY_TYPE = LargeBinary(CONTEXT_ID_BIN_MAX_LENGTH).with_variant(
NativeLargeBinary(CONTEXT_ID_BIN_MAX_LENGTH), "mysql", "mariadb", "sqlite"
)
TIMESTAMP_TYPE = DOUBLE_TYPE
class _LiteralProcessorType(Protocol):
def __call__(self, value: Any) -> str: ...
class JSONLiteral(JSON):
"""Teach SA how to literalize json."""
def literal_processor(self, dialect: Dialect) -> _LiteralProcessorType:
"""Processor to convert a value to JSON."""
def process(value: Any) -> str:
"""Dump json."""
return JSON_DUMP(value)
return process
class Events(Base):
"""Event history data."""
__table_args__ = (
# Used for fetching events at a specific time
# see logbook
Index(
"ix_events_event_type_id_time_fired_ts", "event_type_id", "time_fired_ts"
),
Index(
EVENTS_CONTEXT_ID_BIN_INDEX,
"context_id_bin",
mysql_length=CONTEXT_ID_BIN_MAX_LENGTH,
mariadb_length=CONTEXT_ID_BIN_MAX_LENGTH,
),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_EVENTS
event_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
event_type: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
event_data: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
origin: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
origin_idx: Mapped[int | None] = mapped_column(SmallInteger)
time_fired: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
time_fired_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE, index=True)
context_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
context_user_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
context_parent_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
data_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("event_data.data_id"), index=True
)
context_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
context_user_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
context_parent_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
event_type_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("event_types.event_type_id")
)
event_data_rel: Mapped[EventData | None] = relationship("EventData")
event_type_rel: Mapped[EventTypes | None] = relationship("EventTypes")
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.Events("
f"id={self.event_id}, event_type_id='{self.event_type_id}', "
f"origin_idx='{self.origin_idx}', time_fired='{self._time_fired_isotime}'"
f", data_id={self.data_id})>"
)
@property
def _time_fired_isotime(self) -> str | None:
"""Return time_fired as an isotime string."""
date_time: datetime | None
if self.time_fired_ts is not None:
date_time = dt_util.utc_from_timestamp(self.time_fired_ts)
else:
date_time = process_timestamp(self.time_fired)
if date_time is None:
return None
return date_time.isoformat(sep=" ", timespec="seconds")
@staticmethod
def from_event(event: Event) -> Events:
"""Create an event database object from a native event."""
context = event.context
return Events(
event_type=None,
event_data=None,
origin_idx=event.origin.idx,
time_fired=None,
time_fired_ts=event.time_fired_timestamp,
context_id=None,
context_id_bin=ulid_to_bytes_or_none(context.id),
context_user_id=None,
context_user_id_bin=uuid_hex_to_bytes_or_none(context.user_id),
context_parent_id=None,
context_parent_id_bin=ulid_to_bytes_or_none(context.parent_id),
)
class LegacyEvents(LegacyBase):
"""Event history data with event_id, used for schema migration."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_EVENTS
event_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
context_id: Mapped[str | None] = mapped_column(
String(LEGACY_MAX_LENGTH_EVENT_CONTEXT_ID), index=True
)
class EventData(Base):
"""Event data history."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_EVENT_DATA
data_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
hash: Mapped[int | None] = mapped_column(UINT_32_TYPE, index=True)
# Note that this is not named attributes to avoid confusion with the states table
shared_data: Mapped[str | None] = mapped_column(
Text().with_variant(mysql.LONGTEXT, "mysql", "mariadb")
)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.EventData("
f"id={self.data_id}, hash='{self.hash}', data='{self.shared_data}'"
")>"
)
@staticmethod
def shared_data_bytes_from_event(
event: Event, dialect: SupportedDialect | None
) -> bytes:
"""Create shared_data from an event."""
encoder = json_bytes_strip_null if dialect == PSQL_DIALECT else json_bytes
bytes_result = encoder(event.data)
if len(bytes_result) > MAX_EVENT_DATA_BYTES:
_LOGGER.warning(
"Event data for %s exceed maximum size of %s bytes. "
"This can cause database performance issues; Event data "
"will not be stored",
event.event_type,
MAX_EVENT_DATA_BYTES,
)
return b"{}"
return bytes_result
@staticmethod
def hash_shared_data_bytes(shared_data_bytes: bytes) -> int:
"""Return the hash of json encoded shared data."""
return fnv1a_32(shared_data_bytes)
class EventTypes(Base):
"""Event type history."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_EVENT_TYPES
event_type_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
event_type: Mapped[str | None] = mapped_column(
String(MAX_LENGTH_EVENT_EVENT_TYPE), index=True, unique=True
)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.EventTypes("
f"id={self.event_type_id}, event_type='{self.event_type}'"
")>"
)
class States(Base):
"""State change history."""
__table_args__ = (
# Used for fetching the state of entities at a specific time
# (get_states in history.py)
Index(METADATA_ID_LAST_UPDATED_INDEX_TS, "metadata_id", "last_updated_ts"),
Index(
STATES_CONTEXT_ID_BIN_INDEX,
"context_id_bin",
mysql_length=CONTEXT_ID_BIN_MAX_LENGTH,
mariadb_length=CONTEXT_ID_BIN_MAX_LENGTH,
),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_STATES
state_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
entity_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
state: Mapped[str | None] = mapped_column(String(MAX_LENGTH_STATE_STATE))
attributes: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
event_id: Mapped[int | None] = mapped_column(UNUSED_LEGACY_INTEGER_COLUMN)
last_changed: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
last_changed_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE)
last_reported_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE)
last_updated: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
last_updated_ts: Mapped[float | None] = mapped_column(
TIMESTAMP_TYPE, default=time.time, index=True
)
old_state_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("states.state_id"), index=True
)
attributes_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("state_attributes.attributes_id"), index=True
)
context_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
context_user_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
context_parent_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
origin_idx: Mapped[int | None] = mapped_column(
SmallInteger
) # 0 is local, 1 is remote
old_state: Mapped[States | None] = relationship("States", remote_side=[state_id])
state_attributes: Mapped[StateAttributes | None] = relationship("StateAttributes")
context_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
context_user_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
context_parent_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
metadata_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("states_meta.metadata_id")
)
states_meta_rel: Mapped[StatesMeta | None] = relationship("StatesMeta")
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
f"<recorder.States(id={self.state_id}, entity_id='{self.entity_id}'"
f" metadata_id={self.metadata_id},"
f" state='{self.state}', event_id='{self.event_id}',"
f" last_updated='{self._last_updated_isotime}',"
f" old_state_id={self.old_state_id}, attributes_id={self.attributes_id})>"
)
@property
def _last_updated_isotime(self) -> str | None:
"""Return last_updated as an isotime string."""
date_time: datetime | None
if self.last_updated_ts is not None:
date_time = dt_util.utc_from_timestamp(self.last_updated_ts)
else:
date_time = process_timestamp(self.last_updated)
if date_time is None:
return None
return date_time.isoformat(sep=" ", timespec="seconds")
@staticmethod
def from_event(event: Event[EventStateChangedData]) -> States:
"""Create object from a state_changed event."""
state = event.data["new_state"]
# None state means the state was removed from the state machine
if state is None:
state_value = ""
last_updated_ts = event.time_fired_timestamp
last_changed_ts = None
last_reported_ts = None
else:
state_value = state.state
last_updated_ts = state.last_updated_timestamp
if state.last_updated == state.last_changed:
last_changed_ts = None
else:
last_changed_ts = state.last_changed_timestamp
if state.last_updated == state.last_reported:
last_reported_ts = None
else:
last_reported_ts = state.last_reported_timestamp
context = event.context
return States(
state=state_value,
entity_id=None,
attributes=None,
context_id=None,
context_id_bin=ulid_to_bytes_or_none(context.id),
context_user_id=None,
context_user_id_bin=uuid_hex_to_bytes_or_none(context.user_id),
context_parent_id=None,
context_parent_id_bin=ulid_to_bytes_or_none(context.parent_id),
origin_idx=event.origin.idx,
last_updated=None,
last_changed=None,
last_updated_ts=last_updated_ts,
last_changed_ts=last_changed_ts,
last_reported_ts=last_reported_ts,
)
class LegacyStates(LegacyBase):
"""State change history with entity_id, used for schema migration."""
__table_args__ = (
Index(
LEGACY_STATES_ENTITY_ID_LAST_UPDATED_TS_INDEX,
"entity_id",
"last_updated_ts",
),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_STATES
state_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
entity_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
last_updated_ts: Mapped[float | None] = mapped_column(
TIMESTAMP_TYPE, default=time.time, index=True
)
context_id: Mapped[str | None] = mapped_column(
String(LEGACY_MAX_LENGTH_EVENT_CONTEXT_ID), index=True
)
class StateAttributes(Base):
"""State attribute change history."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_STATE_ATTRIBUTES
attributes_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
hash: Mapped[int | None] = mapped_column(UINT_32_TYPE, index=True)
# Note that this is not named attributes to avoid confusion with the states table
shared_attrs: Mapped[str | None] = mapped_column(
Text().with_variant(mysql.LONGTEXT, "mysql", "mariadb")
)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
f"<recorder.StateAttributes(id={self.attributes_id}, hash='{self.hash}',"
f" attributes='{self.shared_attrs}')>"
)
@staticmethod
def shared_attrs_bytes_from_event(
event: Event[EventStateChangedData],
dialect: SupportedDialect | None,
) -> bytes:
"""Create shared_attrs from a state_changed event."""
# None state means the state was removed from the state machine
if (state := event.data["new_state"]) is None:
return b"{}"
if state_info := state.state_info:
unrecorded_attributes = state_info["unrecorded_attributes"]
exclude_attrs = {
*ALL_DOMAIN_EXCLUDE_ATTRS,
*unrecorded_attributes,
}
if MATCH_ALL in unrecorded_attributes:
# Don't exclude device class, state class, unit of measurement
# or friendly name when using the MATCH_ALL exclude constant
exclude_attrs.update(state.attributes)
exclude_attrs -= _MATCH_ALL_KEEP
else:
exclude_attrs = ALL_DOMAIN_EXCLUDE_ATTRS
encoder = json_bytes_strip_null if dialect == PSQL_DIALECT else json_bytes
bytes_result = encoder(
{k: v for k, v in state.attributes.items() if k not in exclude_attrs}
)
if len(bytes_result) > MAX_STATE_ATTRS_BYTES:
_LOGGER.warning(
"State attributes for %s exceed maximum size of %s bytes. "
"This can cause database performance issues; Attributes "
"will not be stored",
state.entity_id,
MAX_STATE_ATTRS_BYTES,
)
return b"{}"
return bytes_result
@staticmethod
def hash_shared_attrs_bytes(shared_attrs_bytes: bytes) -> int:
"""Return the hash of json encoded shared attributes."""
return fnv1a_32(shared_attrs_bytes)
class StatesMeta(Base):
"""Metadata for states."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_STATES_META
metadata_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
entity_id: Mapped[str | None] = mapped_column(
String(MAX_LENGTH_STATE_ENTITY_ID), index=True, unique=True
)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.StatesMeta("
f"id={self.metadata_id}, entity_id='{self.entity_id}'"
")>"
)
class StatisticsBase:
"""Statistics base class."""
id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
created: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
created_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE, default=time.time)
metadata_id: Mapped[int | None] = mapped_column(
ID_TYPE,
ForeignKey(f"{TABLE_STATISTICS_META}.id", ondelete="CASCADE"),
)
start: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
start_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE, index=True)
mean: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
mean_weight: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
min: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
max: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
last_reset: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
last_reset_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE)
state: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
sum: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
duration: timedelta
@classmethod
def from_stats(
cls, metadata_id: int, stats: StatisticData, now_timestamp: float | None = None
) -> Self:
"""Create object from a statistics with datetime objects."""
return cls( # type: ignore[call-arg]
metadata_id=metadata_id,
created=None,
created_ts=now_timestamp or time.time(),
start=None,
start_ts=stats["start"].timestamp(),
mean=stats.get("mean"),
mean_weight=stats.get("mean_weight"),
min=stats.get("min"),
max=stats.get("max"),
last_reset=None,
last_reset_ts=datetime_to_timestamp_or_none(stats.get("last_reset")),
state=stats.get("state"),
sum=stats.get("sum"),
)
@classmethod
def from_stats_ts(
cls,
metadata_id: int,
stats: StatisticDataTimestamp,
now_timestamp: float | None = None,
) -> Self:
"""Create object from a statistics with timestamps."""
return cls( # type: ignore[call-arg]
metadata_id=metadata_id,
created=None,
created_ts=now_timestamp or time.time(),
start=None,
start_ts=stats["start_ts"],
mean=stats.get("mean"),
mean_weight=stats.get("mean_weight"),
min=stats.get("min"),
max=stats.get("max"),
last_reset=None,
last_reset_ts=stats.get("last_reset_ts"),
state=stats.get("state"),
sum=stats.get("sum"),
)
class Statistics(Base, StatisticsBase):
"""Long term statistics."""
duration = timedelta(hours=1)
__table_args__ = (
# Used for fetching statistics for a certain entity at a specific time
Index(
"ix_statistics_statistic_id_start_ts",
"metadata_id",
"start_ts",
unique=True,
),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_STATISTICS
class _StatisticsShortTerm(StatisticsBase):
"""Short term statistics."""
duration = timedelta(minutes=5)
__tablename__ = TABLE_STATISTICS_SHORT_TERM
class StatisticsShortTerm(Base, _StatisticsShortTerm):
"""Short term statistics."""
__table_args__ = (
# Used for fetching statistics for a certain entity at a specific time
Index(
"ix_statistics_short_term_statistic_id_start_ts",
"metadata_id",
"start_ts",
unique=True,
),
_DEFAULT_TABLE_ARGS,
)
class LegacyStatisticsShortTerm(LegacyBase, _StatisticsShortTerm):
"""Short term statistics with 32-bit index, used for schema migration."""
__table_args__ = (
# Used for fetching statistics for a certain entity at a specific time
Index(
"ix_statistics_short_term_statistic_id_start_ts",
"metadata_id",
"start_ts",
unique=True,
),
_DEFAULT_TABLE_ARGS,
)
metadata_id: Mapped[int | None] = mapped_column(
Integer,
ForeignKey(f"{TABLE_STATISTICS_META}.id", ondelete="CASCADE"),
use_existing_column=True,
)
class _StatisticsMeta:
"""Statistics meta data."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_STATISTICS_META
id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
statistic_id: Mapped[str | None] = mapped_column(
String(255), index=True, unique=True
)
source: Mapped[str | None] = mapped_column(String(32))
unit_of_measurement: Mapped[str | None] = mapped_column(String(255))
has_mean: Mapped[bool | None] = mapped_column(Boolean)
has_sum: Mapped[bool | None] = mapped_column(Boolean)
name: Mapped[str | None] = mapped_column(String(255))
mean_type: Mapped[StatisticMeanType] = mapped_column(
SmallInteger, nullable=False, default=StatisticMeanType.NONE.value
) # See StatisticMeanType
@staticmethod
def from_meta(meta: StatisticMetaData) -> StatisticsMeta:
"""Create object from meta data."""
return StatisticsMeta(**meta)
class StatisticsMeta(Base, _StatisticsMeta):
"""Statistics meta data."""
class LegacyStatisticsMeta(LegacyBase, _StatisticsMeta):
"""Statistics meta data with 32-bit index, used for schema migration."""
id: Mapped[int] = mapped_column(
Integer,
Identity(),
primary_key=True,
use_existing_column=True,
)
class RecorderRuns(Base):
"""Representation of recorder run."""
__table_args__ = (
Index("ix_recorder_runs_start_end", "start", "end"),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_RECORDER_RUNS
run_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
start: Mapped[datetime] = mapped_column(DATETIME_TYPE, default=dt_util.utcnow)
end: Mapped[datetime | None] = mapped_column(DATETIME_TYPE)
closed_incorrect: Mapped[bool] = mapped_column(Boolean, default=False)
created: Mapped[datetime] = mapped_column(DATETIME_TYPE, default=dt_util.utcnow)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
end = (
f"'{self.end.isoformat(sep=' ', timespec='seconds')}'" if self.end else None
)
return (
f"<recorder.RecorderRuns(id={self.run_id},"
f" start='{self.start.isoformat(sep=' ', timespec='seconds')}', end={end},"
f" closed_incorrect={self.closed_incorrect},"
f" created='{self.created.isoformat(sep=' ', timespec='seconds')}')>"
)
class MigrationChanges(Base):
"""Representation of migration changes."""
__tablename__ = TABLE_MIGRATION_CHANGES
__table_args__ = (_DEFAULT_TABLE_ARGS,)
migration_id: Mapped[str] = mapped_column(String(255), primary_key=True)
version: Mapped[int] = mapped_column(SmallInteger)
class SchemaChanges(Base):
"""Representation of schema version changes."""
__tablename__ = TABLE_SCHEMA_CHANGES
__table_args__ = (_DEFAULT_TABLE_ARGS,)
change_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
schema_version: Mapped[int | None] = mapped_column(Integer)
changed: Mapped[datetime] = mapped_column(DATETIME_TYPE, default=dt_util.utcnow)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.SchemaChanges("
f"id={self.change_id}, schema_version={self.schema_version}, "
f"changed='{self.changed.isoformat(sep=' ', timespec='seconds')}'"
")>"
)
class StatisticsRuns(Base):
"""Representation of statistics run."""
__tablename__ = TABLE_STATISTICS_RUNS
__table_args__ = (_DEFAULT_TABLE_ARGS,)
run_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
start: Mapped[datetime] = mapped_column(DATETIME_TYPE, index=True)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
f"<recorder.StatisticsRuns(id={self.run_id},"
f" start='{self.start.isoformat(sep=' ', timespec='seconds')}', )>"
)
EVENT_DATA_JSON = type_coerce(
EventData.shared_data.cast(JSONB_VARIANT_CAST), JSONLiteral(none_as_null=True)
)
OLD_FORMAT_EVENT_DATA_JSON = type_coerce(
Events.event_data.cast(JSONB_VARIANT_CAST), JSONLiteral(none_as_null=True)
)
SHARED_ATTRS_JSON = type_coerce(
StateAttributes.shared_attrs.cast(JSON_VARIANT_CAST), JSON(none_as_null=True)
)
OLD_FORMAT_ATTRS_JSON = type_coerce(
States.attributes.cast(JSON_VARIANT_CAST), JSON(none_as_null=True)
)
ENTITY_ID_IN_EVENT: ColumnElement = EVENT_DATA_JSON["entity_id"]
OLD_ENTITY_ID_IN_EVENT: ColumnElement = OLD_FORMAT_EVENT_DATA_JSON["entity_id"]
DEVICE_ID_IN_EVENT: ColumnElement = EVENT_DATA_JSON["device_id"]
OLD_STATE = aliased(States, name="old_state")
SHARED_ATTR_OR_LEGACY_ATTRIBUTES = case(
(StateAttributes.shared_attrs.is_(None), States.attributes),
else_=StateAttributes.shared_attrs,
).label("attributes")
SHARED_DATA_OR_LEGACY_EVENT_DATA = case(
(EventData.shared_data.is_(None), Events.event_data), else_=EventData.shared_data
).label("event_data")
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/recorder/db_schema_50.py",
"license": "Apache License 2.0",
"lines": 755,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/recorder/test_migration_from_schema_50.py | """Test for migration from DB schema version 50."""
import importlib
import sys
import threading
from unittest.mock import patch
import pytest
from pytest_unordered import unordered
from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import Session
from homeassistant.components import recorder
from homeassistant.components.recorder import core, migration, statistics
from homeassistant.components.recorder.const import UNIT_CLASS_SCHEMA_VERSION
from homeassistant.components.recorder.db_schema import StatisticsMeta
from homeassistant.components.recorder.models import StatisticMeanType
from homeassistant.components.recorder.util import session_scope
from homeassistant.core import HomeAssistant
from .common import (
async_recorder_block_till_done,
async_wait_recording_done,
get_patched_live_version,
)
from .conftest import instrument_migration
from tests.common import async_test_home_assistant
from tests.typing import RecorderInstanceContextManager
CREATE_ENGINE_TARGET = "homeassistant.components.recorder.core.create_engine"
SCHEMA_MODULE_50 = "tests.components.recorder.db_schema_50"
@pytest.fixture
async def mock_recorder_before_hass(
async_test_recorder: RecorderInstanceContextManager,
) -> None:
"""Set up recorder."""
async def _async_wait_migration_done(hass: HomeAssistant) -> None:
"""Wait for the migration to be done."""
await recorder.get_instance(hass).async_block_till_done()
await async_recorder_block_till_done(hass)
def _create_engine_test(*args, **kwargs):
"""Test version of create_engine that initializes with old schema.
This simulates an existing db with the old schema.
"""
importlib.import_module(SCHEMA_MODULE_50)
old_db_schema = sys.modules[SCHEMA_MODULE_50]
engine = create_engine(*args, **kwargs)
old_db_schema.Base.metadata.create_all(engine)
with Session(engine) as session:
session.add(
recorder.db_schema.StatisticsRuns(start=statistics.get_start_time())
)
session.add(
recorder.db_schema.SchemaChanges(
schema_version=old_db_schema.SCHEMA_VERSION
)
)
session.commit()
return engine
@pytest.fixture
def db_schema_50():
"""Fixture to initialize the db with the old schema."""
importlib.import_module(SCHEMA_MODULE_50)
old_db_schema = sys.modules[SCHEMA_MODULE_50]
with (
patch.object(recorder, "db_schema", old_db_schema),
patch.object(migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION),
patch.object(
migration,
"LIVE_MIGRATION_MIN_SCHEMA_VERSION",
get_patched_live_version(old_db_schema),
),
patch.object(migration, "non_live_data_migration_needed", return_value=False),
patch.object(core, "StatesMeta", old_db_schema.StatesMeta),
patch.object(core, "EventTypes", old_db_schema.EventTypes),
patch.object(core, "EventData", old_db_schema.EventData),
patch.object(core, "States", old_db_schema.States),
patch.object(core, "Events", old_db_schema.Events),
patch.object(core, "StateAttributes", old_db_schema.StateAttributes),
patch(CREATE_ENGINE_TARGET, new=_create_engine_test),
):
yield
@pytest.mark.parametrize("persistent_database", [True])
@pytest.mark.usefixtures("hass_storage") # Prevent test hass from writing to storage
async def test_migrate_statistics_meta(
async_test_recorder: RecorderInstanceContextManager,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test migration of metadata adding unit_class."""
importlib.import_module(SCHEMA_MODULE_50)
old_db_schema = sys.modules[SCHEMA_MODULE_50]
def _insert_metadata():
with session_scope(hass=hass) as session:
session.add_all(
(
old_db_schema.StatisticsMeta(
statistic_id="sensor.test1",
source="recorder",
unit_of_measurement="kWh",
has_mean=None,
has_sum=True,
name="Test 1",
mean_type=StatisticMeanType.NONE,
),
old_db_schema.StatisticsMeta(
statistic_id="sensor.test2",
source="recorder",
unit_of_measurement="cats",
has_mean=None,
has_sum=True,
name="Test 2",
mean_type=StatisticMeanType.NONE,
),
old_db_schema.StatisticsMeta(
statistic_id="sensor.test3",
source="recorder",
unit_of_measurement="ppm",
has_mean=None,
has_sum=True,
name="Test 3",
mean_type=StatisticMeanType.NONE,
),
# Wrong case
old_db_schema.StatisticsMeta(
statistic_id="sensor.test4",
source="recorder",
unit_of_measurement="l/min",
has_mean=None,
has_sum=True,
name="Test 4",
mean_type=StatisticMeanType.NONE,
),
# Wrong encoding
old_db_schema.StatisticsMeta(
statistic_id="sensor.test5",
source="recorder",
unit_of_measurement="㎡",
has_mean=None,
has_sum=True,
name="Test 5",
mean_type=StatisticMeanType.NONE,
),
)
)
# Create database with old schema
with (
patch.object(recorder, "db_schema", old_db_schema),
patch.object(migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION),
patch.object(
migration,
"LIVE_MIGRATION_MIN_SCHEMA_VERSION",
get_patched_live_version(old_db_schema),
),
patch.object(migration.EventsContextIDMigration, "migrate_data"),
patch(CREATE_ENGINE_TARGET, new=_create_engine_test),
):
async with (
async_test_home_assistant() as hass,
async_test_recorder(hass) as instance,
):
await instance.async_add_executor_job(_insert_metadata)
await async_wait_recording_done(hass)
await _async_wait_migration_done(hass)
await hass.async_stop()
await hass.async_block_till_done()
def _object_as_dict(obj):
return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs}
def _fetch_metadata():
with session_scope(hass=hass) as session:
metadatas = session.query(StatisticsMeta).all()
return {
metadata.statistic_id: _object_as_dict(metadata)
for metadata in metadatas
}
# Run again with new schema, let migration run
async with async_test_home_assistant() as hass:
with (
instrument_migration(hass) as instrumented_migration,
):
# Stall migration when the last non-live schema migration is done
instrumented_migration.stall_on_schema_version = UNIT_CLASS_SCHEMA_VERSION
async with async_test_recorder(
hass, wait_recorder=False, wait_recorder_setup=False
) as instance:
# Wait for migration to reach migration of unit class
await hass.async_add_executor_job(
instrumented_migration.apply_update_stalled.wait
)
# Check that it's possible to read metadata via the API, this will
# stop working when version 50 is migrated off line
pre_migration_metadata_api = await instance.async_add_executor_job(
statistics.list_statistic_ids,
hass,
None,
None,
)
instrumented_migration.migration_stall.set()
instance.recorder_and_worker_thread_ids.add(threading.get_ident())
await hass.async_block_till_done()
await async_wait_recording_done(hass)
await async_wait_recording_done(hass)
post_migration_metadata_db = await instance.async_add_executor_job(
_fetch_metadata
)
post_migration_metadata_api = await instance.async_add_executor_job(
statistics.list_statistic_ids,
hass,
None,
None,
)
await hass.async_stop()
await hass.async_block_till_done()
assert pre_migration_metadata_api == unordered(
[
{
"display_unit_of_measurement": "kWh",
"has_mean": False,
"has_sum": True,
"mean_type": StatisticMeanType.NONE,
"name": "Test 1",
"source": "recorder",
"statistic_id": "sensor.test1",
"statistics_unit_of_measurement": "kWh",
"unit_class": "energy",
},
{
"display_unit_of_measurement": "cats",
"has_mean": False,
"has_sum": True,
"mean_type": StatisticMeanType.NONE,
"name": "Test 2",
"source": "recorder",
"statistic_id": "sensor.test2",
"statistics_unit_of_measurement": "cats",
"unit_class": None,
},
{
"display_unit_of_measurement": "ppm",
"has_mean": False,
"has_sum": True,
"mean_type": StatisticMeanType.NONE,
"name": "Test 3",
"source": "recorder",
"statistic_id": "sensor.test3",
"statistics_unit_of_measurement": "ppm",
"unit_class": "unitless",
},
{
"display_unit_of_measurement": "l/min",
"has_mean": False,
"has_sum": True,
"mean_type": StatisticMeanType.NONE,
"name": "Test 4",
"source": "recorder",
"statistic_id": "sensor.test4",
"statistics_unit_of_measurement": "l/min",
"unit_class": None,
},
{
"display_unit_of_measurement": "㎡",
"has_mean": False,
"has_sum": True,
"mean_type": StatisticMeanType.NONE,
"name": "Test 5",
"source": "recorder",
"statistic_id": "sensor.test5",
"statistics_unit_of_measurement": "㎡",
"unit_class": None,
},
]
)
assert post_migration_metadata_db == {
"sensor.test1": {
"has_mean": None,
"has_sum": True,
"id": 1,
"mean_type": 0,
"name": "Test 1",
"source": "recorder",
"statistic_id": "sensor.test1",
"unit_class": "energy",
"unit_of_measurement": "kWh",
},
"sensor.test2": {
"has_mean": None,
"has_sum": True,
"id": 2,
"mean_type": 0,
"name": "Test 2",
"source": "recorder",
"statistic_id": "sensor.test2",
"unit_class": None,
"unit_of_measurement": "cats",
},
"sensor.test3": {
"has_mean": None,
"has_sum": True,
"id": 3,
"mean_type": 0,
"name": "Test 3",
"source": "recorder",
"statistic_id": "sensor.test3",
"unit_class": "unitless",
"unit_of_measurement": "ppm",
},
"sensor.test4": {
"has_mean": None,
"has_sum": True,
"id": 4,
"mean_type": 0,
"name": "Test 4",
"source": "recorder",
"statistic_id": "sensor.test4",
"unit_class": None,
"unit_of_measurement": "l/min",
},
"sensor.test5": {
"has_mean": None,
"has_sum": True,
"id": 5,
"mean_type": 0,
"name": "Test 5",
"source": "recorder",
"statistic_id": "sensor.test5",
"unit_class": None,
"unit_of_measurement": "㎡",
},
}
assert post_migration_metadata_api == unordered(pre_migration_metadata_api)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/recorder/test_migration_from_schema_50.py",
"license": "Apache License 2.0",
"lines": 324,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/xbox/test_image.py | """Test the Xbox image platform."""
from collections.abc import Generator
from datetime import timedelta
from http import HTTPStatus
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
import pytest
from pythonxbox.api.provider.people.models import PeopleResponse
import respx
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.xbox.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import (
MockConfigEntry,
async_fire_time_changed,
async_load_json_object_fixture,
snapshot_platform,
)
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True)
def image_only() -> Generator[None]:
"""Enable only the image platform."""
with patch(
"homeassistant.components.xbox.PLATFORMS",
[Platform.IMAGE],
):
yield
@pytest.fixture(autouse=True)
def mock_getrandbits():
"""Mock image access token which normally is randomized."""
with patch(
"homeassistant.components.image.SystemRandom.getrandbits",
return_value=1312,
):
yield
@pytest.mark.usefixtures("xbox_live_client")
@pytest.mark.freeze_time("2013-12-13 12:13:12")
async def test_image_platform(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test setup of the Xbox image platform."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@respx.mock
async def test_load_image_from_url(
hass: HomeAssistant,
config_entry: MockConfigEntry,
hass_client: ClientSessionGenerator,
freezer: FrozenDateTimeFactory,
xbox_live_client: AsyncMock,
) -> None:
"""Test image platform loads image from url."""
freezer.move_to("2025-06-16T00:00:00-00:00")
respx.get(
"https://images-eds-ssl.xboxlive.com/image?url=wHwbXKif8cus8csoZ03RW_ES.ojiJijNBGRVUbTnZKsoCCCkjlsEJrrMqDkYqs3M0aLOK2"
"kxE9mbLm9M2.R0stAQYoDsGCDJxqDzG9WF3oa4rOCjEK7DbZXdBmBWnMrfErA3M_Q4y_mUTEQLqSAEeYFGlGeCXYsccnQMvEecxRg-&format=png"
).respond(status_code=HTTPStatus.OK, content_type="image/png", content=b"Test")
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
assert (state := hass.states.get("image.gsr_ae_gamerpic"))
assert state.state == "2025-06-16T00:00:00+00:00"
access_token = state.attributes["access_token"]
assert (
state.attributes["entity_picture"]
== f"/api/image_proxy/image.gsr_ae_gamerpic?token={access_token}"
)
client = await hass_client()
resp = await client.get(state.attributes["entity_picture"])
assert resp.status == HTTPStatus.OK
body = await resp.read()
assert body == b"Test"
assert resp.content_type == "image/png"
assert resp.content_length == 4
xbox_live_client.people.get_friends_by_xuid.return_value = PeopleResponse(
**await async_load_json_object_fixture(
hass, "people_batch gamerpic.json", DOMAIN
) # pyright: ignore[reportArgumentType]
)
respx.get(
"https://images-eds-ssl.xboxlive.com/image?url=KT_QTPJeC5ZpnbX.xahcbrZ9enA_IV9WfFEWIqHGUb5P30TpCdy9xIzUMuqZVCfbWmxtVC"
"rgWHJigthrlsHCxEOMG9UGNdojCYasYt6MJHBjmxmtuAHJeo.sOkUiPmg4JHXvOS82c3UOrvdJTDaCKwCwHPJ0t0Plha8oHFC1i_o-&format=png"
).respond(status_code=HTTPStatus.OK, content_type="image/png", content=b"Test2")
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert (state := hass.states.get("image.gsr_ae_gamerpic"))
assert state.state == "2025-06-16T00:00:30+00:00"
access_token = state.attributes["access_token"]
assert (
state.attributes["entity_picture"]
== f"/api/image_proxy/image.gsr_ae_gamerpic?token={access_token}"
)
client = await hass_client()
resp = await client.get(state.attributes["entity_picture"])
assert resp.status == HTTPStatus.OK
body = await resp.read()
assert body == b"Test2"
assert resp.content_type == "image/png"
assert resp.content_length == 5
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/xbox/test_image.py",
"license": "Apache License 2.0",
"lines": 110,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/telegram_bot/test_event.py | """Test the telegram bot event platform."""
from syrupy.assertion import SnapshotAssertion
from syrupy.filters import props
from homeassistant.components.telegram_bot.const import (
ATTR_CHAT_ID,
ATTR_MESSAGE,
DOMAIN,
SERVICE_SEND_MESSAGE,
)
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_send_message(
hass: HomeAssistant,
mock_broadcast_config_entry: MockConfigEntry,
mock_external_calls: None,
snapshot: SnapshotAssertion,
) -> None:
"""Test send message for entries with multiple chat_ids."""
mock_broadcast_config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id)
await hass.async_block_till_done()
await hass.services.async_call(
DOMAIN,
SERVICE_SEND_MESSAGE,
{ATTR_CHAT_ID: 123456, ATTR_MESSAGE: "test message"},
blocking=True,
return_response=True,
)
await hass.async_block_till_done()
state = hass.states.get("event.mock_title_update_event")
assert state is not None
assert state.attributes == snapshot(exclude=props("config_entry_id"))
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/telegram_bot/test_event.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/yardian/test_switch.py | """Validate Yardian switch behavior."""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
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,
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_yardian_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.yardian.PLATFORMS", [Platform.SWITCH]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_turn_on_switch(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_yardian_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test turning on a switch."""
await setup_integration(hass, mock_config_entry)
entity_id = "switch.yardian_smart_sprinkler_zone_1"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_yardian_client.start_irrigation.assert_called_once_with(0, 6)
async def test_turn_off_switch(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_yardian_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test turning off a switch."""
await setup_integration(hass, mock_config_entry)
entity_id = "switch.yardian_smart_sprinkler_zone_1"
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
mock_yardian_client.stop_irrigation.assert_called_once()
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/yardian/test_switch.py",
"license": "Apache License 2.0",
"lines": 58,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/yardian/test_binary_sensor.py | """Validate Yardian binary sensor behavior."""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.yardian.const import DOMAIN
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from . import setup_integration
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_yardian_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test all entities."""
with patch("homeassistant.components.yardian.PLATFORMS", [Platform.BINARY_SENSOR]):
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_zone_enabled_sensors_disabled_by_default(
hass: HomeAssistant,
mock_yardian_client: AsyncMock,
mock_config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
) -> None:
"""All per-zone binary sensors remain disabled by default."""
await setup_integration(hass, mock_config_entry)
for idx in range(2):
entity_id = entity_registry.async_get_entity_id(
"binary_sensor", DOMAIN, f"{mock_config_entry.unique_id}-zone_enabled_{idx}"
)
assert entity_id is not None
entity_entry = entity_registry.async_get(entity_id)
assert entity_entry is not None
assert entity_entry.disabled
assert entity_entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/yardian/test_binary_sensor.py",
"license": "Apache License 2.0",
"lines": 40,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/yardian/test_init.py | """Test the initialization of Yardian."""
from unittest.mock import AsyncMock
import pytest
from pyyardian import NetworkException, NotAuthorizedException
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from . import setup_integration
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
("exception", "entry_state"),
[
(NotAuthorizedException, ConfigEntryState.SETUP_ERROR),
(TimeoutError, ConfigEntryState.SETUP_RETRY),
(NetworkException, ConfigEntryState.SETUP_RETRY),
(Exception, ConfigEntryState.SETUP_RETRY),
],
)
async def test_setup_unauthorized(
hass: HomeAssistant,
mock_yardian_client: AsyncMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
entry_state: ConfigEntryState,
) -> None:
"""Test setup when unauthorized."""
mock_yardian_client.fetch_device_state.side_effect = exception
await setup_integration(hass, mock_config_entry)
assert mock_config_entry.state is entry_state
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/yardian/test_init.py",
"license": "Apache License 2.0",
"lines": 28,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/victron_remote_monitoring/test_energy.py | """Test the Victron Remote Monitoring energy platform."""
from homeassistant.components.victron_remote_monitoring import energy
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def test_energy_solar_forecast(
hass: HomeAssistant, init_integration: MockConfigEntry
) -> None:
"""Test fetching the solar forecast for the energy dashboard."""
config_entry = init_integration
assert config_entry.state is ConfigEntryState.LOADED
assert await energy.async_get_solar_forecast(hass, config_entry.entry_id) == {
"wh_hours": {
"2025-04-23T10:00:00+00:00": 5050.1,
"2025-04-23T11:00:00+00:00": 5000.2,
"2025-04-24T10:00:00+00:00": 2250.3,
"2025-04-24T11:00:00+00:00": 2000.4,
"2025-04-25T10:00:00+00:00": 1000.5,
"2025-04-25T11:00:00+00:00": 500.6,
}
}
async def test_energy_missing_entry(hass: HomeAssistant) -> None:
"""Return None when config entry cannot be found."""
assert await energy.async_get_solar_forecast(hass, "missing") is None
async def test_energy_no_solar_data(
hass: HomeAssistant, init_integration: MockConfigEntry
) -> None:
"""Return None when the coordinator has no solar forecast data."""
config_entry = init_integration
assert config_entry.state is ConfigEntryState.LOADED
config_entry.runtime_data.data.solar = None
assert await energy.async_get_solar_forecast(hass, config_entry.entry_id) is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/victron_remote_monitoring/test_energy.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/sql/test_services.py | """Tests for the SQL integration services."""
from __future__ import annotations
from pathlib import Path
import sqlite3
from unittest.mock import patch
import pytest
import voluptuous as vol
from voluptuous import MultipleInvalid
from homeassistant.components.recorder import Recorder
from homeassistant.components.sql.const import DOMAIN
from homeassistant.components.sql.services import SERVICE_QUERY
from homeassistant.components.sql.util import generate_lambda_stmt
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.setup import async_setup_component
from tests.components.recorder.common import async_wait_recording_done
async def test_query_service_recorder_db(
recorder_mock: Recorder,
hass: HomeAssistant,
) -> None:
"""Test the query service with the default recorder database."""
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
# Populate the recorder database with some data
hass.states.async_set("sensor.test", "123", {"attr": "value"})
hass.states.async_set("sensor.test2", "456")
await async_wait_recording_done(hass)
response = await hass.services.async_call(
DOMAIN,
SERVICE_QUERY,
{
"query": (
"SELECT states_meta.entity_id, states.state "
"FROM states INNER JOIN states_meta ON states.metadata_id = states_meta.metadata_id "
"WHERE states_meta.entity_id LIKE 'sensor.test%' ORDER BY states_meta.entity_id"
)
},
blocking=True,
return_response=True,
)
assert response == {
"result": [
{"entity_id": "sensor.test", "state": "123"},
{"entity_id": "sensor.test2", "state": "456"},
]
}
async def test_query_service_external_db(hass: HomeAssistant, tmp_path: Path) -> None:
"""Test the query service with an external database via db_url."""
db_path = tmp_path / "test.db"
db_url = f"sqlite:///{db_path}"
# Create and populate the external database
conn = sqlite3.connect(db_path)
conn.execute("CREATE TABLE users (name TEXT, age INTEGER)")
conn.execute("INSERT INTO users (name, age) VALUES ('Alice', 30), ('Bob', 25)")
conn.commit()
conn.close()
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
response = await hass.services.async_call(
DOMAIN,
SERVICE_QUERY,
{"query": "SELECT name, age FROM users ORDER BY age", "db_url": db_url},
blocking=True,
return_response=True,
)
assert response == {
"result": [
{"name": "Bob", "age": 25},
{"name": "Alice", "age": 30},
]
}
async def test_query_service_rollback_on_error(hass: HomeAssistant) -> None:
"""Test the query service."""
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
with (
patch(
"homeassistant.components.sql.services.generate_lambda_stmt",
return_value=generate_lambda_stmt("Faulty syntax create operational issue"),
),
pytest.raises(
ServiceValidationError, match="An error occurred when executing the query"
),
patch("sqlalchemy.orm.session.Session.rollback") as mock_session_rollback,
):
await hass.services.async_call(
DOMAIN,
SERVICE_QUERY,
{
"query": "SELECT name, age FROM users ORDER BY age",
"db_url": "sqlite:///",
},
blocking=True,
return_response=True,
)
mock_session_rollback.assert_called_once()
async def test_query_service_data_conversion(
hass: HomeAssistant, tmp_path: Path
) -> None:
"""Test the query service correctly converts data types."""
db_path = tmp_path / "test_types.db"
db_url = f"sqlite:///{db_path}"
conn = sqlite3.connect(db_path)
conn.execute(
"CREATE TABLE data (id INTEGER, cost DECIMAL(10, 2), event_date DATE, raw BLOB)"
)
conn.execute(
"INSERT INTO data (id, cost, event_date, raw) VALUES (1, 199.99, '2023-01-15', X'DEADBEEF')"
)
conn.commit()
conn.close()
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
response = await hass.services.async_call(
DOMAIN,
SERVICE_QUERY,
{"query": "SELECT * FROM data", "db_url": db_url},
blocking=True,
return_response=True,
)
assert response == {
"result": [
{
"id": 1,
"cost": 199.99, # Converted from Decimal to float
"event_date": "2023-01-15", # Converted from date to ISO string
"raw": "0xdeadbeef", # Converted from bytes to hex string
}
]
}
async def test_query_service_no_results(
recorder_mock: Recorder,
hass: HomeAssistant,
) -> None:
"""Test the query service when a query returns no results."""
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
response = await hass.services.async_call(
DOMAIN,
SERVICE_QUERY,
{"query": "SELECT * FROM states"},
blocking=True,
return_response=True,
)
assert response == {"result": []}
async def test_query_service_invalid_query_not_select(
recorder_mock: Recorder,
hass: HomeAssistant,
) -> None:
"""Test the service rejects non-SELECT queries."""
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
with pytest.raises(vol.Invalid, match="SQL query must be of type SELECT"):
await hass.services.async_call(
DOMAIN,
SERVICE_QUERY,
{"query": "UPDATE states SET state = 'hacked'"},
blocking=True,
return_response=True,
)
async def test_query_service_sqlalchemy_error(
recorder_mock: Recorder,
hass: HomeAssistant,
) -> None:
"""Test the service handles SQLAlchemy errors during query execution."""
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
with pytest.raises(MultipleInvalid, match="SQL query is empty or unknown type"):
await hass.services.async_call(
DOMAIN,
SERVICE_QUERY,
# Syntactically incorrect query
{"query": "SELEC * FROM states"},
blocking=True,
return_response=True,
)
async def test_query_service_invalid_db_url(hass: HomeAssistant) -> None:
"""Test the service handles an invalid database URL."""
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
with (
patch(
"homeassistant.components.sql.util._validate_and_get_session_maker_for_db_url",
return_value=None,
),
pytest.raises(
ServiceValidationError, match="Failed to connect to the database"
),
):
await hass.services.async_call(
DOMAIN,
SERVICE_QUERY,
{
"query": "SELECT 1",
"db_url": "postgresql://user:pass@host:123/dbname",
},
blocking=True,
return_response=True,
)
async def test_query_service_performance_issue_validation(
recorder_mock: Recorder,
hass: HomeAssistant,
) -> None:
"""Test the service validates queries against the recorder for performance issues."""
await async_setup_component(hass, DOMAIN, {})
await hass.async_block_till_done()
with pytest.raises(
ServiceValidationError,
match="The provided query is not allowed: Query contains entity_id but does not reference states_meta",
):
await hass.services.async_call(
DOMAIN,
SERVICE_QUERY,
{"query": "SELECT entity_id FROM states"},
blocking=True,
return_response=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/sql/test_services.py",
"license": "Apache License 2.0",
"lines": 217,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/xbox/test_media_player.py | """Test the Xbox media_player platform."""
from collections.abc import Generator
from http import HTTPStatus
from typing import Any
from unittest.mock import patch
from httpx import HTTPStatusError, RequestError, TimeoutException
import pytest
from pythonxbox.api.provider.catalog.models import CatalogResponse
from pythonxbox.api.provider.smartglass.models import (
SmartglassConsoleStatus,
VolumeDirection,
)
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.media_player import (
ATTR_MEDIA_CONTENT_ID,
ATTR_MEDIA_CONTENT_TYPE,
ATTR_MEDIA_VOLUME_MUTED,
DOMAIN as MEDIA_PLAYER_DOMAIN,
SERVICE_PLAY_MEDIA,
MediaType,
)
from homeassistant.components.xbox import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
ATTR_ENTITY_ID,
SERVICE_MEDIA_NEXT_TRACK,
SERVICE_MEDIA_PAUSE,
SERVICE_MEDIA_PLAY,
SERVICE_MEDIA_PREVIOUS_TRACK,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
SERVICE_VOLUME_DOWN,
SERVICE_VOLUME_MUTE,
SERVICE_VOLUME_UP,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from tests.common import (
AsyncMock,
Mock,
MockConfigEntry,
async_load_json_object_fixture,
snapshot_platform,
)
from tests.typing import MagicMock, WebSocketGenerator
@pytest.fixture(autouse=True)
def media_player_only() -> Generator[None]:
"""Enable only the media_player platform."""
with patch(
"homeassistant.components.xbox.PLATFORMS",
[Platform.MEDIA_PLAYER],
):
yield
@pytest.fixture(autouse=True)
def mock_token() -> Generator[MagicMock]:
"""Mock token generator."""
with patch("secrets.token_hex", return_value="mock_token") as token:
yield token
@pytest.mark.parametrize(
("fixture_status", "fixture_catalog"),
[
("smartglass_console_status.json", "catalog_product_lookup.json"),
("smartglass_console_status_idle.json", "catalog_product_lookup.json"),
("smartglass_console_status_livetv.json", "catalog_product_lookup_livetv.json"),
],
ids=["app", "idle", "livetvapp"],
)
async def test_media_players(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
xbox_live_client: AsyncMock,
fixture_status: str,
fixture_catalog: str | None,
) -> None:
"""Test setup of the Xbox media player platform."""
xbox_live_client.smartglass.get_console_status.return_value = (
SmartglassConsoleStatus(
**await async_load_json_object_fixture(hass, fixture_status, DOMAIN) # pyright: ignore[reportArgumentType]
)
)
xbox_live_client.catalog.get_product_from_alternate_id.return_value = (
CatalogResponse(
**await async_load_json_object_fixture(hass, fixture_catalog, DOMAIN) # pyright: ignore[reportArgumentType]
)
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.usefixtures("xbox_live_client")
async def test_browse_media(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test async_browse_media."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
client = await hass_ws_client()
await client.send_json_auto_id(
{
"type": "media_player/browse_media",
"entity_id": "media_player.xone",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == snapshot(name="library")
await client.send_json_auto_id(
{
"type": "media_player/browse_media",
"entity_id": "media_player.xone",
"media_content_id": "App",
"media_content_type": "app",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == snapshot(name="apps")
await client.send_json_auto_id(
{
"type": "media_player/browse_media",
"entity_id": "media_player.xone",
"media_content_id": "Game",
"media_content_type": "game",
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == snapshot(name="games")
@pytest.mark.parametrize(
("service", "service_args", "call_method", "call_args"),
[
(SERVICE_TURN_ON, {}, "wake_up", ()),
(SERVICE_TURN_OFF, {}, "turn_off", ()),
(SERVICE_VOLUME_MUTE, {ATTR_MEDIA_VOLUME_MUTED: False}, "unmute", ()),
(SERVICE_VOLUME_MUTE, {ATTR_MEDIA_VOLUME_MUTED: True}, "mute", ()),
(SERVICE_VOLUME_UP, {}, "volume", (VolumeDirection.Up,)),
(SERVICE_VOLUME_DOWN, {}, "volume", (VolumeDirection.Down,)),
(SERVICE_MEDIA_PLAY, {}, "play", ()),
(SERVICE_MEDIA_PAUSE, {}, "pause", ()),
(SERVICE_MEDIA_PREVIOUS_TRACK, {}, "previous", ()),
(SERVICE_MEDIA_NEXT_TRACK, {}, "next", ()),
(
SERVICE_PLAY_MEDIA,
{ATTR_MEDIA_CONTENT_TYPE: MediaType.APP, ATTR_MEDIA_CONTENT_ID: "Home"},
"go_home",
(),
),
(
SERVICE_PLAY_MEDIA,
{
ATTR_MEDIA_CONTENT_TYPE: MediaType.APP,
ATTR_MEDIA_CONTENT_ID: "327370029",
},
"launch_app",
("327370029",),
),
],
)
async def test_media_player_actions(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
service: str,
service_args: dict[str, Any],
call_method: str,
call_args: set[Any],
) -> None:
"""Test media player actions."""
xbox_live_client.smartglass.get_console_status.return_value = (
SmartglassConsoleStatus(
**await async_load_json_object_fixture(
hass, "smartglass_console_status_playing.json", DOMAIN
) # pyright: ignore[reportArgumentType]
)
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
service,
target={ATTR_ENTITY_ID: "media_player.xone", **service_args},
blocking=True,
)
getattr(xbox_live_client.smartglass, call_method).assert_called_once_with(
"HIJKLMN", *call_args
)
@pytest.mark.parametrize(
("service", "service_args", "call_method"),
[
(SERVICE_TURN_ON, {}, "wake_up"),
(SERVICE_TURN_OFF, {}, "turn_off"),
(SERVICE_VOLUME_MUTE, {ATTR_MEDIA_VOLUME_MUTED: False}, "unmute"),
(SERVICE_VOLUME_MUTE, {ATTR_MEDIA_VOLUME_MUTED: True}, "mute"),
(SERVICE_VOLUME_UP, {}, "volume"),
(SERVICE_VOLUME_DOWN, {}, "volume"),
(SERVICE_MEDIA_PLAY, {}, "play"),
(SERVICE_MEDIA_PAUSE, {}, "pause"),
(SERVICE_MEDIA_PREVIOUS_TRACK, {}, "previous"),
(SERVICE_MEDIA_NEXT_TRACK, {}, "next"),
(
SERVICE_PLAY_MEDIA,
{ATTR_MEDIA_CONTENT_TYPE: MediaType.APP, ATTR_MEDIA_CONTENT_ID: "Home"},
"go_home",
),
(
SERVICE_PLAY_MEDIA,
{
ATTR_MEDIA_CONTENT_TYPE: MediaType.APP,
ATTR_MEDIA_CONTENT_ID: "327370029",
},
"launch_app",
),
],
)
@pytest.mark.parametrize(
("exception", "translation_key"),
[
(TimeoutException(""), "timeout_exception"),
(RequestError("", request=Mock()), "request_exception"),
(HTTPStatusError("", request=Mock(), response=Mock()), "request_exception"),
],
)
async def test_media_player_action_exceptions(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
service: str,
service_args: dict[str, Any],
call_method: str,
exception: Exception,
translation_key: str,
) -> None:
"""Test media player action exceptions."""
xbox_live_client.smartglass.get_console_status.return_value = (
SmartglassConsoleStatus(
**await async_load_json_object_fixture(
hass, "smartglass_console_status_playing.json", DOMAIN
) # pyright: ignore[reportArgumentType]
)
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
getattr(xbox_live_client.smartglass, call_method).side_effect = exception
with pytest.raises(HomeAssistantError) as e:
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
service,
target={ATTR_ENTITY_ID: "media_player.xone", **service_args},
blocking=True,
)
assert e.value.translation_key == translation_key
async def test_media_player_turn_on_failed(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
) -> None:
"""Test media player turn on failed."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
xbox_live_client.smartglass.wake_up.side_effect = (
HTTPStatusError(
"", request=Mock(), response=Mock(status_code=HTTPStatus.NOT_FOUND)
),
)
with pytest.raises(HomeAssistantError) as e:
await hass.services.async_call(
MEDIA_PLAYER_DOMAIN,
SERVICE_TURN_ON,
target={ATTR_ENTITY_ID: "media_player.xone"},
blocking=True,
)
assert e.value.translation_key == "turn_on_failed"
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/xbox/test_media_player.py",
"license": "Apache License 2.0",
"lines": 288,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/xbox/test_remote.py | """Test the Xbox remote platform."""
from collections.abc import Generator
from http import HTTPStatus
from unittest.mock import AsyncMock, patch
from httpx import HTTPStatusError, RequestError, TimeoutException
import pytest
from pythonxbox.api.provider.smartglass.models import InputKeyType
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.remote import (
ATTR_DELAY_SECS,
DOMAIN as REMOTE_DOMAIN,
SERVICE_SEND_COMMAND,
)
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import (
ATTR_COMMAND,
ATTR_ENTITY_ID,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import entity_registry as er
from tests.common import Mock, MockConfigEntry, snapshot_platform
@pytest.fixture(autouse=True)
def remote_only() -> Generator[None]:
"""Enable only the remote platform."""
with patch(
"homeassistant.components.xbox.PLATFORMS",
[Platform.REMOTE],
):
yield
@pytest.mark.usefixtures("xbox_live_client")
async def test_remotes(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test setup of the Xbox remote platform."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize(
("button", "payload"),
[
("A", InputKeyType.A),
("B", InputKeyType.B),
("X", InputKeyType.X),
("Y", InputKeyType.Y),
("Up", InputKeyType.Up),
("Down", InputKeyType.Down),
("Left", InputKeyType.Left),
("Right", InputKeyType.Right),
("Menu", InputKeyType.Menu),
("View", InputKeyType.View),
("Nexus", InputKeyType.Nexus),
],
)
async def test_send_button_command(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
button: str,
payload: InputKeyType,
) -> None:
"""Test remote send button command."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await hass.services.async_call(
REMOTE_DOMAIN,
SERVICE_SEND_COMMAND,
{ATTR_COMMAND: button, ATTR_DELAY_SECS: 0},
target={ATTR_ENTITY_ID: "remote.xone"},
blocking=True,
)
xbox_live_client.smartglass.press_button.assert_called_once_with("HIJKLMN", payload)
@pytest.mark.parametrize(
("command", "call_method"),
[
("WakeUp", "wake_up"),
("TurnOff", "turn_off"),
("Reboot", "reboot"),
("Mute", "mute"),
("Unmute", "unmute"),
("Play", "play"),
("Pause", "pause"),
("Previous", "previous"),
("Next", "next"),
("GoHome", "go_home"),
("GoBack", "go_back"),
("ShowGuideTab", "show_guide_tab"),
("ShowGuide", "show_tv_guide"),
],
)
async def test_send_command(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
command: str,
call_method: str,
) -> None:
"""Test remote send command."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await hass.services.async_call(
REMOTE_DOMAIN,
SERVICE_SEND_COMMAND,
{ATTR_COMMAND: command, ATTR_DELAY_SECS: 0},
target={ATTR_ENTITY_ID: "remote.xone"},
blocking=True,
)
call = getattr(xbox_live_client.smartglass, call_method)
call.assert_called_once_with("HIJKLMN")
async def test_send_text(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
) -> None:
"""Test remote send text."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await hass.services.async_call(
REMOTE_DOMAIN,
SERVICE_SEND_COMMAND,
{ATTR_COMMAND: "Hello", ATTR_DELAY_SECS: 0},
target={ATTR_ENTITY_ID: "remote.xone"},
blocking=True,
)
xbox_live_client.smartglass.insert_text.assert_called_once_with("HIJKLMN", "Hello")
async def test_turn_on(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
) -> None:
"""Test remote turn on."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await hass.services.async_call(
REMOTE_DOMAIN,
SERVICE_TURN_ON,
target={ATTR_ENTITY_ID: "remote.xone"},
blocking=True,
)
xbox_live_client.smartglass.wake_up.assert_called_once_with("HIJKLMN")
async def test_turn_off(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
) -> None:
"""Test remote turn off."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await hass.services.async_call(
REMOTE_DOMAIN,
SERVICE_TURN_OFF,
target={ATTR_ENTITY_ID: "remote.xone"},
blocking=True,
)
xbox_live_client.smartglass.turn_off.assert_called_once_with("HIJKLMN")
@pytest.mark.parametrize(
("command", "call_method"),
[
("Play", "play"),
("Nexus", "press_button"),
("Hello world", "insert_text"),
],
)
@pytest.mark.parametrize(
("exception", "translation_key"),
[
(TimeoutException(""), "timeout_exception"),
(RequestError("", request=Mock()), "request_exception"),
(HTTPStatusError("", request=Mock(), response=Mock()), "request_exception"),
],
)
async def test_send_command_exceptions(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
command: str,
call_method: str,
exception: Exception,
translation_key: str,
) -> None:
"""Test remote send command exceptions."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
getattr(xbox_live_client.smartglass, call_method).side_effect = exception
with pytest.raises(HomeAssistantError) as e:
await hass.services.async_call(
REMOTE_DOMAIN,
SERVICE_SEND_COMMAND,
{ATTR_COMMAND: command, ATTR_DELAY_SECS: 0},
target={ATTR_ENTITY_ID: "remote.xone"},
blocking=True,
)
assert e.value.translation_key == translation_key
@pytest.mark.parametrize(
("exception", "translation_key"),
[
(TimeoutException(""), "timeout_exception"),
(RequestError("", request=Mock()), "request_exception"),
(HTTPStatusError("", request=Mock(), response=Mock()), "request_exception"),
(
HTTPStatusError(
"", request=Mock(), response=Mock(status_code=HTTPStatus.NOT_FOUND)
),
"turn_on_failed",
),
],
)
async def test_turn_on_exceptions(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
exception: Exception,
translation_key: str,
) -> None:
"""Test remote turn on exceptions."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
xbox_live_client.smartglass.wake_up.side_effect = exception
with pytest.raises(HomeAssistantError) as e:
await hass.services.async_call(
REMOTE_DOMAIN,
SERVICE_TURN_ON,
target={ATTR_ENTITY_ID: "remote.xone"},
blocking=True,
)
assert e.value.translation_key == translation_key
@pytest.mark.parametrize(
("exception", "translation_key"),
[
(TimeoutException(""), "timeout_exception"),
(RequestError("", request=Mock()), "request_exception"),
(HTTPStatusError("", request=Mock(), response=Mock()), "request_exception"),
],
)
async def test_turn_off_exceptions(
hass: HomeAssistant,
xbox_live_client: AsyncMock,
config_entry: MockConfigEntry,
exception: Exception,
translation_key: str,
) -> None:
"""Test remote turn off exceptions."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
xbox_live_client.smartglass.turn_off.side_effect = exception
with pytest.raises(HomeAssistantError) as e:
await hass.services.async_call(
REMOTE_DOMAIN,
SERVICE_TURN_OFF,
target={ATTR_ENTITY_ID: "remote.xone"},
blocking=True,
)
assert e.value.translation_key == translation_key
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/xbox/test_remote.py",
"license": "Apache License 2.0",
"lines": 277,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/xbox/test_init.py | """Tests for the Xbox integration."""
from datetime import timedelta
from http import HTTPStatus
from unittest.mock import AsyncMock, MagicMock, Mock, patch
from aiohttp import ClientError
from freezegun.api import FrozenDateTimeFactory
from httpx import ConnectTimeout, HTTPStatusError, ProtocolError, RequestError, Response
import pytest
from pythonxbox.api.provider.smartglass.models import SmartglassConsoleList
from pythonxbox.common.exceptions import AuthenticationException
import respx
from homeassistant.components.xbox.const import DOMAIN, OAUTH2_TOKEN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
OAuth2TokenRequestReauthError,
OAuth2TokenRequestTransientError,
)
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.config_entry_oauth2_flow import (
ImplementationUnavailableError,
)
from tests.common import (
MockConfigEntry,
async_fire_time_changed,
async_load_json_object_fixture,
)
@pytest.mark.usefixtures("xbox_live_client")
async def test_entry_setup_unload(
hass: HomeAssistant, config_entry: MockConfigEntry
) -> None:
"""Test integration setup and unload."""
config_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
assert await hass.config_entries.async_unload(config_entry.entry_id)
assert config_entry.state is ConfigEntryState.NOT_LOADED
@pytest.mark.parametrize(
"exception",
[
ConnectTimeout(""),
HTTPStatusError("", request=Mock(), response=Mock()),
ProtocolError(""),
],
)
async def test_config_entry_not_ready(
hass: HomeAssistant,
config_entry: MockConfigEntry,
xbox_live_client: AsyncMock,
exception: Exception,
) -> None:
"""Test config entry not ready."""
xbox_live_client.smartglass.get_console_list.side_effect = exception
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
@pytest.mark.usefixtures("xbox_live_client")
async def test_config_implementation_not_available(
hass: HomeAssistant,
config_entry: MockConfigEntry,
) -> None:
"""Test implementation not available."""
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.xbox.async_get_config_entry_implementation",
side_effect=ImplementationUnavailableError,
):
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
@pytest.mark.parametrize(
("state", "exception"),
[
(
ConfigEntryState.SETUP_ERROR,
OAuth2TokenRequestReauthError(domain=DOMAIN, request_info=Mock()),
),
(
ConfigEntryState.SETUP_RETRY,
OAuth2TokenRequestTransientError(domain=DOMAIN, request_info=Mock()),
),
(
ConfigEntryState.SETUP_RETRY,
ClientError,
),
],
)
@respx.mock
async def test_oauth_session_refresh_failure_exceptions(
hass: HomeAssistant,
config_entry: MockConfigEntry,
state: ConfigEntryState,
exception: Exception | type[Exception],
oauth2_session: AsyncMock,
) -> None:
"""Test OAuth2 session refresh failures."""
oauth2_session.async_ensure_token_valid.side_effect = exception
oauth2_session.valid_token = False
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is state
@pytest.mark.parametrize(
("state", "exception"),
[
(
ConfigEntryState.SETUP_RETRY,
HTTPStatusError(
"", request=MagicMock(), response=Response(HTTPStatus.IM_A_TEAPOT)
),
),
(ConfigEntryState.SETUP_RETRY, RequestError("", request=Mock())),
(ConfigEntryState.SETUP_ERROR, AuthenticationException),
],
)
@respx.mock
async def test_oauth_session_refresh_user_and_xsts_token_exceptions(
hass: HomeAssistant,
config_entry: MockConfigEntry,
state: ConfigEntryState,
exception: Exception | type[Exception],
oauth2_session: AsyncMock,
) -> None:
"""Test OAuth2 user and XSTS token refresh failures."""
oauth2_session.valid_token = True
respx.post(OAUTH2_TOKEN).mock(side_effect=exception)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is state
@pytest.mark.parametrize(
"exception",
[
ConnectTimeout(""),
HTTPStatusError("", request=Mock(), response=Mock()),
ProtocolError(""),
],
)
@pytest.mark.parametrize(
("provider", "method"),
[
("smartglass", "get_console_status"),
("catalog", "get_product_from_alternate_id"),
("people", "get_friends_by_xuid"),
("people", "get_friends_own"),
],
)
async def test_coordinator_update_failed(
hass: HomeAssistant,
config_entry: MockConfigEntry,
xbox_live_client: AsyncMock,
exception: Exception,
provider: str,
method: str,
) -> None:
"""Test coordinator update failed."""
provider = getattr(xbox_live_client, provider)
getattr(provider, method).side_effect = exception
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.SETUP_RETRY
@pytest.mark.freeze_time
async def test_dynamic_devices(
hass: HomeAssistant,
config_entry: MockConfigEntry,
xbox_live_client: AsyncMock,
device_registry: dr.DeviceRegistry,
freezer: FrozenDateTimeFactory,
) -> None:
"""Test adding of new and removal of stale devices at runtime."""
xbox_live_client.smartglass.get_console_list.return_value = SmartglassConsoleList(
**await async_load_json_object_fixture(
hass, "smartglass_console_list_empty.json", DOMAIN
) # pyright: ignore[reportArgumentType]
)
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
assert device_registry.async_get_device({(DOMAIN, "ABCDEFG")}) is None
assert device_registry.async_get_device({(DOMAIN, "HIJKLMN")}) is None
xbox_live_client.smartglass.get_console_list.return_value = SmartglassConsoleList(
**await async_load_json_object_fixture(
hass, "smartglass_console_list.json", DOMAIN
) # pyright: ignore[reportArgumentType]
)
freezer.tick(timedelta(minutes=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert device_registry.async_get_device({(DOMAIN, "ABCDEFG")})
assert device_registry.async_get_device({(DOMAIN, "HIJKLMN")})
xbox_live_client.smartglass.get_console_list.return_value = SmartglassConsoleList(
**await async_load_json_object_fixture(
hass, "smartglass_console_list_empty.json", DOMAIN
) # pyright: ignore[reportArgumentType]
)
freezer.tick(timedelta(minutes=10))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert device_registry.async_get_device({(DOMAIN, "ABCDEFG")}) is None
assert device_registry.async_get_device({(DOMAIN, "HIJKLMN")}) is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/xbox/test_init.py",
"license": "Apache License 2.0",
"lines": 204,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/zeroconf/test_repairs.py | """Tests for zeroconf repair issues."""
from unittest.mock import patch
import pytest
from zeroconf import ServiceStateChange
from zeroconf.asyncio import AsyncServiceInfo
from homeassistant.components.homeassistant import DOMAIN as HOMEASSISTANT_DOMAIN
from homeassistant.components.repairs import DOMAIN as REPAIRS_DOMAIN
from homeassistant.components.zeroconf import DOMAIN, discovery, repairs
from homeassistant.components.zeroconf.discovery import ZEROCONF_TYPE
from homeassistant.const import EVENT_HOMEASSISTANT_STARTED
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import instance_id, issue_registry as ir
from homeassistant.setup import async_setup_component
from .test_init import service_update_mock
from tests.components.repairs import (
async_process_repairs_platforms,
process_repair_fix_flow,
start_repair_fix_flow,
)
from tests.typing import ClientSessionGenerator
def service_state_change_mock(
zeroconf,
services,
handlers,
*,
state_change: ServiceStateChange = ServiceStateChange.Removed,
) -> None:
"""Call service update handler."""
for service in services:
handlers[0](zeroconf, service, f"_name.{service}", state_change)
def _get_hass_service_info_mock(
service_type: str,
name: str,
*,
instance_id="abc123",
) -> AsyncServiceInfo:
"""Return service info for Home Assistant instance."""
return AsyncServiceInfo(
ZEROCONF_TYPE,
name,
addresses=[b"\n\x00\x00\x01"],
port=8123,
weight=0,
priority=0,
server="other-host.local.",
properties={
"base_url": "http://10.0.0.1:8123",
"external_url": None,
"internal_url": "http://10.0.0.1:8123",
"location_name": "Home",
"requires_api_password": "True",
"uuid": instance_id,
"version": "2025.9.0.dev0",
},
)
@pytest.mark.usefixtures("mock_async_zeroconf")
async def test_instance_id_conflict_creates_repair_issue_remove(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test that a repair issue is created on instance ID conflict and gets removed when instance disappears."""
with (
patch("homeassistant.helpers.instance_id.async_get", return_value="abc123"),
patch.object(
discovery, "AsyncServiceBrowser", side_effect=service_update_mock
) as mock_browser,
patch.object(hass.config_entries.flow, "async_init"),
patch(
"homeassistant.components.zeroconf.discovery.AsyncServiceInfo",
side_effect=_get_hass_service_info_mock,
),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
issue = issue_registry.async_get_issue(
domain="zeroconf", issue_id="duplicate_instance_id"
)
assert issue
assert issue.severity == ir.IssueSeverity.ERROR
assert issue.translation_key == "duplicate_instance_id"
assert issue.translation_placeholders == {
"other_host_url": "other-host.local",
"other_ip": "10.0.0.1",
"instance_id": "abc123",
}
# Now test that the issue is removed when the service goes away
service_state_change_mock(
mock_browser.call_args[0][0],
[ZEROCONF_TYPE],
mock_browser.call_args[1]["handlers"],
)
assert (
issue_registry.async_get_issue(
domain="zeroconf", issue_id="duplicate_instance_id"
)
is None
)
@pytest.mark.usefixtures("mock_async_zeroconf")
async def test_instance_id_conflict_creates_repair_issue_changing_id(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test that a repair issue is created on instance ID conflict and gets removed when instance ID changes."""
with (
patch("homeassistant.helpers.instance_id.async_get", return_value="abc123"),
patch.object(
discovery, "AsyncServiceBrowser", side_effect=service_update_mock
) as mock_browser,
patch.object(hass.config_entries.flow, "async_init"),
patch(
"homeassistant.components.zeroconf.discovery.AsyncServiceInfo",
side_effect=_get_hass_service_info_mock,
),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
issue = issue_registry.async_get_issue(
domain="zeroconf", issue_id="duplicate_instance_id"
)
assert issue
assert issue.severity == ir.IssueSeverity.ERROR
assert issue.translation_key == "duplicate_instance_id"
assert issue.translation_placeholders == {
"other_host_url": "other-host.local",
"other_ip": "10.0.0.1",
"instance_id": "abc123",
}
with (
patch(
"homeassistant.components.zeroconf.discovery.AsyncServiceInfo",
side_effect=lambda service_type, name: _get_hass_service_info_mock(
service_type, name, instance_id="different-id"
),
),
):
# Now test that the issue is removed when the service goes away
service_state_change_mock(
mock_browser.call_args[0][0],
[ZEROCONF_TYPE],
mock_browser.call_args[1]["handlers"],
state_change=ServiceStateChange.Updated,
)
assert (
issue_registry.async_get_issue(
domain="zeroconf", issue_id="duplicate_instance_id"
)
is None
)
@pytest.mark.usefixtures("mock_async_zeroconf")
async def test_instance_id_no_repair_issue_own_ip(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test that no repair issue is created when the other instance ID matches our IP."""
with (
patch("homeassistant.helpers.instance_id.async_get", return_value="abc123"),
patch.object(discovery, "AsyncServiceBrowser", side_effect=service_update_mock),
patch.object(hass.config_entries.flow, "async_init"),
patch(
"homeassistant.components.zeroconf.discovery.AsyncServiceInfo",
side_effect=_get_hass_service_info_mock,
),
patch(
"homeassistant.components.network.async_get_announce_addresses",
return_value=["10.0.0.1", "10.0.0.2"],
),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert (
issue_registry.async_get_issue(
domain="zeroconf", issue_id="duplicate_instance_id"
)
is None
)
@pytest.mark.usefixtures("mock_async_zeroconf")
async def test_instance_id_no_conflict_no_repair_issue(
hass: HomeAssistant, issue_registry: ir.IssueRegistry
) -> None:
"""Test that a repair issue is not created when no instance ID conflict exists."""
with (
patch("homeassistant.helpers.instance_id.async_get", return_value="xyz123"),
patch.object(discovery, "AsyncServiceBrowser", side_effect=service_update_mock),
patch.object(hass.config_entries.flow, "async_init"),
patch(
"homeassistant.components.zeroconf.discovery.AsyncServiceInfo",
side_effect=_get_hass_service_info_mock,
),
patch("homeassistant.helpers.issue_registry.async_create_issue"),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert (
issue_registry.async_get_issue(
domain="zeroconf", issue_id="duplicate_instance_id"
)
is None
)
async def test_create_fix_flow_raises_on_unknown_issue_id(hass: HomeAssistant) -> None:
"""Test create_fix_flow raises on unknown issue_id."""
with pytest.raises(ValueError):
await repairs.async_create_fix_flow(hass, "no_such_issue", None)
@pytest.mark.usefixtures("mock_async_zeroconf")
async def test_duplicate_repair_issue_repair_flow(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test desired flow of the fix flow for duplicate instance ID."""
assert await async_setup_component(hass, REPAIRS_DOMAIN, {REPAIRS_DOMAIN: {}})
assert await async_setup_component(hass, HOMEASSISTANT_DOMAIN, {})
await async_process_repairs_platforms(hass)
with (
patch("homeassistant.helpers.instance_id.async_get", return_value="abc123"),
patch.object(discovery, "AsyncServiceBrowser", side_effect=service_update_mock),
patch.object(hass.config_entries.flow, "async_init"),
patch(
"homeassistant.components.zeroconf.discovery.AsyncServiceInfo",
side_effect=_get_hass_service_info_mock,
),
patch.object(
instance_id, "async_recreate", return_value="new-uuid"
) as mock_recreate,
patch("homeassistant.config.async_check_ha_config_file", return_value=None),
patch("homeassistant.core.HomeAssistant.async_stop", return_value=None),
):
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
issue = issue_registry.async_get_issue(
domain="zeroconf", issue_id="duplicate_instance_id"
)
assert issue is not None
client = await hass_client()
result = await start_repair_fix_flow(client, DOMAIN, issue.issue_id)
flow_id = result["flow_id"]
assert result["type"] == FlowResultType.FORM
assert result["step_id"] == "confirm_recreate"
result = await process_repair_fix_flow(client, flow_id, json={})
assert result["type"] == "create_entry"
await hass.async_block_till_done()
assert mock_recreate.called
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/zeroconf/test_repairs.py",
"license": "Apache License 2.0",
"lines": 244,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/xbox/test_binary_sensor.py | """Test the Xbox binary_sensor platform."""
from collections.abc import Generator
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from homeassistant.components.xbox.binary_sensor import XboxBinarySensor
from homeassistant.components.xbox.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture(autouse=True)
def binary_sensor_only() -> Generator[None]:
"""Enable only the binary_sensor platform."""
with patch(
"homeassistant.components.xbox.PLATFORMS",
[Platform.BINARY_SENSOR],
):
yield
@pytest.mark.usefixtures("xbox_live_client", "entity_registry_enabled_by_default")
async def test_binary_sensors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test setup of the Xbox binary_sensor platform."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize(
("entity_id", "key"),
[
("gsr_ae_in_multiplayer", XboxBinarySensor.IN_MULTIPLAYER),
("gsr_ae_in_party", XboxBinarySensor.IN_PARTY),
],
)
@pytest.mark.usefixtures("xbox_live_client", "entity_registry_enabled_by_default")
async def test_binary_sensor_deprecation_remove_disabled(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
entity_id: str,
key: XboxBinarySensor,
) -> None:
"""Test we remove a deprecated binary sensor."""
entity_registry.async_get_or_create(
BINARY_SENSOR_DOMAIN,
DOMAIN,
f"271958441785640_{key}",
suggested_object_id=entity_id,
)
assert entity_registry is not None
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
assert entity_registry.async_get(f"binary_sensor.{entity_id}") is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/xbox/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:tests/components/xbox/test_sensor.py | """Test the Xbox sensor platform."""
from collections.abc import Generator
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.xbox.const import DOMAIN
from homeassistant.components.xbox.sensor import XboxSensor
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.fixture(autouse=True)
def sensor_only() -> Generator[None]:
"""Enable only the sensor platform."""
with patch(
"homeassistant.components.xbox.PLATFORMS",
[Platform.SENSOR],
):
yield
@pytest.mark.usefixtures("xbox_live_client", "entity_registry_enabled_by_default")
async def test_sensors(
hass: HomeAssistant,
config_entry: MockConfigEntry,
snapshot: SnapshotAssertion,
entity_registry: er.EntityRegistry,
) -> None:
"""Test setup of the Xbox sensor platform."""
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize(
("entity_id", "key"),
[
("gsr_ae_account_tier", XboxSensor.ACCOUNT_TIER),
("gsr_ae_gold_tenure", XboxSensor.GOLD_TENURE),
],
)
@pytest.mark.usefixtures("xbox_live_client", "entity_registry_enabled_by_default")
async def test_sensor_deprecation_remove_entity(
hass: HomeAssistant,
config_entry: MockConfigEntry,
entity_registry: er.EntityRegistry,
entity_id: str,
key: XboxSensor,
) -> None:
"""Test we remove a deprecated sensor."""
entity_registry.async_get_or_create(
SENSOR_DOMAIN,
DOMAIN,
f"271958441785640_{key}",
suggested_object_id=entity_id,
)
assert entity_registry is not None
config_entry.add_to_hass(hass)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
assert config_entry.state is ConfigEntryState.LOADED
assert entity_registry.async_get(f"sensor.{entity_id}") is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/xbox/test_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:tests/helpers/template/helpers.py | """Helpers for tests around template rendering."""
from __future__ import annotations
from collections.abc import Iterable
from typing import Any
from homeassistant.core import HomeAssistant
from homeassistant.helpers import template
from homeassistant.helpers.typing import TemplateVarsType
def render(
hass: HomeAssistant,
template_str: str,
variables: TemplateVarsType | None = None,
**render_kwargs: Any,
) -> Any:
"""Render template and return result."""
return template.Template(template_str, hass).async_render(
variables, **render_kwargs
)
def render_to_info(
hass: HomeAssistant, template_str: str, variables: TemplateVarsType | None = None
) -> template.RenderInfo:
"""Create render info from template."""
return template.Template(template_str, hass).async_render_to_info(variables)
def extract_entities(
hass: HomeAssistant, template_str: str, variables: TemplateVarsType | None = None
) -> set[str]:
"""Extract entities from a template."""
return render_to_info(hass, template_str, variables).entities
def assert_result_info(
info: template.RenderInfo,
result: Any,
entities: Iterable[str] | None = None,
domains: Iterable[str] | None = None,
all_states: bool = False,
) -> None:
"""Check result info."""
actual = info.result()
assert actual == result, (
f"Template result mismatch:\n"
f" Expected: {result!r} (type: {type(result).__name__})\n"
f" Actual: {actual!r} (type: {type(actual).__name__})\n"
f" Template: {info.template!r}"
)
assert info.all_states == all_states
assert info.filter("invalid_entity_name.somewhere") == all_states
if entities is not None:
assert info.entities == frozenset(entities)
assert all(info.filter(entity) for entity in entities)
if not all_states:
assert not info.filter("invalid_entity_name.somewhere")
else:
assert not info.entities
if domains is not None:
assert info.domains == frozenset(domains)
assert all(info.filter(domain + ".entity") for domain in domains)
else:
assert not hasattr(info, "_domains")
| {
"repo_id": "home-assistant/core",
"file_path": "tests/helpers/template/helpers.py",
"license": "Apache License 2.0",
"lines": 56,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/unifi/test_light.py | """UniFi Network light platform tests."""
from copy import deepcopy
from unittest.mock import patch
from aiounifi.models.message import MessageKey
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_RGB_COLOR,
DOMAIN as LIGHT_DOMAIN,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.components.unifi.const import CONF_SITE_ID
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_HOST,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE,
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from .conftest import (
ConfigEntryFactoryType,
WebsocketMessageMock,
WebsocketStateManager,
)
from tests.common import MockConfigEntry, snapshot_platform
from tests.test_util.aiohttp import AiohttpClientMocker
DEVICE_WITH_LED = {
"board_rev": 3,
"device_id": "mock-id",
"ip": "10.0.0.1",
"last_seen": 1562600145,
"mac": "10:00:00:00:01:01",
"model": "U6-Lite",
"name": "Device with LED",
"next_interval": 20,
"state": 1,
"type": "uap",
"version": "4.0.42.10433",
"led_override": "on",
"led_override_color": "#0000ff",
"led_override_color_brightness": 80,
"hw_caps": 2,
}
DEVICE_WITHOUT_LED = {
"board_rev": 2,
"device_id": "mock-id-2",
"ip": "10.0.0.2",
"last_seen": 1562600145,
"mac": "10:00:00:00:01:02",
"model": "US-8-60W",
"name": "Device without LED",
"next_interval": 20,
"state": 1,
"type": "usw",
"version": "4.0.42.10433",
"hw_caps": 0,
}
DEVICE_LED_OFF = {
"board_rev": 3,
"device_id": "mock-id-3",
"ip": "10.0.0.3",
"last_seen": 1562600145,
"mac": "10:00:00:00:01:03",
"model": "U6-Pro",
"name": "Device LED Off",
"next_interval": 20,
"state": 1,
"type": "uap",
"version": "4.0.42.10433",
"led_override": "off",
"led_override_color": "#ffffff",
"led_override_color_brightness": 0,
"hw_caps": 2,
}
DEVICE_WITH_LED_NO_RGB = {
"board_rev": 2,
"device_id": "mock-id-4",
"ip": "10.0.0.4",
"last_seen": 1562600145,
"mac": "10:00:00:00:01:04",
"model": "US-16-150W",
"name": "Device LED No RGB",
"next_interval": 20,
"state": 1,
"type": "usw",
"version": "4.0.42.10433",
"led_override": "on",
"led_override_color": "#ffffff",
"led_override_color_brightness": 100,
"hw_caps": 0,
}
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED, DEVICE_WITHOUT_LED]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_lights(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Test lights."""
assert len(hass.states.async_entity_ids(LIGHT_DOMAIN)) == 1
light_entity = hass.states.get("light.device_with_led_led")
assert light_entity is not None
assert light_entity.state == STATE_ON
assert light_entity.attributes["brightness"] == 204
assert light_entity.attributes["rgb_color"] == (0, 0, 255)
assert hass.states.get("light.device_without_led_led") is None
@pytest.mark.parametrize("device_payload", [[DEVICE_LED_OFF]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_off_state(
hass: HomeAssistant,
) -> None:
"""Test light off state."""
assert len(hass.states.async_entity_ids(LIGHT_DOMAIN)) == 1
light_entity = hass.states.get("light.device_led_off_led")
assert light_entity is not None
assert light_entity.state == STATE_OFF
assert light_entity.attributes.get("brightness") is None
assert light_entity.attributes.get("rgb_color") is None
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_turn_on_off(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Test turn on and off."""
aioclient_mock.clear_requests()
aioclient_mock.put(
f"https://{config_entry_setup.data[CONF_HOST]}:1234"
f"/api/s/{config_entry_setup.data[CONF_SITE_ID]}/rest/device/mock-id",
)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "light.device_with_led_led"},
blocking=True,
)
assert aioclient_mock.call_count == 1
call_data = aioclient_mock.mock_calls[0][2]
assert call_data["led_override"] == "off"
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "light.device_with_led_led"},
blocking=True,
)
assert aioclient_mock.call_count == 2
call_data = aioclient_mock.mock_calls[1][2]
assert call_data["led_override"] == "on"
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_set_brightness(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Test set brightness."""
aioclient_mock.clear_requests()
aioclient_mock.put(
f"https://{config_entry_setup.data[CONF_HOST]}:1234"
f"/api/s/{config_entry_setup.data[CONF_SITE_ID]}/rest/device/mock-id",
)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.device_with_led_led",
ATTR_BRIGHTNESS: 127,
},
blocking=True,
)
assert aioclient_mock.call_count == 1
call_data = aioclient_mock.mock_calls[0][2]
assert call_data["led_override"] == "on"
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_set_rgb_color(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Test set RGB color."""
aioclient_mock.clear_requests()
aioclient_mock.put(
f"https://{config_entry_setup.data[CONF_HOST]}:1234"
f"/api/s/{config_entry_setup.data[CONF_SITE_ID]}/rest/device/mock-id",
)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.device_with_led_led",
ATTR_RGB_COLOR: (255, 0, 0),
},
blocking=True,
)
assert aioclient_mock.call_count == 1
call_data = aioclient_mock.mock_calls[0][2]
assert call_data["led_override"] == "on"
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_set_brightness_and_color(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Test set brightness and color."""
aioclient_mock.clear_requests()
aioclient_mock.put(
f"https://{config_entry_setup.data[CONF_HOST]}:1234"
f"/api/s/{config_entry_setup.data[CONF_SITE_ID]}/rest/device/mock-id",
)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{
ATTR_ENTITY_ID: "light.device_with_led_led",
ATTR_RGB_COLOR: (0, 255, 0),
ATTR_BRIGHTNESS: 191,
},
blocking=True,
)
assert aioclient_mock.call_count == 1
call_data = aioclient_mock.mock_calls[0][2]
assert call_data["led_override"] == "on"
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_state_update_via_websocket(
hass: HomeAssistant,
mock_websocket_message: WebsocketMessageMock,
) -> None:
"""Test state update via websocket."""
light_entity = hass.states.get("light.device_with_led_led")
assert light_entity is not None
assert light_entity.state == STATE_ON
assert light_entity.attributes["rgb_color"] == (0, 0, 255)
updated_device = deepcopy(DEVICE_WITH_LED)
updated_device["led_override"] = "off"
updated_device["led_override_color"] = "#ff0000"
updated_device["led_override_color_brightness"] = 100
mock_websocket_message(message=MessageKey.DEVICE, data=[updated_device])
await hass.async_block_till_done()
light_entity = hass.states.get("light.device_with_led_led")
assert light_entity is not None
assert light_entity.state == STATE_OFF
assert light_entity.attributes.get("rgb_color") is None
assert light_entity.attributes.get("brightness") is None
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_device_offline(
hass: HomeAssistant,
mock_websocket_message: WebsocketMessageMock,
) -> None:
"""Test device offline."""
assert len(hass.states.async_entity_ids(LIGHT_DOMAIN)) == 1
assert hass.states.get("light.device_with_led_led") is not None
offline_device = deepcopy(DEVICE_WITH_LED)
offline_device["state"] = 0
mock_websocket_message(message=MessageKey.DEVICE, data=[offline_device])
await hass.async_block_till_done()
light_entity = hass.states.get("light.device_with_led_led")
assert light_entity is not None
assert light_entity.state == STATE_ON
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_device_unavailable(
hass: HomeAssistant,
mock_websocket_state: WebsocketStateManager,
) -> None:
"""Test device unavailable."""
light_entity = hass.states.get("light.device_with_led_led")
assert light_entity is not None
assert light_entity.state == STATE_ON
updated_device = deepcopy(DEVICE_WITH_LED)
updated_device["state"] = 0
await mock_websocket_state.disconnect()
await hass.async_block_till_done()
light_entity = hass.states.get("light.device_with_led_led")
assert light_entity is not None
assert light_entity.state == STATE_UNAVAILABLE
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED]])
async def test_light_platform_snapshot(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
config_entry_factory: ConfigEntryFactoryType,
snapshot: SnapshotAssertion,
) -> None:
"""Test platform snapshot."""
with patch("homeassistant.components.unifi.PLATFORMS", [Platform.LIGHT]):
config_entry = await config_entry_factory()
await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id)
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED_NO_RGB]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_onoff_mode_only(
hass: HomeAssistant,
) -> None:
"""Test light with ONOFF mode only (no LED ring support)."""
assert len(hass.states.async_entity_ids(LIGHT_DOMAIN)) == 1
light_entity = hass.states.get("light.device_led_no_rgb_led")
assert light_entity is not None
assert light_entity.state == STATE_ON
# Device without LED ring support should not expose brightness or RGB
assert light_entity.attributes.get("brightness") is None
assert light_entity.attributes.get("rgb_color") is None
assert light_entity.attributes.get("supported_color_modes") == ["onoff"]
assert light_entity.attributes.get("color_mode") == "onoff"
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED_NO_RGB]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_onoff_mode_turn_on_off(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
config_entry_setup: MockConfigEntry,
) -> None:
"""Test ONOFF-only light turn on and off."""
aioclient_mock.clear_requests()
aioclient_mock.put(
f"https://{config_entry_setup.data[CONF_HOST]}:1234"
f"/api/s/{config_entry_setup.data[CONF_SITE_ID]}/rest/device/mock-id-4",
)
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_OFF,
{ATTR_ENTITY_ID: "light.device_led_no_rgb_led"},
blocking=True,
)
assert aioclient_mock.call_count == 1
call_data = aioclient_mock.mock_calls[0][2]
assert call_data["led_override"] == "off"
# Should not send brightness or color for ONOFF-only devices
assert call_data.get("led_override_color_brightness") is None
assert call_data.get("led_override_color") is None
await hass.services.async_call(
LIGHT_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: "light.device_led_no_rgb_led"},
blocking=True,
)
assert aioclient_mock.call_count == 2
call_data = aioclient_mock.mock_calls[1][2]
assert call_data["led_override"] == "on"
# Should not send brightness or color for ONOFF-only devices
assert call_data.get("led_override_color_brightness") is None
assert call_data.get("led_override_color") is None
@pytest.mark.parametrize("device_payload", [[DEVICE_WITH_LED, DEVICE_WITH_LED_NO_RGB]])
@pytest.mark.usefixtures("config_entry_setup")
async def test_light_rgb_vs_onoff_modes(
hass: HomeAssistant,
) -> None:
"""Test that RGB and ONOFF modes are correctly assigned based on device capabilities."""
assert len(hass.states.async_entity_ids(LIGHT_DOMAIN)) == 2
# Device with LED ring support should have RGB mode
rgb_light = hass.states.get("light.device_with_led_led")
assert rgb_light is not None
assert rgb_light.state == STATE_ON
assert rgb_light.attributes.get("supported_color_modes") == ["rgb"]
assert rgb_light.attributes.get("color_mode") == "rgb"
assert rgb_light.attributes.get("brightness") == 204
assert rgb_light.attributes.get("rgb_color") == (0, 0, 255)
# Device without LED ring support should have ONOFF mode
onoff_light = hass.states.get("light.device_led_no_rgb_led")
assert onoff_light is not None
assert onoff_light.state == STATE_ON
assert onoff_light.attributes.get("supported_color_modes") == ["onoff"]
assert onoff_light.attributes.get("color_mode") == "onoff"
assert onoff_light.attributes.get("brightness") is None
assert onoff_light.attributes.get("rgb_color") is None
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/unifi/test_light.py",
"license": "Apache License 2.0",
"lines": 371,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/volvo/test_button.py | """Test Volvo buttons."""
from collections.abc import Awaitable, Callable
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from volvocarsapi.api import VolvoCarsApi
from volvocarsapi.models import VolvoApiException, VolvoCarsCommandResult
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 . import configure_mock
from .const import DEFAULT_VIN
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("mock_api", "full_model")
@pytest.mark.parametrize(
"full_model",
["ex30_2024", "s90_diesel_2018", "xc40_electric_2024", "xc90_petrol_2019"],
)
async def test_button(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test button."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.BUTTON]):
assert await setup_integration()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.usefixtures("full_model")
@pytest.mark.parametrize(
"command",
[
"start_climatization",
"stop_climatization",
"flash",
"honk",
"honk_flash",
"lock_reduced_guard",
],
)
async def test_button_press(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
command: str,
) -> None:
"""Test button press."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.BUTTON]):
assert await setup_integration()
entity_id = f"button.volvo_xc40_{command}"
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
await hass.async_block_till_done()
assert len(mock_api.async_execute_command.mock_calls) == 1
@pytest.mark.usefixtures("full_model")
@pytest.mark.parametrize(
"command",
[
"start_climatization",
"stop_climatization",
"flash",
"honk",
"honk_flash",
"lock_reduced_guard",
],
)
async def test_button_press_error(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
command: str,
) -> None:
"""Test button press with error response."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.BUTTON]):
assert await setup_integration()
configure_mock(mock_api.async_execute_command, side_effect=VolvoApiException)
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: f"button.volvo_xc40_{command}"},
blocking=True,
)
@pytest.mark.usefixtures("full_model")
@pytest.mark.parametrize(
"command",
[
"start_climatization",
"stop_climatization",
"flash",
"honk",
"honk_flash",
"lock_reduced_guard",
],
)
async def test_button_press_failure(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
mock_api: VolvoCarsApi,
command: str,
) -> None:
"""Test button press with business logic failure."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.BUTTON]):
assert await setup_integration()
configure_mock(
mock_api.async_execute_command,
return_value=VolvoCarsCommandResult(
vin=DEFAULT_VIN, invoke_status="CONNECTION_FAILURE", message=""
),
)
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
BUTTON_DOMAIN,
SERVICE_PRESS,
{ATTR_ENTITY_ID: f"button.volvo_xc40_{command}"},
blocking=True,
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/volvo/test_button.py",
"license": "Apache License 2.0",
"lines": 124,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/volvo/test_device_tracker.py | """Test Volvo device tracker."""
from collections.abc import Awaitable, Callable
from unittest.mock import patch
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from tests.common import MockConfigEntry, snapshot_platform
@pytest.mark.usefixtures("mock_api", "full_model")
@pytest.mark.parametrize(
"full_model",
["ex30_2024", "s90_diesel_2018", "xc40_electric_2024", "xc90_petrol_2019"],
)
async def test_device_tracker(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test device tracker."""
with patch("homeassistant.components.volvo.PLATFORMS", [Platform.DEVICE_TRACKER]):
assert await setup_integration()
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/volvo/test_device_tracker.py",
"license": "Apache License 2.0",
"lines": 25,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/satel_integra/test_init.py | """Test init of Satel Integra integration."""
from copy import deepcopy
from unittest.mock import AsyncMock
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.alarm_control_panel import DOMAIN as ALARM_PANEL_DOMAIN
from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN
from homeassistant.components.satel_integra.const import DOMAIN
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.config_entries import ConfigSubentry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.device_registry import DeviceRegistry
from homeassistant.helpers.entity_registry import EntityRegistry
from . import (
CONF_OUTPUT_NUMBER,
CONF_PARTITION_NUMBER,
CONF_SWITCHABLE_OUTPUT_NUMBER,
CONF_ZONE_NUMBER,
MOCK_CONFIG_DATA,
MOCK_CONFIG_OPTIONS,
MOCK_ENTRY_ID,
MOCK_OUTPUT_SUBENTRY,
MOCK_PARTITION_SUBENTRY,
MOCK_SWITCHABLE_OUTPUT_SUBENTRY,
MOCK_ZONE_SUBENTRY,
setup_integration,
)
from tests.common import MockConfigEntry
@pytest.mark.parametrize(
("original", "number_property"),
[
(MOCK_PARTITION_SUBENTRY, CONF_PARTITION_NUMBER),
(MOCK_ZONE_SUBENTRY, CONF_ZONE_NUMBER),
(MOCK_OUTPUT_SUBENTRY, CONF_OUTPUT_NUMBER),
(MOCK_SWITCHABLE_OUTPUT_SUBENTRY, CONF_SWITCHABLE_OUTPUT_NUMBER),
],
)
async def test_config_flow_migration_version_1_2(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_satel: AsyncMock,
original: ConfigSubentry,
number_property: str,
) -> None:
"""Test that the configured number is added to the subentry title."""
config_entry = MockConfigEntry(
domain=DOMAIN,
title="192.168.0.2",
data=MOCK_CONFIG_DATA,
options=MOCK_CONFIG_OPTIONS,
entry_id=MOCK_ENTRY_ID,
version=1,
minor_version=1,
)
config_entry.subentries = deepcopy({original.subentry_id: original})
await setup_integration(hass, config_entry)
assert config_entry.version == 2
assert config_entry.minor_version == 1
subentry = config_entry.subentries.get(original.subentry_id)
assert subentry is not None
assert subentry.title == f"{original.title} ({original.data[number_property]})"
assert subentry == snapshot
@pytest.mark.parametrize(
("platform", "old_id", "new_id"),
[
(ALARM_PANEL_DOMAIN, "satel_alarm_panel_1", f"{MOCK_ENTRY_ID}_alarm_panel_1"),
(BINARY_SENSOR_DOMAIN, "satel_zone_1", f"{MOCK_ENTRY_ID}_zone_1"),
(BINARY_SENSOR_DOMAIN, "satel_output_1", f"{MOCK_ENTRY_ID}_output_1"),
(SWITCH_DOMAIN, "satel_switch_1", f"{MOCK_ENTRY_ID}_switch_1"),
],
)
async def test_unique_id_migration_from_single_config(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_satel: AsyncMock,
entity_registry: EntityRegistry,
platform: str,
old_id: str,
new_id: str,
) -> None:
"""Test that the unique ID is migrated to use the config entry id."""
config_entry = MockConfigEntry(
domain=DOMAIN,
title="192.168.0.2",
data=MOCK_CONFIG_DATA,
options=MOCK_CONFIG_OPTIONS,
entry_id=MOCK_ENTRY_ID,
version=1,
minor_version=1,
)
config_entry.add_to_hass(hass)
entity = entity_registry.async_get_or_create(
platform,
DOMAIN,
old_id,
config_entry=config_entry,
)
await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
entity = entity_registry.async_get(entity.entity_id)
assert entity is not None
assert entity.unique_id == new_id
assert entity == snapshot
async def test_parent_device_exists(
hass: HomeAssistant,
snapshot: SnapshotAssertion,
mock_satel: AsyncMock,
device_registry: DeviceRegistry,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test that a parent device is created for the alarm panel."""
await setup_integration(hass, mock_config_entry)
device_entry = device_registry.async_get_device(
identifiers={(DOMAIN, MOCK_ENTRY_ID)}
)
assert device_entry == snapshot(name="parent-device")
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/satel_integra/test_init.py",
"license": "Apache License 2.0",
"lines": 116,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/solaredge/test_init.py | """Tests for the SolarEdge integration."""
from unittest.mock import AsyncMock, Mock, patch
from aiohttp import ClientError
from homeassistant.components.recorder import Recorder
from homeassistant.components.solaredge.const import CONF_SITE_ID, DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_API_KEY, CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from .conftest import API_KEY, PASSWORD, SITE_ID, USERNAME
from tests.common import MockConfigEntry
@patch(
"homeassistant.config_entries.ConfigEntries.async_unload_platforms",
return_value=True,
)
async def test_setup_unload_api_key(
mock_unload_platforms: AsyncMock,
recorder_mock: Recorder,
hass: HomeAssistant,
solaredge_api: Mock,
) -> None:
"""Test successful setup and unload of a config entry with API key."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_SITE_ID: SITE_ID, CONF_API_KEY: API_KEY},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.LOADED
assert solaredge_api.get_details.await_count == 2
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
# Unloading should be attempted because sensors were set up.
mock_unload_platforms.assert_awaited_once()
assert entry.state is ConfigEntryState.NOT_LOADED
@patch(
"homeassistant.config_entries.ConfigEntries.async_unload_platforms",
return_value=True,
)
async def test_setup_unload_web_login(
mock_unload_platforms: AsyncMock,
recorder_mock: Recorder,
hass: HomeAssistant,
solaredge_web_api: AsyncMock,
) -> None:
"""Test successful setup and unload of a config entry with web login."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_SITE_ID: SITE_ID,
CONF_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.LOADED
solaredge_web_api.async_get_equipment.assert_awaited_once()
solaredge_web_api.async_get_energy_data.assert_awaited_once()
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
# Unloading should NOT be attempted because sensors were not set up.
mock_unload_platforms.assert_not_called()
assert entry.state is ConfigEntryState.NOT_LOADED
@patch(
"homeassistant.config_entries.ConfigEntries.async_unload_platforms",
return_value=True,
)
async def test_setup_unload_both(
mock_unload_platforms: AsyncMock,
recorder_mock: Recorder,
hass: HomeAssistant,
solaredge_api: Mock,
solaredge_web_api: AsyncMock,
) -> None:
"""Test successful setup and unload of a config entry with both auth methods."""
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_SITE_ID: SITE_ID,
CONF_API_KEY: API_KEY,
CONF_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.LOADED
assert solaredge_api.get_details.await_count == 2
solaredge_web_api.async_get_equipment.assert_awaited_once()
solaredge_web_api.async_get_energy_data.assert_awaited_once()
assert await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
mock_unload_platforms.assert_awaited_once()
assert entry.state is ConfigEntryState.NOT_LOADED
async def test_api_key_config_not_ready(
recorder_mock: Recorder, hass: HomeAssistant, solaredge_api: Mock
) -> None:
"""Test for setup failure with API key."""
solaredge_api.get_details.side_effect = ClientError()
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_SITE_ID: SITE_ID, CONF_API_KEY: API_KEY},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.SETUP_RETRY
async def test_web_login_config_not_ready(
recorder_mock: Recorder, hass: HomeAssistant, solaredge_web_api: AsyncMock
) -> None:
"""Test for setup failure with web login."""
solaredge_web_api.async_get_equipment.side_effect = ClientError()
entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_SITE_ID: SITE_ID,
CONF_USERNAME: USERNAME,
CONF_PASSWORD: PASSWORD,
},
)
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.SETUP_RETRY
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/solaredge/test_init.py",
"license": "Apache License 2.0",
"lines": 127,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/telegram_bot/test_diagnostics.py | """Tests for Telegram bot diagnostics."""
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.telegram_bot.const import DOMAIN
from homeassistant.core import HomeAssistant
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
async def test_diagnostics(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
webhook_bot,
snapshot: SnapshotAssertion,
) -> None:
"""Test diagnostics."""
config_entry = hass.config_entries.async_entries(DOMAIN)[0]
diagnostics = await get_diagnostics_for_config_entry(
hass, hass_client, config_entry
)
assert diagnostics == snapshot
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/telegram_bot/test_diagnostics.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/volvo/test_diagnostics.py | """Test Volvo diagnostics."""
from collections.abc import Awaitable, Callable
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.const import CONF_TOKEN
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
from tests.components.diagnostics import get_diagnostics_for_config_entry
from tests.typing import ClientSessionGenerator
@pytest.mark.usefixtures("mock_api")
async def test_entry_diagnostics(
hass: HomeAssistant,
setup_integration: Callable[[], Awaitable[bool]],
hass_client: ClientSessionGenerator,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test config entry diagnostics."""
assert await setup_integration()
await hass.async_block_till_done()
# Give it a fixed timestamp so it won't change with every test run
mock_config_entry.data[CONF_TOKEN]["expires_at"] = 1759919745.7328658
assert (
await get_diagnostics_for_config_entry(hass, hass_client, mock_config_entry)
== snapshot
)
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/volvo/test_diagnostics.py",
"license": "Apache License 2.0",
"lines": 26,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:tests/components/recorder/db_schema_48.py | """Models for SQLAlchemy.
This file contains the model definitions for schema version 48.
It is used to test the schema migration logic.
"""
from __future__ import annotations
from collections.abc import Callable
from datetime import datetime, timedelta
import logging
import time
from typing import Any, Final, Self, cast
import ciso8601
from fnv_hash_fast import fnv1a_32
from sqlalchemy import (
CHAR,
JSON,
BigInteger,
Boolean,
ColumnElement,
DateTime,
Float,
ForeignKey,
Identity,
Index,
Integer,
LargeBinary,
SmallInteger,
String,
Text,
case,
type_coerce,
)
from sqlalchemy.dialects import mysql, oracle, postgresql, sqlite
from sqlalchemy.engine.interfaces import Dialect
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.orm import DeclarativeBase, Mapped, aliased, mapped_column, relationship
from sqlalchemy.types import TypeDecorator
from homeassistant.components.recorder.const import (
ALL_DOMAIN_EXCLUDE_ATTRS,
SupportedDialect,
)
from homeassistant.components.recorder.models import (
StatisticData,
StatisticDataTimestamp,
StatisticMetaData,
bytes_to_ulid_or_none,
bytes_to_uuid_hex_or_none,
datetime_to_timestamp_or_none,
process_timestamp,
ulid_to_bytes_or_none,
uuid_hex_to_bytes_or_none,
)
from homeassistant.components.sensor import ATTR_STATE_CLASS
from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_FRIENDLY_NAME,
ATTR_UNIT_OF_MEASUREMENT,
MATCH_ALL,
MAX_LENGTH_EVENT_EVENT_TYPE,
MAX_LENGTH_STATE_ENTITY_ID,
MAX_LENGTH_STATE_STATE,
)
from homeassistant.core import Context, Event, EventOrigin, EventStateChangedData, State
from homeassistant.helpers.json import JSON_DUMP, json_bytes, json_bytes_strip_null
from homeassistant.util import dt as dt_util
from homeassistant.util.json import (
JSON_DECODE_EXCEPTIONS,
json_loads,
json_loads_object,
)
# SQLAlchemy Schema
class Base(DeclarativeBase):
"""Base class for tables."""
class LegacyBase(DeclarativeBase):
"""Base class for tables, used for schema migration."""
SCHEMA_VERSION = 48
_LOGGER = logging.getLogger(__name__)
TABLE_EVENTS = "events"
TABLE_EVENT_DATA = "event_data"
TABLE_EVENT_TYPES = "event_types"
TABLE_STATES = "states"
TABLE_STATE_ATTRIBUTES = "state_attributes"
TABLE_STATES_META = "states_meta"
TABLE_RECORDER_RUNS = "recorder_runs"
TABLE_SCHEMA_CHANGES = "schema_changes"
TABLE_STATISTICS = "statistics"
TABLE_STATISTICS_META = "statistics_meta"
TABLE_STATISTICS_RUNS = "statistics_runs"
TABLE_STATISTICS_SHORT_TERM = "statistics_short_term"
TABLE_MIGRATION_CHANGES = "migration_changes"
STATISTICS_TABLES = ("statistics", "statistics_short_term")
MAX_STATE_ATTRS_BYTES = 16384
MAX_EVENT_DATA_BYTES = 32768
PSQL_DIALECT = SupportedDialect.POSTGRESQL
ALL_TABLES = [
TABLE_STATES,
TABLE_STATE_ATTRIBUTES,
TABLE_EVENTS,
TABLE_EVENT_DATA,
TABLE_EVENT_TYPES,
TABLE_RECORDER_RUNS,
TABLE_SCHEMA_CHANGES,
TABLE_MIGRATION_CHANGES,
TABLE_STATES_META,
TABLE_STATISTICS,
TABLE_STATISTICS_META,
TABLE_STATISTICS_RUNS,
TABLE_STATISTICS_SHORT_TERM,
]
TABLES_TO_CHECK = [
TABLE_STATES,
TABLE_EVENTS,
TABLE_RECORDER_RUNS,
TABLE_SCHEMA_CHANGES,
]
LAST_UPDATED_INDEX_TS = "ix_states_last_updated_ts"
METADATA_ID_LAST_UPDATED_INDEX_TS = "ix_states_metadata_id_last_updated_ts"
EVENTS_CONTEXT_ID_BIN_INDEX = "ix_events_context_id_bin"
STATES_CONTEXT_ID_BIN_INDEX = "ix_states_context_id_bin"
LEGACY_STATES_EVENT_ID_INDEX = "ix_states_event_id"
LEGACY_STATES_ENTITY_ID_LAST_UPDATED_TS_INDEX = "ix_states_entity_id_last_updated_ts"
LEGACY_MAX_LENGTH_EVENT_CONTEXT_ID: Final = 36
CONTEXT_ID_BIN_MAX_LENGTH = 16
MYSQL_COLLATE = "utf8mb4_unicode_ci"
MYSQL_DEFAULT_CHARSET = "utf8mb4"
MYSQL_ENGINE = "InnoDB"
_DEFAULT_TABLE_ARGS = {
"mysql_default_charset": MYSQL_DEFAULT_CHARSET,
"mysql_collate": MYSQL_COLLATE,
"mysql_engine": MYSQL_ENGINE,
"mariadb_default_charset": MYSQL_DEFAULT_CHARSET,
"mariadb_collate": MYSQL_COLLATE,
"mariadb_engine": MYSQL_ENGINE,
}
_MATCH_ALL_KEEP = {
ATTR_DEVICE_CLASS,
ATTR_STATE_CLASS,
ATTR_UNIT_OF_MEASUREMENT,
ATTR_FRIENDLY_NAME,
}
class UnusedDateTime(DateTime):
"""An unused column type that behaves like a datetime."""
class Unused(CHAR):
"""An unused column type that behaves like a string."""
@compiles(UnusedDateTime, "mysql", "mariadb", "sqlite")
@compiles(Unused, "mysql", "mariadb", "sqlite")
def compile_char_zero(type_: TypeDecorator, compiler: Any, **kw: Any) -> str:
"""Compile UnusedDateTime and Unused as CHAR(0) on mysql, mariadb, and sqlite."""
return "CHAR(0)" # Uses 1 byte on MySQL (no change on sqlite)
@compiles(Unused, "postgresql")
def compile_char_one(type_: TypeDecorator, compiler: Any, **kw: Any) -> str:
"""Compile Unused as CHAR(1) on postgresql."""
return "CHAR(1)" # Uses 1 byte
class FAST_PYSQLITE_DATETIME(sqlite.DATETIME):
"""Use ciso8601 to parse datetimes instead of sqlalchemy built-in regex."""
def result_processor(self, dialect: Dialect, coltype: Any) -> Callable | None:
"""Offload the datetime parsing to ciso8601."""
return lambda value: None if value is None else ciso8601.parse_datetime(value)
class NativeLargeBinary(LargeBinary):
"""A faster version of LargeBinary for engines that support python bytes natively."""
def result_processor(self, dialect: Dialect, coltype: Any) -> Callable | None:
"""No conversion needed for engines that support native bytes."""
return None
# Although all integers are same in SQLite, it does not allow an identity column to be BIGINT
# https://sqlite.org/forum/info/2dfa968a702e1506e885cb06d92157d492108b22bf39459506ab9f7125bca7fd
ID_TYPE = BigInteger().with_variant(sqlite.INTEGER, "sqlite")
# For MariaDB and MySQL we can use an unsigned integer type since it will fit 2**32
# for sqlite and postgresql we use a bigint
UINT_32_TYPE = BigInteger().with_variant(
mysql.INTEGER(unsigned=True), # type: ignore[no-untyped-call]
"mysql",
"mariadb",
)
JSON_VARIANT_CAST = Text().with_variant(
postgresql.JSON(none_as_null=True), # type: ignore[no-untyped-call]
"postgresql",
)
JSONB_VARIANT_CAST = Text().with_variant(
postgresql.JSONB(none_as_null=True), # type: ignore[no-untyped-call]
"postgresql",
)
DATETIME_TYPE = (
DateTime(timezone=True)
.with_variant(mysql.DATETIME(timezone=True, fsp=6), "mysql", "mariadb") # type: ignore[no-untyped-call]
.with_variant(FAST_PYSQLITE_DATETIME(), "sqlite") # type: ignore[no-untyped-call]
)
DOUBLE_TYPE = (
Float()
.with_variant(mysql.DOUBLE(asdecimal=False), "mysql", "mariadb") # type: ignore[no-untyped-call]
.with_variant(oracle.DOUBLE_PRECISION(), "oracle")
.with_variant(postgresql.DOUBLE_PRECISION(), "postgresql")
)
UNUSED_LEGACY_COLUMN = Unused(0)
UNUSED_LEGACY_DATETIME_COLUMN = UnusedDateTime(timezone=True)
UNUSED_LEGACY_INTEGER_COLUMN = SmallInteger()
DOUBLE_PRECISION_TYPE_SQL = "DOUBLE PRECISION"
BIG_INTEGER_SQL = "BIGINT"
CONTEXT_BINARY_TYPE = LargeBinary(CONTEXT_ID_BIN_MAX_LENGTH).with_variant(
NativeLargeBinary(CONTEXT_ID_BIN_MAX_LENGTH), "mysql", "mariadb", "sqlite"
)
TIMESTAMP_TYPE = DOUBLE_TYPE
class JSONLiteral(JSON):
"""Teach SA how to literalize json."""
def literal_processor(self, dialect: Dialect) -> Callable[[Any], str]:
"""Processor to convert a value to JSON."""
def process(value: Any) -> str:
"""Dump json."""
return JSON_DUMP(value)
return process
EVENT_ORIGIN_ORDER = [EventOrigin.local, EventOrigin.remote]
class Events(Base):
"""Event history data."""
__table_args__ = (
# Used for fetching events at a specific time
# see logbook
Index(
"ix_events_event_type_id_time_fired_ts", "event_type_id", "time_fired_ts"
),
Index(
EVENTS_CONTEXT_ID_BIN_INDEX,
"context_id_bin",
mysql_length=CONTEXT_ID_BIN_MAX_LENGTH,
mariadb_length=CONTEXT_ID_BIN_MAX_LENGTH,
),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_EVENTS
event_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
event_type: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
event_data: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
origin: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
origin_idx: Mapped[int | None] = mapped_column(SmallInteger)
time_fired: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
time_fired_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE, index=True)
context_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
context_user_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
context_parent_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
data_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("event_data.data_id"), index=True
)
context_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
context_user_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
context_parent_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
event_type_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("event_types.event_type_id")
)
event_data_rel: Mapped[EventData | None] = relationship("EventData")
event_type_rel: Mapped[EventTypes | None] = relationship("EventTypes")
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.Events("
f"id={self.event_id}, event_type_id='{self.event_type_id}', "
f"origin_idx='{self.origin_idx}', time_fired='{self._time_fired_isotime}'"
f", data_id={self.data_id})>"
)
@property
def _time_fired_isotime(self) -> str | None:
"""Return time_fired as an isotime string."""
date_time: datetime | None
if self.time_fired_ts is not None:
date_time = dt_util.utc_from_timestamp(self.time_fired_ts)
else:
date_time = process_timestamp(self.time_fired)
if date_time is None:
return None
return date_time.isoformat(sep=" ", timespec="seconds")
@staticmethod
def from_event(event: Event) -> Events:
"""Create an event database object from a native event."""
context = event.context
return Events(
event_type=None,
event_data=None,
origin_idx=event.origin.idx,
time_fired=None,
time_fired_ts=event.time_fired_timestamp,
context_id=None,
context_id_bin=ulid_to_bytes_or_none(context.id),
context_user_id=None,
context_user_id_bin=uuid_hex_to_bytes_or_none(context.user_id),
context_parent_id=None,
context_parent_id_bin=ulid_to_bytes_or_none(context.parent_id),
)
def to_native(self, validate_entity_id: bool = True) -> Event | None:
"""Convert to a native HA Event."""
context = Context(
id=bytes_to_ulid_or_none(self.context_id_bin),
user_id=bytes_to_uuid_hex_or_none(self.context_user_id_bin),
parent_id=bytes_to_ulid_or_none(self.context_parent_id_bin),
)
try:
return Event(
self.event_type or "",
json_loads_object(self.event_data) if self.event_data else {},
EventOrigin(self.origin)
if self.origin
else EVENT_ORIGIN_ORDER[self.origin_idx or 0],
self.time_fired_ts or 0,
context=context,
)
except JSON_DECODE_EXCEPTIONS:
# When json_loads fails
_LOGGER.exception("Error converting to event: %s", self)
return None
class LegacyEvents(LegacyBase):
"""Event history data with event_id, used for schema migration."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_EVENTS
event_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
context_id: Mapped[str | None] = mapped_column(
String(LEGACY_MAX_LENGTH_EVENT_CONTEXT_ID), index=True
)
class EventData(Base):
"""Event data history."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_EVENT_DATA
data_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
hash: Mapped[int | None] = mapped_column(UINT_32_TYPE, index=True)
# Note that this is not named attributes to avoid confusion with the states table
shared_data: Mapped[str | None] = mapped_column(
Text().with_variant(mysql.LONGTEXT, "mysql", "mariadb")
)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.EventData("
f"id={self.data_id}, hash='{self.hash}', data='{self.shared_data}'"
")>"
)
@staticmethod
def shared_data_bytes_from_event(
event: Event, dialect: SupportedDialect | None
) -> bytes:
"""Create shared_data from an event."""
encoder = json_bytes_strip_null if dialect == PSQL_DIALECT else json_bytes
bytes_result = encoder(event.data)
if len(bytes_result) > MAX_EVENT_DATA_BYTES:
_LOGGER.warning(
"Event data for %s exceed maximum size of %s bytes. "
"This can cause database performance issues; Event data "
"will not be stored",
event.event_type,
MAX_EVENT_DATA_BYTES,
)
return b"{}"
return bytes_result
@staticmethod
def hash_shared_data_bytes(shared_data_bytes: bytes) -> int:
"""Return the hash of json encoded shared data."""
return fnv1a_32(shared_data_bytes)
def to_native(self) -> dict[str, Any]:
"""Convert to an event data dictionary."""
shared_data = self.shared_data
if shared_data is None:
return {}
try:
return cast(dict[str, Any], json_loads(shared_data))
except JSON_DECODE_EXCEPTIONS:
_LOGGER.exception("Error converting row to event data: %s", self)
return {}
class EventTypes(Base):
"""Event type history."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_EVENT_TYPES
event_type_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
event_type: Mapped[str | None] = mapped_column(
String(MAX_LENGTH_EVENT_EVENT_TYPE), index=True, unique=True
)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.EventTypes("
f"id={self.event_type_id}, event_type='{self.event_type}'"
")>"
)
class States(Base):
"""State change history."""
__table_args__ = (
# Used for fetching the state of entities at a specific time
# (get_states in history.py)
Index(METADATA_ID_LAST_UPDATED_INDEX_TS, "metadata_id", "last_updated_ts"),
Index(
STATES_CONTEXT_ID_BIN_INDEX,
"context_id_bin",
mysql_length=CONTEXT_ID_BIN_MAX_LENGTH,
mariadb_length=CONTEXT_ID_BIN_MAX_LENGTH,
),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_STATES
state_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
entity_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
state: Mapped[str | None] = mapped_column(String(MAX_LENGTH_STATE_STATE))
attributes: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
event_id: Mapped[int | None] = mapped_column(UNUSED_LEGACY_INTEGER_COLUMN)
last_changed: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
last_changed_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE)
last_reported_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE)
last_updated: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
last_updated_ts: Mapped[float | None] = mapped_column(
TIMESTAMP_TYPE, default=time.time, index=True
)
old_state_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("states.state_id"), index=True
)
attributes_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("state_attributes.attributes_id"), index=True
)
context_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
context_user_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
context_parent_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
origin_idx: Mapped[int | None] = mapped_column(
SmallInteger
) # 0 is local, 1 is remote
old_state: Mapped[States | None] = relationship("States", remote_side=[state_id])
state_attributes: Mapped[StateAttributes | None] = relationship("StateAttributes")
context_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
context_user_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
context_parent_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE)
metadata_id: Mapped[int | None] = mapped_column(
ID_TYPE, ForeignKey("states_meta.metadata_id")
)
states_meta_rel: Mapped[StatesMeta | None] = relationship("StatesMeta")
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
f"<recorder.States(id={self.state_id}, entity_id='{self.entity_id}'"
f" metadata_id={self.metadata_id},"
f" state='{self.state}', event_id='{self.event_id}',"
f" last_updated='{self._last_updated_isotime}',"
f" old_state_id={self.old_state_id}, attributes_id={self.attributes_id})>"
)
@property
def _last_updated_isotime(self) -> str | None:
"""Return last_updated as an isotime string."""
date_time: datetime | None
if self.last_updated_ts is not None:
date_time = dt_util.utc_from_timestamp(self.last_updated_ts)
else:
date_time = process_timestamp(self.last_updated)
if date_time is None:
return None
return date_time.isoformat(sep=" ", timespec="seconds")
@staticmethod
def from_event(event: Event[EventStateChangedData]) -> States:
"""Create object from a state_changed event."""
state = event.data["new_state"]
# None state means the state was removed from the state machine
if state is None:
state_value = ""
last_updated_ts = event.time_fired_timestamp
last_changed_ts = None
last_reported_ts = None
else:
state_value = state.state
last_updated_ts = state.last_updated_timestamp
if state.last_updated == state.last_changed:
last_changed_ts = None
else:
last_changed_ts = state.last_changed_timestamp
if state.last_updated == state.last_reported:
last_reported_ts = None
else:
last_reported_ts = state.last_reported_timestamp
context = event.context
return States(
state=state_value,
entity_id=event.data["entity_id"],
attributes=None,
context_id=None,
context_id_bin=ulid_to_bytes_or_none(context.id),
context_user_id=None,
context_user_id_bin=uuid_hex_to_bytes_or_none(context.user_id),
context_parent_id=None,
context_parent_id_bin=ulid_to_bytes_or_none(context.parent_id),
origin_idx=event.origin.idx,
last_updated=None,
last_changed=None,
last_updated_ts=last_updated_ts,
last_changed_ts=last_changed_ts,
last_reported_ts=last_reported_ts,
)
def to_native(self, validate_entity_id: bool = True) -> State | None:
"""Convert to an HA state object."""
context = Context(
id=bytes_to_ulid_or_none(self.context_id_bin),
user_id=bytes_to_uuid_hex_or_none(self.context_user_id_bin),
parent_id=bytes_to_ulid_or_none(self.context_parent_id_bin),
)
try:
attrs = json_loads_object(self.attributes) if self.attributes else {}
except JSON_DECODE_EXCEPTIONS:
# When json_loads fails
_LOGGER.exception("Error converting row to state: %s", self)
return None
last_updated = dt_util.utc_from_timestamp(self.last_updated_ts or 0)
if self.last_changed_ts is None or self.last_changed_ts == self.last_updated_ts:
last_changed = dt_util.utc_from_timestamp(self.last_updated_ts or 0)
else:
last_changed = dt_util.utc_from_timestamp(self.last_changed_ts or 0)
if (
self.last_reported_ts is None
or self.last_reported_ts == self.last_updated_ts
):
last_reported = dt_util.utc_from_timestamp(self.last_updated_ts or 0)
else:
last_reported = dt_util.utc_from_timestamp(self.last_reported_ts or 0)
return State(
self.entity_id or "",
self.state, # type: ignore[arg-type]
# Join the state_attributes table on attributes_id to get the attributes
# for newer states
attrs,
last_changed=last_changed,
last_reported=last_reported,
last_updated=last_updated,
context=context,
validate_entity_id=validate_entity_id,
)
class LegacyStates(LegacyBase):
"""State change history with entity_id, used for schema migration."""
__table_args__ = (
Index(
LEGACY_STATES_ENTITY_ID_LAST_UPDATED_TS_INDEX,
"entity_id",
"last_updated_ts",
),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_STATES
state_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
entity_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN)
last_updated_ts: Mapped[float | None] = mapped_column(
TIMESTAMP_TYPE, default=time.time, index=True
)
context_id: Mapped[str | None] = mapped_column(
String(LEGACY_MAX_LENGTH_EVENT_CONTEXT_ID), index=True
)
class StateAttributes(Base):
"""State attribute change history."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_STATE_ATTRIBUTES
attributes_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
hash: Mapped[int | None] = mapped_column(UINT_32_TYPE, index=True)
# Note that this is not named attributes to avoid confusion with the states table
shared_attrs: Mapped[str | None] = mapped_column(
Text().with_variant(mysql.LONGTEXT, "mysql", "mariadb")
)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
f"<recorder.StateAttributes(id={self.attributes_id}, hash='{self.hash}',"
f" attributes='{self.shared_attrs}')>"
)
@staticmethod
def shared_attrs_bytes_from_event(
event: Event[EventStateChangedData],
dialect: SupportedDialect | None,
) -> bytes:
"""Create shared_attrs from a state_changed event."""
# None state means the state was removed from the state machine
if (state := event.data["new_state"]) is None:
return b"{}"
if state_info := state.state_info:
unrecorded_attributes = state_info["unrecorded_attributes"]
exclude_attrs = {
*ALL_DOMAIN_EXCLUDE_ATTRS,
*unrecorded_attributes,
}
if MATCH_ALL in unrecorded_attributes:
# Don't exclude device class, state class, unit of measurement
# or friendly name when using the MATCH_ALL exclude constant
exclude_attrs.update(state.attributes)
exclude_attrs -= _MATCH_ALL_KEEP
else:
exclude_attrs = ALL_DOMAIN_EXCLUDE_ATTRS
encoder = json_bytes_strip_null if dialect == PSQL_DIALECT else json_bytes
bytes_result = encoder(
{k: v for k, v in state.attributes.items() if k not in exclude_attrs}
)
if len(bytes_result) > MAX_STATE_ATTRS_BYTES:
_LOGGER.warning(
"State attributes for %s exceed maximum size of %s bytes. "
"This can cause database performance issues; Attributes "
"will not be stored",
state.entity_id,
MAX_STATE_ATTRS_BYTES,
)
return b"{}"
return bytes_result
@staticmethod
def hash_shared_attrs_bytes(shared_attrs_bytes: bytes) -> int:
"""Return the hash of json encoded shared attributes."""
return fnv1a_32(shared_attrs_bytes)
def to_native(self) -> dict[str, Any]:
"""Convert to a state attributes dictionary."""
shared_attrs = self.shared_attrs
if shared_attrs is None:
return {}
try:
return cast(dict[str, Any], json_loads(shared_attrs))
except JSON_DECODE_EXCEPTIONS:
# When json_loads fails
_LOGGER.exception("Error converting row to state attributes: %s", self)
return {}
class StatesMeta(Base):
"""Metadata for states."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_STATES_META
metadata_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
entity_id: Mapped[str | None] = mapped_column(
String(MAX_LENGTH_STATE_ENTITY_ID), index=True, unique=True
)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.StatesMeta("
f"id={self.metadata_id}, entity_id='{self.entity_id}'"
")>"
)
class StatisticsBase:
"""Statistics base class."""
id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
created: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
created_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE, default=time.time)
metadata_id: Mapped[int | None] = mapped_column(
ID_TYPE,
ForeignKey(f"{TABLE_STATISTICS_META}.id", ondelete="CASCADE"),
)
start: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
start_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE, index=True)
mean: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
min: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
max: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
last_reset: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN)
last_reset_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE)
state: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
sum: Mapped[float | None] = mapped_column(DOUBLE_TYPE)
duration: timedelta
@classmethod
def from_stats(
cls, metadata_id: int, stats: StatisticData, now_timestamp: float | None = None
) -> Self:
"""Create object from a statistics with datetime objects."""
return cls( # type: ignore[call-arg]
metadata_id=metadata_id,
created=None,
created_ts=now_timestamp or time.time(),
start=None,
start_ts=stats["start"].timestamp(),
mean=stats.get("mean"),
min=stats.get("min"),
max=stats.get("max"),
last_reset=None,
last_reset_ts=datetime_to_timestamp_or_none(stats.get("last_reset")),
state=stats.get("state"),
sum=stats.get("sum"),
)
@classmethod
def from_stats_ts(
cls,
metadata_id: int,
stats: StatisticDataTimestamp,
now_timestamp: float | None = None,
) -> Self:
"""Create object from a statistics with timestamps."""
return cls( # type: ignore[call-arg]
metadata_id=metadata_id,
created=None,
created_ts=now_timestamp or time.time(),
start=None,
start_ts=stats["start_ts"],
mean=stats.get("mean"),
min=stats.get("min"),
max=stats.get("max"),
last_reset=None,
last_reset_ts=stats.get("last_reset_ts"),
state=stats.get("state"),
sum=stats.get("sum"),
)
class Statistics(Base, StatisticsBase):
"""Long term statistics."""
duration = timedelta(hours=1)
__table_args__ = (
# Used for fetching statistics for a certain entity at a specific time
Index(
"ix_statistics_statistic_id_start_ts",
"metadata_id",
"start_ts",
unique=True,
),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_STATISTICS
class _StatisticsShortTerm(StatisticsBase):
"""Short term statistics."""
duration = timedelta(minutes=5)
__tablename__ = TABLE_STATISTICS_SHORT_TERM
class StatisticsShortTerm(Base, _StatisticsShortTerm):
"""Short term statistics."""
__table_args__ = (
# Used for fetching statistics for a certain entity at a specific time
Index(
"ix_statistics_short_term_statistic_id_start_ts",
"metadata_id",
"start_ts",
unique=True,
),
_DEFAULT_TABLE_ARGS,
)
class LegacyStatisticsShortTerm(LegacyBase, _StatisticsShortTerm):
"""Short term statistics with 32-bit index, used for schema migration."""
__table_args__ = (
# Used for fetching statistics for a certain entity at a specific time
Index(
"ix_statistics_short_term_statistic_id_start_ts",
"metadata_id",
"start_ts",
unique=True,
),
_DEFAULT_TABLE_ARGS,
)
metadata_id: Mapped[int | None] = mapped_column(
Integer,
ForeignKey(f"{TABLE_STATISTICS_META}.id", ondelete="CASCADE"),
use_existing_column=True,
)
class _StatisticsMeta:
"""Statistics meta data."""
__table_args__ = (_DEFAULT_TABLE_ARGS,)
__tablename__ = TABLE_STATISTICS_META
id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
statistic_id: Mapped[str | None] = mapped_column(
String(255), index=True, unique=True
)
source: Mapped[str | None] = mapped_column(String(32))
unit_of_measurement: Mapped[str | None] = mapped_column(String(255))
has_mean: Mapped[bool | None] = mapped_column(Boolean)
has_sum: Mapped[bool | None] = mapped_column(Boolean)
name: Mapped[str | None] = mapped_column(String(255))
@staticmethod
def from_meta(meta: StatisticMetaData) -> StatisticsMeta:
"""Create object from meta data."""
return StatisticsMeta(**meta)
class StatisticsMeta(Base, _StatisticsMeta):
"""Statistics meta data."""
class LegacyStatisticsMeta(LegacyBase, _StatisticsMeta):
"""Statistics meta data with 32-bit index, used for schema migration."""
id: Mapped[int] = mapped_column(
Integer,
Identity(),
primary_key=True,
use_existing_column=True,
)
class RecorderRuns(Base):
"""Representation of recorder run."""
__table_args__ = (
Index("ix_recorder_runs_start_end", "start", "end"),
_DEFAULT_TABLE_ARGS,
)
__tablename__ = TABLE_RECORDER_RUNS
run_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
start: Mapped[datetime] = mapped_column(DATETIME_TYPE, default=dt_util.utcnow)
end: Mapped[datetime | None] = mapped_column(DATETIME_TYPE)
closed_incorrect: Mapped[bool] = mapped_column(Boolean, default=False)
created: Mapped[datetime] = mapped_column(DATETIME_TYPE, default=dt_util.utcnow)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
end = (
f"'{self.end.isoformat(sep=' ', timespec='seconds')}'" if self.end else None
)
return (
f"<recorder.RecorderRuns(id={self.run_id},"
f" start='{self.start.isoformat(sep=' ', timespec='seconds')}', end={end},"
f" closed_incorrect={self.closed_incorrect},"
f" created='{self.created.isoformat(sep=' ', timespec='seconds')}')>"
)
def to_native(self, validate_entity_id: bool = True) -> Self:
"""Return self, native format is this model."""
return self
class MigrationChanges(Base):
"""Representation of migration changes."""
__tablename__ = TABLE_MIGRATION_CHANGES
__table_args__ = (_DEFAULT_TABLE_ARGS,)
migration_id: Mapped[str] = mapped_column(String(255), primary_key=True)
version: Mapped[int] = mapped_column(SmallInteger)
class SchemaChanges(Base):
"""Representation of schema version changes."""
__tablename__ = TABLE_SCHEMA_CHANGES
__table_args__ = (_DEFAULT_TABLE_ARGS,)
change_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
schema_version: Mapped[int | None] = mapped_column(Integer)
changed: Mapped[datetime] = mapped_column(DATETIME_TYPE, default=dt_util.utcnow)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
"<recorder.SchemaChanges("
f"id={self.change_id}, schema_version={self.schema_version}, "
f"changed='{self.changed.isoformat(sep=' ', timespec='seconds')}'"
")>"
)
class StatisticsRuns(Base):
"""Representation of statistics run."""
__tablename__ = TABLE_STATISTICS_RUNS
__table_args__ = (_DEFAULT_TABLE_ARGS,)
run_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True)
start: Mapped[datetime] = mapped_column(DATETIME_TYPE, index=True)
def __repr__(self) -> str:
"""Return string representation of instance for debugging."""
return (
f"<recorder.StatisticsRuns(id={self.run_id},"
f" start='{self.start.isoformat(sep=' ', timespec='seconds')}', )>"
)
EVENT_DATA_JSON = type_coerce(
EventData.shared_data.cast(JSONB_VARIANT_CAST), JSONLiteral(none_as_null=True)
)
OLD_FORMAT_EVENT_DATA_JSON = type_coerce(
Events.event_data.cast(JSONB_VARIANT_CAST), JSONLiteral(none_as_null=True)
)
SHARED_ATTRS_JSON = type_coerce(
StateAttributes.shared_attrs.cast(JSON_VARIANT_CAST), JSON(none_as_null=True)
)
OLD_FORMAT_ATTRS_JSON = type_coerce(
States.attributes.cast(JSON_VARIANT_CAST), JSON(none_as_null=True)
)
ENTITY_ID_IN_EVENT: ColumnElement = EVENT_DATA_JSON["entity_id"]
OLD_ENTITY_ID_IN_EVENT: ColumnElement = OLD_FORMAT_EVENT_DATA_JSON["entity_id"]
DEVICE_ID_IN_EVENT: ColumnElement = EVENT_DATA_JSON["device_id"]
OLD_STATE = aliased(States, name="old_state")
SHARED_ATTR_OR_LEGACY_ATTRIBUTES = case(
(StateAttributes.shared_attrs.is_(None), States.attributes),
else_=StateAttributes.shared_attrs,
).label("attributes")
SHARED_DATA_OR_LEGACY_EVENT_DATA = case(
(EventData.shared_data.is_(None), Events.event_data), else_=EventData.shared_data
).label("event_data")
| {
"repo_id": "home-assistant/core",
"file_path": "tests/components/recorder/db_schema_48.py",
"license": "Apache License 2.0",
"lines": 836,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | test |
home-assistant/core:homeassistant/components/androidtv/services.py | """Services for Android/Fire TV devices."""
from __future__ import annotations
import voluptuous as vol
from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN
from homeassistant.const import ATTR_COMMAND
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, service
from .const import DOMAIN
ATTR_ADB_RESPONSE = "adb_response"
ATTR_DEVICE_PATH = "device_path"
ATTR_HDMI_INPUT = "hdmi_input"
ATTR_LOCAL_PATH = "local_path"
@callback
def async_setup_services(hass: HomeAssistant) -> None:
"""Register the Android TV / Fire TV services."""
service.async_register_platform_entity_service(
hass,
DOMAIN,
"adb_command",
entity_domain=MEDIA_PLAYER_DOMAIN,
schema={vol.Required(ATTR_COMMAND): cv.string},
func="adb_command",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
"learn_sendevent",
entity_domain=MEDIA_PLAYER_DOMAIN,
schema=None,
func="learn_sendevent",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
"download",
entity_domain=MEDIA_PLAYER_DOMAIN,
schema={
vol.Required(ATTR_DEVICE_PATH): cv.string,
vol.Required(ATTR_LOCAL_PATH): cv.string,
},
func="service_download",
)
service.async_register_platform_entity_service(
hass,
DOMAIN,
"upload",
entity_domain=MEDIA_PLAYER_DOMAIN,
schema={
vol.Required(ATTR_DEVICE_PATH): cv.string,
vol.Required(ATTR_LOCAL_PATH): cv.string,
},
func="service_upload",
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/androidtv/services.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/aosmith/select.py | """The select platform for the A. O. Smith integration."""
from homeassistant.components.select import SelectEntity
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from . import AOSmithConfigEntry
from .coordinator import AOSmithStatusCoordinator
from .entity import AOSmithStatusEntity
HWP_LEVEL_HA_TO_AOSMITH = {
"off": 0,
"level1": 1,
"level2": 2,
"level3": 3,
}
HWP_LEVEL_AOSMITH_TO_HA = {value: key for key, value in HWP_LEVEL_HA_TO_AOSMITH.items()}
async def async_setup_entry(
hass: HomeAssistant,
entry: AOSmithConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up A. O. Smith select platform."""
data = entry.runtime_data
async_add_entities(
AOSmithHotWaterPlusSelectEntity(data.status_coordinator, device.junction_id)
for device in data.status_coordinator.data.values()
if device.supports_hot_water_plus
)
class AOSmithHotWaterPlusSelectEntity(AOSmithStatusEntity, SelectEntity):
"""Class for the Hot Water+ select entity."""
_attr_translation_key = "hot_water_plus_level"
_attr_options = list(HWP_LEVEL_HA_TO_AOSMITH)
def __init__(self, coordinator: AOSmithStatusCoordinator, junction_id: str) -> None:
"""Initialize the entity."""
super().__init__(coordinator, junction_id)
self._attr_unique_id = f"hot_water_plus_level_{junction_id}"
@property
def suggested_object_id(self) -> str | None:
"""Override the suggested object id to make '+' get converted to 'plus' in the entity id."""
return "hot_water_plus_level"
@property
def current_option(self) -> str | None:
"""Return the current Hot Water+ mode."""
hot_water_plus_level = self.device.status.hot_water_plus_level
return (
None
if hot_water_plus_level is None
else HWP_LEVEL_AOSMITH_TO_HA.get(hot_water_plus_level)
)
async def async_select_option(self, option: str) -> None:
"""Set the Hot Water+ mode."""
aosmith_hwp_level = HWP_LEVEL_HA_TO_AOSMITH[option]
await self.client.update_mode(
junction_id=self.junction_id,
mode=self.device.status.current_mode,
hot_water_plus_level=aosmith_hwp_level,
)
await self.coordinator.async_request_refresh()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/aosmith/select.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/compit/climate.py | """Module contains the CompitClimate class for controlling climate entities."""
import logging
from typing import Any
from compit_inext_api import Param, Parameter
from compit_inext_api.consts import (
CompitFanMode,
CompitHVACMode,
CompitParameter,
CompitPresetMode,
)
from propcache.api import cached_property
from homeassistant.components.climate import (
FAN_AUTO,
FAN_HIGH,
FAN_LOW,
FAN_MEDIUM,
FAN_OFF,
PRESET_AWAY,
PRESET_ECO,
PRESET_HOME,
PRESET_NONE,
ClimateEntity,
ClimateEntityFeature,
HVACMode,
)
from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
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
_LOGGER: logging.Logger = logging.getLogger(__name__)
# Device class for climate devices in Compit system
CLIMATE_DEVICE_CLASS = 10
PARALLEL_UPDATES = 0
COMPIT_MODE_MAP = {
CompitHVACMode.COOL: HVACMode.COOL,
CompitHVACMode.HEAT: HVACMode.HEAT,
CompitHVACMode.OFF: HVACMode.OFF,
}
COMPIT_FANSPEED_MAP = {
CompitFanMode.OFF: FAN_OFF,
CompitFanMode.AUTO: FAN_AUTO,
CompitFanMode.LOW: FAN_LOW,
CompitFanMode.MEDIUM: FAN_MEDIUM,
CompitFanMode.HIGH: FAN_HIGH,
CompitFanMode.HOLIDAY: FAN_AUTO,
}
COMPIT_PRESET_MAP = {
CompitPresetMode.AUTO: PRESET_HOME,
CompitPresetMode.HOLIDAY: PRESET_ECO,
CompitPresetMode.MANUAL: PRESET_NONE,
CompitPresetMode.AWAY: PRESET_AWAY,
}
HVAC_MODE_TO_COMPIT_MODE = {v: k for k, v in COMPIT_MODE_MAP.items()}
FAN_MODE_TO_COMPIT_FAN_MODE = {v: k for k, v in COMPIT_FANSPEED_MAP.items()}
PRESET_MODE_TO_COMPIT_PRESET_MODE = {v: k for k, v in COMPIT_PRESET_MAP.items()}
async def async_setup_entry(
hass: HomeAssistant,
entry: CompitConfigEntry,
async_add_devices: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up the CompitClimate platform from a config entry."""
coordinator = entry.runtime_data
climate_entities = []
for device_id in coordinator.connector.all_devices:
device = coordinator.connector.all_devices[device_id]
if device.definition.device_class == CLIMATE_DEVICE_CLASS:
climate_entities.append(
CompitClimate(
coordinator,
device_id,
{
parameter.parameter_code: parameter
for parameter in device.definition.parameters
},
device.definition.name,
)
)
async_add_devices(climate_entities)
class CompitClimate(CoordinatorEntity[CompitDataUpdateCoordinator], ClimateEntity):
"""Representation of a Compit climate device."""
_attr_temperature_unit = UnitOfTemperature.CELSIUS
_attr_hvac_modes = [*COMPIT_MODE_MAP.values()]
_attr_name = None
_attr_has_entity_name = True
_attr_supported_features = (
ClimateEntityFeature.TARGET_TEMPERATURE
| ClimateEntityFeature.FAN_MODE
| ClimateEntityFeature.PRESET_MODE
)
def __init__(
self,
coordinator: CompitDataUpdateCoordinator,
device_id: int,
parameters: dict[str, Parameter],
device_name: str,
) -> None:
"""Initialize the climate device."""
super().__init__(coordinator)
self._attr_unique_id = f"{device_name}_{device_id}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, str(device_id))},
name=device_name,
manufacturer=MANUFACTURER_NAME,
model=device_name,
)
self.parameters = parameters
self.device_id = device_id
self.available_presets: Parameter | None = self.parameters.get(
CompitParameter.PRESET_MODE.value
)
self.available_fan_modes: Parameter | None = self.parameters.get(
CompitParameter.FAN_MODE.value
)
@property
def available(self) -> bool:
"""Return if entity is available."""
return (
super().available
and self.device_id in self.coordinator.connector.all_devices
)
@property
def current_temperature(self) -> float | None:
"""Return the current temperature."""
value = self.get_parameter_value(CompitParameter.CURRENT_TEMPERATURE)
if value is None:
return None
return float(value.value)
@property
def target_temperature(self) -> float | None:
"""Return the temperature we try to reach."""
value = self.get_parameter_value(CompitParameter.SET_TARGET_TEMPERATURE)
if value is None:
return None
return float(value.value)
@cached_property
def preset_modes(self) -> list[str] | None:
"""Return the available preset modes."""
if self.available_presets is None or self.available_presets.details is None:
return []
preset_modes = []
for item in self.available_presets.details:
if item is not None:
ha_preset = COMPIT_PRESET_MAP.get(CompitPresetMode(item.state))
if ha_preset and ha_preset not in preset_modes:
preset_modes.append(ha_preset)
return preset_modes
@cached_property
def fan_modes(self) -> list[str] | None:
"""Return the available fan modes."""
if self.available_fan_modes is None or self.available_fan_modes.details is None:
return []
fan_modes = []
for item in self.available_fan_modes.details:
if item is not None:
ha_fan_mode = COMPIT_FANSPEED_MAP.get(CompitFanMode(item.state))
if ha_fan_mode and ha_fan_mode not in fan_modes:
fan_modes.append(ha_fan_mode)
return fan_modes
@property
def preset_mode(self) -> str | None:
"""Return the current preset mode."""
preset_mode = self.get_parameter_value(CompitParameter.PRESET_MODE)
if preset_mode:
compit_preset_mode = CompitPresetMode(preset_mode.value)
return COMPIT_PRESET_MAP.get(compit_preset_mode)
return None
@property
def fan_mode(self) -> str | None:
"""Return the current fan mode."""
fan_mode = self.get_parameter_value(CompitParameter.FAN_MODE)
if fan_mode:
compit_fan_mode = CompitFanMode(fan_mode.value)
return COMPIT_FANSPEED_MAP.get(compit_fan_mode)
return None
@property
def hvac_mode(self) -> HVACMode | None:
"""Return the current HVAC mode."""
hvac_mode = self.get_parameter_value(CompitParameter.HVAC_MODE)
if hvac_mode:
compit_hvac_mode = CompitHVACMode(hvac_mode.value)
return COMPIT_MODE_MAP.get(compit_hvac_mode)
return None
async def async_set_temperature(self, **kwargs: Any) -> None:
"""Set new target temperature."""
temp = kwargs.get(ATTR_TEMPERATURE)
if temp is None:
raise ServiceValidationError("Temperature argument missing")
await self.set_parameter_value(CompitParameter.SET_TARGET_TEMPERATURE, temp)
async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
"""Set new target HVAC mode."""
if not (mode := HVAC_MODE_TO_COMPIT_MODE.get(hvac_mode)):
raise ServiceValidationError(f"Invalid hvac mode {hvac_mode}")
await self.set_parameter_value(CompitParameter.HVAC_MODE, mode.value)
async def async_set_preset_mode(self, preset_mode: str) -> None:
"""Set new target preset mode."""
compit_preset = PRESET_MODE_TO_COMPIT_PRESET_MODE.get(preset_mode)
if compit_preset is None:
raise ServiceValidationError(f"Invalid preset mode: {preset_mode}")
await self.set_parameter_value(CompitParameter.PRESET_MODE, compit_preset.value)
async def async_set_fan_mode(self, fan_mode: str) -> None:
"""Set new target fan mode."""
compit_fan_mode = FAN_MODE_TO_COMPIT_FAN_MODE.get(fan_mode)
if compit_fan_mode is None:
raise ServiceValidationError(f"Invalid fan mode: {fan_mode}")
await self.set_parameter_value(CompitParameter.FAN_MODE, compit_fan_mode.value)
async def set_parameter_value(self, parameter: CompitParameter, value: int) -> None:
"""Call the API to set a parameter to a new value."""
await self.coordinator.connector.set_device_parameter(
self.device_id, parameter, value
)
self.async_write_ha_state()
def get_parameter_value(self, parameter: CompitParameter) -> Param | None:
"""Get the parameter value from the device state."""
return self.coordinator.connector.get_device_parameter(
self.device_id, parameter
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/compit/climate.py",
"license": "Apache License 2.0",
"lines": 220,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/compit/config_flow.py | """Config flow for Compit integration."""
from __future__ import annotations
from collections.abc import Mapping
import logging
from typing import Any
from compit_inext_api import CannotConnect, CompitApiConnector, InvalidAuth
import voluptuous as vol
from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_EMAIL, CONF_PASSWORD
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_EMAIL): str,
vol.Required(CONF_PASSWORD): str,
}
)
STEP_REAUTH_SCHEMA = vol.Schema(
{
vol.Required(CONF_PASSWORD): str,
}
)
class CompitConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Compit."""
VERSION = 1
async def async_step_user(
self,
user_input: dict[str, Any] | None = None,
) -> ConfigFlowResult:
"""Handle the initial step."""
errors: dict[str, str] = {}
if user_input is not None:
session = async_create_clientsession(self.hass)
api = CompitApiConnector(session)
success = False
try:
success = await api.init(
user_input[CONF_EMAIL],
user_input[CONF_PASSWORD],
self.hass.config.language,
)
except CannotConnect:
errors["base"] = "cannot_connect"
except InvalidAuth:
errors["base"] = "invalid_auth"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
if not success:
# Api returned unexpected result but no exception
_LOGGER.error("Compit api returned unexpected result")
errors["base"] = "unknown"
else:
await self.async_set_unique_id(user_input[CONF_EMAIL])
if self.source == SOURCE_REAUTH:
self._abort_if_unique_id_mismatch()
return self.async_update_reload_and_abort(
self._get_reauth_entry(), data_updates=user_input
)
self._abort_if_unique_id_configured()
return self.async_create_entry(
title=user_input[CONF_EMAIL], data=user_input
)
return self.async_show_form(
step_id="user",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
description_placeholders={"compit_url": "https://inext.compit.pl/"},
)
async def async_step_reauth(self, data: Mapping[str, Any]) -> ConfigFlowResult:
"""Handle re-auth."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm re-authentication."""
errors: dict[str, str] = {}
reauth_entry = self._get_reauth_entry()
reauth_entry_data = reauth_entry.data
if user_input:
# Reuse async_step_user with combined credentials
return await self.async_step_user(
{
CONF_EMAIL: reauth_entry_data[CONF_EMAIL],
CONF_PASSWORD: user_input[CONF_PASSWORD],
}
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=STEP_REAUTH_SCHEMA,
description_placeholders={CONF_EMAIL: reauth_entry_data[CONF_EMAIL]},
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/compit/config_flow.py",
"license": "Apache License 2.0",
"lines": 95,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/compit/coordinator.py | """Define an object to manage fetching Compit data."""
from datetime import timedelta
import logging
from compit_inext_api import CompitApiConnector, DeviceInstance
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import DOMAIN
SCAN_INTERVAL = timedelta(seconds=30)
_LOGGER: logging.Logger = logging.getLogger(__name__)
type CompitConfigEntry = ConfigEntry[CompitDataUpdateCoordinator]
class CompitDataUpdateCoordinator(DataUpdateCoordinator[dict[int, DeviceInstance]]):
"""Class to manage fetching data from the API."""
def __init__(
self,
hass: HomeAssistant,
config_entry: ConfigEntry,
connector: CompitApiConnector,
) -> None:
"""Initialize."""
self.connector = connector
super().__init__(
hass,
_LOGGER,
name=DOMAIN,
update_interval=SCAN_INTERVAL,
config_entry=config_entry,
)
async def _async_update_data(self) -> dict[int, DeviceInstance]:
"""Update data via library."""
await self.connector.update_state(device_id=None) # Update all devices
return self.connector.all_devices
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/compit/coordinator.py",
"license": "Apache License 2.0",
"lines": 32,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/cync/config_flow.py | """Config flow for the Cync integration."""
from __future__ import annotations
from collections.abc import Mapping
import logging
from typing import Any
from pycync import Auth
from pycync.exceptions import AuthFailedError, CyncError, TwoFactorRequiredError
import voluptuous as vol
from homeassistant.config_entries import SOURCE_REAUTH, 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 (
CONF_AUTHORIZE_STRING,
CONF_EXPIRES_AT,
CONF_REFRESH_TOKEN,
CONF_TWO_FACTOR_CODE,
CONF_USER_ID,
DOMAIN,
)
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_EMAIL): str,
vol.Required(CONF_PASSWORD): str,
}
)
STEP_TWO_FACTOR_SCHEMA = vol.Schema({vol.Required(CONF_TWO_FACTOR_CODE): str})
class CyncConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Cync."""
VERSION = 1
cync_auth: Auth = None
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Attempt login with user credentials."""
errors: dict[str, str] = {}
if user_input:
try:
errors = await self._validate_credentials(user_input)
except TwoFactorRequiredError:
return await self.async_step_two_factor()
if not errors:
return await self._create_config_entry(self.cync_auth.username)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
async def async_step_two_factor(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Attempt login with the two factor auth code sent to the user."""
errors: dict[str, str] = {}
if user_input:
errors = await self._validate_credentials(user_input)
if not errors:
return await self._create_config_entry(self.cync_auth.username)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
return self.async_show_form(
step_id="two_factor", data_schema=STEP_TWO_FACTOR_SCHEMA, errors=errors
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauth upon an API authentication error."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Dialog that informs the user that reauth is required and prompts for their Cync credentials."""
errors: dict[str, str] = {}
reauth_entry = self._get_reauth_entry()
if user_input:
try:
errors = await self._validate_credentials(user_input)
except TwoFactorRequiredError:
return await self.async_step_two_factor()
if not errors:
return await self._create_config_entry(self.cync_auth.username)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
description_placeholders={CONF_EMAIL: reauth_entry.title},
)
async def _validate_credentials(self, user_input: dict[str, Any]) -> dict[str, str]:
"""Attempt to log in with user email and password, and return the error dict."""
errors: dict[str, str] = {}
if not self.cync_auth:
self.cync_auth = Auth(
async_get_clientsession(self.hass),
username=user_input[CONF_EMAIL],
password=user_input[CONF_PASSWORD],
)
try:
await self.cync_auth.login(user_input.get(CONF_TWO_FACTOR_CODE))
except TwoFactorRequiredError:
raise
except AuthFailedError:
errors["base"] = "invalid_auth"
except CyncError:
errors["base"] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
return errors
async def _create_config_entry(self, user_email: str) -> ConfigFlowResult:
"""Create the Cync config entry using input user data."""
cync_user = self.cync_auth.user
await self.async_set_unique_id(str(cync_user.user_id))
config_data = {
CONF_USER_ID: cync_user.user_id,
CONF_AUTHORIZE_STRING: cync_user.authorize,
CONF_EXPIRES_AT: cync_user.expires_at,
CONF_ACCESS_TOKEN: cync_user.access_token,
CONF_REFRESH_TOKEN: cync_user.refresh_token,
}
if self.source == SOURCE_REAUTH:
self._abort_if_unique_id_mismatch()
return self.async_update_reload_and_abort(
entry=self._get_reauth_entry(), title=user_email, data=config_data
)
self._abort_if_unique_id_configured()
return self.async_create_entry(title=user_email, data=config_data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/cync/config_flow.py",
"license": "Apache License 2.0",
"lines": 124,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/cync/const.py | """Constants for the Cync integration."""
DOMAIN = "cync"
CONF_TWO_FACTOR_CODE = "two_factor_code"
CONF_USER_ID = "user_id"
CONF_AUTHORIZE_STRING = "authorize_string"
CONF_EXPIRES_AT = "expires_at"
CONF_REFRESH_TOKEN = "refresh_token"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/cync/const.py",
"license": "Apache License 2.0",
"lines": 7,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/cync/coordinator.py | """Coordinator to handle keeping device states up to date."""
from __future__ import annotations
from datetime import timedelta
import logging
import time
from pycync import Cync, CyncDevice, User
from pycync.exceptions import AuthFailedError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_ACCESS_TOKEN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from .const import CONF_EXPIRES_AT, CONF_REFRESH_TOKEN
_LOGGER = logging.getLogger(__name__)
type CyncConfigEntry = ConfigEntry[CyncCoordinator]
class CyncCoordinator(DataUpdateCoordinator[dict[int, CyncDevice]]):
"""Coordinator to handle updating Cync device states."""
config_entry: CyncConfigEntry
def __init__(
self, hass: HomeAssistant, config_entry: CyncConfigEntry, cync: Cync
) -> None:
"""Initialize the Cync coordinator."""
super().__init__(
hass,
_LOGGER,
name="Cync Data Coordinator",
config_entry=config_entry,
update_interval=timedelta(seconds=30),
always_update=True,
)
self.cync = cync
async def on_data_update(self, data: dict[int, CyncDevice]) -> None:
"""Update registered devices with new data."""
merged_data = self.data | data if self.data else data
self.async_set_updated_data(merged_data)
async def _async_setup(self) -> None:
"""Set up the coordinator with initial device states."""
logged_in_user = self.cync.get_logged_in_user()
if logged_in_user.access_token != self.config_entry.data[CONF_ACCESS_TOKEN]:
await self._update_config_cync_credentials(logged_in_user)
async def _async_update_data(self) -> dict[int, CyncDevice]:
"""First, refresh the user's auth token if it is set to expire in less than one hour.
Then, fetch all current device states.
"""
logged_in_user = self.cync.get_logged_in_user()
if logged_in_user.expires_at - time.time() < 3600:
await self._async_refresh_cync_credentials()
self.cync.update_device_states()
current_device_states = self.cync.get_devices()
return {device.device_id: device for device in current_device_states}
async def _async_refresh_cync_credentials(self) -> None:
"""Attempt to refresh the Cync user's authentication token."""
try:
refreshed_user = await self.cync.refresh_credentials()
except AuthFailedError as ex:
raise ConfigEntryAuthFailed("Unable to refresh user token") from ex
else:
await self._update_config_cync_credentials(refreshed_user)
async def _update_config_cync_credentials(self, user_info: User) -> None:
"""Update the config entry with current user info."""
new_data = {**self.config_entry.data}
new_data[CONF_ACCESS_TOKEN] = user_info.access_token
new_data[CONF_REFRESH_TOKEN] = user_info.refresh_token
new_data[CONF_EXPIRES_AT] = user_info.expires_at
self.hass.config_entries.async_update_entry(self.config_entry, data=new_data)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/cync/coordinator.py",
"license": "Apache License 2.0",
"lines": 65,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/cync/entity.py | """Setup for a generic entity type for the Cync integration."""
from pycync.devices import CyncDevice
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN
from .coordinator import CyncCoordinator
class CyncBaseEntity(CoordinatorEntity[CyncCoordinator]):
"""Generic base entity for Cync devices."""
_attr_has_entity_name = True
def __init__(
self,
device: CyncDevice,
coordinator: CyncCoordinator,
room_name: str | None = None,
) -> None:
"""Pass coordinator to CoordinatorEntity."""
super().__init__(coordinator)
self._cync_device_id = device.device_id
self._attr_unique_id = device.unique_id
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, device.unique_id)},
manufacturer="GE Lighting",
name=device.name,
suggested_area=room_name,
)
@property
def available(self) -> bool:
"""Determines whether this device is currently available."""
return (
super().available
and self.coordinator.data is not None
and self._cync_device_id in self.coordinator.data
and self.coordinator.data[self._cync_device_id].is_online
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/cync/entity.py",
"license": "Apache License 2.0",
"lines": 34,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/cync/light.py | """Support for Cync light entities."""
from typing import Any
from pycync import CyncLight
from pycync.devices.capabilities import CyncCapability
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_COLOR_TEMP_KELVIN,
ATTR_RGB_COLOR,
ColorMode,
LightEntity,
filter_supported_color_modes,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from homeassistant.util.color import value_to_brightness
from homeassistant.util.scaling import scale_ranged_value_to_int_range
from .coordinator import CyncConfigEntry, CyncCoordinator
from .entity import CyncBaseEntity
async def async_setup_entry(
hass: HomeAssistant,
entry: CyncConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up Cync lights from a config entry."""
coordinator = entry.runtime_data
cync = coordinator.cync
entities_to_add = []
for home in cync.get_homes():
for room in home.rooms:
room_lights = [
CyncLightEntity(device, coordinator, room.name)
for device in room.devices
if isinstance(device, CyncLight)
]
entities_to_add.extend(room_lights)
group_lights = [
CyncLightEntity(device, coordinator, room.name)
for group in room.groups
for device in group.devices
if isinstance(device, CyncLight)
]
entities_to_add.extend(group_lights)
async_add_entities(entities_to_add)
class CyncLightEntity(CyncBaseEntity, LightEntity):
"""Representation of a Cync light."""
_attr_color_mode = ColorMode.ONOFF
_attr_min_color_temp_kelvin = 2000
_attr_max_color_temp_kelvin = 7000
_attr_translation_key = "light"
_attr_name = None
BRIGHTNESS_SCALE = (0, 100)
def __init__(
self,
device: CyncLight,
coordinator: CyncCoordinator,
room_name: str | None = None,
) -> None:
"""Set up base attributes."""
super().__init__(device, coordinator, room_name)
supported_color_modes = {ColorMode.ONOFF}
if device.supports_capability(CyncCapability.CCT_COLOR):
supported_color_modes.add(ColorMode.COLOR_TEMP)
if device.supports_capability(CyncCapability.DIMMING):
supported_color_modes.add(ColorMode.BRIGHTNESS)
if device.supports_capability(CyncCapability.RGB_COLOR):
supported_color_modes.add(ColorMode.RGB)
self._attr_supported_color_modes = filter_supported_color_modes(
supported_color_modes
)
@property
def is_on(self) -> bool | None:
"""Return True if the light is on."""
return self._device.is_on
@property
def brightness(self) -> int:
"""Provide the light's current brightness."""
return value_to_brightness(self.BRIGHTNESS_SCALE, self._device.brightness)
@property
def color_temp_kelvin(self) -> int:
"""Return color temperature in kelvin."""
return scale_ranged_value_to_int_range(
(1, 100),
(self.min_color_temp_kelvin, self.max_color_temp_kelvin),
self._device.color_temp,
)
@property
def rgb_color(self) -> tuple[int, int, int]:
"""Provide the light's current color in RGB format."""
return self._device.rgb
@property
def color_mode(self) -> ColorMode:
"""Return the active color mode."""
if (
self._device.supports_capability(CyncCapability.CCT_COLOR)
and self._device.color_mode > 0
and self._device.color_mode <= 100
):
return ColorMode.COLOR_TEMP
if (
self._device.supports_capability(CyncCapability.RGB_COLOR)
and self._device.color_mode == 254
):
return ColorMode.RGB
if self._device.supports_capability(CyncCapability.DIMMING):
return ColorMode.BRIGHTNESS
return ColorMode.ONOFF
async def async_turn_on(self, **kwargs: Any) -> None:
"""Process an action on the light."""
converted_brightness: int | None = None
converted_color_temp: int | None = None
rgb: tuple[int, int, int] | None = None
if kwargs.get(ATTR_COLOR_TEMP_KELVIN) is not None:
color_temp = kwargs.get(ATTR_COLOR_TEMP_KELVIN)
converted_color_temp = self._normalize_color_temp(color_temp)
elif kwargs.get(ATTR_RGB_COLOR) is not None:
rgb = kwargs.get(ATTR_RGB_COLOR)
elif self.color_mode == ColorMode.RGB:
rgb = self._device.rgb
elif self.color_mode == ColorMode.COLOR_TEMP:
converted_color_temp = self._device.color_temp
if kwargs.get(ATTR_BRIGHTNESS) is not None:
brightness = kwargs.get(ATTR_BRIGHTNESS)
converted_brightness = self._normalize_brightness(brightness)
elif self.color_mode != ColorMode.ONOFF:
converted_brightness = self._device.brightness
await self._device.set_combo(
True, converted_brightness, converted_color_temp, rgb
)
async def async_turn_off(self, **kwargs: Any) -> None:
"""Turn off the light."""
await self._device.turn_off()
def _normalize_brightness(self, brightness: float | None) -> int | None:
"""Return calculated brightness value scaled between 0-100."""
if brightness is not None:
return int((brightness / 255) * 100)
return None
def _normalize_color_temp(self, color_temp_kelvin: float | None) -> int | None:
"""Return calculated color temp value scaled between 1-100."""
if color_temp_kelvin is not None:
kelvin_range = self.max_color_temp_kelvin - self.min_color_temp_kelvin
scaled_kelvin = int(
((color_temp_kelvin - self.min_color_temp_kelvin) / kelvin_range) * 100
)
if scaled_kelvin == 0:
scaled_kelvin += 1
return scaled_kelvin
return None
@property
def _device(self) -> CyncLight:
"""Fetch the reference to the backing Cync light for this device."""
return self.coordinator.data[self._cync_device_id]
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/cync/light.py",
"license": "Apache License 2.0",
"lines": 151,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_complex |
home-assistant/core:homeassistant/components/derivative/diagnostics.py | """Diagnostics support for derivative."""
from __future__ import annotations
from typing import Any
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, config_entry: ConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
registry = er.async_get(hass)
entities = registry.entities.get_entries_for_config_entry_id(config_entry.entry_id)
return {
"config_entry": config_entry.as_dict(),
"entity": [entity.extended_dict for entity in entities],
}
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/derivative/diagnostics.py",
"license": "Apache License 2.0",
"lines": 16,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/droplet/config_flow.py | """Config flow for Droplet integration."""
from __future__ import annotations
from typing import Any
from pydroplet.droplet import DropletConnection, DropletDiscovery
import voluptuous as vol
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_CODE, CONF_DEVICE_ID, CONF_IP_ADDRESS, CONF_PORT
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
from .const import DOMAIN
def normalize_pairing_code(code: str) -> str:
"""Normalize pairing code by removing spaces and capitalizing."""
return code.replace(" ", "").upper()
class DropletConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle Droplet config flow."""
_droplet_discovery: DropletDiscovery
async def async_step_zeroconf(
self, discovery_info: ZeroconfServiceInfo
) -> ConfigFlowResult:
"""Handle zeroconf discovery."""
self._droplet_discovery = DropletDiscovery(
discovery_info.host,
discovery_info.port,
discovery_info.name,
)
if not self._droplet_discovery.is_valid():
return self.async_abort(reason="invalid_discovery_info")
# In this case, device ID was part of the zeroconf discovery info
device_id: str = await self._droplet_discovery.get_device_id()
await self.async_set_unique_id(device_id)
self._abort_if_unique_id_configured(
updates={CONF_IP_ADDRESS: self._droplet_discovery.host},
)
self.context.update({"title_placeholders": {"name": device_id}})
return await self.async_step_confirm()
async def async_step_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm the setup."""
errors: dict[str, str] = {}
device_id: str = await self._droplet_discovery.get_device_id()
if user_input is not None:
# Test if we can connect before returning
session = async_get_clientsession(self.hass)
code = normalize_pairing_code(user_input[CONF_CODE])
if await self._droplet_discovery.try_connect(session, code):
device_data = {
CONF_IP_ADDRESS: self._droplet_discovery.host,
CONF_PORT: self._droplet_discovery.port,
CONF_DEVICE_ID: device_id,
CONF_CODE: code,
}
return self.async_create_entry(
title=device_id,
data=device_data,
)
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="confirm",
data_schema=vol.Schema(
{
vol.Required(CONF_CODE): str,
}
),
description_placeholders={
"device_name": device_id,
},
errors=errors,
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle a flow initialized by the user."""
errors: dict[str, str] = {}
if user_input is not None:
self._droplet_discovery = DropletDiscovery(
user_input[CONF_IP_ADDRESS], DropletConnection.DEFAULT_PORT, ""
)
session = async_get_clientsession(self.hass)
code = normalize_pairing_code(user_input[CONF_CODE])
if await self._droplet_discovery.try_connect(session, code) and (
device_id := await self._droplet_discovery.get_device_id()
):
device_data = {
CONF_IP_ADDRESS: self._droplet_discovery.host,
CONF_PORT: self._droplet_discovery.port,
CONF_DEVICE_ID: device_id,
CONF_CODE: code,
}
await self.async_set_unique_id(device_id, raise_on_progress=False)
self._abort_if_unique_id_configured(
description_placeholders={CONF_DEVICE_ID: device_id},
)
return self.async_create_entry(
title=device_id,
data=device_data,
)
errors["base"] = "cannot_connect"
return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{vol.Required(CONF_IP_ADDRESS): str, vol.Required(CONF_CODE): str}
),
errors=errors,
)
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/droplet/config_flow.py",
"license": "Apache License 2.0",
"lines": 105,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
home-assistant/core:homeassistant/components/droplet/const.py | """Constants for the droplet integration."""
CONNECT_DELAY = 5
DOMAIN = "droplet"
DEVICE_NAME = "Droplet"
KEY_CURRENT_FLOW_RATE = "current_flow_rate"
KEY_VOLUME = "volume"
KEY_SIGNAL_QUALITY = "signal_quality"
KEY_SERVER_CONNECTIVITY = "server_connectivity"
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/droplet/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/droplet/coordinator.py | """Droplet device data update coordinator object."""
from __future__ import annotations
import asyncio
import logging
import time
from pydroplet.droplet import Droplet
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_CODE, CONF_IP_ADDRESS, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import CONNECT_DELAY, DOMAIN
VERSION_TIMEOUT = 5
_LOGGER = logging.getLogger(__name__)
TIMEOUT = 1
type DropletConfigEntry = ConfigEntry[DropletDataCoordinator]
class DropletDataCoordinator(DataUpdateCoordinator[None]):
"""Droplet device object."""
config_entry: DropletConfigEntry
def __init__(self, hass: HomeAssistant, entry: DropletConfigEntry) -> None:
"""Initialize the device."""
super().__init__(
hass, _LOGGER, config_entry=entry, name=f"{DOMAIN}-{entry.unique_id}"
)
self.droplet = Droplet(
host=entry.data[CONF_IP_ADDRESS],
port=entry.data[CONF_PORT],
token=entry.data[CONF_CODE],
session=async_get_clientsession(self.hass),
logger=_LOGGER,
)
assert entry.unique_id is not None
self.unique_id = entry.unique_id
async def _async_setup(self) -> None:
if not await self.setup():
raise ConfigEntryNotReady("Device is offline")
# Droplet should send its metadata within 5 seconds
end = time.time() + VERSION_TIMEOUT
while not self.droplet.version_info_available():
await asyncio.sleep(TIMEOUT)
if time.time() > end:
_LOGGER.warning("Failed to get version info from Droplet")
return
async def _async_update_data(self) -> None:
if not self.droplet.connected:
raise UpdateFailed(
translation_domain=DOMAIN, translation_key="connection_error"
)
async def setup(self) -> bool:
"""Set up droplet client."""
self.config_entry.async_on_unload(self.droplet.stop_listening)
self.config_entry.async_create_background_task(
self.hass,
self.droplet.listen_forever(CONNECT_DELAY, self.async_set_updated_data),
"droplet-listen",
)
end = time.time() + CONNECT_DELAY
while time.time() < end:
if self.droplet.connected:
return True
await asyncio.sleep(TIMEOUT)
return False
def get_availability(self) -> bool:
"""Retrieve Droplet's availability status."""
return self.droplet.get_availability()
| {
"repo_id": "home-assistant/core",
"file_path": "homeassistant/components/droplet/coordinator.py",
"license": "Apache License 2.0",
"lines": 66,
"canary_id": -1,
"canary_value": "",
"pii_type": "",
"provider": "",
"regex_pattern": "",
"repetition": -1,
"template": ""
} | function_simple |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.