1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-21 19:30:02 +00:00
Files
.devcontainer
.github
.vscode
docs
homeassistant
machine
pylint
rootfs
script
tests
auth
backports
components
abode
accuweather
acmeda
adax
adguard
advantage_air
aemet
agent_dvr
air_quality
airly
airnow
airthings
airtouch4
airvisual
alarm_control_panel
alarmdecoder
alert
alexa
almond
ambee
amberelectric
ambiclimate
ambient_station
analytics
androidtv
apache_kafka
api
api_streams
apns
apple_tv
apprise
aprs
arcam_fmj
arlo
aseko_pool_live
asuswrt
atag
august
aurora
aurora_abb_powerone
auth
automation
awair
aws
axis
azure_devops
azure_event_hub
balboa
bayesian
binary_sensor
blackbird
blebox
blink
blueprint
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
broadlink
brother
brunt
bsblan
buienradar
button
caldav
calendar
camera
canary
cast
cert_expiry
climacell
climate
cloud
cloudflare
co2signal
coinbase
color_extractor
comfoconnect
command_line
compensation
config
configurator
control4
conversation
coolmaster
coronavirus
counter
cover
cpuspeed
crownstone
daikin
darksky
datadog
debugpy
deconz
default_config
demo
denonavr
derivative
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
dialogflow
directv
discovery
dlna_dmr
doorbird
dsmr
dte_energy_bridge
duckdns
dunehd
dynalite
eafm
ecobee
econet
efergy
elgato
elkm1
elmax
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
enocean
enphase_envoy
environment_canada
epson
esphome
everlights
evil_genius_labs
ezviz
faa_delays
facebook
facebox
fail2ban
fan
feedreader
ffmpeg
fido
file
filesize
filter
fireservicerota
firmata
fjaraskupan
flic
flick_electric
flipr
flo
flume
flunearyou
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
foscam
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
garages_amsterdam
gdacs
generic
generic_hygrostat
generic_thermostat
geo_json_events
geo_location
geo_rss_events
geofency
geonetnz_quakes
geonetnz_volcano
gios
glances
goalzero
gogogate2
goodwe
google
google_assistant
google_domains
google_pubsub
google_translate
google_travel_time
google_wifi
gpslogger
graphite
gree
greeneye_monitor
group
growatt_server
guardian
habitica
hangouts
harmony
hassio
hddtemp
heos
here_travel_time
hisense_aehw4a1
history
history_stats
hive
hlk_sw16
home_connect
home_plus_control
homeassistant
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
honeywell
html5
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
hvv_departures
hyperion
ialarm
iaqualink
icloud
ifttt
ign_sismologia
image
image_processing
imap_email_content
influxdb
input_boolean
input_button
input_datetime
input_number
input_select
input_text
insteon
integration
intent
intent_script
ios
iotawatt
ipma
ipp
iqvia
islamic_prayer_times
isy994
izone
jellyfin
jewish_calendar
juicenet
keenetic_ndms2
kira
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
lastfm
launch_library
lcn
light
litejet
litterrobot
local_file
local_ip
locative
lock
logbook
logentries
logger
logi_circle
london_air
lookin
lovelace
luftdaten
lutron_caseta
lyric
mailbox
mailgun
manual
manual_mqtt
marytts
maxcube
mazda
media_player
media_source
melcloud
melissa
meraki
met
met_eireann
meteo_france
meteoclimatic
metoffice
mfi
mhz19
microsoft_face
microsoft_face_detect
microsoft_face_identify
mikrotik
mill
min_max
minecraft_server
minio
mobile_app
mochad
modbus
modem_callerid
modern_forms
mold_indicator
monoprice
moon
motion_blinds
motioneye
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
mullvad
mutesync
my
myq
mysensors
mythicbeastsdns
nam
namecheapdns
nanoleaf
neato
ness_alarm
nest
netatmo
netgear
network
nexia
nextbus
nfandroidtv
nightscout
nina
nmap_tracker
no_ip
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nws
nx584
nzbget
octoprint
omnilogic
onboarding
oncue
ondilo_ico
onewire
onvif
open_meteo
openalpr_cloud
openalpr_local
openerz
opengarage
openhardwaremonitor
opentherm_gw
openuv
openweathermap
opnsense
overkiz
ovo_energy
owntracks
ozw
p1_monitor
panasonic_viera
panel_custom
panel_iframe
persistent_notification
person
philips_js
pi_hole
picnic
pilight
ping
plaato
plant
plex
plugwise
plum_lightpad
point
poolsense
powerwall
profiler
progettihwsw
prometheus
prosegur
proximity
ps4
push
pushbullet
pvoutput
pvpc_hourly_pricing
python_script
qld_bushfire
qwikswitch
rachio
radarr
__init__.py
test_sensor.py
rainforest_eagle
rainmachine
random
rdw
recollect_waste
recorder
reddit
remember_the_milk
remote
renault
rest
rest_command
rflink
rfxtrx
ridwell
ring
risco
rituals_perfume_genie
rmvtransport
roku
roomba
roon
rpi_power
rss_feed_template
rtsp_to_webrtc
ruckus_unleashed
safe_mode
samsungtv
scene
screenlogic
script
search
season
select
sense
senseme
sensibo
sensor
sentry
seventeentrack
sharkiq
shell_command
shelly
shopping_list
sia
sigfox
sighthound
signal_messenger
simplisafe
simulated
siren
slack
sleepiq
sma
smappee
smart_meter_texas
smarthab
smartthings
smarttub
smhi
smtp
snips
solaredge
solarlog
soma
somfy
somfy_mylink
sonarr
songpal
sonos
soundtouch
spaceapi
spc
speedtestdotnet
spider
spotify
sql
squeezebox
srp_energy
ssdp
starline
startca
statistics
statsd
steamist
stookalert
stream
stt
subaru
sun
surepetcare
switch
switchbot
switcher_kis
syncthing
syncthru
synology_dsm
system_bridge
system_health
system_log
tado
tag
tailscale
tasmota
tcp
telegram
tellduslive
template
tesla_wall_connector
threshold
tibber
tile
time_date
timer
tod
tolo
tomato
toon
totalconnect
tplink
traccar
trace
tractive
tradfri
trafikverket_weatherstation
transmission
transport_nsw
trend
tts
tuya
twentemilieu
twilio
twinkly
twitch
uk_transport
unifi
unifi_direct
unifiprotect
universal
upb
upcloud
updater
upnp
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
vacuum
vallox
velbus
venstar
vera
verisure
version
vesync
vicare
vilfo
vizio
vlc_telnet
voicerss
volumio
vultr
wake_on_lan
wallbox
water_heater
watttime
waze_travel_time
weather
webhook
webostv
websocket_api
wemo
whirlpool
whois
wiffi
wilight
withings
wled
wolflink
workday
worldclock
wsdot
xbox
xiaomi
xiaomi_aqara
xiaomi_miio
yale_smart_alarm
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
youless
zeroconf
zerproc
zha
zodiac
zone
zwave
zwave_js
__init__.py
conftest.py
fixtures
hassfest
helpers
mock
resources
scripts
test_util
testing_config
util
__init__.py
bandit.yaml
common.py
conftest.py
ignore_uncaught_exceptions.py
test_bootstrap.py
test_config.py
test_config_entries.py
test_core.py
test_data_entry_flow.py
test_exceptions.py
test_loader.py
test_main.py
test_requirements.py
test_runner.py
test_setup.py
test_test_fixtures.py
.core_files.yaml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.ignore
.pre-commit-config.yaml
.prettierignore
.readthedocs.yml
.strict-typing
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
build.yaml
codecov.yml
mypy.ini
pyproject.toml
requirements.txt
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
setup.cfg
setup.py
tox.ini
core/tests/components/radarr/test_sensor.py
2021-03-20 13:55:10 +01:00

