convert tests

This commit is contained in:
2017-12-13 22:15:34 +01:00
parent fc787d4dbb
commit b5f785d62c
38 changed files with 5234 additions and 566 deletions

View File

@ -56,17 +56,10 @@ def validate_callback(callback,
"""
def _validate_option(option):
#validate option
#FIXME etrange ...
if hasattr(option, 'impl_is_symlinkoption'):
if option.impl_is_symlinkoption():
cur_opt = option.impl_getopt()
else:
cur_opt = option
if option.impl_is_symlinkoption():
cur_opt = option.impl_getopt()
else:
raise ValueError(_('{}_params must have an option'
' not a {} for first argument'
).format(type_,
type(option)))
cur_opt = option
if cur_opt != callbackoption:
cur_opt._add_dependency(callbackoption)
callbackoption._has_dependency = True
@ -406,7 +399,7 @@ class BaseOption(Base):
def _impl_valid_string(self,
value):
if not isinstance(value, str):
return ValueError(_('invalid string'))
raise ValueError(_('invalid string'))
def impl_get_display_name(self,
dyn_name=None):
@ -498,7 +491,7 @@ def validate_requires_arg(new_option,
option = exp['option']
option._add_dependency(new_option)
if option is not None:
err = option._validate(exp['value'])
err = option._validate(exp['value'], undefined)
if err:
raise ValueError(_('malformed requirements expected value '
'must be valid for option {0}'
@ -513,7 +506,7 @@ def validate_requires_arg(new_option,
else:
option = get_option(require)
if expected is not None:
err = option._validate(expected)
err = option._validate(expected, undefined)
if err:
raise ValueError(_('malformed requirements expected value '
'must be valid for option {0}'

View File

@ -29,6 +29,10 @@ class BoolOption(Option):
__slots__ = tuple()
_display_name = _('boolean')
def _validate(self, value, context=undefined, current_opt=undefined):
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
if not isinstance(value, bool):
return ValueError()
raise ValueError()

View File

@ -30,26 +30,36 @@ class BroadcastOption(Option):
__slots__ = tuple()
_display_name = _('broadcast address')
def _validate(self, value, context=undefined, current_opt=undefined):
err = self._impl_valid_string(value)
if err:
return err
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
self._impl_valid_string(value)
if value.count('.') != 3:
return ValueError()
raise ValueError()
for val in value.split('.'):
if val.startswith("0") and len(val) > 1:
return ValueError()
raise ValueError()
try:
IP('{0}/32'.format(value))
except ValueError:
return ValueError()
raise ValueError()
def _cons_broadcast(self, current_opt, opts, vals, warnings_only):
def _cons_broadcast(self,
current_opt,
opts,
vals,
warnings_only):
if len(vals) != 3:
return ConfigError(_('invalid len for vals'))
if None in vals:
return
broadcast, network, netmask = vals
if IP('{0}/{1}'.format(network, netmask)).broadcast() != IP(broadcast):
return ValueError(_('broadcast {4} invalid with network {0}/{1} ({2}/{3})').format(
network, netmask, opts[1].impl_getname(), opts[2].impl_getname(), broadcast))
raise ValueError(_('broadcast "{4}" invalid with network {0}/{1} ("{2}"/"{3}")'
'').format(network,
netmask,
opts[1].impl_get_display_name(),
opts[2].impl_get_display_name(),
broadcast))

View File

@ -36,16 +36,30 @@ class ChoiceOption(Option):
__slots__ = tuple()
_display_name = _('choice')
def __init__(self, name, doc, values, default=None,
values_params=None, default_multi=None, requires=None,
multi=False, callback=None, callback_params=None,
validator=None, validator_params=None,
properties=None, warnings_only=False):
def __init__(self,
name,
doc,
values,
default=None,
values_params=None,
default_multi=None,
requires=None,
multi=False,
callback=None,
callback_params=None,
validator=None,
validator_params=None,
properties=None,
warnings_only=False):
"""
:param values: is a list of values the option can possibly take
"""
if isinstance(values, FunctionType):
validate_callback(values, values_params, 'values', self)
validate_callback(values,
values_params,
'values',
self)
else:
if values_params is not None:
raise ValueError(_('values is not a function, so values_params must be None'))
@ -55,7 +69,9 @@ class ChoiceOption(Option):
self._choice_values = values
if values_params is not None:
self._choice_values_params = values_params
super(ChoiceOption, self).__init__(name, doc, default=default,
super(ChoiceOption, self).__init__(name,
doc,
default=default,
default_multi=default_multi,
callback=callback,
callback_params=callback_params,
@ -66,7 +82,10 @@ class ChoiceOption(Option):
properties=properties,
warnings_only=warnings_only)
def impl_get_values(self, context, current_opt=undefined):
def impl_get_values(self,
setting_properties,
context,
current_opt=undefined):
if current_opt is undefined:
current_opt = self
#FIXME cache? but in context...
@ -75,25 +94,29 @@ class ChoiceOption(Option):
if context is None:
values = []
else:
values = carry_out_calculation(current_opt, context=context,
values = carry_out_calculation(current_opt,
setting_properties=setting_properties,
context=context,
callback=values,
callback_params=getattr(self, '_choice_values_params', {}))
if isinstance(values, Exception):
return values
if values is not undefined and not isinstance(values, list):
raise ConfigError(_('calculated values for {0} is not a list'
'').format(self.impl_getname()))
return values
def _validate(self, value, context=undefined, current_opt=undefined):
values = self.impl_get_values(context, current_opt=current_opt)
if isinstance(values, Exception):
return values
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
values = self.impl_get_values(setting_properties,
context,
current_opt=current_opt)
if values is not undefined and not value in values:
if len(values) == 1:
return ValueError(_('only {0} is allowed'
'').format(values[0]))
raise ValueError(_('only {0} is allowed'
'').format(values[0]))
else:
return ValueError(_('only {0} are allowed'
'').format(display_list(values)))
raise ValueError(_('only {0} are allowed'
'').format(display_list(values)))

View File

@ -29,11 +29,13 @@ class DateOption(Option):
__slots__ = tuple()
_display_name = _('date')
def _validate(self, value, context=undefined, current_opt=undefined):
err = self._impl_valid_string(value)
if err:
return err
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
self._impl_valid_string(value)
try:
datetime.strptime(value, "%Y-%m-%d")
except ValueError:
return ValueError()
raise ValueError()

View File

@ -36,11 +36,23 @@ class DomainnameOption(Option):
__slots__ = tuple()
_display_name = _('domain name')
def __init__(self, name, doc, default=None, default_multi=None,
requires=None, multi=False, callback=None,
callback_params=None, validator=None, validator_params=None,
properties=None, allow_ip=False, type_='domainname',
warnings_only=False, allow_without_dot=False):
def __init__(self,
name,
doc,
default=None,
default_multi=None,
requires=None,
multi=False,
callback=None,
callback_params=None,
validator=None,
validator_params=None,
properties=None,
allow_ip=False,
type_='domainname',
warnings_only=False,
allow_without_dot=False):
if type_ not in ['netbios', 'hostname', 'domainname']:
raise ValueError(_('unknown type_ {0} for hostname').format(type_))
extra = {'_dom_type': type_}
@ -50,8 +62,6 @@ class DomainnameOption(Option):
raise ValueError(_('allow_without_dot must be a boolean'))
extra['_allow_ip'] = allow_ip
extra['_allow_without_dot'] = allow_without_dot
# FIXME should be
# regexp = r'^((?!-)[a-z0-9-]{1,63}(?<!-)\.{0,1})$'
if type_ == 'domainname':
if allow_without_dot:
min_time = 0
@ -67,7 +77,9 @@ class DomainnameOption(Option):
extra['_domain_re'] = re.compile(regexp)
extra['_has_upper'] = re.compile('[A-Z]')
super(DomainnameOption, self).__init__(name, doc, default=default,
super(DomainnameOption, self).__init__(name,
doc,
default=default,
default_multi=default_multi,
callback=callback,
callback_params=callback_params,
@ -85,49 +97,50 @@ class DomainnameOption(Option):
else:
return 63
def _validate(self, value, context=undefined, current_opt=undefined):
err = self._impl_valid_string(value)
if err:
return err
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
self._impl_valid_string(value)
def _valid_length(val):
if len(val) < 1:
return ValueError(_("invalid length (min 1)"))
raise ValueError(_("invalid length (min 1)"))
if len(val) > part_name_length:
return ValueError(_("invalid length (max {0})"
raise ValueError(_("invalid length (max {0})"
"").format(part_name_length))
if self._get_extra('_allow_ip') is True:
try:
IP('{0}/32'.format(value))
return
except ValueError:
pass
else:
return
else:
try:
IP('{0}/32'.format(value))
except ValueError:
pass
else:
return ValueError(_('must not be an IP'))
raise ValueError(_('must not be an IP'))
part_name_length = self._get_len(self._get_extra('_dom_type'))
if self._get_extra('_dom_type') == 'domainname':
if not self._get_extra('_allow_without_dot') and not "." in value:
return ValueError(_("must have dot"))
raise ValueError(_("must have dot"))
if len(value) > 255:
return ValueError(_("invalid length (max 255)"))
raise ValueError(_("invalid length (max 255)"))
for dom in value.split('.'):
err = _valid_length(dom)
if err:
return err
_valid_length(dom)
else:
return _valid_length(value)
_valid_length(value)
def _second_level_validation(self, value, warnings_only):
if self._get_extra('_has_upper').search(value):
return ValueError(_('some characters are uppercase'))
raise ValueError(_('some characters are uppercase'))
if not self._get_extra('_domain_re').search(value):
if warnings_only:
return ValueError(_('some characters may cause problems'))
raise ValueError(_('some characters may cause problems'))
else:
return ValueError()
raise ValueError()

View File

@ -29,6 +29,10 @@ class FloatOption(Option):
__slots__ = tuple()
_display_name = _('float')
def _validate(self, value, context=undefined, current_opt=undefined):
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
if not isinstance(value, float):
return ValueError()
raise ValueError()

View File

@ -29,6 +29,10 @@ class IntOption(Option):
__slots__ = tuple()
_display_name = _('integer')
def _validate(self, value, context=undefined, current_opt=undefined):
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
if not isinstance(value, int):
return ValueError()
raise ValueError()

View File

@ -31,14 +31,26 @@ class IPOption(Option):
__slots__ = tuple()
_display_name = _('IP')
def __init__(self, name, doc, default=None, default_multi=None,
requires=None, multi=False, callback=None,
callback_params=None, validator=None, validator_params=None,
properties=None, private_only=False, allow_reserved=False,
def __init__(self,
name,
doc,
default=None,
default_multi=None,
requires=None,
multi=False,
callback=None,
callback_params=None,
validator=None,
validator_params=None,
properties=None,
private_only=False,
allow_reserved=False,
warnings_only=False):
extra = {'_private_only': private_only,
'_allow_reserved': allow_reserved}
super(IPOption, self).__init__(name, doc, default=default,
super(IPOption, self).__init__(name,
doc,
default=default,
default_multi=default_multi,
callback=callback,
callback_params=callback_params,
@ -50,47 +62,62 @@ class IPOption(Option):
warnings_only=warnings_only,
extra=extra)
def _validate(self, value, context=undefined, current_opt=undefined):
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
# sometimes an ip term starts with a zero
# but this does not fit in some case, for example bind does not like it
err = self._impl_valid_string(value)
if err:
return err
self._impl_valid_string(value)
if value.count('.') != 3:
return ValueError()
raise ValueError()
for val in value.split('.'):
if val.startswith("0") and len(val) > 1:
return ValueError()
raise ValueError()
# 'standard' validation
try:
IP('{0}/32'.format(value))
except ValueError:
return ValueError()
raise ValueError()
def _second_level_validation(self, value, warnings_only):
def _second_level_validation(self,
value,
warnings_only):
ip = IP('{0}/32'.format(value))
if not self._get_extra('_allow_reserved') and ip.iptype() == 'RESERVED':
if warnings_only:
msg = _("shouldn't in reserved class")
else:
msg = _("mustn't be in reserved class")
return ValueError(msg)
raise ValueError(msg)
if self._get_extra('_private_only') and ip.iptype() != 'PRIVATE':
if warnings_only:
msg = _("should be in private class")
else:
msg = _("must be in private class")
return ValueError(msg)
raise ValueError(msg)
def _cons_in_network(self, current_opt, opts, vals, warnings_only):
def _cons_in_network(self,
current_opt,
opts,
vals,
warnings_only):
if len(vals) != 3:
return ConfigError(_('invalid len for vals'))
if None in vals:
return
ip, network, netmask = vals
if IP(ip) not in IP('{0}/{1}'.format(network, netmask)):
msg = _('{4} is not in network {0}/{1} ({2}/{3})')
return ValueError(msg.format(network, netmask,
opts[1].impl_getname(), opts[2].impl_getname(), ip))
if IP(ip) not in IP('{0}/{1}'.format(network,
netmask)):
msg = _('"{4}" is not in network "{0}"/"{1}" ("{2}"/"{3}")')
raise ValueError(msg.format(network,
netmask,
opts[1].impl_get_display_name(),
opts[2].impl_getname(),
ip))
# test if ip is not network/broadcast IP
return opts[2]._cons_ip_netmask(current_opt, (opts[2], opts[0]), (netmask, ip), warnings_only)
opts[2]._cons_ip_netmask(current_opt,
(opts[2], opts[0]),
(netmask, ip),
warnings_only)

View File

@ -175,7 +175,7 @@ class MasterSlaves(OptionDescription):
context):
if option.impl_is_master_slaves('master') and isinstance(value, list):
if len(value) < context._impl_length:
return ValueError(_('cannot reduce length of master "{}"'
raise ValueError(_('cannot reduce length of master "{}"'
'').format(option.impl_get_display_name()))
def is_masterslaves(self):

View File

@ -31,50 +31,72 @@ class NetmaskOption(Option):
__slots__ = tuple()
_display_name = _('netmask address')
def _validate(self, value, context=undefined, current_opt=undefined):
err = self._impl_valid_string(value)
if err:
return err
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
self._impl_valid_string(value)
if value.count('.') != 3:
return ValueError()
raise ValueError()
for val in value.split('.'):
if val.startswith("0") and len(val) > 1:
return ValueError()
raise ValueError()
try:
IP('0.0.0.0/{0}'.format(value))
except ValueError:
return ValueError()
raise ValueError()
def _cons_network_netmask(self, current_opt, opts, vals, warnings_only):
def _cons_network_netmask(self,
current_opt,
opts,
vals,
warnings_only):
#opts must be (netmask, network) options
if None in vals:
return
return self.__cons_netmask(opts, vals[0], vals[1], False, warnings_only)
return self.__cons_netmask(opts,
vals[0],
vals[1],
False,
warnings_only)
def _cons_ip_netmask(self, current_opt, opts, vals, warnings_only):
def _cons_ip_netmask(self,
current_opt,
opts,
vals,
warnings_only):
#opts must be (netmask, ip) options
if None in vals:
return
return self.__cons_netmask(opts, vals[0], vals[1], True, warnings_only)
self.__cons_netmask(opts,
vals[0],
vals[1],
True,
warnings_only)
def __cons_netmask(self, opts, val_netmask, val_ipnetwork, make_net,
def __cons_netmask(self,
opts,
val_netmask,
val_ipnetwork,
make_net,
warnings_only):
if len(opts) != 2:
return ConfigError(_('invalid len for opts'))
msg = None
try:
ip = IP('{0}/{1}'.format(val_ipnetwork, val_netmask),
make_net=make_net)
ip = IP('{0}/{1}'.format(val_ipnetwork, val_netmask), make_net=make_net)
#if cidr == 32, ip same has network
if make_net and ip.prefixlen() != 32:
val_ip = IP(val_ipnetwork)
if ip.net() == val_ip:
msg = _("this is a network with netmask {0} ({1})")
msg = _('this is a network with netmask "{0}" ("{1}")')
if ip.broadcast() == val_ip:
msg = _("this is a broadcast with netmask {0} ({1})")
msg = _('this is a broadcast with netmask "{0}" ("{1}")')
except ValueError:
if not make_net:
msg = _('with netmask {0} ({1})')
msg = _('with netmask "{0}" ("{1}")')
if msg is not None:
return ValueError(msg.format(val_netmask, opts[1].impl_getname()))
raise ValueError(msg.format(val_netmask,
opts[1].impl_get_diplay_name()))

View File

@ -30,25 +30,29 @@ class NetworkOption(Option):
__slots__ = tuple()
_display_name = _('network address')
def _validate(self, value, context=undefined, current_opt=undefined):
err = self._impl_valid_string(value)
if err:
return err
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
self._impl_valid_string(value)
if value.count('.') != 3:
return ValueError()
raise ValueError()
for val in value.split('.'):
if val.startswith("0") and len(val) > 1:
return ValueError()
raise ValueError()
try:
IP(value)
except ValueError:
return ValueError()
raise ValueError()
def _second_level_validation(self, value, warnings_only):
def _second_level_validation(self,
value,
warnings_only):
ip = IP(value)
if ip.iptype() == 'RESERVED':
if warnings_only:
msg = _("shouldn't be in reserved class")
else:
msg = _("mustn't be in reserved class")
return ValueError(msg)
raise ValueError(msg)

View File

@ -133,7 +133,8 @@ class Option(OnlyOption):
is_multi=is_multi)
if is_multi and default_multi is not None:
def test_multi_value(value):
err = self._validate(value)
err = self._validate(value,
undefined)
if err:
raise ValueError(_("invalid default_multi value {0} "
"for option {1}: {2}").format(str(value),
@ -152,10 +153,8 @@ class Option(OnlyOption):
_setattr(self, '_default_multi', default_multi)
if unique is not undefined:
_setattr(self, '_unique', unique)
err = self.impl_validate(default,
is_multi=is_multi)
if err:
raise err
self.impl_validate(default,
is_multi=is_multi)
if (is_multi and default != []) or \
(not is_multi and default is not None):
if is_multi:
@ -300,8 +299,7 @@ class Option(OnlyOption):
force_index=None,
current_opt=undefined,
is_multi=None,
display_error=True,
display_warnings=True,
check_error=True,
multi=None,
setting_properties=undefined):
"""
@ -315,14 +313,13 @@ class Option(OnlyOption):
"""
if current_opt is undefined:
current_opt = self
if display_warnings and setting_properties is undefined and context is not undefined:
setting_properties = context.cfgimpl_get_settings()._getproperties(read_write=False)
display_warnings = display_warnings and (setting_properties is undefined or 'warnings' in setting_properties)
if check_error is False and not 'warnings' in setting_properties:
return
def _is_not_unique(value):
#FIXME pourquoi la longueur doit etre egal ???
if display_error and self.impl_is_unique() and len(set(value)) != len(value):
if check_error and self.impl_is_unique() and len(set(value)) != len(value):
for idx, val in enumerate(value):
if val in value[idx+1:]:
raise ValueError(_('invalid value "{}", this value is already in "{}"'
@ -361,16 +358,18 @@ class Option(OnlyOption):
raise ValueError(_('invalid value "{}" for "{}" '
'which must not be a list').format(_value,
self.impl_get_display_name()))
#FIXME a revoir ...
is_warnings_only = getattr(self, '_warnings_only', False)
try:
if _value is not None:
if display_error:
if check_error:
# option validation
self._validate(_value,
setting_properties,
context,
current_opt)
if ((display_error and not is_warnings_only) or
(display_warnings and is_warnings_only)):
if ((check_error and not is_warnings_only) or
(not check_error and is_warnings_only)):
calculation_validator(_value,
_index)
self._second_level_validation(_value,
@ -379,8 +378,7 @@ class Option(OnlyOption):
_value,
context,
_index,
display_warnings,
display_error,
check_error,
setting_properties)
except ValueError as err:
if debug: # pragma: no cover
@ -402,12 +400,12 @@ class Option(OnlyOption):
err_msg = '{0}'.format(err)
if err_msg:
msg += ', {}'.format(err_msg)
if is_warnings_only:
if check_error:
raise ValueError(msg)
else:
warnings.warn_explicit(ValueWarning(msg, self),
ValueWarning,
self.__class__.__name__, 0)
else:
raise ValueError(msg)
if is_multi is None:
is_multi = self.impl_is_multi()
@ -563,10 +561,10 @@ class Option(OnlyOption):
all_cons_opts,
params)
#validate default value when add consistency
err = self.impl_validate(self.impl_getdefault())
if err:
self._del_consistency()
raise err
self.impl_validate(self.impl_getdefault())
#FIXME
#if err:
# self._del_consistency()
if func != '_cons_not_equal':
#consistency could generate warnings or errors
self._has_dependency = True
@ -584,8 +582,7 @@ class Option(OnlyOption):
value,
context,
index,
display_warnings,
display_error,
check_error,
setting_properties):
if context is not undefined:
descr = context.cfgimpl_get_description()
@ -601,7 +598,7 @@ class Option(OnlyOption):
if consistencies is not None:
for func, all_cons_opts, params in consistencies:
warnings_only = params.get('warnings_only', False)
if (warnings_only and display_warnings) or (not warnings_only and display_error):
if (warnings_only and not check_error) or (not warnings_only and check_error):
transitive = params.get('transitive', True)
#all_cons_opts[0] is the option where func is set
if isinstance(option, DynSymLinkOption):
@ -745,6 +742,7 @@ class RegexpOption(Option):
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
err = self._impl_valid_string(value)

View File

@ -99,7 +99,7 @@ class CacheOptionDescription(BaseOption):
params))
# if context is set to callback, must be reset each time a value change
if hasattr(option, '_has_calc_context'):
_dependencies.append(option)
self._add_dependency(option)
is_slave = None
if is_multi:
all_requires = option.impl_getrequires()
@ -150,10 +150,10 @@ class CacheOptionDescription(BaseOption):
return False
def impl_build_force_store_values(self,
config,
context,
force_store_values):
session = config._impl_values._p_.getsession()
value_set = False
value_setted = False
values = context.cfgimpl_get_values()
for subpath, option in self._cache_force_store_values:
if option.impl_is_master_slaves('slave'):
# problem with index
@ -162,19 +162,24 @@ class CacheOptionDescription(BaseOption):
if option._is_subdyn():
raise ConfigError(_('a dynoption ({0}) cannot have '
'force_store_value property').format(subpath))
if force_store_values and not config._impl_values._p_.hasvalue(subpath, session):
value = impl_build_force_store_values.getvalue(option,
subpath,
index=None,
setting_properties=undefined,
self_properties=undefined,
validate=False)
value_set = True
config._impl_values._p_.setvalue(subpath, value,
owners.forced, None, session, False)
if force_store_values is False:
raise Exception('ok ca existe ...')
if force_store_values and not values._p_.hasvalue(subpath):
value = values.getvalue(option,
subpath,
index=None,
setting_properties=None,
self_properties=None,
validate=False)
value_setted = True
values._p_.setvalue(subpath,
value,
owners.forced,
None,
False)
if value_set:
config._impl_values._p_.commit()
if value_setted:
values._p_.commit()
def _build_cache_option(self,
_currpath=None,

View File

@ -29,7 +29,9 @@ class PasswordOption(Option):
__slots__ = tuple()
_display_name = _('password')
def _validate(self, value, context=undefined, current_opt=undefined):
err = self._impl_valid_string(value)
if err:
return err
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
self._impl_valid_string(value)

View File

@ -40,12 +40,25 @@ class PortOption(Option):
port_re = re.compile(r"^[0-9]*$")
_display_name = _('port')
def __init__(self, name, doc, default=None, default_multi=None,
requires=None, multi=False, callback=None,
callback_params=None, validator=None, validator_params=None,
properties=None, allow_range=False, allow_zero=False,
allow_wellknown=True, allow_registred=True,
allow_private=False, warnings_only=False):
def __init__(self,
name,
doc,
default=None,
default_multi=None,
requires=None,
multi=False,
callback=None,
callback_params=None,
validator=None,
validator_params=None,
properties=None,
allow_range=False,
allow_zero=False,
allow_wellknown=True,
allow_registred=True,
allow_private=False,
warnings_only=False):
extra = {'_allow_range': allow_range,
'_min_value': None,
'_max_value': None}
@ -69,7 +82,9 @@ class PortOption(Option):
if extra['_max_value'] is None:
raise ValueError(_('max value is empty'))
super(PortOption, self).__init__(name, doc, default=default,
super(PortOption, self).__init__(name,
doc,
default=default,
default_multi=default_multi,
callback=callback,
callback_params=callback_params,
@ -81,30 +96,29 @@ class PortOption(Option):
warnings_only=warnings_only,
extra=extra)
def _validate(self, value, context=undefined, current_opt=undefined):
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
if isinstance(value, int):
if sys.version_info[0] >= 3: # pragma: no cover
value = str(value)
else:
value = unicode(value)
err = self._impl_valid_string(value)
if err:
return err
value = str(value)
self._impl_valid_string(value)
if self._get_extra('_allow_range') and ":" in str(value):
value = str(value).split(':')
if len(value) != 2:
return ValueError(_('range must have two values only'))
raise ValueError(_('range must have two values only'))
if not value[0] < value[1]:
return ValueError(_('first port in range must be'
' smaller than the second one'))
raise ValueError(_('first port in range must be'
' smaller than the second one'))
else:
value = [value]
for val in value:
if not self.port_re.search(val):
return ValueError()
raise ValueError()
val = int(val)
if not self._get_extra('_min_value') <= val <= self._get_extra('_max_value'):
return ValueError(_('must be an integer between {0} '
'and {1}').format(self._get_extra('_min_value'),
self._get_extra('_max_value')))
raise ValueError(_('must be an integer between {0} '
'and {1}').format(self._get_extra('_min_value'),
self._get_extra('_max_value')))

View File

@ -30,23 +30,16 @@ class StrOption(Option):
__slots__ = tuple()
_display_name = _('string')
def _validate(self, value, context=undefined, current_opt=undefined):
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
if not isinstance(value, str):
return ValueError()
raise ValueError()
if sys.version_info[0] >= 3: # pragma: no cover
#UnicodeOption is same as StrOption in python 3+
class UnicodeOption(StrOption):
__slots__ = tuple()
pass
else:
class UnicodeOption(Option):
"represents the choice of a unicode string"
__slots__ = tuple()
_empty = u''
_display_name = _('unicode string')
def _validate(self, value, context=undefined, current_opt=undefined):
if not isinstance(value, unicode):
return ValueError()
#UnicodeOption is same as StrOption in python 3+
class UnicodeOption(StrOption):
__slots__ = tuple()
_display_name = _('unicode')

View File

@ -38,6 +38,10 @@ class SymLinkOption(OnlyOption):
_setattr(self, '_opt', opt)
opt._add_dependency(self)
def __getattr__(self,
name):
return getattr(self._opt, name)
def impl_has_dependency(self, self_is_dep=True):
"""If self_is_dep is True, it has dependency (self._opt), so return True
if self_is_dep is False, cannot has validation or callback, so return False
@ -47,37 +51,32 @@ class SymLinkOption(OnlyOption):
def impl_is_symlinkoption(self):
return True
def __getattr__(self,
name,
context=undefined):
return getattr(self.impl_getopt(), name)
def impl_getopt(self):
return self._opt
def impl_get_information(self,
key,
default=undefined):
return self.impl_getopt().impl_get_information(key, default)
#def impl_get_information(self,
# key,
# default=undefined):
# return self._opt.impl_get_information(key, default)
def impl_is_readonly(self):
return True
def impl_getproperties(self):
return self.impl_getopt().impl_getproperties()
#def impl_getproperties(self):
# return self._opt.impl_getproperties()
def impl_get_callback(self):
return self.impl_getopt().impl_get_callback()
#def impl_get_callback(self):
# return self._opt.impl_get_callback()
def impl_has_callback(self):
"to know if a callback has been defined or not"
return self.impl_getopt().impl_has_callback()
#def impl_has_callback(self):
# "to know if a callback has been defined or not"
# return self._opt.impl_has_callback()
def impl_is_multi(self):
return self.impl_getopt().impl_is_multi()
#def impl_is_multi(self):
# return self._opt.impl_is_multi()
def _is_subdyn(self):
return getattr(self.impl_getopt(), '_subdyn', None) is not None
#def _is_subdyn(self):
# return getattr(self._opt, '_subdyn', None) is not None
def _get_consistencies(self):
return ()
@ -100,15 +99,14 @@ class DynSymLinkOption(object):
self._suffix = suffix
def __getattr__(self,
name,
context=undefined):
return getattr(self.impl_getopt(), name)
name):
return getattr(self._opt, name)
def impl_getname(self):
return self._opt.impl_getname() + self._suffix
def impl_get_display_name(self):
return self.impl_getopt().impl_get_display_name(dyn_name=self.impl_getname())
return self._opt.impl_get_display_name(dyn_name=self.impl_getname())
def impl_getopt(self):
return self._opt
@ -125,23 +123,20 @@ class DynSymLinkOption(object):
def impl_validate(self,
value,
context=undefined,
validate=True,
force_index=None,
is_multi=None,
display_error=True,
display_warnings=True,
check_error=True,
multi=None,
setting_properties=undefined):
return self.impl_getopt().impl_validate(value,
context,
validate,
force_index,
current_opt=self,
is_multi=is_multi,
display_error=display_error,
display_warnings=display_warnings,
multi=multi,
setting_properties=setting_properties)
# add current_opt !
self._opt.impl_validate(value,
context,
force_index,
current_opt=self,
is_multi=is_multi,
check_error=check_error,
multi=multi,
setting_properties=setting_properties)
def impl_is_dynsymlinkoption(self):
return True

