Skip to content

Commit 7d5f563

Browse files
committed
Add URL validation
1 parent 6806521 commit 7d5f563

2 files changed

Lines changed: 35 additions & 2 deletions

File tree

consulate/utils.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,17 @@
55
"""
66
import re
77
import sys
8-
try:
8+
try: # pylint: disable=import-error
99
from urllib.parse import quote
1010
except ImportError:
1111
from urllib import quote
1212

13+
try: # pylint: disable=import-error
14+
from urllib import parse as _urlparse
15+
except ImportError:
16+
import urlparse as _urlparse
17+
18+
1319
from consulate import exceptions
1420

1521
DURATION_PATTERN = re.compile(r'^(?:(?:-|)(?:\d+|\d+\.\d+)(?:µs|ms|s|m|h))+$')
@@ -80,12 +86,26 @@ def response_ok(response, raise_on_404=False):
8086
return False
8187

8288

83-
def validate_go_interval(value):
89+
def validate_go_interval(value, _model=None):
8490
"""Validate the value passed in returning :data:`True` if it is a Go
8591
Duration value.
8692
8793
:param str value: The string to check
94+
:param consulate.models.base.Model _model: Optional model passed in
8895
:rtype: bool
8996
9097
"""
9198
return DURATION_PATTERN.match(value) is not None
99+
100+
101+
def validate_url(value, _model=None):
102+
"""Validate that the value passed in is a URL, returning :data:`True` if
103+
it is.
104+
105+
:param str value: The string to check
106+
:param consulate.models.base.Model _model: Optional model passed in
107+
:rtype: bool
108+
109+
"""
110+
parsed = _urlparse.urlparse(value)
111+
return parsed.scheme and parsed.netloc

tests/utils_tests.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,16 @@ def test_invalid_values(self):
3030
for value in {'100', '1 year', '5M', '30S'}:
3131
print('Testing {}'.format(value))
3232
self.assertFalse(utils.validate_go_interval(value))
33+
34+
35+
class ValidateURLTestCase(unittest.TestCase):
36+
37+
def test_valid_values(self):
38+
for value in {'https://foo', 'http://localhost/bar'}:
39+
print('Testing {}'.format(value))
40+
self.assertTrue(utils.validate_url(value))
41+
42+
def test_invalid_values(self):
43+
for value in {'localhost', 'a'}:
44+
print('Testing {}'.format(value))
45+
self.assertFalse(utils.validate_url(value))

0 commit comments

Comments
 (0)