diff --git a/tests/components/braviatv/__init__.py b/tests/components/braviatv/__init__.py index c2d6d8ef37ed..0a753812ee62 100644 --- a/tests/components/braviatv/__init__.py +++ b/tests/components/braviatv/__init__.py @@ -1 +1,15 @@ """Tests for Bravia TV.""" + +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.core import HomeAssistant + + +async def init_integration( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Set up the Bravia TV integration in Home Assistant.""" + mock_config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() diff --git a/tests/components/braviatv/conftest.py b/tests/components/braviatv/conftest.py index 78f4d76c276b..e7a955aa65f6 100644 --- a/tests/components/braviatv/conftest.py +++ b/tests/components/braviatv/conftest.py @@ -1,9 +1,107 @@ """Test fixtures for Bravia TV.""" from collections.abc import Generator +import copy from unittest.mock import AsyncMock, patch import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.components.braviatv.const import CONF_USE_PSK, DOMAIN +from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PIN + +BRAVIA_SYSTEM_INFO = { + "product": "TV", + "region": "XEU", + "language": "pol", + "model": "TV-Model", + "serial": "serial_number", + "macAddr": "AA:BB:CC:DD:EE:FF", + "name": "BRAVIA", + "generation": "5.2.0", + "area": "POL", + "cid": "very_unique_string", +} + +BRAVIA_INPUTS = [ + { + "uri": "extInput:hdmi?port=1", + "title": "HDMI 1", + "connection": True, + "label": "", + "icon": "meta:hdmi", + }, + { + "uri": "extInput:hdmi?port=2", + "title": "HDMI 2", + "connection": False, + "label": "", + "icon": "meta:hdmi", + }, + { + "uri": "extInput:component?port=1", + "title": "AV/Component", + "connection": False, + "label": "", + "icon": "meta:component", + }, +] + +BRAVIA_APPS = [ + { + "title": "YouTube", + "uri": "com.sony.dtv.com.google.android.youtube.tv", + "icon": "http://bravia-host/youtube.png", + }, + { + "title": "Netflix", + "uri": "com.sony.dtv.com.netflix.ninja", + "icon": "http://bravia-host/netflix.png", + }, + { + "title": "Settings", + "uri": "com.sony.dtv.com.android.tv.settings", + "icon": "", + }, +] + +BRAVIA_CHANNELS = [ + { + "uri": "tv:dvbt?trip=1.2.3&srvName=TVP1", + "title": "TVP 1", + "dispNum": "001", + "index": 0, + "programMediaType": "tv", + }, + { + "uri": "tv:dvbt?trip=1.2.4&srvName=TVP2", + "title": "TVP 2", + "dispNum": "002", + "index": 1, + "programMediaType": "tv", + }, + { + "uri": "tv:dvbt?trip=1.2.5&srvName=TVN", + "title": "TVN", + "dispNum": "003", + "index": 2, + "programMediaType": "tv", + }, +] + +BRAVIA_VOLUME_INFO = {"volume": 25, "mute": False, "target": "speaker"} + +BRAVIA_PLAYING_INFO = { + "uri": "extInput:hdmi?port=1", + "source": "extInput:hdmi", + "title": "HDMI 1", +} + +BRAVIA_COMMAND_LIST = { + "Power": "AAAAAQAAAAEAAAAVAw==", + "Num1": "AAAAAQAAAAEAAAAAAw==", + "VolumeUp": "AAAAAQAAAAEAAAASAw==", +} @pytest.fixture(autouse=True) @@ -30,3 +128,54 @@ def mock_setup_entry() -> Generator[AsyncMock]: "homeassistant.components.braviatv.async_setup_entry", return_value=None ) as mock_setup_entry: yield mock_setup_entry + + +@pytest.fixture +def mock_config_entry() -> MockConfigEntry: + """Return the default mocked config entry.""" + return MockConfigEntry( + domain=DOMAIN, + title="BRAVIA TV-Model", + unique_id="very_unique_string", + entry_id="3bd2acb0e4f0476d40865546d0d91921", + minor_version=2, + data={ + CONF_HOST: "bravia-host", + CONF_MAC: "AA:BB:CC:DD:EE:FF", + CONF_PIN: "12345qwerty", + CONF_USE_PSK: True, + }, + ) + + +@pytest.fixture +def mock_braviatv() -> Generator[AsyncMock]: + """Mock the BraviaClient class.""" + with ( + patch( + "homeassistant.components.braviatv.BraviaClient", autospec=True + ) as mock_class, + patch( + "homeassistant.components.braviatv.config_flow.BraviaClient", + new=mock_class, + ), + ): + yield mock_class + + +@pytest.fixture +def mock_braviatv_client(mock_braviatv: AsyncMock) -> AsyncMock: + """Mock a BraviaClient instance.""" + client = mock_braviatv.return_value + client.mac = "AA:BB:CC:DD:EE:FF" + client.get_app_list.return_value = copy.deepcopy(BRAVIA_APPS) + client.get_command_list.return_value = copy.deepcopy(BRAVIA_COMMAND_LIST) + client.get_content_list_all.return_value = copy.deepcopy(BRAVIA_CHANNELS) + client.get_external_status.return_value = copy.deepcopy(BRAVIA_INPUTS) + client.get_playing_info.return_value = copy.deepcopy(BRAVIA_PLAYING_INFO) + client.get_power_status.return_value = "active" + client.get_system_info.return_value = copy.deepcopy(BRAVIA_SYSTEM_INFO) + client.get_volume_info.return_value = copy.deepcopy(BRAVIA_VOLUME_INFO) + client.send_command.return_value = True + + return client diff --git a/tests/components/braviatv/snapshots/test_diagnostics.ambr b/tests/components/braviatv/snapshots/test_diagnostics.ambr index 56ab37a00b8d..2f41c5bcb4d7 100644 --- a/tests/components/braviatv/snapshots/test_diagnostics.ambr +++ b/tests/components/braviatv/snapshots/test_diagnostics.ambr @@ -3,7 +3,7 @@ dict({ 'config_entry': dict({ 'data': dict({ - 'host': 'localhost', + 'host': 'bravia-host', 'mac': '**REDACTED**', 'pin': '**REDACTED**', 'use_psk': True, @@ -37,7 +37,10 @@ 'region': 'XEU', 'serial': 'serial_number', }), - 'remote_command_list': list([ - ]), + 'remote_command_list': dict({ + 'Num1': 'AAAAAQAAAAEAAAAAAw==', + 'Power': 'AAAAAQAAAAEAAAAVAw==', + 'VolumeUp': 'AAAAAQAAAAEAAAASAw==', + }), }) # --- diff --git a/tests/components/braviatv/test_config_flow.py b/tests/components/braviatv/test_config_flow.py index 69d433e05c3b..35f5fedfab7e 100644 --- a/tests/components/braviatv/test_config_flow.py +++ b/tests/components/braviatv/test_config_flow.py @@ -1,6 +1,6 @@ """Define tests for the Bravia TV config flow.""" -from unittest.mock import patch +from unittest.mock import ANY, AsyncMock from pybravia import ( BraviaAuthError, @@ -30,26 +30,7 @@ from homeassistant.helpers.service_info.ssdp import ( SsdpServiceInfo, ) -BRAVIA_SYSTEM_INFO = { - "product": "TV", - "region": "XEU", - "language": "pol", - "model": "TV-Model", - "serial": "serial_number", - "macAddr": "AA:BB:CC:DD:EE:FF", - "name": "BRAVIA", - "generation": "5.2.0", - "area": "POL", - "cid": "very_unique_string", -} - -BRAVIA_SOURCES = [ - {"title": "HDMI 1", "uri": "extInput:hdmi?port=1"}, - {"title": "HDMI 2", "uri": "extInput:hdmi?port=2"}, - {"title": "HDMI 3/ARC", "uri": "extInput:hdmi?port=3"}, - {"title": "HDMI 4", "uri": "extInput:hdmi?port=4"}, - {"title": "AV/Component", "uri": "extInput:component?port=1"}, -] +from .conftest import BRAVIA_SYSTEM_INFO BRAVIA_SSDP = SsdpServiceInfo( ssdp_usn="mock_usn", @@ -89,12 +70,15 @@ FAKE_BRAVIA_SSDP = SsdpServiceInfo( }, ) -pytestmark = pytest.mark.usefixtures("mock_setup_entry") +pytestmark = pytest.mark.usefixtures("mock_setup_entry", "mock_braviatv_client") -async def test_ssdp_discovery(hass: HomeAssistant) -> None: +async def test_ssdp_discovery( + hass: HomeAssistant, mock_braviatv_client: AsyncMock +) -> None: """Test that the device is discovered.""" uuid = await instance_id.async_get(hass) + nickname = f"{NICKNAME_PREFIX} {uuid[:6]}" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, @@ -103,46 +87,41 @@ async def test_ssdp_discovery(hass: HomeAssistant) -> None: assert result["type"] is FlowResultType.FORM assert result["step_id"] == "confirm" - with ( - patch("pybravia.BraviaClient.connect"), - patch("pybravia.BraviaClient.pair"), - patch("pybravia.BraviaClient.set_wol_mode"), - patch( - "pybravia.BraviaClient.get_system_info", - return_value=BRAVIA_SYSTEM_INFO, - ), - ): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={} - ) - await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={} + ) - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "authorize" + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "authorize" - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: False, CONF_USE_SSL: False} - ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: False, CONF_USE_SSL: False} + ) - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "pin" + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "pin" + mock_braviatv_client.pair.assert_called_once_with(uuid, nickname) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "1234"} - ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "1234"} + ) - assert result["type"] is FlowResultType.CREATE_ENTRY - assert result["result"].unique_id == "very_unique_string" - assert result["title"] == "BRAVIA TV-Model" - assert result["data"] == { - CONF_HOST: "bravia-host", - CONF_PIN: "1234", - CONF_USE_PSK: False, - CONF_USE_SSL: False, - CONF_MAC: "AA:BB:CC:DD:EE:FF", - CONF_CLIENT_ID: uuid, - CONF_NICKNAME: f"{NICKNAME_PREFIX} {uuid[:6]}", - } + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "very_unique_string" + assert result["title"] == "BRAVIA TV-Model" + assert result["data"] == { + CONF_HOST: "bravia-host", + CONF_PIN: "1234", + CONF_USE_PSK: False, + CONF_USE_SSL: False, + CONF_MAC: "AA:BB:CC:DD:EE:FF", + CONF_CLIENT_ID: uuid, + CONF_NICKNAME: nickname, + } + mock_braviatv_client.connect.assert_called_once_with( + pin="1234", clientid=uuid, nickname=nickname + ) + mock_braviatv_client.set_wol_mode.assert_called_once_with(True) async def test_ssdp_discovery_fake(hass: HomeAssistant) -> None: @@ -157,19 +136,11 @@ async def test_ssdp_discovery_fake(hass: HomeAssistant) -> None: assert result["reason"] == "not_bravia_device" -async def test_ssdp_discovery_exist(hass: HomeAssistant) -> None: +async def test_ssdp_discovery_exist( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: """Test that the existed device is not discovered.""" - config_entry = MockConfigEntry( - domain=DOMAIN, - unique_id="very_unique_string", - data={ - CONF_HOST: "bravia-host", - CONF_PIN: "1234", - CONF_MAC: "AA:BB:CC:DD:EE:FF", - }, - title="TV-Model", - ) - config_entry.add_to_hass(hass) + mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, @@ -196,80 +167,22 @@ async def test_user_invalid_host(hass: HomeAssistant) -> None: assert result["errors"] == {CONF_HOST: "invalid_host"} - with ( - patch("pybravia.BraviaClient.connect"), - patch("pybravia.BraviaClient.pair"), - patch("pybravia.BraviaClient.set_wol_mode"), - patch( - "pybravia.BraviaClient.get_system_info", - return_value=BRAVIA_SYSTEM_INFO, - ), - ): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_HOST: "bravia-host"} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: False, CONF_USE_SSL: False} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "1234"} - ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "bravia-host"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: False, CONF_USE_SSL: False} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "1234"} + ) assert result["type"] is FlowResultType.CREATE_ENTRY @pytest.mark.parametrize( - ("side_effect", "error_message"), - [ - (BraviaAuthError, "invalid_auth"), - (BraviaNotSupported, "unsupported_model"), - (BraviaConnectionError, "cannot_connect"), - ], + ("use_psk", "pin", "pair_calls"), [(False, "1234", 2), (True, "mypsk", 0)] ) -async def test_pin_form_error( - hass: HomeAssistant, side_effect: type[Exception], error_message: str -) -> None: - """Test that PIN form errors are correct.""" - with ( - patch( - "pybravia.BraviaClient.connect", - side_effect=side_effect, - ) as mock_connect, - patch("pybravia.BraviaClient.pair"), - ): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER} - ) - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "user" - - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_HOST: "bravia-host"} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: False} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "1234"} - ) - - assert result["errors"] == {"base": error_message} - - mock_connect.side_effect = None - with ( - patch("pybravia.BraviaClient.set_wol_mode"), - patch( - "pybravia.BraviaClient.get_system_info", - return_value=BRAVIA_SYSTEM_INFO, - ), - ): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "1234"} - ) - - assert result["type"] is FlowResultType.CREATE_ENTRY - - @pytest.mark.parametrize( ("side_effect", "error_message"), [ @@ -278,225 +191,274 @@ async def test_pin_form_error( (BraviaConnectionError, "cannot_connect"), ], ) -async def test_psk_form_error( - hass: HomeAssistant, side_effect: type[Exception], error_message: str +async def test_form_error( + hass: HomeAssistant, + mock_braviatv_client: AsyncMock, + use_psk: bool, + pin: str, + pair_calls: int, + side_effect: type[Exception], + error_message: str, ) -> None: - """Test that PSK form errors are correct.""" - with patch( - "pybravia.BraviaClient.connect", - side_effect=side_effect, - ) as mock_connect: - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER} - ) - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "user" + """Test that PIN and PSK form errors are correct.""" + mock_braviatv_client.connect.side_effect = side_effect - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_HOST: "bravia-host"} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: True} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "mypsk"} - ) - - assert result["errors"] == {"base": error_message} - - mock_connect.side_effect = None - with ( - patch("pybravia.BraviaClient.set_wol_mode"), - patch( - "pybravia.BraviaClient.get_system_info", - return_value=BRAVIA_SYSTEM_INFO, - ), - ): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "mypsk"} - ) - - assert result["type"] is FlowResultType.CREATE_ENTRY - - -async def test_no_ip_control(hass: HomeAssistant) -> None: - """Test that error are shown when IP Control is disabled on the TV.""" - with patch("pybravia.BraviaClient.pair", side_effect=BraviaError): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER} - ) - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "user" - - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_HOST: "bravia-host"} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: False} - ) - - assert result["type"] is FlowResultType.ABORT - assert result["reason"] == "no_ip_control" - - -async def test_duplicate_error(hass: HomeAssistant) -> None: - """Test that error are shown when duplicates are added.""" - config_entry = MockConfigEntry( - domain=DOMAIN, - unique_id="very_unique_string", - data={ - CONF_HOST: "bravia-host", - CONF_PIN: "1234", - CONF_MAC: "AA:BB:CC:DD:EE:FF", - }, - title="TV-Model", + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} ) - config_entry.add_to_hass(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" - with ( - patch("pybravia.BraviaClient.connect"), - patch("pybravia.BraviaClient.pair"), - patch("pybravia.BraviaClient.set_wol_mode"), - patch( - "pybravia.BraviaClient.get_system_info", - return_value=BRAVIA_SYSTEM_INFO, - ), - ): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER} - ) - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "user" + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "bravia-host"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: use_psk} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: pin} + ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_HOST: "bravia-host"} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: False} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "1234"} - ) + assert result["errors"] == {"base": error_message} + assert mock_braviatv_client.pair.call_count == pair_calls - assert result["type"] is FlowResultType.ABORT - assert result["reason"] == "already_configured" + mock_braviatv_client.connect.side_effect = None + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: pin} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"][CONF_PIN] == pin + assert mock_braviatv_client.connect.call_count == 2 -@pytest.mark.parametrize( - ("use_psk", "use_ssl"), - [ - (True, False), - (False, False), - (True, True), - (False, True), - ], -) -async def test_create_entry(hass: HomeAssistant, use_psk, use_ssl) -> None: - """Test that entry is added correctly.""" +async def test_no_ip_control( + hass: HomeAssistant, mock_braviatv_client: AsyncMock +) -> None: + """Test that error are shown when IP Control is disabled on the TV.""" + mock_braviatv_client.pair.side_effect = BraviaError + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "bravia-host"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: False} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "no_ip_control" + + +async def test_duplicate_error( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test that error are shown when duplicates are added.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "bravia-host"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: False} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "1234"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +@pytest.mark.parametrize("use_ssl", [True, False]) +async def test_create_entry_psk( + hass: HomeAssistant, + mock_braviatv: AsyncMock, + mock_braviatv_client: AsyncMock, + use_ssl: bool, +) -> None: + """Test that entry is added correctly with a PSK.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "bravia-host"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "authorize" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: True, CONF_USE_SSL: use_ssl} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "psk" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "secret"} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "very_unique_string" + assert result["title"] == "BRAVIA TV-Model" + assert result["data"] == { + CONF_HOST: "bravia-host", + CONF_PIN: "secret", + CONF_USE_PSK: True, + CONF_USE_SSL: use_ssl, + CONF_MAC: "AA:BB:CC:DD:EE:FF", + } + mock_braviatv_client.pair.assert_not_called() + mock_braviatv_client.connect.assert_called_once_with(psk="secret") + mock_braviatv.assert_called_once_with(host="bravia-host", session=ANY, ssl=use_ssl) + mock_braviatv_client.set_wol_mode.assert_called_once_with(True) + + +@pytest.mark.parametrize("use_ssl", [True, False]) +async def test_create_entry_pin( + hass: HomeAssistant, + mock_braviatv: AsyncMock, + mock_braviatv_client: AsyncMock, + use_ssl: bool, +) -> None: + """Test that entry is added correctly with a PIN.""" uuid = await instance_id.async_get(hass) + nickname = f"{NICKNAME_PREFIX} {uuid[:6]}" - with ( - patch("pybravia.BraviaClient.connect"), - patch("pybravia.BraviaClient.pair"), - patch("pybravia.BraviaClient.set_wol_mode"), - patch( - "pybravia.BraviaClient.get_system_info", - return_value=BRAVIA_SYSTEM_INFO, - ), - ): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER} - ) - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "user" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_HOST: "bravia-host"} - ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "bravia-host"} + ) - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "authorize" + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "authorize" - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: use_psk, CONF_USE_SSL: use_ssl} - ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: False, CONF_USE_SSL: use_ssl} + ) - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "psk" if use_psk else "pin" + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "pin" + mock_braviatv_client.pair.assert_called_once_with(uuid, nickname) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "secret"} - ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "secret"} + ) - assert result["type"] is FlowResultType.CREATE_ENTRY - assert result["result"].unique_id == "very_unique_string" - assert result["title"] == "BRAVIA TV-Model" - assert result["data"] == { - CONF_HOST: "bravia-host", - CONF_PIN: "secret", - CONF_USE_PSK: use_psk, - CONF_USE_SSL: use_ssl, - CONF_MAC: "AA:BB:CC:DD:EE:FF", - **( - { - CONF_CLIENT_ID: uuid, - CONF_NICKNAME: f"{NICKNAME_PREFIX} {uuid[:6]}", - } - if not use_psk - else {} - ), - } + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "very_unique_string" + assert result["title"] == "BRAVIA TV-Model" + assert result["data"] == { + CONF_HOST: "bravia-host", + CONF_PIN: "secret", + CONF_USE_PSK: False, + CONF_USE_SSL: use_ssl, + CONF_MAC: "AA:BB:CC:DD:EE:FF", + CONF_CLIENT_ID: uuid, + CONF_NICKNAME: nickname, + } + mock_braviatv_client.connect.assert_called_once_with( + pin="secret", clientid=uuid, nickname=nickname + ) + mock_braviatv.assert_called_once_with(host="bravia-host", session=ANY, ssl=use_ssl) + mock_braviatv_client.set_wol_mode.assert_called_once_with(True) -@pytest.mark.parametrize( - ("use_psk", "new_pin"), - [ - (True, "7777"), - (False, "newpsk"), - ], -) -async def test_reauth_successful(hass: HomeAssistant, use_psk, new_pin) -> None: - """Test that the reauthorization is successful.""" +async def test_reauth_successful_psk( + hass: HomeAssistant, + mock_braviatv_client: AsyncMock, +) -> None: + """Test that the reauthorization of a legacy PIN entry with a PSK is successful.""" config_entry = MockConfigEntry( domain=DOMAIN, + title="BRAVIA TV-Model", unique_id="very_unique_string", data={ CONF_HOST: "bravia-host", - CONF_PIN: "1234", CONF_MAC: "AA:BB:CC:DD:EE:FF", + CONF_PIN: "1234", }, - title="TV-Model", ) config_entry.add_to_hass(hass) result = await config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "authorize" - with ( - patch("pybravia.BraviaClient.connect"), - patch( - "pybravia.BraviaClient.get_power_status", - return_value="active", - ), - patch( - "pybravia.BraviaClient.get_external_status", - return_value=BRAVIA_SOURCES, - ), - patch( - "pybravia.BraviaClient.send_rest_req", - return_value={}, - ), - ): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: use_psk} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: new_pin} - ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: True} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "newpsk"} + ) - assert result["type"] is FlowResultType.ABORT - assert result["reason"] == "reauth_successful" - assert config_entry.data[CONF_PIN] == new_pin + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert config_entry.data == { + CONF_HOST: "bravia-host", + CONF_MAC: "AA:BB:CC:DD:EE:FF", + CONF_PIN: "newpsk", + CONF_USE_PSK: True, + CONF_USE_SSL: False, + } + mock_braviatv_client.connect.assert_called_once_with(psk="newpsk") + mock_braviatv_client.set_wol_mode.assert_called_once_with(True) + + +async def test_reauth_successful_pin( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_braviatv_client: AsyncMock, +) -> None: + """Test that the reauthorization with a PIN is successful.""" + uuid = await instance_id.async_get(hass) + mock_config_entry.add_to_hass(hass) + result = await mock_config_entry.start_reauth_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "authorize" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: False} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "7777"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data == { + CONF_HOST: "bravia-host", + CONF_MAC: "AA:BB:CC:DD:EE:FF", + CONF_PIN: "7777", + CONF_USE_PSK: False, + CONF_USE_SSL: False, + CONF_CLIENT_ID: uuid, + CONF_NICKNAME: f"{NICKNAME_PREFIX} {uuid[:6]}", + } + mock_braviatv_client.connect.assert_called_once_with( + pin="7777", clientid=uuid, nickname=f"{NICKNAME_PREFIX} {uuid[:6]}" + ) + mock_braviatv_client.set_wol_mode.assert_called_once_with(True) @pytest.mark.parametrize("use_psk", [True, False]) @@ -510,52 +472,39 @@ async def test_reauth_successful(hass: HomeAssistant, use_psk, new_pin) -> None: ) async def test_reauth_error( hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_braviatv_client: AsyncMock, use_psk: bool, side_effect: type[Exception], error_message: str, ) -> None: """Test that the reauthorization recovers from errors.""" - config_entry = MockConfigEntry( - domain=DOMAIN, - unique_id="very_unique_string", - data={ - CONF_HOST: "bravia-host", - CONF_PIN: "1234", - CONF_MAC: "AA:BB:CC:DD:EE:FF", - }, - title="TV-Model", - ) - config_entry.add_to_hass(hass) - result = await config_entry.start_reauth_flow(hass) + mock_config_entry.add_to_hass(hass) + result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "authorize" - with ( - patch( - "pybravia.BraviaClient.connect", - side_effect=side_effect, - ) as mock_connect, - patch("pybravia.BraviaClient.pair"), - patch("pybravia.BraviaClient.set_wol_mode"), - ): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: use_psk, CONF_USE_SSL: False} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "wrong"} - ) + mock_braviatv_client.connect.side_effect = side_effect - assert result["type"] is FlowResultType.FORM - assert result["errors"] == {"base": error_message} + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: use_psk, CONF_USE_SSL: False} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "wrong"} + ) - mock_connect.side_effect = None - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "7777"} - ) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": error_message} + + mock_braviatv_client.connect.side_effect = None + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "7777"} + ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" - assert config_entry.data[CONF_PIN] == "7777" + assert mock_config_entry.data[CONF_PIN] == "7777" @pytest.mark.parametrize( @@ -595,6 +544,7 @@ async def test_reauth_error( ) async def test_user_flow_with_empty_cid( hass: HomeAssistant, + mock_braviatv_client: AsyncMock, existing_unique_id: str, existing_mac: str, disabled_by: ConfigEntryDisabler | None, @@ -608,29 +558,23 @@ async def test_user_flow_with_empty_cid( data={CONF_HOST: "other-host", CONF_MAC: existing_mac}, disabled_by=disabled_by, ).add_to_hass(hass) + mock_braviatv_client.get_system_info.return_value = { + **BRAVIA_SYSTEM_INFO, + "cid": "", + } - with ( - patch("pybravia.BraviaClient.connect"), - patch("pybravia.BraviaClient.pair"), - patch("pybravia.BraviaClient.set_wol_mode"), - patch( - "pybravia.BraviaClient.get_system_info", - return_value=BRAVIA_SYSTEM_INFO - | {"cid": "", "macAddr": "AA:BB:CC:DD:EE:FF"}, - ), - ): - result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": SOURCE_USER} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_HOST: "bravia-host"} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_USE_PSK: True, CONF_USE_SSL: False} - ) - result = await hass.config_entries.flow.async_configure( - result["flow_id"], user_input={CONF_PIN: "secret"} - ) + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "bravia-host"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: True, CONF_USE_SSL: False} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "secret"} + ) assert result["type"] is expected_type assert ( diff --git a/tests/components/braviatv/test_coordinator.py b/tests/components/braviatv/test_coordinator.py index 4bbee869ae21..34fc4ab407f1 100644 --- a/tests/components/braviatv/test_coordinator.py +++ b/tests/components/braviatv/test_coordinator.py @@ -6,10 +6,9 @@ from unittest.mock import AsyncMock import pytest from pytest_homeassistant.common import MockConfigEntry -from homeassistant.components.braviatv.const import CONF_USE_PSK, DOMAIN, SourceType +from homeassistant.components.braviatv.const import SourceType from homeassistant.components.braviatv.coordinator import BraviaTVCoordinator from homeassistant.components.media_player import MediaType -from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PIN from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError @@ -24,22 +23,16 @@ from homeassistant.exceptions import ServiceValidationError @pytest.mark.freeze_time("2026-08-22T12:00:00+00:00") async def test_async_update_playing( hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_braviatv_client: AsyncMock, start_datetime: str, ) -> None: """Test updating playing info with a start datetime.""" await hass.config.async_set_time_zone("Europe/Warsaw") - config_entry = MockConfigEntry( - domain=DOMAIN, - data={ - CONF_HOST: "localhost", - CONF_MAC: "AA:BB:CC:DD:EE:FF", - CONF_USE_PSK: True, - CONF_PIN: "12345qwerty", - }, - ) - client = AsyncMock() - client.get_playing_info.return_value = {"startDateTime": start_datetime} - coordinator = BraviaTVCoordinator(hass, config_entry, client) + mock_braviatv_client.get_playing_info.return_value = { + "startDateTime": start_datetime + } + coordinator = BraviaTVCoordinator(hass, mock_config_entry, mock_braviatv_client) await coordinator.async_update_playing() @@ -49,19 +42,13 @@ async def test_async_update_playing( ) -async def test_async_source_find_not_found(hass: HomeAssistant) -> None: +async def test_async_source_find_not_found( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_braviatv_client: AsyncMock, +) -> None: """Test finding a source that does not exist raises a validation error.""" - config_entry = MockConfigEntry( - domain=DOMAIN, - data={ - CONF_HOST: "localhost", - CONF_MAC: "AA:BB:CC:DD:EE:FF", - CONF_USE_PSK: True, - CONF_PIN: "12345qwerty", - }, - ) - client = AsyncMock() - coordinator = BraviaTVCoordinator(hass, config_entry, client) + coordinator = BraviaTVCoordinator(hass, mock_config_entry, mock_braviatv_client) coordinator.source_map = { "extInput:hdmi?port=1": { "uri": "extInput:hdmi?port=1", @@ -75,58 +62,46 @@ async def test_async_source_find_not_found(hass: HomeAssistant) -> None: assert exc_info.value.translation_key == "source_not_found" assert exc_info.value.translation_placeholders == { - "device": "Mock Title", + "device": "BRAVIA TV-Model", "source_type": "input", "query": "HDMI 9", } - client.set_play_content.assert_not_called() + mock_braviatv_client.set_play_content.assert_not_called() -async def test_async_play_media_invalid_media_type(hass: HomeAssistant) -> None: +async def test_async_play_media_invalid_media_type( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_braviatv_client: AsyncMock, +) -> None: """Test playing an unsupported media type raises a validation error.""" - config_entry = MockConfigEntry( - domain=DOMAIN, - data={ - CONF_HOST: "localhost", - CONF_MAC: "AA:BB:CC:DD:EE:FF", - CONF_USE_PSK: True, - CONF_PIN: "12345qwerty", - }, - ) - client = AsyncMock() - coordinator = BraviaTVCoordinator(hass, config_entry, client) + coordinator = BraviaTVCoordinator(hass, mock_config_entry, mock_braviatv_client) with pytest.raises(ServiceValidationError) as exc_info: await coordinator.async_play_media(MediaType.MUSIC, "something") assert exc_info.value.translation_key == "invalid_media_type" assert exc_info.value.translation_placeholders == { - "device": "Mock Title", + "device": "BRAVIA TV-Model", "media_type": "music", } -async def test_async_send_command_unsupported(hass: HomeAssistant) -> None: +async def test_async_send_command_unsupported( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_braviatv_client: AsyncMock, +) -> None: """Test sending an unsupported command raises a validation error.""" - config_entry = MockConfigEntry( - domain=DOMAIN, - data={ - CONF_HOST: "localhost", - CONF_MAC: "AA:BB:CC:DD:EE:FF", - CONF_USE_PSK: True, - CONF_PIN: "12345qwerty", - }, - ) - client = AsyncMock() - client.send_command.return_value = False - coordinator = BraviaTVCoordinator(hass, config_entry, client) + mock_braviatv_client.send_command.return_value = False + coordinator = BraviaTVCoordinator(hass, mock_config_entry, mock_braviatv_client) with pytest.raises(ServiceValidationError) as exc_info: await coordinator.async_send_command(["Foo", "Bar"], 2) assert exc_info.value.translation_key == "unsupported_command" assert exc_info.value.translation_placeholders == { - "device": "Mock Title", + "device": "BRAVIA TV-Model", "command": "Foo", } - client.send_command.assert_called_once_with("Foo") + mock_braviatv_client.send_command.assert_called_once_with("Foo") diff --git a/tests/components/braviatv/test_diagnostics.py b/tests/components/braviatv/test_diagnostics.py index 96644a52999d..ff39bae9ec3f 100644 --- a/tests/components/braviatv/test_diagnostics.py +++ b/tests/components/braviatv/test_diagnostics.py @@ -1,76 +1,29 @@ """Test the BraviaTV diagnostics.""" -from unittest.mock import patch - +import pytest from pytest_homeassistant.common import MockConfigEntry from pytest_homeassistant.components.diagnostics import get_diagnostics_for_config_entry from pytest_homeassistant.typing import ClientSessionGenerator from syrupy.assertion import SnapshotAssertion from syrupy.filters import props -from homeassistant.components.braviatv.const import CONF_USE_PSK, DOMAIN -from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PIN from homeassistant.core import HomeAssistant -from homeassistant.setup import async_setup_component -BRAVIA_SYSTEM_INFO = { - "product": "TV", - "region": "XEU", - "language": "pol", - "model": "TV-Model", - "serial": "serial_number", - "macAddr": "AA:BB:CC:DD:EE:FF", - "name": "BRAVIA", - "generation": "5.2.0", - "area": "POL", - "cid": "very_unique_string", -} -INPUTS = [ - { - "uri": "extInput:hdmi?port=1", - "title": "HDMI 1", - "connection": False, - "label": "", - "icon": "meta:hdmi", - } -] +from . import init_integration +@pytest.mark.usefixtures("mock_braviatv_client") async def test_entry_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, + mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test config entry diagnostics.""" + await init_integration(hass, mock_config_entry) - config_entry = MockConfigEntry( - domain=DOMAIN, - title="BRAVIA TV-Model", - data={ - CONF_HOST: "localhost", - CONF_MAC: "AA:BB:CC:DD:EE:FF", - CONF_USE_PSK: True, - CONF_PIN: "12345qwerty", - }, - unique_id="very_unique_string", - entry_id="3bd2acb0e4f0476d40865546d0d91921", + result = await get_diagnostics_for_config_entry( + hass, hass_client, mock_config_entry ) - config_entry.add_to_hass(hass) - with ( - patch("pybravia.BraviaClient.connect"), - patch("pybravia.BraviaClient.pair"), - patch("pybravia.BraviaClient.set_wol_mode"), - patch("pybravia.BraviaClient.get_system_info", return_value=BRAVIA_SYSTEM_INFO), - patch("pybravia.BraviaClient.get_power_status", return_value="active"), - patch("pybravia.BraviaClient.get_external_status", return_value=INPUTS), - patch("pybravia.BraviaClient.get_volume_info", return_value={}), - patch("pybravia.BraviaClient.get_playing_info", return_value={}), - patch("pybravia.BraviaClient.get_app_list", return_value=[]), - patch("pybravia.BraviaClient.get_content_list_all", return_value=[]), - patch("pybravia.BraviaClient.get_command_list", return_value=[]), - ): - assert await async_setup_component(hass, DOMAIN, {}) - result = await get_diagnostics_for_config_entry(hass, hass_client, config_entry) - assert result == snapshot(exclude=props("created_at", "modified_at")) diff --git a/tests/components/braviatv/test_init.py b/tests/components/braviatv/test_init.py index 43e21299f9d7..3e900364be69 100644 --- a/tests/components/braviatv/test_init.py +++ b/tests/components/braviatv/test_init.py @@ -1,7 +1,5 @@ """Test the Bravia TV integration setup.""" -from unittest.mock import patch - import pytest from pytest_homeassistant.common import MockConfigEntry @@ -18,17 +16,13 @@ ENTRY_DATA = { } +@pytest.mark.usefixtures("mock_braviatv_client") @pytest.mark.parametrize( ("unique_id", "mac", "expected_unique_id"), [ - pytest.param("", "AA:BB:CC:DD:EE:FF", "aa:bb:cc:dd:ee:ff", id="empty_cid"), - pytest.param( - "very_unique_string", - "AA:BB:CC:DD:EE:FF", - "very_unique_string", - id="existing_cid", - ), - pytest.param("", "", "", id="empty_cid_and_mac"), + ("", "AA:BB:CC:DD:EE:FF", "aa:bb:cc:dd:ee:ff"), + ("very_unique_string", "AA:BB:CC:DD:EE:FF", "very_unique_string"), + ("", "", ""), ], ) async def test_migrate_unique_id( @@ -51,15 +45,8 @@ async def test_migrate_unique_id( "media_player", DOMAIN, unique_id, config_entry=config_entry ) - with ( - patch("homeassistant.components.braviatv.BraviaClient", autospec=True), - patch( - "homeassistant.components.braviatv.coordinator.BraviaTVCoordinator._async_update_data", - return_value=None, - ), - ): - assert await hass.config_entries.async_setup(config_entry.entry_id) - await hass.async_block_till_done() + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() assert config_entry.unique_id == expected_unique_id assert config_entry.minor_version == 2 @@ -69,6 +56,7 @@ async def test_migrate_unique_id( assert migrated_entity.unique_id == expected_unique_id +@pytest.mark.usefixtures("mock_braviatv_client") async def test_migration_keeps_entities_and_device( hass: HomeAssistant, entity_registry: er.EntityRegistry, @@ -90,15 +78,8 @@ async def test_migration_keeps_entities_and_device( "button", DOMAIN, "_reboot", config_entry=config_entry, device_id=device.id ) - with ( - patch("homeassistant.components.braviatv.BraviaClient", autospec=True), - patch( - "homeassistant.components.braviatv.coordinator.BraviaTVCoordinator._async_update_data", - return_value=None, - ), - ): - assert await hass.config_entries.async_setup(config_entry.entry_id) - await hass.async_block_till_done() + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() assert config_entry.unique_id == "aa:bb:cc:dd:ee:ff" assert config_entry.minor_version == 2