Move imports in samsungtv component (#27775)

* Move imports in samsungtv component

* Fix tests

* Fix review 1

* Fix review 2

* wakeonlan is a module
This commit is contained in:
Quentame 2019-11-05 15:04:19 +01:00 committed by Martin Hjelmare
parent a43095b2b5
commit 136f1f7fe9
2 changed files with 35 additions and 31 deletions

View File

@ -3,7 +3,9 @@ import asyncio
from datetime import timedelta from datetime import timedelta
import socket import socket
from samsungctl import exceptions as samsung_exceptions, Remote as SamsungRemote
import voluptuous as vol import voluptuous as vol
import wakeonlan
from homeassistant.components.media_player import ( from homeassistant.components.media_player import (
MediaPlayerDevice, MediaPlayerDevice,
@ -113,17 +115,11 @@ class SamsungTVDevice(MediaPlayerDevice):
def __init__(self, host, port, name, timeout, mac, uuid): def __init__(self, host, port, name, timeout, mac, uuid):
"""Initialize the Samsung device.""" """Initialize the Samsung device."""
from samsungctl import exceptions
from samsungctl import Remote
import wakeonlan
# Save a reference to the imported classes # Save a reference to the imported classes
self._exceptions_class = exceptions
self._remote_class = Remote
self._name = name self._name = name
self._mac = mac self._mac = mac
self._uuid = uuid self._uuid = uuid
self._wol = wakeonlan
# Assume that the TV is not muted # Assume that the TV is not muted
self._muted = False self._muted = False
# Assume that the TV is in Play mode # Assume that the TV is in Play mode
@ -163,13 +159,13 @@ class SamsungTVDevice(MediaPlayerDevice):
try: try:
self._config["method"] = method self._config["method"] = method
LOGGER.debug("Try config: %s", self._config) LOGGER.debug("Try config: %s", self._config)
self._remote = self._remote_class(self._config.copy()) self._remote = SamsungRemote(self._config.copy())
self._state = STATE_ON self._state = STATE_ON
LOGGER.debug("Found working config: %s", self._config) LOGGER.debug("Found working config: %s", self._config)
break break
except ( except (
self._exceptions_class.UnhandledResponse, samsung_exceptions.UnhandledResponse,
self._exceptions_class.AccessDenied, samsung_exceptions.AccessDenied,
): ):
# We got a response so it's working. # We got a response so it's working.
self._state = STATE_ON self._state = STATE_ON
@ -189,7 +185,7 @@ class SamsungTVDevice(MediaPlayerDevice):
if self._remote is None: if self._remote is None:
# We need to create a new instance to reconnect. # We need to create a new instance to reconnect.
self._remote = self._remote_class(self._config.copy()) self._remote = SamsungRemote(self._config.copy())
return self._remote return self._remote
@ -205,7 +201,7 @@ class SamsungTVDevice(MediaPlayerDevice):
try: try:
self.get_remote().control(key) self.get_remote().control(key)
break break
except (self._exceptions_class.ConnectionClosed, BrokenPipeError): except (samsung_exceptions.ConnectionClosed, BrokenPipeError):
# BrokenPipe can occur when the commands is sent to fast # BrokenPipe can occur when the commands is sent to fast
self._remote = None self._remote = None
self._state = STATE_ON self._state = STATE_ON
@ -213,8 +209,8 @@ class SamsungTVDevice(MediaPlayerDevice):
# Auto-detect could not find working config yet # Auto-detect could not find working config yet
pass pass
except ( except (
self._exceptions_class.UnhandledResponse, samsung_exceptions.UnhandledResponse,
self._exceptions_class.AccessDenied, samsung_exceptions.AccessDenied,
): ):
# We got a response so it's on. # We got a response so it's on.
self._state = STATE_ON self._state = STATE_ON
@ -343,7 +339,7 @@ class SamsungTVDevice(MediaPlayerDevice):
def turn_on(self): def turn_on(self):
"""Turn the media player on.""" """Turn the media player on."""
if self._mac: if self._mac:
self._wol.send_magic_packet(self._mac) wakeonlan.send_magic_packet(self._mac)
else: else:
self.send_key("KEY_POWERON") self.send_key("KEY_POWERON")

View File

@ -1,12 +1,13 @@
"""Tests for samsungtv Components.""" """Tests for samsungtv component."""
import asyncio import asyncio
from asynctest import mock from unittest.mock import call, patch
from datetime import timedelta from datetime import timedelta
import logging import logging
from asynctest import mock
import pytest import pytest
from samsungctl import exceptions from samsungctl import exceptions
from tests.common import MockDependency, async_fire_time_changed from tests.common import async_fire_time_changed
from unittest.mock import call, patch
from homeassistant.components.media_player import DEVICE_CLASS_TV from homeassistant.components.media_player import DEVICE_CLASS_TV
from homeassistant.components.media_player.const import ( from homeassistant.components.media_player.const import (
@ -62,7 +63,7 @@ MOCK_CONFIG = {
CONF_NAME: "fake", CONF_NAME: "fake",
CONF_PORT: 8001, CONF_PORT: 8001,
CONF_TIMEOUT: 10, CONF_TIMEOUT: 10,
CONF_MAC: "fake", CONF_MAC: "38:f9:d3:82:b4:f1",
} }
} }
@ -125,7 +126,9 @@ AUTODETECT_LEGACY = {
@pytest.fixture(name="remote") @pytest.fixture(name="remote")
def remote_fixture(): def remote_fixture():
"""Patch the samsungctl Remote.""" """Patch the samsungctl Remote."""
with patch("samsungctl.Remote") as remote_class, patch( with patch(
"homeassistant.components.samsungtv.media_player.SamsungRemote"
) as remote_class, patch(
"homeassistant.components.samsungtv.media_player.socket" "homeassistant.components.samsungtv.media_player.socket"
) as socket_class: ) as socket_class:
remote = mock.Mock() remote = mock.Mock()
@ -138,8 +141,10 @@ def remote_fixture():
@pytest.fixture(name="wakeonlan") @pytest.fixture(name="wakeonlan")
def wakeonlan_fixture(): def wakeonlan_fixture():
"""Patch the wakeonlan Remote.""" """Patch the wakeonlan Remote."""
with MockDependency("wakeonlan") as wakeonlan: with patch(
yield wakeonlan "homeassistant.components.samsungtv.media_player.wakeonlan"
) as wakeonlan_module:
yield wakeonlan_module
@pytest.fixture @pytest.fixture
@ -249,9 +254,9 @@ async def test_send_key(hass, remote, wakeonlan):
async def test_send_key_autodetect_websocket(hass, remote): async def test_send_key_autodetect_websocket(hass, remote):
"""Test for send key with autodetection of protocol.""" """Test for send key with autodetection of protocol."""
with patch("samsungctl.Remote") as remote, patch( with patch(
"homeassistant.components.samsungtv.media_player.socket" "homeassistant.components.samsungtv.media_player.SamsungRemote"
): ) as remote, patch("homeassistant.components.samsungtv.media_player.socket"):
await setup_samsungtv(hass, MOCK_CONFIG_AUTO) await setup_samsungtv(hass, MOCK_CONFIG_AUTO)
assert await hass.services.async_call( assert await hass.services.async_call(
DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID_AUTO}, True DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID_AUTO}, True
@ -266,7 +271,8 @@ async def test_send_key_autodetect_websocket_exception(hass, caplog):
"""Test for send key with autodetection of protocol.""" """Test for send key with autodetection of protocol."""
caplog.set_level(logging.DEBUG) caplog.set_level(logging.DEBUG)
with patch( with patch(
"samsungctl.Remote", side_effect=[exceptions.AccessDenied("Boom"), mock.DEFAULT] "homeassistant.components.samsungtv.media_player.SamsungRemote",
side_effect=[exceptions.AccessDenied("Boom"), mock.DEFAULT],
) as remote, patch("homeassistant.components.samsungtv.media_player.socket"): ) as remote, patch("homeassistant.components.samsungtv.media_player.socket"):
await setup_samsungtv(hass, MOCK_CONFIG_AUTO) await setup_samsungtv(hass, MOCK_CONFIG_AUTO)
assert await hass.services.async_call( assert await hass.services.async_call(
@ -287,7 +293,8 @@ async def test_send_key_autodetect_websocket_exception(hass, caplog):
async def test_send_key_autodetect_legacy(hass, remote): async def test_send_key_autodetect_legacy(hass, remote):
"""Test for send key with autodetection of protocol.""" """Test for send key with autodetection of protocol."""
with patch( with patch(
"samsungctl.Remote", side_effect=[OSError("Boom"), mock.DEFAULT] "homeassistant.components.samsungtv.media_player.SamsungRemote",
side_effect=[OSError("Boom"), mock.DEFAULT],
) as remote, patch("homeassistant.components.samsungtv.media_player.socket"): ) as remote, patch("homeassistant.components.samsungtv.media_player.socket"):
await setup_samsungtv(hass, MOCK_CONFIG_AUTO) await setup_samsungtv(hass, MOCK_CONFIG_AUTO)
assert await hass.services.async_call( assert await hass.services.async_call(
@ -304,9 +311,10 @@ async def test_send_key_autodetect_legacy(hass, remote):
async def test_send_key_autodetect_none(hass, remote): async def test_send_key_autodetect_none(hass, remote):
"""Test for send key with autodetection of protocol.""" """Test for send key with autodetection of protocol."""
with patch("samsungctl.Remote", side_effect=OSError("Boom")) as remote, patch( with patch(
"homeassistant.components.samsungtv.media_player.socket" "homeassistant.components.samsungtv.media_player.SamsungRemote",
): side_effect=OSError("Boom"),
) as remote, patch("homeassistant.components.samsungtv.media_player.socket"):
await setup_samsungtv(hass, MOCK_CONFIG_AUTO) await setup_samsungtv(hass, MOCK_CONFIG_AUTO)
assert await hass.services.async_call( assert await hass.services.async_call(
DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID_AUTO}, True DOMAIN, SERVICE_VOLUME_UP, {ATTR_ENTITY_ID: ENTITY_ID_AUTO}, True
@ -557,7 +565,7 @@ async def test_turn_on_with_mac(hass, remote, wakeonlan):
) )
# key and update called # key and update called
assert wakeonlan.send_magic_packet.call_count == 1 assert wakeonlan.send_magic_packet.call_count == 1
assert wakeonlan.send_magic_packet.call_args_list == [call("fake")] assert wakeonlan.send_magic_packet.call_args_list == [call("38:f9:d3:82:b4:f1")]
async def test_turn_on_without_mac(hass, remote): async def test_turn_on_without_mac(hass, remote):