Rewrite Plex tests (#27624)

This commit is contained in:
jjlawren 2019-10-13 23:59:25 -05:00 committed by Paulus Schoutsen
parent b37f0ad812
commit cf76f22c89
2 changed files with 217 additions and 218 deletions

View file

@ -1,35 +1,97 @@
"""Mock classes used in tests.""" """Mock classes used in tests."""
from homeassistant.const import CONF_HOST, CONF_PORT
from homeassistant.components.plex.const import CONF_SERVER, CONF_SERVER_IDENTIFIER
MOCK_HOST_1 = "1.2.3.4" MOCK_SERVERS = [
MOCK_PORT_1 = 32400 {
MOCK_HOST_2 = "4.3.2.1" CONF_HOST: "1.2.3.4",
MOCK_PORT_2 = 32400 CONF_PORT: 32400,
CONF_SERVER: "Plex Server 1",
CONF_SERVER_IDENTIFIER: "unique_id_123",
},
{
CONF_HOST: "4.3.2.1",
CONF_PORT: 32400,
CONF_SERVER: "Plex Server 2",
CONF_SERVER_IDENTIFIER: "unique_id_456",
},
]
class MockAvailableServer: # pylint: disable=too-few-public-methods class MockResource:
"""Mock avilable server objects.""" """Mock a PlexAccount resource."""
def __init__(self, name, client_id): def __init__(self, index):
"""Initialize the object.""" """Initialize the object."""
self.name = name self.name = MOCK_SERVERS[index][CONF_SERVER]
self.clientIdentifier = client_id # pylint: disable=invalid-name self.clientIdentifier = MOCK_SERVERS[index][ # pylint: disable=invalid-name
CONF_SERVER_IDENTIFIER
]
self.provides = ["server"] self.provides = ["server"]
self._mock_plex_server = MockPlexServer(index)
self._connections = []
for connection in range(2):
self._connections.append(MockConnection(connection))
@property
def connections(self):
"""Mock the resource connection listing method."""
return self._connections
def connect(self):
"""Mock the resource connect method."""
return self._mock_plex_server
class MockConnection: # pylint: disable=too-few-public-methods class MockConnection: # pylint: disable=too-few-public-methods
"""Mock a single account resource connection object.""" """Mock a single account resource connection object."""
def __init__(self, ssl): def __init__(self, index, ssl=True):
"""Initialize the object.""" """Initialize the object."""
prefix = "https" if ssl else "http" prefix = "https" if ssl else "http"
self.httpuri = f"{prefix}://{MOCK_HOST_1}:{MOCK_PORT_1}" self.httpuri = (
self.uri = "{prefix}://{MOCK_HOST_2}:{MOCK_PORT_2}" f"http://{MOCK_SERVERS[index][CONF_HOST]}:{MOCK_SERVERS[index][CONF_PORT]}"
self.local = True )
self.uri = f"{prefix}://{MOCK_SERVERS[index][CONF_HOST]}:{MOCK_SERVERS[index][CONF_PORT]}"
# Only first server is local
self.local = not bool(index)
class MockConnections: # pylint: disable=too-few-public-methods class MockPlexAccount:
"""Mock a list of resource connections.""" """Mock a PlexAccount instance."""
def __init__(self, ssl=False): def __init__(self, servers=1):
"""Initialize the object.""" """Initialize the object."""
self.connections = [MockConnection(ssl)] self._resources = []
for index in range(servers):
self._resources.append(MockResource(index))
def resource(self, name):
"""Mock the PlexAccount resource lookup method."""
return [x for x in self._resources if x.name == name][0]
def resources(self):
"""Mock the PlexAccount resources listing method."""
return self._resources
class MockPlexServer:
"""Mock a PlexServer instance."""
def __init__(self, index=0, ssl=True):
"""Initialize the object."""
host = MOCK_SERVERS[index][CONF_HOST]
port = MOCK_SERVERS[index][CONF_PORT]
self.friendlyName = MOCK_SERVERS[index][ # pylint: disable=invalid-name
CONF_SERVER
]
self.machineIdentifier = MOCK_SERVERS[index][ # pylint: disable=invalid-name
CONF_SERVER_IDENTIFIER
]
prefix = "https" if ssl else "http"
self._baseurl = f"{prefix}://{host}:{port}"
@property
def url_in_use(self):
"""Return URL used by PlexServer."""
return self._baseurl

