Fix attribute-defined-outside-init in harmony tests (#119614)

This commit is contained in:
epenet 2024-06-13 16:57:20 +02:00 committed by GitHub
parent 3b8337985c
commit 50fe29ccc1
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -4,6 +4,7 @@ from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch
from aioharmony.const import ClientCallbackType from aioharmony.const import ClientCallbackType
import pytest import pytest
from typing_extensions import Generator
from homeassistant.components.harmony.const import ACTIVITY_POWER_OFF, DOMAIN from homeassistant.components.harmony.const import ACTIVITY_POWER_OFF, DOMAIN
from homeassistant.const import CONF_HOST, CONF_NAME from homeassistant.const import CONF_HOST, CONF_NAME
@ -46,21 +47,17 @@ IDS_TO_DEVICES = {
class FakeHarmonyClient: class FakeHarmonyClient:
"""FakeHarmonyClient to mock away network calls.""" """FakeHarmonyClient to mock away network calls."""
def initialize( _callbacks: ClientCallbackType
self, ip_address: str = "", callbacks: ClientCallbackType = MagicMock()
): def __init__(self) -> None:
"""Initialize FakeHarmonyClient class to capture callbacks.""" """Initialize FakeHarmonyClient class to capture callbacks."""
# pylint: disable=attribute-defined-outside-init
self._activity_name = "Watch TV" self._activity_name = "Watch TV"
self.close = AsyncMock() self.close = AsyncMock()
self.send_commands = AsyncMock() self.send_commands = AsyncMock()
self.change_channel = AsyncMock() self.change_channel = AsyncMock()
self.sync = AsyncMock() self.sync = AsyncMock()
self._callbacks = callbacks
self.fw_version = "123.456" self.fw_version = "123.456"
return self
async def connect(self): async def connect(self):
"""Connect and call the appropriate callbacks.""" """Connect and call the appropriate callbacks."""
self._callbacks.connect(None) self._callbacks.connect(None)
@ -152,20 +149,27 @@ class FakeHarmonyClient:
@pytest.fixture @pytest.fixture
def harmony_client(): def harmony_client() -> FakeHarmonyClient:
"""Create the FakeHarmonyClient instance.""" """Create the FakeHarmonyClient instance."""
return FakeHarmonyClient() return FakeHarmonyClient()
@pytest.fixture @pytest.fixture
def mock_hc(harmony_client): def mock_hc(harmony_client: FakeHarmonyClient) -> Generator[None]:
"""Patch the real HarmonyClient with initialization side effect.""" """Patch the real HarmonyClient with initialization side effect."""
def _on_create_instance(
ip_address: str, callbacks: ClientCallbackType
) -> FakeHarmonyClient:
"""Set client callbacks on instance creation."""
harmony_client._callbacks = callbacks
return harmony_client
with patch( with patch(
"homeassistant.components.harmony.data.HarmonyClient", "homeassistant.components.harmony.data.HarmonyClient",
side_effect=harmony_client.initialize, side_effect=_on_create_instance,
) as fake: ):
yield fake yield
@pytest.fixture @pytest.fixture