core/tests/components/darksky/test_sensor.py

171 lines
5.8 KiB
Python
Raw Normal View History

"""The tests for the Dark Sky platform."""
import re
import unittest
from unittest.mock import MagicMock, patch
from datetime import timedelta
from requests.exceptions import HTTPError
import requests_mock
import forecastio
Consolidate all platforms that have tests (#22109) * Moved climate components with tests into platform dirs. * Updated tests from climate component. * Moved binary_sensor components with tests into platform dirs. * Updated tests from binary_sensor component. * Moved calendar components with tests into platform dirs. * Updated tests from calendar component. * Moved camera components with tests into platform dirs. * Updated tests from camera component. * Moved cover components with tests into platform dirs. * Updated tests from cover component. * Moved device_tracker components with tests into platform dirs. * Updated tests from device_tracker component. * Moved fan components with tests into platform dirs. * Updated tests from fan component. * Moved geo_location components with tests into platform dirs. * Updated tests from geo_location component. * Moved image_processing components with tests into platform dirs. * Updated tests from image_processing component. * Moved light components with tests into platform dirs. * Updated tests from light component. * Moved lock components with tests into platform dirs. * Moved media_player components with tests into platform dirs. * Updated tests from media_player component. * Moved scene components with tests into platform dirs. * Moved sensor components with tests into platform dirs. * Updated tests from sensor component. * Moved switch components with tests into platform dirs. * Updated tests from sensor component. * Moved vacuum components with tests into platform dirs. * Updated tests from vacuum component. * Moved weather components with tests into platform dirs. * Fixed __init__.py files * Fixes for stuff moved as part of this branch. * Fix stuff needed to merge with balloob's branch. * Formatting issues. * Missing __init__.py files. * Fix-ups * Fixup * Regenerated requirements. * Linting errors fixed. * Fixed more broken tests. * Missing init files. * Fix broken tests. * More broken tests * There seems to be a thread race condition. I suspect the logger stuff is running in another thread, which means waiting until the aio loop is done is missing the log messages. Used sleep instead because that allows the logger thread to run. I think the api_streams sensor might not be thread safe. * Disabled tests, will remove sensor in #22147 * Updated coverage and codeowners.
2019-03-19 06:07:39 +00:00
from homeassistant.components.darksky import sensor as darksky
from homeassistant.setup import setup_component
from tests.common import (load_fixture, get_test_home_assistant,
MockDependency)
VALID_CONFIG_MINIMAL = {
'sensor': {
'platform': 'darksky',
'api_key': 'foo',
'forecast': [1, 2],
'hourly_forecast': [1, 2],
'monitored_conditions': ['summary', 'icon', 'temperature_high'],
'scan_interval': timedelta(seconds=120),
}
}
INVALID_CONFIG_MINIMAL = {
'sensor': {
'platform': 'darksky',
'api_key': 'foo',
'forecast': [1, 2],
'hourly_forecast': [1, 2],
'monitored_conditions': ['sumary', 'iocn', 'temperature_high'],
'scan_interval': timedelta(seconds=120),
}
}
VALID_CONFIG_LANG_DE = {
'sensor': {
'platform': 'darksky',
'api_key': 'foo',
'forecast': [1, 2],
'hourly_forecast': [1, 2],
'units': 'us',
'language': 'de',
'monitored_conditions': ['summary', 'icon', 'temperature_high',
'minutely_summary', 'hourly_summary',
'daily_summary', 'humidity', ],
'scan_interval': timedelta(seconds=120),
}
}
INVALID_CONFIG_LANG = {
'sensor': {
'platform': 'darksky',
'api_key': 'foo',
'forecast': [1, 2],
'hourly_forecast': [1, 2],
'language': 'yz',
'monitored_conditions': ['summary', 'icon', 'temperature_high'],
'scan_interval': timedelta(seconds=120),
}
}
def load_forecastMock(key, lat, lon,
units, lang): # pylint: disable=invalid-name
"""Mock darksky forecast loading."""
return ''
class TestDarkSkySetup(unittest.TestCase):
"""Test the Dark Sky platform."""
def add_entities(self, new_entities, update_before_add=False):
"""Mock add entities."""
if update_before_add:
for entity in new_entities:
entity.update()
for entity in new_entities:
self.entities.append(entity)
def setUp(self):
"""Initialize values for this testcase class."""
self.hass = get_test_home_assistant()
self.key = 'foo'
self.lat = self.hass.config.latitude = 37.8267
self.lon = self.hass.config.longitude = -122.423
self.entities = []
2017-01-07 00:47:25 +00:00
def tearDown(self): # pylint: disable=invalid-name
"""Stop everything that was started."""
self.hass.stop()
@MockDependency('forecastio')
@patch('forecastio.load_forecast', new=load_forecastMock)
def test_setup_with_config(self, mock_forecastio):
"""Test the platform setup with configuration."""
setup_component(self.hass, 'sensor', VALID_CONFIG_MINIMAL)
state = self.hass.states.get('sensor.dark_sky_summary')
assert state is not None
@MockDependency('forecastio')
@patch('forecastio.load_forecast', new=load_forecastMock)
def test_setup_with_invalid_config(self, mock_forecastio):
"""Test the platform setup with invalid configuration."""
setup_component(self.hass, 'sensor', INVALID_CONFIG_MINIMAL)
state = self.hass.states.get('sensor.dark_sky_summary')
assert state is None
@MockDependency('forecastio')
@patch('forecastio.load_forecast', new=load_forecastMock)
def test_setup_with_language_config(self, mock_forecastio):
"""Test the platform setup with language configuration."""
setup_component(self.hass, 'sensor', VALID_CONFIG_LANG_DE)
state = self.hass.states.get('sensor.dark_sky_summary')
assert state is not None
@MockDependency('forecastio')
@patch('forecastio.load_forecast', new=load_forecastMock)
def test_setup_with_invalid_language_config(self, mock_forecastio):
"""Test the platform setup with language configuration."""
setup_component(self.hass, 'sensor', INVALID_CONFIG_LANG)
state = self.hass.states.get('sensor.dark_sky_summary')
assert state is None
@patch('forecastio.api.get_forecast')
def test_setup_bad_api_key(self, mock_get_forecast):
"""Test for handling a bad API key."""
# The Dark Sky API wrapper that we use raises an HTTP error
# when you try to use a bad (or no) API key.
url = 'https://api.darksky.net/forecast/{}/{},{}?units=auto'.format(
self.key, str(self.lat), str(self.lon)
)
msg = '400 Client Error: Bad Request for url: {}'.format(url)
mock_get_forecast.side_effect = HTTPError(msg,)
response = darksky.setup_platform(
self.hass,
VALID_CONFIG_MINIMAL['sensor'],
MagicMock()
)
assert not response
@requests_mock.Mocker()
@patch('forecastio.api.get_forecast', wraps=forecastio.api.get_forecast)
def test_setup(self, mock_req, mock_get_forecast):
"""Test for successfully setting up the forecast.io platform."""
uri = (r'https://api.(darksky.net|forecast.io)\/forecast\/(\w+)\/'
r'(-?\d+\.?\d*),(-?\d+\.?\d*)')
mock_req.get(re.compile(uri), text=load_fixture('darksky.json'))
assert setup_component(self.hass, 'sensor', VALID_CONFIG_MINIMAL)
assert mock_get_forecast.called
assert mock_get_forecast.call_count == 1
assert len(self.hass.states.entity_ids()) == 12
state = self.hass.states.get('sensor.dark_sky_summary')
assert state is not None
assert state.state == 'Clear'
assert state.attributes.get('friendly_name') == \
'Dark Sky Summary'