Compare commits

...

9 Commits

Author SHA1 Message Date
Abílio Costa
f88129ed11 Apply suggestion from @abmantis 2025-12-11 11:47:12 +00:00
Abílio Costa
5b000d02db Merge branch 'dev' into enable_duplicated_log_file 2025-12-11 11:46:32 +00:00
epenet
7fe0d96c88 Remove unnecessary wrapper base method in Tuya (#158708) 2025-12-11 10:13:24 +01:00
Joost Lekkerkerker
cdc2192bba Clean up Homelink tests (#158685)
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-12-11 09:10:02 +01:00
Matt Zimmerman
74b1c1f6fd Bump python-smarttub to 0.0.46 (#158702) 2025-12-11 09:07:46 +01:00
J. Nick Koston
69c7a7b0ab Pin pycares to 4.11.0 (#158695) 2025-12-10 22:00:59 -05:00
Norbert Rittel
ef302215cc Add two common config flow strings in energyid (#158680) 2025-12-10 21:23:18 +01:00
Norbert Rittel
6378f5f02a Use common reauth_successful string in rituals_perfume_genie (#158684) 2025-12-10 21:14:25 +01:00
abmantis
1578bb1dfc Enable log file on supervised when HA_DUPLICATE_LOG_FILE env var is set 2025-12-10 18:38:26 +00:00
25 changed files with 428 additions and 296 deletions

View File

@@ -624,8 +624,11 @@ async def async_enable_logging(
if log_file is None:
default_log_path = hass.config.path(ERROR_LOG_FILENAME)
if "SUPERVISOR" in os.environ:
_LOGGER.info("Running in Supervisor, not logging to file")
if "SUPERVISOR" in os.environ and "HA_DUPLICATE_LOG_FILE" not in os.environ:
_LOGGER.info(
"Running in Supervisor without the duplicate log option, "
"not logging to file"
)
# Rename the default log file if it exists, since previous versions created
# it even on Supervisor
if os.path.isfile(default_log_path):

View File

@@ -1,8 +1,8 @@
{
"config": {
"abort": {
"already_configured": "This device is already configured.",
"reauth_successful": "Reauthentication successful."
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
},
"create_entry": {
"add_sensor_mapping_hint": "You can now add mappings from any sensor in Home Assistant to {integration_name} using the '+ add sensor mapping' button."

View File

@@ -10,7 +10,7 @@ from homeassistant.helpers import aiohttp_client, config_entry_oauth2_flow
from . import oauth2
from .const import DOMAIN
from .coordinator import HomeLinkConfigEntry, HomeLinkCoordinator, HomeLinkData
from .coordinator import HomeLinkConfigEntry, HomeLinkCoordinator
PLATFORMS: list[Platform] = [Platform.EVENT]
@@ -44,9 +44,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: HomeLinkConfigEntry) ->
)
await coordinator.async_config_entry_first_refresh()
entry.runtime_data = HomeLinkData(
provider=provider, coordinator=coordinator, last_update_id=None
)
entry.runtime_data = coordinator
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
return True
@@ -54,5 +52,5 @@ async def async_setup_entry(hass: HomeAssistant, entry: HomeLinkConfigEntry) ->
async def async_unload_entry(hass: HomeAssistant, entry: HomeLinkConfigEntry) -> bool:
"""Unload a config entry."""
await entry.runtime_data.coordinator.async_on_unload(None)
await entry.runtime_data.async_on_unload(None)
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)

View File

@@ -3,7 +3,6 @@
from __future__ import annotations
from collections.abc import Callable
from dataclasses import dataclass
from functools import partial
import logging
from typing import TypedDict
@@ -17,19 +16,10 @@ from homeassistant.util.ssl import get_default_context
_LOGGER = logging.getLogger(__name__)
type HomeLinkConfigEntry = ConfigEntry[HomeLinkData]
type HomeLinkConfigEntry = ConfigEntry[HomeLinkCoordinator]
type EventCallback = Callable[[HomeLinkEventData], None]
@dataclass
class HomeLinkData:
"""Class for HomeLink integration runtime data."""
provider: MQTTProvider
coordinator: HomeLinkCoordinator
last_update_id: str | None
class HomeLinkEventData(TypedDict):
"""Data for a single event."""
@@ -68,7 +58,7 @@ class HomeLinkCoordinator:
self._listeners[target_event_id] = update_callback
return partial(self.__async_remove_listener_internal, target_event_id)
def __async_remove_listener_internal(self, listener_id: str):
def __async_remove_listener_internal(self, listener_id: str) -> None:
del self._listeners[listener_id]
@callback
@@ -92,7 +82,7 @@ class HomeLinkCoordinator:
await self.discover_devices()
self.provider.listen(self.on_message)
async def discover_devices(self):
async def discover_devices(self) -> None:
"""Discover devices and build the Entities."""
self.device_data = await self.provider.discover()

View File

@@ -3,25 +3,24 @@
from __future__ import annotations
from homeassistant.components.event import EventDeviceClass, EventEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.device_registry import DeviceInfo
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .const import DOMAIN, EVENT_PRESSED
from .coordinator import HomeLinkCoordinator, HomeLinkEventData
from .coordinator import HomeLinkConfigEntry, HomeLinkCoordinator, HomeLinkEventData
async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
config_entry: HomeLinkConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Add the entities for the binary sensor."""
coordinator = config_entry.runtime_data.coordinator
"""Add the entities for the event platform."""
coordinator = config_entry.runtime_data
async_add_entities(
HomeLinkEventEntity(button.id, button.name, device.id, device.name, coordinator)
HomeLinkEventEntity(coordinator, button.id, button.name, device.id, device.name)
for device in coordinator.device_data
for button in device.buttons
)
@@ -40,11 +39,11 @@ class HomeLinkEventEntity(EventEntity):
def __init__(
self,
coordinator: HomeLinkCoordinator,
button_id: str,
param_name: str,
device_id: str,
device_name: str,
coordinator: HomeLinkCoordinator,
) -> None:
"""Initialize the event entity."""
@@ -74,5 +73,4 @@ class HomeLinkEventEntity(EventEntity):
if update_data["requestId"] != self.last_request_id:
self._trigger_event(EVENT_PRESSED)
self.last_request_id = update_data["requestId"]
self.async_write_ha_state()
self.async_write_ha_state()

View File

@@ -2,7 +2,7 @@
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
"reauth_successful": "Re-authentication was successful"
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",

View File

@@ -6,5 +6,5 @@
"documentation": "https://www.home-assistant.io/integrations/smarttub",
"iot_class": "cloud_polling",
"loggers": ["smarttub"],
"requirements": ["python-smarttub==0.0.45"]
"requirements": ["python-smarttub==0.0.46"]
}

View File

@@ -380,7 +380,7 @@ class _CustomDPCodeWrapper(DPCodeWrapper):
def read_device_status(self, device: CustomerDevice) -> bool | None:
"""Read the device value for the dpcode."""
if (raw_value := self._read_device_status_raw(device)) is None:
if (raw_value := device.status.get(self.dpcode)) is None:
return None
return raw_value in self._valid_values

View File

@@ -33,7 +33,7 @@ class _DPCodePercentageMappingWrapper(DPCodeIntegerWrapper):
return False
def read_device_status(self, device: CustomerDevice) -> float | None:
if (value := self._read_device_status_raw(device)) is None:
if (value := device.status.get(self.dpcode)) is None:
return None
return round(

View File

@@ -77,7 +77,7 @@ class _AlarmMessageWrapper(DPCodeStringWrapper, _DPCodeEventWrapper):
def get_event_attributes(self, device: CustomerDevice) -> dict[str, Any] | None:
"""Return the event attributes for the alarm message."""
if (raw_value := self._read_device_status_raw(device)) is None:
if (raw_value := device.status.get(self.dpcode)) is None:
return None
return {"message": b64decode(raw_value).decode("utf-8")}

View File

@@ -53,7 +53,7 @@ class _BrightnessWrapper(DPCodeIntegerWrapper):
def read_device_status(self, device: CustomerDevice) -> Any | None:
"""Return the brightness of this light between 0..255."""
if (brightness := self._read_device_status_raw(device)) is None:
if (brightness := device.status.get(self.dpcode)) is None:
return None
# Remap value to our scale
@@ -114,7 +114,7 @@ class _ColorTempWrapper(DPCodeIntegerWrapper):
def read_device_status(self, device: CustomerDevice) -> Any | None:
"""Return the color temperature value in Kelvin."""
if (temperature := self._read_device_status_raw(device)) is None:
if (temperature := device.status.get(self.dpcode)) is None:
return None
return color_util.color_temperature_mired_to_kelvin(

View File

@@ -46,13 +46,6 @@ class DPCodeWrapper(DeviceWrapper):
"""Init DPCodeWrapper."""
self.dpcode = dpcode
def _read_device_status_raw(self, device: CustomerDevice) -> Any | None:
"""Read the raw device status for the DPCode.
Private helper method for `read_device_status`.
"""
return device.status.get(self.dpcode)
def _convert_value_to_raw_value(self, device: CustomerDevice, value: Any) -> Any:
"""Convert a Home Assistant value back to a raw device value.
@@ -90,7 +83,7 @@ class DPCodeTypeInformationWrapper[T: TypeInformation](DPCodeWrapper):
def read_device_status(self, device: CustomerDevice) -> Any | None:
"""Read the device value for the dpcode."""
return self.type_information.process_raw_value(
self._read_device_status_raw(device), device
device.status.get(self.dpcode), device
)
@classmethod
@@ -197,7 +190,7 @@ class DPCodeBitmapBitWrapper(DPCodeWrapper):
def read_device_status(self, device: CustomerDevice) -> bool | None:
"""Read the device value for the dpcode."""
if (raw_value := self._read_device_status_raw(device)) is None:
if (raw_value := device.status.get(self.dpcode)) is None:
return None
return (raw_value & (1 << self._mask)) != 0

View File

@@ -76,9 +76,7 @@ class _WindDirectionWrapper(DPCodeTypeInformationWrapper[EnumTypeInformation]):
def read_device_status(self, device: CustomerDevice) -> float | None:
"""Read the device value for the dpcode."""
if (
raw_value := self._read_device_status_raw(device)
) in self.type_information.range:
if (raw_value := device.status.get(self.dpcode)) in self.type_information.range:
return self._WIND_DIRECTIONS.get(raw_value)
return None

View File

@@ -223,3 +223,6 @@ gql<4.0.0
# Pin pytest-rerunfailures to prevent accidental breaks
pytest-rerunfailures==16.0.1
# pycares 5.x is not yet compatible with aiodns
pycares==4.11.0

2
requirements_all.txt generated
View File

@@ -2578,7 +2578,7 @@ python-ripple-api==0.0.3
python-roborock==3.12.2
# homeassistant.components.smarttub
python-smarttub==0.0.45
python-smarttub==0.0.46
# homeassistant.components.snoo
python-snoo==0.8.3

View File

@@ -2159,7 +2159,7 @@ python-rabbitair==0.0.8
python-roborock==3.12.2
# homeassistant.components.smarttub
python-smarttub==0.0.45
python-smarttub==0.0.46
# homeassistant.components.snoo
python-snoo==0.8.3

View File

@@ -214,6 +214,9 @@ gql<4.0.0
# Pin pytest-rerunfailures to prevent accidental breaks
pytest-rerunfailures==16.0.1
# pycares 5.x is not yet compatible with aiodns
pycares==4.11.0
"""
GENERATED_MESSAGE = (

View File

@@ -1 +1,32 @@
"""Tests for the homelink integration."""
from typing import Any
from unittest.mock import AsyncMock
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
async def setup_integration(hass: HomeAssistant, entry: MockConfigEntry) -> None:
"""Set up the homelink integration for testing."""
entry.add_to_hass(hass)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
async def update_callback(
hass: HomeAssistant, mock: AsyncMock, update_type: str, data: dict[str, Any]
) -> None:
"""Invoke the MQTT provider's message callback with the specified update type and data."""
for call in mock.listen.call_args_list:
call[0][0](
"topic",
{
"type": update_type,
"data": data,
},
)
await hass.async_block_till_done()
await hass.async_block_till_done()

View File

@@ -3,8 +3,14 @@
from collections.abc import Generator
from unittest.mock import AsyncMock, patch
from homelink.model.button import Button
import homelink.model.device
import pytest
from homeassistant.components.gentex_homelink import DOMAIN
from tests.common import MockConfigEntry
@pytest.fixture
def mock_srp_auth() -> Generator[AsyncMock]:
@@ -24,6 +30,50 @@ def mock_srp_auth() -> Generator[AsyncMock]:
yield instance
@pytest.fixture
def mock_mqtt_provider(mock_device: AsyncMock) -> Generator[AsyncMock]:
"""Mock MQTT provider."""
with patch(
"homeassistant.components.gentex_homelink.MQTTProvider", autospec=True
) as mock_mqtt_provider:
instance = mock_mqtt_provider.return_value
instance.discover.return_value = [mock_device]
yield instance
@pytest.fixture
def mock_device() -> AsyncMock:
"""Mock Device instance."""
device = AsyncMock(spec=homelink.model.device.Device, autospec=True)
buttons = [
Button(id="1", name="Button 1", device=device),
Button(id="2", name="Button 2", device=device),
Button(id="3", name="Button 3", device=device),
]
device.id = "TestDevice"
device.name = "TestDevice"
device.buttons = buttons
return device
@pytest.fixture
def mock_config_entry() -> MockConfigEntry:
"""Mock setup entry."""
return MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation": "gentex_homelink",
"token": {
"access_token": "access",
"refresh_token": "refresh",
"expires_in": 3600,
"token_type": "bearer",
"expires_at": 1234567890,
},
},
)
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Mock setup entry."""

View File

@@ -0,0 +1,172 @@
# serializer version: 1
# name: test_entities[event.testdevice_button_1-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'event_types': list([
'Pressed',
]),
}),
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'event',
'entity_category': None,
'entity_id': 'event.testdevice_button_1',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <EventDeviceClass.BUTTON: 'button'>,
'original_icon': None,
'original_name': 'Button 1',
'platform': 'gentex_homelink',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': '1',
'unit_of_measurement': None,
})
# ---
# name: test_entities[event.testdevice_button_1-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'button',
'event_type': None,
'event_types': list([
'Pressed',
]),
'friendly_name': 'TestDevice Button 1',
}),
'context': <ANY>,
'entity_id': 'event.testdevice_button_1',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_entities[event.testdevice_button_2-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'event_types': list([
'Pressed',
]),
}),
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'event',
'entity_category': None,
'entity_id': 'event.testdevice_button_2',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <EventDeviceClass.BUTTON: 'button'>,
'original_icon': None,
'original_name': 'Button 2',
'platform': 'gentex_homelink',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': '2',
'unit_of_measurement': None,
})
# ---
# name: test_entities[event.testdevice_button_2-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'button',
'event_type': None,
'event_types': list([
'Pressed',
]),
'friendly_name': 'TestDevice Button 2',
}),
'context': <ANY>,
'entity_id': 'event.testdevice_button_2',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_entities[event.testdevice_button_3-entry]
EntityRegistryEntrySnapshot({
'aliases': set({
}),
'area_id': None,
'capabilities': dict({
'event_types': list([
'Pressed',
]),
}),
'config_entry_id': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'event',
'entity_category': None,
'entity_id': 'event.testdevice_button_3',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'options': dict({
}),
'original_device_class': <EventDeviceClass.BUTTON: 'button'>,
'original_icon': None,
'original_name': 'Button 3',
'platform': 'gentex_homelink',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': None,
'unique_id': '3',
'unit_of_measurement': None,
})
# ---
# name: test_entities[event.testdevice_button_3-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'device_class': 'button',
'event_type': None,
'event_types': list([
'Pressed',
]),
'friendly_name': 'TestDevice Button 3',
}),
'context': <ANY>,
'entity_id': 'event.testdevice_button_3',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---

View File

@@ -0,0 +1,32 @@
# serializer version: 1
# name: test_device
DeviceRegistryEntrySnapshot({
'area_id': None,
'config_entries': <ANY>,
'config_entries_subentries': <ANY>,
'configuration_url': None,
'connections': set({
}),
'disabled_by': None,
'entry_type': None,
'hw_version': None,
'id': <ANY>,
'identifiers': set({
tuple(
'gentex_homelink',
'TestDevice',
),
}),
'labels': set({
}),
'manufacturer': None,
'model': None,
'model_id': None,
'name': 'TestDevice',
'name_by_user': None,
'primary_config_entry': <ANY>,
'serial_number': None,
'sw_version': None,
'via_device_id': None,
})
# ---

View File

@@ -1,160 +0,0 @@
"""Tests for the homelink coordinator."""
import asyncio
import time
from unittest.mock import patch
from homelink.model.button import Button
from homelink.model.device import Device
import pytest
from homeassistant.components.gentex_homelink import async_setup_entry
from homeassistant.components.gentex_homelink.const import EVENT_PRESSED
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNAVAILABLE
from homeassistant.core import HomeAssistant
import homeassistant.helpers.entity_registry as er
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
DOMAIN = "gentex_homelink"
deviceInst = Device(id="TestDevice", name="TestDevice")
deviceInst.buttons = [
Button(id="Button 1", name="Button 1", device=deviceInst),
Button(id="Button 2", name="Button 2", device=deviceInst),
Button(id="Button 3", name="Button 3", device=deviceInst),
]
async def test_get_state_updates(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test state updates.
Tests that get_state calls are called by home assistant, and the homeassistant components respond appropriately to the data returned.
"""
with patch(
"homeassistant.components.gentex_homelink.MQTTProvider", autospec=True
) as MockProvider:
instance = MockProvider.return_value
instance.discover.return_value = [deviceInst]
config_entry = MockConfigEntry(
domain=DOMAIN,
unique_id=None,
version=1,
data={
"auth_implementation": "gentex_homelink",
"token": {"expires_at": time.time() + 10000, "access_token": ""},
"last_update_id": None,
},
state=ConfigEntryState.LOADED,
)
config_entry.add_to_hass(hass)
result = await async_setup_entry(hass, config_entry)
# Assert configuration worked without errors
assert result
provider = config_entry.runtime_data.provider
state_data = {
"type": "state",
"data": {
"Button 1": {"requestId": "rid1", "timestamp": time.time()},
"Button 2": {"requestId": "rid2", "timestamp": time.time()},
"Button 3": {"requestId": "rid3", "timestamp": time.time()},
},
}
# Test successful setup and first data fetch. The buttons should be unknown at the start
await hass.async_block_till_done(wait_background_tasks=True)
states = hass.states.async_all()
assert states, "No states were loaded"
assert all(state != STATE_UNAVAILABLE for state in states), (
"At least one state was not initialized as STATE_UNAVAILABLE"
)
buttons_unknown = [s.state == "unknown" for s in states]
assert buttons_unknown and all(buttons_unknown), (
"At least one button state was not initialized to unknown"
)
provider.listen.mock_calls[0].args[0](None, state_data)
await hass.async_block_till_done(wait_background_tasks=True)
await asyncio.gather(*asyncio.all_tasks() - {asyncio.current_task()})
await asyncio.sleep(0.01)
states = hass.states.async_all()
assert all(state != STATE_UNAVAILABLE for state in states), (
"Some button became unavailable"
)
buttons_pressed = [s.attributes["event_type"] == EVENT_PRESSED for s in states]
assert buttons_pressed and all(buttons_pressed), (
"At least one button was not pressed"
)
async def test_request_sync(hass: HomeAssistant) -> None:
"""Test that the config entry is reloaded when a requestSync request is sent."""
updatedDeviceInst = Device(id="TestDevice", name="TestDevice")
updatedDeviceInst.buttons = [
Button(id="Button 1", name="New Button 1", device=deviceInst),
Button(id="Button 2", name="New Button 2", device=deviceInst),
Button(id="Button 3", name="New Button 3", device=deviceInst),
]
with patch(
"homeassistant.components.gentex_homelink.MQTTProvider", autospec=True
) as MockProvider:
instance = MockProvider.return_value
instance.discover.side_effect = [[deviceInst], [updatedDeviceInst]]
config_entry = MockConfigEntry(
domain=DOMAIN,
unique_id=None,
version=1,
data={
"auth_implementation": "gentex_homelink",
"token": {"expires_at": time.time() + 10000, "access_token": ""},
"last_update_id": None,
},
state=ConfigEntryState.LOADED,
)
config_entry.add_to_hass(hass)
result = await async_setup_entry(hass, config_entry)
# Assert configuration worked without errors
assert result
# Check to see if the correct buttons names were loaded
comp = er.async_get(hass)
button_names = {"Button 1", "Button 2", "Button 3"}
registered_button_names = {b.original_name for b in comp.entities.values()}
assert button_names == registered_button_names, (
"Expect button names to be correct for the initial config"
)
provider = config_entry.runtime_data.provider
coordinator = config_entry.runtime_data.coordinator
with patch.object(
coordinator.hass.config_entries, "async_reload"
) as async_reload_mock:
# Mimic request sync event
state_data = {
"type": "requestSync",
}
# async reload should not be called yet
async_reload_mock.assert_not_called()
# Send the request sync
provider.listen.mock_calls[0].args[0](None, state_data)
# Wait for the request to be processed
await hass.async_block_till_done(wait_background_tasks=True)
await asyncio.gather(*asyncio.all_tasks() - {asyncio.current_task()})
await asyncio.sleep(0.01)
# Now async reload should have been called
async_reload_mock.assert_called()

View File

@@ -1,77 +1,55 @@
"""Test that the devices and entities are correctly configured."""
from unittest.mock import patch
import time
from unittest.mock import AsyncMock
from homelink.model.button import Button
from homelink.model.device import Device
import pytest
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.gentex_homelink import async_setup_entry
from homeassistant.components.gentex_homelink.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import STATE_UNKNOWN
from homeassistant.core import HomeAssistant
import homeassistant.helpers.device_registry as dr
import homeassistant.helpers.entity_registry as er
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
from . import setup_integration, update_callback
CLIENT_ID = "1234"
CLIENT_SECRET = "5678"
TEST_CONFIG_ENTRY_ID = "ABC123"
"""Mock classes for testing."""
from tests.common import MockConfigEntry, snapshot_platform
deviceInst = Device(id="TestDevice", name="TestDevice")
deviceInst.buttons = [
Button(id="1", name="Button 1", device=deviceInst),
Button(id="2", name="Button 2", device=deviceInst),
Button(id="3", name="Button 3", device=deviceInst),
]
@pytest.fixture
async def test_setup_config(
async def test_entities(
hass: HomeAssistant,
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
mock_config_entry: MockConfigEntry,
mock_mqtt_provider: AsyncMock,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Setup config entry."""
with patch(
"homeassistant.components.gentex_homelink.MQTTProvider", autospec=True
) as MockProvider:
instance = MockProvider.return_value
instance.discover.return_value = [deviceInst]
config_entry = MockConfigEntry(
domain=DOMAIN,
unique_id=None,
version=1,
data={"auth_implementation": "gentex_homelink"},
state=ConfigEntryState.LOADED,
)
config_entry.add_to_hass(hass)
result = await async_setup_entry(hass, config_entry)
# Assert configuration worked without errors
assert result
async def test_device_registered(hass: HomeAssistant, test_setup_config) -> None:
"""Check if a device is registered."""
# Assert we got a device with the test ID
device_registry = dr.async_get(hass)
device = device_registry.async_get_device([(DOMAIN, "TestDevice")])
assert device
assert device.name == "TestDevice"
def test_entities_registered(hass: HomeAssistant, test_setup_config) -> None:
"""Check if the entities are registered."""
comp = er.async_get(hass)
button_names = {"Button 1", "Button 2", "Button 3"}
registered_button_names = {b.original_name for b in comp.entities.values()}
await setup_integration(hass, mock_config_entry)
assert button_names == registered_button_names
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
@pytest.mark.freeze_time("2021-07-30")
async def test_entities_update(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_mqtt_provider: AsyncMock,
) -> None:
"""Check if the entities are updated."""
await setup_integration(hass, mock_config_entry)
assert hass.states.get("event.testdevice_button_1").state == STATE_UNKNOWN
await update_callback(
hass,
mock_mqtt_provider,
"state",
{
"1": {"requestId": "rid1", "timestamp": time.time()},
"2": {"requestId": "rid2", "timestamp": time.time()},
"3": {"requestId": "rid3", "timestamp": time.time()},
},
)
assert (
hass.states.get("event.testdevice_button_1").state
== "2021-07-30T00:00:00.000+00:00"
)

View File

@@ -1,32 +1,66 @@
"""Test that the integration is initialized correctly."""
from unittest.mock import patch
from unittest.mock import AsyncMock, patch
from syrupy.assertion import SnapshotAssertion
from homeassistant.components import gentex_homelink
from homeassistant.components.gentex_homelink.const import DOMAIN
from homeassistant.config_entries import ConfigEntryState
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
import homeassistant.helpers.device_registry as dr
from . import setup_integration, update_callback
from tests.common import MockConfigEntry
async def test_device(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_mqtt_provider: AsyncMock,
device_registry: dr.DeviceRegistry,
snapshot: SnapshotAssertion,
) -> None:
"""Test device is registered correctly."""
await setup_integration(hass, mock_config_entry)
device = device_registry.async_get_device(
identifiers={(DOMAIN, "TestDevice")},
)
assert device
assert device == snapshot
async def test_reload_sync(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_mqtt_provider: AsyncMock,
) -> None:
"""Test that the config entry is reloaded when a requestSync request is sent."""
await setup_integration(hass, mock_config_entry)
with patch.object(hass.config_entries, "async_reload") as async_reload_mock:
await update_callback(
hass,
mock_mqtt_provider,
"requestSync",
{},
)
async_reload_mock.assert_called_once_with(mock_config_entry.entry_id)
async def test_load_unload_entry(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_mqtt_provider: AsyncMock,
) -> None:
"""Test the entry can be loaded and unloaded."""
with patch("homeassistant.components.gentex_homelink.MQTTProvider", autospec=True):
entry = MockConfigEntry(
domain=DOMAIN,
unique_id=None,
version=1,
data={"auth_implementation": "gentex_homelink"},
)
entry.add_to_hass(hass)
await setup_integration(hass, mock_config_entry)
assert await async_setup_component(hass, DOMAIN, {}) is True, (
"Component is not set up"
)
assert mock_config_entry.state is ConfigEntryState.LOADED
assert await gentex_homelink.async_unload_entry(hass, entry), (
"Component not unloaded"
)
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

View File

@@ -130,8 +130,16 @@ async def test_async_enable_logging(
cleanup_log_files()
@pytest.mark.parametrize(
("extra_env", "log_file_count", "old_log_file_count"),
[({}, 0, 1), ({"HA_DUPLICATE_LOG_FILE": "1"}, 1, 0)],
)
async def test_async_enable_logging_supervisor(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
extra_env: dict[str, str],
log_file_count: int,
old_log_file_count: int,
) -> None:
"""Test to ensure the default log file is not created on Supervisor installations."""
@@ -141,14 +149,14 @@ async def test_async_enable_logging_supervisor(
assert len(glob.glob(ARG_LOG_FILE)) == 0
with (
patch.dict(os.environ, {"SUPERVISOR": "1"}),
patch.dict(os.environ, {"SUPERVISOR": "1", **extra_env}),
patch(
"homeassistant.bootstrap.async_activate_log_queue_handler"
) as mock_async_activate_log_queue_handler,
patch("logging.getLogger"),
):
await bootstrap.async_enable_logging(hass)
assert len(glob.glob(CONFIG_LOG_FILE)) == 0
assert len(glob.glob(CONFIG_LOG_FILE)) == log_file_count
mock_async_activate_log_queue_handler.assert_called_once()
mock_async_activate_log_queue_handler.reset_mock()
@@ -162,9 +170,10 @@ async def test_async_enable_logging_supervisor(
await hass.async_add_executor_job(write_log_file)
assert len(glob.glob(CONFIG_LOG_FILE)) == 1
assert len(glob.glob(f"{CONFIG_LOG_FILE}.old")) == 0
await bootstrap.async_enable_logging(hass)
assert len(glob.glob(CONFIG_LOG_FILE)) == 0
assert len(glob.glob(f"{CONFIG_LOG_FILE}.old")) == 1
assert len(glob.glob(CONFIG_LOG_FILE)) == log_file_count
assert len(glob.glob(f"{CONFIG_LOG_FILE}.old")) == old_log_file_count
mock_async_activate_log_queue_handler.assert_called_once()
mock_async_activate_log_queue_handler.reset_mock()