442 lines
15 KiB
Python

"""The tests for the Radarr platform."""
from unittest.mock import patch
import pytest
from homeassistant.const import DATA_GIGABYTES
from homeassistant.setup import async_setup_component
def mocked_exception(*args, **kwargs):
"""Mock exception thrown by requests.get."""
raise OSError
def mocked_requests_get(*args, **kwargs):
"""Mock requests.get invocations."""
class MockResponse:
"""Class to represent a mocked response."""
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
url = str(args[0])
if "api/calendar" in url:
return MockResponse(
[
{
"title": "Resident Evil",
"sortTitle": "resident evil final chapter",
"sizeOnDisk": 0,
"status": "announced",
"overview": "Alice, Jill, Claire, Chris, Leon, Ada, and...",
"inCinemas": "2017-01-25T00:00:00Z",
"physicalRelease": "2017-01-27T00:00:00Z",
"images": [
{
"coverType": "poster",
"url": (
"/radarr/MediaCover/12/poster.jpg"
"?lastWrite=636208663600000000"
),
},
{
"coverType": "banner",
"url": (
"/radarr/MediaCover/12/banner.jpg"
"?lastWrite=636208663600000000"
),
},
],
"website": "",
"downloaded": "false",
"year": 2017,
"hasFile": "false",
"youTubeTrailerId": "B5yxr7lmxhg",
"studio": "Impact Pictures",
"path": "/path/to/Resident Evil The Final Chapter (2017)",
"profileId": 3,
"monitored": "false",
"runtime": 106,
"lastInfoSync": "2017-01-24T14:52:40.315434Z",
"cleanTitle": "residentevilfinalchapter",
"imdbId": "tt2592614",
"tmdbId": 173897,
"titleSlug": "resident-evil-the-final-chapter-2017",
"genres": ["Action", "Horror", "Science Fiction"],
"tags": [],
"added": "2017-01-24T14:52:39.989964Z",
"ratings": {"votes": 363, "value": 4.3},
"alternativeTitles": ["Resident Evil: Rising"],
"qualityProfileId": 3,
"id": 12,
}
],
200,
)
if "api/command" in url:
return MockResponse(
[
{
"name": "RescanMovie",
"startedOn": "0001-01-01T00:00:00Z",
"stateChangeTime": "2014-02-05T05:09:09.2366139Z",
"sendUpdatesToClient": "true",
"state": "pending",
"id": 24,
}
],
200,
)
if "api/movie" in url:
return MockResponse(
[
{
"title": "Assassin's Creed",
"sortTitle": "assassins creed",
"sizeOnDisk": 0,
"status": "released",
"overview": "Lynch discovers he is a descendant of...",
"inCinemas": "2016-12-21T00:00:00Z",
"images": [
{
"coverType": "poster",
"url": (
"/radarr/MediaCover/1/poster.jpg"
"?lastWrite=636200219330000000"
),
},
{
"coverType": "banner",
"url": (
"/radarr/MediaCover/1/banner.jpg"
"?lastWrite=636200219340000000"
),
},
],
"website": "https://www.ubisoft.com/en-US/",
"downloaded": "false",
"year": 2016,
"hasFile": "false",
"youTubeTrailerId": "pgALJgMjXN4",
"studio": "20th Century Fox",
"path": "/path/to/Assassin's Creed (2016)",
"profileId": 6,
"monitored": "true",
"runtime": 115,
"lastInfoSync": "2017-01-23T22:05:32.365337Z",
"cleanTitle": "assassinscreed",
"imdbId": "tt2094766",
"tmdbId": 121856,
"titleSlug": "assassins-creed-121856",
"genres": ["Action", "Adventure", "Fantasy", "Science Fiction"],
"tags": [],
"added": "2017-01-14T20:18:52.938244Z",
"ratings": {"votes": 711, "value": 5.2},
"alternativeTitles": ["Assassin's Creed: The IMAX Experience"],
"qualityProfileId": 6,
"id": 1,
}
],
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": "0.2.0.210",
"buildTime": "2017-01-22T23:12:49Z",
"isDebug": "false",
"isProduction": "true",
"isAdmin": "false",
"isUserInteractive": "false",
"startupPath": "/path/to/radarr",
"appData": "/path/to/radarr/data",
"osVersion": "4.8.13.1",
"isMonoRuntime": "true",
"isMono": "true",
"isLinux": "true",
"isOsx": "false",
"isWindows": "false",
"branch": "develop",
"authentication": "forms",
"sqliteVersion": "3.16.2",
"urlBase": "",
"runtimeVersion": (
"4.6.1 (Stable 4.6.1.3/abb06f1 Mon Oct 3 07:57:59 UTC 2016)"
),
},
200,
)
return MockResponse({"error": "Unauthorized"}, 401)
async def test_diskspace_no_paths(hass):
"""Test getting all disk space."""
config = {
"sensor": {
"platform": "radarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": [],
"monitored_conditions": ["diskspace"],
}
}
with patch(
"requests.get",
side_effect=mocked_requests_get,
):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
entity = hass.states.get("sensor.radarr_disk_space")
assert entity is not None
assert entity.state == "263.10"
assert entity.attributes["icon"] == "mdi:harddisk"
assert entity.attributes["unit_of_measurement"] == DATA_GIGABYTES
assert entity.attributes["friendly_name"] == "Radarr Disk Space"
assert entity.attributes["/data"] == "263.10/465.42GB (56.53%)"
async def test_diskspace_paths(hass):
"""Test getting diskspace for included paths."""
config = {
"sensor": {
"platform": "radarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["diskspace"],
}
}
with patch(
"requests.get",
side_effect=mocked_requests_get,
):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
entity = hass.states.get("sensor.radarr_disk_space")
assert entity is not None
assert entity.state == "263.10"
assert entity.attributes["icon"] == "mdi:harddisk"
assert entity.attributes["unit_of_measurement"] == DATA_GIGABYTES
assert entity.attributes["friendly_name"] == "Radarr Disk Space"
assert entity.attributes["/data"] == "263.10/465.42GB (56.53%)"
async def test_commands(hass):
"""Test getting running commands."""
config = {
"sensor": {
"platform": "radarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["commands"],
}
}
with patch(
"requests.get",
side_effect=mocked_requests_get,
):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
entity = hass.states.get("sensor.radarr_commands")
assert entity is not None
assert int(entity.state) == 1
assert entity.attributes["icon"] == "mdi:code-braces"
assert entity.attributes["unit_of_measurement"] == "Commands"
assert entity.attributes["friendly_name"] == "Radarr Commands"
assert entity.attributes["RescanMovie"] == "pending"
async def test_movies(hass):
"""Test getting the number of movies."""
config = {
"sensor": {
"platform": "radarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["movies"],
}
}
with patch(
"requests.get",
side_effect=mocked_requests_get,
):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
entity = hass.states.get("sensor.radarr_movies")
assert entity is not None
assert int(entity.state) == 1
assert entity.attributes["icon"] == "mdi:television"
assert entity.attributes["unit_of_measurement"] == "Movies"
assert entity.attributes["friendly_name"] == "Radarr Movies"
assert entity.attributes["Assassin's Creed (2016)"] == "false"
async def test_upcoming_multiple_days(hass):
"""Test the upcoming movies for multiple days."""
config = {
"sensor": {
"platform": "radarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["upcoming"],
}
}
with patch(
"requests.get",
side_effect=mocked_requests_get,
):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
entity = hass.states.get("sensor.radarr_upcoming")
assert entity is not None
assert int(entity.state) == 1
assert entity.attributes["icon"] == "mdi:television"
assert entity.attributes["unit_of_measurement"] == "Movies"
assert entity.attributes["friendly_name"] == "Radarr Upcoming"
assert entity.attributes["Resident Evil (2017)"] == "2017-01-27T00:00:00Z"
@pytest.mark.skip
async def test_upcoming_today(hass):
"""Test filtering for a single day.
Radarr needs to respond with at least 2 days.
"""
config = {
"sensor": {
"platform": "radarr",
"api_key": "foo",
"days": "1",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["upcoming"],
}
}
with patch(
"requests.get",
side_effect=mocked_requests_get,
):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
entity = hass.states.get("sensor.radarr_upcoming")
assert int(entity.state) == 1
assert entity.attributes["icon"] == "mdi:television"
assert entity.attributes["unit_of_measurement"] == "Movies"
assert entity.attributes["friendly_name"] == "Radarr Upcoming"
assert entity.attributes["Resident Evil (2017)"] == "2017-01-27T00:00:00Z"
async def test_system_status(hass):
"""Test the getting of the system status."""
config = {
"sensor": {
"platform": "radarr",
"api_key": "foo",
"days": "2",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["status"],
}
}
with patch(
"requests.get",
side_effect=mocked_requests_get,
):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
entity = hass.states.get("sensor.radarr_status")
assert entity is not None
assert entity.state == "0.2.0.210"
assert entity.attributes["icon"] == "mdi:information"
assert entity.attributes["friendly_name"] == "Radarr Status"
assert entity.attributes["osVersion"] == "4.8.13.1"
async def test_ssl(hass):
"""Test SSL being enabled."""
config = {
"sensor": {
"platform": "radarr",
"api_key": "foo",
"days": "1",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["upcoming"],
"ssl": "true",
}
}
with patch(
"requests.get",
side_effect=mocked_requests_get,
):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
entity = hass.states.get("sensor.radarr_upcoming")
assert entity is not None
assert int(entity.state) == 1
assert entity.attributes["icon"] == "mdi:television"
assert entity.attributes["unit_of_measurement"] == "Movies"
assert entity.attributes["friendly_name"] == "Radarr Upcoming"
assert entity.attributes["Resident Evil (2017)"] == "2017-01-27T00:00:00Z"
async def test_exception_handling(hass):
"""Test exception being handled."""
config = {
"sensor": {
"platform": "radarr",
"api_key": "foo",
"days": "1",
"unit": DATA_GIGABYTES,
"include_paths": ["/data"],
"monitored_conditions": ["upcoming"],
}
}
with patch(
"requests.get",
side_effect=mocked_exception,
):
assert await async_setup_component(hass, "sensor", config)
await hass.async_block_till_done()
entity = hass.states.get("sensor.radarr_upcoming")
assert entity is not None
assert entity.state == "unavailable"