review exception

This commit is contained in:
Emmanuel Garette 2013-04-14 12:01:32 +02:00
parent fbcbbfbd2b
commit 9357b342c1
12 changed files with 130 additions and 144 deletions

View File

@ -167,7 +167,7 @@ def test_find_in_config():
def test_does_not_find_in_config():
descr = make_description()
conf = Config(descr)
raises(NotFoundError, "conf.find(byname='IDontExist')")
raises(AttributeError, "conf.find(byname='IDontExist')")
#def test_validator():
# "validates the integrity of an option towards a whole configuration"

View File

@ -242,7 +242,7 @@ def test_has_callback():
dummy = config.unwrap_from_path('gc.dummy')
setting.enable_property('freeze')
setting.add_property('frozen', dummy)
raises(TypeError, "config.gc.dummy = True")
raises(ConfigError, "config.gc.dummy = True")
def test_freeze_and_has_callback_with_setoption():
descr = make_description_callback()
@ -253,5 +253,5 @@ def test_freeze_and_has_callback_with_setoption():
config.cfgimpl_get_settings().enable_property('freeze')
dummy = config.unwrap_from_path('gc.dummy')
config.cfgimpl_get_settings().add_property('frozen', dummy)
raises(TypeError, "config.gc.setoption('dummy', descr.gc.dummy, True)")
raises(ConfigError, "config.gc.setoption('dummy', descr.gc.dummy, True)")
#____________________________________________________________

View File

@ -69,7 +69,7 @@ def test_reset_with_multi():
config.unwrap_from_path("string").reset(config)
# assert config.string == ["string"]
assert config.cfgimpl_get_values().getowner(s) == 'default'
raises(ValidateError, "config.string = None")
raises(ValueError, "config.string = None")
def test_default_with_multi():
"default with multi is a list"
@ -240,7 +240,7 @@ def test_multi_with_bool_two():
descr = OptionDescription("options", "", [s])
config = Config(descr)
assert descr.bool.is_multi() == True
raises(ValidateError, "config.bool = True")
raises(ValueError, "config.bool = True")
def test_choice_access_with_multi():
ch = ChoiceOption("t1", "", ("a", "b"), default=["a"], multi=True)
@ -278,7 +278,7 @@ def test_dwim_set():
assert not c.b2
assert c.sub.c1 == 'c'
raises(AmbigousOptionError, "c.set(d1=True)")
raises(NoMatchingOptionFound, "c.set(unknown='foo')")
raises(AttributeError, "c.set(unknown='foo')")
def test_more_set():
descr = OptionDescription("opt", "", [
@ -309,7 +309,7 @@ def test_set_with_unknown_option():
IntOption("int", "", default=42)])
d = {'s1.a': True, 'int': 23}
config = Config(descr)
raises(NoMatchingOptionFound, "config.set(**d)")
raises(AttributeError, "config.set(**d)")
def test_set_symlink_option():
@ -380,7 +380,7 @@ def test_allow_multiple_changes_from_config():
def test_access_by_get():
descr = make_description()
cfg = Config(descr)
raises(NotFoundError, "cfg.find(byname='idontexist')" )
raises(AttributeError, "cfg.find(byname='idontexist')" )
assert cfg.find_first(byname='wantref', type_='value') == False
assert cfg.gc.dummy == False
assert cfg.find_first(byname='dummy', type_='value') == False
@ -399,4 +399,4 @@ def test_access_by_get_whith_hide():
c = Config(descr)
setting = c.cfgimpl_get_settings()
setting.read_write()
raises(NotFoundError, "c.find(byname='b1')")
raises(AttributeError, "c.find(byname='b1')")

View File

