Skip to content

Commit

Permalink
Use config entry setup in cast tests (#93595)
Browse files Browse the repository at this point in the history
* Use config entry setup in cast tests

* Remove import step from config flow

* Remove import tests

* Fix tests
  • Loading branch information
emontnemery committed May 28, 2023
1 parent fad3a4e commit 02b76be
Show file tree
Hide file tree
Showing 7 changed files with 8 additions and 161 deletions.
34 changes: 1 addition & 33 deletions homeassistant/components/cast/__init__.py
Original file line number Diff line number Diff line change
@@ -1,59 +1,27 @@
"""Component to embed Google Cast."""
from __future__ import annotations

import logging
from typing import Protocol

from pychromecast import Chromecast
import voluptuous as vol

from homeassistant.components.media_player import BrowseMedia, MediaType
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv, device_registry as dr
from homeassistant.helpers.integration_platform import (
async_process_integration_platforms,
)
from homeassistant.helpers.typing import ConfigType

from . import home_assistant_cast
from .const import DOMAIN
from .media_player import ENTITY_SCHEMA

CONFIG_SCHEMA = cv.removed(DOMAIN, raise_if_present=False)

_LOGGER = logging.getLogger(__name__)

PLATFORMS = [Platform.MEDIA_PLAYER]


async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the Cast component."""
if (conf := config.get(DOMAIN)) is not None:
media_player_config_validated = []
media_player_config = conf.get("media_player", {})
if not isinstance(media_player_config, list):
media_player_config = [media_player_config]
for cfg in media_player_config:
try:
cfg = ENTITY_SCHEMA(cfg)
media_player_config_validated.append(cfg)
except vol.Error as ex:
_LOGGER.warning("Invalid config '%s': %s", cfg, ex)

hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=media_player_config_validated,
)
)

return True


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Cast from a config entry."""
await home_assistant_cast.async_setup_ha_cast(hass, entry)
Expand Down
15 changes: 0 additions & 15 deletions homeassistant/components/cast/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,21 +38,6 @@ def async_get_options_flow(
"""Get the options flow for this handler."""
return CastOptionsFlowHandler(config_entry)

async def async_step_import(self, import_data=None):
"""Import data."""
if self._async_current_entries():
return self.async_abort(reason="single_instance_allowed")

media_player_config = import_data or []
for cfg in media_player_config:
if CONF_IGNORE_CEC in cfg:
self._ignore_cec.update(set(cfg[CONF_IGNORE_CEC]))
if CONF_UUID in cfg:
self._wanted_uuid.add(cfg[CONF_UUID])

data = self._get_data()
return self.async_create_entry(title="Google Cast", data=data)

async def async_step_user(self, user_input=None):
"""Handle a flow initialized by the user."""
if self._async_current_entries():
Expand Down
11 changes: 0 additions & 11 deletions homeassistant/components/cast/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
CONNECTION_STATUS_CONNECTED,
CONNECTION_STATUS_DISCONNECTED,
)
import voluptuous as vol
import yarl

from homeassistant.components import media_source, zeroconf
Expand All @@ -47,7 +46,6 @@
)
from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
Expand Down Expand Up @@ -83,15 +81,6 @@

CAST_SPLASH = "https://www.home-assistant.io/images/cast/splash.png"

ENTITY_SCHEMA = vol.All(
vol.Schema(
{
vol.Optional(CONF_UUID): cv.string,
vol.Optional(CONF_IGNORE_CEC): vol.All(cv.ensure_list, [cv.string]),
}
),
)


@callback
def _async_create_cast_device(hass: HomeAssistant, info: ChromecastInfo):
Expand Down
3 changes: 2 additions & 1 deletion tests/components/cast/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from unittest.mock import AsyncMock, MagicMock, patch

import pychromecast
from pychromecast.controllers import multizone
import pytest


Expand Down Expand Up @@ -30,7 +31,7 @@ def castbrowser_mock():
@pytest.fixture
def mz_mock():
"""Mock pychromecast MultizoneManager."""
return MagicMock(spec_set=pychromecast.controllers.multizone.MultizoneManager)
return MagicMock(spec_set=multizone.MultizoneManager)


@pytest.fixture
Expand Down
1 change: 0 additions & 1 deletion tests/components/cast/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ async def test_creating_entry_sets_up_media_player(hass: HomeAssistant) -> None:
@pytest.mark.parametrize(
"source",
[
config_entries.SOURCE_IMPORT,
config_entries.SOURCE_USER,
config_entries.SOURCE_ZEROCONF,
],
Expand Down
50 changes: 0 additions & 50 deletions tests/components/cast/test_init.py

This file was deleted.

55 changes: 5 additions & 50 deletions tests/components/cast/test_media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def remove_chromecast(service_name: str, info: ChromecastInfo) -> None:


async def async_setup_media_player_cast(hass: HomeAssistant, info: ChromecastInfo):
"""Set up the cast platform with async_setup_component."""
"""Set up a cast config entry."""
browser = MagicMock(devices={}, zc={})
chromecast = get_fake_chromecast(info)
zconf = get_fake_zconf(host=info.cast_info.host, port=info.cast_info.port)
Expand All @@ -196,9 +196,10 @@ async def async_setup_media_player_cast(hass: HomeAssistant, info: ChromecastInf
"homeassistant.components.cast.discovery.ChromeCastZeroconf.get_zeroconf",
return_value=zconf,
):
await async_setup_component(
hass, "cast", {"cast": {"media_player": {"uuid": info.uuid}}}
)
data = {"ignore_cec": [], "known_hosts": [], "uuid": [str(info.uuid)]}
entry = MockConfigEntry(data=data, domain="cast")
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
await hass.async_block_till_done()

Expand Down Expand Up @@ -2014,52 +2015,6 @@ async def test_entry_setup_no_config(hass: HomeAssistant) -> None:
assert not hass.config_entries.async_entries("cast")


async def test_entry_setup_empty_config(hass: HomeAssistant) -> None:
"""Test deprecated empty yaml config.."""
await async_setup_component(hass, "cast", {"cast": {}})
await hass.async_block_till_done()

config_entry = hass.config_entries.async_entries("cast")[0]
assert config_entry.data["uuid"] == []
assert config_entry.data["ignore_cec"] == []


async def test_entry_setup_single_config(hass: HomeAssistant) -> None:
"""Test deprecated yaml config with a single config media_player."""
await async_setup_component(
hass, "cast", {"cast": {"media_player": {"uuid": "bla", "ignore_cec": "cast1"}}}
)
await hass.async_block_till_done()

config_entry = hass.config_entries.async_entries("cast")[0]
assert config_entry.data["uuid"] == ["bla"]
assert config_entry.data["ignore_cec"] == ["cast1"]

assert ["cast1"] == pychromecast.IGNORE_CEC


async def test_entry_setup_list_config(hass: HomeAssistant) -> None:
"""Test deprecated yaml config with multiple media_players."""
await async_setup_component(
hass,
"cast",
{
"cast": {
"media_player": [
{"uuid": "bla", "ignore_cec": "cast1"},
{"uuid": "blu", "ignore_cec": ["cast2", "cast3"]},
]
}
},
)
await hass.async_block_till_done()

config_entry = hass.config_entries.async_entries("cast")[0]
assert set(config_entry.data["uuid"]) == {"bla", "blu"}
assert set(config_entry.data["ignore_cec"]) == {"cast1", "cast2", "cast3"}
assert set(pychromecast.IGNORE_CEC) == {"cast1", "cast2", "cast3"}


async def test_invalid_cast_platform(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
Expand Down

0 comments on commit 02b76be

Please sign in to comment.