diff --git a/homeassistant/components/sensor/sonarr.py b/homeassistant/components/sensor/sonarr.py index 9f4ed3d0581..62f33556c17 100644 --- a/homeassistant/components/sensor/sonarr.py +++ b/homeassistant/components/sensor/sonarr.py @@ -86,6 +86,7 @@ class SonarrSensor(Entity): self.ssl = 's' if conf.get(CONF_SSL) else '' # Object data + self.data = [] self._tz = timezone(str(hass.config.time_zone)) self.type = sensor_type self._name = SENSOR_TYPES[self.type][0] @@ -96,16 +97,24 @@ class SonarrSensor(Entity): self._icon = SENSOR_TYPES[self.type][2] # Update sensor + self._available = False self.update() def update(self): """Update the data for the sensor.""" start = get_date(self._tz) end = get_date(self._tz, self.days) - res = requests.get( - ENDPOINTS[self.type].format( - self.ssl, self.host, self.port, self.apikey, start, end), - timeout=5) + try: + res = requests.get( + ENDPOINTS[self.type].format( + self.ssl, self.host, self.port, self.apikey, start, end), + timeout=5) + except OSError: + _LOGGER.error('Host %s is not available', self.host) + self._available = False + self._state = None + return + if res.status_code == 200: if self.type in ['upcoming', 'queue', 'series', 'commands']: if self.days == 1 and self.type == 'upcoming': @@ -146,6 +155,7 @@ class SonarrSensor(Entity): self._unit ) ) + self._available = True @property def name(self): @@ -157,6 +167,11 @@ class SonarrSensor(Entity): """Return sensor state.""" return self._state + @property + def available(self): + """Return sensor availability.""" + return self._available + @property def unit_of_measurement(self): """Return the unit of the sensor.""" diff --git a/tests/components/sensor/test_sonarr.py b/tests/components/sensor/test_sonarr.py index c44d01f3ce0..cc9186677dc 100644 --- a/tests/components/sensor/test_sonarr.py +++ b/tests/components/sensor/test_sonarr.py @@ -10,6 +10,11 @@ from homeassistant.components.sensor import sonarr from tests.common import get_test_home_assistant +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: @@ -814,3 +819,23 @@ class TestSonarrSetup(unittest.TestCase): 'S04E11', device.device_state_attributes["Bob's Burgers"] ) + + @unittest.mock.patch('requests.get', side_effect=mocked_exception) + def test_exception_handling(self, req_mock): + """Tests exception being handled""" + config = { + 'platform': 'sonarr', + 'api_key': 'foo', + 'days': '1', + 'unit': 'GB', + "include_paths": [ + '/data' + ], + 'monitored_conditions': [ + 'upcoming' + ] + } + sonarr.setup_platform(self.hass, config, self.add_devices, None) + for device in self.DEVICES: + device.update() + self.assertEqual(None, device.state)