@ -64,7 +64,7 @@ def test_freeze_whole_config():
settings = conf.cfgimpl_get_settings()
settings.enable_property('everything_frozen')
assert conf.gc.dummy == False
raises(TypeError, "conf.gc.dummy = True")
raises(ConfigError, "conf.gc.dummy = True")
settings.disable_property('everything_frozen')
conf.gc.dummy = True
assert conf.gc.dummy == True
@ -79,7 +79,7 @@ def test_freeze_one_option():
dummy = conf.unwrap_from_path('gc.dummy')
conf.gc.cfgimpl_get_settings().add_property('frozen', dummy)
assert conf.gc.dummy == False
raises(TypeError, "conf.gc.dummy = True")
raises(ConfigError, "conf.gc.dummy = True")
def test_frozen_value():
"setattr a frozen value at the config level"
@ -88,7 +88,7 @@ def test_frozen_value():
config = Config(descr)
settings = config.cfgimpl_get_settings().enable_property('frozen')
config.cfgimpl_get_settings().add_property('frozen', s)
raises(TypeError, 'config.string = "egg"')
raises(ConfigError, 'config.string = "egg"')
def test_freeze():
"freeze a whole configuration object"
@ -97,7 +97,7 @@ def test_freeze():
settings = conf.cfgimpl_get_settings().enable_property('frozen')
name = conf.unwrap_from_path("gc.name")
conf.cfgimpl_get_settings().add_property('frozen', name)
raises(TypeError, "conf.gc.name = 'framework'")
raises(ConfigError, "conf.gc.name = 'framework'")
# ____________________________________________________________
def test_is_hidden():
descr = make_description()

View File

@ -45,11 +45,11 @@ def test_root_config_answers_ok():
assert cfg.boolop == True
def test_optname_shall_not_start_with_numbers():
raises(NameError, "gcdummy = BoolOption('123dummy', 'dummy', default=False)")
raises(NameError, "descr = OptionDescription('123tiramisu', '', [])")
raises(ValueError, "gcdummy = BoolOption('123dummy', 'dummy', default=False)")
raises(ValueError, "descr = OptionDescription('123tiramisu', '', [])")
#def test_option_has_an_api_name():
# gcdummy = BoolOption('cfgimpl_get_settings', 'dummy', default=False)
# boolop = BoolOption('boolop', 'Test boolean option op', default=True)
# descr = OptionDescription('tiramisu', '', [gcdummy, boolop])
# raises(NameError, "cfg = Config(descr)")
# raises(ValueError, "cfg = Config(descr)")

View File

@ -60,10 +60,7 @@ def test_get_group_type():
assert grp.get_group_type() == groups.family
assert grp.get_group_type() == 'family'
assert isinstance(grp.get_group_type(), groups.GroupType)
grp.set_group_type(groups.default)
assert isinstance(grp.get_group_type(), groups.DefaultGroupType)
assert grp.get_group_type() == groups.default
assert grp.get_group_type() == 'default'
raises(TypeError, 'grp.set_group_type(groups.default)')
def test_iter_on_groups():
descr = make_description()
@ -101,26 +98,26 @@ def test_allowed_groups():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
interface1 = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
raises(ConfigError, "interface1.set_group_type('toto')")
raises(ValueError, "interface1.set_group_type('toto')")
def test_master_not_valid_name():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
invalid_group = OptionDescription('interface1', '', [ip_admin_eth0, netmask_admin_eth0])
raises(ConfigError, "invalid_group.set_group_type(groups.master)")
raises(ValueError, "invalid_group.set_group_type(groups.master)")
def test_sub_group_in_master_group():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau", multi=True)
subgroup = OptionDescription("subgroup", '', [])
invalid_group = OptionDescription('ip_admin_eth0', '', [subgroup, ip_admin_eth0, netmask_admin_eth0])
raises(ConfigError, "invalid_group.set_group_type(groups.master)")
raises(ValueError, "invalid_group.set_group_type(groups.master)")
def test_group_always_has_multis():
ip_admin_eth0 = StrOption('ip_admin_eth0', "ip réseau autorisé", multi=True)
netmask_admin_eth0 = StrOption('netmask_admin_eth0', "masque du sous-réseau")
group = OptionDescription('ip_admin_eth0', '', [ip_admin_eth0, netmask_admin_eth0])
raises(ConfigError, "group.set_group_type(groups.master)")
raises(ValueError, "group.set_group_type(groups.master)")
#____________________________________________________________

View File

