Replace PJLink API by an async API (#167548)

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
jtjart
2026-12-01 10:28:27 +01:00
committed by GitHub
co-authored by Copilot Autofix powered by AI Copilot
parent c7781e3f1f
commit e207eb238c
8 changed files with 365 additions and 251 deletions
+17 -3
View File
@@ -1,18 +1,32 @@
"""The PJLink integration."""
from aiopjlink2 import PJLink
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, Platform
from homeassistant.core import HomeAssistant
_PLATFORMS: list[Platform] = [Platform.MEDIA_PLAYER]
type PJLinkConfigEntry = ConfigEntry[PJLink]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
async def async_setup_entry(hass: HomeAssistant, entry: PJLinkConfigEntry) -> None:
"""Set up PJLink from a config entry."""
client = PJLink(
entry.data[CONF_HOST],
entry.data[CONF_PORT],
entry.data.get(CONF_PASSWORD),
idle_timeout_seconds=2,
)
entry.runtime_data = client
await hass.config_entries.async_forward_entry_setups(entry, _PLATFORMS)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
async def async_unload_entry(hass: HomeAssistant, entry: PJLinkConfigEntry) -> None:
"""Unload a config entry."""
await hass.config_entries.async_unload_platforms_or_raise(entry, _PLATFORMS)
await entry.runtime_data.close()
+11 -19
View File
@@ -3,9 +3,8 @@
import logging
from typing import Any, override
from aiopjlink2 import PJLink, PJLinkAuthenticationError, PJLinkConnectionError
import probatio
from pypjlink import Projector
from pypjlink.projector import ProjectorError
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT
@@ -23,15 +22,6 @@ STEP_USER_DATA_SCHEMA = probatio.Schema(
)
def validate_projector_connection(
host: str, port: int | None, password: str | None
) -> str:
"""Validate that we can connect to the projector."""
with Projector.from_address(host, port) as projector:
projector.authenticate(password)
return projector.get_name()
class PJLinkConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for PJLink."""
@@ -47,22 +37,24 @@ class PJLinkConfigFlow(ConfigFlow, domain=DOMAIN):
self._async_abort_entries_match(
{CONF_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT]}
)
client = PJLink(
user_input[CONF_HOST],
user_input[CONF_PORT],
user_input.get(CONF_PASSWORD),
)
try:
projector_name = await self.hass.async_add_executor_job(
validate_projector_connection,
user_input[CONF_HOST],
user_input[CONF_PORT],
user_input.get(CONF_PASSWORD),
)
except TimeoutError, OSError:
projector_name = await client.info.projector_name()
except PJLinkConnectionError:
errors["base"] = "cannot_connect"
except RuntimeError, ProjectorError:
except PJLinkAuthenticationError:
errors["base"] = "invalid_auth"
except Exception:
_LOGGER.exception("Unexpected exception")
errors["base"] = "unknown"
else:
return self.async_create_entry(title=projector_name, data=user_input)
finally:
await client.close()
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
@@ -8,6 +8,6 @@
"documentation": "https://www.home-assistant.io/integrations/pjlink",
"integration_type": "device",
"iot_class": "local_polling",
"loggers": ["pypjlink"],
"requirements": ["pypjlink2==1.2.1"]
"loggers": ["aiopjlink2"],
"requirements": ["aiopjlink2==2.0.0"]
}
+84 -85
View File
@@ -1,10 +1,10 @@
"""Support for controlling projector via the PJLink protocol."""
from collections.abc import Callable
from typing import Any, override
from collections.abc import Awaitable, Callable
import logging
from typing import override
from pypjlink import MUTE_AUDIO, Projector
from pypjlink.projector import ProjectorError
from aiopjlink2 import PJLink, PJLinkError, PJLinkNotReadyError, Power, Sources
from homeassistant.components.media_player import (
MediaPlayerDeviceClass,
@@ -12,27 +12,27 @@ from homeassistant.components.media_player import (
MediaPlayerEntityFeature,
MediaPlayerState,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
ERR_PROJECTOR_UNAVAILABLE = "projector unavailable"
from . import PJLinkConfigEntry
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
entry: PJLinkConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up PJLink media player."""
async_add_entities([PjLinkDevice(entry)], update_before_add=True)
def format_input_source(input_source_name, input_source_number):
def _format_input_source(input_source: tuple[Sources.Mode, str]) -> str:
"""Format input source for display in UI."""
return f"{input_source_name} {input_source_number}"
return f"{input_source[0].name} {input_source[1]}"
class PjLinkDevice(MediaPlayerEntity):
@@ -46,12 +46,11 @@ class PjLinkDevice(MediaPlayerEntity):
| MediaPlayerEntityFeature.SELECT_SOURCE
)
def __init__(self, entry: ConfigEntry) -> None:
def __init__(self, entry: PJLinkConfigEntry) -> None:
"""Initialize the PJLink device."""
self._host = entry.data[CONF_HOST]
self._port = entry.data[CONF_PORT]
self._password = entry.data.get(CONF_PASSWORD)
self._source_name_mapping: dict[str, Any] = {}
self._projector = entry.runtime_data
self._source_name_mapping: dict[str, tuple[Sources.Mode, str]] = {}
self._source_list_loaded = False
self._attr_name = entry.title
self._attr_is_volume_muted = False
@@ -66,91 +65,91 @@ class PjLinkDevice(MediaPlayerEntity):
self._attr_is_volume_muted = False
self._attr_source = None
def _setup_projector(self):
try:
with self.projector() as projector:
if not self._attr_name:
self._attr_name = projector.get_name()
inputs = projector.get_inputs()
except ProjectorError as err:
if str(err) == ERR_PROJECTOR_UNAVAILABLE:
return False
raise
self._source_name_mapping = {format_input_source(*x): x for x in inputs}
self._attr_source_list = sorted(self._source_name_mapping)
return True
def projector(self):
"""Create PJLink Projector instance."""
try:
projector = Projector.from_address(self._host, self._port)
projector.authenticate(self._password)
except (TimeoutError, OSError) as err:
self._attr_available = False
raise ProjectorError(ERR_PROJECTOR_UNAVAILABLE) from err
return projector
def update(self) -> None:
"""Get the latest state from the device."""
if not self._attr_available:
self._attr_available = self._setup_projector()
if not self._attr_available:
self._force_off()
async def _async_update_source_list(self) -> None:
"""Fetch the source list after the projector is on."""
if self._source_list_loaded:
return
try:
with self.projector() as projector:
pwstate = projector.get_power()
if pwstate in ("on", "warm-up"):
self._attr_state = MediaPlayerState.ON
self._attr_is_volume_muted = projector.get_mute()[1]
self._attr_source = format_input_source(*projector.get_input())
else:
self._force_off()
except KeyError as err:
if str(err) == "'OK'":
self._force_off()
else:
raise
except ProjectorError as err:
if str(err) == "unavailable time":
self._force_off()
elif str(err) == ERR_PROJECTOR_UNAVAILABLE:
self._attr_available = False
else:
raise
inputs = await self._projector.sources.available()
except PJLinkError as err:
_LOGGER.debug("Unable to update projector sources: %r", err)
return
def _run_command(self, command: Callable[[Projector], None]) -> None:
self._source_name_mapping = {_format_input_source(x): x for x in inputs}
self._attr_source_list = sorted(self._source_name_mapping)
self._source_list_loaded = True
async def async_update(self) -> None:
"""Get the latest state from the device."""
try:
pwstate = await self._projector.power.get()
except PJLinkNotReadyError:
self._attr_available = True
self._force_off()
return
except PJLinkError as err:
_LOGGER.debug("Unable to update projector: %r", err)
self._attr_available = False
return
self._attr_available = True
if pwstate not in (Power.State.ON, Power.State.WARMING):
self._force_off()
return
self._attr_state = MediaPlayerState.ON
if pwstate is Power.State.WARMING:
return
await self._async_update_source_list()
try:
mute_status = await self._projector.mute.status()
self._attr_is_volume_muted = mute_status[1]
self._attr_source = _format_input_source(
await self._projector.sources.get()
)
except PJLinkNotReadyError:
return
except PJLinkError as err:
_LOGGER.debug("Unable to update projector: %r", err)
self._attr_available = False
async def _async_run_command(
self, command: Callable[[PJLink], Awaitable[None]]
) -> None:
"""Run a projector command and surface failures as HomeAssistantError."""
try:
with self.projector() as projector:
command(projector)
except (ProjectorError, TimeoutError, OSError) as err:
# script helpers honor continue_on_error only for HomeAssistantError
raise HomeAssistantError(f"PJLink command failed: {err}") from err
await command(self._projector)
except PJLinkError as err:
raise HomeAssistantError("PJLink command failed") from err
@override
def turn_off(self) -> None:
async def async_turn_off(self) -> None:
"""Turn projector off."""
self._run_command(lambda projector: projector.set_power("off"))
await self._async_run_command(lambda projector: projector.power.turn_off())
@override
def turn_on(self) -> None:
async def async_turn_on(self) -> None:
"""Turn projector on."""
self._run_command(lambda projector: projector.set_power("on"))
await self._async_run_command(lambda projector: projector.power.turn_on())
@override
def mute_volume(self, mute: bool) -> None:
async def async_mute_volume(self, mute: bool) -> None:
"""Mute (true) of unmute (false) media player."""
self._run_command(lambda projector: projector.set_mute(MUTE_AUDIO, mute))
await self._async_run_command(lambda projector: projector.mute.audio(mute))
@override
def select_source(self, source: str) -> None:
async def async_select_source(self, source: str) -> None:
"""Set the input source."""
selected = self._source_name_mapping[source]
self._run_command(lambda projector: projector.set_input(*selected))
if not self._source_list_loaded:
await self._async_update_source_list()
try:
mode, index = self._source_name_mapping[source]
except KeyError as err:
raise HomeAssistantError("PJLink source is not available") from err
await self._async_run_command(
lambda projector: projector.sources.set(mode, index)
)
+3 -3
View File
@@ -406,6 +406,9 @@ aiooui==0.1.11
# homeassistant.components.pegel_online
aiopegelonline==0.1.1
# homeassistant.components.pjlink
aiopjlink2==2.0.0
# homeassistant.components.opnsense
aiopnsense==1.0.10
@@ -2610,9 +2613,6 @@ pypck==0.9.13
# homeassistant.components.pglab
pypglab==0.0.5
# homeassistant.components.pjlink
pypjlink2==1.2.1
# homeassistant.components.plaato
pyplaato==0.0.19
+34 -9
View File
@@ -3,6 +3,7 @@
from collections.abc import Generator
from unittest.mock import AsyncMock, MagicMock, patch
from aiopjlink2 import Power, Sources
import pytest
from pytest_homeassistant.common import MockConfigEntry
@@ -30,13 +31,37 @@ def mock_config_entry() -> MockConfigEntry:
@pytest.fixture
def mock_projector() -> Generator[MagicMock]:
def mock_pjlink() -> Generator[MagicMock]:
"""Mock the PJLink Projector in the config flow."""
with patch(
"homeassistant.components.pjlink.config_flow.Projector",
autospec=True,
) as mock_projector:
mock_instance = mock_projector.from_address.return_value
mock_instance.get_name.return_value = "test name"
mock_instance.__enter__.return_value = mock_instance
yield mock_projector
with (
patch("homeassistant.components.pjlink.PJLink", autospec=True) as mock_class,
patch("homeassistant.components.pjlink.config_flow.PJLink", new=mock_class),
):
instance = mock_class.return_value
instance.info = MagicMock()
instance.info.projector_name = AsyncMock(return_value="test name")
instance.power = MagicMock()
instance.power.get = AsyncMock(return_value=Power.State.OFF)
instance.power.turn_off = AsyncMock()
instance.power.turn_on = AsyncMock()
# The library returns the input index as a single character string.
instance.sources = MagicMock()
instance.sources.get = AsyncMock(return_value=(Sources.Mode.DIGITAL, "1"))
instance.sources.available = AsyncMock(
return_value=[
(Sources.Mode.DIGITAL, "1"),
(Sources.Mode.DIGITAL, "2"),
(Sources.Mode.VIDEO, "1"),
]
)
instance.sources.set = AsyncMock()
instance.mute = MagicMock()
instance.mute.status = AsyncMock(return_value=(False, True))
instance.mute.audio = AsyncMock()
yield instance
+20 -8
View File
@@ -2,6 +2,13 @@
from unittest.mock import AsyncMock, MagicMock
from aiopjlink2 import (
PJLinkAuthenticationError,
PJLinkConnectionClosedError,
PJLinkNoConnectionError,
PJLinkProtocolError,
PJLinkUnexpectedValueError,
)
import pytest
from pytest_homeassistant.common import MockConfigEntry
@@ -16,7 +23,7 @@ from .const import DEFAULT_DATA
async def test_user_flow_creates_entry(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_projector: MagicMock,
mock_pjlink: MagicMock,
) -> None:
"""Test that the user flow creates an entry."""
result = await hass.config_entries.flow.async_init(
@@ -32,12 +39,13 @@ async def test_user_flow_creates_entry(
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test name"
assert result["data"] == DEFAULT_DATA
mock_pjlink.close.assert_awaited_once()
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.usefixtures("mock_setup_entry")
async def test_user_flow_aborts_if_already_configured(
hass: HomeAssistant, mock_projector: MagicMock, mock_config_entry: MockConfigEntry
hass: HomeAssistant, mock_pjlink: MagicMock, mock_config_entry: MockConfigEntry
) -> None:
"""Test user flow aborts if already configured."""
@@ -60,15 +68,18 @@ async def test_user_flow_aborts_if_already_configured(
@pytest.mark.parametrize(
("side_effect", "error_str"),
[
(RuntimeError, "invalid_auth"),
(TimeoutError, "cannot_connect"),
(PJLinkAuthenticationError, "invalid_auth"),
(PJLinkNoConnectionError, "cannot_connect"),
(PJLinkConnectionClosedError, "cannot_connect"),
(PJLinkProtocolError, "unknown"),
(PJLinkUnexpectedValueError, "unknown"),
(Exception, "unknown"),
],
)
async def test_form_invalid_inputs(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
mock_projector: MagicMock,
mock_pjlink: MagicMock,
side_effect: type[Exception],
error_str: str,
) -> None:
@@ -77,16 +88,16 @@ async def test_form_invalid_inputs(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
mock_instance = mock_projector.from_address.return_value
mock_instance.authenticate.side_effect = side_effect
mock_pjlink.info.projector_name.side_effect = side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"], DEFAULT_DATA
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": error_str}
mock_pjlink.close.assert_awaited_once()
mock_instance.authenticate.side_effect = None
mock_pjlink.info.projector_name.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], DEFAULT_DATA
)
@@ -94,4 +105,5 @@ async def test_form_invalid_inputs(
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "test name"
assert result["data"] == DEFAULT_DATA
assert mock_pjlink.close.await_count == 2
assert len(mock_setup_entry.mock_calls) == 1
+194 -122
View File
@@ -1,13 +1,22 @@
"""Test the pjlink media player platform."""
from datetime import timedelta
import socket
import logging
from operator import attrgetter
from typing import Any
from unittest.mock import MagicMock, create_autospec, patch
from unittest.mock import MagicMock
import pypjlink
from pypjlink import MUTE_AUDIO
from pypjlink.projector import ProjectorError
from aiopjlink2 import (
PJLinkConnectionClosedError,
PJLinkMalfunctionError,
PJLinkNoConnectionError,
PJLinkNotReadyError,
PJLinkProjectorError,
PJLinkProtocolError,
PJLinkUnexpectedValueError,
Power,
Sources,
)
import pytest
from pytest_homeassistant.common import async_fire_time_changed
@@ -20,45 +29,12 @@ from homeassistant.util import dt as dt_util
from . import setup_pjlink_entry
@pytest.fixture(name="projector_from_address")
def projector_from_address():
"""Create pjlink Projector mock."""
with patch("pypjlink.Projector.from_address") as from_address:
constructor = create_autospec(pypjlink.Projector)
constructor.__enter__.return_value = constructor
from_address.return_value = constructor
yield from_address
@pytest.fixture(name="mocked_projector")
def mocked_projector(projector_from_address: MagicMock) -> MagicMock:
"""Create pjlink Projector instance mock."""
instance = projector_from_address.return_value
instance.get_name.return_value = "Test"
instance.get_power.return_value = "on"
instance.get_mute.return_value = [0, True]
instance.get_input.return_value = [0, 1]
instance.get_inputs.return_value = (
("HDMI", 1),
("HDMI", 2),
("VGA", 1),
)
instance.__enter__.return_value = instance
return instance
@pytest.mark.parametrize("side_effect", [socket.timeout, OSError])
async def test_offline_initialization(
projector_from_address: MagicMock, hass: HomeAssistant, side_effect: type[Exception]
mock_pjlink: MagicMock, hass: HomeAssistant
) -> None:
"""Test initialization of a device that is offline."""
projector_from_address.side_effect = side_effect
mock_pjlink.power.get.side_effect = PJLinkNoConnectionError
await setup_pjlink_entry(hass)
@@ -66,79 +42,163 @@ async def test_offline_initialization(
assert state.state == "unavailable"
async def test_initialization(
projector_from_address: MagicMock, hass: HomeAssistant
async def test_not_ready_initialization(
mock_pjlink: MagicMock, hass: HomeAssistant
) -> None:
"""Test a device that is available."""
"""Test initialization when the projector is not ready."""
mocked_instance = projector_from_address.return_value
mock_pjlink.power.get.side_effect = PJLinkNotReadyError
mocked_instance.get_name.return_value = "Test"
mocked_instance.get_inputs.return_value = (
("HDMI", 1),
("HDMI", 2),
("VGA", 1),
)
await setup_pjlink_entry(hass)
state = hass.states.get("media_player.test")
assert state.state == "off"
assert "source_list" in state.attributes
source_list = state.attributes["source_list"]
assert set(source_list) == {"HDMI 1", "HDMI 2", "VGA 1"}
async def test_not_ready_recovers_availability(
mock_pjlink: MagicMock, hass: HomeAssistant
) -> None:
"""Test not-ready response makes an unavailable projector available."""
mock_pjlink.power.get.return_value = Power.State.ON
await setup_pjlink_entry(hass)
mock_pjlink.power.get.side_effect = PJLinkNoConnectionError
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get("media_player.test").state == "unavailable"
mock_pjlink.power.get.side_effect = PJLinkNotReadyError
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get("media_player.test").state == "off"
@pytest.mark.parametrize(
"error",
[
PJLinkNoConnectionError,
PJLinkConnectionClosedError,
PJLinkProtocolError,
PJLinkNotReadyError,
PJLinkMalfunctionError,
PJLinkUnexpectedValueError,
],
)
async def test_source_list_error_does_not_make_projector_unavailable(
mock_pjlink: MagicMock,
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
error: type[Exception],
) -> None:
"""Test that PJLink errors during initialization do not prevent entity creation."""
caplog.set_level(
logging.DEBUG, logger="homeassistant.components.pjlink.media_player"
)
mock_pjlink.sources.available.side_effect = error
await setup_pjlink_entry(hass)
state = hass.states.get("media_player.test")
assert state.state == "off"
mock_pjlink.sources.available.assert_not_awaited()
mock_pjlink.power.get.return_value = Power.State.ON
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("media_player.test")
assert state.state == "on"
mock_pjlink.sources.available.assert_awaited_once()
assert error.__name__ in caplog.text
mock_pjlink.sources.available.side_effect = None
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done(wait_background_tasks=True)
state = hass.states.get("media_player.test")
assert state.state == "on"
assert state.attributes["source_list"] == [
"DIGITAL 1",
"DIGITAL 2",
"VIDEO 1",
]
async def test_initialization(mock_pjlink: MagicMock, hass: HomeAssistant) -> None:
"""Test a device that is available."""
await setup_pjlink_entry(hass)
state = hass.states.get("media_player.test")
assert state.state == "off"
assert "source_list" not in state.attributes
mock_pjlink.sources.available.assert_not_awaited()
assert state.attributes["device_class"] == "projector"
@pytest.mark.parametrize("power_state", ["on", "warm-up"])
@pytest.mark.parametrize(
("power_state", "source"),
[
pytest.param(Power.State.ON, "DIGITAL 1", id="on"),
pytest.param(Power.State.WARMING, None, id="warming"),
],
)
async def test_on_state_init(
mocked_projector: MagicMock, hass: HomeAssistant, power_state: str
mock_pjlink: MagicMock,
hass: HomeAssistant,
power_state: Power.State,
source: str | None,
) -> None:
"""Test a device that is available."""
mocked_projector.get_power.return_value = power_state
mocked_projector.get_input.return_value = ("HDMI", 1)
mock_pjlink.power.get.return_value = power_state
await setup_pjlink_entry(hass)
state = hass.states.get("media_player.test")
assert state.state == "on"
assert state.attributes["source"] == "HDMI 1"
assert state.attributes.get("source") == source
async def test_api_error(mocked_projector: MagicMock, hass: HomeAssistant) -> None:
"""Test invalid api responses."""
@pytest.mark.parametrize(
("power_state", "expected_mute_status_calls"),
[
pytest.param(Power.State.ON, 1, id="on"),
pytest.param(Power.State.WARMING, 0, id="warming"),
],
)
async def test_not_ready_detail_query_keeps_projector_on(
mock_pjlink: MagicMock,
hass: HomeAssistant,
power_state: Power.State,
expected_mute_status_calls: int,
) -> None:
"""A not-ready detail query does not turn an on or warming projector off."""
mocked_projector.get_power.side_effect = KeyError("OK")
mock_pjlink.power.get.return_value = power_state
mock_pjlink.mute.status.side_effect = PJLinkNotReadyError
await setup_pjlink_entry(hass)
state = hass.states.get("media_player.test")
assert state.state == "off"
assert state.state == "on"
assert mock_pjlink.mute.status.await_count == expected_mute_status_calls
async def test_update_unavailable(
projector_from_address: MagicMock, hass: HomeAssistant
) -> None:
async def test_update_unavailable(mock_pjlink: MagicMock, hass: HomeAssistant) -> None:
"""Test update to a device that is unavailable."""
mocked_instance = projector_from_address.return_value
mocked_instance.get_name.return_value = "Test"
mocked_instance.get_inputs.return_value = (
("HDMI", 1),
("HDMI", 2),
("VGA", 1),
)
await setup_pjlink_entry(hass)
state = hass.states.get("media_player.test")
assert state.state == "off"
projector_from_address.side_effect = socket.timeout
mock_pjlink.power.get.side_effect = PJLinkNoConnectionError
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done(wait_background_tasks=True)
@@ -146,11 +206,44 @@ async def test_update_unavailable(
assert state.state == "unavailable"
async def test_unavailable_time(
mocked_projector: MagicMock, hass: HomeAssistant
@pytest.mark.parametrize(
"error",
[
PJLinkConnectionClosedError,
PJLinkProtocolError,
PJLinkMalfunctionError,
PJLinkUnexpectedValueError,
],
)
async def test_update_error_sets_unavailable(
mock_pjlink: MagicMock,
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
error: type[Exception],
) -> None:
"""Test PJLink errors during updates mark the entity unavailable."""
caplog.set_level(
logging.DEBUG, logger="homeassistant.components.pjlink.media_player"
)
mock_pjlink.power.get.return_value = Power.State.ON
await setup_pjlink_entry(hass)
assert hass.states.get("media_player.test").state == "on"
mock_pjlink.power.get.side_effect = error
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done(wait_background_tasks=True)
assert hass.states.get("media_player.test").state == "unavailable"
assert error.__name__ in caplog.text
async def test_unavailable_time(mock_pjlink: MagicMock, hass: HomeAssistant) -> None:
"""Test unavailable time projector error."""
mock_pjlink.power.get.return_value = Power.State.ON
await setup_pjlink_entry(hass)
state = hass.states.get("media_player.test")
@@ -158,7 +251,7 @@ async def test_unavailable_time(
assert state.attributes["source"] is not None
assert state.attributes["is_volume_muted"] is not False
mocked_projector.get_power.side_effect = ProjectorError("unavailable time")
mock_pjlink.power.get.side_effect = PJLinkNotReadyError
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=10))
await hass.async_block_till_done(wait_background_tasks=True)
@@ -168,7 +261,7 @@ async def test_unavailable_time(
assert "is_volume_muted" not in state.attributes
async def test_turn_off(mocked_projector: MagicMock, hass: HomeAssistant) -> None:
async def test_turn_off(mock_pjlink: MagicMock, hass: HomeAssistant) -> None:
"""Test turning off beamer."""
await setup_pjlink_entry(hass)
@@ -180,10 +273,10 @@ async def test_turn_off(mocked_projector: MagicMock, hass: HomeAssistant) -> Non
blocking=True,
)
mocked_projector.set_power.assert_called_with("off")
mock_pjlink.power.turn_off.assert_awaited()
async def test_turn_on(mocked_projector: MagicMock, hass: HomeAssistant) -> None:
async def test_turn_on(mock_pjlink: MagicMock, hass: HomeAssistant) -> None:
"""Test turning on beamer."""
await setup_pjlink_entry(hass)
@@ -195,10 +288,10 @@ async def test_turn_on(mocked_projector: MagicMock, hass: HomeAssistant) -> None
blocking=True,
)
mocked_projector.set_power.assert_called_with("on")
mock_pjlink.power.turn_on.assert_awaited()
async def test_mute(mocked_projector: MagicMock, hass: HomeAssistant) -> None:
async def test_mute(mock_pjlink: MagicMock, hass: HomeAssistant) -> None:
"""Test muting beamer."""
await setup_pjlink_entry(hass)
@@ -210,10 +303,10 @@ async def test_mute(mocked_projector: MagicMock, hass: HomeAssistant) -> None:
blocking=True,
)
mocked_projector.set_mute.assert_called_with(MUTE_AUDIO, True)
mock_pjlink.mute.audio.assert_awaited_with(True)
async def test_unmute(mocked_projector: MagicMock, hass: HomeAssistant) -> None:
async def test_unmute(mock_pjlink: MagicMock, hass: HomeAssistant) -> None:
"""Test unmuting beamer."""
await setup_pjlink_entry(hass)
@@ -225,42 +318,44 @@ async def test_unmute(mocked_projector: MagicMock, hass: HomeAssistant) -> None:
blocking=True,
)
mocked_projector.set_mute.assert_called_with(MUTE_AUDIO, False)
mock_pjlink.mute.audio.assert_awaited_with(False)
async def test_select_source(mocked_projector: MagicMock, hass: HomeAssistant) -> None:
async def test_select_source(mock_pjlink: MagicMock, hass: HomeAssistant) -> None:
"""Test selecting source."""
mock_pjlink.power.get.return_value = Power.State.ON
await setup_pjlink_entry(hass)
await hass.services.async_call(
domain=media_player.DOMAIN,
service="select_source",
service_data={ATTR_ENTITY_ID: "media_player.test", "source": "VGA 1"},
service_data={ATTR_ENTITY_ID: "media_player.test", "source": "VIDEO 1"},
blocking=True,
)
mocked_projector.set_input.assert_called_with("VGA", 1)
mock_pjlink.sources.set.assert_awaited_with(Sources.Mode.VIDEO, "1")
_ERROR = ProjectorError("projector error")
_ERROR = PJLinkProjectorError("projector error")
@pytest.mark.parametrize(
("service", "service_data", "method_name"),
[
pytest.param("turn_off", {}, "set_power", id="turn_off"),
pytest.param("turn_on", {}, "set_power", id="turn_on"),
pytest.param("turn_off", {}, "power.turn_off", id="turn_off"),
pytest.param("turn_on", {}, "power.turn_on", id="turn_on"),
pytest.param(
"volume_mute", {"is_volume_muted": True}, "set_mute", id="volume_mute"
"volume_mute", {"is_volume_muted": True}, "mute.audio", id="volume_mute"
),
pytest.param(
"select_source", {"source": "VGA 1"}, "set_input", id="select_source"
"select_source", {"source": "VIDEO 1"}, "sources.set", id="select_source"
),
],
)
async def test_service_command_error_is_home_assistant_error(
mocked_projector: MagicMock,
mock_pjlink: MagicMock,
hass: HomeAssistant,
service: str,
service_data: dict[str, Any],
@@ -268,7 +363,8 @@ async def test_service_command_error_is_home_assistant_error(
) -> None:
"""Projector failures during a service command surface as HomeAssistantError."""
getattr(mocked_projector, method_name).side_effect = _ERROR
attrgetter(method_name)(mock_pjlink).side_effect = _ERROR
mock_pjlink.power.get.return_value = Power.State.ON
await setup_pjlink_entry(hass)
@@ -282,38 +378,14 @@ async def test_service_command_error_is_home_assistant_error(
async def test_service_error_when_projector_unreachable_is_home_assistant_error(
mocked_projector: MagicMock,
projector_from_address: MagicMock,
mock_pjlink: MagicMock,
hass: HomeAssistant,
) -> None:
"""A command on an unreachable projector surfaces as HomeAssistantError."""
await setup_pjlink_entry(hass)
projector_from_address.side_effect = socket.timeout
with pytest.raises(HomeAssistantError):
await hass.services.async_call(
media_player.DOMAIN,
"turn_off",
{ATTR_ENTITY_ID: "media_player.test"},
blocking=True,
)
@pytest.mark.parametrize(
"socket_error", [TimeoutError, OSError], ids=["timeout", "os_error"]
)
async def test_service_socket_error_during_command_is_home_assistant_error(
mocked_projector: MagicMock,
hass: HomeAssistant,
socket_error: type[Exception],
) -> None:
"""A socket error raised by the command itself surfaces as HomeAssistantError."""
mocked_projector.set_power.side_effect = socket_error
await setup_pjlink_entry(hass)
mock_pjlink.power.turn_off.side_effect = PJLinkNoConnectionError
with pytest.raises(HomeAssistantError):
await hass.services.async_call(