mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 04:08:19 -04:00
Expand the Openhome test coverage (#181686)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5
parent
f4a2213b12
commit
1c8b7287e0
@@ -1 +1,25 @@
|
||||
"""Tests for the Linn / OpenHome integration."""
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
|
||||
|
||||
async def setup_integration(hass: HomeAssistant, config_entry: MockConfigEntry) -> None:
|
||||
"""Set up the openhome integration."""
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
await hass.config_entries.async_setup(config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def async_poll(hass: HomeAssistant) -> None:
|
||||
"""Trigger a poll of the polling platforms.
|
||||
|
||||
Well past the media player's ten second scan interval.
|
||||
"""
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=30))
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Fixtures for the Openhome integration tests."""
|
||||
|
||||
from collections.abc import Generator
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from openhomedevice.device import Device
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.openhome.const import DOMAIN
|
||||
from homeassistant.const import CONF_HOST, Platform
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
HOST = "http://localhost"
|
||||
|
||||
TRACK_INFO = {
|
||||
"albumArtwork": "http://localhost/album.jpg",
|
||||
"albumTitle": "album_title",
|
||||
"artist": ["artist"],
|
||||
"title": "title",
|
||||
"uri": "http://localhost/track.flac",
|
||||
}
|
||||
|
||||
SOURCES = [
|
||||
{"index": 0, "name": "Playlist", "type": "Playlist"},
|
||||
{"index": 1, "name": "Radio", "type": "Radio"},
|
||||
]
|
||||
|
||||
# The device coroutines the actions drive, referenced from the library so a
|
||||
# rename upstream fails the tests rather than leaving an action uncovered.
|
||||
ACTION_METHODS = (
|
||||
Device.set_standby,
|
||||
Device.play,
|
||||
Device.pause,
|
||||
Device.stop,
|
||||
Device.skip,
|
||||
Device.increase_volume,
|
||||
Device.decrease_volume,
|
||||
Device.set_volume,
|
||||
Device.set_mute,
|
||||
Device.set_source,
|
||||
Device.play_media,
|
||||
Device.invoke_pin,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config_entry() -> MockConfigEntry:
|
||||
"""Return a mocked config entry."""
|
||||
return MockConfigEntry(domain=DOMAIN, data={CONF_HOST: HOST}, unique_id="uuid")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platforms() -> list[Platform]:
|
||||
"""Platforms to load; override per module or per test."""
|
||||
return []
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def patch_platforms(platforms: list[Platform]) -> Generator[None]:
|
||||
"""Load only the platforms the test asks for."""
|
||||
with patch("homeassistant.components.openhome.PLATFORMS", platforms):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_device_class() -> Generator[MagicMock]:
|
||||
"""Return the patched Openhome Device class."""
|
||||
with patch("homeassistant.components.openhome.Device", MagicMock()) as mock_class:
|
||||
device = mock_class.return_value
|
||||
device.init = AsyncMock()
|
||||
device.uuid = MagicMock(return_value="uuid")
|
||||
device.manufacturer = MagicMock(return_value="manufacturer")
|
||||
device.model_name = MagicMock(return_value="model_name")
|
||||
device.friendly_name = MagicMock(return_value="friendly_name")
|
||||
device.volume_enabled = True
|
||||
device.pins_enabled = True
|
||||
device.room = AsyncMock(return_value="room")
|
||||
device.track_info = AsyncMock(return_value={})
|
||||
device.volume = AsyncMock(return_value=50)
|
||||
device.is_muted = AsyncMock(return_value=False)
|
||||
device.sources = AsyncMock(return_value=SOURCES)
|
||||
device.source = AsyncMock(return_value=SOURCES[0])
|
||||
device.is_in_standby = AsyncMock(return_value=False)
|
||||
device.transport_state = AsyncMock(return_value="Playing")
|
||||
device.software_status = AsyncMock(return_value=None)
|
||||
device.update_firmware = AsyncMock()
|
||||
for method in ACTION_METHODS:
|
||||
setattr(device, method.__name__, AsyncMock())
|
||||
yield mock_class
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_device(mock_device_class: MagicMock) -> MagicMock:
|
||||
"""Return a mocked Openhome device that polls successfully."""
|
||||
return mock_device_class.return_value
|
||||
@@ -0,0 +1,70 @@
|
||||
# serializer version: 1
|
||||
# name: test_media_player[media_player.friendly_name-entry]
|
||||
EntityRegistryEntrySnapshot({
|
||||
'aliases': list([
|
||||
None,
|
||||
]),
|
||||
'area_id': None,
|
||||
'capabilities': dict({
|
||||
<MediaPlayerEntityCapabilityAttribute.INPUT_SOURCE_LIST: 'source_list'>: list([
|
||||
'Playlist',
|
||||
'Radio',
|
||||
]),
|
||||
}),
|
||||
'config_entry_id': <ANY>,
|
||||
'config_subentry_id': <ANY>,
|
||||
'device_class': None,
|
||||
'device_id': <ANY>,
|
||||
'disabled_by': None,
|
||||
'domain': 'media_player',
|
||||
'entity_category': None,
|
||||
'entity_id': 'media_player.friendly_name',
|
||||
'has_entity_name': False,
|
||||
'hidden_by': None,
|
||||
'icon': None,
|
||||
'id': <ANY>,
|
||||
'labels': set({
|
||||
}),
|
||||
'name': None,
|
||||
'object_id_base': None,
|
||||
'options': dict({
|
||||
}),
|
||||
'original_device_class': None,
|
||||
'original_icon': None,
|
||||
'original_name': 'room',
|
||||
'platform': 'openhome',
|
||||
'previous_unique_id': None,
|
||||
'suggested_object_id': None,
|
||||
'supported_features': <MediaPlayerEntityFeature: 151485>,
|
||||
'translation_key': None,
|
||||
'unique_id': 'uuid',
|
||||
'unit_of_measurement': None,
|
||||
})
|
||||
# ---
|
||||
# name: test_media_player[media_player.friendly_name-state]
|
||||
StateSnapshot({
|
||||
'attributes': ReadOnlyDict({
|
||||
<EntityStateAttribute.ENTITY_PICTURE: 'entity_picture'>: '/api/media_player_proxy/media_player.friendly_name?token=mock_token&cache=bf6152779af9031a',
|
||||
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'friendly_name room',
|
||||
<MediaPlayerEntityStateAttribute.MEDIA_VOLUME_MUTED: 'is_volume_muted'>: False,
|
||||
<MediaPlayerEntityStateAttribute.MEDIA_ALBUM_NAME: 'media_album_name'>: 'album_title',
|
||||
<MediaPlayerEntityStateAttribute.MEDIA_ARTIST: 'media_artist'>: 'artist',
|
||||
<MediaPlayerEntityStateAttribute.MEDIA_CONTENT_ID: 'media_content_id'>: 'http://localhost/track.flac',
|
||||
<MediaPlayerEntityStateAttribute.MEDIA_CONTENT_TYPE: 'media_content_type'>: <MediaType.MUSIC: 'music'>,
|
||||
<MediaPlayerEntityStateAttribute.MEDIA_TITLE: 'media_title'>: 'title',
|
||||
<MediaPlayerEntityStateAttribute.INPUT_SOURCE: 'source'>: 'Playlist',
|
||||
<MediaPlayerEntityCapabilityAttribute.INPUT_SOURCE_LIST: 'source_list'>: list([
|
||||
'Playlist',
|
||||
'Radio',
|
||||
]),
|
||||
<EntityStateAttribute.SUPPORTED_FEATURES: 'supported_features'>: <MediaPlayerEntityFeature: 151485>,
|
||||
<MediaPlayerEntityStateAttribute.MEDIA_VOLUME_LEVEL: 'volume_level'>: 0.5,
|
||||
}),
|
||||
'context': <ANY>,
|
||||
'entity_id': 'media_player.friendly_name',
|
||||
'last_changed': <ANY>,
|
||||
'last_reported': <ANY>,
|
||||
'last_updated': <ANY>,
|
||||
'state': 'playing',
|
||||
})
|
||||
# ---
|
||||
@@ -1,32 +1,61 @@
|
||||
"""Tests for the Openhome integration setup."""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from openhomedevice.exceptions import OpenhomeConnectionError
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.openhome.const import DOMAIN
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import CONF_HOST
|
||||
from homeassistant.const import STATE_UNAVAILABLE, Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
|
||||
from . import setup_integration
|
||||
from .conftest import HOST
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
HOST = "http://localhost"
|
||||
ENTITY_ID = "media_player.friendly_name"
|
||||
|
||||
|
||||
async def test_device_uses_shared_session(hass: HomeAssistant) -> None:
|
||||
async def test_device_uses_shared_session(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_device_class: MagicMock,
|
||||
) -> None:
|
||||
"""Test the device is given Home Assistant's shared aiohttp session."""
|
||||
entry = MockConfigEntry(domain=DOMAIN, data={CONF_HOST: HOST}, unique_id="uuid")
|
||||
entry.add_to_hass(hass)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.openhome.PLATFORMS", []),
|
||||
patch("homeassistant.components.openhome.Device", MagicMock()) as mock_device,
|
||||
):
|
||||
mock_device.return_value.init = AsyncMock()
|
||||
mock_device.return_value.uuid = MagicMock(return_value="uuid")
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
mock_device_class.assert_called_once_with(
|
||||
HOST, session=async_get_clientsession(hass)
|
||||
)
|
||||
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
mock_device.assert_called_once_with(HOST, session=async_get_clientsession(hass))
|
||||
async def test_setup_retries_when_device_unreachable(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_device: MagicMock
|
||||
) -> None:
|
||||
"""Test setup is retried when the device cannot be reached."""
|
||||
mock_device.init.side_effect = OpenhomeConnectionError("device unreachable")
|
||||
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
|
||||
@pytest.mark.parametrize("platforms", [[Platform.MEDIA_PLAYER]])
|
||||
@pytest.mark.usefixtures("mock_device")
|
||||
async def test_unload_entry(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry
|
||||
) -> None:
|
||||
"""Test unloading the config entry also unloads its platforms."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.LOADED
|
||||
assert hass.states.get(ENTITY_ID).state != STATE_UNAVAILABLE
|
||||
|
||||
assert 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
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
"""Tests for the Openhome media player platform."""
|
||||
|
||||
from collections.abc import Callable, Generator
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from openhomedevice.device import Device
|
||||
from openhomedevice.exceptions import OpenhomeConnectionError
|
||||
import pytest
|
||||
from syrupy.assertion import SnapshotAssertion
|
||||
|
||||
from homeassistant.components.media_player import (
|
||||
ATTR_INPUT_SOURCE,
|
||||
@@ -27,7 +27,6 @@ from homeassistant.components.openhome.services import (
|
||||
)
|
||||
from homeassistant.const import (
|
||||
ATTR_ENTITY_ID,
|
||||
CONF_HOST,
|
||||
SERVICE_MEDIA_NEXT_TRACK,
|
||||
SERVICE_MEDIA_PAUSE,
|
||||
SERVICE_MEDIA_PLAY,
|
||||
@@ -39,40 +38,27 @@ from homeassistant.const import (
|
||||
SERVICE_VOLUME_MUTE,
|
||||
SERVICE_VOLUME_SET,
|
||||
SERVICE_VOLUME_UP,
|
||||
STATE_IDLE,
|
||||
STATE_OFF,
|
||||
STATE_PAUSED,
|
||||
STATE_PLAYING,
|
||||
STATE_UNAVAILABLE,
|
||||
Platform,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.util import dt as dt_util
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from tests.common import MockConfigEntry, async_fire_time_changed
|
||||
from . import async_poll, setup_integration
|
||||
from .conftest import TRACK_INFO
|
||||
|
||||
from tests.common import MockConfigEntry, snapshot_platform
|
||||
|
||||
ENTITY_ID = "media_player.friendly_name"
|
||||
MEDIA_ID = "http://localhost/track.flac"
|
||||
|
||||
SOURCES = [
|
||||
{"index": 0, "name": "Playlist", "type": "Playlist"},
|
||||
{"index": 1, "name": "Radio", "type": "Radio"},
|
||||
]
|
||||
|
||||
# The device coroutines the actions drive, referenced from the library so a
|
||||
# rename upstream fails the test rather than silently skipping an action.
|
||||
ACTION_METHODS = (
|
||||
Device.set_standby,
|
||||
Device.play,
|
||||
Device.pause,
|
||||
Device.stop,
|
||||
Device.skip,
|
||||
Device.increase_volume,
|
||||
Device.decrease_volume,
|
||||
Device.set_volume,
|
||||
Device.set_mute,
|
||||
Device.set_source,
|
||||
Device.play_media,
|
||||
Device.invoke_pin,
|
||||
)
|
||||
|
||||
# Each action, the coroutine it drives, and a source type that exposes the
|
||||
# supported feature it is gated behind.
|
||||
# Each action, the coroutine it drives, a source type that exposes the supported
|
||||
# feature it is gated behind, and the arguments the device must be called with.
|
||||
ACTIONS = [
|
||||
pytest.param(
|
||||
MEDIA_PLAYER_DOMAIN,
|
||||
@@ -80,6 +66,7 @@ ACTIONS = [
|
||||
{},
|
||||
Device.set_standby,
|
||||
"Playlist",
|
||||
(False,),
|
||||
id="turn_on",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -88,6 +75,7 @@ ACTIONS = [
|
||||
{},
|
||||
Device.set_standby,
|
||||
"Playlist",
|
||||
(True,),
|
||||
id="turn_off",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -96,6 +84,7 @@ ACTIONS = [
|
||||
{},
|
||||
Device.play,
|
||||
"Playlist",
|
||||
(),
|
||||
id="media_play",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -104,6 +93,7 @@ ACTIONS = [
|
||||
{},
|
||||
Device.pause,
|
||||
"Playlist",
|
||||
(),
|
||||
id="media_pause",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -112,6 +102,7 @@ ACTIONS = [
|
||||
{},
|
||||
Device.stop,
|
||||
"Radio",
|
||||
(),
|
||||
id="media_stop",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -120,6 +111,7 @@ ACTIONS = [
|
||||
{},
|
||||
Device.skip,
|
||||
"Playlist",
|
||||
(1,),
|
||||
id="media_next_track",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -128,6 +120,7 @@ ACTIONS = [
|
||||
{},
|
||||
Device.skip,
|
||||
"Playlist",
|
||||
(-1,),
|
||||
id="media_previous_track",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -136,6 +129,7 @@ ACTIONS = [
|
||||
{},
|
||||
Device.increase_volume,
|
||||
"Playlist",
|
||||
(),
|
||||
id="volume_up",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -144,6 +138,7 @@ ACTIONS = [
|
||||
{},
|
||||
Device.decrease_volume,
|
||||
"Playlist",
|
||||
(),
|
||||
id="volume_down",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -152,6 +147,7 @@ ACTIONS = [
|
||||
{ATTR_MEDIA_VOLUME_LEVEL: 0.5},
|
||||
Device.set_volume,
|
||||
"Playlist",
|
||||
(50,),
|
||||
id="volume_set",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -160,14 +156,25 @@ ACTIONS = [
|
||||
{ATTR_MEDIA_VOLUME_MUTED: True},
|
||||
Device.set_mute,
|
||||
"Playlist",
|
||||
(True,),
|
||||
id="volume_mute",
|
||||
),
|
||||
pytest.param(
|
||||
MEDIA_PLAYER_DOMAIN,
|
||||
SERVICE_VOLUME_MUTE,
|
||||
{ATTR_MEDIA_VOLUME_MUTED: False},
|
||||
Device.set_mute,
|
||||
"Playlist",
|
||||
(False,),
|
||||
id="volume_unmute",
|
||||
),
|
||||
pytest.param(
|
||||
MEDIA_PLAYER_DOMAIN,
|
||||
SERVICE_SELECT_SOURCE,
|
||||
{ATTR_INPUT_SOURCE: "Playlist"},
|
||||
{ATTR_INPUT_SOURCE: "Radio"},
|
||||
Device.set_source,
|
||||
"Playlist",
|
||||
(1,),
|
||||
id="select_source",
|
||||
),
|
||||
pytest.param(
|
||||
@@ -175,82 +182,92 @@ ACTIONS = [
|
||||
SERVICE_PLAY_MEDIA,
|
||||
{
|
||||
ATTR_MEDIA_CONTENT_TYPE: MediaType.MUSIC,
|
||||
ATTR_MEDIA_CONTENT_ID: "http://localhost/track.flac",
|
||||
ATTR_MEDIA_CONTENT_ID: MEDIA_ID,
|
||||
},
|
||||
Device.play_media,
|
||||
"Playlist",
|
||||
({"title": "Home Assistant", "uri": MEDIA_ID},),
|
||||
id="play_media",
|
||||
),
|
||||
pytest.param(
|
||||
DOMAIN,
|
||||
SERVICE_INVOKE_PIN,
|
||||
{ATTR_PIN_INDEX: 1},
|
||||
Device.invoke_pin,
|
||||
"Playlist",
|
||||
id="invoke_pin",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def media_proxy_token() -> Generator[None]:
|
||||
"""Freeze the media proxy token, which otherwise varies per run."""
|
||||
with patch("secrets.token_hex", return_value="mock_token"):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_device() -> Generator[MagicMock]:
|
||||
"""Return a mocked Openhome device that polls successfully."""
|
||||
with patch("homeassistant.components.openhome.Device", MagicMock()) as mock_class:
|
||||
device = mock_class.return_value
|
||||
device.init = AsyncMock()
|
||||
device.uuid = MagicMock(return_value="uuid")
|
||||
device.manufacturer = MagicMock(return_value="manufacturer")
|
||||
device.model_name = MagicMock(return_value="model_name")
|
||||
device.friendly_name = MagicMock(return_value="friendly_name")
|
||||
device.volume_enabled = True
|
||||
device.pins_enabled = True
|
||||
device.room = AsyncMock(return_value="room")
|
||||
device.track_info = AsyncMock(return_value={})
|
||||
device.volume = AsyncMock(return_value=50)
|
||||
device.is_muted = AsyncMock(return_value=False)
|
||||
device.sources = AsyncMock(return_value=SOURCES)
|
||||
device.is_in_standby = AsyncMock(return_value=False)
|
||||
device.transport_state = AsyncMock(return_value="Playing")
|
||||
for method in ACTION_METHODS:
|
||||
setattr(device, method.__name__, AsyncMock())
|
||||
yield device
|
||||
def platforms() -> list[Platform]:
|
||||
"""Only load the media player platform."""
|
||||
return [Platform.MEDIA_PLAYER]
|
||||
|
||||
|
||||
async def setup_platform(
|
||||
hass: HomeAssistant, mock_device: MagicMock, source_type: str
|
||||
async def setup_media_player(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry
|
||||
) -> None:
|
||||
"""Load the media player platform and poll once to populate features."""
|
||||
mock_device.source = AsyncMock(
|
||||
return_value={"index": 0, "name": source_type, "type": source_type}
|
||||
)
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN, data={CONF_HOST: "http://localhost"}, unique_id="uuid"
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
with patch("homeassistant.components.openhome.PLATFORMS", [Platform.MEDIA_PLAYER]):
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
"""Load the media player platform and poll once."""
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
# Supported features are only set once the device has been polled.
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=30))
|
||||
await hass.async_block_till_done()
|
||||
await async_poll(hass)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("domain", "service", "data", "method", "source_type"), ACTIONS
|
||||
("domain", "service", "data", "method", "source_type", "expected_args"), ACTIONS
|
||||
)
|
||||
async def test_action_error_is_raised(
|
||||
async def test_action_calls_device(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_device: MagicMock,
|
||||
domain: str,
|
||||
service: str,
|
||||
data: dict[str, Any],
|
||||
method: Callable[..., Any],
|
||||
source_type: str,
|
||||
expected_args: tuple[Any, ...],
|
||||
) -> None:
|
||||
"""Test every action calls the device with the arguments it expects."""
|
||||
mock_device.source.return_value = {
|
||||
"index": 0,
|
||||
"name": source_type,
|
||||
"type": source_type,
|
||||
}
|
||||
|
||||
await setup_media_player(hass, mock_config_entry)
|
||||
|
||||
await hass.services.async_call(
|
||||
domain, service, {ATTR_ENTITY_ID: ENTITY_ID, **data}, blocking=True
|
||||
)
|
||||
|
||||
getattr(mock_device, method.__name__).assert_awaited_once_with(*expected_args)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("domain", "service", "data", "method", "source_type", "expected_args"), ACTIONS
|
||||
)
|
||||
async def test_action_error_is_raised(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_device: MagicMock,
|
||||
domain: str,
|
||||
service: str,
|
||||
data: dict[str, Any],
|
||||
method: Callable[..., Any],
|
||||
source_type: str,
|
||||
expected_args: tuple[Any, ...],
|
||||
) -> None:
|
||||
"""Test every action raises when the device rejects the request."""
|
||||
await setup_platform(hass, mock_device, source_type)
|
||||
# The feature each action is gated behind depends on the selected source.
|
||||
mock_device.source.return_value = {
|
||||
"index": 0,
|
||||
"name": source_type,
|
||||
"type": source_type,
|
||||
}
|
||||
|
||||
await setup_media_player(hass, mock_config_entry)
|
||||
|
||||
mocked = getattr(mock_device, method.__name__)
|
||||
mocked.side_effect = OpenhomeConnectionError("no route to host")
|
||||
@@ -266,12 +283,42 @@ async def test_action_error_is_raised(
|
||||
mocked.assert_awaited()
|
||||
|
||||
|
||||
async def test_invoke_pin_without_pin_support(
|
||||
hass: HomeAssistant, mock_device: MagicMock
|
||||
async def test_invoke_pin_calls_device(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_device: MagicMock
|
||||
) -> None:
|
||||
"""Test invoking a pin on a device without pin support raises."""
|
||||
mock_device.pins_enabled = False
|
||||
await setup_platform(hass, mock_device, "Playlist")
|
||||
"""Test the invoke_pin action passes the requested pin to the device."""
|
||||
await setup_media_player(hass, mock_config_entry)
|
||||
|
||||
await hass.services.async_call(
|
||||
DOMAIN,
|
||||
SERVICE_INVOKE_PIN,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID, ATTR_PIN_INDEX: 3},
|
||||
blocking=True,
|
||||
)
|
||||
|
||||
mock_device.invoke_pin.assert_awaited_once_with(3)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("pins_enabled", "translation_key", "await_count"),
|
||||
[
|
||||
pytest.param(True, SERVICE_INVOKE_PIN, 1, id="pins_supported"),
|
||||
pytest.param(False, "pins_not_supported", 0, id="pins_not_supported"),
|
||||
],
|
||||
)
|
||||
async def test_invoke_pin(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_device: MagicMock,
|
||||
pins_enabled: bool,
|
||||
translation_key: str,
|
||||
await_count: int,
|
||||
) -> None:
|
||||
"""Test invoking a pin on a device with and without pin support."""
|
||||
mock_device.pins_enabled = pins_enabled
|
||||
|
||||
await setup_media_player(hass, mock_config_entry)
|
||||
mock_device.invoke_pin.side_effect = OpenhomeConnectionError("no route to host")
|
||||
|
||||
with pytest.raises(HomeAssistantError) as err:
|
||||
await hass.services.async_call(
|
||||
@@ -282,5 +329,78 @@ async def test_invoke_pin_without_pin_support(
|
||||
)
|
||||
|
||||
assert err.value.translation_domain == DOMAIN
|
||||
assert err.value.translation_key == "pins_not_supported"
|
||||
mock_device.invoke_pin.assert_not_awaited()
|
||||
assert err.value.translation_key == translation_key
|
||||
assert mock_device.invoke_pin.await_count == await_count
|
||||
|
||||
|
||||
async def test_media_player(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_device: MagicMock,
|
||||
entity_registry: er.EntityRegistry,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test the media player is set up from the device state."""
|
||||
mock_device.track_info.return_value = TRACK_INFO
|
||||
|
||||
await setup_media_player(hass, mock_config_entry)
|
||||
|
||||
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
|
||||
|
||||
|
||||
async def test_becomes_unavailable_and_recovers(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_device: MagicMock,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test a failed poll logs once, marks the device unavailable and recovers."""
|
||||
await setup_media_player(hass, mock_config_entry)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_PLAYING
|
||||
|
||||
mock_device.room.side_effect = OpenhomeConnectionError("device unreachable")
|
||||
await async_poll(hass)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
|
||||
assert caplog.text.count("device unreachable") == 1
|
||||
|
||||
# A second consecutive failure must not log the same outage again.
|
||||
await async_poll(hass)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
|
||||
assert caplog.text.count("device unreachable") == 1
|
||||
|
||||
mock_device.room.side_effect = None
|
||||
await async_poll(hass)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == STATE_PLAYING
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("in_standby", "transport_state", "expected_state"),
|
||||
[
|
||||
pytest.param(True, "Playing", STATE_OFF, id="standby"),
|
||||
pytest.param(False, "Paused", STATE_PAUSED, id="paused"),
|
||||
pytest.param(False, "Playing", STATE_PLAYING, id="playing"),
|
||||
pytest.param(False, "Buffering", STATE_PLAYING, id="buffering"),
|
||||
pytest.param(False, "Stopped", STATE_IDLE, id="stopped"),
|
||||
# An external source with no transport controls still counts as playing.
|
||||
pytest.param(False, "Unknown", STATE_PLAYING, id="external_source"),
|
||||
],
|
||||
)
|
||||
async def test_state_mapping(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_device: MagicMock,
|
||||
in_standby: bool,
|
||||
transport_state: str,
|
||||
expected_state: str,
|
||||
) -> None:
|
||||
"""Test the device transport state maps onto the media player state."""
|
||||
mock_device.is_in_standby.return_value = in_standby
|
||||
mock_device.transport_state.return_value = transport_state
|
||||
|
||||
await setup_media_player(hass, mock_config_entry)
|
||||
|
||||
assert hass.states.get(ENTITY_ID).state == expected_state
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""Tests for the Openhome update platform."""
|
||||
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from openhomedevice.exceptions import OpenhomeConnectionError
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.openhome.const import DOMAIN
|
||||
from homeassistant.components.update import (
|
||||
ATTR_INSTALLED_VERSION,
|
||||
ATTR_LATEST_VERSION,
|
||||
@@ -17,7 +17,6 @@ from homeassistant.components.update import (
|
||||
from homeassistant.const import (
|
||||
ATTR_DEVICE_CLASS,
|
||||
ATTR_ENTITY_ID,
|
||||
CONF_HOST,
|
||||
STATE_ON,
|
||||
STATE_UNKNOWN,
|
||||
Platform,
|
||||
@@ -25,6 +24,8 @@ from homeassistant.const import (
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
from . import setup_integration
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
|
||||
LATEST_FIRMWARE_INSTALLED = {
|
||||
@@ -60,42 +61,24 @@ FIRMWARE_UPDATE_AVAILABLE = {
|
||||
}
|
||||
|
||||
|
||||
async def setup_integration(
|
||||
hass: HomeAssistant,
|
||||
software_status: dict,
|
||||
update_firmware: AsyncMock,
|
||||
ENTITY_ID = "update.friendly_name"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def platforms() -> list[Platform]:
|
||||
"""Only load the update platform."""
|
||||
return [Platform.UPDATE]
|
||||
|
||||
|
||||
async def test_not_supported(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_device: MagicMock
|
||||
) -> None:
|
||||
"""Load an openhome platform with mocked device."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={CONF_HOST: "http://localhost"},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.openhome.PLATFORMS", [Platform.UPDATE]),
|
||||
patch("homeassistant.components.openhome.Device", MagicMock()) as mock_device,
|
||||
):
|
||||
mock_device.return_value.init = AsyncMock()
|
||||
mock_device.return_value.uuid = MagicMock(return_value="uuid")
|
||||
mock_device.return_value.manufacturer = MagicMock(return_value="manufacturer")
|
||||
mock_device.return_value.model_name = MagicMock(return_value="model_name")
|
||||
mock_device.return_value.friendly_name = MagicMock(return_value="friendly_name")
|
||||
mock_device.return_value.software_status = AsyncMock(
|
||||
return_value=software_status
|
||||
)
|
||||
mock_device.return_value.update_firmware = update_firmware
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
|
||||
async def test_not_supported(hass: HomeAssistant) -> None:
|
||||
"""Ensure update entity works if service not supported."""
|
||||
mock_device.software_status.return_value = None
|
||||
|
||||
update_firmware = AsyncMock()
|
||||
await setup_integration(hass, None, update_firmware)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
state = hass.states.get("update.friendly_name")
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
|
||||
assert state
|
||||
assert state.state == STATE_UNKNOWN
|
||||
@@ -104,16 +87,19 @@ async def test_not_supported(hass: HomeAssistant) -> None:
|
||||
assert state.attributes[ATTR_LATEST_VERSION] is None
|
||||
assert state.attributes[ATTR_RELEASE_URL] is None
|
||||
assert state.attributes[ATTR_RELEASE_SUMMARY] is None
|
||||
update_firmware.assert_not_called()
|
||||
mock_device.update_firmware.assert_not_called()
|
||||
|
||||
|
||||
async def test_on_latest_firmware(hass: HomeAssistant) -> None:
|
||||
async def test_on_latest_firmware(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_device: MagicMock
|
||||
) -> None:
|
||||
"""Test device on latest firmware."""
|
||||
|
||||
update_firmware = AsyncMock()
|
||||
await setup_integration(hass, LATEST_FIRMWARE_INSTALLED, update_firmware)
|
||||
mock_device.software_status.return_value = LATEST_FIRMWARE_INSTALLED
|
||||
|
||||
state = hass.states.get("update.friendly_name")
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
|
||||
assert state
|
||||
assert state.state == STATE_UNKNOWN
|
||||
@@ -122,16 +108,19 @@ async def test_on_latest_firmware(hass: HomeAssistant) -> None:
|
||||
assert state.attributes[ATTR_LATEST_VERSION] is None
|
||||
assert state.attributes[ATTR_RELEASE_URL] is None
|
||||
assert state.attributes[ATTR_RELEASE_SUMMARY] is None
|
||||
update_firmware.assert_not_called()
|
||||
mock_device.update_firmware.assert_not_called()
|
||||
|
||||
|
||||
async def test_update_available(hass: HomeAssistant) -> None:
|
||||
async def test_update_available(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_device: MagicMock
|
||||
) -> None:
|
||||
"""Test device has firmware update available."""
|
||||
|
||||
update_firmware = AsyncMock()
|
||||
await setup_integration(hass, FIRMWARE_UPDATE_AVAILABLE, update_firmware)
|
||||
mock_device.software_status.return_value = FIRMWARE_UPDATE_AVAILABLE
|
||||
|
||||
state = hass.states.get("update.friendly_name")
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
state = hass.states.get(ENTITY_ID)
|
||||
|
||||
assert state
|
||||
assert state.state == STATE_ON
|
||||
@@ -150,25 +139,49 @@ async def test_update_available(hass: HomeAssistant) -> None:
|
||||
await hass.services.async_call(
|
||||
UPDATE_DOMAIN,
|
||||
SERVICE_INSTALL,
|
||||
{ATTR_ENTITY_ID: "update.friendly_name"},
|
||||
{ATTR_ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
update_firmware.assert_called_once()
|
||||
mock_device.update_firmware.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_firmware_update_not_required(hass: HomeAssistant) -> None:
|
||||
"""Ensure firmware install does nothing if up to date."""
|
||||
async def test_firmware_update_error(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_device: MagicMock
|
||||
) -> None:
|
||||
"""Ensure a failed firmware install is raised to the user."""
|
||||
mock_device.software_status.return_value = FIRMWARE_UPDATE_AVAILABLE
|
||||
mock_device.update_firmware.side_effect = OpenhomeConnectionError(
|
||||
"no route to host"
|
||||
)
|
||||
|
||||
update_firmware = AsyncMock()
|
||||
await setup_integration(hass, LATEST_FIRMWARE_INSTALLED, update_firmware)
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
with pytest.raises(HomeAssistantError):
|
||||
await hass.services.async_call(
|
||||
UPDATE_DOMAIN,
|
||||
SERVICE_INSTALL,
|
||||
{ATTR_ENTITY_ID: "update.friendly_name"},
|
||||
{ATTR_ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
update_firmware.assert_not_called()
|
||||
mock_device.update_firmware.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_firmware_update_not_required(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_device: MagicMock
|
||||
) -> None:
|
||||
"""Ensure firmware install does nothing if up to date."""
|
||||
|
||||
mock_device.software_status.return_value = LATEST_FIRMWARE_INSTALLED
|
||||
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
|
||||
with pytest.raises(HomeAssistantError):
|
||||
await hass.services.async_call(
|
||||
UPDATE_DOMAIN,
|
||||
SERVICE_INSTALL,
|
||||
{ATTR_ENTITY_ID: ENTITY_ID},
|
||||
blocking=True,
|
||||
)
|
||||
mock_device.update_firmware.assert_not_called()
|
||||
|
||||
Reference in New Issue
Block a user