@ -19,7 +19,7 @@
# the whole pypy projet is under MIT licence
# ____________________________________________________________
"enables us to carry out a calculation and return an option's value"
from tiramisu.error import PropertiesOptionError, ConflictConfigError
from tiramisu.error import PropertiesOptionError, ConfigError
# ____________________________________________________________
# automatic Option object
#def special_owner_factory(name, owner, value,
@ -56,11 +56,10 @@ def carry_out_calculation(name, config, callback, callback_params):
if opt_value is not None:
len_value = len(opt_value)
if len_multi != 0 and len_multi != len_value:
raise ConflictConfigError('unable to carry out '
'a calculation, option '
'values with multi types'
' must have same length '
'for: ' + name)
raise ConfigError('unable to carry out a '
'calculation, option values with'
' multi types must have same '
'length for: ' + name)
len_multi = len_value
one_is_multi = True
tcparams.setdefault(key, []).append((opt_value, is_multi))
@ -116,6 +115,6 @@ def calculate(name, callback, params, tcparams):
except AttributeError, err:
import traceback
traceback.print_exc()
raise ConflictConfigError("callback: {0} return error {1} for "
"option: {2}".format(callback, str(err),
name))
raise ConfigError("callback: {0} return error {1} for "
"option: {2}".format(callback, str(err),
name))

View File