View file

@ -1,28 +1,26 @@
"""Tests for Plex config flow.""" """Tests for Plex config flow."""
from unittest.mock import MagicMock, Mock, patch, PropertyMock from unittest.mock import patch
import asynctest import asynctest
import plexapi.exceptions import plexapi.exceptions
import requests.exceptions import requests.exceptions
from homeassistant.components.plex import config_flow from homeassistant.components.plex import config_flow
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TOKEN, CONF_URL from homeassistant.const import CONF_HOST, CONF_PORT, CONF_SSL, CONF_TOKEN, CONF_URL
from homeassistant.setup import async_setup_component from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry from tests.common import MockConfigEntry
from .mock_classes import MOCK_HOST_1, MOCK_PORT_1, MockAvailableServer, MockConnections from .mock_classes import MOCK_SERVERS, MockPlexAccount, MockPlexServer
MOCK_NAME_1 = "Plex Server 1"
MOCK_ID_1 = "unique_id_123"
MOCK_NAME_2 = "Plex Server 2"
MOCK_ID_2 = "unique_id_456"
MOCK_TOKEN = "secret_token" MOCK_TOKEN = "secret_token"
MOCK_FILE_CONTENTS = { MOCK_FILE_CONTENTS = {
f"{MOCK_HOST_1}:{MOCK_PORT_1}": {"ssl": False, "token": MOCK_TOKEN, "verify": True} f"{MOCK_SERVERS[0][CONF_HOST]}:{MOCK_SERVERS[0][CONF_PORT]}": {
"ssl": False,
"token": MOCK_TOKEN,
"verify": True,
}
} }
MOCK_SERVER_1 = MockAvailableServer(MOCK_NAME_1, MOCK_ID_1)
MOCK_SERVER_2 = MockAvailableServer(MOCK_NAME_2, MOCK_ID_2)
DEFAULT_OPTIONS = { DEFAULT_OPTIONS = {
config_flow.MP_DOMAIN: { config_flow.MP_DOMAIN: {
@ -41,16 +39,7 @@ def init_config_flow(hass):
async def test_bad_credentials(hass): async def test_bad_credentials(hass):
"""Test when provided credentials are rejected.""" """Test when provided credentials are rejected."""
mock_connections = MockConnections()
mm_plex_account = MagicMock()
mm_plex_account.resources = Mock(return_value=[MOCK_SERVER_1])
mm_plex_account.resource = Mock(return_value=mock_connections)
with patch("plexapi.myplex.MyPlexAccount", return_value=mm_plex_account), patch(
"plexapi.server.PlexServer", side_effect=plexapi.exceptions.Unauthorized
), asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value="BAD TOKEN"
):
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN, context={"source": "user"} config_flow.DOMAIN, context={"source": "user"}
) )
@ -60,6 +49,11 @@ async def test_bad_credentials(hass):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external" assert result["type"] == "external"
with patch(
"plexapi.myplex.MyPlexAccount", side_effect=plexapi.exceptions.Unauthorized
), asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value="BAD TOKEN"
):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external_done" assert result["type"] == "external_done"
@ -74,31 +68,32 @@ async def test_import_file_from_discovery(hass):
"""Test importing a legacy file during discovery.""" """Test importing a legacy file during discovery."""
file_host_and_port, file_config = list(MOCK_FILE_CONTENTS.items())[0] file_host_and_port, file_config = list(MOCK_FILE_CONTENTS.items())[0]
used_url = f"http://{file_host_and_port}" file_use_ssl = file_config[CONF_SSL]
file_prefix = "https" if file_use_ssl else "http"
used_url = f"{file_prefix}://{file_host_and_port}"
with patch("plexapi.server.PlexServer") as mock_plex_server, patch( mock_plex_server = MockPlexServer(ssl=file_use_ssl)
with patch("plexapi.server.PlexServer", return_value=mock_plex_server), patch(
"homeassistant.components.plex.config_flow.load_json", "homeassistant.components.plex.config_flow.load_json",
return_value=MOCK_FILE_CONTENTS, return_value=MOCK_FILE_CONTENTS,
): ):
type(mock_plex_server.return_value).machineIdentifier = PropertyMock(
return_value=MOCK_ID_1
)
type(mock_plex_server.return_value).friendlyName = PropertyMock(
return_value=MOCK_NAME_1
)
type( # pylint: disable=protected-access
mock_plex_server.return_value
)._baseurl = PropertyMock(return_value=used_url)
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN, config_flow.DOMAIN,
context={"source": "discovery"}, context={"source": "discovery"},
data={CONF_HOST: MOCK_HOST_1, CONF_PORT: MOCK_PORT_1}, data={
CONF_HOST: MOCK_SERVERS[0][CONF_HOST],
CONF_PORT: MOCK_SERVERS[0][CONF_PORT],
},
) )
assert result["type"] == "create_entry" assert result["type"] == "create_entry"
assert result["title"] == MOCK_NAME_1 assert result["title"] == mock_plex_server.friendlyName
assert result["data"][config_flow.CONF_SERVER] == MOCK_NAME_1 assert result["data"][config_flow.CONF_SERVER] == mock_plex_server.friendlyName
assert result["data"][config_flow.CONF_SERVER_IDENTIFIER] == MOCK_ID_1 assert (
result["data"][config_flow.CONF_SERVER_IDENTIFIER]
== mock_plex_server.machineIdentifier
)
assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL] == used_url assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL] == used_url
assert ( assert (
result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN] result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN]
@ -112,7 +107,10 @@ async def test_discovery(hass):
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN, config_flow.DOMAIN,
context={"source": "discovery"}, context={"source": "discovery"},
data={CONF_HOST: MOCK_HOST_1, CONF_PORT: MOCK_PORT_1}, data={
CONF_HOST: MOCK_SERVERS[0][CONF_HOST],
CONF_PORT: MOCK_SERVERS[0][CONF_PORT],
},
) )
assert result["type"] == "abort" assert result["type"] == "abort"
assert result["reason"] == "discovery_no_file" assert result["reason"] == "discovery_no_file"
@ -128,7 +126,10 @@ async def test_discovery_while_in_progress(hass):
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN, config_flow.DOMAIN,
context={"source": "discovery"}, context={"source": "discovery"},
data={CONF_HOST: MOCK_HOST_1, CONF_PORT: MOCK_PORT_1}, data={
CONF_HOST: MOCK_SERVERS[0][CONF_HOST],
CONF_PORT: MOCK_SERVERS[0][CONF_PORT],
},
) )
assert result["type"] == "abort" assert result["type"] == "abort"
assert result["reason"] == "already_configured" assert result["reason"] == "already_configured"
@ -137,42 +138,28 @@ async def test_discovery_while_in_progress(hass):
async def test_import_success(hass): async def test_import_success(hass):
"""Test a successful configuration import.""" """Test a successful configuration import."""
mock_connections = MockConnections(ssl=True) mock_plex_server = MockPlexServer()
mm_plex_account = MagicMock()
mm_plex_account.resources = Mock(return_value=[MOCK_SERVER_1])
mm_plex_account.resource = Mock(return_value=mock_connections)
with patch("plexapi.server.PlexServer") as mock_plex_server:
type(mock_plex_server.return_value).machineIdentifier = PropertyMock(
return_value=MOCK_SERVER_1.clientIdentifier
)
type(mock_plex_server.return_value).friendlyName = PropertyMock(
return_value=MOCK_SERVER_1.name
)
type( # pylint: disable=protected-access
mock_plex_server.return_value
)._baseurl = PropertyMock(return_value=mock_connections.connections[0].httpuri)
with patch("plexapi.server.PlexServer", return_value=mock_plex_server):
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
config_flow.DOMAIN, config_flow.DOMAIN,
context={"source": "import"}, context={"source": "import"},
data={ data={
CONF_TOKEN: MOCK_TOKEN, CONF_TOKEN: MOCK_TOKEN,
CONF_URL: f"https://{MOCK_HOST_1}:{MOCK_PORT_1}", CONF_URL: f"https://{MOCK_SERVERS[0][CONF_HOST]}:{MOCK_SERVERS[0][CONF_PORT]}",
}, },
) )
assert result["type"] == "create_entry" assert result["type"] == "create_entry"
assert result["title"] == MOCK_SERVER_1.name assert result["title"] == mock_plex_server.friendlyName
assert result["data"][config_flow.CONF_SERVER] == MOCK_SERVER_1.name assert result["data"][config_flow.CONF_SERVER] == mock_plex_server.friendlyName
assert ( assert (
result["data"][config_flow.CONF_SERVER_IDENTIFIER] result["data"][config_flow.CONF_SERVER_IDENTIFIER]
== MOCK_SERVER_1.clientIdentifier == mock_plex_server.machineIdentifier
) )
assert ( assert (
result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL] result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL]
== mock_connections.connections[0].httpuri == mock_plex_server.url_in_use
) )
assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN
@ -188,7 +175,7 @@ async def test_import_bad_hostname(hass):
context={"source": "import"}, context={"source": "import"},
data={ data={
CONF_TOKEN: MOCK_TOKEN, CONF_TOKEN: MOCK_TOKEN,
CONF_URL: f"http://{MOCK_HOST_1}:{MOCK_PORT_1}", CONF_URL: f"http://{MOCK_SERVERS[0][CONF_HOST]}:{MOCK_SERVERS[0][CONF_PORT]}",
}, },
) )
assert result["type"] == "form" assert result["type"] == "form"
@ -205,19 +192,12 @@ async def test_unknown_exception(hass):
assert result["type"] == "form" assert result["type"] == "form"
assert result["step_id"] == "start_website_auth" assert result["step_id"] == "start_website_auth"
mock_connections = MockConnections()
mm_plex_account = MagicMock()
mm_plex_account.resources = Mock(return_value=[MOCK_SERVER_1])
mm_plex_account.resource = Mock(return_value=mock_connections)
with patch("plexapi.myplex.MyPlexAccount", return_value=mm_plex_account), patch(
"plexapi.server.PlexServer", side_effect=Exception
), asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value="MOCK_TOKEN"
):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external" assert result["type"] == "external"
with patch("plexapi.myplex.MyPlexAccount", side_effect=Exception), asynctest.patch(
"plexauth.PlexAuth.initiate_auth"
), asynctest.patch("plexauth.PlexAuth.token", return_value="MOCK_TOKEN"):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external_done" assert result["type"] == "external_done"
@ -237,18 +217,15 @@ async def test_no_servers_found(hass):
assert result["type"] == "form" assert result["type"] == "form"
assert result["step_id"] == "start_website_auth" assert result["step_id"] == "start_website_auth"
mm_plex_account = MagicMock() result = await hass.config_entries.flow.async_configure(result["flow_id"])
mm_plex_account.resources = Mock(return_value=[]) assert result["type"] == "external"
with patch( with patch(
"plexapi.myplex.MyPlexAccount", return_value=mm_plex_account "plexapi.myplex.MyPlexAccount", return_value=MockPlexAccount(servers=0)
), asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch( ), asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value=MOCK_TOKEN "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
): ):
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external"
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external_done" assert result["type"] == "external_done"
@ -261,6 +238,8 @@ async def test_no_servers_found(hass):
async def test_single_available_server(hass): async def test_single_available_server(hass):
"""Test creating an entry with one server available.""" """Test creating an entry with one server available."""
mock_plex_server = MockPlexServer()
await async_setup_component(hass, "http", {"http": {}}) await async_setup_component(hass, "http", {"http": {}})
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -269,46 +248,28 @@ async def test_single_available_server(hass):
assert result["type"] == "form" assert result["type"] == "form"
assert result["step_id"] == "start_website_auth" assert result["step_id"] == "start_website_auth"
mock_connections = MockConnections()
mm_plex_account = MagicMock()
mm_plex_account.resources = Mock(return_value=[MOCK_SERVER_1])
mm_plex_account.resource = Mock(return_value=mock_connections)
with patch("plexapi.myplex.MyPlexAccount", return_value=mm_plex_account), patch(
"plexapi.server.PlexServer"
) as mock_plex_server, asynctest.patch(
"plexauth.PlexAuth.initiate_auth"
), asynctest.patch(
"plexauth.PlexAuth.token", return_value=MOCK_TOKEN
):
type(mock_plex_server.return_value).machineIdentifier = PropertyMock(
return_value=MOCK_SERVER_1.clientIdentifier
)
type(mock_plex_server.return_value).friendlyName = PropertyMock(
return_value=MOCK_SERVER_1.name
)
type( # pylint: disable=protected-access
mock_plex_server.return_value
)._baseurl = PropertyMock(return_value=mock_connections.connections[0].httpuri)
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external" assert result["type"] == "external"
with patch("plexapi.myplex.MyPlexAccount", return_value=MockPlexAccount()), patch(
"plexapi.server.PlexServer", return_value=mock_plex_server
), asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value=MOCK_TOKEN
):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external_done" assert result["type"] == "external_done"
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "create_entry" assert result["type"] == "create_entry"
assert result["title"] == MOCK_SERVER_1.name assert result["title"] == mock_plex_server.friendlyName
assert result["data"][config_flow.CONF_SERVER] == MOCK_SERVER_1.name assert result["data"][config_flow.CONF_SERVER] == mock_plex_server.friendlyName
assert ( assert (
result["data"][config_flow.CONF_SERVER_IDENTIFIER] result["data"][config_flow.CONF_SERVER_IDENTIFIER]
== MOCK_SERVER_1.clientIdentifier == mock_plex_server.machineIdentifier
) )
assert ( assert (
result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL] result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL]
== mock_connections.connections[0].httpuri == mock_plex_server.url_in_use
) )
assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN
@ -316,6 +277,8 @@ async def test_single_available_server(hass):
async def test_multiple_servers_with_selection(hass): async def test_multiple_servers_with_selection(hass):
"""Test creating an entry with multiple servers available.""" """Test creating an entry with multiple servers available."""
mock_plex_server = MockPlexServer()
await async_setup_component(hass, "http", {"http": {}}) await async_setup_component(hass, "http", {"http": {}})
result = await hass.config_entries.flow.async_init( result = await hass.config_entries.flow.async_init(
@ -324,31 +287,18 @@ async def test_multiple_servers_with_selection(hass):
assert result["type"] == "form" assert result["type"] == "form"
assert result["step_id"] == "start_website_auth" assert result["step_id"] == "start_website_auth"
mock_connections = MockConnections() result = await hass.config_entries.flow.async_configure(result["flow_id"])
mm_plex_account = MagicMock() assert result["type"] == "external"
mm_plex_account.resources = Mock(return_value=[MOCK_SERVER_1, MOCK_SERVER_2])
mm_plex_account.resource = Mock(return_value=mock_connections)
with patch("plexapi.myplex.MyPlexAccount", return_value=mm_plex_account), patch( with patch(
"plexapi.server.PlexServer" "plexapi.myplex.MyPlexAccount", return_value=MockPlexAccount(servers=2)
) as mock_plex_server, asynctest.patch( ), patch(
"plexapi.server.PlexServer", return_value=mock_plex_server
), asynctest.patch(
"plexauth.PlexAuth.initiate_auth" "plexauth.PlexAuth.initiate_auth"
), asynctest.patch( ), asynctest.patch(
"plexauth.PlexAuth.token", return_value=MOCK_TOKEN "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
): ):
type(mock_plex_server.return_value).machineIdentifier = PropertyMock(
return_value=MOCK_SERVER_1.clientIdentifier
)
type(mock_plex_server.return_value).friendlyName = PropertyMock(
return_value=MOCK_SERVER_1.name
)
type( # pylint: disable=protected-access
mock_plex_server.return_value
)._baseurl = PropertyMock(return_value=mock_connections.connections[0].httpuri)
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external"
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external_done" assert result["type"] == "external_done"
@ -357,18 +307,21 @@ async def test_multiple_servers_with_selection(hass):
assert result["step_id"] == "select_server" assert result["step_id"] == "select_server"
result = await hass.config_entries.flow.async_configure( result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input={config_flow.CONF_SERVER: MOCK_SERVER_1.name} result["flow_id"],
user_input={
config_flow.CONF_SERVER: MOCK_SERVERS[0][config_flow.CONF_SERVER]
},
) )
assert result["type"] == "create_entry" assert result["type"] == "create_entry"
assert result["title"] == MOCK_SERVER_1.name assert result["title"] == mock_plex_server.friendlyName
assert result["data"][config_flow.CONF_SERVER] == MOCK_SERVER_1.name assert result["data"][config_flow.CONF_SERVER] == mock_plex_server.friendlyName
assert ( assert (
result["data"][config_flow.CONF_SERVER_IDENTIFIER] result["data"][config_flow.CONF_SERVER_IDENTIFIER]
== MOCK_SERVER_1.clientIdentifier == mock_plex_server.machineIdentifier
) )
assert ( assert (
result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL] result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL]
== mock_connections.connections[0].httpuri == mock_plex_server.url_in_use
) )
assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN
@ -376,13 +329,17 @@ async def test_multiple_servers_with_selection(hass):
async def test_adding_last_unconfigured_server(hass): async def test_adding_last_unconfigured_server(hass):
"""Test automatically adding last unconfigured server when multiple servers on account.""" """Test automatically adding last unconfigured server when multiple servers on account."""
mock_plex_server = MockPlexServer()
await async_setup_component(hass, "http", {"http": {}}) await async_setup_component(hass, "http", {"http": {}})
MockConfigEntry( MockConfigEntry(
domain=config_flow.DOMAIN, domain=config_flow.DOMAIN,
data={ data={
config_flow.CONF_SERVER_IDENTIFIER: MOCK_ID_2, config_flow.CONF_SERVER_IDENTIFIER: MOCK_SERVERS[1][
config_flow.CONF_SERVER: MOCK_NAME_2, config_flow.CONF_SERVER_IDENTIFIER
],
config_flow.CONF_SERVER: MOCK_SERVERS[1][config_flow.CONF_SERVER],
}, },
).add_to_hass(hass) ).add_to_hass(hass)
@ -392,45 +349,32 @@ async def test_adding_last_unconfigured_server(hass):
assert result["type"] == "form" assert result["type"] == "form"
assert result["step_id"] == "start_website_auth" assert result["step_id"] == "start_website_auth"
mock_connections = MockConnections() result = await hass.config_entries.flow.async_configure(result["flow_id"])
mm_plex_account = MagicMock() assert result["type"] == "external"
mm_plex_account.resources = Mock(return_value=[MOCK_SERVER_1, MOCK_SERVER_2])
mm_plex_account.resource = Mock(return_value=mock_connections)
with patch("plexapi.myplex.MyPlexAccount", return_value=mm_plex_account), patch( with patch(
"plexapi.server.PlexServer" "plexapi.myplex.MyPlexAccount", return_value=MockPlexAccount(servers=2)
) as mock_plex_server, asynctest.patch( ), patch(
"plexapi.server.PlexServer", return_value=mock_plex_server
), asynctest.patch(
"plexauth.PlexAuth.initiate_auth" "plexauth.PlexAuth.initiate_auth"
), asynctest.patch( ), asynctest.patch(
"plexauth.PlexAuth.token", return_value=MOCK_TOKEN "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
): ):
type(mock_plex_server.return_value).machineIdentifier = PropertyMock(
return_value=MOCK_SERVER_1.clientIdentifier
)
type(mock_plex_server.return_value).friendlyName = PropertyMock(
return_value=MOCK_SERVER_1.name
)
type( # pylint: disable=protected-access
mock_plex_server.return_value
)._baseurl = PropertyMock(return_value=mock_connections.connections[0].httpuri)
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external"
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external_done" assert result["type"] == "external_done"
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "create_entry" assert result["type"] == "create_entry"
assert result["title"] == MOCK_SERVER_1.name assert result["title"] == mock_plex_server.friendlyName
assert result["data"][config_flow.CONF_SERVER] == MOCK_SERVER_1.name assert result["data"][config_flow.CONF_SERVER] == mock_plex_server.friendlyName
assert ( assert (
result["data"][config_flow.CONF_SERVER_IDENTIFIER] result["data"][config_flow.CONF_SERVER_IDENTIFIER]
== MOCK_SERVER_1.clientIdentifier == mock_plex_server.machineIdentifier
) )
assert ( assert (
result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL] result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_URL]
== mock_connections.connections[0].httpuri == mock_plex_server.url_in_use
) )
assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN assert result["data"][config_flow.PLEX_SERVER_CONFIG][CONF_TOKEN] == MOCK_TOKEN
@ -438,32 +382,28 @@ async def test_adding_last_unconfigured_server(hass):
async def test_already_configured(hass): async def test_already_configured(hass):
"""Test a duplicated successful flow.""" """Test a duplicated successful flow."""
mock_plex_server = MockPlexServer()
flow = init_config_flow(hass) flow = init_config_flow(hass)
MockConfigEntry( MockConfigEntry(
domain=config_flow.DOMAIN, data={config_flow.CONF_SERVER_IDENTIFIER: MOCK_ID_1} domain=config_flow.DOMAIN,
data={
config_flow.CONF_SERVER_IDENTIFIER: MOCK_SERVERS[0][
config_flow.CONF_SERVER_IDENTIFIER
]
},
).add_to_hass(hass) ).add_to_hass(hass)
mock_connections = MockConnections() with patch(
"plexapi.server.PlexServer", return_value=mock_plex_server
mm_plex_account = MagicMock() ), asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
mm_plex_account.resources = Mock(return_value=[MOCK_SERVER_1]) "plexauth.PlexAuth.token", return_value=MOCK_TOKEN
mm_plex_account.resource = Mock(return_value=mock_connections) ):
with patch("plexapi.server.PlexServer") as mock_plex_server, asynctest.patch(
"plexauth.PlexAuth.initiate_auth"
), asynctest.patch("plexauth.PlexAuth.token", return_value=MOCK_TOKEN):
type(mock_plex_server.return_value).machineIdentifier = PropertyMock(
return_value=MOCK_SERVER_1.clientIdentifier
)
type(mock_plex_server.return_value).friendlyName = PropertyMock(
return_value=MOCK_SERVER_1.name
)
type( # pylint: disable=protected-access
mock_plex_server.return_value
)._baseurl = PropertyMock(return_value=mock_connections.connections[0].httpuri)
result = await flow.async_step_import( result = await flow.async_step_import(
{CONF_TOKEN: MOCK_TOKEN, CONF_URL: f"http://{MOCK_HOST_1}:{MOCK_PORT_1}"} {
CONF_TOKEN: MOCK_TOKEN,
CONF_URL: f"http://{MOCK_SERVERS[0][CONF_HOST]}:{MOCK_SERVERS[0][CONF_PORT]}",
}
) )
assert result["type"] == "abort" assert result["type"] == "abort"
assert result["reason"] == "already_configured" assert result["reason"] == "already_configured"
@ -477,16 +417,20 @@ async def test_all_available_servers_configured(hass):
MockConfigEntry( MockConfigEntry(
domain=config_flow.DOMAIN, domain=config_flow.DOMAIN,
data={ data={
config_flow.CONF_SERVER_IDENTIFIER: MOCK_ID_1, config_flow.CONF_SERVER_IDENTIFIER: MOCK_SERVERS[0][
config_flow.CONF_SERVER: MOCK_NAME_1, config_flow.CONF_SERVER_IDENTIFIER
],
config_flow.CONF_SERVER: MOCK_SERVERS[0][config_flow.CONF_SERVER],
}, },
).add_to_hass(hass) ).add_to_hass(hass)
MockConfigEntry( MockConfigEntry(
domain=config_flow.DOMAIN, domain=config_flow.DOMAIN,
data={ data={
config_flow.CONF_SERVER_IDENTIFIER: MOCK_ID_2, config_flow.CONF_SERVER_IDENTIFIER: MOCK_SERVERS[1][
config_flow.CONF_SERVER: MOCK_NAME_2, config_flow.CONF_SERVER_IDENTIFIER
],
config_flow.CONF_SERVER: MOCK_SERVERS[1][config_flow.CONF_SERVER],
}, },
).add_to_hass(hass) ).add_to_hass(hass)
@ -496,20 +440,14 @@ async def test_all_available_servers_configured(hass):
assert result["type"] == "form" assert result["type"] == "form"
assert result["step_id"] == "start_website_auth" assert result["step_id"] == "start_website_auth"
mock_connections = MockConnections()
mm_plex_account = MagicMock()
mm_plex_account.resources = Mock(return_value=[MOCK_SERVER_1, MOCK_SERVER_2])
mm_plex_account.resource = Mock(return_value=mock_connections)
with patch(
"plexapi.myplex.MyPlexAccount", return_value=mm_plex_account
), asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value=MOCK_TOKEN
):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external" assert result["type"] == "external"
with patch(
"plexapi.myplex.MyPlexAccount", return_value=MockPlexAccount(servers=2)
), asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value=MOCK_TOKEN
):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external_done" assert result["type"] == "external_done"
@ -557,13 +495,12 @@ async def test_external_timed_out(hass):
assert result["type"] == "form" assert result["type"] == "form"
assert result["step_id"] == "start_website_auth" assert result["step_id"] == "start_website_auth"
with asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value=None
):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external" assert result["type"] == "external"
with asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value=None
):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external_done" assert result["type"] == "external_done"
@ -583,12 +520,12 @@ async def test_callback_view(hass, aiohttp_client):
assert result["type"] == "form" assert result["type"] == "form"
assert result["step_id"] == "start_website_auth" assert result["step_id"] == "start_website_auth"
with asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value=MOCK_TOKEN
):
result = await hass.config_entries.flow.async_configure(result["flow_id"]) result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] == "external" assert result["type"] == "external"
with asynctest.patch("plexauth.PlexAuth.initiate_auth"), asynctest.patch(
"plexauth.PlexAuth.token", return_value=MOCK_TOKEN
):
client = await aiohttp_client(hass.http.app) client = await aiohttp_client(hass.http.app)
forward_url = f'{config_flow.AUTH_CALLBACK_PATH}?flow_id={result["flow_id"]}' forward_url = f'{config_flow.AUTH_CALLBACK_PATH}?flow_id={result["flow_id"]}'