Swedish weather institute weather component (#16717)

* SMHI Component

* Clean up typos

* Fixed default values first config to home location (tests will follow)

* Fixed tests and removed unused function

* Minor fixup after comments from @kane610

* add support for precipitation in forecast

* Removed old async_step_init not needed.
This commit is contained in:
Tomas Hellström authored and Martin Hjelmare committed 2018-10-08 23:54:55 +02:00
1 parent 56a43436d7
commit 540d22d603
18 files changed
+2716 -2

No files matched your search

+1
View File
@@ -0,0 +1 @@
"""Tests for the SMHI component."""
+11
View File
@@ -0,0 +1,11 @@
"""Common test utilities."""
from unittest.mock import Mock
class AsyncMock(Mock):
"""Implements Mock async."""
# pylint: disable=W0235
async def __call__(self, *args, **kwargs):
"""Hack for async support for Mock."""
return super(AsyncMock, self).__call__(*args, **kwargs)
+276
View File
@@ -0,0 +1,276 @@
"""Tests for SMHI config flow."""
from unittest.mock import Mock, patch
from smhi.smhi_lib import Smhi as SmhiApi, SmhiForecastException
from tests.common import mock_coro
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE
from homeassistant.components.smhi import config_flow
# pylint: disable=W0212
async def test_homeassistant_location_exists() -> None:
"""Test if homeassistant location exists it should return True."""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
with patch.object(flow, '_check_location',
return_value=mock_coro(True)):
# Test exists
hass.config.location_name = 'Home'
hass.config.latitude = 17.8419
hass.config.longitude = 59.3262
assert await flow._homeassistant_location_exists() is True
# Test not exists
hass.config.location_name = None
hass.config.latitude = 0
hass.config.longitude = 0
assert await flow._homeassistant_location_exists() is False
async def test_name_in_configuration_exists() -> None:
"""Test if home location exists in configuration."""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
# Test exists
hass.config.location_name = 'Home'
hass.config.latitude = 17.8419
hass.config.longitude = 59.3262
# Check not exists
with patch.object(config_flow, 'smhi_locations',
return_value={
'test': 'something', 'test2': 'something else'
}):
assert flow._name_in_configuration_exists('no_exist_name') is False
# Check exists
with patch.object(config_flow, 'smhi_locations',
return_value={
'test': 'something', 'name_exist': 'config'
}):
assert flow._name_in_configuration_exists('name_exist') is True
def test_smhi_locations(hass) -> None:
"""Test return empty set."""
locations = config_flow.smhi_locations(hass)
assert not locations
async def test_show_config_form() -> None:
"""Test show configuration form."""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
result = await flow._show_config_form()
assert result['type'] == 'form'
assert result['step_id'] == 'user'
async def test_show_config_form_default_values() -> None:
"""Test show configuration form."""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
result = await flow._show_config_form(
name="test", latitude='65', longitude='17')
assert result['type'] == 'form'
assert result['step_id'] == 'user'
async def test_flow_with_home_location(hass) -> None:
"""Test config flow .
Tests the flow when a default location is configured
then it should return a form with default values
"""
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
with patch.object(flow, '_check_location',
return_value=mock_coro(True)):
hass.config.location_name = 'Home'
hass.config.latitude = 17.8419
hass.config.longitude = 59.3262
result = await flow.async_step_user()
assert result['type'] == 'form'
assert result['step_id'] == 'user'
async def test_flow_show_form() -> None:
"""Test show form scenarios first time.
Test when the form should show when no configurations exists
"""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
# Test show form when home assistant config exists and
# home is already configured, then new config is allowed
with \
patch.object(flow, '_show_config_form',
return_value=mock_coro()) as config_form, \
patch.object(flow, '_homeassistant_location_exists',
return_value=mock_coro(True)), \
patch.object(config_flow, 'smhi_locations',
return_value={
'test': 'something', 'name_exist': 'config'
}):
await flow.async_step_user()
assert len(config_form.mock_calls) == 1
# Test show form when home assistant config not and
# home is not configured
with \
patch.object(flow, '_show_config_form',
return_value=mock_coro()) as config_form, \
patch.object(flow, '_homeassistant_location_exists',
return_value=mock_coro(False)), \
patch.object(config_flow, 'smhi_locations',
return_value={
'test': 'something', 'name_exist': 'config'
}):
await flow.async_step_user()
assert len(config_form.mock_calls) == 1
async def test_flow_show_form_name_exists() -> None:
"""Test show form if name already exists.
Test when the form should show when no configurations exists
"""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
test_data = {'name': 'home', CONF_LONGITUDE: '0', CONF_LATITUDE: '0'}
# Test show form when home assistant config exists and
# home is already configured, then new config is allowed
with \
patch.object(flow, '_show_config_form',
return_value=mock_coro()) as config_form, \
patch.object(flow, '_name_in_configuration_exists',
return_value=True), \
patch.object(config_flow, 'smhi_locations',
return_value={
'test': 'something', 'name_exist': 'config'
}), \
patch.object(flow, '_check_location',
return_value=mock_coro(True)):
await flow.async_step_user(user_input=test_data)
assert len(config_form.mock_calls) == 1
assert len(flow._errors) == 1
async def test_flow_entry_created_from_user_input() -> None:
"""Test that create data from user input.
Test when the form should show when no configurations exists
"""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
test_data = {'name': 'home', CONF_LONGITUDE: '0', CONF_LATITUDE: '0'}
# Test that entry created when user_input name not exists
with \
patch.object(flow, '_show_config_form',
return_value=mock_coro()) as config_form, \
patch.object(flow, '_name_in_configuration_exists',
return_value=False), \
patch.object(flow, '_homeassistant_location_exists',
return_value=mock_coro(False)), \
patch.object(config_flow, 'smhi_locations',
return_value={
'test': 'something', 'name_exist': 'config'
}), \
patch.object(flow, '_check_location',
return_value=mock_coro(True)):
result = await flow.async_step_user(user_input=test_data)
assert result['type'] == 'create_entry'
assert result['data'] == test_data
assert not config_form.mock_calls
async def test_flow_entry_created_user_input_faulty() -> None:
"""Test that create data from user input and are faulty.
Test when the form should show when user puts faulty location
in the config gui. Then the form should show with error
"""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
test_data = {'name': 'home', CONF_LONGITUDE: '0', CONF_LATITUDE: '0'}
# Test that entry created when user_input name not exists
with \
patch.object(flow, '_check_location',
return_value=mock_coro(True)), \
patch.object(flow, '_show_config_form',
return_value=mock_coro()) as config_form, \
patch.object(flow, '_name_in_configuration_exists',
return_value=False), \
patch.object(flow, '_homeassistant_location_exists',
return_value=mock_coro(False)), \
patch.object(config_flow, 'smhi_locations',
return_value={
'test': 'something', 'name_exist': 'config'
}), \
patch.object(flow, '_check_location',
return_value=mock_coro(False)):
await flow.async_step_user(user_input=test_data)
assert len(config_form.mock_calls) == 1
assert len(flow._errors) == 1
async def test_check_location_correct() -> None:
"""Test check location when correct input."""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
with \
patch.object(config_flow.aiohttp_client, 'async_get_clientsession'),\
patch.object(SmhiApi, 'async_get_forecast',
return_value=mock_coro()):
assert await flow._check_location('58', '17') is True
async def test_check_location_faulty() -> None:
"""Test check location when faulty input."""
hass = Mock()
flow = config_flow.SmhiFlowHandler()
flow.hass = hass
with \
patch.object(config_flow.aiohttp_client,
'async_get_clientsession'), \
patch.object(SmhiApi, 'async_get_forecast',
side_effect=SmhiForecastException()):
assert await flow._check_location('58', '17') is False
+39
View File
@@ -0,0 +1,39 @@
"""Test SMHI component setup process."""
from unittest.mock import Mock
from homeassistant.components import smhi
from .common import AsyncMock
TEST_CONFIG = {
"config": {
"name": "0123456789ABCDEF",
"longitude": "62.0022",
"latitude": "17.0022"
}
}
async def test_setup_always_return_true() -> None:
"""Test async_setup always returns True."""
hass = Mock()
# Returns true with empty config
assert await smhi.async_setup(hass, {}) is True
# Returns true with a config provided
assert await smhi.async_setup(hass, TEST_CONFIG) is True
async def test_forward_async_setup_entry() -> None:
"""Test that it will forward setup entry."""
hass = Mock()
assert await smhi.async_setup_entry(hass, {}) is True
assert len(hass.config_entries.async_forward_entry_setup.mock_calls) == 1
async def test_forward_async_unload_entry() -> None:
"""Test that it will forward unload entry."""
hass = AsyncMock()
assert await smhi.async_unload_entry(hass, {}) is True
assert len(hass.config_entries.async_forward_entry_unload.mock_calls) == 1
+292
View File
@@ -0,0 +1,292 @@
"""Test for the smhi weather entity."""
import asyncio
import logging
from datetime import datetime, timezone
from unittest.mock import Mock, patch
from homeassistant.components.weather import (
ATTR_FORECAST_CONDITION, ATTR_FORECAST_TEMP, ATTR_FORECAST_TIME,
ATTR_WEATHER_TEMPERATURE, ATTR_WEATHER_HUMIDITY, ATTR_WEATHER_PRESSURE,
ATTR_FORECAST_TEMP_LOW, ATTR_WEATHER_VISIBILITY, ATTR_WEATHER_ATTRIBUTION,
ATTR_WEATHER_WIND_BEARING, ATTR_WEATHER_WIND_SPEED,
ATTR_FORECAST_PRECIPITATION, smhi as weather_smhi,
DOMAIN as WEATHER_DOMAIN)
from homeassistant.const import TEMP_CELSIUS
from homeassistant.core import HomeAssistant
from tests.common import load_fixture, MockConfigEntry
from homeassistant.components.smhi.const import ATTR_SMHI_CLOUDINESS
_LOGGER = logging.getLogger(__name__)
TEST_CONFIG = {
"name": "test",
"longitude": "17.84197",
"latitude": "59.32624"
}
async def test_setup_hass(hass: HomeAssistant, aioclient_mock) -> None:
"""Test for successfully setting up the smhi platform.
This test are deeper integrated with the core. Since only
config_flow is used the component are setup with
"async_forward_entry_setup". The actual result are tested
with the entity state rather than "per function" unity tests
"""
from smhi.smhi_lib import APIURL_TEMPLATE
uri = APIURL_TEMPLATE.format(
TEST_CONFIG['longitude'], TEST_CONFIG['latitude'])
api_response = load_fixture('smhi.json')
aioclient_mock.get(uri, text=api_response)
entry = MockConfigEntry(domain='smhi', data=TEST_CONFIG)
await hass.config_entries.async_forward_entry_setup(entry, WEATHER_DOMAIN)
assert aioclient_mock.call_count == 1
# Testing the actual entity state for
# deeper testing than normal unity test
state = hass.states.get('weather.smhi_test')
assert state.state == 'sunny'
assert state.attributes[ATTR_SMHI_CLOUDINESS] == 50
assert state.attributes[ATTR_WEATHER_ATTRIBUTION].find('SMHI') >= 0
assert state.attributes[ATTR_WEATHER_HUMIDITY] == 55
assert state.attributes[ATTR_WEATHER_PRESSURE] == 1024
assert state.attributes[ATTR_WEATHER_TEMPERATURE] == 17
assert state.attributes[ATTR_WEATHER_VISIBILITY] == 50
assert state.attributes[ATTR_WEATHER_WIND_SPEED] == 7
assert state.attributes[ATTR_WEATHER_WIND_BEARING] == 134
_LOGGER.error(state.attributes)
assert len(state.attributes['forecast']) == 1
forecast = state.attributes['forecast'][0]
assert forecast[ATTR_FORECAST_TIME] == datetime(2018, 9, 2, 12, 0,
tzinfo=timezone.utc)
assert forecast[ATTR_FORECAST_TEMP] == 20
assert forecast[ATTR_FORECAST_TEMP_LOW] == 6
assert forecast[ATTR_FORECAST_PRECIPITATION] == 0
assert forecast[ATTR_FORECAST_CONDITION] == 'partlycloudy'
async def test_setup_plattform(hass):
"""Test that setup plattform does nothing."""
assert await weather_smhi.async_setup_platform(hass, None, None) is None
def test_properties_no_data(hass: HomeAssistant) -> None:
"""Test properties when no API data available."""
weather = weather_smhi.SmhiWeather('name', '10', '10')
weather.hass = hass
assert weather.name == 'name'
assert weather.should_poll is True
assert weather.temperature is None
assert weather.humidity is None
assert weather.wind_speed is None
assert weather.wind_bearing is None
assert weather.visibility is None
assert weather.pressure is None
assert weather.cloudiness is None
assert weather.condition is None
assert weather.forecast is None
assert weather.temperature_unit == TEMP_CELSIUS
# pylint: disable=W0212
def test_properties_unknown_symbol() -> None:
"""Test behaviour when unknown symbol from API."""
hass = Mock()
data = Mock()
data.temperature = 5
data.mean_precipitation = 1
data.humidity = 5
data.wind_speed = 10
data.wind_direction = 180
data.horizontal_visibility = 6
data.pressure = 1008
data.cloudiness = 52
data.symbol = 100 # Faulty symbol
data.valid_time = datetime(2018, 1, 1, 0, 1, 2)
data2 = Mock()
data2.temperature = 5
data2.mean_precipitation = 1
data2.humidity = 5
data2.wind_speed = 10
data2.wind_direction = 180
data2.horizontal_visibility = 6
data2.pressure = 1008
data2.cloudiness = 52
data2.symbol = 100 # Faulty symbol
data2.valid_time = datetime(2018, 1, 1, 12, 1, 2)
data3 = Mock()
data3.temperature = 5
data3.mean_precipitation = 1
data3.humidity = 5
data3.wind_speed = 10
data3.wind_direction = 180
data3.horizontal_visibility = 6
data3.pressure = 1008
data3.cloudiness = 52
data3.symbol = 100 # Faulty symbol
data3.valid_time = datetime(2018, 1, 2, 12, 1, 2)
testdata = [
data,
data2,
data3
]
weather = weather_smhi.SmhiWeather('name', '10', '10')
weather.hass = hass
weather._forecasts = testdata
assert weather.condition is None
forecast = weather.forecast[0]
assert forecast[ATTR_FORECAST_CONDITION] is None
# pylint: disable=W0212
async def test_refresh_weather_forecast_exceeds_retries(hass) -> None:
"""Test the refresh weather forecast function."""
from smhi.smhi_lib import SmhiForecastException
with \
patch.object(hass.helpers.event, 'async_call_later') as call_later, \
patch.object(weather_smhi.SmhiWeather, 'get_weather_forecast',
side_effect=SmhiForecastException()):
weather = weather_smhi.SmhiWeather(
'name', '17.0022', '62.0022')
weather.hass = hass
weather._fail_count = 2
await weather.async_update()
assert weather._forecasts is None
assert not call_later.mock_calls
async def test_refresh_weather_forecast_timeout(hass) -> None:
"""Test timeout exception."""
weather = weather_smhi.SmhiWeather(
'name', '17.0022', '62.0022')
weather.hass = hass
with \
patch.object(hass.helpers.event, 'async_call_later') as call_later, \
patch.object(weather_smhi.SmhiWeather, 'retry_update'), \
patch.object(weather_smhi.SmhiWeather, 'get_weather_forecast',
side_effect=asyncio.TimeoutError):
await weather.async_update()
assert len(call_later.mock_calls) == 1
# Assert we are going to wait RETRY_TIMEOUT seconds
assert call_later.mock_calls[0][1][0] == weather_smhi.RETRY_TIMEOUT
async def test_refresh_weather_forecast_exception() -> None:
"""Test any exception."""
from smhi.smhi_lib import SmhiForecastException
hass = Mock()
weather = weather_smhi.SmhiWeather(
'name', '17.0022', '62.0022')
weather.hass = hass
with \
patch.object(hass.helpers.event, 'async_call_later') as call_later, \
patch.object(weather_smhi, 'async_timeout'), \
patch.object(weather_smhi.SmhiWeather, 'retry_update'), \
patch.object(weather_smhi.SmhiWeather, 'get_weather_forecast',
side_effect=SmhiForecastException()):
hass.async_add_job = Mock()
call_later = hass.helpers.event.async_call_later
await weather.async_update()
assert len(call_later.mock_calls) == 1
# Assert we are going to wait RETRY_TIMEOUT seconds
assert call_later.mock_calls[0][1][0] == weather_smhi.RETRY_TIMEOUT
async def test_retry_update():
"""Test retry function of refresh forecast."""
hass = Mock()
weather = weather_smhi.SmhiWeather(
'name', '17.0022', '62.0022')
weather.hass = hass
with patch.object(weather_smhi.SmhiWeather,
'async_update') as update:
await weather.retry_update()
assert len(update.mock_calls) == 1
def test_condition_class():
"""Test condition class."""
def get_condition(index: int) -> str:
"""Return condition given index."""
return [k for k, v in weather_smhi.CONDITION_CLASSES.items()
if index in v][0]
# SMHI definitions as follows, see
# http://opendata.smhi.se/apidocs/metfcst/parameters.html
# 1. Clear sky
assert get_condition(1) == 'sunny'
# 2. Nearly clear sky
assert get_condition(2) == 'sunny'
# 3. Variable cloudiness
assert get_condition(3) == 'partlycloudy'
# 4. Halfclear sky
assert get_condition(4) == 'partlycloudy'
# 5. Cloudy sky
assert get_condition(5) == 'cloudy'
# 6. Overcast
assert get_condition(6) == 'cloudy'
# 7. Fog
assert get_condition(7) == 'fog'
# 8. Light rain showers
assert get_condition(8) == 'rainy'
# 9. Moderate rain showers
assert get_condition(9) == 'rainy'
# 18. Light rain
assert get_condition(18) == 'rainy'
# 19. Moderate rain
assert get_condition(19) == 'rainy'
# 10. Heavy rain showers
assert get_condition(10) == 'pouring'
# 20. Heavy rain
assert get_condition(20) == 'pouring'
# 21. Thunder
assert get_condition(21) == 'lightning'
# 11. Thunderstorm
assert get_condition(11) == 'lightning-rainy'
# 15. Light snow showers
assert get_condition(15) == 'snowy'
# 16. Moderate snow showers
assert get_condition(16) == 'snowy'
# 17. Heavy snow showers
assert get_condition(17) == 'snowy'
# 25. Light snowfall
assert get_condition(25) == 'snowy'
# 26. Moderate snowfall
assert get_condition(26) == 'snowy'
# 27. Heavy snowfall
assert get_condition(27) == 'snowy'
# 12. Light sleet showers
assert get_condition(12) == 'snowy-rainy'
# 13. Moderate sleet showers
assert get_condition(13) == 'snowy-rainy'
# 14. Heavy sleet showers
assert get_condition(14) == 'snowy-rainy'
# 22. Light sleet
assert get_condition(22) == 'snowy-rainy'
# 23. Moderate sleet
assert get_condition(23) == 'snowy-rainy'
# 24. Heavy sleet
assert get_condition(24) == 'snowy-rainy'