@ -21,8 +21,8 @@
# the whole pypy projet is under MIT licence
# ____________________________________________________________
#from inspect import getmembers, ismethod
from tiramisu.error import (PropertiesOptionError, NotFoundError,
AmbigousOptionError, NoMatchingOptionFound, MandatoryError)
from tiramisu.error import (PropertiesOptionError, ConfigError,
AmbigousOptionError, MandatoryError)
from tiramisu.option import OptionDescription, Option, SymLinkOption
from tiramisu.setting import groups, Setting, apply_requires
from tiramisu.value import Values
@ -86,7 +86,7 @@ class SubConfig(object):
"validation for the setattr and the getattr"
if not isinstance(opt_or_descr, Option) and \
not isinstance(opt_or_descr, OptionDescription):
raise TypeError(_('Unexpected object: {0}').format(repr(opt_or_descr)))
raise TypeError(_('unexpected object: {0}').format(repr(opt_or_descr)))
properties = set(self.cfgimpl_get_settings().get_properties(opt_or_descr))
#remove this properties, those properties are validate in value/setting
properties = properties - set(['mandatory', 'frozen'])
@ -154,16 +154,16 @@ class SubConfig(object):
apply_requires(child, self)
#needed to ?
if child not in self._cfgimpl_descr._children[1]:
raise AttributeError(_('unknown option {}').format(name))
raise AttributeError(_('unknown option {0}').format(name))
if setting.has_property('everything_frozen'):
raise TypeError(_("cannot set a value to the option {} if the whole "
"config has been frozen").format(name))
raise ConfigError(_("cannot set a value to the option {0} if the whole "
"config has been frozen").format(name))
if setting.has_property('frozen') and setting.has_property('frozen',
child, is_apply_req=False):
raise TypeError(_('cannot change the value to {} for '
'option {} this option is frozen').format(str(value), name))
raise ConfigError(_('cannot change the value to {0} for '
'option {1} this option is frozen').format(str(value), name))
self.cfgimpl_get_values()[child] = value
def cfgimpl_get_home_by_path(self, path, force_permissive=False, force_properties=None):
@ -227,7 +227,7 @@ class SubConfig(object):
"""
if group_type is not None:
if not isinstance(group_type, groups.GroupType):
raise TypeError(_("Unknown group_type: {0}").format(group_type))
raise TypeError(_("unknown group_type: {0}").format(group_type))
for child in self._cfgimpl_descr._children[1]:
if isinstance(child, OptionDescription):
try:
@ -340,8 +340,8 @@ class SubConfig(object):
else:
tmypath = mypath + '.'
if not path.startswith(tmypath):
raise Exception(_('unexpected path {}, '
'should start with {}').format(path, mypath))
raise AttributeError(_('unexpected path {0}, '
'should start with {1}').format(path, mypath))
path = path[len(tmypath):]
self._make_sub_dict(opt, path, pathsvalues, _currpath, flatten)
#withoption can be set to None below !
@ -424,6 +424,7 @@ class Config(SubConfig):
except MandatoryError:
pass
except Exception, e:
#FIXME hu? should have Exception ?
raise e # HiddenOptionError or DisabledOptionError
child = getattr(homeconfig._cfgimpl_descr, name)
homeconfig.setoption(name, child, value)
@ -431,7 +432,7 @@ class Config(SubConfig):
raise AmbigousOptionError(
_('more than one option that ends with {}').format(key))
else:
raise NoMatchingOptionFound(
raise AttributeError(
_('there is no option that matches {}'
' or the option is hidden or disabled').format(key))
@ -484,7 +485,7 @@ class Config(SubConfig):
# return False
# return False
if type_ not in ('option', 'path', 'value'):
raise ValueError(_('unknown type_ type {} for _find').format(type_))
raise ValueError(_('unknown type_ type {0} for _find').format(type_))
find_results = []
opts, paths = self.cfgimpl_get_description()._cache_paths
for index in range(0, len(paths)):
@ -518,7 +519,7 @@ class Config(SubConfig):
else:
find_results.append(retval)
if find_results == []:
raise NotFoundError(_("no option found in config with these criteria"))
raise AttributeError(_("no option found in config with these criteria"))
else:
return find_results

View File

@ -1,53 +1,45 @@
class ValidateError(Exception):
"If validation failed"
#ValueError if function's parameter not correct
# or if not logical
# or if validation falied
#TypeError if parameter has no good type
#AttributeError if no option or optiondescription in optiondescription (also when specified a path)
class AmbigousOptionError(StandardError):
"more than one option"
pass
class AmbigousOptionError(Exception):
pass
class NoMatchingOptionFound(AttributeError):
pass
class ConfigError(Exception):
class ConfigError(StandardError):
"""if modify frozen config
or try to change owner for an option without value
or if error in calculation"""
pass
class ConflictConfigError(ConfigError):
"duplicate config"
pass
class PropertiesOptionError(AttributeError):
"try to access to opt with not allowed property"
def __init__(self, msg, proptype):
self.proptype = proptype
super(PropertiesOptionError, self).__init__(msg)
class NotFoundError(Exception):
pass
class MethodCallError(Exception):
pass
class RequiresError(Exception):
pass
class RequirementRecursionError(RequiresError):
class RequirementRecursionError(StandardError):
"recursive error"
pass
class MandatoryError(Exception):
pass
class OptionValueError(Exception):
"mandatory error"
pass
class MultiTypeError(Exception):
"""multi must be a list
or error with multi length"""
pass

View File

@ -25,8 +25,7 @@ from copy import copy
from types import FunctionType
from IPy import IP
from tiramisu.error import (ConfigError, NotFoundError, ConflictConfigError,
RequiresError, ValidateError)
from tiramisu.error import ConflictConfigError
from tiramisu.setting import groups, multitypes
from tiramisu.i18n import _
@ -37,7 +36,7 @@ def valid_name(name):
try:
name = str(name)
except:
raise ValueError(_('not a valid string name'))
return False
if re.match(name_regexp, name) is None:
return True
else:
@ -104,7 +103,7 @@ class Option(BaseInformation):
:param validator_args: the validator's parameters
"""
if not valid_name(name):
raise NameError(_("invalid name: {0} for option").format(name))
raise ValueError(_("invalid name: {0} for option").format(name))
self._name = name
self._informations = {}
self.set_information('doc', doc)
@ -121,17 +120,17 @@ class Option(BaseInformation):
else:
self._validator = None
if not self._multi and default_multi is not None:
raise ConfigError(_("a default_multi is set whereas multi is False"
" in option: {0}").format(name))
raise ValueError(_("a default_multi is set whereas multi is False"
" in option: {0}").format(name))
if default_multi is not None and not self._validate(default_multi):
raise ConfigError(_("invalid default_multi value {0} "
"for option {1}").format(str(default_multi), name))
raise ValueError(_("invalid default_multi value {0} "
"for option {1}").format(str(default_multi), name))
if callback is not None and (default is not None or default_multi is not None):
raise ConfigError(_("defaut values not allowed if option: {0} "
"is calculated").format(name))
raise ValueError(_("defaut values not allowed if option: {0} "
"is calculated").format(name))
if callback is None and callback_params is not None:
raise ConfigError(_("params defined for a callback function but "
"no callback defined yet for option {0}").format(name))
raise ValueError(_("params defined for a callback function but "
"no callback defined yet for option {0}").format(name))
if callback is not None:
self._callback = (callback, callback_params)
else:
@ -144,21 +143,21 @@ class Option(BaseInformation):
# "for option {1} : not list type"
# "".format(str(default), name))
if not self.validate(default):
raise ValidateError(_("invalid default value {0} "
"for option {1}"
"").format(str(default), name))
raise ValueError(_("invalid default value {0} "
"for option {1}"
"").format(str(default), name))
self._multitype = multitypes.default
self._default_multi = default_multi
else:
if default is not None and not self.validate(default):
raise ValidateError(_("invalid default value {0} "
"for option {1}").format(str(default), name))
raise ValueError(_("invalid default value {0} "
"for option {1}").format(str(default), name))
self._default = default
if properties is None:
properties = ()
if not isinstance(properties, tuple):
raise ConfigError(_('invalid properties type {0} for {1},'
' must be a tuple').format(type(properties), self._name))
raise TypeError(_('invalid properties type {0} for {1},'
' must be a tuple').format(type(properties), self._name))
self._properties = properties # 'hidden', 'disabled'...
def validate(self, value, context=None, validate=True):
@ -184,7 +183,7 @@ class Option(BaseInformation):
return cons.valid_consistency(self, value, context, None)
else:
if not isinstance(value, list):
raise ValidateError(_("invalid value {0} "
raise ValueError(_("invalid value {0} "
"for option {1} which must be a list"
"").format(value, self._name))
for index in range(0, len(value)):
@ -280,11 +279,11 @@ class ChoiceOption(Option):
callback_params=None, open_values=False, validator=None,
validator_args=None, properties=()):
if not isinstance(values, tuple):
raise ConfigError(_('values must be a tuple for {0}').format(name))
raise TypeError(_('values must be a tuple for {0}').format(name))
self._values = values
if open_values not in (True, False):
raise ConfigError(_('open_values must be a boolean for '
'{0}').format(name))
raise TypeError(_('open_values must be a boolean for '
'{0}').format(name))
self._open_values = open_values
super(ChoiceOption, self).__init__(name, doc, default=default,
default_multi=default_multi,
@ -406,7 +405,7 @@ class NetmaskOption(Option):
properties=None, opt_ip=None):
if opt_ip is not None and not isinstance(opt_ip, IPOption) and \
not isinstance(opt_ip, NetworkOption):
raise ValueError(_('opt_ip must be a IPOption not {}').format(type(opt_ip)))
raise TypeError(_('opt_ip must be a IPOption not {}').format(type(opt_ip)))
super(NetmaskOption, self).__init__(name, doc, default=default,
default_multi=default_multi,
callback=callback,
@ -423,7 +422,7 @@ class NetmaskOption(Option):
elif isinstance(opt_ip, NetworkOption):
self._consistencies = [('cons_network_netmask', (self, opt_ip))]
else:
raise ValueError(_('unknown type for opt_ip'))
raise TypeError(_('unknown type for opt_ip'))
def _validate(self, value):
try:
@ -477,7 +476,7 @@ class OptionDescription(BaseInformation):
``OptionDescription`` instances for nested namespaces).
"""
if not valid_name(name):
raise NameError(_("invalid name: {0} for option descr").format(name))
raise ValueError(_("invalid name: {0} for option descr").format(name))
self._name = name
self._informations = {}
self.set_information('doc', doc)
@ -497,7 +496,7 @@ class OptionDescription(BaseInformation):
self._cache_paths = None
self._consistencies = None
if not isinstance(properties, tuple):
raise ConfigError(_('invalid properties type {0} for {1},'
raise TypeError(_('invalid properties type {0} for {1},'
' must be a tuple').format(type(properties), self._name))
self._properties = properties # 'hidden', 'disabled'...
# the group_type is useful for filtering OptionDescriptions in a config
@ -562,8 +561,6 @@ class OptionDescription(BaseInformation):
for consistency in option._consistencies:
func, opts = consistency
for opt in opts:
if opt in _consistencies:
raise ValueError(_('opt {} already in consistency').format(opt._name))
_consistencies.setdefault(opt, []).append((func, opts))
else:
_currpath.append(attr)
@ -586,13 +583,13 @@ class OptionDescription(BaseInformation):
try:
return self._cache_paths[0][self._cache_paths[1].index(path)]
except ValueError:
raise NotFoundError(_('no option for path {}').format(path))
raise AttributeError(_('no option for path {}').format(path))
def get_path_by_opt(self, opt):
try:
return self._cache_paths[1][self._cache_paths[0].index(opt)]
except ValueError:
raise NotFoundError(_('no option {} found').format(opt))
raise AttributeError(_('no option {} found').format(opt))
# ____________________________________________________________
def set_group_type(self, group_type):
@ -602,8 +599,8 @@ class OptionDescription(BaseInformation):
that lives in `setting.groups`
"""
if self._group_type != groups.default:
ConfigError(_('cannot change group_type if already set '
'(old {}, new {})').format(self._group_type, group_type))
raise TypeError(_('cannot change group_type if already set '
'(old {}, new {})').format(self._group_type, group_type))
if isinstance(group_type, groups.GroupType):
self._group_type = group_type
if isinstance(group_type, groups.MasterGroupType):
@ -614,12 +611,12 @@ class OptionDescription(BaseInformation):
master = None
for child in self._children[1]:
if isinstance(child, OptionDescription):
raise ConfigError(_("master group {} shall not have "
"a subgroup").format(self._name))
raise ValueError(_("master group {} shall not have "
"a subgroup").format(self._name))
if not child.is_multi():
raise ConfigError(_("not allowed option {0} in group {1}"
": this option is not a multi"
"").format(child._name, self._name))
raise ValueError(_("not allowed option {0} in group {1}"
": this option is not a multi"
"").format(child._name, self._name))
if child._name == self._name:
identical_master_child_name = True
child._multitype = multitypes.master
@ -627,18 +624,18 @@ class OptionDescription(BaseInformation):
else:
slaves.append(child)
if master is None:
raise ConfigError(_('master group with wrong master name for {}'
'').format(self._name))
raise ValueError(_('master group with wrong master name for {}'
'').format(self._name))
master._master_slaves = tuple(slaves)
for child in self._children[1]:
if child != master:
child._master_slaves = master
child._multitype = multitypes.slave
if not identical_master_child_name:
raise ConfigError(_("the master group: {} has not any "
"master child").format(self._name))
raise ValueError(_("the master group: {} has not any "
"master child").format(self._name))
else:
raise ConfigError(_('not allowed group_type : {0}').format(group_type))
raise ValueError(_('not allowed group_type : {0}').format(group_type))
def get_group_type(self):
return self._group_type
@ -660,8 +657,8 @@ def validate_requires_arg(requires, name):
config_action = {}
for req in requires:
if not type(req) == tuple:
raise RequiresError(_("malformed requirements type for option:"
" {0}, must be a tuple").format(name))
raise ValueError(_("malformed requirements type for option:"
" {0}, must be a tuple").format(name))
if len(req) == 3:
action = req[2]
inverse = False
@ -669,11 +666,11 @@ def validate_requires_arg(requires, name):
action = req[2]
inverse = req[3]
else:
raise RequiresError(_("malformed requirements for option: {0}"
" invalid len").format(name))
raise ValueError(_("malformed requirements for option: {0}"
" invalid len").format(name))
if action in config_action:
if inverse != config_action[action]:
raise RequiresError(_("inconsistency in action types for option: {0}"
" action: {1}").format(name, action))
raise ValueError(_("inconsistency in action types for option: {0}"
" action: {1}").format(name, action))
else:
config_action[action] = inverse

View File

@ -21,8 +21,8 @@
# the whole pypy projet is under MIT licence
# ____________________________________________________________
from tiramisu.error import (RequirementRecursionError, PropertiesOptionError,
NotFoundError)
from tiramisu.error import RequirementRecursionError, PropertiesOptionError
from tiramisu.i18n import _
class _const:
@ -33,13 +33,13 @@ class _const:
def __setattr__(self, name, value):
if name in self.__dict__:
raise self.ConstError, "Can't rebind group ({})".format(name)
raise self.ConstError, _("Can't rebind group ({})").format(name)
self.__dict__[name] = value
def __delattr__(self, name):
if name in self.__dict__:
raise self.ConstError, "Can't unbind group ({})".format(name)
raise NameError(name)
raise self.ConstError, _("Can't unbind group ({})").format(name)
raise ValueError(name)
# ____________________________________________________________
@ -216,14 +216,14 @@ class Setting(object):
def set_permissive(self, permissive, opt=None):
if not isinstance(permissive, list):
raise TypeError('permissive must be a list')
raise TypeError(_('permissive must be a list'))
self.permissives[opt] = permissive
#____________________________________________________________
def setowner(self, owner):
":param owner: sets the default value for owner at the Config level"
if not isinstance(owner, owners.Owner):
raise TypeError("invalid generic owner {0}".format(str(owner)))
raise TypeError(_("invalid generic owner {0}").format(str(owner)))
self.owner = owner
def getowner(self):
@ -275,18 +275,19 @@ def apply_requires(opt, config):
elif len(require) == 4:
path, expected, action, inverse = require
if path == optpath or path.startswith(optpath + '.'):
raise RequirementRecursionError("malformed requirements "
raise RequirementRecursionError(_("malformed requirements "
"imbrication detected for option: '{0}' "
"with requirement on: '{1}'".format(optpath, path))
"with requirement on: '{1}'").format(optpath, path))
try:
value = config.cfgimpl_get_context()._getattr(path, force_permissive=True)
except PropertiesOptionError, err:
properties = err.proptype
raise NotFoundError("option '{0}' has requirement's property error: "
"{1} {2}".format(opt._name, path, properties))
#FIXME: AttributeError or PropertiesOptionError ?
raise AttributeError(_("option '{0}' has requirement's property error: "
"{1} {2}").format(opt._name, path, properties))
except AttributeError:
raise NotFoundError("required option not found: "
"{0}".format(path))
raise AttributeError(_("required option not found: "
"{0}").format(path))
if value == expected:
if inverse:
setting.del_property(action, opt, False)

View File

@ -17,8 +17,7 @@
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# ____________________________________________________________
from tiramisu.error import MandatoryError, MultiTypeError, \
ConfigError, ValidateError
from tiramisu.error import MandatoryError, MultiTypeError, ConfigError
from tiramisu.setting import owners, multitypes
from tiramisu.autolib import carry_out_calculation
from tiramisu.i18n import _
@ -145,15 +144,15 @@ class Values(object):
value = self.fill_multi(opt, value)
self._test_mandatory(opt, value, force_properties)
if validate and not opt.validate(value, self.context, setting.has_property('validator')):
raise ValidateError(_('invalid calculated value returned'
' for option {0}: {1}').format(opt._name, value))
raise ValueError(_('invalid calculated value returned'
' for option {0}: {1}').format(opt._name, value))
return value
def __setitem__(self, opt, value):
if not opt.validate(value, self.context,
self.context.cfgimpl_get_settings().has_property('validator')):
raise ValidateError(_('invalid value {}'
' for option {}').format(value, opt._name))
raise ValueError(_('invalid value {}'
' for option {}').format(value, opt._name))
if opt.is_multi():
if opt.get_multitype() == multitypes.master:
masterlen = len(value)
@ -245,7 +244,7 @@ class Multi(list):
def _validate(self, value):
if value is not None and not self.opt._validate(value):
raise ConfigError(_("invalid value {0} "
raise ValueError(_("invalid value {0} "
"for option {1}").format(str(value),
self.opt._name))