From ca1de9cac1bd4e000744207a3e0ad823103f2043 Mon Sep 17 00:00:00 2001 From: Fabian Affolter Date: Fri, 19 Aug 2016 13:41:01 +0200 Subject: [PATCH] Add url to validation (#2874) * Add url to validation * Fix pylint issue * Clean-up --- homeassistant/helpers/config_validation.py | 12 ++++++++++++ tests/helpers/test_config_validation.py | 19 +++++++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index ff1f694151f..d9c761832dc 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -1,5 +1,6 @@ """Helpers for config validation using voluptuous.""" from datetime import timedelta +from urllib.parse import urlparse from typing import Any, Union, TypeVar, Callable, Sequence, List, Dict @@ -255,6 +256,17 @@ def time_zone(value): weekdays = vol.All(ensure_list, [vol.In(WEEKDAYS)]) +# pylint: disable=no-value-for-parameter +def url(value: Any) -> str: + """Validate an URL.""" + url_in = str(value) + + if urlparse(url_in).scheme in ['http', 'https']: + return vol.Schema(vol.Url())(url_in) + + raise vol.Invalid('invalid url') + + # Validator helpers def key_dependency(key, dependency): diff --git a/tests/helpers/test_config_validation.py b/tests/helpers/test_config_validation.py index 3a72ef1da37..14d80d9104d 100644 --- a/tests/helpers/test_config_validation.py +++ b/tests/helpers/test_config_validation.py @@ -48,10 +48,10 @@ def test_longitude(): def test_port(): - """Test tcp/udp network port.""" + """Test TCP/UDP network port.""" schema = vol.Schema(cv.port) - for value in('invalid', None, -1, 0, 80000, '81000'): + for value in ('invalid', None, -1, 0, 80000, '81000'): with pytest.raises(vol.MultipleInvalid): schema(value) @@ -59,6 +59,21 @@ def test_port(): schema(value) +def test_url(): + """Test URL.""" + schema = vol.Schema(cv.url) + + for value in ('invalid', None, 100, 'htp://ha.io', 'http//ha.io', + 'http://??,**', 'https://??,**'): + with pytest.raises(vol.MultipleInvalid): + schema(value) + + for value in ('http://localhost', 'https://localhost/test/index.html', + 'http://home-assistant.io', 'http://home-assistant.io/test/', + 'https://community.home-assistant.io/'): + assert schema(value) + + def test_platform_config(): """Test platform config validation.""" for value in (