This commit is contained in:
Emmanuel Garette 2018-09-26 21:30:05 +02:00
parent df77bc8738
commit 4426cc5111
6 changed files with 71 additions and 63 deletions

View File

@ -541,6 +541,37 @@ def test_requires_dyndescription():
assert frozenset(props) == frozenset(['disabled']) assert frozenset(props) == frozenset(['disabled'])
def test_requires_dyndescription_boolean():
boolean1 = BoolOption('boolean1', '', True)
boolean = BoolOption('boolean', '', True, requires=[{'option': boolean1,
'expected': False,
'action': 'disabled'}])
st = StrOption('st', '', requires=[{'option': boolean, 'expected': False,
'action': 'disabled'}])
dod = DynOptionDescription('dod', '', [st], callback=return_list)
od = OptionDescription('od', '', [dod])
od2 = OptionDescription('od', '', [od, boolean1, boolean])
cfg = Config(od2)
cfg.property.read_write()
assert cfg.value.dict() == {'boolean1': True,
'boolean': True,
'od.dodval1.stval1': None,
'od.dodval2.stval2': None}
#
cfg.option('boolean').value.set(False)
assert cfg.value.dict() == {'boolean1': True,
'boolean': False}
#
cfg.option('boolean').value.set(True)
assert cfg.value.dict() == {'boolean1': True,
'boolean': True,
'od.dodval1.stval1': None,
'od.dodval2.stval2': None}
#
cfg.option('boolean1').value.set(False)
assert cfg.value.dict() == {'boolean1': False}
def test_requires_dyndescription_in_dyn(): def test_requires_dyndescription_in_dyn():
boolean = BoolOption('boolean', '', True) boolean = BoolOption('boolean', '', True)
st = StrOption('st', '', requires=[{'option': boolean, 'expected': False, st = StrOption('st', '', requires=[{'option': boolean, 'expected': False,

View File

@ -227,9 +227,12 @@ def test_freeze_and_has_callback():
def test_callback(): def test_callback():
val1 = StrOption('val1', "", callback=return_val) val1 = StrOption('val1', "", callback=return_val)
maconfig = OptionDescription('rootconfig', '', [val1]) val2 = StrOption('val2', "")
maconfig = OptionDescription('rootconfig', '', [val1, val2])
api = Config(maconfig) api = Config(maconfig)
api.property.read_write() api.property.read_write()
assert api.option('val1').option.callbacks() != (None, None)
assert api.option('val2').option.callbacks() == (None, None)
assert api.option('val1').value.get() == 'val' assert api.option('val1').value.get() == 'val'
api.option('val1').value.set('new-val') api.option('val1').value.set('new-val')
assert api.option('val1').value.get() == 'new-val' assert api.option('val1').value.get() == 'new-val'

View File

@ -50,9 +50,13 @@ def test_consistency_warnings_only_default():
def test_consistency_warnings_only(): def test_consistency_warnings_only():
a = IntOption('a', '') a = IntOption('a', '')
b = IntOption('b', '') b = IntOption('b', '')
od = OptionDescription('od', '', [a, b]) c = IntOption('c', '')
od = OptionDescription('od', '', [a, b, c])
a.impl_add_consistency('not_equal', b, warnings_only=True) a.impl_add_consistency('not_equal', b, warnings_only=True)
api = Config(od) api = Config(od)
assert api.option('a').option.consistencies()
assert not api.option('b').option.consistencies()
assert not api.option('c').option.consistencies()
api.option('a').value.set(1) api.option('a').value.set(1)
warnings.simplefilter("always", ValueWarning) warnings.simplefilter("always", ValueWarning)
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:

View File

@ -643,10 +643,10 @@ class TiramisuOption(CommonTiramisu):
group_type=None): group_type=None):
"""list options in an optiondescription (only for optiondescription)""" """list options in an optiondescription (only for optiondescription)"""
if type not in ('all', 'option', 'optiondescription'): if type not in ('all', 'option', 'optiondescription'):
raise APIError(_('unknown list type {}').format(type)) raise APIError(_('unknown list type {}').format(type)) # pragma: no cover
if group_type is not None and not isinstance(group_type, if group_type is not None and not isinstance(group_type,
groups.GroupType): groups.GroupType):
raise TypeError(_("unknown group_type: {0}").format(group_type)) raise TypeError(_("unknown group_type: {0}").format(group_type)) # pragma: no cover
def _filter(opt): def _filter(opt):
if self.config_bag.properties: if self.config_bag.properties:
name = opt.impl_getname() name = opt.impl_getname()

View File

@ -209,21 +209,12 @@ class SubConfig(object):
option_bag.fromconsistency = fromconsistency option_bag.fromconsistency = fromconsistency
self = self.get_subconfig(step, self = self.get_subconfig(step,
option_bag) option_bag)
if not isinstance(self, SubConfig): assert isinstance(self, SubConfig), _('unknown option {}').format(path[-1])
raise AttributeError(_('unknown option {}').format(path[-1]))
return self, path[-1] return self, path[-1]
# ______________________________________________________________________ # ______________________________________________________________________
def cfgimpl_get_context(self): def cfgimpl_get_context(self):
"""context could be None, we need to test it return self._impl_context()
context is None only if all reference to `Config` object is deleted
(for example we delete a `Config` and we manipulate a reference to
old `SubConfig`, `Values`, `Multi` or `Settings`)
"""
context = self._impl_context()
if context is None: # pragma: no cover
raise ConfigError(_('the context does not exist anymore'))
return context
def cfgimpl_get_description(self): def cfgimpl_get_description(self):
if self._impl_descr is None: if self._impl_descr is None:
@ -275,18 +266,10 @@ class SubConfig(object):
def get_subconfig(self, def get_subconfig(self,
name, name,
option_bag): option_bag):
if '.' in name:
if option_bag.fromconsistency: if option_bag.fromconsistency:
fromconsistency = option_bag.fromconsistency.copy() fromconsistency = option_bag.fromconsistency.copy()
else: else:
fromconsistency = None fromconsistency = None
self, name = self.cfgimpl_get_home_by_path(name,
option_bag.config_bag,
fromconsistency)
elif option_bag.fromconsistency:
fromconsistency = option_bag.fromconsistency.copy()
else:
fromconsistency = None
self.cfgimpl_get_settings().validate_properties(option_bag) self.cfgimpl_get_settings().validate_properties(option_bag)
return SubConfig(option_bag.option, return SubConfig(option_bag.option,
@ -523,10 +506,9 @@ class SubConfig(object):
break break
else: else:
tmypath = mypath + '.' tmypath = mypath + '.'
if not path.startswith(tmypath): # pragma: no cover assert path.startswith(tmypath), _('unexpected path "{0}", '
raise AttributeError(_('unexpected path "{0}", '
'should start with "{1}"' 'should start with "{1}"'
'').format(path, mypath)) '').format(path, mypath)
path = path[len(tmypath):] path = path[len(tmypath):]
self._make_sub_dict(path, self._make_sub_dict(path,
pathsvalues, pathsvalues,
@ -685,6 +667,7 @@ class _CommonConfig(SubConfig):
metaconfig_prefix=None, metaconfig_prefix=None,
child=None, child=None,
deep=False): deep=False):
assert isinstance(self, (KernelConfig, KernelMetaConfig)), _('cannot duplicate {}').format(self.__class__.__name__)
if isinstance(self, KernelConfig): if isinstance(self, KernelConfig):
duplicated_config = KernelConfig(self._impl_descr, duplicated_config = KernelConfig(self._impl_descr,
_duplicate=True, _duplicate=True,
@ -704,8 +687,6 @@ class _CommonConfig(SubConfig):
force_settings=force_settings, force_settings=force_settings,
persistent=persistent, persistent=persistent,
storage=storage) storage=storage)
else:
raise Exception(_('unknown type'))
duplicated_config.cfgimpl_get_values()._p_.importation(self.cfgimpl_get_values()._p_.exportation()) duplicated_config.cfgimpl_get_values()._p_.importation(self.cfgimpl_get_values()._p_.exportation())
duplicated_config.cfgimpl_get_settings()._p_.importation(self.cfgimpl_get_settings( duplicated_config.cfgimpl_get_settings()._p_.importation(self.cfgimpl_get_settings(
)._p_.exportation()) )._p_.exportation())
@ -785,9 +766,6 @@ class KernelConfig(_CommonConfig):
def impl_getname(self): def impl_getname(self):
return self._impl_name return self._impl_name
def impl_getsessionid(self):
return self._impl_values._p_._storage.session_id
class KernelGroupConfig(_CommonConfig): class KernelGroupConfig(_CommonConfig):
__slots__ = ('__weakref__', __slots__ = ('__weakref__',
@ -803,16 +781,11 @@ class KernelGroupConfig(_CommonConfig):
_descr=None, _descr=None,
_duplicate=False, _duplicate=False,
storage=None): storage=None):
if not isinstance(children, list): assert isinstance(children, list), _("groupconfig's children must be a list")
raise ValueError(_("groupconfig's children must be a list"))
names = [] names = []
for child in children: for child in children:
if not isinstance(child, assert isinstance(child,
_CommonConfig): _CommonConfig), _("groupconfig's children must be Config, MetaConfig or GroupConfig")
try:
child = child._config
except:
raise ValueError(_("groupconfig's children must be Config, MetaConfig or GroupConfig"))
name_ = child._impl_name name_ = child._impl_name
names.append(name_) names.append(name_)
if len(names) != len(set(names)): if len(names) != len(set(names)):
@ -832,8 +805,7 @@ class KernelGroupConfig(_CommonConfig):
session_id, session_id,
persistent, persistent,
storage=storage) storage=storage)
if not valid_name(session_id): assert valid_name(session_id), _("invalid session ID: {0} for config").format(session_id)
raise ValueError(_("invalid session ID: {0} for config").format(session_id))
self._impl_settings = Settings(properties, self._impl_settings = Settings(properties,
permissives) permissives)
self._impl_values = Values(values) self._impl_values = Values(values)
@ -994,9 +966,9 @@ class KernelMetaConfig(KernelGroupConfig):
if not _duplicate: if not _duplicate:
new_children = [] new_children = []
for child_session_id in children: for child_session_id in children:
if not isinstance(child_session_id, str): assert isinstance(child_session_id, str), _('MetaConfig with optiondescription'
raise TypeError(_('MetaConfig with optiondescription must have ' ' must have string has child, '
'string has child, not {}').format(child_session_id)) 'not {}').format(child_session_id)
new_children.append(KernelConfig(optiondescription, new_children.append(KernelConfig(optiondescription,
persistent=persistent, persistent=persistent,
session_id=child_session_id)) session_id=child_session_id))
@ -1138,6 +1110,7 @@ class KernelMetaConfig(KernelGroupConfig):
if session_id in [child._impl_name for child in self._impl_children]: if session_id in [child._impl_name for child in self._impl_children]:
raise ConflictError(_('config name must be uniq in ' raise ConflictError(_('config name must be uniq in '
'groupconfig for {0}').format(session_id)) 'groupconfig for {0}').format(session_id))
assert type_ in ('config', 'metaconfig'), _('unknown type {}').format(type_)
if type_ == 'config': if type_ == 'config':
config = KernelConfig(self._impl_descr, config = KernelConfig(self._impl_descr,
session_id=session_id, session_id=session_id,
@ -1147,8 +1120,6 @@ class KernelMetaConfig(KernelGroupConfig):
optiondescription=self._impl_descr, optiondescription=self._impl_descr,
session_id=session_id, session_id=session_id,
persistent=persistent) persistent=persistent)
else: # pragma: no cover
raise ConfigError(_('unknown type {}').format(type_))
# Copy context properties/permissives # Copy context properties/permissives
config.cfgimpl_get_settings().set_context_properties(self.cfgimpl_get_settings().get_context_properties(), config) config.cfgimpl_get_settings().set_context_properties(self.cfgimpl_get_settings().get_context_properties(), config)
config.cfgimpl_get_settings().set_context_permissives(self.cfgimpl_get_settings().get_context_permissives()) config.cfgimpl_get_settings().set_context_permissives(self.cfgimpl_get_settings().get_context_permissives())
@ -1159,7 +1130,7 @@ class KernelMetaConfig(KernelGroupConfig):
def pop_config(self, def pop_config(self,
session_id): session_id):
for idx, child in enumerate(self._impl_children): # pragma: no cover for idx, child in enumerate(self._impl_children):
if session_id == child._impl_name: if session_id == child._impl_name:
return self._impl_children.pop(idx) return self._impl_children.pop(idx)
raise ConfigError(_('cannot find the config {}').format(session_id)) raise ConfigError(_('cannot find the config {}').format(session_id))

View File

@ -535,10 +535,9 @@ class Values(object):
config_bag, config_bag,
description, description,
currpath, currpath,
config, subconfig,
od_config_bag): od_config_bag):
settings = context.cfgimpl_get_settings() settings = context.cfgimpl_get_settings()
# for option in config.cfgimpl_get_children(self.config_bag):
for option in description.impl_getchildren(config_bag, context): for option in description.impl_getchildren(config_bag, context):
name = option.impl_getname() name = option.impl_getname()
path = '.'.join(currpath + [name]) path = '.'.join(currpath + [name])
@ -550,7 +549,7 @@ class Values(object):
path, path,
None, None,
od_config_bag) od_config_bag)
subconfig = config.get_subconfig(name, subsubconfig = subconfig.get_subconfig(name,
option_bag) option_bag)
except PropertiesOptionError as err: except PropertiesOptionError as err:
pass pass
@ -559,7 +558,7 @@ class Values(object):
config_bag, config_bag,
option, option,
currpath + [name], currpath + [name],
subconfig, subsubconfig,
od_config_bag): od_config_bag):
yield path yield path
elif not option.impl_is_symlinkoption(): elif not option.impl_is_symlinkoption():
@ -572,17 +571,17 @@ class Values(object):
None, None,
config_bag) config_bag)
if 'mandatory' in option_bag.properties or 'empty' in option_bag.properties: if 'mandatory' in option_bag.properties or 'empty' in option_bag.properties:
config.getattr(name, subconfig.getattr(name,
option_bag) option_bag)
else: else:
for index in range(config.cfgimpl_get_length()): for index in range(subconfig.cfgimpl_get_length()):
option_bag = OptionBag() option_bag = OptionBag()
option_bag.set_option(option, option_bag.set_option(option,
path, path,
index, index,
config_bag) config_bag)
if 'mandatory' in option_bag.properties: if 'mandatory' in option_bag.properties:
config.getattr(name, subconfig.getattr(name,
option_bag) option_bag)
except PropertiesOptionError as err: except PropertiesOptionError as err:
if err.proptype == ['mandatory']: if err.proptype == ['mandatory']: