Add url to validation (#2874)

* Add url to validation

* Fix pylint issue

* Clean-up
This commit is contained in:
Fabian Affolter 2016-08-19 13:41:01 +02:00 committed by GitHub
parent c74e167a7b
commit ca1de9cac1
2 changed files with 29 additions and 2 deletions

View File

@ -1,5 +1,6 @@
"""Helpers for config validation using voluptuous.""" """Helpers for config validation using voluptuous."""
from datetime import timedelta from datetime import timedelta
from urllib.parse import urlparse
from typing import Any, Union, TypeVar, Callable, Sequence, List, Dict 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)]) 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 # Validator helpers
def key_dependency(key, dependency): def key_dependency(key, dependency):

View File

@ -48,10 +48,10 @@ def test_longitude():
def test_port(): def test_port():
"""Test tcp/udp network port.""" """Test TCP/UDP network port."""
schema = vol.Schema(cv.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): with pytest.raises(vol.MultipleInvalid):
schema(value) schema(value)
@ -59,6 +59,21 @@ def test_port():
schema(value) 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(): def test_platform_config():
"""Test platform config validation.""" """Test platform config validation."""
for value in ( for value in (