Refactor Sonarr Integration (#33859)

Co-authored-by: Paulus Schoutsen <paulus@home-assistant.io>
This commit is contained in:
Chris TalkingtonandPaulus Schoutsen authored and GitHub committed 2020-05-29 17:08:05 -07:00
1 parent f4a518edcc
commit 940249f45e
22 files changed
+2179 -899

No files matched your search

+217 -1
View File
@@ -1 +1,217 @@
"""Tests for the sonarr component."""
"""Tests for the Sonarr component."""
from socket import gaierror as SocketGIAError
from homeassistant.components.sonarr.const import (
CONF_BASE_PATH,
CONF_UPCOMING_DAYS,
CONF_WANTED_MAX_ITEMS,
DEFAULT_UPCOMING_DAYS,
DEFAULT_WANTED_MAX_ITEMS,
DOMAIN,
)
from homeassistant.const import (
CONF_API_KEY,
CONF_HOST,
CONF_PORT,
CONF_SSL,
CONF_VERIFY_SSL,
)
from homeassistant.helpers.typing import HomeAssistantType
from tests.common import MockConfigEntry, load_fixture
from tests.test_util.aiohttp import AiohttpClientMocker
HOST = "192.168.1.189"
PORT = 8989
BASE_PATH = "/api"
API_KEY = "MOCK_API_KEY"
MOCK_SENSOR_CONFIG = {
"platform": DOMAIN,
"host": HOST,
"api_key": API_KEY,
"days": 3,
}
MOCK_USER_INPUT = {
CONF_HOST: HOST,
CONF_PORT: PORT,
CONF_BASE_PATH: BASE_PATH,
CONF_SSL: False,
CONF_API_KEY: API_KEY,
}
def mock_connection(
aioclient_mock: AiohttpClientMocker,
host: str = HOST,
port: str = PORT,
base_path: str = BASE_PATH,
error: bool = False,
invalid_auth: bool = False,
server_error: bool = False,
) -> None:
"""Mock Sonarr connection."""
if error:
mock_connection_error(
aioclient_mock, host=host, port=port, base_path=base_path,
)
return
if invalid_auth:
mock_connection_invalid_auth(
aioclient_mock, host=host, port=port, base_path=base_path,
)
return
if server_error:
mock_connection_server_error(
aioclient_mock, host=host, port=port, base_path=base_path,
)
return
sonarr_url = f"http://{host}:{port}{base_path}"
aioclient_mock.get(
f"{sonarr_url}/system/status",
text=load_fixture(f"sonarr/system-status.json"),
headers={"Content-Type": "application/json"},
)
aioclient_mock.get(
f"{sonarr_url}/diskspace",
text=load_fixture(f"sonarr/diskspace.json"),
headers={"Content-Type": "application/json"},
)
aioclient_mock.get(
f"{sonarr_url}/calendar",
text=load_fixture(f"sonarr/calendar.json"),
headers={"Content-Type": "application/json"},
)
aioclient_mock.get(
f"{sonarr_url}/command",
text=load_fixture(f"sonarr/command.json"),
headers={"Content-Type": "application/json"},
)
aioclient_mock.get(
f"{sonarr_url}/queue",
text=load_fixture(f"sonarr/queue.json"),
headers={"Content-Type": "application/json"},
)
aioclient_mock.get(
f"{sonarr_url}/series",
text=load_fixture(f"sonarr/series.json"),
headers={"Content-Type": "application/json"},
)
aioclient_mock.get(
f"{sonarr_url}/wanted/missing",
text=load_fixture(f"sonarr/wanted-missing.json"),
headers={"Content-Type": "application/json"},
)
def mock_connection_error(
aioclient_mock: AiohttpClientMocker,
host: str = HOST,
port: str = PORT,
base_path: str = BASE_PATH,
) -> None:
"""Mock Sonarr connection errors."""
sonarr_url = f"http://{host}:{port}{base_path}"
aioclient_mock.get(f"{sonarr_url}/system/status", exc=SocketGIAError)
aioclient_mock.get(f"{sonarr_url}/diskspace", exc=SocketGIAError)
aioclient_mock.get(f"{sonarr_url}/calendar", exc=SocketGIAError)
aioclient_mock.get(f"{sonarr_url}/command", exc=SocketGIAError)
aioclient_mock.get(f"{sonarr_url}/queue", exc=SocketGIAError)
aioclient_mock.get(f"{sonarr_url}/series", exc=SocketGIAError)
aioclient_mock.get(f"{sonarr_url}/missing/wanted", exc=SocketGIAError)
def mock_connection_invalid_auth(
aioclient_mock: AiohttpClientMocker,
host: str = HOST,
port: str = PORT,
base_path: str = BASE_PATH,
) -> None:
"""Mock Sonarr invalid auth errors."""
sonarr_url = f"http://{host}:{port}{base_path}"
aioclient_mock.get(f"{sonarr_url}/system/status", status=403)
aioclient_mock.get(f"{sonarr_url}/diskspace", status=403)
aioclient_mock.get(f"{sonarr_url}/calendar", status=403)
aioclient_mock.get(f"{sonarr_url}/command", status=403)
aioclient_mock.get(f"{sonarr_url}/queue", status=403)
aioclient_mock.get(f"{sonarr_url}/series", status=403)
aioclient_mock.get(f"{sonarr_url}/missing/wanted", status=403)
def mock_connection_server_error(
aioclient_mock: AiohttpClientMocker,
host: str = HOST,
port: str = PORT,
base_path: str = BASE_PATH,
) -> None:
"""Mock Sonarr server errors."""
sonarr_url = f"http://{host}:{port}{base_path}"
aioclient_mock.get(f"{sonarr_url}/system/status", status=500)
aioclient_mock.get(f"{sonarr_url}/diskspace", status=500)
aioclient_mock.get(f"{sonarr_url}/calendar", status=500)
aioclient_mock.get(f"{sonarr_url}/command", status=500)
aioclient_mock.get(f"{sonarr_url}/queue", status=500)
aioclient_mock.get(f"{sonarr_url}/series", status=500)
aioclient_mock.get(f"{sonarr_url}/missing/wanted", status=500)
async def setup_integration(
hass: HomeAssistantType,
aioclient_mock: AiohttpClientMocker,
host: str = HOST,
port: str = PORT,
base_path: str = BASE_PATH,
api_key: str = API_KEY,
unique_id: str = None,
skip_entry_setup: bool = False,
connection_error: bool = False,
invalid_auth: bool = False,
server_error: bool = False,
) -> MockConfigEntry:
"""Set up the Sonarr integration in Home Assistant."""
entry = MockConfigEntry(
domain=DOMAIN,
unique_id=unique_id,
data={
CONF_HOST: host,
CONF_PORT: port,
CONF_BASE_PATH: base_path,
CONF_SSL: False,
CONF_VERIFY_SSL: False,
CONF_API_KEY: api_key,
CONF_UPCOMING_DAYS: DEFAULT_UPCOMING_DAYS,
CONF_WANTED_MAX_ITEMS: DEFAULT_WANTED_MAX_ITEMS,
},
)
entry.add_to_hass(hass)
mock_connection(
aioclient_mock,
host=host,
port=port,
base_path=base_path,
error=connection_error,
invalid_auth=invalid_auth,
server_error=server_error,
)
if not skip_entry_setup:
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
return entry
+183
View File
@@ -0,0 +1,183 @@
"""Test the Sonarr config flow."""
from homeassistant.components.sonarr.const import (
CONF_UPCOMING_DAYS,
CONF_WANTED_MAX_ITEMS,
DEFAULT_UPCOMING_DAYS,
DEFAULT_WANTED_MAX_ITEMS,
DOMAIN,
)
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_SOURCE, CONF_VERIFY_SSL
from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT,
RESULT_TYPE_CREATE_ENTRY,
RESULT_TYPE_FORM,
)
from homeassistant.helpers.typing import HomeAssistantType
from tests.async_mock import patch
from tests.components.sonarr import (
HOST,
MOCK_USER_INPUT,
mock_connection,
mock_connection_error,
mock_connection_invalid_auth,
setup_integration,
)
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_options(hass, aioclient_mock: AiohttpClientMocker):
"""Test updating options."""
entry = await setup_integration(hass, aioclient_mock)
assert entry.options[CONF_UPCOMING_DAYS] == DEFAULT_UPCOMING_DAYS
assert entry.options[CONF_WANTED_MAX_ITEMS] == DEFAULT_WANTED_MAX_ITEMS
result = await hass.config_entries.options.async_init(entry.entry_id)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={CONF_UPCOMING_DAYS: 2, CONF_WANTED_MAX_ITEMS: 100},
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["data"][CONF_UPCOMING_DAYS] == 2
assert result["data"][CONF_WANTED_MAX_ITEMS] == 100
async def test_show_user_form(hass: HomeAssistantType) -> None:
"""Test that the user set up form is served."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE: SOURCE_USER},
)
assert result["step_id"] == "user"
assert result["type"] == RESULT_TYPE_FORM
async def test_cannot_connect(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we show user form on connection error."""
mock_connection_error(aioclient_mock)
user_input = MOCK_USER_INPUT.copy()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=user_input,
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "cannot_connect"}
async def test_invalid_auth(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we show user form on invalid auth."""
mock_connection_invalid_auth(aioclient_mock)
user_input = MOCK_USER_INPUT.copy()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=user_input,
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user"
assert result["errors"] == {"base": "invalid_auth"}
async def test_unknown_error(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test we show user form on unknown error."""
user_input = MOCK_USER_INPUT.copy()
with patch(
"homeassistant.components.sonarr.config_flow.Sonarr.update",
side_effect=Exception,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE: SOURCE_USER}, data=user_input,
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "unknown"
async def test_full_import_flow_implementation(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the full manual user flow from start to finish."""
mock_connection(aioclient_mock)
user_input = MOCK_USER_INPUT.copy()
result = await hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE: SOURCE_IMPORT}, data=user_input,
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == HOST
assert result["data"]
assert result["data"][CONF_HOST] == HOST
assert result["result"]
assert result["result"].options[CONF_UPCOMING_DAYS] == DEFAULT_UPCOMING_DAYS
assert result["result"].options[CONF_WANTED_MAX_ITEMS] == DEFAULT_WANTED_MAX_ITEMS
async def test_full_user_flow_implementation(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the full manual user flow from start to finish."""
mock_connection(aioclient_mock)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE: SOURCE_USER},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user"
user_input = MOCK_USER_INPUT.copy()
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=user_input,
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == HOST
assert result["data"]
assert result["data"][CONF_HOST] == HOST
async def test_full_user_flow_advanced_options(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the full manual user flow with advanced options."""
mock_connection(aioclient_mock)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={CONF_SOURCE: SOURCE_USER, "show_advanced_options": True}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user"
user_input = {
**MOCK_USER_INPUT,
CONF_VERIFY_SSL: True,
}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input=user_input,
)
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == HOST
assert result["data"]
assert result["data"][CONF_HOST] == HOST
assert result["data"][CONF_VERIFY_SSL]
+36
View File
@@ -0,0 +1,36 @@
"""Tests for the Sonsrr integration."""
from homeassistant.components.sonarr.const import DOMAIN
from homeassistant.config_entries import (
ENTRY_STATE_LOADED,
ENTRY_STATE_NOT_LOADED,
ENTRY_STATE_SETUP_RETRY,
)
from homeassistant.core import HomeAssistant
from tests.components.sonarr import setup_integration
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_config_entry_not_ready(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the configuration entry not ready."""
entry = await setup_integration(hass, aioclient_mock, connection_error=True)
assert entry.state == ENTRY_STATE_SETUP_RETRY
async def test_unload_config_entry(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the configuration entry unloading."""
entry = await setup_integration(hass, aioclient_mock)
assert hass.data[DOMAIN]
assert entry.entry_id in hass.data[DOMAIN]
assert entry.state == ENTRY_STATE_LOADED
await hass.config_entries.async_unload(entry.entry_id)
await hass.async_block_till_done()
assert entry.entry_id not in hass.data[DOMAIN]
assert entry.state == ENTRY_STATE_NOT_LOADED
+173 -692
View File
@@ -1,722 +1,203 @@
"""The tests for the Sonarr platform."""
from datetime import datetime
import time
import unittest
"""Tests for the Sonarr sensor platform."""
from datetime import timedelta
import pytest
import homeassistant.components.sonarr.sensor as sonarr
from homeassistant.const import DATA_GIGABYTES, UNIT_PERCENTAGE
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.components.sonarr.const import (
CONF_BASE_PATH,
CONF_UPCOMING_DAYS,
DOMAIN,
)
from homeassistant.const import (
ATTR_ICON,
ATTR_UNIT_OF_MEASUREMENT,
DATA_GIGABYTES,
STATE_UNAVAILABLE,
)
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from tests.async_mock import patch
from tests.common import get_test_home_assistant
from tests.common import async_fire_time_changed
from tests.components.sonarr import (
MOCK_SENSOR_CONFIG,
mock_connection,
setup_integration,
)
from tests.test_util.aiohttp import AiohttpClientMocker
UPCOMING_ENTITY_ID = f"{SENSOR_DOMAIN}.sonarr_upcoming"
def mocked_exception(*args, **kwargs):
"""Mock exception thrown by requests.get."""
raise OSError
async def test_import_from_sensor_component(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test import from sensor platform."""
mock_connection(aioclient_mock)
assert await async_setup_component(
hass, SENSOR_DOMAIN, {SENSOR_DOMAIN: MOCK_SENSOR_CONFIG}
)
await hass.async_block_till_done()
entries = hass.config_entries.async_entries(DOMAIN)
assert len(entries) == 1
assert entries[0].data[CONF_BASE_PATH] == "/api"
assert entries[0].options[CONF_UPCOMING_DAYS] == 3
assert hass.states.get(UPCOMING_ENTITY_ID)
def mocked_requests_get(*args, **kwargs):
"""Mock requests.get invocations."""
async def test_sensors(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the creation and values of the sensors."""
entry = await setup_integration(hass, aioclient_mock, skip_entry_setup=True)
registry = await hass.helpers.entity_registry.async_get_registry()
class MockResponse:
"""Class to represent a mocked response."""
# Pre-create registry entries for disabled by default sensors
sensors = {
"commands": "sonarr_commands",
"diskspace": "sonarr_disk_space",
"queue": "sonarr_queue",
"series": "sonarr_shows",
"wanted": "sonarr_wanted",
}
def __init__(self, json_data, status_code):
"""Initialize the mock response class."""
self.json_data = json_data
self.status_code = status_code
def json(self):
"""Return the json of the response."""
return self.json_data
today = datetime.date(datetime.fromtimestamp(time.time()))
url = str(args[0])
if "api/calendar" in url:
return MockResponse(
[
{
"seriesId": 3,
"episodeFileId": 0,
"seasonNumber": 4,
"episodeNumber": 11,
"title": "Easy Com-mercial, Easy Go-mercial",
"airDate": str(today),
"airDateUtc": "2014-01-27T01:30:00Z",
"overview": "To compete with fellow “restaurateur,” Ji...",
"hasFile": "false",
"monitored": "true",
"sceneEpisodeNumber": 0,
"sceneSeasonNumber": 0,
"tvDbEpisodeId": 0,
"series": {
"tvdbId": 194031,
"tvRageId": 24607,
"imdbId": "tt1561755",
"title": "Bob's Burgers",
"cleanTitle": "bobsburgers",
"status": "continuing",
"overview": "Bob's Burgers follows a third-generation ...",
"airTime": "5:30pm",
"monitored": "true",
"qualityProfileId": 1,
"seasonFolder": "true",
"lastInfoSync": "2014-01-26T19:25:55.4555946Z",
"runtime": 30,
"images": [
{
"coverType": "banner",
"url": "http://slurm.trakt.us/images/bann.jpg",
},
{
"coverType": "poster",
"url": "http://slurm.trakt.us/images/poster00.jpg",
},
{
"coverType": "fanart",
"url": "http://slurm.trakt.us/images/fan6.jpg",
},
],
"seriesType": "standard",
"network": "FOX",
"useSceneNumbering": "false",
"titleSlug": "bobs-burgers",
"path": "T:\\Bob's Burgers",
"year": 0,
"firstAired": "2011-01-10T01:30:00Z",
"qualityProfile": {
"value": {
"name": "SD",
"allowed": [
{"id": 1, "name": "SDTV", "weight": 1},
{"id": 8, "name": "WEBDL-480p", "weight": 2},
{"id": 2, "name": "DVD", "weight": 3},
],
"cutoff": {"id": 1, "name": "SDTV", "weight": 1},
"id": 1,
},
"isLoaded": "true",
},
"seasons": [
{"seasonNumber": 4, "monitored": "true"},
{"seasonNumber": 3, "monitored": "true"},
{"seasonNumber": 2, "monitored": "true"},
{"seasonNumber": 1, "monitored": "true"},
{"seasonNumber": 0, "monitored": "false"},
],
"id": 66,
},
"downloading": "false",
"id": 14402,
}
],
200,
for (unique, oid) in sensors.items():
registry.async_get_or_create(
SENSOR_DOMAIN,
DOMAIN,
f"{entry.entry_id}_{unique}",
suggested_object_id=oid,
disabled_by=None,
)
if "api/command" in url:
return MockResponse(
[
{
"name": "RescanSeries",
"startedOn": "0001-01-01T00:00:00Z",
"stateChangeTime": "2014-02-05T05:09:09.2366139Z",
"sendUpdatesToClient": "true",
"state": "pending",
"id": 24,
}
],
200,
)
if "api/wanted/missing" in url or "totalRecords" in url:
return MockResponse(
{
"page": 1,
"pageSize": 15,
"sortKey": "airDateUtc",
"sortDirection": "descending",
"totalRecords": 1,
"records": [
{
"seriesId": 1,
"episodeFileId": 0,
"seasonNumber": 5,
"episodeNumber": 4,
"title": "Archer Vice: House Call",
"airDate": "2014-02-03",
"airDateUtc": "2014-02-04T03:00:00Z",
"overview": "Archer has to stage an that ... ",
"hasFile": "false",
"monitored": "true",
"sceneEpisodeNumber": 0,
"sceneSeasonNumber": 0,
"tvDbEpisodeId": 0,
"absoluteEpisodeNumber": 50,
"series": {
"tvdbId": 110381,
"tvRageId": 23354,
"imdbId": "tt1486217",
"title": "Archer (2009)",
"cleanTitle": "archer2009",
"status": "continuing",
"overview": "At ISIS, an international spy ...",
"airTime": "7:00pm",
"monitored": "true",
"qualityProfileId": 1,
"seasonFolder": "true",
"lastInfoSync": "2014-02-05T04:39:28.550495Z",
"runtime": 30,
"images": [
{
"coverType": "banner",
"url": "http://slurm.trakt.us//57.12.jpg",
},
{
"coverType": "poster",
"url": "http://slurm.trakt.u/57.12-300.jpg",
},
{
"coverType": "fanart",
"url": "http://slurm.trakt.us/image.12.jpg",
},
],
"seriesType": "standard",
"network": "FX",
"useSceneNumbering": "false",
"titleSlug": "archer-2009",
"path": "E:\\Test\\TV\\Archer (2009)",
"year": 2009,
"firstAired": "2009-09-18T02:00:00Z",
"qualityProfile": {
"value": {
"name": "SD",
"cutoff": {"id": 1, "name": "SDTV"},
"items": [
{
"quality": {"id": 1, "name": "SDTV"},
"allowed": "true",
},
{
"quality": {"id": 8, "name": "WEBDL-480p"},
"allowed": "true",
},
{
"quality": {"id": 2, "name": "DVD"},
"allowed": "true",
},
{
"quality": {"id": 4, "name": "HDTV-720p"},
"allowed": "false",
},
{
"quality": {"id": 9, "name": "HDTV-1080p"},
"allowed": "false",
},
{
"quality": {"id": 10, "name": "Raw-HD"},
"allowed": "false",
},
{
"quality": {"id": 5, "name": "WEBDL-720p"},
"allowed": "false",
},
{
"quality": {"id": 6, "name": "Bluray-720p"},
"allowed": "false",
},
{
"quality": {"id": 3, "name": "WEBDL-1080p"},
"allowed": "false",
},
{
"quality": {
"id": 7,
"name": "Bluray-1080p",
},
"allowed": "false",
},
],
"id": 1,
},
"isLoaded": "true",
},
"seasons": [
{"seasonNumber": 5, "monitored": "true"},
{"seasonNumber": 4, "monitored": "true"},
{"seasonNumber": 3, "monitored": "true"},
{"seasonNumber": 2, "monitored": "true"},
{"seasonNumber": 1, "monitored": "true"},
{"seasonNumber": 0, "monitored": "false"},
],
"id": 1,
},
"downloading": "false",
"id": 55,
}
],
},
200,
)
if "api/queue" in url:
return MockResponse(
[
{
"series": {
"title": "Game of Thrones",
"sortTitle": "game thrones",
"seasonCount": 6,
"status": "continuing",
"overview": "Seven noble families fight for land ...",
"network": "HBO",
"airTime": "21:00",
"images": [
{
"coverType": "fanart",
"url": "http://thetvdb.com/banners/fanart/-83.jpg",
},
{
"coverType": "banner",
"url": "http://thetvdb.com/banners/-g19.jpg",
},
{
"coverType": "poster",
"url": "http://thetvdb.com/banners/posters-34.jpg",
},
],
"seasons": [
{"seasonNumber": 0, "monitored": "false"},
{"seasonNumber": 1, "monitored": "false"},
{"seasonNumber": 2, "monitored": "true"},
{"seasonNumber": 3, "monitored": "false"},
{"seasonNumber": 4, "monitored": "false"},
{"seasonNumber": 5, "monitored": "true"},
{"seasonNumber": 6, "monitored": "true"},
],
"year": 2011,
"path": "/Volumes/Media/Shows/Game of Thrones",
"profileId": 5,
"seasonFolder": "true",
"monitored": "true",
"useSceneNumbering": "false",
"runtime": 60,
"tvdbId": 121361,
"tvRageId": 24493,
"tvMazeId": 82,
"firstAired": "2011-04-16T23:00:00Z",
"lastInfoSync": "2016-02-05T16:40:11.614176Z",
"seriesType": "standard",
"cleanTitle": "gamethrones",
"imdbId": "tt0944947",
"titleSlug": "game-of-thrones",
"certification": "TV-MA",
"genres": ["Adventure", "Drama", "Fantasy"],
"tags": [],
"added": "2015-12-28T13:44:24.204583Z",
"ratings": {"votes": 1128, "value": 9.4},
"qualityProfileId": 5,
"id": 17,
},
"episode": {
"seriesId": 17,
"episodeFileId": 0,
"seasonNumber": 3,
"episodeNumber": 8,
"title": "Second Sons",
"airDate": "2013-05-19",
"airDateUtc": "2013-05-20T01:00:00Z",
"overview": "King’s Landing hosts a wedding, and ...",
"hasFile": "false",
"monitored": "false",
"absoluteEpisodeNumber": 28,
"unverifiedSceneNumbering": "false",
"id": 889,
},
"quality": {
"quality": {"id": 7, "name": "Bluray-1080p"},
"revision": {"version": 1, "real": 0},
},
"size": 4472186820,
"title": "Game.of.Thrones.S03E08.Second.Sons.2013.1080p.",
"sizeleft": 0,
"timeleft": "00:00:00",
"estimatedCompletionTime": "2016-02-05T22:46:52.440104Z",
"status": "Downloading",
"trackedDownloadStatus": "Ok",
"statusMessages": [],
"downloadId": "SABnzbd_nzo_Mq2f_b",
"protocol": "usenet",
"id": 1503378561,
}
],
200,
)
if "api/series" in url:
return MockResponse(
[
{
"title": "Marvel's Daredevil",
"alternateTitles": [{"title": "Daredevil", "seasonNumber": -1}],
"sortTitle": "marvels daredevil",
"seasonCount": 2,
"totalEpisodeCount": 26,
"episodeCount": 26,
"episodeFileCount": 26,
"sizeOnDisk": 79282273693,
"status": "continuing",
"overview": "Matt Murdock was blinded in a tragic accident...",
"previousAiring": "2016-03-18T04:01:00Z",
"network": "Netflix",
"airTime": "00:01",
"images": [
{
"coverType": "fanart",
"url": "/sonarr/MediaCover/7/fanart.jpg?lastWrite=",
},
{
"coverType": "banner",
"url": "/sonarr/MediaCover/7/banner.jpg?lastWrite=",
},
{
"coverType": "poster",
"url": "/sonarr/MediaCover/7/poster.jpg?lastWrite=",
},
],
"seasons": [
{
"seasonNumber": 1,
"monitored": "false",
"statistics": {
"previousAiring": "2015-04-10T04:01:00Z",
"episodeFileCount": 13,
"episodeCount": 13,
"totalEpisodeCount": 13,
"sizeOnDisk": 22738179333,
"percentOfEpisodes": 100,
},
},
{
"seasonNumber": 2,
"monitored": "false",
"statistics": {
"previousAiring": "2016-03-18T04:01:00Z",
"episodeFileCount": 13,
"episodeCount": 13,
"totalEpisodeCount": 13,
"sizeOnDisk": 56544094360,
"percentOfEpisodes": 100,
},
},
],
"year": 2015,
"path": "F:\\TV_Shows\\Marvels Daredevil",
"profileId": 6,
"seasonFolder": "true",
"monitored": "true",
"useSceneNumbering": "false",
"runtime": 55,
"tvdbId": 281662,
"tvRageId": 38796,
"tvMazeId": 1369,
"firstAired": "2015-04-10T04:00:00Z",
"lastInfoSync": "2016-09-09T09:02:49.4402575Z",
"seriesType": "standard",
"cleanTitle": "marvelsdaredevil",
"imdbId": "tt3322312",
"titleSlug": "marvels-daredevil",
"certification": "TV-MA",
"genres": ["Action", "Crime", "Drama"],
"tags": [],
"added": "2015-05-15T00:20:32.7892744Z",
"ratings": {"votes": 461, "value": 8.9},
"qualityProfileId": 6,
"id": 7,
}
],
200,
)
if "api/diskspace" in url:
return MockResponse(
[
{
"path": "/data",
"label": "",
"freeSpace": 282500067328,
"totalSpace": 499738734592,
}
],
200,
)
if "api/system/status" in url:
return MockResponse(
{
"version": "2.0.0.1121",
"buildTime": "2014-02-08T20:49:36.5560392Z",
"isDebug": "false",
"isProduction": "true",
"isAdmin": "true",
"isUserInteractive": "false",
"startupPath": "C:\\ProgramData\\NzbDrone\\bin",
"appData": "C:\\ProgramData\\NzbDrone",
"osVersion": "6.2.9200.0",
"isMono": "false",
"isLinux": "false",
"isWindows": "true",
"branch": "develop",
"authentication": "false",
"startOfWeek": 0,
"urlBase": "",
},
200,
)
return MockResponse({"error": "Unauthorized"}, 401)
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
for (unique, oid) in sensors.items():
entity = registry.async_get(f"sensor.{oid}")
assert entity
assert entity.unique_id == f"{entry.entry_id}_{unique}"
state = hass.states.get("sensor.sonarr_commands")
assert state
assert state.attributes.get(ATTR_ICON) == "mdi:code-braces"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "Commands"
assert state.state == "2"
state = hass.states.get("sensor.sonarr_disk_space")
assert state
assert state.attributes.get(ATTR_ICON) == "mdi:harddisk"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == DATA_GIGABYTES
assert state.state == "263.10"
state = hass.states.get("sensor.sonarr_queue")
assert state
assert state.attributes.get(ATTR_ICON) == "mdi:download"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "Episodes"
assert state.state == "1"
state = hass.states.get("sensor.sonarr_shows")
assert state
assert state.attributes.get(ATTR_ICON) == "mdi:television"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "Series"
assert state.state == "1"
state = hass.states.get("sensor.sonarr_upcoming")
assert state
assert state.attributes.get(ATTR_ICON) == "mdi:television"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "Episodes"
assert state.state == "1"
state = hass.states.get("sensor.sonarr_wanted")
assert state
assert state.attributes.get(ATTR_ICON) == "mdi:television"
assert state.attributes.get(ATTR_UNIT_OF_MEASUREMENT) == "Episodes"
assert state.state == "2"
class TestSonarrSetup(unittest.TestCase):
"""Test the Sonarr platform."""
@pytest.mark.parametrize(
"entity_id",
(
"sensor.sonarr_commands",
"sensor.sonarr_disk_space",
"sensor.sonarr_queue",
"sensor.sonarr_shows",
"sensor.sonarr_wanted",
),
)
async def test_disabled_by_default_sensors(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker, entity_id: str
) -> None:
"""Test the disabled by default sensors."""
await setup_integration(hass, aioclient_mock)
registry = await hass.helpers.entity_registry.async_get_registry()
print(registry.entities)
# pylint: disable=invalid-name
DEVICES = []
state = hass.states.get(entity_id)
assert state is None
def add_entities(self, devices, update):
"""Mock add devices."""
for device in devices:
self.DEVICES.append(device)
entry = registry.async_get(entity_id)
assert entry
assert entry.disabled
assert entry.disabled_by == "integration"
def setUp(self):
"""Initialize values for this testcase class."""
self.DEVICES = []
self.hass = get_test_home_assistant()
self.hass.config.time_zone = "America/Los_Angeles"
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
async def test_availability(
hass: HomeAssistantType, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test entity availability."""
now = dt_util.utcnow()
@patch("requests.get", side_effect=mocked_requests_get)
def test_diskspace_no_paths(self, req_mock):
"""Test getting all disk space."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": [],
"monitored_conditions": ["diskspace"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert "263.10" == device.state
assert "mdi:harddisk" == device.icon
assert DATA_GIGABYTES == device.unit_of_measurement
assert "Sonarr Disk Space" == device.name
assert "263.10/465.42GB (56.53%)" == device.device_state_attributes["/data"]
with patch("homeassistant.util.dt.utcnow", return_value=now):
await setup_integration(hass, aioclient_mock)
@patch("requests.get", side_effect=mocked_requests_get)
def test_diskspace_paths(self, req_mock):
"""Test getting diskspace for included paths."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["diskspace"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert "263.10" == device.state
assert "mdi:harddisk" == device.icon
assert DATA_GIGABYTES == device.unit_of_measurement
assert "Sonarr Disk Space" == device.name
assert "263.10/465.42GB (56.53%)" == device.device_state_attributes["/data"]
assert hass.states.get(UPCOMING_ENTITY_ID).state == "1"
@patch("requests.get", side_effect=mocked_requests_get)
def test_commands(self, req_mock):
"""Test getting running commands."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["commands"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert 1 == device.state
assert "mdi:code-braces" == device.icon
assert "Commands" == device.unit_of_measurement
assert "Sonarr Commands" == device.name
assert "pending" == device.device_state_attributes["RescanSeries"]
# state to unavailable
aioclient_mock.clear_requests()
mock_connection(aioclient_mock, error=True)
@patch("requests.get", side_effect=mocked_requests_get)
def test_queue(self, req_mock):
"""Test getting downloads in the queue."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["queue"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert 1 == device.state
assert "mdi:download" == device.icon
assert "Episodes" == device.unit_of_measurement
assert "Sonarr Queue" == device.name
assert (
f"100.00{UNIT_PERCENTAGE}"
== device.device_state_attributes["Game of Thrones S03E08"]
)
future = now + timedelta(minutes=1)
with patch("homeassistant.util.dt.utcnow", return_value=future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@patch("requests.get", side_effect=mocked_requests_get)
def test_series(self, req_mock):
"""Test getting the number of series."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["series"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert 1 == device.state
assert "mdi:television" == device.icon
assert "Shows" == device.unit_of_measurement
assert "Sonarr Series" == device.name
assert (
"26/26 Episodes" == device.device_state_attributes["Marvel's Daredevil"]
)
assert hass.states.get(UPCOMING_ENTITY_ID).state == STATE_UNAVAILABLE
@patch("requests.get", side_effect=mocked_requests_get)
def test_wanted(self, req_mock):
"""Test getting wanted episodes."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["wanted"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert 1 == device.state
assert "mdi:television" == device.icon
assert "Episodes" == device.unit_of_measurement
assert "Sonarr Wanted" == device.name
assert (
"2014-02-03" == device.device_state_attributes["Archer (2009) S05E04"]
)
# state to available
aioclient_mock.clear_requests()
mock_connection(aioclient_mock)
@patch("requests.get", side_effect=mocked_requests_get)
def test_upcoming_multiple_days(self, req_mock):
"""Test the upcoming episodes for multiple days."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["upcoming"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert 1 == device.state
assert "mdi:television" == device.icon
assert "Episodes" == device.unit_of_measurement
assert "Sonarr Upcoming" == device.name
assert "S04E11" == device.device_state_attributes["Bob's Burgers"]
future += timedelta(minutes=1)
with patch("homeassistant.util.dt.utcnow", return_value=future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@pytest.mark.skip
@patch("requests.get", side_effect=mocked_requests_get)
def test_upcoming_today(self, req_mock):
"""Test filtering for a single day.
assert hass.states.get(UPCOMING_ENTITY_ID).state == "1"
Sonarr needs to respond with at least 2 days
"""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "1",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["upcoming"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert 1 == device.state
assert "mdi:television" == device.icon
assert "Episodes" == device.unit_of_measurement
assert "Sonarr Upcoming" == device.name
assert "S04E11" == device.device_state_attributes["Bob's Burgers"]
# state to unavailable
aioclient_mock.clear_requests()
mock_connection(aioclient_mock, invalid_auth=True)
@patch("requests.get", side_effect=mocked_requests_get)
def test_system_status(self, req_mock):
"""Test getting system status."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["status"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert "2.0.0.1121" == device.state
assert "mdi:information" == device.icon
assert "Sonarr Status" == device.name
assert "6.2.9200.0" == device.device_state_attributes["osVersion"]
future += timedelta(minutes=1)
with patch("homeassistant.util.dt.utcnow", return_value=future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
@pytest.mark.skip
@patch("requests.get", side_effect=mocked_requests_get)
def test_ssl(self, req_mock):
"""Test SSL being enabled."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "1",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["upcoming"],
"ssl": "true",
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert 1 == device.state
assert "s" == device.ssl
assert "mdi:television" == device.icon
assert "Episodes" == device.unit_of_measurement
assert "Sonarr Upcoming" == device.name
assert "S04E11" == device.device_state_attributes["Bob's Burgers"]
assert hass.states.get(UPCOMING_ENTITY_ID).state == STATE_UNAVAILABLE
@patch("requests.get", side_effect=mocked_exception)
def test_exception_handling(self, req_mock):
"""Test exception being handled."""
config = {
"platform": "sonarr",
"api_key": "foo",
"days": "1",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["upcoming"],
}
sonarr.setup_platform(self.hass, config, self.add_entities, None)
for device in self.DEVICES:
device.update()
assert device.state is None
# state to available
aioclient_mock.clear_requests()
mock_connection(aioclient_mock)
future += timedelta(minutes=1)
with patch("homeassistant.util.dt.utcnow", return_value=future):
async_fire_time_changed(hass, future)
await hass.async_block_till_done()
assert hass.states.get(UPCOMING_ENTITY_ID).state == "1"