Add max_length to URIOpt

Currently StrOpt has a max_length parameter to restrict the length
of the value, but URIOpt does not. The keystone project actually
has use for a max_length to restrict a URI used for the SAML2
entity ID.

Reference patch:
https://review.openstack.org/#/c/341514

Change-Id: I39d012b0b7ebeddf6067016487ac8258461dda30
This commit is contained in:
Eric Brown 2016-07-13 12:32:10 -07:00
parent 9b05dc903f
commit 8ed5f7555d
4 changed files with 41 additions and 3 deletions

View File

@ -1283,11 +1283,19 @@ class URIOpt(Opt):
Option with ``type`` :class:`oslo_config.types.URI`
:param max_length: If positive integer, the value must be less than or
equal to this parameter.
.. versionadded:: 3.12
.. versionchanged:: 3.14
Added *max_length* parameter
"""
def __init__(self, name, **kwargs):
super(URIOpt, self).__init__(name, type=types.URI(), **kwargs)
def __init__(self, name, max_length=None, **kwargs):
super(URIOpt, self).__init__(name,
type=types.URI(max_length=max_length),
**kwargs)
class MultiOpt(Opt):

View File

@ -4327,6 +4327,19 @@ class StrOptMaxLengthTestCase(BaseTestCase):
self.assertRaises(SystemExit, self.conf, ['--foo', '123456'])
class URIOptMaxLengthTestCase(BaseTestCase):
def test_uriopt_max_length_good(self):
self.conf.register_cli_opt(cfg.URIOpt('foo', max_length=30))
self.conf(['--foo', 'http://www.example.com'])
self.assertEqual('http://www.example.com', self.conf.foo)
def test_uriopt_max_length_bad(self):
self.conf.register_cli_opt(cfg.URIOpt('foo', max_length=30))
self.assertRaises(SystemExit, self.conf,
['--foo', 'http://www.example.com/versions'])
class PrintHelpTestCase(base.BaseTestCase):
def test_print_help_without_init(self):

View File

@ -649,3 +649,9 @@ class URITypeTests(TypeTestHelper, unittest.TestCase):
def test_repr(self):
self.assertEqual('URI', repr(types.URI()))
def test_max_length(self):
self.type_instance = types.String(max_length=30)
self.assertInvalid('http://www.example.com/versions')
self.assertConvertedValue('http://www.example.com',
'http://www.example.com')

View File

@ -665,16 +665,27 @@ class URI(ConfigType):
Represents URI. Value will be validated as RFC 3986.
:param type_name: Type name to be used in the sample config file.
:param max_length: Optional integer. If a positive value is specified,
a maximum length of an option value must be less than
or equal to this parameter. Otherwise no length check
will be done.
.. versionchanged:: 3.14
Added *max_length* parameter.
"""
def __init__(self, type_name='uri value'):
def __init__(self, max_length=None, type_name='uri value'):
super(URI, self).__init__(type_name=type_name)
self.max_length = max_length
def __call__(self, value):
if not rfc3986.is_valid_uri(value, require_scheme=True,
require_authority=True):
raise ValueError('invalid URI: %r' % value)
if self.max_length is not None and len(value) > self.max_length:
raise ValueError("Value '%s' exceeds maximum length %d" %
(value, self.max_length))
self.value = value
return value