Validate WWLLN window size in config schema (#32621)

* Validate WWLLN window size in config schema

* Cleanup

* Clean up imports

* Fix tests
This commit is contained in:
Aaron Bach 2020-03-09 17:18:39 -06:00 committed by GitHub
parent d4615fd432
commit 9a3c58213b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 18 additions and 52 deletions

View File

@ -1,8 +1,7 @@
{ {
"config": { "config": {
"abort": { "abort": {
"already_configured": "This location is already registered.", "already_configured": "This location is already registered."
"window_too_small": "A too-small window will cause Home Assistant to miss events."
}, },
"step": { "step": {
"user": { "user": {

View File

@ -1,4 +1,6 @@
"""Support for World Wide Lightning Location Network.""" """Support for World Wide Lightning Location Network."""
import logging
from aiowwlln import Client from aiowwlln import Client
import voluptuous as vol import voluptuous as vol
@ -6,14 +8,9 @@ from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_RADIUS from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE, CONF_RADIUS
from homeassistant.helpers import aiohttp_client, config_validation as cv from homeassistant.helpers import aiohttp_client, config_validation as cv
from .const import ( from .const import CONF_WINDOW, DATA_CLIENT, DEFAULT_RADIUS, DEFAULT_WINDOW, DOMAIN
CONF_WINDOW,
DATA_CLIENT, _LOGGER = logging.getLogger(__name__)
DEFAULT_RADIUS,
DEFAULT_WINDOW,
DOMAIN,
LOGGER,
)
CONFIG_SCHEMA = vol.Schema( CONFIG_SCHEMA = vol.Schema(
{ {
@ -26,6 +23,7 @@ CONFIG_SCHEMA = vol.Schema(
cv.time_period, cv.time_period,
cv.positive_timedelta, cv.positive_timedelta,
lambda value: value.total_seconds(), lambda value: value.total_seconds(),
vol.Range(min=DEFAULT_WINDOW.total_seconds()),
), ),
} }
) )
@ -91,7 +89,7 @@ async def async_migrate_entry(hass, config_entry):
default_total_seconds = DEFAULT_WINDOW.total_seconds() default_total_seconds = DEFAULT_WINDOW.total_seconds()
LOGGER.debug("Migrating from version %s", version) _LOGGER.debug("Migrating from version %s", version)
# 1 -> 2: Expanding the default window to 1 hour (if needed): # 1 -> 2: Expanding the default window to 1 hour (if needed):
if version == 1: if version == 1:
@ -99,6 +97,6 @@ async def async_migrate_entry(hass, config_entry):
data[CONF_WINDOW] = default_total_seconds data[CONF_WINDOW] = default_total_seconds
version = config_entry.version = 2 version = config_entry.version = 2
hass.config_entries.async_update_entry(config_entry, data=data) hass.config_entries.async_update_entry(config_entry, data=data)
LOGGER.info("Migration to version %s successful", version) _LOGGER.info("Migration to version %s successful", version)
return True return True

View File

@ -10,7 +10,6 @@ from .const import ( # pylint: disable=unused-import
DEFAULT_RADIUS, DEFAULT_RADIUS,
DEFAULT_WINDOW, DEFAULT_WINDOW,
DOMAIN, DOMAIN,
LOGGER,
) )
@ -43,18 +42,6 @@ class WWLLNFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async def async_step_import(self, import_config): async def async_step_import(self, import_config):
"""Import a config entry from configuration.yaml.""" """Import a config entry from configuration.yaml."""
default_window_seconds = DEFAULT_WINDOW.total_seconds()
if (
CONF_WINDOW in import_config
and import_config[CONF_WINDOW] < default_window_seconds
):
LOGGER.error(
"Refusing to use too-small window (%s < %s)",
import_config[CONF_WINDOW],
default_window_seconds,
)
return self.async_abort(reason="window_too_small")
return await self.async_step_user(import_config) return await self.async_step_user(import_config)
async def async_step_user(self, user_input=None): async def async_step_user(self, user_input=None):

View File

@ -1,8 +1,5 @@
"""Define constants for the WWLLN integration.""" """Define constants for the WWLLN integration."""
from datetime import timedelta from datetime import timedelta
import logging
LOGGER = logging.getLogger(__package__)
DOMAIN = "wwlln" DOMAIN = "wwlln"

View File

@ -1,5 +1,6 @@
"""Support for WWLLN geo location events.""" """Support for WWLLN geo location events."""
from datetime import timedelta from datetime import timedelta
import logging
from aiowwlln.errors import WWLLNError from aiowwlln.errors import WWLLNError
@ -21,7 +22,9 @@ from homeassistant.helpers.dispatcher import (
from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.event import async_track_time_interval
from homeassistant.util.dt import utc_from_timestamp from homeassistant.util.dt import utc_from_timestamp
from .const import CONF_WINDOW, DATA_CLIENT, DOMAIN, LOGGER from .const import CONF_WINDOW, DATA_CLIENT, DOMAIN
_LOGGER = logging.getLogger(__name__)
ATTR_EXTERNAL_ID = "external_id" ATTR_EXTERNAL_ID = "external_id"
ATTR_PUBLICATION_DATE = "publication_date" ATTR_PUBLICATION_DATE = "publication_date"
@ -81,7 +84,7 @@ class WWLLNEventManager:
@callback @callback
def _create_events(self, ids_to_create): def _create_events(self, ids_to_create):
"""Create new geo location events.""" """Create new geo location events."""
LOGGER.debug("Going to create %s", ids_to_create) _LOGGER.debug("Going to create %s", ids_to_create)
events = [] events = []
for strike_id in ids_to_create: for strike_id in ids_to_create:
strike = self._strikes[strike_id] strike = self._strikes[strike_id]
@ -100,7 +103,7 @@ class WWLLNEventManager:
@callback @callback
def _remove_events(self, ids_to_remove): def _remove_events(self, ids_to_remove):
"""Remove old geo location events.""" """Remove old geo location events."""
LOGGER.debug("Going to remove %s", ids_to_remove) _LOGGER.debug("Going to remove %s", ids_to_remove)
for strike_id in ids_to_remove: for strike_id in ids_to_remove:
async_dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(strike_id)) async_dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(strike_id))
@ -116,7 +119,7 @@ class WWLLNEventManager:
async def async_update(self): async def async_update(self):
"""Refresh data.""" """Refresh data."""
LOGGER.debug("Refreshing WWLLN data") _LOGGER.debug("Refreshing WWLLN data")
try: try:
self._strikes = await self._client.within_radius( self._strikes = await self._client.within_radius(
@ -127,7 +130,7 @@ class WWLLNEventManager:
window=self._window, window=self._window,
) )
except WWLLNError as err: except WWLLNError as err:
LOGGER.error("Error while updating WWLLN data: %s", err) _LOGGER.error("Error while updating WWLLN data: %s", err)
return return
new_strike_ids = set(self._strikes) new_strike_ids = set(self._strikes)

View File

@ -12,8 +12,7 @@
} }
}, },
"abort": { "abort": {
"already_configured": "This location is already registered.", "already_configured": "This location is already registered."
"window_too_small": "A too-small window will cause Home Assistant to miss events."
} }
} }
} }

View File

@ -62,23 +62,6 @@ async def test_step_import(hass):
} }
async def test_step_import_too_small_window(hass):
"""Test that the import step with a too-small window is aborted."""
conf = {
CONF_LATITUDE: 39.128712,
CONF_LONGITUDE: -104.9812612,
CONF_RADIUS: 25,
CONF_WINDOW: 60,
}
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=conf
)
assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
assert result["reason"] == "window_too_small"
async def test_step_user(hass): async def test_step_user(hass):
"""Test that the user step works.""" """Test that the user step works."""
conf = {CONF_LATITUDE: 39.128712, CONF_LONGITUDE: -104.9812612, CONF_RADIUS: 25} conf = {CONF_LATITUDE: 39.128712, CONF_LONGITUDE: -104.9812612, CONF_RADIUS: 25}