View File

@ -40,16 +40,23 @@ class SynDynOptionDescription(object):
def __getattr__(self, name):
return getattr(self._opt, name)
def impl_getopt(self):
return self._opt
def impl_getchild(self,
name,
setting_properties,
subconfig):
if name.endswith(self._suffix):
oname = name[:-len(self._suffix)]
child = self._children[1][self._children[0].index(oname)]
return self._impl_get_dynchild(child,
self._suffix,
subconfig.cfgimpl_get_path())
try:
if name.endswith(self._suffix):
oname = name[:-len(self._suffix)]
child = self._children[1][self._children[0].index(oname)]
return self._impl_get_dynchild(child,
self._suffix,
subconfig.cfgimpl_get_path())
except ValueError:
# when oname not in self._children
pass
raise AttributeError(_('unknown Option {0} '
'in SynDynOptionDescription {1}'
'').format(name, self.impl_getname()))

View File

@ -32,13 +32,15 @@ class URLOption(DomainnameOption):
path_re = re.compile(r"^[A-Za-z0-9\-\._~:/\?#\[\]@!%\$&\'\(\)\*\+,;=]+$")
_display_name = _('URL')
def _validate(self, value, context=undefined, current_opt=undefined):
err = self._impl_valid_string(value)
if err:
return err
def _validate(self,
value,
setting_properties,
context=undefined,
current_opt=undefined):
self._impl_valid_string(value)
match = self.proto_re.search(value)
if not match:
return ValueError(_('must start with http:// or '
raise ValueError(_('must start with http:// or '
'https://'))
value = value[len(match.group(0)):]
# get domain/files
@ -56,18 +58,17 @@ class URLOption(DomainnameOption):
else:
domain, port = splitted
if not 0 <= int(port) <= 65535:
return ValueError(_('port must be an between 0 and '
raise ValueError(_('port must be an between 0 and '
'65536'))
# validate domainname
err = super(URLOption, self)._validate(domain)
if err:
return err
err = super(URLOption, self)._second_level_validation(domain, False)
if err:
return err
super(URLOption, self)._validate(domain,
setting_properties,
context,
current_opt)
super(URLOption, self)._second_level_validation(domain, False)
# validate file
if files is not None and files != '' and not self.path_re.search(files):
return ValueError(_('must ends with a valid resource name'))
raise ValueError(_('must ends with a valid resource name'))
def _second_level_validation(self, value, warnings_only):
pass